3 * Table Definition for mtrack_change
5 class_exists('DB_DataObject') ? '' : require_once 'DB/DataObject.php';
7 class Pman_MTrack_DataObjects_Mtrack_change extends DB_DataObject
10 /* the code below is auto generated do not remove the above tag */
12 public $__table = 'mtrack_change'; // table name
13 public $id; // int(11) not_null primary_key auto_increment
14 public $person_id; // int(11)
15 public $ontable; // string(128)
16 public $onid; // int(11) not_null
17 public $changedate; // datetime(19) not_null binary
18 public $reason; // blob(65535) blob
21 /* the code above is auto generated do not remove the tag below */
25 function objectCached()
28 if (empty($this->ontable) || empty($this->onid)) {
32 if (isset($cache[$this->ontable.':'. $this->onid])) {
33 $cache[$this->ontable.':'. $this->onid];
35 $o = DB_DataObject::factory($this->ontable);
37 $cache[$this->ontable.':'. $this->onid] = $o;
43 //checkPerm('S'/'E'/'A', $authuser) - can
44 function checkPerm($perm, $au)
47 if ($au && $au->company()->comptype == 'OWNER') {
48 // owner can do anything..????
52 if ($perm == 'E' || $perm == 'D' ) { // Edit and delete ..not allowed..
56 if (!$au && $perm != 'S') {
57 // non-authenticated users can only list stuff..
62 //DB_DataObject::debugLevel(1);
63 $obj = $this->objectCached();
67 if (!method_exists($obj, 'checkPerm')) {
72 return $obj->checkPerm($perm, $au);
79 function applyFilters($q, $au, $roo)
83 if (!empty($q['timeline'])) {
84 return $this->applyFilterTimeline($q,$au, $roo);
87 if (!empty($q['_is_update_request'])) {
94 $obj = $this->objectCached();
97 // global searching on non-object...
98 // needed for timelime, but not ready yet...
101 $this->whereAdd('1=0');
105 if (!method_exists($obj, 'checkPerm')) {
106 $this->whereAdd('1=0');
110 if (!$au || (!$obj->checkPerm('S', $au) || !$obj->checkPerm('E', $au)) ) {
111 $this->whereAdd('1=0');
119 // this is the query for timelines..
120 function applyFilterTimeline($q, $au, $roo)
124 $start = empty($q['on_date']) ? date('Y-m-d') :
125 date('Y-m-d', strtotime($q['on_date']));
128 //DB_DataObject::debugLevel(1);
131 $pd = DB_DataObject::factory('ProjectDirectory');
132 $pd->whereAdd("role != ''");
133 $pids = $pd->projects($au);
135 $roo->jerr("User is not a member of any projects");
138 if (!empty($q['project_id'])) {
139 if (!in_array($q['project_id'], $pids)) {
140 $roo->jerr("Selected project not in your permitted project list.");
142 $pids = array($q['project_id']);
145 $pids = implode(',', $pids);
149 ( ontable='mtrack_ticket' AND
150 onid IN (SELECT id FROM mtrack_ticket where project_id IN ( $pids ))
153 ( ontable='mtrack_repos' AND
154 onid IN (SELECT id FROM mtrack_repos where project_id IN ( $pids ))
157 $this->orderBy('changedate DESC');
159 if (!empty($q['viewtype']) && $q['viewtype'] == 'summary') {
160 //DB_DataObject::debugLevel(1);
163 changedate >= '$start 00:00:00'
165 changedate < '$start 00:00:00' + INTERVAL 1 DAY
170 //$this->joinAdd(DB_DataObject::factory('Person'), 'LEFT');
172 DATE_FORMAT(changedate, '%Y-%m-%d') as changeday,
173 join_person_id_id.id as person_id,
174 join_person_id_id.name as person_name,
175 Projects.id as project_id,
176 mtrack_repos.shortname as repo_name,
177 mtrack_repos.id as repo_id,
179 Projects.code as project_code,
181 COUNT(mtrack_change.id) as nchanges
184 LEFT JOIN Projects ON
185 Projects.id = IF (ontable='mtrack_repos',
186 (SELECT project_id FROM mtrack_repos where onid = mtrack_repos.id ),
187 (SELECT project_id FROM mtrack_ticket where onid = mtrack_ticket.id )
189 LEFT JOIN mtrack_repos ON
190 mtrack_repos.id = IF (ontable='mtrack_repos', onid, 0)
195 $this->groupBy("changeday,
196 join_person_id_id.id,
197 join_person_id_id.name,
200 mtrack_repos.shortname,
202 $this->orderBy('project_code asc, repo_name ASC, person_name asc');
204 $roo->jdata($this->fetchAll(false,false,'toArray'));
208 $this->whereAdd("changedate >= '$start_day 00:00:00' AND
209 changedate < '$start_day 00:00:00' + INTERVAL 1 DAY");
211 //DB_DataObject::debugLevel(1);
217 // do not accept use input for this..
218 function autoJoinObject($tbl)
222 $d = DB_DataObject::Factory($tbl);
223 $ji = $d->autoJoin();
224 //echo '<PRE>';print_R($ji);
226 foreach($ji['join_names'] as $cname=>$fname) {
227 $this->selectAdd($fname . ' as ontable_id_' . $cname );
230 //$this->selectAdd($d->_query['data_select']); -- this will cause the same dataIndex...
232 LEFT JOIN {$d->tableName()} ON {$this->tableName()}.onid = {$d->tableName()}.id
235 $this->selectAs($d, 'ontable_%s');
246 static $cache = array();
247 if (isset($cache[$this->person_id])) {
248 return $cache[$this->person_id];
250 $p = DB_DataObject::factory('core_person');
251 $p->get($this->person_id);
252 $cache[$this->person_id] = $p;
257 function getCommit($repo, $hash, $runhistory=true)
259 $this->object = $repo->toIdString(); // should be repo:1
261 if ($this->find(true)) {
266 throw new Exception("Can not find revision");
268 $this->refreshHistory($repo);
269 if ( $this->find(true)) {
272 }; /// yes I know we say you should not run this twice...
278 *@param {TrackCommitHookChangeEvent} ce the change event..
280 function createFromCommit($ce, $checker, $ticket = false)
282 $rev_ar = explode(',', $ce->rev);
283 $rev = substr(array_pop($rev_ar), 0, -1);
286 $tc->ontable = 'mtrack_repos';
287 $tc->onid = $checker->repo->id;
289 $tc->cgtype = 'COMMIT';
290 $tc->branch = $ce->branch;
291 if ($tc->count()) { // if we have already tracked this..
303 $tc->ontable = $ticket->tableName();
304 $tc->onid = $ticket->id;
305 $tc->changedate = date('Y-m-d H:i:s', $ce->ctime);
306 $tc->reason = $ce->changelog;
307 $tc->person_id = $ce->changeby_id;
309 $tcid = $tc->insert();
314 $this->ontable = 'mtrack_repos';
315 $this->onid = $checker->repo->id;
316 $this->changedate = date('Y-m-d H:i:s', $ce->ctime);
317 $this->reason = $ce->changelog;
318 $this->person_id = $ce->changeby_id;
319 $this->branch = $ce->branch;
323 // add all the chanedge files..
324 foreach($ce->fileActions as $f => $cg) {
326 $au = DB_DataObject::factory('mtrack_change_audit');
327 $au->change_id = $this->id;
328 $au->ticket_change_id = $tcid;
329 $au->fieldname = $rev;
330 $au->action = 'commit-'.$cg;
335 $this->onInsert(array(), HTML_FlexyFramework::get()->page);
337 // finnaly trigger watchers
339 if (!$ticket && preg_match('/_T([0-9]+)_/', $ce->branch, $matches)) {
340 $ticket = DB_DataObject::factory('mtrack_ticket');
341 if (!$ticket->get($matches[1])) {
346 $ts = DB_DataObject::Factory('cash_invoice_entry');
347 $ts->updateFromCommit($ce, $ticket);
355 // audit should contain files changed..
358 function onInsert($request,$roo)
361 // for a commit ? - ontable = repos, onid = the repo id...
362 // for a change... ontable - will be the ticked, and onid will be the ticket id..
364 $obj = $this->objectCached();
366 if ($obj->tableName() == 'mtrack_ticket') {
367 $obj = $obj->project();
370 $target = empty($this->branch) ? $obj : $obj->branchObject($this->branch);
374 $core_watch = DB_DataObject::Factory('core_watch');
378 "medium='ENDOFDAYMAIL'",
380 date('Y-m-d 23:59:59'),
381 $target->tableName(),
389 * scans repo history and imports it... ??? does not know about branches yet...
391 function refreshHistory($repo)
393 $c = DB_DataObject::factory('mtrack_changes');
394 $c->object = $repo->toIdString();
395 $c->orderBy('changedate DESC');
396 $c->whereAdd("rev != ''");
398 if ($c->find(true)) {
401 // history returns an array of scmEvents... - should actually return an array of this object...
402 $recs = $repo->history('', null, $last ? 'rev' : null, $last ? $last :null);
404 foreach($recs as $r) {
405 // see if we have a copy of it already.
406 $c = DB_DataObject::factory('mtrack_change');
407 $c->object = $repo->toIdString();
408 $c->changedate != $r->ctime;
410 $c->whereAdd("rev != ''");
411 if (!$c->find(true)) {
412 // not found, create a new one..
417 $cr->reason = $r->changelog;
418 $cr->who = $r->changeby;
420 foreach($cr->files as $f) {
421 // we could do with adding 'X' lines changed on this
422 $ca = DB_DataObject::factory('change_audit');
424 $ca->fieldname = $cr->object. ':file';
425 $ca->action = $f->status . ($f->added ? ' +' . $f->added : '') . ($f->removed ? ' -' . $f->removed : '') ;
426 $ca->value = $f->name;
437 function beginChange($object, $reason = '', $when = null)
439 // $db->beginTransaction();
440 //$this->query('BEGIN');
441 $pg = HTML_FlexyFramework::get()->page;
444 $this->person_id = $au->id;
445 $this->ontable = $object->tableName(); // string(128)
446 $this->onid = $object->id; // should use keys( really..)
447 $this->reason = $reason;
448 //$d = date_create("@" . (empty($when) ? time() : $when), new DateTimeZone('UTC'));
449 $this->changedate = date('Y-m-d H:i:s'); // everythign at server time..
450 //$d->format('Y-m-d\TH:i:s.u\Z');
451 $this->cgtype = $reason == 'Changed' ? 'CHANGE' : 'COMMENT';
453 $this->onInsert(array(), $pg);
459 if ($this->count == 0) {
460 // throw new Exception("no changes were made as part of this changeset");
462 if (self::$use_txn) {
463 //$this->query('COMMIT');
468 function addentry($fieldname, $action, $old, $value = null)
471 // final sanity check..
472 $o = DB_DataObject::factory($this->ontable);
473 $info = $o->tableColumns();
474 $far = explode(':',$fieldname);
475 $col = array_pop($far);
476 if (!isset($info[$col])) {
481 if ($info[$col] & (defined('DB_DATAOBJECT_INT') ? DB_DATAOBJECT_INT : PDO_DataObject::INT)) {
482 if (((int) $old) == ((int) $value)) {
489 $ca = DB_DataObject::factory('mtrack_change_audit');
491 'change_id' => $this->id,
492 'fieldname' => $fieldname,
505 * add('xxx:yyy:zzz' , new , old)
506 * add('xxx:yyy', new_do, old_do) // two dataobjects.. (will diff the two..
507 * add($new_do, $old_do)
511 function add($fieldname, $new, $old = false)
513 //print_r(array("ADD", $fieldname, $new, $old));
514 //echo "check: $fieldname ($old) => ($new)\n";
516 if (is_object($fieldname)) {
517 return $this->add($this->ontable.':'. $this->onid , $fieldname, $new );
519 if (is_object($new)) {
520 // should check keys() - so it does not log primary key addition.
522 $cols = array_keys($new->tableColumns());
523 $keys = $new->keys();
524 $links = $new->links();
526 foreach($cols as $k) {
527 if (in_array($k, $keys)) {
530 $alinks = isset($links[$k]) ? explode(':', $links[$k]) : false;
531 if ($alinks && $this->tablename() == array_shift($alinks)) {
534 if (!$old && !isset($new->{$k})) {
538 $ret += $this->add($fieldname .':'. $k, $new->{$k}, !$old ? '' : $old->{$k});
547 if ($old !== false) {
548 return $this->addentry($fieldname, 'set', $old, $new);
551 if ($new === false) {
552 return $this->addentry($fieldname, 'deleted', $old, $new);
555 return $this->addentry($fieldname, 'changed', $old, $new);
564 function cachedAudit()
566 static $cache = array();
568 if (!isset($cache[$this->id])) {
569 $cache[$this->id]= $this->audit();
571 return $cache[$this->id];
573 function cachedAuditToJSONArray()
576 $ar = $this->cachedAudit();
582 $add = $a->toJSONArray($this);
593 function relatedCommits()
595 if (empty($this->rev)) {
598 // occurs on a ticket... when listing...
599 $mc = DB_DataObject::Factory('mtrack_change');
600 $mc->rev = $this->rev;
601 $mc->ontable = 'mtrack_repos';
602 if (!$mc->find(true)) {
605 // got the repo.. and the commit..
607 $repo = $mc->objectCached();
609 return $repo->historyToSummary(
610 $repo->impl()->history('.', 1, 'rev', $this->rev),
622 $a = DB_DataObject::Factory('mtrack_change_audit');
624 {$a->tableName()}.change_id = {$this->id} OR
625 {$a->tableName()}.ticket_change_id = {$this->id}
627 // var_dump($a->find());exit;
629 return $a->fetchAll();
632 function changesSince($object,$since)
634 $q = DB_DataObject::factory('mtrack_change');
635 $q->onid = $object->id;
636 $q->ontable = $object->tableName();
637 $q->whereAdd("changedate > '$since'");
638 $q->orderBy('changedate ASC');
640 // we are going to end up with a list of objects that have changed.
641 // eg. a ticket or a repo..
643 return $q->fetchAll();
649 function cachedAuditToString()
653 $ar = $this->cachedAudit();
654 foreach($ar as $audit) {
655 $add = $audit->toAuditString($this);
656 if ($add === false) {
662 return implode("\n",$body);
665 function toRooArray()
667 $ret = $this->toArray();
668 $ret['audit'] = $this->cachedAuditToJSONArray();
669 $ret['commit'] = $this->relatedCommits();
675 function beforeInsert($req, $roo)
677 // originally this was blocked - we are going to try and use it now???
678 if (empty($roo->authUser)) {
679 $roo->jerr("Invalid user inserting");
681 $this->person_id = $roo->authUser->id;
684 $obj = $this->objectCached();
686 if (!$obj || !$obj->checkPerm('E', $roo->authUser)) {
687 $roo->jerr("Invalid object / permission denied");
690 $this->changedate = $this->sqlValue('NOW()');
693 function beforeUpdate($old,$req,$roo)
695 $roo->jerr("update not allowed by user interface.");
700 function changedate($format)
702 return date($format, strtotime($this->changedate));
704 function postListFilter($data, $authUser, $q)
706 if (empty($q['ontable']) || empty($q['onid']) || $q['ontable'] != 'mtrack_ticket') {
709 //DB_DataObject::debugLevel(1);
710 // look up in the accounting system what time was spent on the ticket..
711 $ie = DB_DataObject::factory('cash_invoice_entry');
712 $ie->ticket_id = $q['onid'];
713 $ie->orderBy('entered_dt ASC'); // doesnt matter really - we will sort it..
717 cash_invoice_entry.id * -1 as id,
718 staff_id as person_id,
719 join_staff_id_id.name as person_id_name,
720 entered_dt as changedate,
721 'TIMESHEET' as cgtype ,
722 CONCAT(qtyvalue , ' Hours worked: ', cash_invoice_entry.description) as reason,
726 $hours = $ie->fetchAll(false,false,'toArray');
728 $ret = array_merge($data , $hours);
730 usort($ret, function ($a,$b) use($q) {
731 $aa = $a['changedate'];
732 $bb = $b['changedate'];
736 if ($q['dir'] == 'ASC') {
737 return strtotime($aa) < strtotime($bb) ? -1 : 1;
739 return strtotime($aa) > strtotime($bb) ? -1 : 1;
749 function sendTelegram()
751 if ($this->ontable != 'mtrack_ticket') {
757 require_once 'Net/Telegram.php';
758 $tg = new Net_Telegram(HTML_FlexyFramework::get()->Pman_Telegram['token']);
760 $t = $this->objectCached();
762 foreach ($this->audit() as $a) {
763 $str[] = $a->toAuditString($this);
766 $res = $tg->factory('SendMessage',array(
767 'chat_id' => 35721679,
768 'parse_mode' => 'MarkdownV2',
769 'text' => "/ticket@{$this->onid} *". htmlspecialchars($t->summary) . "*\n\n".
770 "{$this->cgtype} by {$this->person()->name} \n\n" . htmlspecialchars(implode("\n", $str))