initial commit
[namibia] / module / Workspace / src / Workspace / Controller / DeviceWorkspaceController.php
1 <?php
2 namespace Workspace\Controller;
3
4
5
6 class DeviceWorkspaceController extends \Zend\Mvc\Controller\AbstractActionController
7 {
8
9         /**
10          * @var \Zend\Session\Container
11          */
12         protected $session;
13         /**
14          * @var array
15          */
16         protected $request;
17         /**
18          * @var array
19          */
20         protected $response;
21         /**
22          * @var \Zend\ServiceManager\ServiceManager
23          */
24         protected $sm;
25
26         protected $em;
27         /**
28          * @var boolean
29          */
30         protected $authenticated = false;
31         /**
32          * @var \User\Service\Authentication
33          */
34         protected $authDetails;
35
36
37
38         /**
39          * Retrieve workspace manager.
40          */
41         public function initPost($initSession = true, $tokenParam = 'authToken')
42         {
43                 defined('APPLICATION')
44                         || define('APPLICATION', 'Mobile');
45                 $this->request = $_POST;
46                 $this->response = array();
47                 if ($initSession)
48                 {
49                         if (!isset($this->request[$tokenParam]) || empty($this->request[$tokenParam]))
50                         {
51                                 return false;
52                         }
53                         try
54                         {
55                                 \Utility\Registry::setSession($this->request[$tokenParam]);
56                                 $this->authenticated = true;
57                                 $this->authDetails = \Utility\Registry::getAuthData();
58                         }
59                         catch (\Exception $e)
60                         {
61                                 return false;
62                         }
63                 }
64                 \Utility\Registry::setServiceManager($this->serviceLocator);
65                 \Utility\Registry::addDynamicConfig(
66                                 \Utility\Registry::getEntityManager()
67                                         ->getRepository('Config\Entity\Config')
68                                         ->find(1)
69                                         ->toArray()
70                                 );
71                 return true;
72         }
73
74         /**
75          * Convenience method to extract parameters from request packet.
76          * @param string $paramName
77          * @param unknown $default
78          * @return unknown
79          */
80         protected function reqParam($paramName, $default = null)
81         {
82                 return isset($this->request[$paramName])
83                         ? $this->request[$paramName]
84                         : $default;
85         }
86
87         /**
88          * Convenience method to extract parameters from a nested request packet.
89          * @param string $root
90          * @param string $paramName
91          * @param unknown $default
92          * @return unknown
93          */
94         protected function reqNestedParam($root, $paramName, $default = null)
95         {
96                 return isset($this->request[$root][$paramName])
97                         ? $this->request[$root][$paramName]
98                         : $default;
99         }
100
101         /**
102          * Convenience method to extract parameters from a nested request packet.
103          * @param string $root
104          * @param string $paramName
105          * @param string $entityName
106          * @param unknown $default
107          * @return unknown
108          */
109         protected function reqNestedParamRef($root, $paramName, $entityName, $default = null)
110         {
111                 return isset($this->request[$root][$paramName])
112                                 && !is_null($this->request[$root][$paramName])
113                                 && 0 != $this->request[$root][$paramName]
114                         ? $this->em->getReference($entityName, $this->request[$root][$paramName])
115                         : $default;
116         }
117
118
119
120         /**
121          * Display list of tasks for specified workflows.
122          * @see \Zend\Mvc\Controller\AbstractActionController::indexAction()
123          * @return \Zend\View\Model\JsonModel
124          */
125         public function indexAction()
126         {
127                 return new \Zend\View\Model\JsonModel(array(
128                                 'login' => 'Requires an array with `email`, `pin`.',
129                                 'get-dataset' => 'Requires `token`, `datasetName`, [`page`, `timeStart`, `timeEnd`]'
130                 ));
131         }
132
133
134         /**
135          * Mobile handshake.
136          * @return \Zend\View\Model\JsonModel
137          */
138         public function pingAction()
139         {
140                 return new \Zend\View\Model\JsonModel(array(
141                                 'Meta' => array(
142                                                 'Task'         => 'Ping',
143                                                 'Status'       => 'Success',
144                                                 'StatusReason' => ''
145                                 ),
146                                 'Data' => array(
147                                                 'ServerTime' => time()
148                                 )
149                 ));
150         }
151
152
153         /**
154          * Mobile device connected to push server.
155          * @return \Zend\View\Model\JsonModel
156          */
157         public function registerDeviceAction()
158         {
159                 $this->initPost(true, 'ident');
160
161                 if ($this->authenticated)
162                 {
163                         \Utility\Registry::setAuthParam('pubid', $this->request['pubid']);
164                         $em = \Utility\Registry::getEntityManager();
165                         $session = $em->getRepository('\User\Entity\Session')
166                                 ->findOneBy(array('authToken' => $this->request['ident']));
167                         if (!is_null($session))
168                         {
169                                 $session->pubId = $this->request['pubid'];
170                                 $em->flush();
171                         }
172                 }
173                 /* error_log('User connected');
174                 $this->authenticated
175                         && error_log('Email: ' . $this->authDetails['email']);
176                 error_log('pubid: ' . $this->request['pubid']);
177                 error_log('ident: ' . $this->request['ident']); */
178                 return new \Zend\View\Model\JsonModel(array('ApeReg' => 'Success'));
179         }
180
181         /**
182          * Mobile device disconnected from push server.
183          * @return \Zend\View\Model\JsonModel
184          */
185         public function deregisterDeviceAction()
186         {
187                 $this->initPost(true, 'ident');
188
189                 if ($this->authenticated)
190                 {
191                         \Utility\Registry::setAuthParam('pubid', null);
192                         $em = \Utility\Registry::getEntityManager();
193                         $session = $em->getRepository('\User\Entity\Session')
194                                 ->findOneBy(array('authToken' => $this->request['ident']));
195                         if (!is_null($session))
196                         {
197                                 $session->pubId = null;
198                                 $em->flush();
199                         }
200                 }
201                 /* error_log('User disconnected');
202                 error_log('pubid: ' . $this->request['pubid']);
203                 error_log('ident: ' . $this->request['ident']); */
204                 return new \Zend\View\Model\JsonModel(array('ApeDereg' => 'Success'));
205         }
206
207         /**
208          * Broadcast a dataset change
209          * @return \Zend\View\Model\JsonModel
210          */
211         public function notifyDeviceAction()
212         {
213                 $this->initJson(false);
214
215                 $ds = isset($this->request['ds'])
216                         ? $this->request['ds']
217                         : 'countries';
218                 $pubid = isset($this->request['pubid'])
219                         ? $this->request['pubid']
220                         : false;
221                 //$response = \Utility\Comms\Ape::broadcast('synchv1', array('dataSet' => $ds), 'data', $pubid);
222                 return new \Zend\View\Model\JsonModel(array('Response' => $response));
223         }
224
225         /**
226          * Log debug data to db.
227          * @return \Zend\View\Model\JsonModel
228          */
229         public function logDebugAction()
230         {
231                 $this->initPost(false);
232                 $em = \Utility\Registry::getEntityManager();
233                 $debugLog = new \Utility\Entity\DebugLog();
234                 $debugLog->userId      = $this->reqParam('userId', null);
235                 $debugLog->callName    = $this->reqParam('callName', null);
236                 $debugLog->params      = serialize($this->reqParam('params', array()));
237                 $debugLog->errorString = $this->reqParam('errorString', null);
238                 $em->persist($debugLog);
239                 $em->flush();
240                 return new \Zend\View\Model\JsonModel(array(
241                                 'Meta' => array(
242                                                 'Task'         => 'LogDebug',
243                                                 'Status'       => 'Success',
244                                                 'StatusReason' => ''
245                                 ),
246                                 'Data' => array()
247                 ));
248         }
249
250         /**
251          * Device user login.
252          * @return \Zend\View\Model\JsonModel
253          */
254         public function loginAction()
255         {
256                 $this->initPost(false);
257
258                 $input = new \Workspace\Utility\ServiceInput('ParamSet', array(
259                                 'Login' => array(
260                                                 'email' => $this->request['email'],
261                                                 'pin'   => $this->request['pin']
262                                 )
263                 ));
264                 $serviceInput = new \Workspace\Utility\ServiceInput('ServiceInput', array(
265                                 'data' => $input->pack()
266                 ));
267                 $profileService = $this->serviceLocator->get('User.Service.Profile');
268                 $response = $profileService->deviceLogin($serviceInput->pack());
269                 if (isset($response['Data']['authToken']))
270                 {
271                         $em = \Utility\Registry::getEntityManager();
272                         $session = new \User\Entity\Session();
273                         $session->profile = $em->getReference('\User\Entity\Profile', $response['Data']['id']);
274                         $session->authToken = $response['Data']['authToken'];
275                         $em->persist($session);
276                         $em->flush();
277                 }
278                 return new \Zend\View\Model\JsonModel(array(
279                                 'Meta' => array_merge(array('Task' => 'Login'), $response['Meta']),
280                                 'Data' => $response['Data']
281                 ));
282         }
283
284         /**
285          * Device user pin reset.
286          * @return \Zend\View\Model\JsonModel
287          */
288         public function resetPinAction()
289         {
290                 $this->initPost(false);
291
292                 $input = new \Workspace\Utility\ServiceInput('ParamSet', array(
293                                 'Login' => array(
294                                                 'email'  => isset($this->request['email'])
295                                                                         ? $this->request['email']
296                                                                         : null,
297                                                 'mobile' => isset($this->request['mobile'])
298                                                                         ? $this->request['mobile']
299                                                                         : null
300                                 )
301                 ));
302                 $serviceInput = new \Workspace\Utility\ServiceInput('ServiceInput', array(
303                                 'data' => $input->pack()
304                 ));
305                 $profileService = $this->serviceLocator->get('User.Service.Profile');
306                 $response = $profileService->deviceResetPin($serviceInput->pack());
307                 return new \Zend\View\Model\JsonModel(array(
308                                 'Meta' => array_merge(array('Task' => 'ResetPin'), $response['Meta']),
309                                 'Data' => $response['Data']
310                 ));
311         }
312
313         /**
314          * Claim a job item from queue.
315          * @return \Zend\View\Model\JsonModel
316          */
317         public function claimJobAction()
318         {
319                 if (!$this->initPost())
320                 {
321                         return new \Zend\View\Model\JsonModel(array(
322                                         'Meta' => array(
323                                                         'Task'         => 'ClaimJob',
324                                                         'Status'       => 'Exception',
325                                                         'StatusReason' => 'Invalid session requested.',
326                                                         'DatasetName'  => null
327                                         ),
328                                         'Data' => array()
329                         ));
330                 }
331
332                 if (!isset($this->request['datasetName'])
333                         || !isset($this->request['id'])
334                         || 0 >= $this->request['id'])
335                 {
336                         return new \Zend\View\Model\JsonModel(array(
337                                         'Meta' => array(
338                                                         'Task'         => 'ClaimJob',
339                                                         'Status'       => 'Fail',
340                                                         'StatusReason' => 'Api call requires valid `datasetName` and `id` parameters.',
341                                                         'DatasetName'  => null
342                                         ),
343                                         'Data' => array()
344                         ));
345                 }
346                 $ds = $this->request['datasetName'];
347                 $id = $this->request['id'];
348                 switch ($ds)
349                 {
350                         case 'valuations':
351                         default:
352                                 $entityName = '\Valuation\Entity\Valuation';
353                                 $service = new \Valuation\Service\Valuation();
354                                 $service->setWorkflow(new \Valuation\Workflow());
355                                 break;
356                 }
357                 $em = \Utility\Registry::getEntityManager();
358                 $record = $em->getRepository($entityName)
359                         ->find($id);
360                 if (is_null($record) || 1 != $record->queueStatus)
361                 {
362                         if (!$record->claimQueueItem($em))
363                         {
364                                 return new \Zend\View\Model\JsonModel(array(
365                                                 'Meta' => array(
366                                                                 'Task'         => 'ClaimJob',
367                                                                 'Status'       => 'Fail',
368                                                                 'StatusReason' => 'Job not available.',
369                                                                 'DatasetName'  => $ds
370                                                 ),
371                                                 'Data' => array('id' => $record->id)
372                                 ));
373                         }
374                         else
375                         {
376                                 return new \Zend\View\Model\JsonModel(array(
377                                                 'Meta' => array(
378                                                                 'Task'         => 'ClaimJob',
379                                                                 'Status'       => 'Success',
380                                                                 'StatusReason' => '',
381                                                                 'DatasetName'  => $ds
382                                                 ),
383                                                 'Data' => $record->toArray(array('stock'), array(), 2)
384                                 ));
385                         }
386                 }
387                 $record->claimQueueItem($em);
388                 return new \Zend\View\Model\JsonModel(array(
389                                 'Meta' => array(
390                                                 'Task'         => 'ClaimJob',
391                                                 'Status'       => 'Success',
392                                                 'StatusReason' => '',
393                                                 'DatasetName'  => $ds
394                                 ),
395                                 'Data' => $record->toArray(array('stock'), array(), 2)
396                 ));
397         }
398
399         /**
400          * Return a claimed job item from queue.
401          * @return \Zend\View\Model\JsonModel
402          */
403         public function unclaimJobAction()
404         {
405                 if (!$this->initPost())
406                 {
407                         return new \Zend\View\Model\JsonModel(array(
408                                         'Meta' => array(
409                                                         'Task'         => 'UnclaimJob',
410                                                         'Status'       => 'Exception',
411                                                         'StatusReason' => 'Invalid session requested.',
412                                                         'DatasetName'  => null
413                                         ),
414                                         'Data' => array()
415                         ));
416                 }
417
418                 if (!isset($this->request['datasetName'])
419                         || !isset($this->request['id'])
420                         || 0 >= $this->request['id'])
421                 {
422                         return new \Zend\View\Model\JsonModel(array(
423                                         'Meta' => array(
424                                                         'Task'         => 'ClaimJob',
425                                                         'Status'       => 'Fail',
426                                                         'StatusReason' => 'Api call requires valid `datasetName` and `id` parameters.',
427                                                         'DatasetName'  => null
428                                         ),
429                                         'Data' => array()
430                         ));
431                 }
432                 $ds = $this->request['datasetName'];
433                 $id = $this->request['id'];
434                 switch ($ds)
435                 {
436                         case 'valuations':
437                         default:
438                                 $entityName = '\Valuation\Entity\Valuation';
439                                 $service = new \Valuation\Service\Valuation();
440                                 $service->setWorkflow(new \Valuation\Workflow());
441                                 break;
442                 }
443                 $em = \Utility\Registry::getEntityManager();
444                 $record = $em->getRepository($entityName)
445                         ->find($id);
446                 if (is_null($record) || 2 != $record->queueStatus)
447                 {
448                         return new \Zend\View\Model\JsonModel(array(
449                                         'Meta' => array(
450                                                         'Task'         => 'UnclaimJob',
451                                                         'Status'       => 'Fail',
452                                                         'StatusReason' => 'Job not claimed.',
453                                                         'DatasetName'  => $ds
454                                         ),
455                                         'Data' => $record->toArray()
456                         ));
457                 }
458                 try
459                 {
460                         $record->unclaimQueueItem($em);
461                         return new \Zend\View\Model\JsonModel(array(
462                                         'Meta' => array(
463                                                         'Task'         => 'UnclaimJob',
464                                                         'Status'       => 'Success',
465                                                         'StatusReason' => '',
466                                                         'DatasetName'  => $ds
467                                         ),
468                                         'Data' => $record->toArray(array(), array(), false, 2)
469                         ));
470                 }
471                 catch (\Exception $e)
472                 {
473                         return new \Zend\View\Model\JsonModel(array(
474                                         'Meta' => array(
475                                                         'Task'         => 'UnclaimJob',
476                                                         'Status'       => 'Fail',
477                                                         'StatusReason' => 'Job owned by different user.',
478                                                         'DatasetName'  => $ds
479                                         ),
480                                         'Data' => $record->toArray()
481                         ));
482                 }
483         }
484
485         /**
486          * Synchronize critical valuation info.
487          * @return \Zend\View\Model\JsonModel
488          */
489         public function synchPhotoAction()
490         {
491                 if (!$this->initPost())
492                 {
493                         return new \Zend\View\Model\JsonModel(array(
494                                         'Meta' => array(
495                                                         'Task'         => 'SynchPhoto',
496                                                         'Status'       => 'Exception',
497                                                         'StatusReason' => 'Invalid session requested.',
498                                                         'DatasetName'  => null
499                                         ),
500                                         'Data' => array()
501                         ));
502                 }
503
504                 $this->em = \Utility\Registry::getEntityManager();
505                 $params = json_decode($this->request['params'], true);
506                 $params = $params[0];
507                 $uvi    = $params['uvi'];
508                 $type   = $params['type'];
509                 $params['photo'] = base64_decode($params['photo']);
510                 $this->em = \Utility\Registry::getEntityManager();
511                 $stock = $this->em
512                         ->getRepository('\Stock\Entity\Stock')
513                         ->findOneBy(array('uvi' => $uvi));
514                 if ($stock)
515                 {
516                         #-> Write image to file.
517                         $filePath = \Utility\Registry::getConfigParam('ImagePath');
518                         $thumbPath = \Utility\Registry::getConfigParam('ThumbnailPath');
519                         file_put_contents($filePath . $type . $uvi . '.jpg', $params['photo']);
520                         $this->resizeImage($params['photo'], 'image/jpeg', $thumbPath . $type . $uvi . '.jpg');
521
522                         #-> Create image entry.
523                         $image = new \Utility\Entity\Image();
524                         $image->filename = $type . $uvi . '.jpg';
525                         $image->mimeType = 'image/jpeg';
526                         $this->em->persist($image);
527                         $this->em->flush();
528
529                         #-> Update stock entry.
530                         switch ($type)
531                         {
532                                 case 'MAIN':
533                                         $stock->mainImage = $image;
534                                         break;
535                                 case 'FRONT':
536                                         $stock->frontImage = $image;
537                                         break;
538                                 case 'RIGHT':
539                                         $stock->rightImage = $image;
540                                         break;
541                                 case 'LEFT':
542                                         $stock->leftImage = $image;
543                                         break;
544                                 case 'BACK':
545                                         $stock->backImage = $image;
546                                         break;
547                                 case 'ENGINE':
548                                         $stock->engineImage = $image;
549                                         break;
550                                 case 'INTERIOR':
551                                         $stock->interiorImage = $image;
552                                         break;
553                                 case 'NATIS':
554                                         $stock->natisImage = $image;
555                                         break;
556                         }
557                         $this->em->flush();
558                         return new \Zend\View\Model\JsonModel(array(
559                                         'Meta' => array(
560                                                         'Task'         => 'SynchPhoto',
561                                                         'Status'       => 'Success',
562                                                         'StatusReason' => 'Synchronized.'
563                                         ),
564                                         'Data' => array(array('uvi' => $uvi, 'type' => $type))
565                         ));
566                 }
567                 else
568                 {
569                         return new \Zend\View\Model\JsonModel(array(
570                                         'Meta' => array(
571                                                         'Task'         => 'SynchPhoto',
572                                                         'Status'       => 'Error',
573                                                         'StatusReason' => 'Valuation with UVI ' . $uvi . ' not found.'
574                                         ),
575                                         'Data' => array()
576                         ));
577                 }
578         }
579
580         private function resizeImage($imgString, $mimeType, $destination)
581         {
582                 switch ($mimeType)
583                 {
584                         case 'image/jpeg':
585                         case 'image/pjpeg':
586                                 $fileExt = '.jpg';
587                                 break;
588                         case 'image/gif':
589                                 $fileExt = '.gif';
590                                 break;
591                         case 'image/png':
592                                 $fileExt = '.png';
593                                 break;
594                         case 'image/bmp':
595                         case 'image/x-windows-bmp':
596                                 $fileExt = '.bmp';
597                                 break;
598                         default:
599                                 return false;
600                 }
601                 /* $tmpFile = \Utility\Registry::getConfigParam('ImagePath')
602                                                  . mt_rand(10000000, 99999999) . $fileExt; */
603                 $tmpFile = $destination;
604                 $bytesWritten = file_put_contents($tmpFile, $imgString);
605                 list($img_width, $img_height) = getimagesize($tmpFile);
606                 unlink($tmpFile);
607                 if (!$img_width || !$img_height)
608                 {
609                         return false;
610                 }
611                 $src_img = imagecreatefromstring($imgString);
612                 $scale = min(
613                                 300 / $img_width,
614                                 200 / $img_height
615                 );
616                 if ($scale >= 1)
617                 {
618                         file_put_contents($tmpFile, $imgString);
619                         return true;
620                 }
621                 $new_width = $img_width * $scale;
622                 $new_height = $img_height * $scale;
623                 $new_img = @imagecreatetruecolor($new_width, $new_height);
624                 switch ($mimeType)
625                 {
626                         case 'image/jpeg':
627                         case 'image/pjpeg':
628                                 $write_image = 'imagejpeg';
629                                 $image_quality = 95;
630                                 break;
631                         case 'image/gif':
632                                 @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0));
633                         $write_image = 'imagegif';
634                         $image_quality = null;
635                         break;
636                         case 'image/png':
637                                 @imagecolortransparent($new_img, @imagecolorallocate($new_img, 0, 0, 0));
638                                 @imagealphablending($new_img, false);
639                                 @imagesavealpha($new_img, true);
640                                 $write_image = 'imagepng';
641                                 $image_quality = 9;
642                                 break;
643                         case 'image/bmp':
644                         case 'image/x-windows-bmp':
645                                 $write_image = 'imagebmp';
646                                 $image_quality = null;
647                                 break;
648                         default:
649                                 return false;
650                 }
651                 $success = @imagecopyresampled(
652                                 $new_img,
653                                 $src_img,
654                                 0, 0, 0, 0,
655                                 $new_width,
656                                 $new_height,
657                                 $img_width,
658                                 $img_height
659                 );
660                 if ($success)
661                 {
662                         $write_image($new_img, $tmpFile, $image_quality);
663                         @imagedestroy($src_img);
664                         @imagedestroy($new_img);
665                         return true;
666                 }
667                 @imagedestroy($src_img);
668                 @imagedestroy($new_img);
669                 return false;
670         }
671
672         /**
673          * Synchronize multiple valuations.
674          * @return \Zend\View\Model\JsonModel
675          */
676         public function synchValuationsAction()
677         {
678                 if (!$this->initPost())
679                 {
680                         return new \Zend\View\Model\JsonModel(array(
681                                         'Meta' => array(
682                                                         'Task'         => 'SynchValuations',
683                                                         'Status'       => 'Exception',
684                                                         'StatusReason' => 'Invalid session requested.',
685                                                         'DatasetName'  => null
686                                         ),
687                                         'Data' => array()
688                         ));
689                 }
690
691                 $this->em = \Utility\Registry::getEntityManager();
692                 $input     = json_decode($this->request['params'], true);
693                 $responses = array();
694                 foreach ($input as $paramSet)
695                 {
696                         $response = $this->synchValuation($paramSet);
697                         $responses[] = 'Success' == $response['Meta']['Status']
698                                 ? $response['Data']
699                                 : array('uvi' => null);
700                 }
701                 return new \Zend\View\Model\JsonModel(array(
702                                 'Meta' => array(
703                                                 'Task'         => 'SynchValuations',
704                                                 'Status'       => 'Success',
705                                                 'StatusReason' => ''
706                                 ),
707                                 'Data' => $responses
708                 ));
709         }
710
711         /**
712          * Synchronize critical valuation info.
713          * @return \Zend\View\Model\JsonModel
714          */
715         public function synchValuationInfoAction()
716         {
717                 if (!$this->initPost())
718                 {
719                         return new \Zend\View\Model\JsonModel(array(
720                                         'Meta' => array(
721                                                         'Task'         => 'SynchValuationInfo',
722                                                         'Status'       => 'Exception',
723                                                         'StatusReason' => 'Invalid session requested.',
724                                                         'DatasetName'  => null
725                                         ),
726                                         'Data' => array()
727                         ));
728                 }
729
730                 $this->em = \Utility\Registry::getEntityManager();
731                 $data = json_decode($this->request['params'], true);
732                 $response = $this->synchValuation($data);
733                 //$response['Data'] = array($response['Data']);
734                 return new \Zend\View\Model\JsonModel(
735                                 $response
736                                 );
737         }
738
739         /**
740          * Synchronize critical valuation info.
741          * @return \Zend\View\Model\JsonModel
742          */
743         private function synchValuation($params)
744         {
745                 $this->request['params'] = $params;
746                 $this->request['params']['vehicle_accessories'] = is_array($this->request['params']['vehicle_accessories'])
747                         ? $this->request['params']['vehicle_accessories']
748                         : json_decode($this->request['params']['vehicle_accessories'], true);
749                 $this->request['params']['vehicle_damages'] = is_array($this->request['params']['vehicle_damages'])
750                         ? $this->request['params']['vehicle_damages']
751                         : json_decode($this->request['params']['vehicle_damages'], true);
752                 $this->request['params']['vehicle_accessories'] = isset($this->request['params']['vehicle_accessories']['values'])
753                         ? $this->request['params']['vehicle_accessories']['values']
754                         : $this->request['params']['vehicle_accessories'];
755                 $this->request['params']['vehicle_damages'] = isset($this->request['params']['vehicle_damages']['values'])
756                         ? $this->request['params']['vehicle_damages']['values']
757                         : $this->request['params']['vehicle_damages'];
758
759                 if (is_null($this->em))
760                 {
761                         $this->em = \Utility\Registry::getEntityManager();
762                 }
763                 $valuationId = $this->reqNestedParam('params', 'server_id', false);
764                 $uvi = $this->reqNestedParam('params', 'valuation_id', false);
765                 $tt = $this->reqNestedParamRef('params', 'vehicle_type', '\Stock\Entity\Type', false);
766                 if (!$valuationId && !$uvi && !$tt)
767                 {
768                         return array(
769                                         'Meta' => array(
770                                                         'Task'         => 'SynchValuation',
771                                                         'Status'       => 'Exception',
772                                                         'StatusReason' => 'Insufficient data provided.'
773                                         ),
774                                         'Data' => array('uvi' => $uvi)
775                         );
776                 }
777                 $isNewEntry = false;
778                 $pgOverrideDoNotSend = false;
779                 if ($valuationId)
780                 {
781                         $valuation = $this->em
782                                 ->getRepository('\Valuation\Entity\Valuation')
783                                 ->find($valuationId);
784                         if (is_null($valuation))
785                         {
786                                 $valuation = new \Valuation\Entity\Valuation();
787                                 $stock = new \Stock\Entity\Stock();
788                         $valuation->stock = $stock;
789                         $isNewEntry = true;
790                         }
791                         else
792                         {
793                                 $stock = $valuation->stock;
794                                 if ('Price Guide' == $valuation->jobState || 'Price Guide' == $stock->jobState)
795                                 {
796                                         $pgOverrideDoNotSend = true;
797                                 }
798                         }
799                 }
800                 else
801                 {
802                         $stock = $this->em
803                                 ->getRepository('\Stock\Entity\Stock')
804                                 ->findOneBy(array('uvi' => $uvi));
805                         if ($stock)
806                         {
807                                 if (!is_null($stock->valuation))
808                                 {
809                                         $valuation = $this->em
810                                                 ->getRepository('\Valuation\Entity\Valuation')
811                                                 ->find($stock->valuation->id);
812                                         if ('Price Guide' == $valuation->jobState || 'Price Guide' == $stock->jobState)
813                                         {
814                                                 $pgOverrideDoNotSend = true;
815                                         }
816                                 }
817                                 else
818                                 {
819                                         $valuation = new \Valuation\Entity\Valuation();
820                                         $stock = new \Stock\Entity\Stock();
821                                         $valuation->stock = $stock;
822                                         $isNewEntry = true;
823                                 }
824                         }
825                         else
826                         {
827                                 $valuation = new \Valuation\Entity\Valuation();
828                                 $stock = new \Stock\Entity\Stock();
829                         $valuation->stock = $stock;
830                         $isNewEntry = true;
831                         }
832                 }
833
834                 $iterator = $stock->damages->getIterator();
835                 foreach ($iterator as $dmg)
836                 {
837                         $this->em->remove($dmg);
838                 }
839                 $iterator = $stock->accessories->getIterator();
840                 foreach ($iterator as $acc)
841                 {
842                         $this->em->remove($acc);
843                 }
844                 $this->em->flush();
845
846
847                 $accessories = array();
848                 foreach ($this->reqNestedParam('params', 'vehicle_accessories', array()) as $accId)
849                 {
850                         $accessories[] = array('id' => $accId);
851                 }
852
853                 $tradePrice = $this->reqNestedParam('params', 'trade_price', null);
854                 $retailPrice = $this->reqNestedParam('params', 'retail_price', null);
855         $listPrice = $this->reqNestedParam('params', 'list_price', null);
856                 /* try
857                 {
858                         if (is_null($tradePrice) || 0 == $tradePrice
859                                 || is_null($retailPrice) || 0 == $retailPrice)
860                         {
861                                 $vehicleYear = $this->em->find(
862                                                 '\Stock\Entity\Year',
863                                                 $this->reqNestedParam('params', 'vehicle_year', null));
864                                 $vehicleType = $this->em->find(
865                                                 '\Stock\Entity\Type',
866                                                 $this->reqNestedParam('params', 'vehicle_type', null));
867                                 if (is_object($vehicleYear) && is_object($vehicleType))
868                                 {
869                                         if ($vehicleYear->name != date('Y'))
870                                         {
871                                                 $tu = new \Utility\Comms\TransUnion();
872                                                 $tuRes = $tu->searchByMmCode($vehicleType->mmCode, $vehicleYear->name);
873                                                 \Utility\Debug::errorLog('TY Fetch on Synch', $tuRes);
874                                                 if (false != $tuRes)
875                                                 {
876                                                         $tradePrice = $tuRes['VehicleDetails'][0]['Value']['TradePrice'];
877                                                         $retailPrice = $tuRes['VehicleDetails'][0]['Value']['RetailPrice'];
878                                                 }
879                                         }
880                                 }
881                         }
882                 }
883                 catch (\Exception $e)
884                 {
885                         \Utility\Debug::errorLog('TY Fetch Error on Synch', $e->getMessage());
886                 } */
887
888                 $keys = $this->reqNestedParam('params', 'vehicle_spare_keys', null);
889                 if (null != $keys)
890                 {
891                         $keys = 'Yes' == $keys
892                                 ? true
893                                 : false;
894                 }
895                 $stockData = array(
896                                 'vehicleYear' => $this->reqNestedParamRef('params', 'vehicle_year', '\Stock\Entity\Year', null),
897                                 'type' => $this->reqNestedParamRef('params', 'vehicle_type', '\Stock\Entity\Type', null),
898                                 'registrationNumber' => $this->reqNestedParam('params', 'vehicle_reg', null),
899                                 'fuelType' => $this->reqNestedParamRef('params', 'vehicle_fuel_type', 'Stock\Entity\FuelType', null),
900                                 'transmissionType' => $this->reqNestedParamRef('params', 'vehicle_transmission_type', 'Stock\Entity\TransmissionType', null),
901
902                                 'km' => $this->reqNestedParam('params', 'vehicle_mileage', null),
903                                 'tradePrice' => $this->reqNestedParam('params', 'trade_price', null),
904                                 'retailPrice' => $this->reqNestedParam('params', 'retail_price', null),
905                 'listPrice' => $this->reqNestedParam('params', 'list_price', null),
906                                 'condition' => $this->reqNestedParamRef('params', 'vehicle_condition', 'Stock\Entity\Condition', null),
907                                 'exteriorColour' => $this->reqNestedParamRef('params', 'vehicle_exterior_colour', 'Stock\Entity\ExteriorColour', null),
908                                 'interiorColour' => $this->reqNestedParamRef('params', 'vehicle_interior_colour', 'Stock\Entity\InteriorColour', null),
909                                 'upholstery' => $this->reqNestedParamRef('params', 'vehicle_upholstery', 'Stock\Entity\Upholstery', null),
910                                 'vinNumber' => $this->reqNestedParam('params', 'vehicle_vin', null),
911                                 'engineNumber' => $this->reqNestedParam('params', 'vehicle_engine_number', null),
912                                 'previousRepairsNoted' => $this->reqNestedParam('params', 'vehicle_prev_repairs', null),
913                                 'previousRepairsNotes' => $this->reqNestedParam('params', 'vehicle_prev_repairs_comments', null),
914                                 'accessories' => $accessories,
915                                 'accessoryNotes' => $this->reqNestedParam('params', 'vehicle_accessories_comments', null),
916                                 'damages' => $this->reqNestedParam('params', 'vehicle_damages', null),
917                                 'damageNotes' => $this->reqNestedParam('params', 'vehicle_damages_comments', null),
918                                 'spareKeys' => $keys,
919                                 'papers' => $this->reqNestedParamRef('params', 'vehicle_papers', 'Stock\Entity\Paper', null),
920                                 'fullServiceHistory' => $this->reqNestedParamRef('params', 'vehicle_fsh', 'Stock\Entity\FullServiceHistory', null),
921                                 'fshNotes' => $this->reqNestedParam('params', 'vehicle_fsh_notes', null),
922                 );
923                 $valuationData = array(
924                                 'firstName' => $this->reqNestedParam('params', 'customer_name', null),
925                                 'familyName' => $this->reqNestedParam('params', 'customer_surname', null),
926                                 'mobile' => $this->reqNestedParam('params', 'customer_mobile_number', null),
927                                 'department' => $this->reqNestedParam('params', 'customer_department', null),
928                                 'idNumber' => $this->reqNestedParam('params', 'customer_id_number', null),
929                                 'email' => $this->reqNestedParam('params', 'customer_email', null)
930                 );
931                 $emailValidator = new \Zend\Validator\EmailAddress();
932                         if (!$emailValidator->isValid($valuationData['email']))
933                         {
934                                 $valuationData['email'] = null;
935                         }
936                 try
937                 {
938                         $wValuation = $this->serviceLocator->get('Valuation');
939                         $valuation->fromArray($valuationData);
940                         $stock->fromArray($stockData);
941                         $stock->uvi = $uvi;
942                         $stock->jobState = 'Valuation';
943                         if ($isNewEntry)
944                         {
945                                 $this->em->persist($stock);
946                                 $this->em->persist($valuation);
947                         }
948                         $this->em->flush($stock);
949                         $this->em->flush($valuation);
950                         if ($isNewEntry)
951                         {
952                                 $stock->valuation = $valuation;
953                                 $stock->postInsert();
954                                 $valuation->postInsert();
955                                 $this->em->flush($stock);
956                         }
957                         $oValuation = new \Valuation\Service\Valuation();
958                         $oValuation->setWorkflow($wValuation);
959                         $wValuation->loadJob($valuation->id);
960                         if (!$pgOverrideDoNotSend)
961                         {
962                                 $wValuation->changeState('This.PendingValuation');
963                         }
964                         if (!$pgOverrideDoNotSend && $this->reqNestedParam('params', 'send_to_priceguide', false))
965                         {
966                                 $authData = \Utility\Registry::getAuthData();
967                                 $clubs = $this->em->getRepository('\PriceGuide\Entity\Club')
968                                         ->findBy(array(
969                                                         'company' => $this->em->getReference('\Company\Entity\Company', $authData['company']['id']),
970                                                         'useAsDefault' => true
971                                         ));
972                                 if (!empty($clubs))
973                                 {
974                                         $sendTo = array();
975                                         foreach ($clubs as $club)
976                                         {
977                                                 $sendTo[] = array('id' => $club->id);
978                                         }
979                                         $input = new \Workspace\Utility\ServiceInput('ParamSet', array(
980                                                         'id' => $valuation->id,
981                                                         'Context' => array(
982                                                                         'clubs' => $sendTo
983                                                         ),
984                                                         'Valuation' => array(
985                                                                         'firstName'     => $valuationData['firstName'],
986                                                                         'familyName'    => $valuationData['familyName'],
987                                                                         'mobile'        => $valuationData['mobile']
988                                                         ),
989                                                         'Stock' => array(
990                                                                         'vehicleYear'          => $stockData['vehicleYear']->id,
991                                                                         'type'                 => $stockData['type']->id,
992                                                                         'registrationNumber'   => $stockData['registrationNumber'],
993                                                                         'fuelType'             => $stockData['fuelType']->id,
994                                                                         'transmissionType'     => $stockData['transmissionType']->id
995                                                         )));
996                                         $serviceInput = new \Workspace\Utility\ServiceInput('ServiceInput', array(
997                                                         'data' => $input->pack()
998                                         ));
999                                         $contract = $serviceInput->pack();
1000                                         $result = $wValuation->executeRoute('Valuation.SendToPriceGuide', $valuation->id, $serviceInput->pack());
1001                                 }
1002                         }
1003                 }
1004                 catch (\Exception $e)
1005                 {
1006                         \Utility\Debug::errorLog('SynchValuationInfo Exception', "$e");
1007                         return array(
1008                                         'Meta' => array(
1009                                                         'Task'         => 'SynchValuationInfo',
1010                                                         'Status'       => 'Exception',
1011                                                         'StatusReason' => 'Server code exception occurred. Could not synchronize data.'
1012                                         ),
1013                                         'Data' => array('uvi' => $uvi)
1014                         );
1015                 }
1016                 unset($this->request['params']);
1017                 if (!$valuation->id)
1018                 {
1019                         return array(
1020                                                 'Meta' => array(
1021                                                                 'Task'         => 'SynchValuationInfo',
1022                                                                 'Status'       => 'Error',
1023                                                                 'StatusReason' => 'Could not save entry to database.'
1024                                                 ),
1025                                                 'Data' => array('uvi' => $uvi)
1026                                 );
1027                 }
1028                 else
1029                 {
1030                         return array(
1031                                                 'Meta' => array(
1032                                                                 'Task'         => 'SynchValuationInfo',
1033                                                                 'Status'       => 'Success',
1034                                                                 'StatusReason' => 'Synchronized.'
1035                                                 ),
1036                                                 'Data' => array('uvi' => $uvi)
1037                                 );
1038                 }
1039         }
1040
1041         /**
1042          * Retrieve a dataset.
1043          * @return \Zend\View\Model\JsonModel
1044          */
1045         public function getDatasetAction()
1046         {
1047                 if (!$this->initPost())
1048                 {
1049                         return new \Zend\View\Model\JsonModel(array(
1050                                         'Meta' => array(
1051                                                         'Task'         => 'GetDataset',
1052                                                         'Status'       => 'Exception',
1053                                                         'StatusReason' => 'Invalid session requested.',
1054                                                         'DatasetName'  => null
1055                                         ),
1056                                         'Data' => array()
1057                         ));
1058                 }
1059
1060                 if (!isset($this->request['datasetName']))
1061                 {
1062                         return new \Zend\View\Model\JsonModel(array(
1063                                         'Meta' => array(
1064                                                         'Task'         => 'GetDataset',
1065                                                         'Status'       => 'Fail',
1066                                                         'StatusReason' => 'Api call requires valid `datasetName` parameter.',
1067                                                         'DatasetName'  => null
1068                                         ),
1069                                         'Data' => array()
1070                         ));
1071                 }
1072                 $ds = $this->request['datasetName'];
1073                 $reverse = false;
1074                 switch ($ds)
1075                 {
1076                         #-> Location
1077                         case 'countries': $entityName = '\Location\Entity\Country'; break;
1078                         case 'regions': $entityName = '\Location\Entity\Region'; break;
1079                         case 'towns': $entityName = '\Location\Entity\Town'; break;
1080                         #-> Stock
1081                         case 'valuations': $entityName = '\Valuation\Entity\Valuation'; break;
1082                         case 'accessories': $entityName = '\Stock\Entity\Accessory'; break;
1083                         case 'damages': $entityName = '\Stock\Entity\Damage'; break;
1084                         case 'upholstery': $entityName = '\Stock\Entity\Upholstery'; break;
1085                         case 'condition': $entityName = '\Stock\Entity\Condition'; break;
1086                         case 'exteriorColours': $entityName = '\Stock\Entity\ExteriorColour'; break;
1087                         case 'interiorColours': $entityName = '\Stock\Entity\InteriorColour'; break;
1088                         case 'fuelTypes': $entityName = '\Stock\Entity\FuelType'; break;
1089                         case 'fullServiceHistory': $entityName = '\Stock\Entity\FullServiceHistory'; break;
1090                         case 'transmissionTypes': $entityName = '\Stock\Entity\TransmissionType'; break;
1091                         case 'natis': $entityName = '\Stock\Entity\Natis'; break;
1092                         case 'papers': $entityName = '\Stock\Entity\Paper'; break;
1093                         case 'years': $entityName = '\Stock\Entity\Year'; $reverse = true; break;
1094                         case 'categories': $entityName = '\Stock\Entity\Category'; break;
1095                         case 'makes': $entityName = '\Stock\Entity\Make'; break;
1096                         case 'models': $entityName = '\Stock\Entity\Model'; break;
1097                         case 'types': $entityName = '\Stock\Entity\Type'; break;
1098                         default:
1099                                 return new \Zend\View\Model\JsonModel(array(
1100                                                 'Meta' => array(
1101                                                                 'Task'         => 'GetDataset',
1102                                                                 'Status'       => 'Fail',
1103                                                                 'StatusReason' => 'Unknown dataset requested.',
1104                                                                 'DatasetName'  => $ds
1105                                                 ),
1106                                                 'Data' => array()
1107                                 ));
1108                                 break;
1109                 }
1110                 $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
1111                 if ('Build' == $entityName::PULL_SYNCH_STRATEGY || 'years' == $ds || 'accessories' == $ds)
1112                 {
1113                         $filter = ' WHERE 1 = 1 ';
1114                         $filter .= defined($entityName . '::JOB_QUEUE')
1115                                 ? ' AND a.queueStatus = 1 '
1116                                 : '';
1117                         $filter .= $entityName::ARCHIVE
1118                                 ? ' AND a.archived = 0 '
1119                                 : '';
1120                         if (method_exists($entityName, 'getSynchQuery'))
1121                         {
1122                                 $query = $em->createQuery(
1123                                                 $entityName::getSynchQuery()
1124                                                 );
1125                         }
1126                         else
1127                         {
1128                                 $query = $em->createQuery(
1129                                                 "SELECT a FROM $entityName a $filter ORDER BY a.id ASC"
1130                                 );
1131                         }
1132                         $data = $query->getResult();
1133                         if (defined($entityName . '::JOB_QUEUE'))
1134                         {
1135                                 foreach ($data as $rowId => $record)
1136                                 {
1137                                         $data[$rowId] = $record->toQueueArray();
1138                                 }
1139                         }
1140                         else
1141                         {
1142                                 foreach ($data as $rowId => $record)
1143                                 {
1144                                         $data[$rowId] = $record->toSynchArray();
1145                                 }
1146                         }
1147                         if ($reverse)
1148                         {
1149                                 $data = array_reverse($data);
1150                         }
1151
1152                 }
1153                 else
1154                 {
1155                         $data = array();
1156                         $version = isset($this->request['version'])
1157                                 ? (int) $this->request['version']
1158                                 : 1;
1159                         $filter = '';
1160                         $filter .= defined($entityName . '::JOB_QUEUE')
1161                                 ? ' AND a.queueStatus = 1'
1162                                 : '';
1163                         $filter .= $entityName::ARCHIVE
1164                                 ? ' AND a.archived = 0'
1165                                 : '';
1166                         if (method_exists($entityName, 'getSynchFilter'))
1167                         {
1168                                 $synchMod = $entityName::getSynchFilter();
1169                         }
1170                         else
1171                         {
1172                                 $synchMod = array(
1173                                                 'Join' => '',
1174                                                 'Filter' => ''
1175                                 );
1176                         }
1177
1178                         #-> Records to add.
1179                         $query = "SELECT [SELECTION] "
1180                                         . "FROM $entityName a "
1181                                         . $synchMod['Join']
1182                                         . "WHERE a.archived = :archived"
1183                                         . " $filter " . $synchMod['Filter']
1184                                         . " AND a.createVersion = :version"
1185                                         . " ORDER BY a.id ASC";
1186                         $params = array(
1187                                         'archived' => false,
1188                                         'version'  => $version
1189                         );
1190                         $data['Create'] = $em->createQuery(
1191                                         str_replace('[SELECTION]', 'a', $query)
1192                                         )
1193                                 ->setParameters($params)
1194                                 ->getResult();
1195
1196                         #-> Records to update.
1197                         $query = "SELECT [SELECTION] "
1198                                         . "FROM $entityName a "
1199                                         . $synchMod['Join']
1200                                         . "WHERE a.archived = :archived"
1201                                         . " $filter " . $synchMod['Filter']
1202                                         . " AND a.createVersion != :version"
1203                                         . " AND a.updateVersion = :version"
1204                                         . " ORDER BY a.id ASC";
1205                         $params = array(
1206                                         'archived'  => false,
1207                                         'version'  => $version
1208                         );
1209                         $data['Update'] = $em->createQuery(
1210                                         str_replace('[SELECTION]', 'a', $query)
1211                                         )
1212                                 ->setParameters($params)
1213                                 ->getResult();
1214                         $data['Delete'] = array();
1215
1216
1217                         #-> Finalize.
1218                         if (defined($entityName . '::JOB_QUEUE'))
1219                         {
1220                                 foreach ($data as $type => $dataset)
1221                                 {
1222                                         foreach ($dataset as $rowId => $record)
1223                                         {
1224                                                 $data[$type][$rowId] = $record->toQueueArray();
1225                                         }
1226                                 }
1227                         }
1228                         else
1229                         {
1230                                 foreach ($data as $type => $dataset)
1231                                 {
1232                                         foreach ($dataset as $rowId => $record)
1233                                         {
1234                                                 $data[$type][$rowId] = $record->toSynchArray();
1235                                         }
1236                                 }
1237                         }
1238                 }
1239
1240                 return new \Zend\View\Model\JsonModel(array(
1241                                 'Meta' => array(
1242                                         'Task'         => 'GetDataset',
1243                                         'Status'       => 'Success',
1244                                         'StatusReason' => '',
1245                                         'DatasetName'  => $ds,
1246                                         'Strategy'     => $entityName::PULL_SYNCH_STRATEGY,
1247                                         'DataPages'    => 1,
1248                                         'Page'         => 1,
1249                                         'StartTime'    => 0,
1250                                         'EndTime'      => date('Y-m-d H:i:s')
1251
1252                                 ),
1253                                 'Data' => $data
1254                 ));
1255         }
1256
1257         /**
1258          * Retrieve a dataset.
1259          * @return \Zend\View\Model\JsonModel
1260          */
1261         public function getVersionedDatasetAction()
1262         {
1263                 if (!$this->initPost())
1264                 {
1265                         return new \Zend\View\Model\JsonModel(array(
1266                                         'Meta' => array(
1267                                                         'Task'         => 'GetDataset',
1268                                                         'Status'       => 'Exception',
1269                                                         'StatusReason' => 'Invalid session requested.',
1270                                                         'DatasetName'  => null
1271                                         ),
1272                                         'Data' => array()
1273                         ));
1274                 }
1275
1276                 if (!isset($this->request['datasetName']))
1277                 {
1278                         return new \Zend\View\Model\JsonModel(array(
1279                                         'Meta' => array(
1280                                                         'Task'         => 'GetDataset',
1281                                                         'Status'       => 'Fail',
1282                                                         'StatusReason' => 'Api call requires valid `datasetName` parameter.',
1283                                                         'DatasetName'  => null
1284                                         ),
1285                                         'Data' => array()
1286                         ));
1287                 }
1288                 $ds = $this->request['datasetName'];
1289                 switch ($ds)
1290                 {
1291                         #-> Location
1292                         case 'countries': $entityName = '\Location\Entity\Country'; break;
1293                         case 'regions': $entityName = '\Location\Entity\Region'; break;
1294                         case 'towns': $entityName = '\Location\Entity\Town'; break;
1295                         #-> Stock
1296                         case 'valuations': $entityName = '\Valuation\Entity\Valuation'; break;
1297                         case 'accessories': $entityName = '\Stock\Entity\Accessory'; break;
1298                         case 'damages': $entityName = '\Stock\Entity\Damage'; break;
1299                         case 'upholstery': $entityName = '\Stock\Entity\Upholstery'; break;
1300                         case 'condition': $entityName = '\Stock\Entity\Condition'; break;
1301                         case 'exteriorColours': $entityName = '\Stock\Entity\ExteriorColour'; break;
1302                         case 'interiorColours': $entityName = '\Stock\Entity\InteriorColour'; break;
1303                         case 'fuelTypes': $entityName = '\Stock\Entity\FuelType'; break;
1304                         case 'fullServiceHistory': $entityName = '\Stock\Entity\FullServiceHistory'; break;
1305                         case 'transmissionTypes': $entityName = '\Stock\Entity\TransmissionType'; break;
1306                         case 'natis': $entityName = '\Stock\Entity\Natis'; break;
1307                         case 'papers': $entityName = '\Stock\Entity\Paper'; break;
1308                         case 'years': $entityName = '\Stock\Entity\Year'; break;
1309                         case 'categories': $entityName = '\Stock\Entity\Category'; break;
1310                         case 'makes': $entityName = '\Stock\Entity\Make'; break;
1311                         case 'models': $entityName = '\Stock\Entity\Model'; break;
1312                         case 'types': $entityName = '\Stock\Entity\Type'; break;
1313                         default:
1314                                 return new \Zend\View\Model\JsonModel(array(
1315                                                 'Meta' => array(
1316                                                                 'Task'         => 'GetDataset',
1317                                                                 'Status'       => 'Fail',
1318                                                                 'StatusReason' => 'Unknown dataset requested.',
1319                                                                 'DatasetName'  => $ds
1320                                                 ),
1321                                                 'Data' => array()
1322                                 ));
1323                                 break;
1324                 }
1325                 $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
1326                 if ('Build' == $entityName::PULL_SYNCH_STRATEGY)
1327                 {
1328                         /* $timeStart = 0;
1329                         $timeEnd   = time();
1330                         $numPages  = 1;
1331                         $page      = 1;
1332                         $timestamp = time(); */
1333                         $filter = ' WHERE 1 = 1 ';
1334                         $filter .= defined($entityName . '::JOB_QUEUE')
1335                                 ? ' AND a.queueStatus = 1 '
1336                                 : '';
1337                         $filter .= $entityName::ARCHIVE
1338                                 ? ' AND a.archived = 0 '
1339                                 : '';
1340                         if (method_exists($entityName, 'getSynchQuery'))
1341                         {
1342                                 $query = $em->createQuery(
1343                                                 $entityName::getSynchQuery()
1344                                                 );
1345                         }
1346                         else
1347                         {
1348                                 $query = $em->createQuery(
1349                                                 "SELECT a FROM $entityName a $filter ORDER BY a.id ASC"
1350                                 );
1351                         }
1352
1353                         $data = $query->getResult();
1354                         if (defined($entityName . '::JOB_QUEUE'))
1355                         {
1356                                 foreach ($data as $rowId => $record)
1357                                 {
1358                                         $data[$rowId] = $record->toQueueArray();
1359                                 }
1360                         }
1361                         else
1362                         {
1363                                 foreach ($data as $rowId => $record)
1364                                 {
1365                                         $data[$rowId] = $record->toSynchArray();
1366                                 }
1367                         }
1368                 }
1369                 else
1370                 {
1371                         $data = array();
1372                         /* $page = isset($this->request['page'])
1373                                 ? (int) $this->request['page']
1374                                 : 1;
1375                         $timeStart = isset($this->request['timeStart'])
1376                                 ? (int) $this->request['timeStart']
1377                                 : 0;
1378                         $timeEnd = isset($this->request['timeEnd'])
1379                                                 && 0 != $this->request['timeEnd']
1380                                 ? (int) $this->request['timeEnd']
1381                                 : time();
1382                         $recs = 1000; */
1383                         $version = isset($this->request['version'])
1384                                 ? (int) $this->request['version']
1385                                 : 0;
1386                         $version++;
1387                         $filter = '';
1388                         $filter .= defined($entityName . '::JOB_QUEUE')
1389                                 ? ' AND a.queueStatus = 1'
1390                                 : '';
1391                         $filter .= $entityName::ARCHIVE
1392                                 ? ' AND a.archived = 0'
1393                                 : '';
1394                         if (method_exists($entityName, 'getSynchFilter'))
1395                         {
1396                                 $synchMod = $entityName::getSynchFilter();
1397                         }
1398                         else
1399                         {
1400                                 $synchMod = array(
1401                                                 'Join' => '',
1402                                                 'Filter' => ''
1403                                 );
1404                         }
1405                         //$dateTimeFormat = \Utility\Definitions\Locale::getDateTimeFormat();
1406                         //$numRecs = 0;
1407
1408                         #-> Records to add.
1409                         $query = "SELECT [SELECTION] "
1410                                         . "FROM $entityName a "
1411                                         . $synchMod['Join']
1412                                         . "WHERE a.archived = :archived"
1413                                         . " $filter " . $synchMod['Filter']
1414                                         . " AND a.createVersion = :version"
1415                                         . " ORDER BY a.id ASC";
1416                         $params = array(
1417                                         'archived' => false,
1418                                         'version'  => $version
1419                                         /* 'timeStart' => date($dateTimeFormat, $timeStart),
1420                                         'timeEnd'   => date($dateTimeFormat, $timeEnd) */
1421                         );
1422                         /* $numRecsRes = $em->createQuery(
1423                                         str_replace('[SELECTION]', 'COUNT(a.id) AS total', $query)
1424                                         )
1425                                 ->setParameters($params)
1426                                 ->getSingleResult();
1427                         $numRecs = ($numRecsRes['total'] > $numRecs)
1428                                 ? $numRecsRes['total']
1429                                 : $numRecs; */
1430                         $data['Create'] = $em->createQuery(
1431                                         str_replace('[SELECTION]', 'a', $query)
1432                                         )
1433                                 ->setParameters($params)
1434                                 ->getResult();
1435                                 /* ->setFirstResult(($page -1) * $recs)
1436                                 ->setMaxResults($recs) */
1437
1438                         #-> Records to update.
1439                         $query = "SELECT [SELECTION] "
1440                                         . "FROM $entityName a "
1441                                         . $synchMod['Join']
1442                                         . "WHERE a.archived = :archived"
1443                                         . " $filter " . $synchMod['Filter']
1444                                         . " AND a.createVersion != :version"
1445                                         . " AND a.updateVersion = :version"
1446                                         . " ORDER BY a.id ASC";
1447                         $params = array(
1448                                         'archived'  => false,
1449                                         'version'  => $version
1450                                         /* 'timeStart' => date($dateTimeFormat, $timeStart),
1451                                         'timeEnd'   => date($dateTimeFormat, $timeEnd) */
1452                         );
1453                         /* $numRecsRes = $em->createQuery(
1454                                         str_replace('[SELECTION]', 'COUNT(a.id) AS total', $query)
1455                                         )
1456                                 ->setParameters($params)
1457                                 ->getSingleResult();
1458                         $numRecs = ($numRecsRes['total'] > $numRecs)
1459                                 ? $numRecsRes['total']
1460                                 : $numRecs; */
1461                         $data['Update'] = $em->createQuery(
1462                                         str_replace('[SELECTION]', 'a', $query)
1463                                         )
1464                                 ->setParameters($params)
1465                                 ->getResult();
1466                                 /* ->setFirstResult(($page -1) * $recs)
1467                                 ->setMaxResults($recs) */
1468
1469                         #-> Records to remove.
1470                         /* $query = "SELECT [SELECTION] "
1471                                         . "FROM $entityName a "
1472                                         . $synchMod['Join']
1473                                         . "WHERE a.archived = :archived"
1474                                         . " $filter " . $synchMod['Filter']
1475                                         . " AND a.created NOT BETWEEN :timeStart AND :timeEnd"
1476                                         . " AND a.updated BETWEEN :timeStart AND :timeEnd"
1477                                         . " ORDER BY a.id ASC";
1478                         $params = array(
1479                                         'archived'  => true,
1480                                         'timeStart' => date($dateTimeFormat, $timeStart),
1481                                         'timeEnd'   => date($dateTimeFormat, $timeEnd)
1482                         );
1483                         $numRecsRes = $em->createQuery(
1484                                         str_replace('[SELECTION]', 'COUNT(a.id) AS total', $query)
1485                                         )
1486                                 ->setParameters($params)
1487                                 ->getSingleResult();
1488                         $numRecs = ($numRecsRes['total'] > $numRecs)
1489                                 ? $numRecsRes['total']
1490                                 : $numRecs;
1491                         $data['Delete'] = $em->createQuery(
1492                                         str_replace('[SELECTION]', 'a', $query)
1493                                         )
1494                                 ->setParameters($params)
1495                                 ->setFirstResult(($page -1) * $recs)
1496                                 ->setMaxResults($recs)
1497                                 ->getResult(); */
1498                         $data['Delete'] = array();
1499                         if (empty($data['Create'])
1500                                 && empty($data['Update'])
1501                                 && empty($data['Delete']))
1502                         {
1503                                 $version--;
1504                         }
1505
1506
1507                         #-> Finalize.
1508                         if (defined($entityName . '::JOB_QUEUE'))
1509                         {
1510                                 foreach ($data as $type => $dataset)
1511                                 {
1512                                         foreach ($dataset as $rowId => $record)
1513                                         {
1514                                                 $data[$type][$rowId] = $record->toQueueArray();
1515                                         }
1516                                 }
1517                         }
1518                         else
1519                         {
1520                                 foreach ($data as $type => $dataset)
1521                                 {
1522                                         foreach ($dataset as $rowId => $record)
1523                                         {
1524                                                 $data[$type][$rowId] = $record->toSynchArray();
1525                                         }
1526                                 }
1527                         }
1528                 }
1529
1530                 return new \Zend\View\Model\JsonModel(array(
1531                                 'Meta' => array(
1532                                         'Task'         => 'GetDataset',
1533                                         'Status'       => 'Success',
1534                                         'StatusReason' => '',
1535                                         'DatasetName'  => $ds,
1536                                         'Strategy'     => $entityName::PULL_SYNCH_STRATEGY,
1537                                         'Version'      => $version
1538
1539                                 ),
1540                                 'Data' => $data
1541                 ));
1542         }
1543
1544         /**
1545          * Retrieve trade and retail from mmCode.
1546          * @return \Zend\View\Model\JsonModel
1547          */
1548         public function transunionFromMmcodeAction()
1549         {
1550                 if (!$this->initPost())
1551                 {
1552                         \Utility\Debug::errorLog('transunionFromMmcodeAction.Error', 'NO AUTH');
1553                         return new \Zend\View\Model\JsonModel(array(
1554                                         'Meta' => array(
1555                                                         'Task'         => 'TransunionFromMmcodeAction',
1556                                                         'Status'       => 'Exception',
1557                                                         'StatusReason' => 'Invalid session requested.',
1558                                                         'DatasetName'  => null
1559                                         ),
1560                                         'Data' => array()
1561                         ));
1562                 }
1563
1564                 if (!isset($this->request['mmCode']) || !is_numeric($this->request['mmCode'])
1565                         || !isset($this->request['vehicleYear']) || !is_numeric($this->request['vehicleYear']))
1566                 {
1567                         \Utility\Debug::errorLog('transunionFromMmcodeAction.Error', 'missing mmCode or vehicleYear');
1568                         return new \Zend\View\Model\JsonModel(array(
1569                                         'Meta' => array(
1570                                                         'Task'         => 'TransunionFromMmcodeAction',
1571                                                         'Status'       => 'Fail',
1572                                                         'StatusReason' => 'Requires `mmCode` and `vehicleYear`. Optionally accepts `mileage` and `condition`.'
1573                                         ),
1574                                         'Data' => array()
1575                         ));
1576                 }
1577                 $input = new \Workspace\Utility\ServiceInput('ParamSet', array(
1578                                 'Filter' => array(
1579                                                 'mmCode'      => $this->request['mmCode'],
1580                                                 'vehicleYear' => $this->request['vehicleYear'],
1581                                                 'mileage'     => isset($this->request['mileage']) && !empty($this->request['mileage'])
1582                                                                                         ? $this->request['mileage']
1583                                                                                         : null,
1584                                                 'condition'   => isset($this->request['condition']) && !empty($this->request['condition'])
1585                                                                                         ? $this->request['condition']
1586                                                                                         : null
1587                                 )
1588                 ));
1589                 $serviceInput = new \Workspace\Utility\ServiceInput('ServiceInput', array(
1590                                 'data' => $input->pack()
1591                 ));
1592                 $stockUtilService = $this->serviceLocator->get('Stock.Service.Utility');
1593                 $response = $stockUtilService->deviceTransUnionFromMmCode($serviceInput->pack());
1594                 return new \Zend\View\Model\JsonModel(array(
1595                                 'Meta' => array_merge(array('Task' => 'Login'), $response['Meta']),
1596                                 'Data' => $response['Data']
1597                 ));
1598         }
1599
1600 }