initial commit
[namibia] / module / Workspace / src / Workspace / Controller / WorkspaceController.php
1 <?php
2 namespace Workspace\Controller;
3
4
5 /*
6                                                    _
7                        /                            )
8                       (                             |\
9                      /|                              \\
10                     //                                \\
11                    ///                                 \|
12                   /( \                                  )\
13                   \\  \_                               //)
14                    \\  :\__                           ///
15                     \\     )                         // \
16                      \\:  /                         // |/
17                       \\ / \                       //  \
18                        /)   \     ___..-'         ((  \_|
19                       //     /  .'  _.'           \ \  \
20                      /|       \(  _\_____          \ | /
21                     (| _ _  __/          '-.       ) /.'
22                      \\ .  '-.__ \          \_    / / \
23                       \\_'.     > '-._   '.   \  / / /
24                        \ \      \     \    \   .' /.'
25                         \ \  '._ /     \  /   / .' |
26                          \ \_     \_   |    .'_/ __/
27                           \  \      \_ |   / /  _/ \_
28                            \  \       / _.' /  /     \
29                            \   |     /.'   / .'       '-,_
30                             \   \  .'   _.'_/             \
31                /\    /\      ) ___(    /_.'           \    |
32               | _\__// \    (.'      _/               |    |
33               \/_  __  /--'`    ,                   __/    /
34               (_ ) /b)  \  '.   :            \___.-:_/ \__/
35               /:/:  ,     ) :        (      /_.'_/-' |_ _ /
36              /:/: __/\ >  __,_.----.__\    /        (/(/(/
37             (_(,_/V .'/--'    _/  __/ |   /
38              VvvV  //`    _.-' _.'     \   \
39                n_n//     (((/->/        |   /
40                '--'         ~='          \  |
41                                           | |_,,,
42                                           \  \  /
43                                            '.__)
44
45            THERE BE DRAGONS HERE, DO NOT MESS WITH THIS CODE
46  */
47
48
49 class WorkspaceController extends \Zend\Mvc\Controller\AbstractActionController
50 {
51
52         /**
53          * @var \Zend\Session\Container
54          */
55         protected $session;
56         /**
57          * @var array
58          */
59         protected $request;
60         /**
61          * @var array
62          */
63         protected $response;
64         /**
65          * @var \Zend\ServiceManager\ServiceManager
66          */
67         protected $sm;
68         /**
69          * @var \Doctrine\ORM\EntityManager
70          */
71         protected $em;
72         /**
73          * @var boolean
74          */
75         protected $authenticated;
76         /**
77          * @var \User\Service\Authentication
78          */
79         protected $authDetails;
80
81
82
83         public function checkWsdlAction()
84         {
85                 exit();
86
87                 //$h="http://secureuat.decisionsystems.co.za/AISConvergedB2BService/AISConvergedB2BService.svc?singleWsdl";
88                 //$p="8000";
89
90
91                 /* $service = new \Zend\Soap\Client("/test/php/bassa.wsdl", array(
92                  "soap_version"   => SOAP_1_2,
93                                 "trace"      => 1,
94                                 "exceptions" => 1,
95                                 "location" => "http://".$h.":".$p)); */
96
97
98                 /* $client = new \Zend\Soap\Client("http://196.36.251.126/AISConvergedB2BService/AISConvergedB2BService.svc?wsdl", array(
99                  'soap_version' => SOAP_1_1
100                 )); */
101
102
103                 //$url = "http://secureuat.decisionsystems.co.za/AISConvergedB2BService/AISConvergedB2BService.svc?singleWsdl";
104         //        http://secureuat.decisionsystems.co.za/AISConvergedB2BWrapper/AISConvergedB2BWrapper.asmx?wsdl
105         //        https://autoinsight.transunion.co.za/AISConvergedB2BWrapper/AISConvergedB2BWrapper.asmx?wsdl
106 //
107                 $client =  new \Zend\Soap\Client("https://autotest.transunion.co.za/AISConvergedB2BWrapper/AISConvergedB2BWrapper.asmx?wsdl", array(
108                         'soap_version' => SOAP_1_1
109                         //'trace' => 1
110                         //'exception' => 0
111
112                 ));
113
114                 //$header     = new Zend\Soap\Header("http://www.example.com/webservices/", "APICredentials", $auth, false);
115
116                 // M)andatory/ (O)ptional /(C)onditional //trade and retail
117
118
119                 //$client->setHttpLogin('181306');
120                 //$client->setHttpPassword('PW181306#');
121                 //$client->setLocation("http://secureuat.decisionsystems.co.za/AISConvergedB2BService/AISConvergedB2BService.svc?singleWsdl");
122
123
124                 /*$res = $client->call("AISConvergedB2B", array(
125                                 'AISConvergedB2B' => array(
126                                                 'query' => array(
127                                                                 'ExtensionData'                 => null,
128                                                                 'ClientReference'               => "",
129                                                                 'Colour'                                => "GOLD",
130                                                                 'Condition'                     => "FAIR",
131                                                                 'CustomerProductId'     => 0,
132                                                                 'EngineNumber'                  => "2E5060747",
133                                                                 'GuideMonth'                    => 1,
134                                                                 'GuideYear'                     => 2014,
135                                                                 //'LoginId'                             => "181367",
136                                                                 'LoginId'                               => "171887",
137                                                                 'OptionCodeNew'                 => "0",
138                                                                 'OptionCodeUsed'                => "0",
139                                                                 //'Password'                            => "PW181367#",
140                                                                 'Password'                              => "PW171887#",
141                                                                 'RegistrationNumber'    => "SLD174GP",
142                                                                 'RegistrationYear'              => 2005,
143                                                                 'RequestorPerson'               => "Andre",
144                                                                 'RequestorTelNumber'    => "0",
145                                                                 'VehicleCode'                   => "22020110",
146                                                                 'VehicleMileage'                => 0,
147                                                                 'VinOrChasisNumber'     => "AHT54EE900A030001"
148                                                 )
149                                 )
150                 ));*/
151                 $res = $client->call("AISConvergedB2B", array(
152                                 'AISConvergedB2B' => array(
153                                                 'query' => array(
154                                                                 'ExtensionData'                 => null,
155                                                                 'ClientReference'               => "",
156                                                                 //'Colour'                              => "White",
157                                                                 'Condition'                     => "Good",
158                                                                 'CustomerProductId'     => 0,
159                                                                 'EngineNumber'                  => "G4HGBM370811",
160                                                                 'GuideMonth'                    => 5,
161                                                                 'GuideYear'                     => 2014,
162                                                                 'LoginId'                               => "181367",
163                                                                 'OptionCodeNew'                 => "0",
164                                                                 'OptionCodeUsed'                => "0",
165                                                                 'Password'                              => "PW181367#",
166                                                                 'RegistrationNumber'    => "NPN47328",
167                                                                 'RegistrationYear'              => 2012,
168                                                                 'RequestorPerson'               => "Andre",
169                                                                 'RequestorTelNumber'    => "0825732810",
170                                                                 'VehicleCode'                   => "26516101",
171                                                                 'VehicleMileage'                => 0,
172                                                                 'VinOrChasisNumber'     => "MALAN51BLCM020415"
173                                                 )
174                                 )
175                 ));
176                 /* $res = $client->call("AISConvergedB2B", array(
177                                 'AISConvergedB2B' => array(
178                                                 'query' => array(
179                                                                 'ExtensionData'                 => null,
180                                                                 'ClientReference'               => "",
181                                                                 'Colour'                                => "Silver",
182                                                                 'Condition'                     => "Good",
183                                                                 'CustomerProductId'     => 0,
184                                                                 'EngineNumber'                  => "CLP126405",
185                                                                 'GuideMonth'                    => 5,
186                                                                 'GuideYear'                     => 2014,
187                                                                 'LoginId'                               => "181367",
188                                                                 'OptionCodeNew'                 => "0",
189                                                                 'OptionCodeUsed'                => "0",
190                                                                 'Password'                              => "PW181367#",
191                                                                 'RegistrationNumber'    => "CJ28TLGP",
192                                                                 'RegistrationYear'              => 2013,
193                                                                 'RequestorPerson'               => "Andre",
194                                                                 'RequestorTelNumber'    => "0825732810",
195                                                                 'VehicleCode'                   => "26516101",
196                                                                 'VehicleMileage'                => 0,
197                                                                 'VinOrChasisNumber'     => "AAVZZZ6SZDU019961"
198                                                 )
199                                 )
200                 )); */
201                 \Utility\Debug::errorLog('test', $res->AISConvergedB2BResult);
202                 //echo 'Please check the php error log :)';
203                 /* echo '<pre>';
204                 var_dump($res->AISConvergedB2BResult);
205                 echo '</pre>'; */
206
207                 //var_dump($client->getFunctions());
208                 exit();
209
210         }
211
212
213
214
215
216
217         public function imageUploadAction()
218         {
219                 \Utility\Registry::setServiceManager($this->serviceLocator);
220                 \Utility\Registry::addDynamicConfig(
221                                 \Utility\Cache::fetchEntity(
222                                                 'Config\Entity\Config', 1, \Utility\Registry::getEntityManager(), 600
223                                 )
224                 );
225                 $upload = new \Utility\Upload\Image();
226                 exit();
227         }
228
229
230         public function documentUploadAction()
231         {
232                 \Utility\Registry::setServiceManager($this->serviceLocator);
233                 \Utility\Registry::addDynamicConfig(
234                                 \Utility\Cache::fetchEntity(
235                                                 'Config\Entity\Config', 1, \Utility\Registry::getEntityManager(), 600
236                                 )
237                 );
238                 $upload = new \Utility\Upload\Document();
239                 exit();
240         }
241
242         public function attachmentUploadAction()
243         {
244                 \Utility\Registry::setServiceManager($this->serviceLocator);
245                 \Utility\Registry::addDynamicConfig(
246                                 \Utility\Cache::fetchEntity(
247                                                 'Config\Entity\Config', 1, \Utility\Registry::getEntityManager(), 600
248                                 )
249                 );
250                 $upload = new \Utility\Upload\Attachment();
251                 exit();
252         }
253
254         public function init()
255         {
256                 $this->getServiceLocator()->get('Application')->getEventManager()->attach(\Zend\Mvc\MvcEvent::EVENT_RENDER, function($event){
257                         $event->getResponse()->getHeaders()->addHeaderLine('Content-Type', 'application/json');
258                 }, -10000);
259         }
260
261
262         /**
263          * Retrieve workspace manager.
264          */
265         public function initJson()
266         {
267                 $this->init();
268                 define('APPLICATION', 'Portal');
269                 $this->session = new \Zend\Session\Container(__CLASS__);
270                 isset($this->session->hashLog)
271                         || $this->session->hashLog = array();
272                 $this->request = json_decode(file_get_contents('php://input'), true);
273                 if (is_null($this->request))
274                 {
275                         $this->initPost();
276                         return;
277                 }
278                 $this->response = array();
279                 $this->authenticated = \Utility\Registry::isAuthenticated();
280                 if ($this->authenticated)
281                 {
282                         $this->authDetails = \Utility\Registry::getAuthData();
283                 }
284                 \Utility\Registry::setServiceManager($this->serviceLocator);
285                 \Utility\Registry::addDynamicConfig(
286                                 \Utility\Cache::fetchEntity(
287                                                 'Config\Entity\Config', 1, \Utility\Registry::getEntityManager(), 600
288                                 )
289                 );
290         }
291
292         public function banner1Action()
293         {
294                 \Utility\Registry::setServiceManager($this->serviceLocator);
295                 $click = new \Statistical\Entity\Click();
296                 $click->bannerId = 'Home: Banner 1 (Left)';
297                 $click->ipAddress = $_SERVER['REMOTE_ADDR'];
298                 $click->created = new \DateTime("now");
299                 $em = \Utility\Registry::getEntityManager();
300                 $em->persist($click);
301                 $em->flush();
302                 header('Location: http://www.combinefreight.co.za');
303                 exit();
304         }
305
306         public function banner2Action()
307         {
308                 \Utility\Registry::setServiceManager($this->serviceLocator);
309                 $click = new \Statistical\Entity\Click();
310                 $click->bannerId = 'Home: Banner 2 (Right)';
311                 $click->ipAddress = $_SERVER['REMOTE_ADDR'];
312                 $click->created = new \DateTime("now");
313                 $em = \Utility\Registry::getEntityManager();
314                 $em->persist($click);
315                 $em->flush();
316                 header('Location: http://www.combinefreight.co.za');
317                 exit();
318         }
319
320         public function checkUniqueEmailAction()
321         {
322                 header('Expires: Fri, 26 Nov 1976 05:00:00 GMT');
323                 header('Cache-Control: no-cache, must-revalidate');
324                 header("Pragma: no-cache");
325                 header('Content-type: application/json; charset=utf-8');
326                 $request = array_merge($_POST, $_GET);
327                 if (!isset($request['email']))
328                 {
329                         echo \Zend\Json\Json::encode('Email address is required.');
330                         exit();
331                 }
332                 $email = $request['email'];
333                 \Utility\Registry::setServiceManager($this->serviceLocator);
334                 $em = \Utility\Registry::getEntityManager();
335                 $entry = $em->getRepository('\User\Entity\Profile')
336                         ->findOneBy(array('email' => $email));
337                 echo \Zend\Json\Json::encode(
338                         is_null($entry)
339                                 ? true
340                                 : 'Email address already in use.'
341                 );
342                 exit();
343         }
344
345         public function checkUniqueCompanyAction()
346         {
347                 header('Expires: Fri, 26 Nov 1976 05:00:00 GMT');
348                 header('Cache-Control: no-cache, must-revalidate');
349                 header("Pragma: no-cache");
350                 header('Content-type: application/json; charset=utf-8');
351                 $request = array_merge($_POST, $_GET);
352                 if (!isset($request['name']))
353                 {
354                         echo \Zend\Json\Json::encode('Company name is required.');
355                         exit();
356                 }
357                 $name = $request['name'];
358                 \Utility\Registry::setServiceManager($this->serviceLocator);
359                 $em = \Utility\Registry::getEntityManager();
360                 $entry = $em->getRepository('\Company\Entity\Company')
361                         ->findOneBy(array('name' => $name));
362                 echo \Zend\Json\Json::encode(
363                         is_null($entry)
364                                 ? true
365                                 : 'Company name already in use.'
366                 );
367                 exit();
368         }
369
370         /**
371          * Retrieve workspace manager.
372          */
373         public function initPost()
374         {
375                 $this->session = new \Zend\Session\Container(__CLASS__);
376                 isset($this->session->hashLog)
377                         || $this->session->hashLog = array();
378                 $this->request = array($_POST);
379                 $this->response = array();
380                 $this->authenticated = \Utility\Registry::isAuthenticated();
381                 if ($this->authenticated)
382                 {
383                         $this->authDetails = \Utility\Registry::getAuthData();
384                 }
385                 \Utility\Registry::setServiceManager($this->serviceLocator);
386                 \Utility\Registry::addDynamicConfig(
387                                 \Utility\Cache::fetchEntity(
388                                                 'Config\Entity\Config', 1, \Utility\Registry::getEntityManager(), 600
389                                 )
390                 );
391         }
392
393         /**
394          * Convenience method to extract parameters from request packet.
395          * @param integer $requestId
396          * @param string $paramName
397          * @param unknown $default
398          * @return unknown
399          */
400         protected function reqParam($requestId, $paramName, $default = null)
401         {
402                 return isset($this->request[$requestId][$paramName])
403                         ? $this->request[$requestId][$paramName]
404                         : $default;
405         }
406
407
408
409         /**
410          * Display list of tasks for specified workflows.
411          * @see \Zend\Mvc\Controller\AbstractActionController::indexAction()
412          * @return \Zend\View\Model\ViewModel
413          */
414         public function indexAction()
415         {
416                 $this->initJson();
417
418                 #-> Input format safety check.
419                 if (!is_array($this->request))
420                 {
421                         return new \Zend\View\Model\JsonModel(array(
422                                         'Status' => 'Exception',
423                                         'StatusReason' => 'This api call requires an array of Workflow names as input.'
424                         ));
425                 }
426
427                 #-> Process requests.
428                 foreach ($this->request as $requestId => $request)
429                 {
430                         #-> Collect basic data.
431                         if (is_array($request))
432                         {
433                                 list($workflow, $state) = each($request);
434                         }
435                         else
436                         {
437                                 $workflow = $request;
438                                 $state = 'Global';
439                         }
440
441                         #-> Safety check.
442                         if (!$workflow)
443                         {
444                                 $this->response[$requestId]['Status'] = 'Exception';
445                                 $this->response[$requestId]['StatusReason'] = 'Malformed server request. No Workflow name provided.';
446                                 continue;
447                         }
448                         $this->response[$requestId] = array();
449
450                         #-> Retrieve task list.
451                         try
452                         {
453                                 $wf = $this->getServiceLocator()->get($workflow);
454                                 $this->response[$requestId] = array_merge(
455                                                 $this->response[$requestId],
456                                                 $wf->listStateTasks($state)
457                                                 );
458                         }
459                         catch (\Exception $e)
460                         {
461                                 $this->response[$requestId]['Status'] = 'Exception';
462                                 $this->response[$requestId]['StatusReason'] = 'Invalid Workflow requested.';
463                                 $this->response[$requestId]['Exception'] = "$e";
464                         }
465                 }
466                 return new \Zend\View\Model\JsonModel($this->response);
467         }
468
469         /**
470          * Negotiate task contract(s).
471          * @return \Zend\View\Model\JsonModel
472          */
473         protected function contract($type)
474         {
475                 $this->initJson();
476
477                 #-> Input format safety check.
478                 if (!is_array($this->request))
479                 {
480                         return new \Zend\View\Model\JsonModel(array(
481                                         'Status' => 'Exception',
482                                         'StatusReason' => 'This api call requires an array of Contract Request Items as input.'
483                         ));
484                 }
485
486                 #-> Process requests.
487                 foreach ($this->request as $requestId => $request)
488                 {
489                         #-> Collect basic data.
490                         $workflow = $this->reqParam($requestId, 'Workspace', false);
491                         $jobId = $this->reqParam($requestId, 'JobId', null);
492                         $task = $this->reqParam($requestId, $type, false);
493                         $packet = $this->reqParam($requestId, 'Packet', array());
494                         !is_null($jobId)
495                                 && 0 < $jobId
496                                 && !isset($packet['id'])
497                                 && $packet['id'] = $jobId;
498
499                         #-> Safety check.
500                         if (!$workflow || !$task)
501                         {
502                                 $this->response[$requestId]['Status'] = 'Exception';
503                                 $this->response[$requestId]['StatusReason'] = 'Malformed server request. Parameters `Workspace` and `' . $type . '` required.';
504                                 continue;
505                         }
506                         $hash = md5(serialize($request) . '.Contract');
507                         $this->response[$requestId] = array(
508                                         'Workflow' => $workflow,
509                                         $type => $task,
510                                         'Hash' => $hash
511                         );
512
513                         #-> Refine data.
514                         $taskParts = explode('.', $task);
515                         $theme = $taskParts[0];
516                         $action = isset($taskParts[1])
517                                 ? $taskParts[1]
518                                 : 'Index';
519
520                         #-> Store contract request
521                         $this->session->hashLog[$hash] = array(
522                                 'Workspace' => $workflow,
523                                 'Type'    => $type,
524                                 'JobId'  => $jobId,
525                                 'Theme'  => $theme,
526                                 'Action'        => $action,
527                                 'Packet'        => $packet,
528                                 'LifeTime'  => 'UseOnce'
529                         );
530
531                         #-> Retrieve contract.
532                         $action = 'contract' . $action;
533                         try
534                         {
535                                 $wf = $this->getServiceLocator()->get($workflow);
536                                 if ('Task' == $type)
537                                 {
538                                         $contract = $wf
539                                                 ->contractTask($task, $jobId, $packet)
540                                                 ->package();
541                                 }
542                                 else
543                                 {
544                                         $contract = $wf
545                                                 ->contractRoute($task, $jobId, $packet)
546                                                 ->package();
547                                 }
548                                 $this->session->hashLog[$hash] = array_merge($this->session->hashLog[$hash], $contract);
549                                 $this->response[$requestId] = array_merge(
550                                                 $this->response[$requestId],
551                                                 $contract
552                                 );
553                         }
554                         catch (\Exception $e)
555                         {
556                                 unset($this->response[$requestId]['Hash']);
557                                 $this->response[$requestId]['Status'] = 'Exception';
558                                 $this->response[$requestId]['StatusReason'] = $e->getMessage();
559                                 $this->response[$requestId]['Exception']        = "$e";
560                                 unset($this->session->hashLog[$hash]);
561                         }
562                 }
563                 return new \Zend\View\Model\JsonModel($this->response);
564         }
565
566         /**
567          * Execute contracted task(s).
568          * @return \Zend\View\Model\JsonModel
569          */
570         public function execute($type)
571         {
572                 $this->initJson();
573
574                 #-> Input format safety check.
575                 if (!is_array($this->request))
576                 {
577                         return new \Zend\View\Model\JsonModel(array(
578                                         'Status' => 'Exception',
579                                         'StatusReason' => 'This api call requires an array of Contract Execution Items as input.'
580                         ));
581                 }
582
583                 #-> Process requests.
584                 foreach ($this->request as $requestId => $request)
585                 {
586                         #-> Collect basic data.
587                         $hash   = $this->reqParam($requestId, 'Contract', false);
588                         $packet  = $this->reqParam($requestId, 'Packet', array());
589                         $options = $this->reqParam($requestId, 'Options', array());
590
591 //                      error_log('$hash: ' . $hash);
592                         
593                         #-> Safety checks.
594                         if (!$hash)
595                         {
596                                 $this->response[$requestId]['Status'] = 'Exception';
597                                 $this->response[$requestId]['StatusReason'] = 'Malformed server request. Parameter `Contract` required.';
598                                 continue;
599                         }
600                         if (!isset($this->session->hashLog[$hash]))
601                         {
602                                 $this->response[$requestId]['Status'] = 'Exception';
603                                 $this->response[$requestId]['StatusReason'] = 'Invalid contract request. No such contract found for execution.';
604                                 continue;
605                         }
606                         if ($type != $this->session->hashLog[$hash]['Type'])
607                         {
608                                 $this->response[$requestId]['Status'] = 'Exception';
609                                 $this->response[$requestId]['StatusReason'] = 'Call type mismatch, contract is of type '
610                                                 . $this->session->hashLog[$hash]['Type'] . '.';
611                         }
612                         $this->response[$requestId] = array();
613
614                         try
615                         {
616                                 #-> Validate contract.
617                                 $packet = array_merge(
618                                                 $packet,
619                                                 $this->session->hashLog[$hash]['Packet']
620                                                 );
621                                 $contractClass = '\\Workspace\\Contract\\' . $this->session->hashLog[$hash]['LifeTime'];
622                                 $contract         = new $contractClass(null, null, $this->session->hashLog[$hash], $packet, $options);
623                                 $workflow         = $this->session->hashLog[$hash]['Workspace'];
624                                 $jobId           = $this->session->hashLog[$hash]['JobId'];
625                                 $theme           = $this->session->hashLog[$hash]['Theme'];
626                                 $action         = $this->session->hashLog[$hash]['Action'];
627                                 $wf                     = $this->getServiceLocator()->get($workflow);
628                                 if (!$contract->isValid($wf))
629                                 {
630                                         $this->response[$requestId]['Status']      = 'Exception';
631                                         $this->response[$requestId]['StatusReason'] = 'Input validation errors.';
632                                         $this->response[$requestId]['Messages']  = $contract->getMessages();
633                                         continue;
634                                 }
635
636                                 #-> Execute contract.
637                                 if ('Task' == $type)
638                                 {
639                                         $this->response[$requestId] = array_merge(
640                                                         $this->response[$requestId],
641                                                         $wf->executeTask(
642                                                                 "$theme.$action",
643                                                                 $jobId,
644                                                                 $contract->getSignedContract($requestId, $hash)
645                                                                 )
646                                                         );
647                                 }
648                                 else
649                                 {
650                                         $this->response[$requestId] = array_merge(
651                                                         $this->response[$requestId],
652                                                         $wf->executeRoute(
653                                                                 "$theme.$action",
654                                                                 $jobId,
655                                                                 $contract->getSignedContract($requestId, $hash)
656                                                         )
657                                         );
658                                 }
659                                 if ($this->session->hashLog[$hash]['LifeTime'] == 'UseOnce' && 'Success' == $this->response[$requestId]['Status'])
660                                 {
661                                         #-> Contract fulfilled and expired.
662                                         unset($this->session->hashLog[$hash]);
663                                 }
664                         }
665                         catch (\Exception $e)
666                         {
667                                 #-> Oops, something went wrong.
668                                 $this->response[$requestId]['Status']      = 'Exception';
669                                 $this->response[$requestId]['StatusReason'] = $e->getMessage();
670                                 $this->response[$requestId]['Exception']        = "$e";
671                         }
672                 }
673                 return new \Zend\View\Model\JsonModel($this->response);
674         }
675
676         /**
677          * Execute direct task(s).
678          * @return \Zend\View\Model\JsonModel
679          */
680         public function executeDirect($type)
681         {
682                 $this->initJson();
683
684                 #-> Input format safety check.
685                 if (!is_array($this->request))
686                 {
687                         return new \Zend\View\Model\JsonModel(array(
688                                         'Status' => 'Exception',
689                                         'StatusReason' => 'This api call requires an array of Contract Request Items as input.'
690                         ));
691                 }
692
693                 #-> Process requests.
694                 foreach ($this->request as $requestId => $request)
695                 {
696                         #-> Collect basic data.
697                         $workflow = $this->reqParam($requestId, 'Workspace', false);
698                         $jobId = $this->reqParam($requestId, 'JobId', null);
699                         $task = $this->reqParam($requestId, $type, false);
700                         $packet = $this->reqParam($requestId, 'Packet', array());
701
702                         #-> Safety check.
703                         if (!$workflow || !$task)
704                         {
705                                 $this->response[$requestId]['Status'] = 'Exception';
706                                 $this->response[$requestId]['StatusReason'] = 'Malformed server request. Parameters `Workspace` and `' . $type . '` required.';
707                                 continue;
708                         }
709                         $hash = md5(serialize($request) . '.Contract');
710                         $this->response[$requestId] = array(
711                                         'Workflow' => $workflow,
712                                         $type => $task,
713                                         'Hash' => $hash
714                         );
715
716                         #-> Refine data.
717                         $taskParts = explode('.', $task);
718                         $theme = $taskParts[0];
719                         $action = isset($taskParts[1])
720                                 ? $taskParts[1]
721                                 : 'Index';
722
723                         #-> Retrieve contract.
724                         $action = 'contract' . $action;
725                         try
726                         {
727                                 $wf = $this->getServiceLocator()->get($workflow);
728                                 if ('Route' == $type)
729                                 {
730                                         $contract = $wf
731                                                 ->directRoute($task, $jobId);
732                                 }
733                                 else
734                                 {
735                                         return new \Zend\View\Model\JsonModel(array(
736                                                         'Status' => 'Exception',
737                                                         'StatusReason' => 'Direct execution only allowed on Routes.'
738                                         ));
739                                 }
740                                 $this->response[$requestId] = array_merge(
741                                                 $this->response[$requestId],
742                                                 $contract
743                                 );
744                         }
745                         catch (\Exception $e)
746                         {
747                                 unset($this->response[$requestId]['Hash']);
748                                 $this->response[$requestId]['Status'] = 'Exception';
749                                 $this->response[$requestId]['StatusReason'] = $e->getMessage();
750                         }
751                 }
752                 return new \Zend\View\Model\JsonModel($this->response);
753
754         }
755
756         /**
757          * Negotiate task contract(s).
758          * @return \Zend\View\Model\JsonModel
759          */
760         public function contractTaskAction()
761         {
762                 return $this->contract('Task');
763         }
764
765         /**
766          * Execute task contract(s).
767          * @return \Zend\View\Model\JsonModel
768          */
769         public function executeTaskAction()
770         {
771                 return $this->execute('Task');
772         }
773
774         /**
775          * Execute direct task(s).
776          * @return \Zend\View\Model\JsonModel
777          */
778         public function directTaskAction()
779         {
780                 return $this->executeDirect('Task');
781         }
782
783         /**
784          * Negotiate route contract(s).
785          * @return \Zend\View\Model\JsonModel
786          */
787         public function contractRouteAction()
788         {
789                 return $this->contract('Route');
790         }
791
792         /**
793          * Execute route contract(s).
794          * @return \Zend\View\Model\JsonModel
795          */
796         public function executeRouteAction()
797         {
798                 return $this->execute('Route');
799         }
800
801         /**
802          * Execute direct route(s).
803          * @return \Zend\View\Model\JsonModel
804          */
805         public function directRouteAction()
806         {
807                 return $this->executeDirect('Route');
808         }
809
810         /**
811          * Cancel task contract(s).
812          * @return \Zend\View\Model\JsonModel
813          */
814         public function negateAction()
815         {
816                 $this->initJson();
817
818                 #-> Input format safety check.
819                 if (!is_array($this->request))
820                 {
821                         return new \Zend\View\Model\JsonModel(array(
822                                         'Status'           => 'Exception',
823                                         'StatusReason' => 'This api call requires an array of Contract Identifiers.'
824                         ));
825                 }
826
827                 #-> Process requests.
828                 foreach ($this->request as $requestId => $hash)
829                 {
830                         #-> Safety checks.
831                         if (!$hash)
832                         {
833                                 $this->response[$requestId]['Status']      = 'Exception';
834                                 $this->response[$requestId]['StatusReason'] = 'Malformed server request. Contract Identifier required.';
835                                 continue;
836                         }
837                         if (!isset($this->session->hashLog[$hash]))
838                         {
839                                 $this->response[$requestId]['Status']      = 'Exception';
840                                 $this->response[$requestId]['StatusReason'] = 'Invalid contract request. No such contract found.';
841                                 continue;
842                         }
843                         $this->response[$requestId] = array();
844
845                         #-> Contract cancelled.
846                         unset($this->session->hashLog[$hash]);
847                         $this->response[$requestId]['Status'] = 'Success';
848                 }
849                 return new \Zend\View\Model\JsonModel($this->response);
850         }
851
852         /**
853          * Validate unique value for a specified field.
854          * @return \Zend\View\Model\JsonModel
855          */
856         public function validateUniqueFieldAction()
857         {
858                 $this->initJson();
859
860                 #-> Input format safety check.
861                 is_array($this->request)
862                         && !empty($this->request)
863                         && $this->request = $this->request[0];
864                 if (!is_array($this->request)
865                         || !isset($this->request['Workspace'])
866                         || !isset($this->request['Group'])
867                         || !isset($this->request['Field'])
868                         || !isset($this->request['Value']))
869                 {
870                         return new \Zend\View\Model\JsonModel(array(
871                                         'Status' => 'Exception',
872                                         'StatusReason' => 'This api call requires an array with `Workspace`, `Group`, `Field` and `Value` parameters set.'
873                         ));
874                 }
875
876                 #-> Process request.
877                 try
878                 {
879                         $contract = new \Workspace\Utility\ServiceInput('Contract', array(
880                                                 'Group' => $this->request['Group'],
881                                                 'Field' => $this->request['Field'],
882                                                 'Value' => $this->request['Value'],
883                                                 'Id'    => isset($this->request['Id'])
884                                                                         ? $this->request['Id']
885                                                                         : 0
886                                 ));
887                         $this->response = $this->getServiceLocator()
888                                 ->get($this->request['Workspace'])
889                                 ->fieldIsUnique($contract->pack());
890
891                 }
892                 catch (\Exception $e)
893                 {
894                         #-> Oops, something went wrong.
895                         $this->response['Status'] = 'Exception';
896                         $this->response['StatusReason'] = 'Invalid Workflow requested.';
897                         $this->response['Exception'] = "$e";
898                 }
899                 return new \Zend\View\Model\JsonModel($this->response);
900         }
901
902         /**
903          * Validate unique value for a specified field.
904          * @return \Zend\View\Model\JsonModel
905          */
906         public function validateUniqueFieldDirectAction()
907         {
908                 $this->initJson();
909
910                 #-> Input format safety check.
911                 is_array($this->request)
912                         && !empty($this->request)
913                         && $this->request = $this->request[0];
914                 if (!is_array($this->request)
915                         || !isset($this->request['Workspace'])
916                         || !isset($this->request['Group'])
917                         || !isset($this->request['Field'])
918                         || !isset($this->request['Value']))
919                 {
920                         return new \Zend\View\Model\JsonModel(array(
921                                         'Status' => 'Exception',
922                                         'StatusReason' => 'This api call requires an array with `Workspace`, `Group`, `Field` and `Value` parameters set.'
923                         ));
924                 }
925
926                 #-> Process request.
927                 try
928                 {
929                         $contract = new \Workspace\Utility\ServiceInput('Contract', array(
930                                                 'Group' => $this->request['Group'],
931                                                 'Field' => $this->request['Field'],
932                                                 'Value' => $this->request['Value'],
933                                                 'Id'    => isset($this->request['Id'])
934                                                                         ? $this->request['Id']
935                                                                         : 0
936                                 ));
937                         $this->response = $this->getServiceLocator()
938                                 ->get($this->request['Workspace'])
939                                 ->fieldIsUnique($contract->pack());
940                         if ('Success' == $this->response['Status'])
941                         {
942                                 header('Expires: Fri, 26 Nov 1976 05:00:00 GMT');
943                                 header('Cache-Control: no-cache, must-revalidate');
944                                 header("Pragma: no-cache");
945                                 header('Content-type: application/json; charset=utf-8');
946                                 echo \Zend\Json\Json::encode(true);
947                                 exit();
948                         }
949
950                 }
951                 catch (\Exception $e)
952                 {
953                         #-> Oops, something went wrong.
954                         $this->response['Status'] = 'Exception';
955                         $this->response['StatusReason'] = 'Invalid Workflow requested.';
956                         $this->response['Exception'] = "$e";
957                 }
958                 return new \Zend\View\Model\JsonModel($this->response);
959         }
960
961         protected function createEntry($entityName, $data)
962         {
963                 $item = new $entityName();
964                 $item->fromArray($data);
965                 $this->em->persist($item);
966                 $this->em->flush();
967                 return $item->id;
968         }
969
970         protected function updateEntry($entityName, $id, $data)
971         {
972                 $item = $this->em
973                         ->getRepository($entityName)
974                         ->find($id)
975                         ->fromArray($data);
976                 $this->em->flush();
977         }
978
979         public function contactRequestAction()
980         {
981                 $this->initJson();
982                 $this->request = isset($this->request[0])
983                         ? $this->request[0]
984                         : $this->request;
985
986                 $params = array(
987                         'personName'    => $this->request['name'],
988                         'tradingName'   => $this->request['company'],
989                         'email'                 => $this->request['email'],
990                         'mobile'                => $this->request['mobile'],
991                         'telephone'     => $this->request['telephone'],
992                         'subject'               => $this->request['subject'],
993                         'message'               => $this->request['message']
994                 );
995
996                 $oNotify = new \Utility\Comms\Notification();
997                 $oNotify->sendFromTemplate(
998                                 null, null, null, null,
999                                 'info@bid4cars.co.za',
1000                                 null, null, 'contact-rquest', $params
1001                 );
1002                 $oNotify->sendFromTemplate(
1003                                 null, null, null, null,
1004                                 'mohau@bid4cars.co.za',
1005                                 null, null, 'contact-rquest', $params
1006                 );
1007                 $oNotify->sendFromTemplate(
1008                                 null, null, null, null,
1009                                 'dineo@bid4cars.co.za',
1010                                 null, null, 'contact-rquest', $params
1011                 );
1012                 $oNotify->sendFromTemplate(
1013                                 null, null, null, null,
1014                                 'cearahw@hyundai.co.za',
1015                                 null, null, 'contact-rquest', $params
1016                 );
1017
1018                 return new \Zend\View\Model\JsonModel(array('Status' => 'Success'));
1019         }
1020
1021         public function contactRequestCcAction()
1022         {
1023                 $this->initJson();
1024                 $this->request = isset($this->request[0])
1025                         ? $this->request[0]
1026                         : $this->request;
1027
1028                 $params = array(
1029                         'personName'    => $this->request['name'],
1030                         'tradingName'   => $this->request['company'],
1031                         'email'                 => $this->request['email'],
1032                         'mobile'                => $this->request['mobile'],
1033                         'telephone'     => $this->request['telephone'],
1034                         'subject'               => $this->request['subject'],
1035                         'message'               => $this->request['message']
1036                 );
1037
1038                 $oNotify = new \Utility\Comms\Notification();
1039 //              $oNotify->sendFromTemplate(
1040 //                              null, null, null, null,
1041 //                              'info@bid4cars.co.za',
1042 //                              null, null, 'contact-rquest', $params
1043 //              );
1044
1045                 if('1'==$this->request['company'] ){
1046                         $oNotify->sendFromTemplate(
1047                                 null, null, null, null,
1048                                 'thinus@wepay4cars.co.za',
1049                                 null, null, 'contact-rquest', $params
1050                         );
1051                 }
1052                 if('2'==$this->request['company'] ){
1053                         $oNotify->sendFromTemplate(
1054                                 null, null, null, null,
1055                                 'bronson@wepay4cars.co.za',
1056                                 null, null, 'contact-rquest', $params
1057                         );
1058                 }
1059
1060                 return new \Zend\View\Model\JsonModel(array('Status' => 'Success'));
1061         }
1062
1063         public function importTuCsvAction()
1064         {
1065                 set_time_limit(0);
1066                 \Utility\Registry::setServiceManager($this->serviceLocator);
1067                 $this->em = \Utility\Registry::getEntityManager();
1068                 $categoryMap = array(
1069                                 'T' => 1,
1070                                 'A' => 2,
1071                                 'C' => 3,
1072                                 'B' => 4,
1073                                 'M' => 5,
1074                                 'H' => 6,
1075                                 'Z' => 7
1076                 );
1077                 $years = array();
1078                 $i = 1;
1079                 for ($y = 1970; $y < 2014; $y++)
1080                 {
1081                         $years[$y] = $i;
1082                         $i++;
1083                 }
1084                 $makes  = array();
1085                 $models = array();
1086                 $types  = array();
1087
1088                 #-> Load in csv data, BOORAH!!!!
1089                 $csvToFieldMap = array(
1090                                 'mmCode', 'make', 'model', 'type', 'category',
1091                                 'cylinders', 'cubicCapacity', 'kilowatts',
1092                                 'bodyType', 'doors', 'intro_date', 'disc_date'
1093                 );
1094                 $numericFields = array('cylinders', 'cubicCapacity', 'kilowatts', 'doors');
1095                 $handle = fopen(__DIR__ . '/../../../../../data/Transunion20130624.csv', "r");
1096                 $data = fgetcsv($handle);
1097
1098
1099                 #-> Handle csv data.
1100                 while (($data = fgetcsv($handle)) !== false)
1101                 {
1102                         $packet = array();
1103                         foreach ($csvToFieldMap as $index => $field)
1104                         {
1105                                 $packet[$field] = $data[$index];
1106                                 if (in_array($field, $numericFields))
1107                                 {
1108                                         $packet[$field] = ('' == $packet[$field])
1109                                                 ? null
1110                                                 : $packet[$field];
1111                                 }
1112                         }
1113                         $packet['name'] = $packet['type'];
1114                         list($imonth, $iyear) = explode('/', $packet['intro_date']);
1115                         if ($iyear < 1970)
1116                         {
1117                                 continue;
1118                         }
1119                         $dyear = false;
1120                         !empty($packet['disc_date'])
1121                                 && list($dmonth, $dyear) = explode('/', $packet['disc_date']);
1122                         unset($packet['intro_date']);
1123                         unset($packet['disc_date']);
1124                         $packet['introYear'] = $this->em->getReference(
1125                                         '\Stock\Entity\Year', $years[$iyear]
1126                                         );
1127                         $packet['introMonth'] = $imonth;
1128                         if ($dyear)
1129                         {
1130                                 $packet['discYear'] = $this->em->getReference(
1131                                                 '\Stock\Entity\Year', $years[$dyear]
1132                                 );
1133                                 $packet['discMonth'] = $dmonth;
1134                         }
1135
1136                         if (!isset($makes[$packet['make']]))
1137                         {
1138                                 $makeId = $this->createEntry('\Stock\Entity\Make', array(
1139                                                 'name' => $packet['make']
1140                                 ));
1141                                 $makes[$packet['make']] = $makeId;
1142                         }
1143                         else
1144                         {
1145                                 $makeId = $makes[$packet['make']];
1146                         }
1147
1148                         if (!isset($models[$makeId]) || !isset($models[$makeId][$packet['model']]))
1149                         {
1150                                 isset($models[$makeId])
1151                                         || $models[$makeId] = array();
1152                                 $modelId = $this->createEntry('\Stock\Entity\Model', array(
1153                                                 'make' => $this->em->getReference('\Stock\Entity\Make', $makeId),
1154                                                 'name' => $packet['model']
1155                                 ));
1156                                 $models[$makeId][$packet['model']] = $modelId;
1157                         }
1158                         else
1159                         {
1160                                 $modelId = $models[$makeId][$packet['model']];
1161                         }
1162                         $packet['category'] = $this->em->getReference(
1163                                         '\Stock\Entity\Category', $categoryMap[$packet['category']]
1164                                         );
1165                         $packet['model'] = $this->em->getReference('\Stock\Entity\Model', $modelId);
1166                         $this->createEntry('\Stock\Entity\Type', $packet);
1167                 }
1168         }
1169
1170
1171     public function completeValuationGetCustomerAction()
1172     {
1173         $this->initJson();
1174
1175         $this->request = json_decode(file_get_contents('php://input'), true);
1176         if (is_null($this->request))
1177         {
1178             $this->initPost();
1179             return;
1180         }
1181
1182         if('' != $this->request['customerHash'])
1183         {
1184             \Utility\Registry::setServiceManager($this->serviceLocator);
1185             $this->em = \Utility\Registry::getEntityManager();
1186
1187             $customerPublicValuationEntry = $this->em->getRepository('\\Valuation\\Entity\\CustomerPublicValuation')
1188                 ->findOneBy(array(
1189                     'customerHash'              => $this->request['customerHash'],
1190                     'archived'                  => false
1191                 ));
1192
1193             if(!is_null($customerPublicValuationEntry))
1194             {
1195                 return new \Zend\View\Model\JsonModel(array('Success' => array('valuationId' => $customerPublicValuationEntry->valuation->id)));
1196             }
1197
1198
1199         }
1200
1201
1202         return new \Zend\View\Model\JsonModel(array('Error' => "Could not find customer hash"));
1203     }
1204
1205     public function populateCompleteValuationAppointmentTableAction()
1206     {
1207         $this->initJson();
1208
1209         $this->request = json_decode(file_get_contents('php://input'), true);
1210         if (is_null($this->request))
1211         {
1212             $this->initPost();
1213             return;
1214         }
1215
1216         \Utility\Registry::setServiceManager($this->serviceLocator);
1217         $this->em = \Utility\Registry::getEntityManager();
1218
1219         $currentPositionDate = \Utility\FileStore::fetchJson('currentPositionDate');
1220
1221         \Utility\Debug::errorLog('$this->request', $this->request);
1222
1223         if('' != $this->request['currentPosition'])
1224         {
1225             switch ($this->request['currentPosition']) {
1226                 case '0':
1227
1228                     if (date('w') == 1)
1229                     {
1230                         $date = date('Y-m-d');
1231
1232                         \Utility\FileStore::storeJson('currentPositionDate', $date);
1233                     }
1234                     else
1235                     {
1236                         $date =  date('Y-m-d', strtotime("previous monday"));
1237
1238                         \Utility\FileStore::storeJson('currentPositionDate', $date);
1239                     }
1240
1241                     break;
1242                 case '+1':
1243
1244                     $date = date('Y-m-d', strtotime( $currentPositionDate . "next monday"));
1245
1246                     \Utility\FileStore::storeJson('currentPositionDate', $date);
1247
1248                     break;
1249                 case '-1':
1250
1251                     $date = date('Y-m-d', strtotime( $currentPositionDate . "last monday"));
1252
1253                     \Utility\FileStore::storeJson('currentPositionDate', $date);
1254
1255                     break;
1256             }
1257         }
1258
1259         $currentPositionDate = \Utility\FileStore::fetchJson('currentPositionDate');
1260
1261         $appointmentTimeSlotsEntry = $this->em->getRepository('\\Valuation\\Entity\\ValuationTimeSlots')
1262             ->findBy(array(
1263                 'archived'                      => false
1264             ));
1265
1266
1267         $appointmentTimeSlotsCount = count($appointmentTimeSlotsEntry);
1268
1269         $valuationEntry = $this->em->getRepository('\\Valuation\\Entity\\Valuation')
1270             ->findOneBy(array(
1271                 'id'                    => $this->request['valuationId'],
1272                 'archived'                      => false
1273             ));
1274
1275         $outputTableBody = 'foc';
1276
1277                 if(!is_null($valuationEntry))
1278         {
1279             $profileEntry = $this->em->getRepository('\\User\\Entity\\Profile')
1280                 ->findBy(array(
1281                     'company'                   => $valuationEntry->stock->company->id,
1282                     'permissions'                   => '7',
1283                     'archived'                  => 0
1284                 ));
1285
1286             if(!is_null($profileEntry))
1287             {
1288                 $profileCounter = 1;
1289
1290                 foreach($profileEntry as $profile)
1291                 {
1292                     $outputTableBody .= '<tr class="handy">';
1293
1294                     \Utility\Debug::errorLog('$profile', $profile->id);
1295
1296                     if(null != $valuationEntry->valuatedBy)
1297                     {
1298                         if(1 == $profileCounter)
1299                         {
1300                             $profileCounter = 2;
1301                         }
1302
1303                         if($valuationEntry->valuatedBy == $profile->id)
1304                         {
1305                             $outputTableBody .= '<td class="valuator no-hover">Valuator 1</td>';
1306                         }
1307                     }
1308                     else
1309                     {
1310
1311                         $outputTableBody .= '<td class="valuator no-hover">Valuator ' . $profileCounter . '</td>';
1312                     }
1313
1314                     $profileCounter++;
1315
1316
1317                     /*
1318                     * check appointemtns for monday
1319                     */
1320
1321                     $currentDate=date('Ymd');
1322
1323                     $dateCounter = 0;
1324                     for($i = 1; $i <= 5; $i++)
1325                     {
1326
1327                         $setDate = date('d-m-Y', strtotime( $currentPositionDate . "+$dateCounter days"));
1328                         $setDateCheck = date('Ymd', strtotime( $currentPositionDate . "+$dateCounter days"));
1329
1330                         $appointmentEntry = $this->em->getRepository('\\Valuation\\Entity\\ValuationAppointments')
1331                             ->findBy(array(
1332                                 'valuator'                      => $profile->id,
1333                                 'appointmentDate'               => new \DateTime($setDate),
1334                                 'archived'                      => false
1335                             ));
1336
1337                         if($currentDate > $setDateCheck)
1338                         {
1339                             if(!empty($appointmentEntry))
1340                             {
1341
1342                                 $appointmentCount = count($appointmentEntry);
1343
1344                                 $percentageOfAppointments = ($appointmentCount / 100) * $appointmentTimeSlotsCount;
1345
1346                                 if($percentageOfAppointments <= '100' && $percentageOfAppointments >= '90')
1347                                 {
1348                                     $outputTableBody .= '<td class="' . $profile->id . '_' . $dateCounter . ' " data-content="Full"  class="no-hover" style="background: #953b39;color:#ffffff;">Full</td>';
1349                                 }
1350                                 else if($percentageOfAppointments <= '90' && $percentageOfAppointments >= '30')
1351                                 {
1352                                     $outputTableBody .= '<td class="' . $profile->id . '_' . $dateCounter . ' " data-content="Almost Full" class="no-hover" style="background: #953b39;color:#ffffff;">Almost Full</td>';
1353                                 }
1354                                 else
1355                                 {
1356                                     $outputTableBody .= '<td class="' . $profile->id . '_' . $dateCounter . ' " data-content="Available" class="no-hover" style="background: #953b39;color:#ffffff;">Available</td>';
1357                                 }
1358                             }
1359                             else
1360                             {
1361                                 //its empty so avaliable
1362                                 $outputTableBody .= '<td class="' . $profile->id . '_' . $dateCounter . ' " data-content="Available" class="no-hover" style="background: #953b39;color:#ffffff;">Available</td>';
1363                             }
1364                         }
1365                         else
1366                         {
1367                             if(!is_null($appointmentEntry))
1368                             {
1369                                 $appointmentCount = count($appointmentEntry);
1370
1371                                 $percentageOfAppointments = ($appointmentCount / $appointmentTimeSlotsCount) * 100;
1372
1373                                 if($percentageOfAppointments <= '100' && $percentageOfAppointments >= '90')
1374                                 {
1375                                     $outputTableBody .= '<td class="' . $profile->id . '_' . $dateCounter . ' " data-content="Full" onClick="_w.customercompletevaluation.goToNext(' . $profile->id . ', ' . $dateCounter . ' ,  '. $profileCounter . ')">Full</td>';
1376                                 }
1377                                 else if($percentageOfAppointments <= '90' && $percentageOfAppointments >= '60')
1378                                 {
1379                                     $outputTableBody .= '<td class="' . $profile->id . '_' . $dateCounter . ' " data-content="Almost Full" onClick="_w.customercompletevaluation.goToNext(' . $profile->id . ', ' . $dateCounter . ' , ' . $profileCounter . ')">Almost Full</td>';
1380                                 }
1381                                 else
1382                                 {
1383                                     $outputTableBody .= '<td class="' . $profile->id . '_' . $dateCounter . ' " data-content="Available" onClick="_w.customercompletevaluation.goToNext(' . $profile->id . ', ' . $dateCounter . ' , ' . $profileCounter . ')">Available</td>';
1384                                 }
1385                             }
1386                             else
1387                             {
1388                                 //its empty so avaliable
1389                                 $outputTableBody .= '<td class="' . $profile->id . '_' . $dateCounter . ' " data-content="Available" onClick="_w.customercompletevaluation.goToNext(' . $profile->id . ', ' . $dateCounter . ' , ' . $profileCounter . ')">Available</td>';
1390                             }
1391                         }
1392
1393
1394                         $dateCounter++;
1395
1396                     }
1397
1398                     $outputTableBody .= '</tr>';
1399                 }
1400             }
1401         }
1402
1403
1404
1405
1406         $outputTableHeader = '<th class="">
1407                                     <div class="table-heading-wrapper">
1408                                         Valuator
1409                                     </div>
1410                                 </th>
1411                                 <th class="">
1412                                     <div class="table-heading-wrapper" id="date_monday">
1413                                         ' . $currentPositionDate . '
1414                                     </div>
1415                                 </th>
1416                                 <th class="">
1417                                     <div class="table-heading-wrapper" id="date_tuesday">
1418                                          ' . date('Y-m-d', strtotime( $currentPositionDate . "+1 days")) . '
1419                                     </div>
1420                                 </th>
1421                                 <th class="">
1422                                     <div class="table-heading-wrapper" id="date_wednesday">
1423                                         ' . date('Y-m-d', strtotime( $currentPositionDate . "+2 days")) . '
1424                                     </div>
1425                                 </th>
1426                                 <th class="">
1427                                     <div class="table-heading-wrapper" id="date_thursday">
1428                                        ' . date('Y-m-d', strtotime( $currentPositionDate . "+3 days")) . '
1429                                     </div>
1430                                 </th>
1431                                 <th class="">
1432                                     <div class="table-heading-wrapper" id="date_friday">
1433                                         ' . date('Y-m-d', strtotime( $currentPositionDate . "+4 days")) . '
1434                                     </div>
1435                                 </th>';
1436
1437
1438
1439         return new \Zend\View\Model\JsonModel(array('outputTableHeader' => $outputTableHeader,'outputTableBody' => $outputTableBody));
1440     }
1441
1442
1443     public function populateCompleteValuationAppointmentTimeTableAction()
1444     {
1445         $this->initJson();
1446
1447         $this->request = json_decode(file_get_contents('php://input'), true);
1448
1449         if (is_null($this->request)) {
1450             $this->initPost();
1451             return;
1452         }
1453
1454         \Utility\Registry::setServiceManager($this->serviceLocator);
1455         $this->em = \Utility\Registry::getEntityManager();
1456
1457         $currentPositionDate = \Utility\FileStore::fetchJson('currentPositionDate');
1458
1459         $dateSentThrough =  $this->request['dateNo'];
1460
1461         $setSelected = date('Y-m-d', strtotime( $currentPositionDate . "+$dateSentThrough days"));
1462
1463         $appointmentTimeSlotsEntry = $this->em->getRepository('\\Valuation\\Entity\\ValuationTimeSlots')
1464             ->findBy(array(
1465                 'archived'                      => 0
1466             ));
1467
1468         $outputTableHeader = '<th class="">
1469                                     <div class="table-heading-wrapper">
1470                                         Valuator ' . $this->request['valuatorNo'] . '
1471                                     </div>
1472                                 </th>
1473                                 <th class="">
1474                                     <div class="table-heading-wrapper">
1475                                        ' . $setSelected . '
1476                                     </div>
1477                                 </th>';
1478
1479         $outputTableHeader .= '<th class="">
1480                                     &nbsp;
1481                                 </th>
1482                                 <th class="">
1483                                     &nbsp;
1484                                 </th>
1485                                 <th class="">
1486                                     &nbsp;
1487                                 </th>
1488                                 <th class="">
1489                                     &nbsp;
1490                                 </th>';
1491
1492         $outputTableBody = '';
1493
1494         $currentTime=date('H:i:s', time());
1495         $currentDate=date('Y-m-d');
1496
1497         if(!is_null($appointmentTimeSlotsEntry))
1498         {
1499             $outputTableBody .= '<tr class="handy">';
1500
1501             foreach($appointmentTimeSlotsEntry as $appointmentTimeSlot)
1502             {
1503 //                  \Utility\Debug::errorLog('$appointmentTimeSlots', $appointmentTimeSlot->id);
1504
1505                 $currentTimeMatchArray = explode(' - ',$appointmentTimeSlot->timeSlot);
1506
1507                 if($currentTime > $currentTimeMatchArray[1]  && $setSelected == $currentDate)
1508                 {
1509                     $valuationAppointmentsEntry = $this->em->getRepository('\\Valuation\\Entity\\ValuationAppointments')
1510                         ->findOneBy(array(
1511                             'valuator'              => $this->em->getReference('\\User\Entity\Profile', $this->request['profileId']),
1512                             'timeSlot'          => $this->em->getReference('\\Valuation\Entity\ValuationTimeSlots', $appointmentTimeSlot->id),
1513                             'appointmentDate'   => new \DateTime($setSelected),
1514                             'archived'                  => false
1515                         ));
1516
1517                     if(is_null($valuationAppointmentsEntry) && empty($valuationAppointmentsEntry))
1518                     {
1519                         $outputTableBody .= "<td data-content='$appointmentTimeSlot->timeSlot' class='no-hover' style='background: #953b39;color:#ffffff; '> " . $appointmentTimeSlot->timeSlotDisplayName . ' </td>';
1520                     }
1521                     else
1522                     {
1523                         $outputTableBody .= "<td data-content='$appointmentTimeSlot->timeSlot' class='no-hover' style='background: #953b39;color:#ffffff; '> " . $appointmentTimeSlot->timeSlotDisplayName . ' </td>';
1524                     }
1525                 }
1526                 else
1527                 {
1528                     $valuationAppointmentsEntry = $this->em->getRepository('\\Valuation\\Entity\\ValuationAppointments')
1529                         ->findOneBy(array(
1530                             'valuator'              => $this->em->getReference('\\User\Entity\Profile', $this->request['profileId']),
1531                             'timeSlot'          => $this->em->getReference('\\Valuation\Entity\ValuationTimeSlots', $appointmentTimeSlot->id),
1532                             'appointmentDate'   => new \DateTime($setSelected),
1533                             'archived'                  => false
1534                         ));
1535
1536                     if(is_null($valuationAppointmentsEntry) && empty($valuationAppointmentsEntry))
1537                     {
1538                         $outputTableBody .= "<td data-content='$appointmentTimeSlot->timeSlot' onClick='_w.customercompletevaluation.goToFinish(" .  '"'  . "$appointmentTimeSlot->id" .  '"'  . "," .  '"'  . "$appointmentTimeSlot->timeSlotDisplayName" .  '"'  . " )'> " . $appointmentTimeSlot->timeSlotDisplayName . ' </td>';
1539                     }
1540                     else
1541                     {
1542                         $outputTableBody .= "<td data-content='$appointmentTimeSlot->timeSlot' class='no-hover' style='background: #dddddd '> " . $appointmentTimeSlot->timeSlotDisplayName . ' </td>';
1543                     }
1544                 }
1545
1546             }
1547
1548             $outputTableBody .= '</tr>';
1549         }
1550
1551
1552
1553         return new \Zend\View\Model\JsonModel(array('dateSelected' => $setSelected, 'outputTableHeader' => $outputTableHeader,'outputTableBody' => $outputTableBody));
1554
1555
1556     }
1557
1558
1559     /**
1560      * get the calendar events to display for user.
1561      */
1562     public function getCalendarEventsAction()
1563     {
1564
1565         $this->initJson();
1566
1567         $this->request = json_decode(file_get_contents('php://input'), true);
1568         if (is_null($this->request)) {
1569             $this->initPost();
1570             return;
1571         }
1572
1573         \Utility\Registry::setServiceManager($this->serviceLocator);
1574         $this->em = \Utility\Registry::getEntityManager();
1575
1576         $profileId =  $this->request['userId'];
1577
1578         $limitMonth = new \DateTime('NOW');
1579         $limitMonth->modify( '-1 month' );
1580
1581         $appointmentsEntry = $this->em->createQuery(
1582             "SELECT calendar.id,
1583             calendar.appointmentDate,
1584             calendar.appointmentCompleted,
1585             calendar.appointmentCancelled,
1586             timeSlot.timeSlot,
1587             valuation.id as valuationId,
1588             valuation.firstName,
1589             valuation.familyName,
1590             stock.registrationNumber
1591             "
1592             . "FROM \\Valuation\\Entity\\ValuationAppointments calendar "
1593             . "LEFT JOIN calendar.timeSlot timeSlot "
1594             . "LEFT JOIN calendar.valuator valuator "
1595             . "LEFT JOIN calendar.valuation valuation "
1596             . "LEFT JOIN valuation.stock stock "
1597             . "WHERE calendar.archived = :archived "
1598             . "AND valuation.archived = :archived "
1599             . "AND calendar.appointmentDate > :oneMonth  "
1600             . "AND valuator.id = :valuatorId "
1601             . "GROUP BY calendar.id"
1602         )
1603             ->setParameter('archived', false)
1604             ->setParameter('valuatorId', $profileId)
1605             ->setParameter('oneMonth', $limitMonth)
1606             ->getArrayResult();
1607
1608         $returnData = array();
1609
1610         if(!empty($appointmentsEntry))
1611         {
1612             foreach ($appointmentsEntry as $appointments)
1613             {
1614
1615                 $bookingDate = $appointments['appointmentDate'];
1616                 $bookingDate = $bookingDate->format('Y-m-d');
1617                 $bookingTimeSlot = $appointments['timeSlot'];
1618
1619                 $bookingTimeSlotArray = explode(' - ',$bookingTimeSlot);
1620
1621                 $startDate = date($bookingDate . ' ' . $bookingTimeSlotArray[0] . ':00');
1622                 $endDate = date($bookingDate . ' ' . $bookingTimeSlotArray[1] . ':00');
1623
1624
1625                 array_push($returnData, array(
1626                     'title' => $appointments['firstName'] . ' ' . $appointments['familyName'] . ', ' . $appointments['registrationNumber'],
1627                     'start' => $startDate,
1628                     'end' => $endDate,
1629                     'appointmentId' => $appointments['id'],
1630                     'appointmentCompleted' => $appointments['appointmentCompleted'],
1631                     'appointmentCancelled' => $appointments['appointmentCancelled'],
1632
1633                 ));
1634
1635             }
1636         }
1637
1638
1639         return new \Zend\View\Model\JsonModel(array($returnData));
1640
1641     }
1642
1643
1644 }