File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.118: download - view: text, annotated - select for diffs
Tue Sep 1 03:35:54 2020 UTC (3 years, 8 months ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Current user's shown in username textbox for Individual Points Overview
  if no student selected.
- Eliminate unused assignment of $notshowSPRSlink in &real_handler(), it's
  set in &startGradeScreen() now.
- If no navmap object available display error message.
- Course personnel see: 'Students will see link to spreadsheet." note in
  page header, if course configured to use spreadsheet.

    1: # The LearningOnline Network with CAPA
    2: # Quick Student Grades Display
    3: #
    4: # $Id: lonquickgrades.pm,v 1.118 2020/09/01 03:35:54 raeburn Exp $
    5: #
    6: # Copyright Michigan State University Board of Trustees
    7: #
    8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    9: #
   10: # LON-CAPA is free software; you can redistribute it and/or modify
   11: # it under the terms of the GNU General Public License as published by
   12: # the Free Software Foundation; either version 2 of the License, or
   13: # (at your option) any later version.
   14: #
   15: # LON-CAPA is distributed in the hope that it will be useful,
   16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   18: # GNU General Public License for more details.
   19: #
   20: # You should have received a copy of the GNU General Public License
   21: # along with LON-CAPA; if not, write to the Free Software
   22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   23: #
   24: # /home/httpd/html/adm/gpl.txt
   25: #
   26: # http://www.lon-capa.org/
   27: #
   28: 
   29: package Apache::lonquickgrades;
   30: 
   31: use strict;
   32: use Apache::Constants qw(:common :http REDIRECT);
   33: use POSIX;
   34: use Apache::loncommon;
   35: use Apache::lonlocal;
   36: use Apache::lonnet;
   37: use Apache::grades;
   38: use Apache::loncoursedata;
   39: use Apache::lonstudentassessment;
   40: use Apache::lonuserstate;
   41: 
   42: use Time::HiRes;
   43: use Spreadsheet::WriteExcel;
   44: use Spreadsheet::WriteExcel::Utility();
   45: #
   46: # Excel data
   47: #
   48: my $excel_sheet;
   49: my $excel_workbook;
   50: my $filename;
   51: my $format;
   52: my $request_aborted;
   53: my $header_row;
   54: my $cols_output;
   55: my %prog_state;
   56: 
   57: 
   58: sub handler {
   59:     my $r = shift;
   60:     return real_handler($r);
   61: }
   62: 
   63: sub real_handler {
   64:     my $r = shift;
   65: 
   66:     &Apache::loncommon::get_unprocessed_cgi($ENV{QUERY_STRING});
   67: 
   68:     # Handle header-only request
   69:     if ($env{'browser.mathml'}) {
   70: 	&Apache::loncommon::content_type($r,'text/xml');
   71:     } else {
   72: 	&Apache::loncommon::content_type($r,'text/html');
   73:     }
   74:     if ($r->header_only) {
   75: 	$r->send_http_header;
   76:         return OK;
   77:     }
   78: 
   79:     my $cangrade=&Apache::lonnet::allowed('mgr');
   80:     my $showPoints =
   81:         (($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'standard')
   82:       || ($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'categories'));
   83: 
   84:     my $reinitresult;
   85: 
   86:     if ($env{'request.course.id'}) {
   87:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
   88:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
   89:         my ($blocked,$blocktext) =
   90:             &Apache::loncommon::blocking_status('grades',$cnum,$cdom);
   91:         if ($blocked) {
   92:             my $checkrole = "cm./$cdom/$cnum";
   93:             if ($env{'request.course.sec'} ne '') {
   94:                 $checkrole .= "/$env{'request.course.sec'}";
   95:             }
   96:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
   97:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
   98:                 &grades_blocked($r,$blocktext,$showPoints);
   99:                 return OK;
  100:             }
  101:         }
  102:     }
  103: 
  104:     unless ($cangrade) {
  105:         # Check for critical messages and redirect if present.
  106:         my ($redirect,$url) = &Apache::loncommon::critical_redirect(300,'grades');
  107:         if ($redirect) {
  108:             &Apache::loncommon::content_type($r,'text/html');
  109:             $r->header_out(Location => $url);
  110:             return REDIRECT;
  111:         }
  112: 
  113:         # Check if course needs to be re-initialized
  114:         my $loncaparev = $r->dir_config('lonVersion');
  115:         ($reinitresult,my @reinit) = &Apache::loncommon::needs_coursereinit($loncaparev);
  116: 
  117:         if ($reinitresult eq 'switch') {
  118:             &Apache::loncommon::content_type($r,'text/html');
  119:             $r->send_http_header;
  120:             $r->print(&Apache::loncommon::check_release_result(@reinit));
  121:             return OK;
  122:         } elsif ($reinitresult eq 'update') {
  123:             my $cid = $env{'request.course.id'};
  124:             my $cnum = $env{'course.'.$cid.'.num'};
  125:             my $cdom = $env{'course.'.$cid.'.domain'};
  126:             &Apache::loncommon::content_type($r,'text/html');
  127:             $r->send_http_header;
  128:             &startpage($r,$showPoints);
  129:             my $preamble = '<div id="LC_update_'.$cid.'" class="LC_info">'.
  130:                            '<br />'.
  131:                            &mt('Your course session is being updated because of recent changes by course personnel.').
  132:                            ' '.&mt('Please be patient.').'<br /></div>'.
  133:                            '<div style="padding:0;clear:both;margin:0;border:0"></div>';
  134:             %prog_state = &Apache::lonhtmlcommon::Create_PrgWin($r,undef,$preamble);
  135:             &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,&mt('Updating course'));
  136:             $r->rflush();
  137:             my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
  138:             &Apache::lonhtmlcommon::Update_PrgWin($r,\%prog_state,&mt('Finished')); 
  139:             &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  140:             my $closure = <<ENDCLOSE;
  141: <script type="text/javascript">
  142: // <![CDATA[
  143: \$("#LC_update_$cid").hide('slow');
  144: // ]]>
  145: </script>
  146: ENDCLOSE
  147:             if ($ferr) {
  148:                 $r->print($closure.&Apache::loncommon::end_page());
  149:                 my $requrl = $r->uri;
  150:                 $env{'user.error.msg'}="$requrl:bre:0:0:Course not initialized";
  151:                 $env{'user.reinit'} = 1;
  152:                 return HTTP_NOT_ACCEPTABLE;
  153:             } else {
  154:                $r->print($closure);
  155:             }
  156:         } elsif ((&Apache::loncommon::course_type() eq 'Placement') &&
  157:                  (!$env{'request.role.adv'})) {
  158:             my $furl = &Apache::lonpageflip::first_accessible_resource();
  159:             &Apache::loncommon::content_type($r,'text/html');
  160:             $r->header_out(Location => $furl);
  161:             return REDIRECT;
  162:         }
  163:     }
  164: 
  165:     unless ($reinitresult eq 'update') {
  166:         # Send header, don't cache this page
  167:         &Apache::loncommon::no_cache($r);
  168:         $r->send_http_header;
  169:         &startpage($r,$showPoints);
  170:     }
  171:     $r->rflush();
  172: 
  173:     &startGradeScreen($r,'quick');
  174: 
  175: #
  176: # Pick student
  177: #
  178:     my $uname;
  179:     my $udom;
  180:     my $stdid;
  181:     if ($cangrade) {
  182:         $r->print("<h2>".&mt("Download Multiple")."</h2>".
  183:                   '<table cellspacing="5">'."\n".
  184:                   '<tr>'.
  185:                   '<td align="center"><b>'.&mt('Sections').'</b>'.
  186:                   &Apache::loncommon::help_open_topic("Chart_Sections").
  187:                   '</td>'.
  188:                   '<td align="center"><b>'.&mt('Groups').'</b>'.
  189:                   '</td>'.
  190:                   '<td align="center"><b>'.&mt('Student Data').'</b>'.
  191:                   &Apache::loncommon::help_open_topic("Chart_Student_Data").
  192:                   '</td>'.
  193:                   '<td align="center"><b>'.&mt('Access Status').'</b>'.
  194:                   &Apache::loncommon::help_open_topic("Chart_Enrollment_Status").
  195:                   '</td>'.
  196:                   '<td align="center"><b>'.&mt('Output Format').'</b>'.
  197:                   &Apache::loncommon::help_open_topic("Chart_Output_Formats").
  198:                   '</td><td>&nbsp;</td></tr>'."\n".
  199:                   '<tr><td align="center">'."\n".
  200:                   &Apache::lonstatistics::SectionSelect('Section','multiple',5).
  201:                   '</td><td align="center">'.
  202:                   &Apache::lonstatistics::GroupSelect('Group','multiple',5).
  203:                   '</td><td align="center">'.
  204:                   &Apache::lonstatistics::StudentDataSelect('StudentData','multiple',5,undef).
  205:                   '</td><td>'."\n".
  206:                   &Apache::lonhtmlcommon::StatusOptions(undef,undef,5).
  207:                   '</td><td>'."\n".
  208:                   &Apache::lonstudentassessment::CreateAndParseOutputSelector().
  209:                   '</td><td>'.
  210:                   '<input type="submit" name="download" value="'.&mt('Display/Download Multiple Students').'" />'.
  211:                   '</td></tr>'."\n".
  212:                   '</table>'."\n"
  213:                  );
  214:         $r->print("<hr /><h2>".&mt("Display Individual")."</h2>");
  215:         if ($env{'form.uname'}) { $uname=$env{'form.uname'}; }
  216:         if ($env{'form.udom'}) { $udom=$env{'form.udom'}; }
  217:         if ($env{'form.id'}) { $stdid=$env{'form.id'}; }
  218:         if (($stdid) && ($udom)) {
  219:             $uname=(&Apache::lonnet::idget($udom,[$stdid],'ids'))[1];
  220:         }
  221:         if (($stdid) && (!$uname)) {
  222:             $r->print('<p><span class="LC_warning">'.&mt("Unknown Student/Employee ID: [_1]",$stdid).'</span></p>');
  223:             $stdid='';
  224:         }
  225:         if (($uname eq '') && ($udom eq '')) {
  226:             $uname = $env{'user.name'};
  227:             $udom = $env{'user.domain'};
  228:         }
  229:         $r->print('<form method="post" name="quickform" action="/adm/quickgrades">');
  230:         my $chooseopt=&Apache::loncommon::select_dom_form($udom,'udom').' '.
  231:            &Apache::loncommon::selectstudent_link('quickform','uname','udom');
  232:         $r->print("<p>\n".&Apache::loncommon::studentbrowser_javascript()."\n");
  233:         $r->print(&mt('For User [_1] or Student/Employee ID [_2] at Domain [_3]'
  234:                  ,'<input type="text" value="'.$uname.'" size="12" name="uname" />'
  235:                  ,'<input type="text" value="'.$stdid.'" size="12" name="id" /> '
  236:                  ,$chooseopt).
  237:                  '&nbsp;&nbsp;<input type="submit" name="display" value="'.&mt('Display Individual Student').'" /></p>');
  238:         if (($uname) && ($udom)) {
  239:             $r->print('<p>'.&mt('Full Name: [_1]',&Apache::loncommon::plainname($uname,$udom)).'</p>');
  240:         }
  241:     }
  242:     $r->rflush();
  243: 
  244:     my $notshowTotals=
  245:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'externalnototals';
  246:     my $showCategories=
  247:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'categories';
  248: 
  249:     my ($navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted)=
  250:        &getData($showPoints,$uname,$udom);
  251: 
  252:     if (ref($navmap)) {
  253:         if ($showCategories) {
  254:             &outputCategories($r,$showPoints,$notshowTotals,
  255:                 $navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted);
  256:         } else {
  257:             &outputTable($r,$showPoints,$notshowTotals,
  258:                 $navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted);
  259:         }
  260:     } else {
  261:         if ($cangrade) { $r->print("\n</form>\n"); }
  262:         my $requrl = $r->uri;
  263:         $env{'user.error.msg'} = "$requrl:bre:0:0:Navmap initialization failed.";
  264:         return HTTP_NOT_ACCEPTABLE;
  265:     }
  266:     if ($cangrade) { $r->print("\n</form>\n"); }
  267:     &endGradeScreen($r);
  268:     return OK;
  269: 
  270: }
  271: 
  272: sub grades_blocked {
  273:     my ($r,$blocktext,$caller) = @_;
  274:     my $title = 'Points Display';
  275:     if ($caller eq 'spreadsheet') {
  276:         $title = 'Spreadsheet';
  277:     } elsif ($env{'course.'.$env{'request.course.id'}.'.grading'} ne 'standard') {
  278:         $title = 'Completed Problems Display';
  279:     }
  280:     my $brcrum = [{href=>"/adm/quickgrades",text => $title}];
  281:     &Apache::lonhtmlcommon::clear_breadcrumbs();
  282:     &Apache::lonhtmlcommon::add_breadcrumb({href=>'/adm/quickgrades',
  283:                                             text=> $title});
  284:     my $breadcrumbs = &Apache::lonhtmlcommon::breadcrumbs($title);
  285:     &Apache::loncommon::content_type($r,'text/html');
  286:     &Apache::loncommon::no_cache($r);
  287:     $r->send_http_header;
  288:     $r->print(&Apache::loncommon::start_page($title).
  289:               $breadcrumbs.
  290:               $blocktext.
  291:               &Apache::loncommon::end_page());
  292:     return;
  293: }
  294: 
  295: sub getStudentCatGrade {
  296:     my ($uname,$udom,%categories)=@_;
  297:     my ($navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted)=
  298:        &getData(1,$uname,$udom);
  299:     return &output_category_table(undef,0,$navmap,0,%categories);
  300: }
  301: 
  302: sub getAllStudentData {
  303:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  304:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  305: 
  306:     my %categories=&Apache::lonnet::dump('grading_categories',$cdom,$cnum);
  307: 
  308:     my $classlist = &Apache::loncoursedata::get_classlist();
  309: 
  310:     my $statusidx   = &Apache::loncoursedata::CL_STATUS();
  311:     my $usernameidx = &Apache::loncoursedata::CL_SNAME();
  312:     my $domainidx   = &Apache::loncoursedata::CL_SDOM();
  313:     my $fullnameidx = &Apache::loncoursedata::CL_FULLNAME();
  314: 
  315:     foreach my $key (keys(%{$classlist})) {
  316:         my $student = $classlist->{$key};
  317:         my $perc=&getStudentCatGrade($classlist->{$student}->[$usernameidx],
  318:                                      $classlist->{$student}->[$domainidx],
  319:                                      %categories);
  320:     }
  321: }
  322: 
  323: sub startpage {
  324:     my ($r,$showPoints) = @_;
  325:     my $title = "Grading and Statistics";#$showPoints ? "Points Display" : "Completed Problems Display";
  326:     my $brcrum = [{href=>"/adm/quickgrades",text => "Points Display"}];
  327:     $r->print(&Apache::loncommon::start_page($title,undef,
  328:                                             {'bread_crumbs' => $brcrum})
  329:              );
  330: }
  331: 
  332: sub startGradeScreen {
  333:     my ($r,$mode)=@_;
  334: 
  335:     my $showPoints =
  336:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'standard';
  337:     my $notshowSPRSlink =
  338:         (($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'external')
  339:       || ($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'externalnototals')
  340:       || ($env{'course.'.$env{'request.course.id'}.'.grading'} eq 'categories'));
  341:     my $notshowTotals=
  342:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'externalnototals';
  343:     my $showSPRSlink =
  344:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'spreadsheet';
  345:     my $showCategories=
  346:         $env{'course.'.$env{'request.course.id'}.'.grading'} eq 'categories';
  347:  
  348:     my $allowed_to_view = &Apache::lonnet::allowed('vgr',$env{'request.course.id'});
  349:     if ((!$allowed_to_view) && ($env{'request.course.sec'} ne '')) {
  350:         $allowed_to_view = &Apache::lonnet::allowed('vgr',
  351:                                "$env{'request.course.id'}/$env{'request.course.sec'}");
  352:     }
  353: 
  354:     my $allowed_to_edit = &Apache::lonnet::allowed('mgr',$env{'request.course.id'});
  355:     if ((!$allowed_to_edit) && ($env{'request.course.sec'} ne '')) {
  356:         $allowed_to_edit = &Apache::lonnet::allowed('mgr',
  357:                                "$env{'request.course.id'}/$env{'request.course.sec'}");
  358:     }
  359: 
  360:     if ($allowed_to_view) {
  361:        my @notes;
  362:        push(@notes,&mt('Students do not see total points.')) if ($notshowTotals);
  363:        push(@notes,&mt('Students do not see link to spreadsheet.')) if ($notshowSPRSlink);
  364:        push(@notes,&mt('Students will see points based on problem weights.')) if ($showPoints);
  365:        push(@notes,&mt('Students will see points based on categories.')) if ($showCategories);
  366:        push(@notes,&mt('Students will see link to spreadsheet.')) if ($showSPRSlink);
  367:        push(@notes, &Apache::lonhtmlcommon::coursepreflink(&mt('Grade display settings'),'grading'));
  368:        $r->print(&Apache::loncommon::head_subbox(join('&nbsp;&nbsp;',@notes)));
  369:     }
  370: 
  371: 
  372:     $r->print("\n".'<ul class="LC_TabContentBigger" id="main">');
  373:     $r->print("\n".'<li'.($mode eq 'quick'?' class="active"':'').'><a href="/adm/quickgrades"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.
  374:                                           ($showPoints?&mt('Individual Points Overview'):($showCategories?&mt('Grades Overview'):&mt('Completion Overview'))).
  375:                                           '&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>');
  376: 
  377:     if (!($showPoints || $notshowSPRSlink) || ($allowed_to_view)) {
  378:        $r->print("\n".'<li'.($mode eq 'spreadsheet'?' class="active"':'').'><a href="/adm/'.($allowed_to_view?'classcalc':'studentcalc').'"><b>'.
  379:                                                                  &mt('Spreadsheet (Detailed)').'</b></a></li>');
  380:     }
  381:     if ($allowed_to_view) {
  382:        $r->print("\n".'<li'.($mode eq 'statistics'?' class="active"':'').'><a href="/adm/statistics"><b>'.
  383:                                                                  &mt('Statistics and Reports').'</b></a></li>');
  384: 
  385:        $r->print("\n".'<li'.($mode eq 'chart'?' class="active"':'').'><a href="/adm/statistics?reportSelected=student_assessment"><b>'.
  386:                                                                  &mt('Assessment Chart').'</b></a></li>');
  387: 
  388:     }
  389:     if ($allowed_to_edit) {
  390:        $r->print("\n".'<li'.($mode eq 'grading'?' class="active"':'').'><a href="/adm/grades"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.
  391:                                                                  &mt('Content Grading').'&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>');
  392:        if ($env{'form.symb'}) {
  393:           $r->print("\n".'<li'.($mode eq 'probgrading'?' class="active"':'').'><a href="/adm/grades?symb='.
  394:                                               &Apache::lonhtmlcommon::entity_encode($env{'form.symb'}).
  395:                                               '&amp;command=gradingmenu"><b>&nbsp;&nbsp;&nbsp;&nbsp;'.
  396:                                               &mt('Problem Grading').'&nbsp;&nbsp;&nbsp;&nbsp;</b></a></li>');
  397: 
  398:        }
  399:     }
  400:     $r->print("\n".'</ul>'."\n");
  401:     $r->print('<div class="LC_Box" style="clear:both;margin:0;"><div id="maincoursedoc" style="margin:0 0;padding:0 0;"><div class="LC_ContentBox" id="mainCourseDocuments" style="display: block;">');
  402: }
  403: 
  404: sub endGradeScreen {
  405:    my ($r)=@_;
  406:    $r->print('</div></div></div>'.&Apache::loncommon::end_page());
  407:    return;
  408: }
  409: 
  410: # -----------
  411: 
  412: 
  413: sub excel_cleanup {
  414:     undef ($excel_sheet);
  415:     undef ($excel_workbook);
  416:     undef ($filename);
  417:     undef ($format);
  418: }
  419: 
  420: 
  421: sub excel_initialize {
  422:     my ($r) = @_;
  423: 
  424:     &excel_cleanup();
  425: 
  426:     # Create sheet
  427:     ($excel_workbook,$filename,$format)=
  428:         &Apache::loncommon::create_workbook($r);
  429:     return if (! defined($excel_workbook));
  430:    #
  431:    # Add a worksheet
  432:     my $sheetname = $env{'course.'.$env{'request.course.id'}.'.description'};
  433:     $sheetname = &Apache::loncommon::clean_excel_name($sheetname);
  434:     $excel_sheet = $excel_workbook->addworksheet($sheetname);
  435:    #
  436:    # Put the course description in the header
  437:     $excel_sheet->write($header_row,$cols_output++,
  438:                    $env{'course.'.$env{'request.course.id'}.'.description'},
  439:                         $format->{'h1'});
  440: } 
  441: 
  442: sub excel_finish {
  443:     my ($r) = @_;
  444:     if ($request_aborted || ! defined($excel_sheet)) {
  445:         &excel_cleanup();
  446:         return;
  447:     }
  448:     #
  449:     # Write the excel file
  450:     $excel_workbook->close();
  451:     #
  452:     # Close the progress window
  453:     &Apache::lonhtmlcommon::Close_PrgWin($r,\%prog_state);
  454:     #
  455:     # Tell the user where to get their excel file
  456:     $r->print('<br />'.
  457:               '<a href="'.$filename.'">'.&mt('Your Excel spreadsheet').'</a>'."\n");
  458:     $r->rflush();
  459:     &excel_cleanup();
  460:     return;
  461: }
  462: 
  463: 
  464: #
  465: # CSV data
  466: #
  467: # -----------
  468: 
  469: #
  470: # Go through the complete course and collect data
  471: #
  472: 
  473: sub getData {
  474: 
  475:     my ($showPoints,$uname,$udom)=@_;
  476: 
  477:     # Create the nav map
  478:     my $navmap = Apache::lonnavmaps::navmap->new($uname,$udom);
  479: 
  480:     if (!defined($navmap)) {
  481:         return ();
  482:     }
  483: 
  484:     my $res = $navmap->firstResource(); # temp resource to access constants
  485: 
  486:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  487:     my $depth = 1;
  488:     $iterator->next(); # ignore first BEGIN_MAP
  489:     my $curRes = $iterator->next();
  490:     
  491:     # General overview of the following: Walk along the course resources.
  492:     # For every problem in the resource, tell its parent maps how many
  493:     # parts and how many parts correct it has. After that, each map will
  494:     # have a count of the total parts underneath it, correct and otherwise.
  495:     # After that, we will walk through the course again and read off
  496:     # maps in order, with their data. 
  497:     # (If in the future people decide not to be cumulative, only add
  498:     #  the counts to the parent map.)
  499:     # For convenience, "totalParts" is also "totalPoints" when we're looking
  500:     #  at points; I can't come up with a variable name that makes sense
  501:     #  equally for both cases.
  502: 
  503:     my $totalParts = 0; my $totalPossible = 0; my $totalRight = 0;
  504:     my $totalAttempted = 0;
  505:     my $now = time();
  506:     my $topLevelParts = 0; my $topLevelRight = 0; my $topLevelAttempted = 0;
  507: 
  508:     # Pre-run: Count parts correct
  509:     while ( $depth > 0 ) {
  510:         if ($curRes == $iterator->BEGIN_MAP()) {$depth++;}
  511:         if ($curRes == $iterator->END_MAP()) { $depth--; }
  512: 
  513:         if (ref($curRes) && $curRes->is_gradable() && !$curRes->randomout && 
  514:             ($curRes->deeplink ne 'absent'))
  515:         {
  516:             # Get number of correct, incorrect parts
  517:             my $parts = $curRes->parts();
  518:             my $partsRight = 0;
  519: 	    my $partsCount = 0;
  520: 	    my $partsAttempted = 0;
  521:             my $stack = $iterator->getStack();
  522:             
  523:             for my $part (@{$parts}) {
  524: 		my $dateStatus = $curRes->getDateStatus($part);
  525:                 my $weight = $curRes->weight($part);
  526:                 my $problemstatus = $curRes->problemstatus($part);
  527: 
  528:                 if ($curRes->solved($part) eq 'excused') {
  529:                     next;
  530:                 }
  531: 		if ($showPoints) {
  532: 		    my $score = 0;
  533: 		    # If we're not telling status and the answer date isn't passed yet, 
  534: 		    # it's an "attempted" point
  535: 		    if ((($problemstatus eq 'no') ||
  536:                          ($problemstatus eq 'no_feedback_ever')) &&
  537: 			($dateStatus != $curRes->ANSWER_OPEN)) {
  538: 			my $status = $curRes->simpleStatus($part);
  539: 			if ($status == $curRes->ATTEMPTED) {
  540: 			    $partsAttempted += $weight;
  541: 			    $totalAttempted += $partsAttempted;
  542: 			}
  543: 		    } else {
  544: 			$score = &Apache::grades::compute_points($weight, $curRes->awarded($part));
  545: 		    }
  546: 		    $partsRight += $score;
  547: 		    $totalRight += $score;
  548: 		    $partsCount += $weight;
  549: 
  550:                     $curRes->{DATA}->{PROB_SCORE}  += $score;
  551:                     $curRes->{DATA}->{PROB_WEIGHT} += $weight;
  552: 
  553: 		    if ($curRes->opendate($part) < $now) {
  554: 			$totalPossible += $weight;
  555:                         $curRes->{DATA}->{PROB_POSSIBLE} += $weight;
  556: 		    }
  557: 		    $totalParts += $weight;
  558: 		} else {
  559: 		    my $status = $curRes->simpleStatus($part);
  560: 		    my $thisright = 0;
  561: 		    $partsCount++;
  562: 		    if ($status == $curRes->CORRECT ||
  563: 			$status == $curRes->PARTIALLY_CORRECT ) {
  564: 			$partsRight++;
  565: 			$totalRight++;
  566: 			$thisright = 1;
  567: 		    }
  568: 
  569: 		    if ($status == $curRes->ATTEMPTED) {
  570: 			$partsAttempted++;
  571: 			$totalAttempted++;
  572: 		    }
  573: 		    
  574: 		    $totalParts++;
  575: 		    if ($curRes->opendate($part) < $now) {
  576: 			$totalPossible++;
  577: 		    }
  578: 		}
  579:             }
  580: 
  581:             if ($depth == 1) { # in top-level only
  582: 		$topLevelParts += $partsCount;
  583: 		$topLevelRight += $partsRight;
  584: 		$topLevelAttempted += $partsAttempted;
  585: 	    }
  586: 
  587:             # Crawl down stack and record parts correct and total
  588:             for my $res (@{$stack}) {
  589:                 if (ref($res) && $res->is_map()) {
  590:                     if (!defined($res->{DATA}->{CHILD_PARTS})) {
  591:                         $res->{DATA}->{CHILD_PARTS} = 0;
  592:                         $res->{DATA}->{CHILD_CORRECT} = 0;
  593: 			$res->{DATA}->{CHILD_ATTEMPTED} = 0;
  594:                     }
  595:                     
  596:                     $res->{DATA}->{CHILD_PARTS} += $partsCount;
  597:                     $res->{DATA}->{CHILD_CORRECT} += $partsRight;
  598: 		    $res->{DATA}->{CHILD_ATTEMPTED} += $partsAttempted;
  599:                 }
  600:             }
  601:         }
  602:         $curRes = $iterator->next();
  603:     }
  604:     return ($navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted);
  605: }
  606: 
  607: #
  608: # Outputting everything.
  609: #
  610: 
  611: sub outputTable {
  612: 
  613:     my ($r,$showPoints,$notshowTotals,
  614:            $navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted)=@_;
  615: 
  616:     my @start = (255, 255, 192);
  617:     my @end   = (0, 192, 0);
  618: 
  619:     my $indentString = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  620: 
  621:     # Second pass: Print the maps.
  622:     $r->print(&Apache::loncommon::start_data_table()
  623:              .&Apache::loncommon::start_data_table_header_row()
  624:              .'<th>'.&mt('Folder').'</th>');
  625:     my $title = &mt($showPoints ? "Points Scored" : "Done");
  626:     if ($totalAttempted) {
  627:         $title .= " / " . &mt("Attempted");
  628:     }
  629:     $r->print("<th>$title".($notshowTotals?'':" / ".&mt('Total')).'</th>'
  630:              .&Apache::loncommon::end_data_table_header_row());
  631: #
  632: # Output of folder scores
  633: #
  634: 
  635:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  636:     my $depth = 1;
  637:     $iterator->next(); # ignore first BEGIN_MAP
  638:     my $curRes = $iterator->next();
  639: 
  640:     while ($depth > 0) {
  641:         if ($curRes == $iterator->BEGIN_MAP()) {$depth++;}
  642:         if ($curRes == $iterator->END_MAP()) { $depth--; }
  643: 
  644:         if (ref($curRes) && $curRes->is_map()) {
  645:             my $title = $curRes->compTitle();
  646:             
  647:             my $correct = $curRes->{DATA}->{CHILD_CORRECT};
  648:             my $total = $curRes->{DATA}->{CHILD_PARTS};
  649: 	    my $attempted = $curRes->{DATA}->{CHILD_ATTEMPTED};
  650: 
  651:             if ($total > 0) {
  652:                 my $ratio;
  653:                 $ratio = $correct / $total;
  654:                 my $color = &mixColors(\@start, \@end, $ratio);
  655:                 $r->print(&Apache::loncommon::start_data_table_row()
  656:                          .'<td style="background-color:'.$color.';">');
  657:                 
  658: 		my $thisIndent = '';
  659:                 for (my $i = 1; $i < $depth; $i++) { $thisIndent .= $indentString; }
  660:                 
  661:                 $r->print("$thisIndent$title</td>");
  662: 		if ($totalAttempted) {
  663: 		    $r->print('<td valign="top">'
  664:                              .$thisIndent
  665:                              .'<span class="LC_nobreak">'
  666:                              .$correct.' / '.$attempted.($notshowTotals?'':' / '.$total)
  667:                              .'</span></td>'
  668:                              .&Apache::loncommon::end_data_table_row()
  669:                     );
  670: 		} else {
  671: 		    $r->print('<td valign="top">'
  672:                              .$thisIndent
  673:                              .'<span class="LC_nobreak">'
  674:                              .$correct.($notshowTotals?'':' / '.$total)
  675:                              .'</span></td>'
  676:                              .&Apache::loncommon::end_data_table_row());
  677: 		}
  678:             }
  679:         }
  680: 
  681:         $curRes = $iterator->next();
  682:     }
  683: 
  684:     # If there were any problems at the top level, print an extra "catchall"
  685:     if ($topLevelParts > 0) {
  686:         my $ratio = $topLevelRight / $topLevelParts;
  687:         my $color = &mixColors(\@start, \@end, $ratio);
  688:         $r->print(&Apache::loncommon::start_data_table_row()
  689:                  .'<td style="background-color:'.$color.';">');
  690:         $r->print(&mt("Problems Not Contained In A Folder")."</td><td>");
  691:         $r->print("$topLevelRight / $topLevelParts</td>"
  692:                  .&Apache::loncommon::end_data_table_row());
  693:     }
  694: 
  695: #
  696: # show totals (if applicable), close table
  697: #
  698:     if ($showPoints) {
  699:         my $maxHelpLink = &Apache::loncommon::help_open_topic("Quick_Grades_Possibly_Correct");
  700: 
  701:         $title = $showPoints ? "Points" : "Parts Done";
  702:         my $totaltitle = $showPoints ? &mt("Awarded Total Points") : &mt("Total Parts Done");
  703:         $r->print(&Apache::loncommon::start_data_table_row()
  704:                  .'<td colspan="2" align="right">'.$totaltitle.': <b>'.$totalRight.'</b><br />');
  705:         $r->print(&mt('Max Possible To Date')." $maxHelpLink: <b>$totalPossible</b><br />");
  706:         $title = $showPoints ? "Points" : "Parts";
  707:         $r->print(&mt("Total $title In Course").': <b>'.$totalParts.'</b></td>'
  708:                  .&Apache::loncommon::end_data_table_row());
  709:     }
  710: 
  711:     $r->print(&Apache::loncommon::end_data_table());
  712:     return;
  713: }
  714: 
  715: #
  716: # === Outputting category-based grades.
  717: #
  718: # $category{'order'}: output order of categories by id
  719: # $category{'all'}: complete list of all categories 
  720: # $category{$id.'_name'}: display-name of category
  721: #
  722: 
  723: sub outputCategories {
  724: 
  725:     my ($r,$showPoints,$notshowTotals,
  726:            $navmap,$totalParts,$totalPossible,$totalRight,$totalAttempted,$topLevelParts,$topLevelRight,$topLevelAttempted)=@_;
  727: # Take care of storing and retrieving categories
  728: 
  729:     my $cangrade=&Apache::lonnet::allowed('mgr');
  730: 
  731:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
  732:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
  733:     my %categories=();
  734: # Loading old categories
  735:     %categories=&Apache::lonnet::dump('grading_categories',$cdom,$cnum);
  736: # Storing
  737:     if (($cangrade) && (($env{'form.storechanges'}) || ($env{'form.storemove'} ne '') || ($env{'form.cmd'} ne ''))) {
  738: # Process the changes
  739:         %categories=&process_category_edits($r,$cangrade,%categories);
  740: # Actually store
  741:         &Apache::lonnet::put('grading_categories',\%categories,$cdom,$cnum);
  742:     }
  743: # new categories loaded now
  744:     &output_category_table($r,$cangrade,$navmap,1,%categories);
  745: #
  746:     if ($cangrade) {
  747:         $r->print(&Apache::loncommon::resourcebrowser_javascript().
  748:                   '<input type="hidden" name="storemove" value="" />'.
  749:                   '<input type="hidden" name="cmd" value="" />'.
  750:                   '<input type="hidden" name="resourcesymb" value="" />'.
  751:                   '<input type="submit" name="storechanges" value="'.&mt("Save changes to grading categories").'" />'.
  752:                   '<script>function storecmd (cmd) { document.quickform.cmd.value=cmd; document.quickform.submit(); }</script>');
  753:     }
  754: }
  755: 
  756: #
  757: # Get data for all symbs
  758: #
  759: 
  760: sub dumpdata {
  761:     my ($navmap)=@_;
  762:     my %returndata=();
  763: 
  764: # Run through the map and get all data
  765: 
  766:     my $iterator = $navmap->getIterator(undef, undef, undef, 1);
  767:     my $depth = 1;
  768:     $iterator->next(); # ignore first BEGIN_MAP
  769:     my $curRes = $iterator->next();
  770: 
  771:     while ($depth > 0) {
  772:         if ($curRes == $iterator->BEGIN_MAP()) {$depth++;}
  773:         if ($curRes == $iterator->END_MAP()) { $depth--; }
  774:         if (ref($curRes)) {
  775:             if ($curRes->is_map()) {
  776:                 $returndata{$curRes->symb()}='folder:'.$curRes->{DATA}->{CHILD_PARTS}.':'.$curRes->{DATA}->{CHILD_ATTEMPTED}.':'.$curRes->{DATA}->{CHILD_CORRECT};
  777:             } else {
  778:                 $returndata{$curRes->symb()}='res:'.$curRes->{DATA}->{PROB_WEIGHT}.':'.$curRes->{DATA}->{PROB_POSSIBLE}.':'.$curRes->{DATA}->{PROB_SCORE};
  779:             } 
  780:         }
  781:         $curRes = $iterator->next();
  782:     }
  783:     return %returndata;
  784: }
  785: 
  786: #
  787: # Process editing commands, update category hash
  788: #
  789: 
  790: sub process_category_edits {
  791:     my ($r,$cangrade,%categories)=@_;
  792:     unless ($cangrade) { return %categories; }
  793: # First store everything
  794:     foreach my $id (split(/\,/,$categories{'order'})) {
  795: # Set names, types, and weight (there is only one of each per category)
  796:         %categories=&set_category_name($cangrade,$id,$env{'form.name_'.$id},%categories);
  797:         %categories=&set_category_total($cangrade,$id,$env{'form.totaltype_'.$id},$env{'form.total_'.$id},%categories);
  798:         %categories=&set_category_weight($cangrade,$id,$env{'form.weight_'.$id},%categories);
  799:         %categories=&set_category_displayachieved($cangrade,$id,$env{'form.displayachieved_'.$id},%categories);
  800: # Set values for category rules (before names may change)
  801:         %categories=&set_category_rules($cangrade,$id,%categories);
  802:     }
  803: 
  804: # Now deal with commands
  805:     my $cmd=$env{'form.cmd'};
  806:     if ($cmd eq 'createnewcat') {
  807:         %categories=&make_new_category($r,$cangrade,undef,%categories);
  808:     } elsif ($cmd=~/^up\_(.+)$/) {
  809:         %categories=&move_up_category($1,$cangrade,%categories);
  810:     } elsif ($cmd=~/^down\_(.+)$/) {
  811:         %categories=&move_down_category($1,$cangrade,%categories);
  812:     } elsif ($cmd=~/^delcat\_(.+)$/) {
  813:         %categories=&del_category($1,$cangrade,%categories);
  814:     } elsif ($cmd=~/^addcont\_(.+)$/) {
  815:         %categories=&add_category_content($1,$cangrade,$env{'form.resourcesymb'},%categories);
  816:     } elsif ($cmd=~/^delcont\_(.+)\_\_\_\_\_\_(.+)$/) {
  817:         %categories=&del_category_content($1,$cangrade,$2,%categories);
  818:     } elsif ($cmd=~/^newrule\_(.+)$/) {
  819:         %categories=&add_calculation_rule($1,$cangrade,':',%categories);
  820:     } elsif ($cmd=~/^delrule\_(.+)\_\_\_\_\_\_(.*)$/) {
  821:         %categories=&del_calculation_rule($1,$cangrade,$2,%categories);
  822:     }
  823: # Move to a new position
  824:     my $moveid=$env{'form.storemove'};
  825:     if ($moveid) {
  826:         %categories=&move_category($moveid,$cangrade,$env{'form.newpos_'.$moveid},%categories);
  827:     } 
  828:     return %categories;
  829: }
  830: 
  831: #
  832: # Output the table
  833: #
  834: 
  835: sub output_category_table {
  836:     my ($r,$cangrade,$navmaps,$output,%categories)=@_;
  837:     
  838:     my $totalweight=0;
  839:     my $totalpoints=0;
  840: 
  841:     if ($output) { 
  842:        $r->print(&Apache::loncommon::start_data_table());
  843: #
  844:        &output_category_table_header($r,$cangrade);
  845:     }
  846: #
  847:     my @order=split(/\,/,$categories{'order'});
  848: #
  849:     my %performance=&dumpdata($navmaps);
  850:     my $maxpos=$#order;
  851:     for (my $i=0;$i<=$maxpos;$i++) {
  852:         my ($correct,$possible,$type,$weight)=&output_and_calc_category($r,$cangrade,$navmaps,$order[$i],$i,$maxpos,\%performance,$output,%categories);
  853:         unless ($possible) { next; }
  854:         $totalpoints+=$weight*$correct/$possible;
  855:         $totalweight+=$weight;
  856:     }
  857: #
  858:     my $perc=0;
  859:     if ($totalweight) { $perc=100.*$totalpoints/$totalweight; }
  860: 
  861:     if ($output) { 
  862:         &bottom_line_category($r,$cangrade,$perc); 
  863:         $r->print(&Apache::loncommon::end_data_table());
  864:     }
  865:     return $perc;
  866: }
  867: 
  868: sub output_category_table_header {
  869:     my ($r,$cangrade)=@_;
  870:     $r->print(&Apache::loncommon::start_data_table_header_row());
  871:     if ($cangrade) {
  872:         $r->print('<th colspan="2">'.&mt("Move").'</th><th>'.&mt('Action').'</th>');
  873:     }
  874:     $r->print('<th>'.&mt('Category').'</th>'.
  875:               '<th>'.&mt('Contents').'</th>'.
  876:               '<th>'.&mt('Total Points').'</th>'.
  877:               '<th>'.&mt('Calculation').'</th>'.
  878:               '<th>'.&mt('Relative Weight').'</th>'.
  879:               '<th>'.&mt('Achieved').'</th>');
  880:     $r->print(&Apache::loncommon::end_data_table_header_row());
  881: }
  882: 
  883: 
  884: #
  885: # Output one category to table
  886: #
  887: 
  888: sub output_and_calc_category {
  889:     my ($r,$cangrade,$navmaps,$id,$currentpos,$maxpos,$performance,$output,%categories)=@_;
  890:     
  891:     if ($output) { $r->print("\n".&Apache::loncommon::start_data_table_row()); }
  892: 
  893:     if ($output && $cangrade) {
  894:         my $iconpath = &Apache::loncommon::lonhttpdurl($r->dir_config('lonIconsURL') . "/");
  895:         my %lt=&Apache::lonlocal::texthash(
  896:            'up' => 'Move Up',
  897:            'dw' => 'Move Down');
  898: 
  899:         $r->print(<<ENDMOVE);
  900: <td>
  901: <div class="LC_docs_entry_move">
  902:   <a href='javascript:storecmd("up_$id");'>
  903:     <img src="${iconpath}move_up.gif" alt='$lt{'up'}' class="LC_icon" />
  904:   </a>
  905: </div>
  906: <div class="LC_docs_entry_move">
  907:   <a href='javascript:storecmd("down_$id");'>
  908:     <img src="${iconpath}move_down.gif" alt='$lt{'dw'}' class="LC_icon" />
  909:   </a>
  910: </div>
  911: </td>
  912: ENDMOVE
  913:         $r->print("\n<td>\n<select name='newpos_$id' onchange='this.form.storemove.value=\"$id\";this.form.submit()'>");
  914:         for (my $i=0;$i<=$maxpos;$i++) {
  915:             if ($i==$currentpos) {
  916:                 $r->print('<option value="" selected="selected">('.$i.')</option>');
  917:             } else {
  918:                 $r->print('<option value="'.$i.'">'.$i.'</option>');
  919:             }
  920:         }
  921:         $r->print("\n</select>\n</td>\n");
  922:         $r->print('<td><a href="javascript:storecmd(\'delcat_'.$id.'\');">'.&mt('Delete').'</a></td>');
  923:         $r->print('<td><input type="text" name="name_'.$id.
  924:                   '" value="'.&Apache::lonhtmlcommon::entity_encode($categories{$id.'_name'}).'" /></td>');
  925:     } elsif ($output) {
  926:         $r->print('<td>'.$categories{$id.'_name'}.'</td>');
  927:     }
  928: # Content display and summing up of points
  929:     my $totalpossible=0;
  930:     my $totalcorrect=0;
  931:     my @individual=();
  932:     if ($output) { $r->print('<td><ul>'); }
  933:     foreach my $contentid (split(/\,/,$categories{$id.'_content'})) {
  934:         my ($type,$possible,$attempted,$correct)=split(/\:/,$$performance{$contentid});
  935:         $totalpossible+=$possible;
  936:         $totalcorrect+=$correct;
  937:         if ($possible>0) { push(@individual,"$possible:$correct"); }
  938:         if ($output) {
  939:            $r->print('<li>');
  940:            $r->print(&Apache::lonnet::gettitle($contentid).' ('.&numberout($correct).'/'.&numberout($possible).')');
  941:            if ($cangrade) {
  942:               $r->print(' <a href="javascript:storecmd(\'delcont_'.$id.'______'.$contentid.'\');">'.&mt('Delete').'</a>');
  943:            }
  944:            $r->print('</li>');
  945:         }
  946:     }
  947:     if ($output) {
  948:        $r->print('</ul>');
  949:        if ($cangrade) {
  950:            $r->print('<br />'.&Apache::loncommon::selectresource_link('quickform','addcont_'.$id,&mt('Add Problem or Folder')).'<br />');
  951:        }
  952:        $r->print('<p><b>'.&mt('Total raw points: [_1]/[_2]',&numberout($totalcorrect),&numberout($totalpossible)).'</b></p>');
  953:        $r->print('</td>'); 
  954:     }
  955: # Total
  956:     if ($output) { $r->print('<td>'); }
  957:     if ($cangrade) {
  958:        if ($output) { 
  959:           $r->print(
  960:                   '<select name="totaltype_'.$id.'">'.
  961:                   '<option value="default"'.($categories{$id.'_totaltype'} eq 'default'?' selected="selected"':'').'>'.&mt('default').'</option>'.
  962:                   '<option value="typein"'.($categories{$id.'_totaltype'} eq 'typein'?' selected="selected"':'').'>'.&mt('Type-in value').'</option>'.
  963:                   '</select>'.
  964:                   '<input type="text" size="4" name="total_'.$id.
  965:                   '" value="'.&Apache::lonhtmlcommon::entity_encode($categories{$id.'_total'}).'" />'); 
  966:        }
  967:     } else {
  968:        if ($output) {
  969:           $r->print('<td>'.($categories{$id.'_totaltype'} eq 'default'?&mt('default'):$categories{$id.'_total'}));
  970:        }
  971:     }
  972: # Adjust total points
  973:     if ($categories{$id.'_totaltype'} eq 'typein') {
  974:        $totalpossible=1.*$categories{$id.'_total'};
  975:     }
  976:     if ($output) {
  977:        $r->print('<p><b>'.&mt('Adjusted raw points: [_1]/[_2]',&numberout($totalcorrect),&numberout($totalpossible)).'</b></p>');
  978:     }
  979: 
  980: 
  981: # Calculation
  982:     if ($output) { $r->print('<td><ul>'); }
  983:     foreach my $calcrule (split(/\,/,$categories{$id.'_calculations'})) {
  984:         if ($output) { $r->print('<li>'); }
  985:         my ($code,$value)=split(/\:/,$calcrule);
  986:         if ($output) { $r->print(&pretty_prt_rule($cangrade,$id,$code,$value)); }
  987:         if ($cangrade) {
  988:            if ($output) { $r->print(' <a href="javascript:storecmd(\'delrule_'.$id.'______'.$code.'\');">'.&mt('Delete').'</a>'); }
  989:         }
  990:         if ($code eq 'capabove') {
  991:             if ($totalpossible>0) {
  992:                 if ($totalcorrect/$totalpossible>$value/100.) {
  993:                     $totalcorrect=$totalpossible*$value/100.;
  994:                 }
  995:             }
  996:         } elsif ($code eq 'capbelow') {
  997:             if ($totalpossible>0) {
  998:                 if ($totalcorrect/$totalpossible<$value/100.) {
  999:                     $totalcorrect=$totalpossible*$value/100.;
 1000:                 }
 1001:             }
 1002:         } elsif ($code eq 'droplow') {
 1003:             ($totalpossible,$totalcorrect,@individual)=&drop(0,0,$value,@individual);
 1004:         } elsif ($code eq 'drophigh') {
 1005:             ($totalpossible,$totalcorrect,@individual)=&drop(1,0,$value,@individual);
 1006:         } elsif ($code eq 'droplowperc') {
 1007:             ($totalpossible,$totalcorrect,@individual)=&drop(0,1,$value,@individual);
 1008:         } elsif ($code eq 'drophighperc') {
 1009:             ($totalpossible,$totalcorrect,@individual)=&drop(1,1,$value,@individual);
 1010:         }
 1011:         if ($output) { $r->print('</li>'); }
 1012:     }
 1013: # Re-adjust total points if force total
 1014:     if ($categories{$id.'_totaltype'} eq 'typein') {
 1015:        $totalpossible=1.*$categories{$id.'_total'};
 1016:     }
 1017: 
 1018:     if ($output) { 
 1019:         $r->print('</ul>'); 
 1020:         if ($cangrade) { $r->print('<br />'.&new_calc_rule_form($id)); }
 1021:         $r->print('<p><b>'.&mt('Calculated points: [_1]/[_2]',&numberout($totalcorrect),&numberout($totalpossible)).'</b></p>');
 1022:         $r->print('</td>'); 
 1023:     }
 1024: #
 1025: # Prepare for export
 1026: #
 1027: # Weight
 1028:     my $weight=$categories{$id.'_weight'};
 1029:     unless (1.*$weight>0) { $weight=0; }
 1030:     if ($cangrade) {
 1031:        if ($output) { 
 1032:           $r->print('<td>'.
 1033:                   '<input type="text" size="4" name="weight_'.$id.
 1034:                   '" value="'.&Apache::lonhtmlcommon::entity_encode($weight).'" /></td>');
 1035:        }
 1036:     } else {
 1037:        if ($output) {
 1038:           $r->print('<td>'.$weight.'</td>');
 1039:        }
 1040:     }
 1041: # Achieved
 1042:     my $type=$categories{$id.'_displayachieved'};
 1043:     unless (($type eq 'percent') || ($type eq 'points')) { $type='points'; }
 1044:     if ($output) { $r->print('<td>'); }
 1045:     if ($cangrade) {
 1046:         if ($output) {
 1047:            $r->print('<select name="displayachieved_'.$id.'">'.
 1048:                   '<option value="percent"'.($type eq 'percent'?' selected="selected"':'').'>'.&mt('percent').'</option>'.
 1049:                   '<option value="points"'.($type eq 'points'?' selected="selected"':'').'>'.&mt('points').'</option>'.
 1050:                   '</select>');
 1051:         }
 1052:     }
 1053:     if ($output) {
 1054:         $r->print('<p><b>');
 1055:         if ($type eq 'percent') {
 1056:             my $perc='---';
 1057:             if ($totalpossible) {
 1058:                 $perc=100.*$totalcorrect/$totalpossible;
 1059:             }
 1060:             $r->print(&mt('[_1] percent',&numberout($perc)));
 1061:         } else {
 1062:             $r->print(&mt('[_1]/[_2] points',&numberout($totalcorrect),&numberout($totalpossible)));
 1063:         }
 1064:         $r->print('</b></p>');
 1065:     }
 1066:     if ($output) { $r->print('</td>'); }
 1067: 
 1068:     return ($totalcorrect,$totalpossible,$type,$weight);
 1069: }
 1070: 
 1071: #
 1072: # Drop folders and problems
 1073: #
 1074: 
 1075: sub drop {
 1076:     my ($high,$percent,$n,@individual)=@_;
 1077: # Sort assignments by points or percent
 1078:     my @newindividual=sort {
 1079:         my ($pa,$ca)=split(/\:/,$a);
 1080:         my ($pb,$cb)=split(/\:/,$b);
 1081:         if ($percent) {
 1082:             my $perca=0;
 1083:             if ($pa>0) { $perca=$ca/$pa; }
 1084:             my $percb=0;
 1085:             if ($pb>0) { $percb=$cb/$pb; }
 1086:             $perca<=>$percb;
 1087:         } else {
 1088:             $ca<=>$cb;
 1089:         }
 1090:     } @individual;
 1091: # Drop the ones we don't want
 1092:     if ($#newindividual>=$n) {
 1093:         if ($high) {
 1094:            splice(@newindividual,$#newindividual+1-$n,$n);
 1095:         } else {
 1096:            splice(@newindividual,0,$n);
 1097:         }
 1098:     } else {
 1099:         @newindividual=();
 1100:     }
 1101: # Re-calculate how many points possible and achieved
 1102:     my $newpossible=0;
 1103:     my $newcorrect=0;
 1104:     for my $score (@newindividual) {
 1105:         my ($thispossible,$thiscorrect)=(split(/\:/,$score));
 1106:         $newpossible+=$thispossible;
 1107:         $newcorrect+=$thiscorrect;
 1108:     }
 1109:     return ($newpossible,$newcorrect,@newindividual);
 1110: } 
 1111: #
 1112: # Bottom line with grades
 1113: #
 1114: 
 1115: sub bottom_line_category {
 1116:     my ($r,$cangrade,$perc)=@_;
 1117:     $r->print(&Apache::loncommon::start_data_table_row());
 1118:     if ($cangrade) {
 1119:         $r->print('<td colspan="3"><a href="javascript:storecmd(\'createnewcat\');">'.&mt('Create New Category').'</a></td>');
 1120:     }
 1121:     $r->print('<td colspan="6"><b>'.&mt('Total: [_1] percent',&numberout($perc)).'</b></td>');
 1122: }
 1123: 
 1124: sub numberout {
 1125:     my ($number)=@_;
 1126:     my $printout=sprintf("%.3f", $number);
 1127:     $printout=~s/0+$//;
 1128:     $printout=~s/\.$//;
 1129:     return $printout;
 1130: }
 1131: #
 1132: # Make one new category
 1133: #
 1134: 
 1135: sub make_new_category {
 1136:     my ($r,$cangrade,$ordernum,%categories)=@_;
 1137:     unless ($cangrade) { return %categories; }
 1138: # Generate new ID
 1139:     my $id=time.'_'.$$.'_'.rand(10000);
 1140: # Add new ID to list of all IDs ever created in this course
 1141:     $categories{'all'}.=','.$id;
 1142:     $categories{'all'}=~s/^\,//;
 1143: # Add new ID to ordered list of displayed and evaluated categories
 1144:     $categories{'order'}.=','.$id;
 1145:     $categories{'order'}=~s/^\,//;
 1146: # Move it into desired space
 1147:     if (defined($ordernum)) {
 1148:         %categories=&move_category($id,$cangrade,$ordernum,%categories);
 1149:     }
 1150:     $categories{$id.'_weight'}=0;
 1151:     $categories{$id.'_totaltype'}='default';
 1152:     $categories{$id.'_displayachieved'}='percent';
 1153:     return %categories;
 1154: }
 1155: 
 1156: 
 1157: # === Calculation Rule Editing
 1158: 
 1159: sub category_rule_codes {
 1160:     return &Apache::lonlocal::texthash(
 1161:                 'droplowperc'  => 'Drop N lowest grade percentage problems/folders',
 1162:                 'drophighperc' => 'Drop N highest grade percentage problems/folderss',
 1163:                 'droplow'  => 'Drop N lowest point problems/folders',
 1164:                 'drophigh' => 'Drop N highest point problems/folders',
 1165:                 'capabove' => 'Cap percentage above N percent',
 1166:                 'capbelow' => 'Cap percentage below N percent');
 1167: }
 1168: 
 1169: sub pretty_prt_rule {
 1170:     my ($cangrade,$id,$code,$value)=@_;
 1171:     my $cid=$id.'_'.$code;
 1172:     my %lt=&category_rule_codes();
 1173:     my $ret='<span class="LC_nobreak">';
 1174:     if ($cangrade) {
 1175:         $ret.='<select name="sel_'.$cid.'">';
 1176:         foreach my $calc (''=>'',sort(keys(%lt))) {
 1177:             $ret.='<option value="'.$calc.'"'.($calc eq $code?' selected="selected"':'').' />'.$lt{$calc}.'</input>';
 1178:         }
 1179:         $ret.='</select> N=<input type="text" size="5" name="val_'.$cid.'" value="'.$value.'" /></span>';
 1180:     } else {
 1181:         $ret.=$lt{$code}.'; N='.$value;
 1182:     }
 1183:     $ret.='</span>';
 1184:     return $ret;
 1185: }
 1186: 
 1187: sub new_calc_rule_form {
 1188:     my ($id)=@_;
 1189:     return '<a href="javascript:storecmd(\'newrule_'.$id.'\');">'.&mt('New Calculation Rule').'</a>';
 1190: }
 1191: 
 1192: #
 1193: # Add a calculation rule
 1194: #
 1195: 
 1196: sub add_calculation_rule {
 1197:     my ($id,$cangrade,$newcontent,%categories)=@_;
 1198:     unless ($cangrade) { return %categories; }
 1199:     my %newcontent=($newcontent => 1);
 1200:     foreach my $current (split(/\,/,$categories{$id.'_calculations'})) {
 1201:         $newcontent{$current}=1;
 1202:     }
 1203:     $categories{$id.'_calculations'}=join(',',sort(keys(%newcontent)));
 1204:     return %categories;
 1205: }
 1206: 
 1207: #
 1208: # Delete a calculation rule
 1209: #
 1210: 
 1211: sub del_calculation_rule {
 1212:     my ($id,$cangrade,$delcontent,%categories)=@_;
 1213:     unless ($cangrade) { return %categories; }
 1214:     my @newcontent=();
 1215:     foreach my $current (split(/\,/,$categories{$id.'_calculations'})) {
 1216:         unless ($current=~/^\Q$delcontent\E\:/) {
 1217:             push(@newcontent,$current);
 1218:         }
 1219:     }
 1220:     $categories{$id.'_calculations'}=join(',',@newcontent);
 1221:     return %categories;
 1222: }
 1223: 
 1224: sub set_category_rules {
 1225:     my ($cangrade,$id,%categories)=@_;
 1226:     unless ($cangrade) { return %categories; }
 1227:     my %lt=&category_rule_codes();
 1228:     my @newrules=();
 1229:     foreach my $code ('',(keys(%lt))) {
 1230:         if ($env{'form.sel_'.$id.'_'.$code}) {
 1231:             push(@newrules,$env{'form.sel_'.$id.'_'.$code}.':'.$env{'form.val_'.$id.'_'.$code});
 1232:         }
 1233:     }
 1234:     $categories{$id.'_calculations'}=join(',',sort(@newrules));
 1235:     return %categories;
 1236: }
 1237: 
 1238: 
 1239: # === Category Editing
 1240: 
 1241: #
 1242: # Add to category content
 1243: #
 1244: 
 1245: sub add_category_content {
 1246:     my ($id,$cangrade,$newcontent,%categories)=@_;
 1247:     unless ($cangrade) { return %categories; }
 1248:     &Apache::lonnet::logthis("In here $newcontent");
 1249:     my %newcontent=($newcontent => 1);
 1250:     foreach my $current (split(/\,/,$categories{$id.'_content'})) {
 1251:         $newcontent{$current}=1;
 1252:     }
 1253:     $categories{$id.'_content'}=join(',',sort(keys(%newcontent)));
 1254:     return %categories;
 1255: }
 1256: 
 1257: #
 1258: # Delete from category content
 1259: #
 1260: 
 1261: sub del_category_content {
 1262:     my ($id,$cangrade,$delcontent,%categories)=@_;
 1263:     unless ($cangrade) { return %categories; }
 1264:     my @newcontent=();
 1265:     foreach my $current (split(/\,/,$categories{$id.'_content'})) {
 1266:         unless ($current eq $delcontent) {
 1267:             push(@newcontent,$current);
 1268:         }
 1269:     }
 1270:     $categories{$id.'_content'}=join(',',@newcontent);
 1271:     return %categories;
 1272: }
 1273: 
 1274: #
 1275: # Delete category
 1276: #
 1277: 
 1278: sub del_category {
 1279:     my ($id,$cangrade,%categories)=@_;
 1280:     unless ($cangrade) { return %categories; }
 1281:     my @neworder=();
 1282:     foreach my $currentid (split(/\,/,$categories{'order'})) {
 1283:         unless ($currentid eq $id) {
 1284:             push(@neworder,$currentid);
 1285:         }
 1286:     }
 1287:     $categories{'order'}=join(',',@neworder);
 1288:     return %categories;
 1289: }
 1290: 
 1291: #
 1292: # Move category up
 1293: #
 1294: 
 1295: sub move_up_category {
 1296:     my ($id,$cangrade,%categories)=@_;
 1297:     my $currentpos=&current_pos_category($id,%categories);
 1298:     if ($currentpos<1) { return %categories; }
 1299:     return &move_category($id,$cangrade,$currentpos-1,%categories);
 1300: }
 1301: 
 1302: #
 1303: # Move category down
 1304: #
 1305: 
 1306: sub move_down_category {
 1307:     my ($id,$cangrade,%categories)=@_;
 1308:     my $currentpos=&current_pos_category($id,%categories);
 1309:     my @order=split(/\,/,$categories{'order'});
 1310:     if ($currentpos>=$#order) { return %categories; }
 1311:     return &move_category($id,$cangrade,$currentpos+1,%categories);
 1312: }
 1313: 
 1314: #
 1315: # Move a category to a desired position n the display order
 1316: #
 1317: 
 1318: sub move_category {
 1319:     my ($id,$cangrade,$ordernum,%categories)=@_;
 1320:     unless ($cangrade) { return %categories; }
 1321:     my @order=split(/\,/,$categories{'order'});
 1322: # Where is the index currently?
 1323:     my $currentpos=&current_pos_category($id,%categories);
 1324:     if (defined($currentpos)) {
 1325:         if ($currentpos<$ordernum) {
 1326: # This is moving to a higher index
 1327: # ....X1234....
 1328: # ....1234X....
 1329:             for (my $i=$currentpos;$i<$ordernum;$i++) {
 1330:                 $order[$i]=$order[$i+1];
 1331:             }
 1332:             $order[$ordernum]=$id;
 1333:         }
 1334:         if ($currentpos>$ordernum) {
 1335: # This is moving to a lower index
 1336: # ....1234X....
 1337: # ....X1234....
 1338:             for (my $i=$currentpos;$i>$ordernum;$i--) {
 1339:                 $order[$i]=$order[$i-1];
 1340:             }
 1341:             $order[$ordernum]=$id;
 1342:         }
 1343:     }
 1344:     $categories{'order'}=join(',',@order);
 1345:     return %categories;
 1346: }
 1347: 
 1348: #
 1349: #  Find current postion of a category in the order
 1350: #
 1351: 
 1352: sub current_pos_category {
 1353:     my ($id,%categories)=@_;
 1354:     my @order=split(/\,/,$categories{'order'});
 1355:     for (my $i=0;$i<=$#order;$i++) {
 1356:         if ($order[$i] eq $id) { return $i; }
 1357:     }
 1358: # not found
 1359:     return undef;
 1360: }
 1361: 
 1362: #
 1363: # Set name of a category
 1364: #
 1365: sub set_category_name {
 1366:     my ($cangrade,$id,$name,%categories)=@_;
 1367:     unless ($cangrade) { return %categories; }
 1368:     $categories{$id.'_name'}=$name;
 1369:     return %categories;
 1370: }
 1371: 
 1372: #
 1373: # Set total of a category
 1374: #
 1375: sub set_category_total {
 1376:     my ($cangrade,$id,$totaltype,$total,%categories)=@_;
 1377:     unless ($cangrade) { return %categories; }
 1378:     if (($categories{$id.'_total'} eq '') && ($total=~/\d/)) {
 1379:         $totaltype='typein';
 1380:     }
 1381:     $categories{$id.'_totaltype'}=$totaltype;
 1382:     if ($totaltype eq 'default') {
 1383:         $categories{$id.'_total'}='';
 1384:     } else {
 1385:         $total=~s/\D//gs;
 1386:         unless ($total) { $total=0; }
 1387:         $categories{$id.'_total'}=$total;
 1388:     }
 1389:     return %categories;
 1390: }
 1391: 
 1392: sub set_category_weight {
 1393:     my ($cangrade,$id,$weight,%categories)=@_;
 1394:     unless ($cangrade) { return %categories; }
 1395:     $weight=~s/\D//gs;
 1396:     unless ($weight) { $weight=0; }
 1397:     $categories{$id.'_weight'}=$weight;
 1398:     return %categories;
 1399: }
 1400: 
 1401: sub set_category_displayachieved {
 1402:     my ($cangrade,$id,$value,%categories)=@_;
 1403:     unless ($cangrade) { return %categories; }
 1404:     unless (($value eq 'percent') || ($value eq 'points')) { $value='percent'; }
 1405:     $categories{$id.'_displayachieved'}=$value;
 1406:     return %categories;
 1407: }
 1408: 
 1409: 
 1410: #
 1411: # === end category-related
 1412: #
 1413: #
 1414: # Pass this two refs to arrays for the start and end color, and a number
 1415: # from 0 to 1 for how much of the latter you want to mix in. It will
 1416: # return a string ready to show ("#FFC309");
 1417: 
 1418: sub mixColors {
 1419:     my $start = shift;
 1420:     my $end = shift;
 1421:     my $ratio = shift;
 1422:     
 1423:     my ($a,$b);
 1424:     my $final = "";
 1425:     $a = $start->[0]; $b = $end->[0];
 1426:     my $mix1 = POSIX::floor((1-$ratio)*$a + $ratio*$b);
 1427:     $a = $start->[1]; $b = $end->[1];
 1428:     my $mix2 = POSIX::floor((1-$ratio)*$a + $ratio*$b);
 1429:     $a = $start->[2]; $b = $end->[2];
 1430:     my $mix3 = POSIX::floor((1-$ratio)*$a + $ratio*$b);
 1431: 
 1432:     $final = sprintf "%02x%02x%02x", $mix1, $mix2, $mix3;
 1433:     return "#" . $final;
 1434: }
 1435: 
 1436: 1;

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>