File:  [LON-CAPA] / loncom / interface / lonquickgrades.pm
Revision 1.126: download - view: text, annotated - select for diffs
Sun Sep 24 03:31:18 2023 UTC (7 months, 3 weeks ago) by raeburn
Branches: MAIN
CVS tags: HEAD
- Bug 2689

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

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