Files
RecoReco/Model/RecoRecoModel.php

223 lines
8.6 KiB
PHP

<?php
namespace Kanboard\Plugin\RecoReco\Model;
use Kanboard\Core\Base;
use Kanboard\Model\TaskModel;
/**
* The RecoReco engine: find enabled templates and spawn their due occurrences.
*
* Called by the recoreco:run CLI command. v0.3 handles monthly-by-day and fires everything whose
* fire time has arrived (fire time = occurrence - days_before); v1.0 adds the 4-window cron horizon.
*
* Per template: the native-recurrence yield (decision 13), first-run init / manual-edit re-anchor,
* then a catch-up loop that duplicates the card into the target column and advances the cursor.
*/
class RecoRecoModel extends Base
{
const CATCHUP_CAP = 24;
private $calc;
public function run($now = null)
{
$now = $now ?: time();
$horizon = $this->horizon($now);
$spawned = 0;
$task_ids = $this->db->table('task_has_metadata')
->eq('name', 'recoreco_enabled')
->eq('value', '1')
->findAllByColumn('task_id');
foreach ($task_ids as $task_id) {
$spawned += $this->processTemplate((int) $task_id, $now, $horizon);
}
return $spawned;
}
/**
* The look-ahead horizon for this run: fire everything whose fire time is before it. Computed as
* "ceil now to the next 6h boundary, then +12h", which lands on the four daily runs:
* 05:58 -> 18:00, 11:58 -> 00:00, 17:58 -> 06:00, 23:58 -> 12:00. Gives a 12h look-ahead with a
* 6h overlap between runs, so a missed run is covered by its neighbour. Past-due occurrences are
* naturally included (their fire time is < now < horizon) -- that is the catch-up.
*
* @param int $now
* @return int
*/
private function horizon($now)
{
$startOfDay = mktime(0, 0, 0, (int) date('n', $now), (int) date('j', $now), (int) date('Y', $now));
$boundaryHour = (intdiv((int) date('G', $now), 6) + 1) * 6;
return $startOfDay + $boundaryHour * 3600 + 12 * 3600;
}
public function processTemplate($task_id, $now, $horizon)
{
$task = $this->taskFinderModel->getById($task_id);
if (empty($task)) {
return 0;
}
// Native wins: if the card became native-recurring, RecoReco yields (decision 13).
if ($task['recurrence_status'] != TaskModel::RECURRING_STATUS_NONE) {
$this->taskMetadataModel->save($task_id, array('recoreco_enabled' => 0));
$this->logger->info('RecoReco: disabled on task '.$task_id.' (now native-recurring)');
return 0;
}
$meta = $this->taskMetadataModel->getAll($task_id);
$frequency = isset($meta['recoreco_frequency']) ? $meta['recoreco_frequency'] : '';
// All five frequencies are supported since v1.1; skip anything unknown.
if (! in_array($frequency, array('daily', 'weekly', 'monthly_day', 'monthly_dow', 'yearly'), true)) {
return 0;
}
$anchor = isset($meta['recoreco_anchor']) ? (int) $meta['recoreco_anchor'] : 0;
if ($anchor <= 0) {
return 0;
}
$lastDay = isset($meta['recoreco_last_day']) && $meta['recoreco_last_day'] == 1;
$daysBefore = isset($meta['recoreco_days_before']) ? (int) $meta['recoreco_days_before'] : 0;
$targetColumn = isset($meta['recoreco_target_column']) ? (int) $meta['recoreco_target_column'] : (int) $task['column_id'];
// Default off: only keep the duplicate link when explicitly turned on.
$linkCopies = isset($meta['recoreco_link_copies']) && $meta['recoreco_link_copies'] == 1;
$cursor = (int) $task['date_due'];
$synced = isset($meta['recoreco_synced_due']) ? (int) $meta['recoreco_synced_due'] : null;
if ($synced === null) {
// First run after enabling: place the cursor on the first occurrence.
$cursor = $this->firstCursor($anchor, $frequency, $lastDay, $now);
$this->setDue($task_id, $cursor);
} elseif ($cursor !== $synced) {
// The user hand-edited the due date -> re-anchor to it (a reschedule).
$anchor = $cursor;
$this->taskMetadataModel->save($task_id, array('recoreco_anchor' => $anchor));
$this->setDue($task_id, $cursor);
}
// Fire every occurrence whose fire time is before this run's horizon (this includes
// past-due ones -> catch-up), advancing the cursor each time.
$spawned = 0;
$fireTime = $cursor - $daysBefore * 86400;
while ($fireTime < $horizon && $spawned < self::CATCHUP_CAP) {
$this->spawn($task, $targetColumn);
$next = $this->calculator()->occurrenceFrom($anchor, $frequency, $lastDay, $cursor, false);
if ($next === null || $next <= $cursor) {
break;
}
$cursor = $next;
$this->setDue($task_id, $cursor);
$fireTime = $cursor - $daysBefore * 86400;
$spawned++;
}
// Reconcile the duplicate links with the setting (removes both new and old ones when off).
$this->syncCloneLinks($task_id, $linkCopies);
return $spawned;
}
/**
* Reconcile a template's "is a duplicate of" links with the link-copies setting. When off, remove
* the links to THIS template's own RecoReco clones (identified by recoreco_source, so manual
* links are left untouched). When on, do nothing -- new spawns already carry the link.
*
* @param int $template_id
* @param bool $linkCopies
*/
public function syncCloneLinks($template_id, $linkCopies)
{
if ($linkCopies) {
return;
}
foreach ($this->taskLinkModel->getAll($template_id) as $link) {
$opposite = (int) $link['task_id'];
if ((int) $this->taskMetadataModel->get($opposite, 'recoreco_source', 0) === (int) $template_id) {
$this->taskLinkModel->remove($link['id']);
}
}
}
/**
* The first occurrence: respect an explicitly future anchor (the due date the user set) as the
* first one; otherwise jump to the next occurrence on/after now.
*/
private function firstCursor($anchor, $frequency, $lastDay, $now)
{
if ($anchor >= $now) {
return $anchor;
}
return $this->calculator()->occurrenceFrom($anchor, $frequency, $lastDay, $now, true);
}
private function setDue($task_id, $cursor)
{
// Advance the template's due date directly (no task events) + mirror it for edit detection.
$this->db->table(TaskModel::TABLE)->eq('id', $task_id)->update(array('date_due' => $cursor));
$this->taskMetadataModel->save($task_id, array('recoreco_synced_due' => $cursor));
}
private function spawn(array $template, $targetColumn)
{
// The template's date_due is already the occurrence (setDue), so duplicate() copies it onto
// the clone. duplicate() copies fields + tags + links + subtasks, but NO metadata, so the
// clone is not a template.
$newId = $this->taskDuplicationModel->duplicate($template['id']);
if ($newId === false) {
$this->logger->error('RecoReco: duplicate failed for task '.$template['id']);
return false;
}
// duplicate() lands the clone in the source column; move it to the chosen target (top).
if ($targetColumn > 0 && $targetColumn != $template['column_id']) {
$this->taskPositionModel->movePosition($template['project_id'], $newId, $targetColumn, 1, $template['swimlane_id']);
}
// Reset the "[DUPLICATE]" prefix back to the source title (no events).
$this->taskModificationModel->update(array('id' => $newId, 'title' => $template['title']), false);
// Kanboard's duplicate() adds an "is a duplicate of" task link between the template and the
// clone. It is reconciled with the recoreco_link_copies setting by syncCloneLinks() after
// the spawn loop (kept when on, removed when off).
// Mark the clone: white icon + cannot itself be made recurring; record its source template.
$this->taskMetadataModel->save($newId, array(
'recoreco_clone' => 1,
'recoreco_source' => $template['id'],
));
// Signal FinanceBuddy (advance the installment). Harmless no-op if nothing listens.
$payload = array('source_task_id' => (int) $template['id'], 'new_task_id' => (int) $newId);
$this->hook->reference('recoreco:task:spawned', $payload);
return $newId;
}
private function calculator()
{
if ($this->calc === null) {
$this->calc = new OccurrenceCalculator();
}
return $this->calc;
}
}