File:  [LON-CAPA] / loncom / interface / spreadsheet / studentcalc.pm
Revision 1.7: download - view: text, annotated - select for diffs
Fri May 23 21:03:29 2003 UTC (21 years, 1 month ago) by matthew
Branches: MAIN
CVS tags: version_0_99_0, HEAD
CSV output implemented.

    1: #
    2: # $Id: studentcalc.pm,v 1.7 2003/05/23 21:03:29 matthew Exp $
    3: #
    4: # Copyright Michigan State University Board of Trustees
    5: #
    6: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
    7: #
    8: # LON-CAPA is free software; you can redistribute it and/or modify
    9: # it under the terms of the GNU General Public License as published by
   10: # the Free Software Foundation; either version 2 of the License, or
   11: # (at your option) any later version.
   12: #
   13: # LON-CAPA is distributed in the hope that it will be useful,
   14: # but WITHOUT ANY WARRANTY; without even the implied warranty of
   15: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   16: # GNU General Public License for more details.
   17: #
   18: # You should have received a copy of the GNU General Public License
   19: # along with LON-CAPA; if not, write to the Free Software
   20: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
   21: #
   22: # /home/httpd/html/adm/gpl.txt
   23: #
   24: # http://www.lon-capa.org/
   25: #
   26: # The LearningOnline Network with CAPA
   27: # Spreadsheet/Grades Display Handler
   28: #
   29: # POD required stuff:
   30: 
   31: =head1 NAME
   32: 
   33: studentcalc
   34: 
   35: =head1 SYNOPSIS
   36: 
   37: =head1 DESCRIPTION
   38: 
   39: =over 4
   40: 
   41: =cut
   42: 
   43: ###################################################
   44: ###                 StudentSheet                ###
   45: ###################################################
   46: package Apache::studentcalc;
   47: 
   48: use strict;
   49: use Apache::Constants qw(:common :http);
   50: use Apache::lonnet;
   51: use Apache::loncommon();
   52: use Apache::loncoursedata();
   53: use Apache::lonnavmaps;
   54: use Apache::Spreadsheet();
   55: use Apache::assesscalc();
   56: use HTML::Entities();
   57: use Spreadsheet::WriteExcel;
   58: use Time::HiRes;
   59: 
   60: @Apache::studentcalc::ISA = ('Apache::Spreadsheet');
   61: 
   62: my @Sequences = ();
   63: my %Exportrows = ();
   64: 
   65: my $current_course;
   66: 
   67: sub initialize_package {
   68:     $current_course = $ENV{'request.course.id'};
   69:     &initialize_sequence_cache();
   70:     &load_cached_export_rows();
   71: }
   72: 
   73: sub initialize_sequence_cache {
   74:     #
   75:     # Set up the sequences and assessments
   76:     @Sequences = ();
   77:     my ($top,$sequences,$assessments) = 
   78:         &Apache::loncoursedata::get_sequence_assessment_data();
   79:     if (! defined($top) || ! ref($top)) {
   80:         # There has been an error, better report it
   81:         &Apache::lonnet::logthis('top is undefined (studentcalc.pm)');
   82:         return;
   83:     }
   84:     @Sequences = @{$sequences} if (ref($sequences) eq 'ARRAY');
   85: }
   86: 
   87: sub clear_package {
   88:     @Sequences = undef;
   89:     %Exportrows = undef;
   90: }
   91: 
   92: sub get_title {
   93:     my $self = shift;
   94:     my @title = ();
   95:     #
   96:     # Determine the students name
   97:     my %userenv = &Apache::loncoursedata::GetUserName($self->{'name'},
   98:                                                       $self->{'domain'});
   99:     my $name = join(' ',
  100:                  @userenv{'firstname','middlename','lastname','generation'});
  101:     $name =~ s/\s+$//;
  102: 
  103:     push (@title,$name);
  104:     push (@title,$self->{'coursedesc'});
  105:     push (@title,scalar(localtime(time)));
  106:     return @title;
  107: }
  108: 
  109: sub get_html_title {
  110:     my $self = shift;
  111:     my ($name,$desc,$time) = $self->get_title();
  112:     my $title = '<h1>'.$name;
  113:     if ($ENV{'user.name'} ne $self->{'name'} && 
  114:         $ENV{'user.domain'} ne $self->{'domain'}) {
  115:         $title .= &Apache::loncommon::aboutmewrapper
  116:                                     ($self->{'name'}.'@'.$self->{'domain'},
  117:                                      $self->{'name'},$self->{'domain'});
  118:     }
  119:     $title .= "</h1>\n";
  120:     $title .= '<h2>'.$desc."</h2>\n";
  121:     $title .= '<h3>'.$time.'</h3>';
  122:     return $title;
  123: }
  124: 
  125: sub parent_link {
  126:     my $self = shift;
  127:     my $link .= '<p><a href="/adm/classcalc?'.
  128:         'sname='.$self->{'name'}.
  129:             '&sdomain='.$self->{'domain'}.'">'.
  130:                 'Course level sheet</a></p>'."\n";
  131:     return $link;
  132: }
  133: 
  134: sub outsheet_html {
  135:     my $self = shift;
  136:     my ($r) = @_;
  137:     ####################################
  138:     # Get the list of assessment files #
  139:     ####################################
  140:     my @AssessFileNames = $self->othersheets('assesscalc');
  141:     my $editing_is_allowed = &Apache::lonnet::allowed('mgr',
  142:                                                 $ENV{'request.course.id'});
  143:     ####################################
  144:     # Determine table structure        #
  145:     ####################################
  146:     my $num_uneditable = 26;
  147:     my $num_left = 52-$num_uneditable;
  148:     my $tableheader =<<"END";
  149: <p>
  150: <table border="2">
  151: <tr>
  152:   <th colspan="2" rowspan="2"><font size="+2">Student</font></th>
  153:   <td bgcolor="#FFDDDD" colspan="$num_uneditable">
  154:       <b><font size="+1">Import</font></b></td>
  155:   <td colspan="$num_left">
  156:       <b><font size="+1">Calculations</font></b></td>
  157: </tr><tr>
  158: END
  159:     my $label_num = 0;
  160:     foreach (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')){
  161:         if ($label_num<$num_uneditable) { 
  162:             $tableheader .='<td bgcolor="#FFDDDD">';
  163:         } else {
  164:             $tableheader .='<td>';
  165:         }
  166:         $tableheader .="<b><font size=+1>$_</font></b></td>";
  167:         $label_num++;
  168:     }
  169:     $tableheader .="</tr>\n";
  170:     if ($self->blackout()) {
  171:         $r->print('<font color="red" size="+2"><p>'.
  172:                   'Some computations are not available at this time.<br />'.
  173:                   'There are problems whose status you are allowed to view.'.
  174:                   '</font></p>'."\n");
  175:     } else {
  176:         $r->print($tableheader);
  177:         #
  178:         # Print out template row
  179:         if (exists($ENV{'request.role.adv'}) && $ENV{'request.role.adv'}) {
  180:             $r->print('<tr><td>Template</td><td>&nbsp;</td>'.
  181:                       $self->html_template_row($num_uneditable)."</tr>\n");
  182:         }
  183:         #
  184:         # Print out summary/export row
  185:         $r->print('<tr><td>Summary</td><td>0</td>'.
  186:                   $self->html_export_row()."</tr>\n");
  187:     }
  188:     $r->print("</table>\n");
  189:     #
  190:     # Prepare to output rows
  191:     if (exists($ENV{'request.role.adv'}) && $ENV{'request.role.adv'}) {
  192:         $tableheader =<<"END";
  193: </p><p>
  194: <table border="2">
  195: <tr><th>Row</th><th>Assessment</th>
  196: END
  197:     } else {
  198:         $tableheader =<<"END";
  199: </p><p>
  200: <table border="2">
  201: <tr><th>&nbsp;</th><th>Assessment</th>
  202: END
  203:     }
  204:     foreach (split(//,'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')){
  205: 	if ($label_num<$num_uneditable) { 
  206:             $tableheader.='<td bgcolor="#FFDDDD">';
  207:         } else {
  208:             $tableheader.='<td>';
  209:         }
  210:         $tableheader.="<b><font size=+1>$_</font></b></td>";
  211:     }
  212:     $tableheader.="\n";
  213:     #
  214:     my $num_output = 1;
  215:     if (scalar(@Sequences)< 1) {
  216:         &initialize_sequence_cache();
  217:     }
  218:     foreach my $Sequence (@Sequences) {
  219: 	next if ($Sequence->{'num_assess'} < 1);
  220: 	$r->print("<h3>".$Sequence->{'title'}."</h3>\n");
  221:  	$r->print($tableheader);
  222: 	foreach my $resource (@{$Sequence->{'contents'}}) {
  223: 	    next if ($resource->{'type'} ne 'assessment');
  224: 	    my $rownum = $self->get_row_number_from_key($resource->{'symb'});
  225:             my $assess_filename = $self->{'row_source'}->{$rownum};
  226:             my $row_output = '<tr>';
  227:             if ($editing_is_allowed) {
  228:                 $row_output .= '<td>'.$rownum.'</td>';
  229:                 $row_output .= '<td>'.
  230:                     '<a href="/adm/assesscalc?sname='.$self->{'name'}.
  231:                     '&sdomain='.$self->{'domain'}.
  232:                     '&filename='.$assess_filename.
  233:                     '&usymb='.&Apache::lonnet::escape($resource->{'symb'}).
  234:                     '">'.$resource->{'title'}.'</a><br />';
  235:                 $row_output .= &assess_file_selector($rownum,
  236:                                                      $assess_filename,
  237:                                                      \@AssessFileNames).
  238:                                                          '</td>';
  239:             } else {
  240:                 $row_output .= '<td><a href="'.$resource->{'src'}.'?symb='.
  241:                     &Apache::lonnet::escape($resource->{'symb'}).
  242:                     '">Go&nbsp;To</a>';
  243:                 $row_output .= '</td><td>'.$resource->{'title'}.'</td>';
  244:             }
  245:             if ($self->blackout() && $self->{'blackout_rows'}->{$rownum}>0) {
  246:                 $row_output .= 
  247:                     '<td colspan="52">Unavailable at this time</td></tr>'."\n";
  248:             } else {
  249:                 $row_output .= $self->html_row($num_uneditable,$rownum).
  250:                     "</tr>\n";
  251:             }
  252:             $r->print($row_output);
  253: 	}
  254: 	$r->print("</table>\n");
  255:     }
  256:     $r->print("</p>\n");
  257:     return;
  258: }
  259: 
  260: ########################################################
  261: ########################################################
  262: 
  263: =pod
  264: 
  265: =item &assess_file_selector()
  266: 
  267: =cut
  268: 
  269: ########################################################
  270: ########################################################
  271: sub assess_file_selector {
  272:     my ($row,$default,$AssessFiles)=@_;
  273:     if (!defined($AssessFiles) || ! @$AssessFiles) {
  274:         return '';
  275:     }
  276:     return '' if (! &Apache::lonnet::allowed('mgr',$ENV{'request.course.id'}));
  277:     my $element_name = 'FileSelect_'.$row;
  278:     my $load_dialog = '<select size="1" name="'.$element_name.'" '.
  279:         'onchange="'.
  280:         "document.sheet.cell.value='source_$row';".
  281:         "document.sheet.newformula.value=document.sheet.$element_name\.value;".
  282:         'document.sheet.submit()" '.'>'."\n";
  283:     foreach my $file (@{$AssessFiles}) {
  284:         $load_dialog .= '    <option name="'.$file.'"';
  285:         $load_dialog .= ' selected' if ($default eq $file);
  286:         $load_dialog .= '>'.$file."</option>\n";
  287:     }
  288:     $load_dialog .= "</select>\n";
  289:     return $load_dialog;
  290: }
  291: 
  292: sub modify_cell {
  293:     my $self = shift;
  294:     my ($cell,$formula) = @_;
  295:     if ($cell =~ /^source_(\d+)$/) {
  296:         # Need to make sure $formula is a valid filename....
  297:         my $row = $1;
  298:         $cell = 'A'.$row;
  299:         $self->{'row_source'}->{$row} = $formula;
  300:         my $original_source = $self->formula($cell);
  301:         if ($original_source =~ /__&&&__/) {
  302:             ($original_source,undef) = split('__&&&__',$original_source);
  303:         }
  304:         $formula = $original_source.'__&&&__'.$formula;
  305:     } elsif ($cell =~ /([A-z])\-/) {
  306:         $cell = 'template_'.$1;
  307:     } elsif ($cell !~ /^([A-z](\d+)|template_[A-z])$/) {
  308:         return;
  309:     }
  310:     $self->set_formula($cell,$formula);
  311:     $self->rebuild_stats();
  312:     return;
  313: }
  314: 
  315: sub csv_rows {
  316:     # writes the meat of the spreadsheet to an excel worksheet.  Called
  317:     # by Spreadsheet::outsheet_excel;
  318:     my $self = shift;
  319:     my ($filehandle) = @_;
  320:     #
  321:     # Write a header row
  322:     $self->csv_output_row($filehandle,undef,
  323:                           ('Container','Assessment title'));
  324:     #
  325:     # Write each assessments row
  326:     if (scalar(@Sequences)< 1) {
  327:         &initialize_sequence_cache();
  328:     }
  329:     foreach my $Sequence (@Sequences) {
  330: 	next if ($Sequence->{'num_assess'} < 1);
  331: 	foreach my $resource (@{$Sequence->{'contents'}}) {
  332: 	    my $rownum = $self->get_row_number_from_key($resource->{'symb'});
  333:             my @assessdata = ($Sequence->{'title'},
  334:                               $resource->{'title'});
  335:             $self->csv_output_row($filehandle,$rownum,@assessdata);
  336:         }
  337:     }
  338:     return;
  339: }
  340: 
  341: sub excel_rows {
  342:     # writes the meat of the spreadsheet to an excel worksheet.  Called
  343:     # by Spreadsheet::outsheet_excel;
  344:     my $self = shift;
  345:     my ($worksheet,$cols_output,$rows_output) = @_;
  346:     #
  347:     # Write a header row
  348:     $cols_output = 0;
  349:     foreach my $value ('Container','Assessment title') {
  350:         $worksheet->write($rows_output,$cols_output++,$value);
  351:     }
  352:     $rows_output++;    
  353:     #
  354:     # Write each assessments row
  355:     if (scalar(@Sequences)< 1) {
  356:         &initialize_sequence_cache();
  357:     }
  358:     foreach my $Sequence (@Sequences) {
  359: 	next if ($Sequence->{'num_assess'} < 1);
  360: 	foreach my $resource (@{$Sequence->{'contents'}}) {
  361: 	    my $rownum = $self->get_row_number_from_key($resource->{'symb'});
  362:             my @assessdata = ($Sequence->{'title'},
  363:                               $resource->{'title'});
  364:             $self->excel_output_row($worksheet,$rownum,$rows_output++,
  365:                                     @assessdata);
  366:         }
  367:     }
  368:     return;
  369: }
  370: 
  371: sub outsheet_recursive_excel {
  372:     my $self = shift;
  373:     my ($r) = @_;
  374: } 
  375: 
  376: sub set_row_sources {
  377:     my $self = shift;
  378:     while (my ($cell,$value) = each(%{$self->{'formulas'}})) {
  379:         next if ($cell !~ /^A(\d+)/ && $1 > 0);
  380:         my $row = $1;
  381:         (undef,$value) = split('__&&&__',$value);
  382:         $value = 'Default' if (! defined($value));
  383:         $self->{'row_source'}->{$row} = $value;
  384:     }
  385:     return;
  386: }
  387: 
  388: sub compute {
  389:     my $self = shift;
  390:     $self->logthis('computing');
  391:     if (! defined($current_course) ||
  392:         $current_course ne $ENV{'request.course.id'}) {
  393:         $current_course = $ENV{'request.course.id'};
  394:         &clear_package();
  395:         &initialize_sequence_cache();
  396:     }
  397:     $self->initialize_safe_space();
  398:     my @sequences = @Sequences;
  399:     if (@sequences < 1) {
  400:         my ($top,$sequences,$assessments) = 
  401:             &Apache::loncoursedata::get_sequence_assessment_data();
  402:         if (! defined($top) || ! ref($top)) {
  403:             &Apache::lonnet::logthis('top is undefined');
  404:             return;
  405:         }
  406:         @sequences = @{$sequences} if (ref($sequences) eq 'ARRAY');
  407:     }
  408:     &Apache::assesscalc::initialize_package($self->{'name'},$self->{'domain'});
  409:     my %f = $self->formulas();
  410:     #
  411:     # Process the formulas list - 
  412:     #   the formula for the A column of a row is symb__&&__filename
  413:     my %c = $self->constants();
  414:     foreach my $seq (@sequences) {
  415:         next if ($seq->{'num_assess'}<1);
  416:         foreach my $resource (@{$seq->{'contents'}}) {
  417:             next if ($resource->{'type'} ne 'assessment');
  418:             my $rownum = $self->get_row_number_from_key($resource->{'symb'});
  419:             my $cell = 'A'.$rownum;
  420:             my $assess_filename = 'Default';
  421:             if (exists($self->{'row_source'}->{$rownum})) {
  422:                 $assess_filename = $self->{'row_source'}->{$rownum};
  423:             } else {
  424:                 $self->{'row_source'}->{$rownum} = $assess_filename;
  425:             }
  426:             $f{$cell} = $resource->{'symb'}.'__&&&__'.$assess_filename;
  427:             my $assessSheet = Apache::assesscalc->new($self->{'name'},
  428:                                                       $self->{'domain'},
  429:                                                       $assess_filename,
  430:                                                       $resource->{'symb'});
  431:             my @exportdata = $assessSheet->export_data();
  432:             if ($assessSheet->blackout()) {
  433:                 $self->blackout(1);
  434:                 $self->{'blackout_rows'}->{$rownum} = 1;
  435:             }
  436:             #
  437:             # Be sure not to disturb the formulas in the 'A' column
  438:             my $data = shift(@exportdata);
  439:             $c{$cell} = $data if (defined($data));
  440:             #
  441:             # Deal with the remaining columns
  442:             my $i=0;
  443:             foreach (split(//,'BCDEFGHIJKLMNOPQRSTUVWXYZ')) {
  444:                 my $cell = $_.$rownum;
  445:                 my $data = shift(@exportdata);
  446:                 if (defined($data)) {
  447:                     $f{$cell} = 'import';
  448:                     $c{$cell} = $data;
  449:                 }
  450:                 $i++;
  451:             }
  452:         }
  453:     }
  454:     $self->constants(\%c);
  455:     $self->formulas(\%f);
  456:     $self->calcsheet();
  457:     #
  458:     # Store export row in cache
  459:     my @exportarray=$self->exportrow();
  460:     my $student = $self->{'name'}.':'.$self->{'domain'};
  461:     $Exportrows{$student}->{'time'} = time;
  462:     $Exportrows{$student}->{'data'} = \@exportarray;
  463:     # save export row
  464:     $self->save_export_data();
  465:     return;
  466: }
  467: 
  468: sub set_row_numbers {
  469:     my $self = shift;
  470:     while (my ($cell,$formula) = each(%{$self->{'formulas'}})) {
  471:         next if ($cell !~ /^A(\d+)/);
  472:         my $row = $1;
  473:         next if ($row == 0);
  474:         my ($symb,undef) = split('__&&&__',$formula);
  475:         $self->{'row_numbers'}->{$symb} = $row;
  476:     }
  477: }
  478: 
  479: sub get_row_number_from_symb {
  480:     my $self = shift;
  481:     my ($key) = @_;
  482:     ($key,undef) = split('__&&&__',$key) if ($key =~ /__&&&__/);
  483:     return $self->get_row_number_from_key($key);
  484: }
  485: 
  486: #############################################
  487: #############################################
  488: 
  489: =pod
  490: 
  491: =item &load_cached_export_rows
  492: 
  493: Retrieves and parsers the export rows of the student spreadsheets.
  494: These rows are saved in the courses directory in the format:
  495: 
  496:  sname:sdom:studentcalc:.time => time
  497: 
  498:  sname:sdom:studentcalc => ___=___Adata___;___Bdata___;___Cdata___;___ .....
  499: 
  500: =cut
  501: 
  502: #############################################
  503: #############################################
  504: sub load_cached_export_rows {
  505:     %Exportrows = undef;
  506:     my @tmp = &Apache::lonnet::dump('nohist_calculatedsheets',
  507: 		     $ENV{'course.'.$ENV{'request.course.id'}.'.domain'},
  508: 		     $ENV{'course.'.$ENV{'request.course.id'}.'.num'},undef);
  509:     my %Selected_Assess_Sheet;
  510:     if ($tmp[0] =~ /^error/) {
  511:         &Apache::lonnet::logthis('unable to read cached student export rows '.
  512:                                  'for course '.$ENV{'request.course.id'});
  513:         return;
  514:     }
  515:     my %tmp = @tmp;
  516:     while (my ($key,$sheetdata) = each(%tmp)) {
  517:         my ($sname,$sdom,$sheettype,$remainder) = split(':',$key);
  518:         my $student = $sname.':'.$sdom;
  519:         if ($remainder =~ /\.time/) {
  520:             $Exportrows{$student}->{'time'} = $sheetdata;
  521:         } else {
  522:             $sheetdata =~ s/^___=___//;
  523:             my @Data = split('___;___',$sheetdata);
  524:             $Exportrows{$student}->{'data'} = \@Data;
  525:         }
  526:     }
  527: }
  528: 
  529: #############################################
  530: #############################################
  531: 
  532: =pod
  533: 
  534: =item &save_export_data()
  535: 
  536: Writes the export data for this student to the course cache.
  537: 
  538: =cut
  539: 
  540: #############################################
  541: #############################################
  542: sub save_export_data {
  543:     my $self = shift;
  544:     return if ($self->temporary());
  545:     my $student = $self->{'name'}.':'.$self->{'domain'};
  546:     return if (! exists($Exportrows{$student}));
  547:     return if (! $self->is_default());
  548:     my $key = join(':',($self->{'name'},$self->{'domain'},'studentcalc')).':';
  549:     my $timekey = $key.'.time';
  550:     my $newstore = join('___;___',
  551:                         @{$Exportrows{$student}->{'data'}});
  552:     $newstore = '___=___'.$newstore;
  553:     &Apache::lonnet::put('nohist_calculatedsheets',
  554:                          { $key     => $newstore,
  555:                            $timekey => $Exportrows{$student}->{'time'} },
  556:                          $self->{'cdom'},
  557:                          $self->{'cnum'});
  558:     return;
  559: }
  560: 
  561: #############################################
  562: #############################################
  563: 
  564: =pod
  565: 
  566: =item &export_data()
  567: 
  568: Returns the export data associated with the spreadsheet.  Computes the
  569: spreadsheet only if necessary.
  570: 
  571: =cut
  572: 
  573: #############################################
  574: #############################################
  575: sub export_data {
  576:     my $self = shift;
  577:     my $student = $self->{'name'}.':'.$self->{'domain'};
  578:     if (! exists($Exportrows{$student}) ||
  579:         ! $self->check_expiration_time($Exportrows{$student}->{'time'})) {
  580:         $self->compute();
  581:     }
  582:     my @Data = @{$Exportrows{$student}->{'data'}};
  583:     for (my $i=0; $i<=$#Data;$i++) {
  584:         $Data[$i]="'".$Data[$i]."'" if ($Data[$i]=~/\D/ && defined($Data[$i]));
  585:     }
  586:     return @Data;
  587: }
  588: 
  589: 1;
  590: 
  591: __END__

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