Period handling in the backend

This commit is contained in:
PMKuipers 2023-07-27 16:58:23 +02:00
parent 25f6046099
commit 80d8f5c7a4
6 changed files with 164 additions and 291 deletions

View File

@ -6,6 +6,8 @@ require_once($CFG->libdir.'/externallib.php');
class period {
const TABLE = "local_treestudyplan_period";
private static $CACHE = [];
private static $PAGECACHE = [];
private $r; // Holds database record
private $id;
@ -23,6 +25,74 @@ class period {
return self::$CACHE[$id];
}
/**
* Find a period by page and period number [1..$page->periods()]
*/
public static function find(studyplanpage $page,$periodnr): self{
global $DB;
if($periodnr < 1){
// Clamp period index
$periodnr = 1;
}
try{
$id = $DB->get_field(self::TABLE,"id",["page_id"=>$page->id(), "period" => $periodnr],MUST_EXIST);
$period = self::findById($id);
} catch(\dml_missing_record_exception $x){
// Period does not exist - create one ...
// Make a best guess estimate of the start and end date, based on surrounding periods,
// or specified duration of the page and the sequence of the periods
$pcount = $page->periods();
$ystart = $page->startdate()->getTimestamp();
$yend = $page->enddate()->getTimestamp();
// Estimate the period's timing to make a reasonable first guess
$ydelta = $yend - $ystart;
$ptime = $ydelta / $pcount;
try{
// Check if we have a previous period to glance the end date of as a reference
$startdate = $DB->get_field(self::TABLE,"enddate",["page_id"=>$page->id(), "period" => $periodnr-1],MUST_EXIST);
$pstart = strtotime($startdate)+(24*60*60); // Add one day
} catch(\dml_missing_record_exception $x2){
// If not, do a fair guess
$pstart = $ystart + (($periodnr-1)*$ptime);
}
try{
// Check if we have a next period to glance the start date of as a reference
$enddate = $DB->get_field(self::TABLE,"startdate",["page_id"=>$page->id(), "period" => $periodnr+1],MUST_EXIST);
$pstart = strtotime($enddate)-(24*60*60); // subtract one day
} catch(\dml_missing_record_exception $x2){
// If not, do a fair guess
$pend = $pstart + $ptime;
}
// And create the period
$period = self::add([
'page_id' => $page->id(),
'period' => $periodnr,
'fullname' => \get_string("period_default_fullname","local_treestudyplan",$periodnr),
'shortname' => \get_string("period_default_shortname","local_treestudyplan",$periodnr),
'startdate' => date("Y-m-d",$pstart),
'enddate' => date("Y-m-d",$pend),
]);
}
return $period;
}
// Cache constructors to avoid multiple creation events in one session.
public static function findForPage(studyplanpage $page): array {
if(!array_key_exists($page->id(),self::$PAGECACHE)){
$periods = [];
// find and add the periods to an array with the period sequence as a key
for($i=1; $i <= $page->periods(); $i++){
$period = self::find($page,$i);
$periods[$i] = $period;
}
self::$PAGECACHE[$page->id()] = $periods;
}
return self::$PAGECACHE[$page->id()];
}
private function __construct($id) {
global $DB;
$this->id = $id;
@ -68,18 +138,18 @@ class period {
}
}
public static function simple_structure($value=VALUE_REQUIRED){
public static function structure($value=VALUE_REQUIRED){
return new \external_single_structure([
"id" => new \external_value(PARAM_INT, 'id of studyplan page'),
"fullname" => new \external_value(PARAM_TEXT, 'name of studyplan page'),
"shortname"=> new \external_value(PARAM_TEXT, 'shortname of studyplan page'),
"id" => new \external_value(PARAM_INT, 'id of period'),
"fullname" => new \external_value(PARAM_TEXT, 'Full name of period'),
"shortname"=> new \external_value(PARAM_TEXT, 'Short name of period'),
"period" => new \external_value(PARAM_INT, 'period sequence'),
"startdate" => new \external_value(PARAM_TEXT, 'start date of studyplan'),
"enddate" => new \external_value(PARAM_TEXT, 'end date of studyplan'),
],'Studyplan page basic info',$value);
"startdate" => new \external_value(PARAM_TEXT, 'start date of period'),
"enddate" => new \external_value(PARAM_TEXT, 'end date of period'),
],'Period info',$value);
}
public function simple_model(){
public function model(){
return [
'id' => $this->r->id,
'fullname' => $this->r->fullname,
@ -90,27 +160,39 @@ class period {
];
}
/**
* Do not use directly to add periods, unless performing import
* The static find() and findForPage() functions create the period if needed
*/
public static function add($fields){
global $CFG, $DB;
global $DB;
if(!isset($fields['page_id'])){
throw new \InvalidArgumentException("parameter 'studyplan_id' missing");
throw new \InvalidArgumentException("parameter 'page_id' missing");
}
if(!isset($fields['period'])){
throw new \InvalidArgumentException("parameter 'period' missing");
}
$addable = ['page_id','fullname','shortname','description','periods','startdate','enddate'];
$info = ['enddate' => null ];
if($DB->record_exists(self::TABLE,["page_id"=>$fields["page_id"], "period"=>$fields["period"]])){
throw new \InvalidArgumentException("record already exists for specified page and period");
}
$addable = ['page_id','fullname','shortname','period','startdate','enddate'];
$info = [ ];
foreach($addable as $f){
if(array_key_exists($f,$fields)){
$info[$f] = $fields[$f];
}
}
$id = $DB->insert_record(self::TABLE, $info);
unset(self::$PAGECACHE[$fields['page_id']]); // invalidate the cache for this page
return self::findById($id); // make sure the new page is immediately cached
}
public function edit($fields){
global $DB;
$editable = ['fullname','shortname','description','periods','startdate','enddate'];
$editable = ['fullname','shortname','startdate','enddate'];
$info = ['id' => $this->id,];
foreach($editable as $f){
if(array_key_exists($f,$fields)){
@ -120,288 +202,27 @@ class period {
$DB->update_record(self::TABLE, $info);
//reload record after edit
$this->r = $DB->get_record(self::TABLE,['id' => $this->id],"*",MUST_EXIST);
unset(self::$PAGECACHE[$this->r->page_id]); // invalidate the cache for this page
return $this;
}
public function delete($force=false){
public function delete(){
global $DB;
$DB->delete_records(self::TABLE, ['id' => $this->id]);
unset(self::$PAGECACHE[$this->r->page_id]); // invalidate the cache for this page
return success::success();
}
public static function page_structure($value=VALUE_REQUIRED){
return new \external_multiple_structure(self::structure(),"The periods in the page",$value);
}
public static function user_structure($value=VALUE_REQUIRED){
return new \external_single_structure([
"id" => new \external_value(PARAM_INT, 'id of studyplan page'),
"fullname" => new \external_value(PARAM_TEXT, 'name of studyplan page'),
"shortname"=> new \external_value(PARAM_TEXT, 'shortname of studyplan page'),
"description"=> new \external_value(PARAM_TEXT, 'description of studyplan page'),
"periods" => new \external_value(PARAM_INT, 'number of slots in studyplan page'),
"startdate" => new \external_value(PARAM_TEXT, 'start date of studyplan page'),
"enddate" => new \external_value(PARAM_TEXT, 'end date of studyplan page'),
"studylines" => new \external_multiple_structure(studyline::user_structure()),
],'Studyplan page with user info',$value);
}
public function user_model($userid){
$model = [
'id' => $this->r->id,
'fullname' => $this->r->fullname,
'shortname' => $this->r->shortname,
'description' => $this->r->description,
'periods' => $this->r->periods,
'startdate' => $this->r->startdate,
'enddate' => $this->r->enddate,
'studylines' => [],
];
$children = studyline::find_page_children($this);
foreach($children as $c)
{
$model['studylines'][] = $c->user_model($userid);
public static function page_model(studyplanpage $page){
$model = [];
foreach(self::findForPage($page) as $p){
$model[] = $p->model();
}
return $model;
}
public static function find_studyplan_children(studyplan $plan)
{
global $DB;
$list = [];
$ids = $DB->get_fieldset_select(self::TABLE,"id","studyplan_id = :plan_id ORDER BY startdate",
['plan_id' => $plan->id()]);
foreach($ids as $id) {
$list[] = self::findById($id);
}
return $list;
}
public static function duplicate_page($page_id,$name,$shortname)
{
$ori = self::findById($page_id);
$new = $ori->duplicate($name,$shortname);
return $new->simple_model();
}
public function duplicate($name,$shortname)
{
// First duplicate the studyplan structure
$new = studyplanpage::add([
'fullname' => $name,
'shortname' => $shortname,
'description' => $this->r->description,
'pages' => $this->r->pages,
'startdate' => $this->r->startdate,
'enddate' => empty($this->r->enddate)?null:$this->r->enddate,
]);
// next, copy the studylines
$children = studyline::find_page_children($this);
$itemtranslation = [];
$linetranslation = [];
foreach($children as $c){
$newchild = $c->duplicate($this,$itemtranslation);
$linetranslation[$c->id()] = $newchild->id();
}
// now the itemtranslation array contains all of the old child id's as keys and all of the related new ids as values
// (feature of the studyline::duplicate function)
// use this to recreate the lines in the new plan
foreach(array_keys($itemtranslation) as $item_id){
// copy based on the outgoing connections of each item, to avoid duplicates
$connections = studyitemconnection::find_outgoing($item_id);
foreach($connections as $conn){
studyitemconnection::connect($itemtranslation[$conn->from_id],$itemtranslation[$conn->to_id]);
}
}
return $new;
}
public static function export_structure()
{
return new \external_single_structure([
"format" => new \external_value(PARAM_TEXT, 'format of studyplan export'),
"content"=> new \external_value(PARAM_TEXT, 'exported studyplan content'),
],'Exported studyplan');
}
public function export_page()
{
$model = $this->export_model();
$json = json_encode([
"type"=>"studyplanpage",
"version"=>2.0,
"page"=>$model
],\JSON_PRETTY_PRINT);
return [ "format" => "application/json", "content" => $json];
}
public function export_page_csv()
{
//TODO: Period shortnames instead of just P1, P2, P3 etc
$model = $this->editor_model();
$slots = intval($model["slots"]);
// First line
$csv = "\"Studyline[{$slots}]\"";
for($i = 1; $i <= $slots; $i++){
$csv .= ",\"P{$i}\"";
}
$csv .= "\r\n";
// next, make one line per studyline
foreach($model["studylines"] as $line){
// determine how many fields are simultaneous in the line at maximum
$maxlines = 1;
for($i = 1; $i <= $slots; $i++){
if(count($line["slots"]) > $i){
$ct = 0;
foreach($line["slots"][$i][studyline::SLOTSET_COMPETENCY] as $itm){
if($itm["type"] == "course"){
$ct += 1;
}
}
if($ct > $maxlines){
$maxlines = $ct;
}
}
}
for($lct = 0; $lct < $maxlines; $lct++){
$csv .= "\"{$line["name"]}\"";
for($i = 1; $i <= $slots; $i++){
$filled = false;
if(count($line["slots"]) > $i){
$ct = 0;
foreach($line["slots"][$i][studyline::SLOTSET_COMPETENCY] as $itm){
if($itm["type"] == "course"){
if($ct == $lct){
$csv .= ",\"";
$csv .= $itm["course"]["fullname"];
$csv .= "\r\n";
$first = true;
foreach($itm["course"]["grades"] as $g){
if($g["selected"]){
if($first){
$first = false;
}
else{
$csv .= "\r\n";
}
$csv .= "- ".str_replace('"', '\'', $g["name"]);
}
}
$csv .= "\"";
$filled = true;
break;
}
$ct++;
}
}
}
if(!$filled) {
$csv .= ",\"\"";
}
}
$csv .= "\r\n";
}
}
return [ "format" => "text/csv", "content" => $csv];
}
public function export_studylines(){
$model = $this->export_studylines_model();
$json = json_encode([
"type"=>"studylines",
"version"=>1.0,
"studylines"=>$model,
],\JSON_PRETTY_PRINT);
return [ "format" => "application/json", "content" => $json];
}
public function export_model()
{
$model = [
'fullname' => $this->r->name,
'shortname' => $this->r->shortname,
'description' => $this->r->description,
'periods' => $this->r->periods,
'startdate' => $this->r->startdate,
'enddate' => $this->r->enddate,
'studylines' => $this->export_studylines_model(),
];
return $model;
}
public function export_studylines_model()
{
$children = studyline::find_page_children($this);
$lines = [];
foreach($children as $c)
{
$lines[] = $c->export_model();
}
return $lines;
}
public function import_studylines($content,$format="application/json")
{
if($format != "application/json") { return false;}
$content = json_decode($content,true);
if($content["type"] == "studylines" && $content["version"] >= 2.0){
return $this->import_studylines_model($content["studylines"]);
}
else if($content["type"] == "studyplanpage" && $content["version"] >= 2.0){
return $this->import_studylines_model($content["page"]["studylines"]);
}
else {
return false;
}
}
protected function find_studyline_by_shortname($shortname){
$children = studyline::find_page_children($this);
foreach($children as $l){
if($shortname == $l->shortname()){
return $l;
}
}
return null;
}
public function import_studylines_model($model)
{
// First attempt to map each studyline model to an existing or new line
$line_map = [];
foreach($model as $ix => $linemodel){
$line = $this->find_studyline_by_shortname($linemodel["shortname"]);
if(empty($line)){
$linemodel["studyplan_id"] = $this->id;
$line = studyline::add($linemodel);
} else {
//$line->edit($linemodel); // Update the line with the settings from the imported file
}
$line_map[$ix] = $line;
}
// next, let each study line import the study items
$itemtranslation = [];
$connections = [];
foreach($model as $ix => $linemodel){
$line_map[$ix]->import_studyitems($linemodel["slots"],$itemtranslation,$connections);
}
// Finally, create the links between the study items
foreach($connections as $from => $dests){
foreach($dests as $to){
studyitemconnection::connect($from,$itemtranslation[$to]);
}
}
return true;
}
}

View File

@ -586,6 +586,7 @@ class studyplan {
$p["studyplan_id"] = $this->id();
$page = studyplanpage::add($p);
$this->page_cache[] = $page;
$page->import_periods_model($p["perioddesc"]);
$page->import_studylines_model($p["studylines"]);
}
return true;

View File

@ -77,6 +77,7 @@ class studyplanpage {
"description"=> new \external_value(PARAM_TEXT, 'description of studyplan page'),
"startdate" => new \external_value(PARAM_TEXT, 'start date of studyplan'),
"enddate" => new \external_value(PARAM_TEXT, 'end date of studyplan'),
"perioddesc" => period::page_structure(),
],'Studyplan page basic info',$value);
}
@ -89,6 +90,7 @@ class studyplanpage {
'description' => $this->r->description,
'startdate' => $this->r->startdate,
'enddate' => $this->r->enddate,
"perioddesc" => period::page_model($this),
];
}
@ -102,6 +104,7 @@ class studyplanpage {
"startdate" => new \external_value(PARAM_TEXT, 'start date of studyplan page'),
"enddate" => new \external_value(PARAM_TEXT, 'end date of studyplan page'),
"studylines" => new \external_multiple_structure(studyline::editor_structure()),
"perioddesc" => period::page_structure(),
],'Studyplan page full structure',$value);
}
@ -117,6 +120,7 @@ class studyplanpage {
'startdate' => $this->r->startdate,
'enddate' => $this->r->enddate,
'studylines' => [],
"perioddesc" => period::page_model($this),
];
$children = studyline::find_page_children($this);
@ -191,6 +195,7 @@ class studyplanpage {
"startdate" => new \external_value(PARAM_TEXT, 'start date of studyplan page'),
"enddate" => new \external_value(PARAM_TEXT, 'end date of studyplan page'),
"studylines" => new \external_multiple_structure(studyline::user_structure()),
"perioddesc" => period::page_structure(),
],'Studyplan page with user info',$value);
}
@ -205,6 +210,7 @@ class studyplanpage {
'startdate' => $this->r->startdate,
'enddate' => $this->r->enddate,
'studylines' => [],
"perioddesc" => period::page_model($this),
];
$children = studyline::find_page_children($this);
@ -290,7 +296,7 @@ class studyplanpage {
public function export_page_csv()
{
//TODO: Period shortnames instead of just P1, P2, P3 etc
$plist = period::findForPage($this);
$model = $this->editor_model();
@ -298,7 +304,8 @@ class studyplanpage {
// First line
$csv = "\"Studyline[{$slots}]\"";
for($i = 1; $i <= $slots; $i++){
$csv .= ",\"P{$i}\"";
$name = $plist[$i]->shortname();
$csv .= ",\"{$name}\"";
}
$csv .= "\r\n";
// next, make one line per studyline
@ -367,12 +374,23 @@ class studyplanpage {
$model = $this->export_studylines_model();
$json = json_encode([
"type"=>"studylines",
"version"=>1.0,
"version"=>2.0,
"studylines"=>$model,
],\JSON_PRETTY_PRINT);
return [ "format" => "application/json", "content" => $json];
}
public function export_periods(){
$model = period::page_model($this);
$json = json_encode([
"type"=>"periods",
"version"=>2.0,
"perioddesc"=>$model,
],\JSON_PRETTY_PRINT);
return [ "format" => "application/json", "content" => $json];
}
public function export_model()
{
$model = [
@ -383,6 +401,7 @@ class studyplanpage {
'startdate' => $this->r->startdate,
'enddate' => $this->r->enddate,
'studylines' => $this->export_studylines_model(),
'perioddesc' => period::page_model($this),
];
return $model;
}
@ -398,6 +417,22 @@ class studyplanpage {
return $lines;
}
public function import_periods($content,$format="application/json")
{
if($format != "application/json") { return false;}
$content = json_decode($content,true);
if($content["type"] == "periods" && $content["version"] >= 2.0){
return $this->import_periods_model($content["perioddesc"]);
}
else if($content["type"] == "studyplanpage" && $content["version"] >= 2.0){
return $this->import_periods_model($content["page"]["perioddesc"]);
}
else {
return false;
}
}
public function import_studylines($content,$format="application/json")
{
if($format != "application/json") { return false;}
@ -423,6 +458,16 @@ class studyplanpage {
return null;
}
public function import_periods_model($model){
$periods = period::findForPage($this);
foreach($model as $pmodel){
$pi = $pmodel["period"];
if(array_key_exists($pi,$periods)){
$periods[$pi]->edit($pmodel);
}
}
}
public function import_studylines_model($model)
{
// First attempt to map each studyline model to an existing or new line

View File

@ -288,3 +288,6 @@ $string["dateissued"] = "Issued on";
$string["dateexpire"] = "Expires on";
$string["badgeinfo"] = "Badge details";
$string["badgeissuedstats"] = "Issuing progress";
$string["period_default_fullname"] = 'Period {$a}';
$string["period_default_shortname"] = 'P{$a}';

View File

@ -291,3 +291,6 @@ $string["dateissued"] = "Afgegeven op";
$string["dateexpire"] = "Veloopt op";
$string["badgeinfo"] = "Meer details";
$string["badgeissuedstats"] = "Voortgang van uitgifte";
$string["period_default_fullname"] = 'Periode {$a}';
$string["period_default_shortname"] = 'P{$a}';

View File

@ -1,6 +1,6 @@
<?php
$plugin->component = 'local_treestudyplan'; // Recommended since 2.0.2 (MDL-26035). Required since 3.0 (MDL-48494)
$plugin->version = 2023072300; // YYYYMMDDHH (year, month, day, iteration)
$plugin->version = 2023072700; // YYYYMMDDHH (year, month, day, iteration)
$plugin->requires = 2021051700; // YYYYMMDDHH (This is the release version for Moodle 3.11)
$plugin->dependencies = [