initial commit
[namibia] / module / Valuation / src / Valuation / Service / Valuation.php
1 <?php
2 namespace Valuation\Service;
3 use Doctrine\Common\Util\Debug;
4
5
6 /**
7  * Manage Valuation data.
8  * @author andre.fourie
9  */
10 class Valuation extends \Valuation\DataBin\Valuation
11 {
12
13
14         public function initNewItem(\Valuation\Entity\Valuation $valuation)
15         {
16         }
17
18         /**
19          * Route newly added item to initial state.
20          * @param \Valuation\Entity\Valuation
21          * @param string|null $previousState
22          * @param array|null  $routingData
23          * @return string
24          */
25         public function routeNewItem(\Valuation\Entity\Valuation $valuation, $previousState, $routingData)
26         {
27
28
29                 $status = \Utility\Registry::checkOnce('NewValuationItem.Status', 'This.NewValuation');
30                 $data   = \Utility\Registry::checkOnce('Service.Valuation.Context', array());
31
32                 if ('PriceGuide.NewItemFromValuation' == $status)
33                 {
34                         $valuation->previousState = 'Pending Valuation';
35                 }
36                 if ('This.Stock' == $status)
37                 {
38                         $valuation->previousState = 'Pending Valuation';
39                 }
40                 return array(
41                         'Destination' => $status,
42                         'Data'        => $data
43                 );
44
45         }
46
47         /**
48          * Deal Done for stats.
49          * @param \Valuation\Entity\Valuation
50          * @param string|null $previousState
51          * @param array|null  $routingData
52          * @return string
53          */
54         public function directRouteMoveToDealDone(\Valuation\Entity\Valuation $valuation, $previousState)
55         {
56                 //Write hit to Stats logs (need stock or valuation stock id and profile id)
57                 $today = new \DateTime();
58                 //$test = "123";
59                 //\Utility\Debug::errorLog('New dealDone', $test);
60
61                 $em         = \Utility\Registry::getEntityManager();
62                 $loghit     = new \Statistical\Entity\Statistical();
63                 $loghitData = array(
64                         'stock'       => $em->getRepository('\Stock\Entity\Stock')->find($valuation->stock->id),
65                         'dealdone'    => true,
66                         'dealnotdone' => false,
67                         'tradecentre' => false,
68                         'fromProfile' => $em->getRepository('\User\Entity\Profile')->find($valuation->stock->createdBy->id),
69                         'created'     => $today
70                 );
71                 $loghit->fromArray($loghitData);
72                 $em->persist($loghit);
73                 $valuation->stock->previousState = $valuation->stock->jobState;
74                 $valuation->stock->jobState      = 'Stock';
75                 $em->flush();
76
77                 return 'This.Stock';
78         }
79
80         /**
81          * Deal Not Done for stats.
82          * @param \Valuation\Entity\Valuation
83          * @param string|null $previousState
84          * @return string
85          */
86         public function directRouteMoveToDealNotDone(\Valuation\Entity\Valuation $valuation, $previousState)
87         {
88
89                 // Add XML to Higher Gear
90
91
92                 if ($valuation->isPublic)
93                 {
94                         // remove +27 and add 0 like -> +2711xxxx becomes 011xxx
95                         $mobileNumber    = $valuation->mobile;
96                         $mobileNumFormat = substr($mobileNumber, 3);
97                         $mobileNumFormat = 0 . $mobileNumFormat;
98
99
100                         /* xml template  */
101
102                         $xmlTemplateDnd = '
103                                         <?xml version="1.0"?>
104                                                 <?ADF version="1.0"?>
105                                                         <adf>
106                                                                 <prospect>
107                                                                         <requestdate>2013-07-10 19:52:42.38</requestdate>
108                                                                         <vehicle interest="buy" status="Trade">
109                                                                                 <year>' . $valuation->stock->vehicleYear->name . '</year>
110                                                                                 <make>' . $valuation->stock->type->model->make->name . '</make>
111                                                                                 <model>' . $valuation->stock->type->model->name . '</model>
112                                                                                 <odometer units="0">' . $valuation->stock->km . '</odometer>
113                                                                                 <doors>' . $valuation->stock->type->doors . '</doors>
114                                                                                 <transmission>' . $valuation->stock->transmissionType->name . '</transmission>
115                                                                                 <vin>' . $valuation->stock->vinNumber . '</vin>
116                                                                                 <stock>' . $valuation->stock->stockNumber . '</stock>
117                                                                                 <colorcombination>
118                                                                                         <interiorcolor>' . $valuation->stock->exteriorColour->name . '</interiorcolor>
119                                                                                         <exteriorcolor>' . $valuation->stock->interiorColour->name . '</exteriorcolor>
120                                                                                 </colorcombination>
121                                                                         </vehicle>
122
123                                                                         <customer>
124                                                                                 <contact>
125                                                                                         <name part="first">' . $valuation->firstName . '</name>
126                                                                                         <name part="last">' . $valuation->familyName . '</name>
127                                                                                         <phone time="evening">' . $mobileNumFormat . '</phone>
128                                                                                         <phone time="day">' . $mobileNumFormat . '</phone>
129                                                                                         <phone type="cellphone"/>
130                                                                                         <email>' . $valuation->email . '</email>
131                                                                                         <address>' . $valuation->requiredPrice . '</address>
132                                                                                         <city>' . $valuation->amountOffered . '</city>
133                                                                                 </contact>
134                                                                                 <comments></comments>
135                                                                         </customer>
136                                                                         <vendor>
137                                                                                 <id>99999</id>
138                                                                                 <vendorname>bid4cars.co.za</vendorname>
139                                                                                 <contact>
140                                                                                         <name part="full">unknown</name>
141                                                                                         <email>dm1408082@highergear.net</email>
142                                                                                 </contact>
143                                                                         </vendor>
144                                                                         <provider>
145                                                                                 <id></id>
146                                                                                 <name>' . $valuation->stock->company->name . '</name>
147                                                                         </provider>
148                                                                 </prospect>
149                                                         </adf>
150                                         ';
151
152                         $mailer = new \Utility\Comms\Email();
153                         $mailer->send(array(
154                                               'From'    => \Utility\Registry::getConfigParam('sourceEmailAddress'),
155                                               'To'      => 'dm1408082@highergear.net',
156                                               'Subject' => 'Deal Not Done Valuation XML',
157                                               'Body'    => $xmlTemplateDnd
158                                       ));
159
160
161                         $mailer = new \Utility\Comms\Email();
162                         $mailer->send(array(
163                                               'From'    => \Utility\Registry::getConfigParam('sourceEmailAddress'),
164                                               'To'      => 'b4c@nirph.com',
165                                               'Subject' => 'Deal Not Done Valuation XML',
166                                               'Body'    => $xmlTemplateDnd
167                                       ));
168
169
170                         #-> Log notification entry.
171                         $em = \Utility\Registry::getEntityManager();
172
173                         $log     = new \Utility\Entity\NotificationLog();
174                         $logData = array(
175                                 'emailTo'      => 'dm1408082@highergear.net',
176                                 'emailSubject' => 'Deal Not Done Valuation XML',
177                                 'emailBody'    => $xmlTemplateDnd,
178                                 'smsTo'        => '',
179                                 'smsBody'      => '',
180                                 'apiMsgId'     => ''
181                         );
182
183                         $log->fromArray($logData);
184                         $em->persist($log);
185                         $em->flush();
186
187
188                         $log     = new \Utility\Entity\NotificationLog();
189                         $logData = array(
190                                 'emailTo'      => 'b4c@nirph.com',
191                                 'emailSubject' => 'Deal Not Done Valuation XML',
192                                 'emailBody'    => $xmlTemplateDnd,
193                                 'smsTo'        => '',
194                                 'smsBody'      => '',
195                                 'apiMsgId'     => ''
196                         );
197
198                         $log->fromArray($logData);
199                         $em->persist($log);
200                         $em->flush();
201
202                 }
203
204
205                 //Write hit to Stats logs (need stock or valuation stock id and profile id)
206                 $today = new \DateTime();
207                 //$test = "123";
208                 //\Utility\Debug::errorLog('dealNotDone new', $test);
209
210                 $em         = \Utility\Registry::getEntityManager();
211                 $loghit     = new \Statistical\Entity\Statistical();
212                 $loghitData = array(
213                         'stock'       => $em->getRepository('\Stock\Entity\Stock')->find($valuation->stock->id),
214                         'dealdone'    => false,
215                         'dealnotdone' => true,
216                         'tradecentre' => false,
217                         'fromProfile' => $em->getRepository('\User\Entity\Profile')->find($valuation->stock->createdBy->id),
218                         'created'     => $today
219                 );
220
221                 $loghit->fromArray($loghitData);
222                 $em->persist($loghit);
223                 $em->flush();
224
225                 if ('Price Guide' == $valuation->jobState)
226                 {
227                         $this->workflowNode->handover('Price Guide', $valuation->id);
228
229                         $workflow   = \Utility\Registry::getServiceManager()
230                                 ->get('PriceGuide');
231                         $priceGuide = $this->em->getRepository('\PriceGuide\Entity\PriceGuide')
232                                 ->findOneBy(array('valuation' => $valuation->id), array('id' => 'DESC'));
233                         $workflow->loadJob($priceGuide->id);
234                         $workflow->changeState('This.Archived');
235                         $this->em->createQuery(
236                                 'UPDATE \PriceGuide\Entity\Offer o '
237                                 . "SET o.status = 'Archived' "
238                                 . 'WHERE IDENTITY(o.priceGuideStock) = '
239                                 . $priceGuide->id
240                                 . ' AND o.status != \'Archived\''
241                         )
242                                 ->execute();
243                 }
244                 return 'This.Archived';
245
246         }
247
248         /**
249          * Route item that is received back from Price Guide Workflow.
250          * @param \Valuation\Entity\Valuation $valuation
251          * @param string                      $previousState
252          * @param array|null                  $routingData
253          * @return string
254          */
255         public function routePriceGuideHandover(\Valuation\Entity\Valuation $valuation, $previousState, $routingData)
256         {
257                 return $valuation->previousState != 'New Valuation'
258                         ? 'This.' . str_replace(' ', '', $valuation->previousState)
259                         : 'This.PendingValuation';
260         }
261
262         /**
263          * Route item to Offer Accepted status.
264          *
265          * @param \Valuation\Entity\Valuation $valuation
266          * @param string|null                 $previousState
267          * @return string
268          */
269         public function directRouteMoveToOfferAccepted(\Valuation\Entity\Valuation $valuation, $previousState)
270         {
271                 #-> Set price guide entry to accepted.
272                 $priceGuide  = $valuation->stock->priceGuide;
273                 $wPriceGuide = \Utility\Registry::getServiceManager()->get('PriceGuide');
274                 $oPriceGuide = new \Valuation\Service\Valuation();
275                 $oPriceGuide->setWorkflow($wPriceGuide);
276                 $wPriceGuide->loadJob($priceGuide->id);
277                 $wPriceGuide->changeState('This.OfferAccepted');
278
279                 #-> Locate relevant Offer.
280                 $result = $this->em->createQuery(
281                         'SELECT offer, company, profile '
282                         . 'FROM \PriceGuide\Entity\Offer offer '
283                         . 'JOIN offer.company company '
284                         . 'JOIN offer.profile profile '
285                         . 'WHERE IDENTITY(offer.priceGuideStock) = :priceGuideId'
286                         . ' AND offer.amount = :highestOffer '
287                         . 'ORDER BY offer.created ASC'
288                 )
289                         ->setParameter('priceGuideId', $priceGuide->id)
290                         ->setParameter('highestOffer', $valuation->stock->highestOffer)
291                         ->getResult();
292
293                 #-> Set offer as accepted and send notification.
294                 if (0 < count($result))
295                 {
296                         $item = array_shift($result);
297
298                         $item->status = 'Offer Accepted';
299                         $this->em->flush($item);
300                         $hours          = \Utility\Definitions\Locale::getPriceGuideOpenDays();
301                         $hoursRemaining = floor((($item->created->getTimestamp() + (3600 * $hours)) - time()) / 3600);
302                         $params         = array(
303                                 'firstName'          => $item->profile->firstName,
304                                 'familyName'         => $item->profile->familyName,
305                                 'highestOfferAmount' => 'R' . $item->amount,
306                                 'dealershipName'     => $priceGuide->company->name,
307                                 'registeredName'     => $priceGuide->company->name,
308                                 'contactPerson'      => $priceGuide->company->contact->firstName
309                                                         . ' ' . $priceGuide->company->contact->familyName,
310                                 'contactNumber'      => $priceGuide->company->contact->mobile,
311                                 'contactEmail'       => $priceGuide->company->contact->email,
312                                 'year'               => $valuation->stock->vehicleYear->name,
313                                 'make'               => $valuation->stock->type->model->make->name,
314                                 'model'              => $valuation->stock->type->model->name,
315                                 'type'               => $valuation->stock->type->name,
316                                 'trade'              => 'Trade price: R' . $valuation->stock->tradePrice,
317                                 'retail'             => 'Retail price: R' . $valuation->stock->retailPrice,
318                                 'list'               => 'List price: R' . $valuation->stock->listPrice,
319                                 'registrationNumber' => $valuation->stock->registrationNumber,
320                                 'daysRemaining'      => '0 days, ' . $hoursRemaining . ' hours',
321                                 'referenceNumber'    => $valuation->stock->referenceNumber
322                         );
323                         $auth           = \Utility\Registry::getAuthData();
324                         $oNotify        = new \Utility\Comms\Notification();
325                         // Send to Trader whose offer was accepted.
326                         $oNotify->sendFromTemplate(
327                                 $priceGuide->stock->company->id,
328                                 $priceGuide->stock->createdBy->id,
329                                 $item->company->id,
330                                 $item->profile->id,
331                                 $item->profile->email,
332                                 null,
333                                 'Price Guide Offer Accepted',
334                                 'price-guide-offer-accepted',
335                                 $params);
336                         // Send to User that accepted the offer.
337                         $params['firstName']  = $auth['firstName'];
338                         $params['familyName'] = $auth['familyName'];
339                         $oNotify->sendFromTemplate(
340                                 $priceGuide->stock->company->id,
341                                 $priceGuide->stock->createdBy->id,
342                                 $item->company->id,
343                                 $auth['id'],
344                                 $auth['email'],
345                                 null,
346                                 'Price Guide Offer Accepted',
347                                 'price-guide-offer-accepted',
348                                 $params);
349                         // Send to B4C admin.
350                         $params['firstName']  = $item->profile->firstName;
351                         $params['familyName'] = $item->profile->familyName;
352                         $oNotify->sendFromTemplate(
353                                 $priceGuide->stock->company->id,
354                                 $priceGuide->stock->createdBy->id,
355                                 null,
356                                 null,
357                                 'info@bid4cars.co.za',
358                                 null,
359                                 'Price Guide Offer Accepted',
360                                 'price-guide-offer-accepted',
361                                 $params);
362                 }
363
364                 #-> Notify other bidders.
365                 $params = array(
366                         'year'            => $valuation->stock->vehicleYear->name,
367                         'make'            => $valuation->stock->type->model->make->name,
368                         'model'           => $valuation->stock->type->model->name,
369                         'type'            => $valuation->stock->type->name,
370                         'regNo'           => $valuation->stock->registrationNumber,
371                         'referenceNumber' => $valuation->stock->referenceNumber
372                 );
373                 $result = $this->em->createQuery(
374                         'SELECT offer, company, profile '
375                         . 'FROM \PriceGuide\Entity\Offer offer '
376                         . 'JOIN offer.company company '
377                         . 'JOIN offer.profile profile '
378                         . 'WHERE IDENTITY(offer.priceGuideStock) = :priceGuideId '
379                         . 'ORDER BY offer.created ASC'
380                 )
381                         ->setParameter('priceGuideId', $priceGuide->id)
382                         ->getResult();
383                 foreach ($result as $offer)
384                 {
385                         if ($item->id == $offer->id)
386                         {
387                                 continue;
388                         }
389                         $offer->status = 'Expired';
390                         $this->em->flush();
391                         $params['firstName']   = $offer->profile->firstName;
392                         $params['familyName']  = $offer->profile->familyName;
393                         $params['offerAmount'] = 'R' . $offer->amount;
394                         $oNotify->sendFromTemplate(
395                                 $priceGuide->stock->company->id,
396                                 $priceGuide->stock->createdBy->id,
397                                 $offer->company->id,
398                                 $offer->profile->id,
399                                 $offer->profile->email,
400                                 null, null,
401                                 'price-guide-offer-declined',
402                                 $params
403                         );
404                 }
405                 \Utility\Debug::errorLog('take this to stock ', $valuation->stock->id);
406                 return 'This.Stock';
407         }
408
409         /**
410          * Route item to Stock status.
411          *
412          * @param \Valuation\Entity\Valuation $valuation
413          * @param string|null                 $previousState
414          * @return string
415          */
416         public function directRouteMoveToKeepForStock(\Valuation\Entity\Valuation $valuation, $previousState)
417         {
418                 //Write hit to Stats logs (need stock or valuation stock id and profile id)
419                 $today = new \DateTime();
420                 //$test = "123";
421                 //\Utility\Debug::errorLog('directRouteMoveToKeepForStock new', $test);
422
423                 $em         = \Utility\Registry::getEntityManager();
424                 $loghit     = new \Statistical\Entity\Statistical();
425                 $loghitData = array(
426                         'stock'       => $em->getRepository('\Stock\Entity\Stock')->find($valuation->stock->id),
427                         'dealdone'    => true,
428                         'dealnotdone' => false,
429                         'tradecentre' => false,
430                         'fromProfile' => $em->getRepository('\User\Entity\Profile')->find($valuation->stock->createdBy->id),
431                         'created'     => $today
432                 );
433
434                 $loghit->fromArray($loghitData);
435                 $em->persist($loghit);
436                 $em->flush();
437
438                 #-> Get price guide entry.
439                 $priceGuide = $valuation->stock->priceGuide;
440
441                 #-> Locate relevant Offer.
442                 $result = $this->em->createQuery(
443                         'SELECT offer, company, profile '
444                         . 'FROM \PriceGuide\Entity\Offer offer '
445                         . 'JOIN offer.company company '
446                         . 'JOIN offer.profile profile '
447                         . 'WHERE IDENTITY(offer.priceGuideStock) = :priceGuideId'
448                         . ' AND offer.amount = :highestOffer '
449                         . 'ORDER BY offer.created ASC'
450                 )
451                         ->setParameter('priceGuideId', $priceGuide->id)
452                         ->setParameter('highestOffer', $valuation->stock->highestOffer)
453                         ->getResult();
454
455
456                 #-> Send notification.
457                 if (0 < count($result))
458                 {
459
460                         $item = array_shift($result);
461
462
463                         $oNotify = new \Utility\Comms\Notification();
464                         $oNotify->sendFromTemplate(
465                                 $priceGuide->stock->company->id,
466                                 $priceGuide->stock->createdBy->id,
467                                 $item->company->id,
468                                 $item->profile->id,
469                                 $item->profile->email,
470                                 null,
471                                 'Vehicle retained for stock',
472                                 'price-guide-keep-stock',
473                                 array(
474                                         'firstName'          => $item->profile->firstName,
475                                         'familyName'         => $item->profile->familyName,
476                                         'highestOfferAmount' => 'R' . $item->amount,
477                                         'dealershipName'     => $priceGuide->company->name,
478                                         'year'               => $valuation->stock->vehicleYear->name,
479                                         'make'               => $valuation->stock->type->model->make->name,
480                                         'model'              => $valuation->stock->type->model->name,
481                                         'type'               => $valuation->stock->type->name,
482                                         'trade'              => 'Trade price: R' . $valuation->stock->tradePrice,
483                                         'retail'             => 'Retail price: R' . $valuation->stock->retailPrice,
484                                         'list'               => 'List price: R' . $valuation->stock->listPrice,
485                                         'registrationNumber' => $valuation->stock->registrationNumber,
486                                         'referenceNumber'    => $valuation->stock->referenceNumber
487                                 ));
488
489                 }
490
491                 #-> Notify other bidders.
492                 $params = array(
493                         'year'            => $valuation->stock->vehicleYear->name,
494                         'make'            => $valuation->stock->type->model->make->name,
495                         'model'           => $valuation->stock->type->model->name,
496                         'type'            => $valuation->stock->type->name,
497                         'regNo'           => $valuation->stock->registrationNumber,
498                         'referenceNumber' => $valuation->stock->referenceNumber
499                 );
500                 $result = $this->em->createQuery(
501                         'SELECT offer, company, profile '
502                         . 'FROM \PriceGuide\Entity\Offer offer '
503                         . 'JOIN offer.company company '
504                         . 'JOIN offer.profile profile '
505                         . 'WHERE IDENTITY(offer.priceGuideStock) = :priceGuideId '
506                         . 'ORDER BY offer.created ASC'
507                 )
508                         ->setParameter('priceGuideId', $priceGuide->id)
509                         ->getResult();
510                 foreach ($result as $offer)
511                 {
512                         $offer->status = 'Expired';
513                         $this->em->flush();
514                         if ($item->id == $offer->id)
515                         {
516                                 continue;
517                         }
518                         $params['firstName']   = $offer->profile->firstName;
519                         $params['familyName']  = $offer->profile->familyName;
520                         $params['offerAmount'] = 'R' . $offer->amount;
521                         $oNotify->sendFromTemplate(
522                                 $priceGuide->stock->company->id,
523                                 $priceGuide->stock->createdBy->id,
524                                 $offer->company->id,
525                                 $offer->profile->id,
526                                 $offer->profile->email,
527                                 null, null,
528                                 'price-guide-offer-declined',
529                                 $params
530                         );
531                 }
532                 return 'Stock.Handover';
533         }
534
535         /**
536          * Route item that is received back from Price Guide Workflow.
537          * @param \Valuation\Entity\Valuation $valuation
538          * @param string                      $previousState
539          */
540         public function directRouteMoveToArchive(\Valuation\Entity\Valuation $valuation, $previousState)
541         {
542                 $userId = \Utility\Registry::isAuthenticated()
543                         ? \Utility\Registry::getAuthParam('id')
544                         : 0;
545                 exec("php /var/www/B4C2/public/index.php valuation change 3 " . $valuation->id . " $userId  > /dev/null &");
546                 return 'This.Archived';
547         }
548
549         /**
550          * Route item that is received back from Price Guide Workflow.
551          * @param \Valuation\Entity\Valuation $valuation
552          * @param string                      $previousState
553          */
554         public function directRouteUnArchive(\Valuation\Entity\Valuation $valuation, $previousState)
555         {
556                 $userId = \Utility\Registry::isAuthenticated()
557                         ? \Utility\Registry::getAuthParam('id')
558                         : 0;
559                 exec("php /var/www/B4C2/public/index.php valuation change 1 " . $valuation->id . " $userId  > /dev/null &");
560                 return 'This.' . str_replace(' ', '', $valuation->previousState);
561         }
562
563         /**
564          * ExecuteAfter: CreateNew, CreatePending, CreateComplete, CreatePriceGuide, CreateStock.
565          * Set the valuation link on stock item.
566          * @param array                                 $meta
567          * @param object|null                           $jobRecord
568          * @param object|null                           $record
569          * @param \Workspace\Utility\ServiceInputParams $contract
570          * @return array
571          */
572         public function setStockLink($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
573         {
574
575
576                 !is_null($jobRecord)
577                         ? $jobRecord->stock->valuation = $jobRecord
578                         : $record->stock->valuation = $record;
579                 $this->em->flush();
580
581                 // do a check here for input
582
583                 $record = $record
584                         ? $record
585                         : $jobRecord;
586                 // valuation = $record, stock = $record->stock->refNum
587
588                 if (!\Utility\Registry::isAuthenticated())
589                 {
590                         // set valuations flag to is-public true
591                         $record->isPublic = true;
592                         $this->em->flush($record);
593                 }
594
595         }
596
597     /**
598      * ExecuteAfter: CreateNew, CreatePending, CreateComplete, CreatePriceGuide, CreateStock.
599      * Set the valuation link on stock item.
600      * @param array $meta
601      * @param object|null $jobRecord
602      * @param object|null $record
603      * @param \Workspace\Utility\ServiceInputParams $contract
604      * @return array
605      */
606     public function setStockLinkCustomer($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
607     {
608         !is_null($jobRecord)
609             ? $jobRecord->stock->valuation = $jobRecord
610             : $record->stock->valuation = $record;
611         $this->em->flush();
612
613         // do a check here for input
614
615         $record = $record
616             ? $record
617             : $jobRecord;
618         // valuation = $record, stock = $record->stock->refNum
619
620         if (!\Utility\Registry::isAuthenticated())
621         {
622             // set valuations flag to is-public-customer true
623             $record->isPublicCustomer = true;
624             $this->em->flush($record);
625
626 //            error_log($record->id);
627 //            error_log($record->isPublicCustomer);
628 //            error_log($record->stock->id);
629
630             $customerPublicValuationEntry = $this->em->getRepository('\\Valuation\\Entity\\CustomerPublicValuation')
631                 ->findOneBy(array(
632                     'valuation'                 => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
633                     'stock'                 => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
634                     'archived'                  => false
635                 ));
636
637             if(empty($customerPublicValuationEntry))
638             {
639                 $customerPublicValuationEntry = new \Valuation\Entity\CustomerPublicValuation();
640             }
641
642
643             $custHash = md5($record->id . $record->stock->id .  date('Y-m-d H:i'));
644
645             $customerPublicValuationArray = array(
646                 'valuation'                             => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
647                 'stock'                         => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
648                 'customerHash'                  => $custHash
649             );
650
651             try{
652
653                 $customerPublicValuationEntry->fromArray($customerPublicValuationArray);
654                 $this->em->persist($customerPublicValuationEntry);
655                 $this->em->flush();
656
657             }
658             catch (\Exception $e)
659             {
660                 error_log('Could not insert customer valuation hash.<br>' . $e);
661             }
662
663         }
664
665
666     }
667
668         /**
669          * ExecuteAfter: CreateComplete, RouteMoveToComplete.
670          * @param array                                 $meta
671          * @param object|null                           $jobRecord
672          * @param object|null                           $record
673          * @param \Workspace\Utility\ServiceInputParams $contract
674          * @return array
675          */
676         public function sendToSales($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
677         {
678                 $record = !is_null($record)
679                         ? $record
680                         : $jobRecord;
681
682                 if ($record->isPublic)
683                 {
684                         // remove +27 and add 0 -> +2711xxxx becomes 011xxx
685                         $mobileNumber    = $record->mobile;
686                         $mobileNumFormat = substr($mobileNumber, 3);
687                         $mobileNumFormat = 0 . $mobileNumFormat;
688
689
690                         // Removed - keep for refrence
691                         /* <street>' . $record->street . '</street>
692                         <city>' . $citynew . '</city>
693                         <regioncode>' . $record->region->name . '</regioncode>
694                         <postalcode></postalcode>
695
696                         dm105171@highergear.net
697                         */
698
699                         /* xml template  */
700                         $xmlTemplate = '
701                                         <?xml version="1.0"?>
702                                                 <?ADF version="1.0"?>
703                                                         <adf>
704                                                                 <prospect>
705                                                                         <requestdate>2013-07-10 19:52:42.38</requestdate>
706                                                                         <vehicle interest="buy" status="trade">
707                                                                                 <year>' . $record->stock->vehicleYear->name . '</year>
708                                                                                 <make>' . $record->stock->type->model->make->name . '</make>
709                                                                                 <model>' . $record->stock->type->model->name . '</model>
710                                                                                 <odometer units="0">' . $record->stock->km . '</odometer>
711                                                                                 <doors>' . $record->stock->type->doors . '</doors>
712                                                                                 <transmission>' . $record->stock->transmissionType->name . '</transmission>
713                                                                                 <vin>' . $record->stock->vinNumber . '</vin>
714                                                                                 <stock>' . $record->stock->stockNumber . '</stock>
715                                                                                 <colorcombination>
716                                                                                         <interiorcolor>' . $record->stock->exteriorColour->name . '</interiorcolor>
717                                                                                         <exteriorcolor>' . $record->stock->interiorColour->name . '</exteriorcolor>
718                                                                                 </colorcombination>
719                                                                         </vehicle>
720
721                                                                         <customer>
722                                                                                 <contact>
723                                                                                         <name part="first">' . $record->firstName . '</name>
724                                                                                         <name part="last">' . $record->familyName . '</name>
725                                                                                         <phone time="evening">' . $mobileNumFormat . '</phone>
726                                                                                         <phone time="day">' . $mobileNumFormat . '</phone>
727                                                                                         <phone type="cellphone"/>
728                                                                                         <email>' . $record->email . '</email>
729                                                                                         <address>' . $record->stock->valuation->requiredPrice . '</address>
730                                                                                         <city>' . $record->stock->valuation->amountOffered . '</city>
731                                                                                 </contact>
732                                                                                 <comments>' . $record->amountOffered . '</comments>
733                                                                         </customer>
734                                                                         <vendor>
735                                                                                 <id>99999</id>
736                                                                                 <vendorname>bid4cars.co.za</vendorname>
737                                                                                 <contact>
738                                                                                         <name part="full">unknown</name>
739                                                                                         <email>dm705161@highergear.net</email>
740                                                                                 </contact>
741                                                                         </vendor>
742                                                                         <provider>
743                                                                                 <id></id>
744                                                                                 <name>' . $record->stock->company->name . '</name>
745                                                                         </provider>
746                                                                 </prospect>
747                                                         </adf>
748                                         ';
749
750
751                         $mailer = new \Utility\Comms\Email();
752                         $mailer->send(array(
753                                               'From'    => \Utility\Registry::getConfigParam('sourceEmailAddress'),
754                                               'To'      => 'dm705161@highergear.net',
755                                               'Subject' => 'New Public Valuation XML',
756                                               'Body'    => $xmlTemplate
757                                       ));
758
759                         $mailer = new \Utility\Comms\Email();
760                         $mailer->send(array(
761                                               'From'    => \Utility\Registry::getConfigParam('sourceEmailAddress'),
762                                               'To'      => 'b4c@nirph.com',
763                                               'Subject' => 'New Public Valuation XML',
764                                               'Body'    => $xmlTemplate
765                                       ));
766
767
768                         #-> Log notification entry.
769                         $em = \Utility\Registry::getEntityManager();
770
771                         $log     = new \Utility\Entity\NotificationLog();
772                         $logData = array(
773                                 'emailTo'      => 'dm705161@highergear.net',
774                                 'emailSubject' => 'New Public Valuation XML',
775                                 'emailBody'    => $xmlTemplate,
776                                 'smsTo'        => '',
777                                 'smsBody'      => '',
778                                 'apiMsgId'     => ''
779                         );
780
781                         $log->fromArray($logData);
782                         $em->persist($log);
783                         $em->flush();
784
785
786                         $log     = new \Utility\Entity\NotificationLog();
787                         $logData = array(
788                                 'emailTo'      => 'b4c@nirph.com',
789                                 'emailSubject' => 'New Public Valuation XML',
790                                 'emailBody'    => $xmlTemplate,
791                                 'smsTo'        => '',
792                                 'smsBody'      => '',
793                                 'apiMsgId'     => ''
794                         );
795
796                         $log->fromArray($logData);
797                         $em->persist($log);
798                         $em->flush();
799                 }
800
801
802                 if (0.0 < $record->requiredPrice && is_null($record->tradeRetailRequested))
803                 {
804                         $record->tradeRetailRequested = true;
805                         $this->em->flush($record);
806                         $data = \Utility\Comms\TransUnion::searchByMmCode(
807                                 $record->stock->type->mmCode,
808                                 $record->stock->vehicleYear->name
809                         );
810                         if (is_array($data) && isset($data['VehicleDetails'])
811                             && isset($data['VehicleDetails'][0])
812                             && isset($data['VehicleDetails'][0]['Value'])
813                             && isset($data['VehicleDetails'][0]['Value']['RetailPrice'])
814                             && isset($data['VehicleDetails'][0]['Value']['TradePrice'])
815                             && isset($data['VehicleDetails'][0]['Value']['ListPrice'])
816                         )
817                         {
818                                 $record->stock->retailPrice = $data['VehicleDetails'][0]['Value']['RetailPrice'];
819                                 $record->stock->tradePrice  = $data['VehicleDetails'][0]['Value']['TradePrice'];
820                                 $record->stock->listPrice   = $data['VehicleDetails'][0]['Value']['ListPrice'];
821                                 $this->em->flush($record->stock);
822                         }
823                 }
824                 $salesProfileId = $contract->data->Valuation['salesProfile'];
825                 $amountOffered  = $contract->data->Valuation['amountOffered'];
826                 $salesComments  = isset($contract->data->Valuation['salesComments'])
827                         ? $contract->data->Valuation['salesComments']
828                         : '';
829
830                 $record->managerProfile = $this->em->getReference(
831                         '\User\Entity\Profile', \Utility\Registry::getAuthParam('id')
832                 );
833                 if ('Price Guide' == $record->jobState)
834                 {
835                         $record->previousState = 'Complete Valuation';
836                 }
837                 $this->em->flush();
838
839                 /*
840                  * Get data ready for notifcation
841                  */
842                 $tmpRecord = null == $jobRecord ? $record->toArray() : $jobRecord->toArray();
843                 $record    = null == $jobRecord ? $record : $jobRecord;
844
845                 /*
846                  * Get sales person data
847                  */
848                 $em          = \Utility\Registry::getEntityManager();
849                 $salesPerson = $em->getRepository('\User\Entity\Profile')->find($salesProfileId);
850
851                 $toProfileId = $salesProfileId;
852                 $toCompanyId = $salesPerson->company->id;
853                 $email       = $salesPerson->email;
854                 $mobile      = $salesPerson->mobile;
855                 $subject     = null;
856
857                 $templateName = 'valuation-completed';
858
859                 /*
860                  * Get vehicle data
861                  */
862                 $type = $record->stock->type;
863
864                 if (is_null($type))
865                 {
866                         $make  = 'N/A';
867                         $model = 'N/A';
868                         $type  = 'N/A';
869                 }
870                 $make  = $type->model->make->name;
871                 $model = $type->model->name;
872                 $type  = $type->name;
873
874                 /*
875                  * Get auth data
876                  */
877                 $authData      = \Utility\Registry::getAuthData();
878                 $fromCompanyId = isset($authData['company']['id']) ? $authData['company']['id'] : null;
879                 $fromProfileId = isset($authData['id']) ? $authData['id'] : null;
880
881                 /*
882                  * Set template parameters
883                  */
884                 $params               = array();
885                 $params['firstName']  = (string)$salesPerson->firstName;
886                 $params['familyName'] = (string)$salesPerson->familyName;
887
888                 $params['customer.name']       = $tmpRecord['firstName'];
889                 $params['customer.familyName'] = $tmpRecord['familyName'];
890                 $params['dateCreated']         = date('Y-m-d H:i');
891                 $params['refNo']               = (string)$record->stock->referenceNumber;
892                 $params['valNo']               = (string)$tmpRecord['valuationNumber'];
893                 $params['year']                = (string)$record->stock->vehicleYear->name;
894                 $params['make']                = $make;
895                 $params['model']               = $model;
896                 $params['type']                = $type;
897                 $params['regNo']               = (string)$record->stock->registrationNumber;
898                 $params['salesComments']       = $record->salesComments;
899
900                 /*
901                  * Attach PDF
902                  */
903                 $pdf = new \Valuation\Pdf\Pdf002();
904                 $pdf->process(array(
905                                       'jobRecord' => $record
906                               ), array());
907                 $writer      = new \Utility\Export\PdfTemplate($pdf);
908                 $attachments = array($record->valuationNumber . '.pdf' => $writer->output(''));
909
910
911                 $oNotify = new \Utility\Comms\Notification();
912                 $oNotify->sendFromTemplate(
913                         $fromCompanyId, $fromProfileId,
914                         $toCompanyId, $toProfileId,
915                         $email, null,
916                         $subject,
917                         $templateName,
918                         $params,
919                         $attachments
920                 );
921
922                 if (!is_null($record->xmlRpcClient)
923                     && $record->xmlRpcClient->triggerSentToSales
924                 )
925                 {
926                         exec("php /var/www/B4C2/public/index.php xmlrpc sentToSales "
927                              . $record->id
928                              . " >>/log/php.log &");
929                 }
930         }
931
932         /**
933          * ExecuteAfter: CreateNew.
934          * Add item to queue for mobile.
935          * @param array                                 $meta
936          * @param object|null                           $jobRecord
937          * @param object|null                           $record
938          * @param \Workspace\Utility\ServiceInputParams $contract
939          * @return array
940          */
941         public function sendToMobileQueue($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
942         {
943
944                 if (isset($contract->data->Valuation['valuators'])
945                     && !empty($contract->data->Valuation['valuators'])
946                 )
947                 {
948                         $this->update(
949                                 !is_null($jobRecord)
950                                         ? $jobRecord->id
951                                         : $record->id, array('queueStatus' => 1)
952                         );
953                 }
954
955         }
956
957         /**
958          * ExecuteAfter: CreateNew, Update.
959          * Send sms notifications to selected valuators for new item to valuate.
960          * @param array                                 $meta
961          * @param object|null                           $jobRecord
962          * @param object|null                           $record
963          * @param \Workspace\Utility\ServiceInputParams $contract
964          * @return array
965          */
966         public function sendToValuators($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
967         {
968                 $record = !is_null($record)
969                         ? $record
970                         : $jobRecord;
971                 $record->queueStatus = 1;
972                 $this->em->flush();
973                 if (0.0 < $record->requiredPrice && is_null($record->tradeRetailRequested))
974                 {
975                         $record->tradeRetailRequested = true;
976                         $this->em->flush($record);
977
978
979                         $data = \Utility\Comms\TransUnion::searchByMmCode(
980                                 $record->stock->type->mmCode,
981                                 $record->stock->vehicleYear->name
982                         );
983
984                         if (is_array($data) && isset($data['VehicleDetails'])
985                             && isset($data['VehicleDetails'][0])
986                             && isset($data['VehicleDetails'][0]['Value'])
987                             && isset($data['VehicleDetails'][0]['Value']['RetailPrice'])
988                             && isset($data['VehicleDetails'][0]['Value']['TradePrice'])
989                             && isset($data['VehicleDetails'][0]['Value']['ListPrice'])
990                         )
991                         {
992                                 $record->stock->retailPrice = $data['VehicleDetails'][0]['Value']['RetailPrice'];
993                                 $record->stock->tradePrice  = $data['VehicleDetails'][0]['Value']['TradePrice'];
994                                 $record->stock->listPrice   = $data['VehicleDetails'][0]['Value']['ListPrice'];
995                                 $this->em->flush($record->stock);
996                         }
997                 }
998                 if (isset($contract->data->Valuation['valuators'])
999                     && !empty($contract->data->Valuation['valuators'])
1000                 )
1001                 {
1002                         $record = !is_null($record)
1003                                 ? $record
1004                                 : $jobRecord;
1005                         $stock  = null == $jobRecord ? $record->stock : $jobRecord->stock;
1006                         $record = null == $jobRecord ? $record->toArray() : $jobRecord->toArray();
1007
1008                         $params = array();
1009                         if (\Utility\Registry::get('IsDeviceApiCall', false))
1010                         {
1011                                 $fromCompanyId        = $stock->company->id;
1012                                 $fromProfileId        = $stock->createdBy->id;
1013                                 $params['firstName']  = $stock->createdBy->firstName;
1014                                 $params['familyName'] = $stock->createdBy->familyName;
1015                         }
1016                         else
1017                         {
1018                                 $authData = \Utility\Registry::getAuthData();
1019
1020                                 $fromCompanyId = isset($authData['company']['id']) ? $authData['company']['id'] : null;
1021                                 $fromProfileId = isset($authData['id']) ? $authData['id'] : null;
1022
1023                                 $params['firstName']  = $authData['firstName'];
1024                                 $params['familyName'] = $authData['familyName'];
1025                         }
1026                         $params['customer_name']        = $record['firstName'];
1027                         $params['customer_family_name'] = $record['familyName'];
1028                         $params['vehicle_reg']          = is_null($stock->registrationNumber)
1029                                 ? ' '
1030                                 : $stock->registrationNumber;
1031
1032                         for ($i = 0; $i < count($contract->data->Valuation['valuators']); $i++)
1033                         {
1034                                 $valuator = $this->em->getRepository('\User\Entity\Profile')
1035                                         ->find($contract->data->Valuation['valuators'][$i]);
1036                                 $valuator = $valuator->toArray();
1037
1038                                 $toCompanyId  = $fromCompanyId;
1039                                 $toProfileId  = $valuator['id'];
1040                                 $email        = null;
1041                                 $mobile       = $valuator['mobile'];
1042                                 $subject      = null;
1043                                 $templateName = 'valuation-mobile-new';
1044
1045                                 $oNotify = new \Utility\Comms\Notification();
1046                                 $oNotify->sendFromTemplate(
1047                                         $fromCompanyId, $fromProfileId,
1048                                         $toCompanyId, $toProfileId,
1049                                         $email, $mobile,
1050                                         $subject,
1051                                         $templateName,
1052                                         $params
1053                                 );
1054                         }
1055
1056                 }
1057
1058         }
1059
1060         /**
1061          * ExecuteAfter: SendToPriceGuide.
1062          * Populate correct createdBy in case of public submission.
1063          * @param array                                 $meta
1064          * @param object|null                           $jobRecord
1065          * @param object|null                           $record
1066          * @param \Workspace\Utility\ServiceInputParams $contract
1067          * @return array
1068          */
1069         public function checkCreatedBy($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1070         {
1071
1072
1073                 $record = !is_null($record)
1074                         ? $record
1075                         : $jobRecord;
1076
1077
1078                 // Route to the Main Member Public Centre (profile) chosen by Region
1079                 if ($record->isPublic && !\Utility\Registry::isAuthenticated() && isset($contract->data->Stock['publicCentre']))
1080                 {
1081                         $publicCentre           = $contract->data->Stock['publicCentre'];
1082                         $company                = $this->em->getReference('\Company\Entity\Company', $publicCentre);
1083                         $record->stock->company = $company;
1084                         /* $profile = $this->em->getRepository('User\Entity\Profile')
1085                                 ->findOneBy(array(
1086                                                 'company' => $publicCentre,
1087                                                 'mainMemberPublicCentre' => 1
1088                                 ));
1089                         if (!is_null($profile))
1090                         {
1091                                 $record->stock->createdBy = $profile;
1092                                 $record->createdBy = $profile;
1093                         } */
1094
1095                         $record->sighted            = false;
1096                         $record->licenseDiscExpired = false;
1097                         $this->em->flush($record);
1098                 }
1099
1100                 if ($record->isPublic && \Utility\Registry::isAuthenticated())
1101                 {
1102                         $record->createdBy = $this->em->getReference('\User\Entity\Profile', \Utility\Registry::getAuthParam('id'));
1103                         $this->em->flush($record);
1104                 }
1105                 if (isset($contract->data->Valuation['requiredPrice'])
1106                     && is_numeric($contract->data->Valuation['requiredPrice'])
1107                     && 0.0 < $contract->data->Valuation['requiredPrice']
1108                 )
1109                 {
1110                         if (is_null($record->tradeRetailRequested)
1111                             && \Utility\Registry::isAuthenticated()
1112                         )
1113                         {
1114                                 $record->tradeRetailRequested = true;
1115                                 $this->em->flush($record);
1116                                 $data = \Utility\Comms\TransUnion::searchByMmCode(
1117                                         $record->stock->type->mmCode,
1118                                         $record->stock->vehicleYear->name
1119                                 );
1120                                 if (is_array($data) && isset($data['VehicleDetails'])
1121                                     && isset($data['VehicleDetails'][0])
1122                                     && isset($data['VehicleDetails'][0]['Value'])
1123                                     && isset($data['VehicleDetails'][0]['Value']['RetailPrice'])
1124                                     && isset($data['VehicleDetails'][0]['Value']['TradePrice'])
1125                                     && isset($data['VehicleDetails'][0]['Value']['ListPrice'])
1126                                 )
1127                                 {
1128                                         $record->stock->retailPrice = $data['VehicleDetails'][0]['Value']['RetailPrice'];
1129                                         $record->stock->tradePrice  = $data['VehicleDetails'][0]['Value']['TradePrice'];
1130                                         $record->stock->listPrice   = $data['VehicleDetails'][0]['Value']['ListPrice'];
1131                                         $this->em->flush($record->stock);
1132                                 }
1133                         }
1134
1135                         if (!\Utility\Registry::isAuthenticated())
1136                         {
1137                                 $stock  = null == $jobRecord ? $record->stock : $jobRecord->stock;
1138                                 $record = null == $jobRecord ? $record->toArray() : $jobRecord->toArray();
1139
1140
1141                                 $fromCompanyId = null;
1142                                 $fromProfileId = null;
1143
1144
1145                                 //\Utility\Debug::errorLog('$stock->vehicleYear', $stock->vehicleYear->name);
1146
1147                                 $params                = array();
1148                                 $params['first_name']  = $record['firstName'];
1149                                 $params['family_name'] = $record['familyName'];
1150
1151                                 $params['year']   = $stock->vehicleYear->name;
1152                                 $params['make']   = $stock->type->model->make->name;
1153                                 $params['model']  = $stock->type->model->name;
1154                                 $params['type']   = $stock->type->name;
1155                                 $params['reg_no'] = is_null($stock->registrationNumber)
1156                                         ? ''
1157                                         : $stock->registrationNumber;
1158
1159                                 $oNotify = new \Utility\Comms\Notification();
1160                                 $oNotify->sendFromTemplate(
1161                                         null, null,
1162                                         null, null,
1163                                         $record['email'], null,
1164                                         'Notification of successful submission of vehicle',
1165                                         'public-submission',
1166                                         $params
1167                                 );
1168                                 // Removed info@ to 'mohau@bid4cars.co.za', and 'dineo@bid4cars.co.za'
1169                                 $oNotify->sendFromTemplate(
1170                                         null, null,
1171                                         null, null,
1172                                         'mohau@bid4cars.co.za', null,
1173                                         'Notification of successful submission of vehicle',
1174                                         'public-submission',
1175                                         $params
1176                                 );
1177
1178                                 $oNotify->sendFromTemplate(
1179                                         null, null,
1180                                         null, null,
1181                                         'dineo@bid4cars.co.za', null,
1182                                         'Notification of successful submission of vehicle',
1183                                         'public-submission',
1184                                         $params
1185                                 );
1186                         }
1187                 }
1188
1189         }
1190
1191         /**
1192          * ExecuteAfter: CreatePending, CreateComplete, CreatePriceGuide, CreateStock.
1193          * Set the valuator from session authentication data.
1194          * @param array                                 $meta
1195          * @param object|null                           $jobRecord
1196          * @param object|null                           $record
1197          * @param \Workspace\Utility\ServiceInputParams $contract
1198          * @return array
1199          */
1200         public function setValuatorFromAuth($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1201         {
1202                 !is_null($record)
1203                         ? $record->valuatedBy = $this->em->getReference(
1204                         '\User\Entity\Profile', \Utility\Registry::getAuthParam('id')
1205                 )
1206                         : $jobRecord->valuatedBy = $this->em->getReference(
1207                         '\User\Entity\Profile', \Utility\Registry::getAuthParam('id')
1208                 );
1209                 $this->em->flush();
1210         }
1211
1212         /**
1213          * ExecuteAfter: CreateComplete, RouteMoveToComplete.
1214          * @param array                                 $meta
1215          * @param object|null                           $jobRecord
1216          * @param object|null                           $record
1217          * @param \Workspace\Utility\ServiceInputParams $contract
1218          * @return array
1219          */
1220         public function setPreviousStateToComplete($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1221         {
1222                 $jobRecord->previousState = 'Complete Valuation';
1223                 $this->em->flush($jobRecord);
1224
1225                 $record = null == $jobRecord
1226                         ? $record->toArray()
1227                         : $jobRecord->toArray();
1228
1229                 $valuationId = $record['id'];
1230
1231
1232                 $result = $this->em->createQuery(
1233                         'SELECT valuations, st '
1234                         . 'FROM \Valuation\Entity\Valuation valuations '
1235                         . 'JOIN valuations.stock st '
1236                         . 'WHERE valuations.id = :ValuationID '
1237                 )
1238                         ->setParameter('ValuationID', $valuationId)
1239                         ->getArrayResult();
1240
1241                 $StockID = $result[0]['stock']['id'];
1242
1243         }
1244
1245         /**
1246          * ConditionalContract: Update.
1247          * @param array                            $meta
1248          * @param object|null                      $jobRecord
1249          * @param object|null                      $record
1250          * @param \Workspace\Contract\AbstractBase $contract
1251          * @return array
1252          */
1253         public function noEditOnPgItemWithOffers($meta, $jobRecord, $record, \Workspace\Contract\AbstractBase $contract)
1254         {
1255                 if ('Price Guide' == $jobRecord->jobState
1256                     && 0 < $jobRecord->stock->numberOfOffers
1257                 )
1258                 {
1259                         throw new \Exception('Valuation in status Price Guide with offers may not be edited.');
1260                 }
1261         }
1262
1263         public function generateHistoryList($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1264         {
1265                 $record = null == $jobRecord
1266                         ? $record->toArray()
1267                         : $jobRecord->toArray();
1268
1269                 $valuationId = $record['id'];
1270
1271
1272                 $result = $this->em->createQuery(
1273                         'SELECT valuations, st '
1274                         . 'FROM \Valuation\Entity\Valuation valuations '
1275                         . 'JOIN valuations.stock st '
1276                         . 'WHERE valuations.id = :ValuationID '
1277                 )
1278                         ->setParameter('ValuationID', $valuationId)
1279                         ->getArrayResult();
1280
1281                 #-> Clear any existing history for this vehicle.
1282                 $StockID = $result[0]['stock']['id'];
1283                 $this->em->createQuery(
1284                         'DELETE FROM \Stock\Entity\PricingHistory pricingHistory '
1285                         . 'WHERE pricingHistory.stockId = '
1286                         . $StockID
1287                 )
1288                         ->execute();
1289
1290                 $result = $this->em->createQuery(
1291                         'SELECT stock, st, vy '
1292                         . 'FROM \Stock\Entity\Stock stock '
1293                         . 'LEFT JOIN stock.type st '
1294                         . 'LEFT JOIN stock.vehicleYear vy '
1295                         . 'WHERE stock.id = :StockID '
1296                 )
1297                         ->setParameter('StockID', $StockID)
1298                         ->getArrayResult();
1299
1300                 $stockTypeID   = $result[0]['type']['id'];
1301                 $vehicleYearID = $result[0]['vehicleYear']['id'];
1302                 $today         = new \DateTime();
1303                 $dateFrom      = clone $today;
1304                 $dateFrom->modify('-3 months');
1305
1306                 $result = $this->em->createQuery(
1307                         'SELECT stock, priceguide, auction, st, po, cb, bids '
1308                         . 'FROM \Stock\Entity\Stock stock '
1309                         . 'LEFT JOIN stock.priceGuide priceguide WITH priceguide.created BETWEEN :dateFrom AND :dateTo '
1310                         . 'LEFT JOIN stock.auction auction WITH auction.created BETWEEN :dateFrom AND :dateTo '
1311                         . 'LEFT JOIN stock.type st '
1312                         . 'LEFT JOIN priceguide.offers po '
1313                         . 'LEFT JOIN auction.currentBid cb '
1314                         . 'LEFT JOIN auction.bids bids '
1315                         . 'WHERE st.id = :stockTypeID '
1316                         . 'AND IDENTITY(stock.vehicleYear) = :vehicleYearID '
1317                         . 'AND (stock.highestBid > 0 OR stock.highestOffer > 0) '
1318                         . 'AND stock.archived = 0 '
1319                         . 'ORDER by auction.created, priceguide.created ASC '
1320                 )
1321                         ->setParameter('stockTypeID', $stockTypeID)
1322                         ->setParameter('vehicleYearID', $vehicleYearID)
1323                         ->setParameter('dateFrom', $dateFrom)
1324                         ->setParameter('dateTo', $today)
1325                         ->getArrayResult();
1326
1327                 $i        = 0;
1328                 $x        = 0;
1329                 $existing = array();
1330                 foreach ($result as $pricingHistory)
1331                 {
1332                         $StockDamageTotal = $pricingHistory['damageTotal'];
1333                         $StockTradePrice  = $pricingHistory['tradePrice'];
1334                         $StockListPrice   = $pricingHistory['listPrice'];
1335                         $StockKMS         = $pricingHistory['km'];
1336                         if ($StockKMS == '' || is_null($StockKMS))
1337                         {
1338                                 $StockKMS = 0;
1339                         }
1340                         // price guide
1341                         $PriceguideHighestOffer = $pricingHistory['highestOffer'];
1342                         // Auction
1343                         $highestBid = $pricingHistory['highestBid'];
1344
1345                         // Priceguide && Auction
1346                         if ($PriceguideHighestOffer != 0 && $highestBid != 0)
1347                         {
1348                                 $priceGuideOffers = $pricingHistory['priceGuide']['offers'];
1349                                 if (is_array($priceGuideOffers))
1350                                 {
1351                                         $highestAmnt = 0.0;
1352                                         foreach ($priceGuideOffers as $priceGuideOffer)
1353                                         {
1354                                                 if ($priceGuideOffer['amount'] > $highestAmnt)
1355                                                 {
1356                                                         $highestAmnt                 = $priceGuideOffer['amount'];
1357                                                         $priceGuideOffersCreatedDate = $priceGuideOffer['created'];
1358                                                 }
1359                                         }
1360
1361                                         $data = array(
1362                                                 'date'              => $priceGuideOffersCreatedDate,
1363                                                 'trade'             => $StockTradePrice,
1364                                                 'listPrice'         => $StockListPrice,
1365                                                 'totalRecon'        => $StockDamageTotal,
1366                                                 'km'                => $StockKMS,
1367                                                 'pricegOffer'       => $PriceguideHighestOffer,
1368                                                 'auctionWinningBid' => $highestBid,
1369                                                 'stockId'           => $StockID
1370                                         );
1371                                         $hash = md5(serialize($data));
1372                                         if (!isset($existing[$hash]))
1373                                         {
1374                                                 $existing[$hash] = true;
1375                                                 $entry           = new \Stock\Entity\PricingHistory();
1376                                                 $entry->fromArray($data);
1377                                                 $this->em->persist($entry);
1378                                                 $this->em->flush($entry);
1379                                                 $x++;
1380                                         }
1381                                 }
1382                         }
1383                         // Price Guide only
1384                         if ($PriceguideHighestOffer != 0 && $highestBid == 0)
1385                         {
1386                                 $priceGuideOffers = $pricingHistory['priceGuide']['offers'];
1387                                 if (is_array($priceGuideOffers))
1388                                 {
1389                                         $highestAmnt = 0.0;
1390                                         foreach ($priceGuideOffers as $priceGuideOffer)
1391                                         {
1392                                                 if ($priceGuideOffer['amount'] > $highestAmnt)
1393                                                 {
1394                                                         $highestAmnt                 = $priceGuideOffer['amount'];
1395                                                         $priceGuideOffersCreatedDate = $priceGuideOffer['created'];
1396                                                 }
1397                                         }
1398                                         $data = array(
1399                                                 'date'              => $priceGuideOffersCreatedDate, // changes all the time
1400                                                 'trade'             => $StockTradePrice,
1401                                                 'listPrice'         => $StockListPrice,
1402                                                 'totalRecon'        => $StockDamageTotal,
1403                                                 'km'                => $StockKMS,
1404                                                 'pricegOffer'       => $PriceguideHighestOffer,
1405                                                 'auctionWinningBid' => 0.0,
1406                                                 'stockId'           => $StockID
1407
1408                                         );
1409                                         $hash = md5(serialize($data));
1410                                         if (!isset($existing[$hash]))
1411                                         {
1412                                                 $existing[$hash] = true;
1413                                                 $entry           = new \Stock\Entity\PricingHistory();
1414                                                 $entry->fromArray($data);
1415                                                 $this->em->persist($entry);
1416                                                 $this->em->flush($entry);
1417                                                 $x++;
1418                                         }
1419                                 }
1420                         }
1421
1422                         // Auction only
1423                         if ($PriceguideHighestOffer == 0 && $highestBid != 0)
1424                         {
1425                                 $date = $pricingHistory['auction']['created'];
1426                                 $data = array(
1427                                         'date'              => $date, // changes all the time
1428                                         'trade'             => $StockTradePrice,
1429                                         'listPrice'         => $StockListPrice,
1430                                         'totalRecon'        => $StockDamageTotal,
1431                                         'km'                => $StockKMS,
1432                                         'pricegOffer'       => 0.0,
1433                                         'auctionWinningBid' => $highestBid,
1434                                         'stockId'           => $StockID
1435                                 );
1436                                 $hash = md5(serialize($data));
1437                                 if (!isset($existing[$hash]))
1438                                 {
1439                                         $existing[$hash] = true;
1440                                         $entry           = new \Stock\Entity\PricingHistory();
1441                                         $entry->fromArray($data);
1442                                         $this->em->persist($entry);
1443                                         $this->em->flush($entry);
1444                                         $x++;
1445                                 }
1446                         }
1447
1448                         if ($x > 10)
1449                         {
1450                                 break;
1451                         }
1452                 }
1453
1454         }
1455
1456
1457
1458         /**
1459          * Contract to use current highest price guide offer.
1460          * @param object|null $jobRecord
1461          * @param array       $input
1462          * @return \Workspace\Contract\UseOnce
1463          */
1464         public function contractUseOffer($jobRecord, array $input = array())
1465         {
1466                 $options     = new \Workspace\UseCase\Options();
1467                 $requirement = new \Workspace\UseCase\Requirement();
1468                 $requirement->addRequiredInput(array(
1469                                                        'Valuation' => array(
1470                                                                'id' => 'Id'
1471                                                        )
1472                                                ));
1473                 return new \Workspace\Contract\UseOnce($options, $requirement);
1474         }
1475
1476         /**
1477          * Use current highest price guide offer
1478          * @param object|null                           $jobRecord
1479          * @param \Workspace\Utility\ServiceInputParams $contract
1480          * @return array
1481          */
1482         public function executeUseOffer($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
1483         {
1484                 #-> Do we have an existing offer in use?
1485                 $existingOffer = $this->em->getRepository('PriceGuide\Entity\Offer')
1486                         ->findOneBy(array(
1487                                             'priceGuideStock' => $jobRecord->stock->priceGuide->id,
1488                                             'status'          => 'Offer in Use'
1489                                     ));
1490                 if (is_object($existingOffer))
1491                 {
1492                         #-> Have existing offer, change status of offer back to Updateable Offer.
1493                         $existingOffer->status = 'Updateable Offer';
1494                         $this->em->flush($existingOffer);
1495                 }
1496                 else
1497                 {
1498                         $existingOffer = false;
1499                 }
1500
1501                 #-> Get the new highest offer.
1502                 $highestOffer = $this->em->getRepository('PriceGuide\Entity\Offer')
1503                         ->findOneBy(array(
1504                                             'priceGuideStock' => $jobRecord->stock->priceGuide->id,
1505                                             'status'          => 'Updateable Offer'
1506                                     ),
1507                                     array(
1508                                             'amount'  => 'DESC',
1509                                             'created' => 'ASC'
1510                                     ));
1511                 if ($existingOffer && $existingOffer->id == $highestOffer->id)
1512                 {
1513                         $existingOffer = false;
1514                 }
1515                 $highestOffer->status = 'Offer in Use';
1516                 $this->em->flush($highestOffer);
1517
1518
1519                 #-> Notify owner of offer now in use.
1520                 $auth    = \Utility\Registry::getAuthData();
1521                 $oNotify = new \Utility\Comms\Notification();
1522                 $params  = array(
1523                         'firstName'       => $highestOffer->profile->firstName,
1524                         'familyName'      => $highestOffer->profile->familyName,
1525                         'offerAmount'     => $highestOffer->amount,
1526                         'year'            => $jobRecord->stock->vehicleYear->name,
1527                         'make'            => $jobRecord->stock->type->model->make->name,
1528                         'model'           => $jobRecord->stock->type->model->name,
1529                         'type'            => $jobRecord->stock->type->name,
1530                         'regNo'           => $jobRecord->stock->registrationNumber,
1531                         'referenceNumber' => $jobRecord->stock->referenceNumber
1532                 );
1533                 $oNotify->sendFromTemplate(
1534                         $jobRecord->stock->company->id, $auth['id'],
1535                         $highestOffer->company->id, $highestOffer->profile->id,
1536                         $highestOffer->profile->email, null, null,
1537                         'price-guide-offer-used',
1538                         $params
1539                 );
1540                 #-> Notify authed user of offer now in use.
1541                 $params['firstName']  = $auth['firstName'];
1542                 $params['familyName'] = $auth['familyName'];
1543                 $oNotify->sendFromTemplate(
1544                         $jobRecord->stock->company->id, $auth['id'],
1545                         $jobRecord->stock->company->id, $auth['id'],
1546                         $auth['email'], null, null,
1547                         'price-guide-offer-used',
1548                         $params
1549                 );
1550
1551                 #-> Notify authed user & owner of previous offer used that it is no longer in use.
1552                 if ($existingOffer)
1553                 {
1554                         $params['firstName']   = $highestOffer->profile->firstName;
1555                         $params['familyName']  = $highestOffer->profile->familyName;
1556                         $params['offerAmount'] = $existingOffer->amount;
1557                         $oNotify->sendFromTemplate(
1558                                 $jobRecord->stock->company->id, $auth['id'],
1559                                 $highestOffer->company->id, $highestOffer->profile->id,
1560                                 $highestOffer->profile->email, null, null,
1561                                 'price-guide-offer-dropped',
1562                                 $params
1563                         );
1564                         $params['firstName']  = $auth['firstName'];
1565                         $params['familyName'] = $auth['familyName'];
1566                         $oNotify->sendFromTemplate(
1567                                 $jobRecord->stock->company->id, $auth['id'],
1568                                 $jobRecord->stock->company->id, $auth['id'],
1569                                 $auth['email'], null, null,
1570                                 'price-guide-offer-dropped',
1571                                 $params
1572                         );
1573                 }
1574
1575                 return $contract->success('Current Highest Offer is now in use.', array());
1576         }
1577
1578         public function updateCustomVehicles($meta, $jobRecord, $contract, $data)
1579         {
1580                 $contract->data = $this->addCustomVehicles($meta, $contract->data);
1581                 return $contract->data;
1582         }
1583
1584         /**
1585          * ExecuteBefore: Create
1586          * @param array $meta
1587          * @param array $data
1588          */
1589         public function addCustomVehicles($meta, $data)
1590         {
1591
1592                 #-> Check if we have a custom vehicle
1593
1594                 //\Utility\Debug::errorLog('Stock manualy added on before exe', $data->Stock);
1595
1596                 if ($data->Stock['category'] == '8')
1597                 {
1598                         #-> Get latest version.
1599                         $versions   = $this->em->createQuery(
1600                                 'SELECT MAX(vehicleType.createVersion) AS createVersion,'
1601                                 . ' MAX(vehicleType.updateVersion) AS updateVersion '
1602                                 . 'FROM Stock\\Entity\\Type vehicleType'
1603                         )
1604                                 ->getScalarResult();
1605                         $newVersion = $versions[0]['createVersion'] > $versions[0]['updateVersion']
1606                                 ? $versions[0]['createVersion'] + 1
1607                                 : $versions[0]['updateVersion'] + 1;
1608
1609                         #-> Create make, model, type entries
1610                         $makeManual  = $data->Stock['makeManual'];
1611                         $modelManual = $data->Stock['modelManual'];
1612                         $typeManual  = $data->Stock['typeManual'];
1613                         $category    = $data->Stock['category'];
1614                         $today       = new \DateTime();
1615                         $em          = \Utility\Registry::getEntityManager();
1616
1617                         // Make
1618                         // Do a check if this make exists
1619                         if ('' != $makeManual && $makeManual != $data->Stock['make'])
1620                         {
1621                                 $make = $em->getRepository('\Stock\Entity\Make')
1622                                         ->findOneBy(array(
1623                                                             'name' => $makeManual
1624                                                     ));
1625
1626                                 if (is_null($make))
1627                                 {
1628                                         // Else add Make Manual
1629                                         $make     = new \Stock\Entity\Make();
1630                                         $makeData = array(
1631                                                 'name'          => $makeManual,
1632                                                 'created'       => $today,
1633                                                 'createVersion' => $newVersion
1634                                         );
1635
1636                                         $make->fromArray($makeData);
1637                                         $em->persist($make);
1638                                         $em->flush();
1639                                 }
1640                                 // get make id back
1641                                 $makeId = $make->id;
1642                         }
1643                         else
1644                         {
1645                                 $makeId = $data->Stock['make'];
1646                         }
1647
1648
1649                         // Model
1650                         if ('' != $modelManual && $modelManual != $data->Stock['model'])
1651                         {
1652                                 // Do a check if this model exists
1653                                 $model = $em->getRepository('\Stock\Entity\Model')
1654                                         ->findOneBy(array(
1655                                                             'make' => $makeId,
1656                                                             'name' => $makeManual
1657                                                     ));
1658
1659                                 if (is_null($model))
1660                                 {
1661                                         // Add Model Manual
1662                                         $model     = new \Stock\Entity\Model();
1663                                         $modelData = array(
1664                                                 'make'          => $em->getRepository('\Stock\Entity\Make')->find($makeId),
1665                                                 'name'          => $modelManual,
1666                                                 'created'       => $today,
1667                                                 'createVersion' => $newVersion
1668
1669                                         );
1670
1671                                         $model->fromArray($modelData);
1672                                         $em->persist($model);
1673                                         $em->flush();
1674                                 }
1675                                 //get model id back
1676                                 $modelId = $model->id;
1677                         }
1678                         else
1679                         {
1680                                 $modelId = $data->Stock['model'];
1681                         }
1682
1683                         // Type
1684                         if ('' != $typeManual && $typeManual != $data->Stock['type'])
1685                         {
1686                                 // Do a check if this type exists
1687                                 $type = $em->getRepository('\Stock\Entity\Type')
1688                                         ->findOneBy(array(
1689                                                             'model'    => $modelId,
1690                                                             'category' => $category,
1691                                                             'name'     => $typeManual
1692                                                     ));
1693
1694                                 if (is_null($type))
1695                                 {
1696                                         // Add Type Manual
1697                                         $type     = new \Stock\Entity\Type();
1698                                         $typeData = array(
1699                                                 'model'         => $em->getRepository('\Stock\Entity\Model')->find($modelId),
1700                                                 'category'      => $em->getRepository('\Stock\Entity\Category')->find($category),
1701                                                 'name'          => $typeManual,
1702                                                 'mmCode'        => 'other',
1703                                                 'introYear'     => $em->getRepository('\Stock\Entity\Year')->find(1),
1704                                                 'introMonth'    => '1',
1705                                                 'created'       => $today,
1706                                                 'createVersion' => $newVersion
1707
1708                                         );
1709
1710                                         $type->fromArray($typeData);
1711                                         $em->persist($type);
1712                                         $em->flush();
1713
1714                                 }
1715                                 //get model id back
1716                                 $typeId = $type->id;
1717
1718                                 #-> Update data with new ids
1719                                 $data->Stock['type'] = $typeId;
1720                         }
1721
1722                 }
1723
1724                 return $data;
1725         }
1726
1727
1728     /**
1729      * ExecuteAfter: Create
1730      * @param array $meta
1731      * @param array $data
1732      */
1733     public function sendEmailToValuator($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1734     {
1735 //        error_log('sendEmailToValuator');
1736
1737         // do a check here for input
1738         $record = $record
1739             ? $record
1740             : $jobRecord;
1741
1742
1743 //        \Utility\Debug::errorLog('$record', $record->id);
1744
1745         $profileEntry = $this->em->getRepository('\\User\\Entity\\Profile')
1746             ->findBy(array(
1747                 'company'                       => $record->stock->company->id,
1748                 'permissions'               => '7',
1749                 'archived'                      => 0
1750             ));
1751
1752         if(!is_null($profileEntry))
1753         {
1754             foreach ($profileEntry as $profile)
1755             {
1756 //                \Utility\Debug::errorLog('$profile', $profile->id);
1757
1758                 $toCompanyId    = $record->stock->company->id;
1759                 $toProfileId    = $profile->id;
1760                 $email                  = $profile->email;
1761                 $mobile                 = null;
1762                 $subject                = "Public Valuation for " . $record->firstName . " " . $record->familyName;
1763                 $templateName   = 'public-general';
1764
1765                 $params['body'] = '<table border="0" cellspacing="0" cellpadding="0" width="600" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:600px; font-family: Arial, Sans-serif; font-size:12px;">
1766                             <tr>
1767                                 <td width="100%" valign="top" style="width:100%;">
1768                                     Good Day!
1769                                 </td>
1770                             </tr>
1771                             <tr>
1772                                 <td width="100%" valign="top" style="width:100%;">
1773                                     &nbsp;
1774                                 </td>
1775                             </tr>
1776                         </table>
1777                         <table border="0" cellspacing="0" cellpadding="0" width="600" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:600px; font-family: Arial, Sans-serif; font-size:12px;">
1778                             <tr>
1779                                  <td width="100%" valign="top" style="width:100%;">
1780                                  A new public valuation request has been submitted, please log into Bid4Cars to view the valuation:
1781                                  <br>
1782                                 </td>
1783                             </tr>
1784                             <tr>
1785                                 <td width="100%" valign="top" style="width:100%;">';
1786                 $params['body'] .=  $record->stock->registrationNumber;
1787                 $params['body'] .=  '    </td>
1788                             </tr>
1789                                                         <tr>
1790                                 <td width="100%" valign="top" style="width:100%;">';
1791                 $params['body'] .=  $record->stock->vehicleYear->name;
1792                 $params['body'] .=  '    </td>
1793                             </tr>
1794                                                         <tr>
1795                                 <td width="100%" valign="top" style="width:100%;">';
1796                 $params['body'] .=  $record->stock->type->model->make->name;
1797                 $params['body'] .=  '    </td>
1798                             </tr>
1799                                                         <tr>
1800                                 <td width="100%" valign="top" style="width:100%;">';
1801                 $params['body'] .=  $record->stock->type->model->name;
1802                 $params['body'] .=  '    </td>
1803                             </tr>
1804                                                         <tr>
1805                                 <td width="100%" valign="top" style="width:100%;">';
1806                 $params['body'] .=  $record->stock->type->name;
1807                 $params['body'] .=  '    </td>
1808                             </tr>
1809                         </table>
1810                         <table border="0" cellspacing="0" cellpadding="0" width="600" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:600px; font-family: Arial, Sans-serif; font-size:12px;">
1811                             <tr>
1812                                 <td width="100%" valign="top" style="width:100%;">
1813                                     &nbsp;
1814                                 </td>
1815                             </tr>
1816                             <tr>
1817                                 <td width="100%" valign="top" style="width:100%;">
1818                                     Regards
1819                                 </td>
1820                             </tr>
1821                             <tr>
1822                                 <td width="100%" valign="top" style="width:100%;">
1823                                     WePay4Cars Team
1824                                 </td>
1825                             </tr>
1826                         </table>';
1827
1828                 $params['smsBody'] = '';
1829
1830 //                error_log('email body');
1831 //                error_log($params['body']);
1832
1833                 $oNotify = new \Utility\Comms\Notification();
1834                 $oNotify->sendFromTemplate(
1835                     null,
1836                     null,
1837                     $toCompanyId,
1838                     $toProfileId,
1839                     $email,
1840                     $mobile,
1841                     $subject,
1842                     $templateName,
1843                     $params
1844                 );
1845
1846
1847             }
1848         }
1849
1850     }
1851
1852
1853     /**
1854      * ExecuteAfter: Create
1855      * @param array $meta
1856      * @param array $data
1857      */
1858     public function sendPublicCustomerEmail($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1859     {
1860 //        error_log('sendPublicCustomerEmail');
1861
1862         is_null($jobRecord)
1863             ? $jobRecord->stock->valuation = $jobRecord
1864             : $record->stock->valuation = $record;
1865         $this->em->flush();
1866
1867         // do a check here for input
1868         $record = $record
1869             ? $record
1870             : $jobRecord;
1871
1872
1873         $record->valuatedBy = isset($authData['id']) ? $authData['id'] : null;
1874         $this->em->flush($record);
1875
1876
1877 //        // valuation = $record, stock = $record->stock->refNum
1878 //
1879 //        if (!\Utility\Registry::isAuthenticated())
1880 //        {
1881 //            // set valuations flag to is-public true
1882 //            $record->isPublic = true;
1883 //            $this->em->flush($record);
1884 //        }
1885
1886         $customerPublicValuationEntry = $this->em->getRepository('\\Valuation\\Entity\\CustomerPublicValuation')
1887             ->findOneBy(array(
1888                 'valuation'             => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
1889                 'stock'             => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
1890                 'archived'                      => false
1891             ));
1892
1893
1894         $fromCompanyId  = isset($authData['company']['id']) ? $authData['company']['id'] : null;
1895         $fromProfileId  = isset($authData['id']) ? $authData['id'] : null;
1896
1897         $toCompanyId    = $fromCompanyId;
1898         $toProfileId    = $record->valuatedBy;
1899         $email                  = $record->email;
1900         $mobile                 = null;
1901         $subject                = "Valuation for " . $record->firstName . " " . $record->familyName;
1902         $templateName   = 'public-general';
1903
1904         $params['body'] = '<table border="0" cellspacing="0" cellpadding="0" width="600" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:600px; font-family: Arial, Sans-serif; font-size:12px;">
1905                             <tr>
1906                                 <td width="100%" valign="top" style="width:100%;">
1907                                     Good Day ' . $record->firstName . ' ' . $record->familyName . ',
1908                                 </td>
1909                             </tr>
1910                             <tr>
1911                                 <td width="100%" valign="top" style="width:100%;">
1912                                     &nbsp;
1913                                 </td>
1914                             </tr>
1915                             <tr>
1916                                 <td width="100%" valign="top" style="width:100%;">
1917                                    Thank you for making use of <a target="blank" href="';
1918         $params['body'] .=  IS_LIVE_ENV ? "http://www.wepay4cars.co.za/" : "http://cash-cars.nirph.com";
1919         $params['body'] .=  '">WePay4Cars</a>.
1920                                 </td>
1921                             </tr>
1922                             <tr>
1923                                 <td width="100%" valign="top" style="width:100%;">
1924                                     We would be interested at a price of around R' . $record->amountOffered . '
1925                                 </td>
1926                             </tr>
1927                         </table>
1928                         <table border="0" cellspacing="0" cellpadding="0" width="600" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:600px; font-family: Arial, Sans-serif; font-size:12px;">
1929                             <tr>
1930                                  <td width="100%" valign="top" style="width:100%;">
1931                                   Please click on the below link to continue with the valuation process.
1932                                 </td>
1933                             </tr>
1934                             <tr>
1935                                 <td width="100%" valign="top" style="width:100%;">
1936                                  <a target="blank" href="';
1937         $params['body'] .=  IS_LIVE_ENV ? "http://www.wepay4cars.co.za/" : "http://cash-cars.nirph.com";
1938         $params['body'] .=  '/#/customercompletevaluation?customer=';
1939         $params['body'] .=  $customerPublicValuationEntry->customerHash;
1940         $params['body'] .=  '"><h1>Continue valuation</h1></a>
1941                                 </td>
1942                             </tr>
1943                             <tr>
1944                                 <td width="100%" valign="top" style="width:100%;">
1945                                     &nbsp;
1946                                 </td>
1947                             </tr>
1948                         </table>
1949                         <table border="0" cellspacing="0" cellpadding="0" width="600" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:600px; font-family: Arial, Sans-serif; font-size:12px;">
1950                             <tr>
1951                                 <td width="100%" valign="top" style="width:100%;">
1952                                     &nbsp;
1953                                 </td>
1954                             </tr>
1955                             <tr>
1956                                 <td width="100%" valign="top" style="width:100%;">
1957                                     Regards
1958                                 </td>
1959                             </tr>
1960                             <tr>
1961                                 <td width="100%" valign="top" style="width:100%;">
1962                                     WePay4Cars Team
1963                                 </td>
1964                             </tr>
1965                         </table>';
1966         $params['smsBody'] = '';
1967
1968
1969 //        error_log('email body');
1970 //        error_log($params['body']);
1971
1972         $oNotify = new \Utility\Comms\Notification();
1973         $oNotify->sendFromTemplate(
1974             $fromCompanyId,
1975             $fromProfileId,
1976             $toCompanyId,
1977             $toProfileId,
1978             $email,
1979             $mobile,
1980             $subject,
1981             $templateName,
1982             $params
1983         );
1984     }
1985
1986
1987     /**
1988      * ExecuteAfter: Create
1989      * @param array $meta
1990      * @param array $data
1991      */
1992     public function setAppointmentData($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1993     {
1994 //        error_log('setAppointmentData');
1995
1996 //        is_null($jobRecord)
1997 //            ? $jobRecord->stock->valuation = $jobRecord
1998 //            : $record->stock->valuation = $record;
1999 //        $this->em->flush();
2000
2001         // do a check here for input
2002         $record = $record
2003             ? $record
2004             : $jobRecord;
2005
2006 //        \Utility\Debug::errorLog('$contract', $contract->data->Valuation);
2007
2008 //        [valuatorSelected] => 561
2009 //                    [dateSelected] => 2015-09-24
2010 //                    [timeIdSelected] => 5
2011
2012
2013
2014         $valuationAppointmentsEntry = $this->em->getRepository('\\Valuation\\Entity\\ValuationAppointments')
2015         ->findOneBy(array(
2016             'valuation'                 => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
2017             'valuator'              => $this->em->getReference('\\User\Entity\Profile', $contract->data->Valuation['valuatorSelected']),
2018             'timeSlot'          => $this->em->getReference('\\Valuation\Entity\ValuationTimeSlots', $contract->data->Valuation['timeIdSelected']),
2019             'appointmentDate'   => new \DateTime($contract->data->Valuation['dateSelected']),
2020             'archived'                  => false
2021         ));
2022
2023
2024         if(is_null($valuationAppointmentsEntry) && empty($valuationAppointmentsEntry))
2025         {
2026             $valuationAppointmentsEntry = new \Valuation\Entity\ValuationAppointments();
2027         }
2028
2029         $valuationAppointmentsData = array(
2030             'valuation'                 => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
2031             'valuator'              => $this->em->getReference('\\User\Entity\Profile', $contract->data->Valuation['valuatorSelected']),
2032             'timeSlot'          => $this->em->getReference('\\Valuation\Entity\ValuationTimeSlots', $contract->data->Valuation['timeIdSelected']),
2033             'appointmentDate'   => new \DateTime($contract->data->Valuation['dateSelected'])
2034         );
2035
2036         $valuationAppointmentsEntry->fromArray($valuationAppointmentsData);
2037         $this->em->persist($valuationAppointmentsEntry);
2038         $this->em->flush();
2039
2040
2041
2042         $record->valuatedBy = isset($authData['id']) ? $authData['id'] : null;
2043         $this->em->flush($record);
2044
2045
2046 //        // valuation = $record, stock = $record->stock->refNum
2047 //
2048 //        if (!\Utility\Registry::isAuthenticated())
2049 //        {
2050 //            // set valuations flag to is-public true
2051 //            $record->isPublic = true;
2052 //            $this->em->flush($record);
2053 //        }
2054
2055         $customerPublicValuationEntry = $this->em->getRepository('\\Valuation\\Entity\\CustomerPublicValuation')
2056             ->findOneBy(array(
2057                 'valuation'             => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
2058                 'stock'             => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
2059                 'archived'                      => false
2060             ));
2061
2062
2063 //        \Utility\Debug::errorLog('$valuationAppointmentsEntry->appointmentDate', $valuationAppointmentsEntry->appointmentDate);
2064
2065         $appointmentDate = new \DateTime($valuationAppointmentsEntry->appointmentDate->date);
2066
2067         $fromCompanyId  = isset($authData['company']['id']) ? $authData['company']['id'] : null;
2068         $fromProfileId  = isset($authData['id']) ? $authData['id'] : null;
2069
2070         $toCompanyId    = $fromCompanyId;
2071         $toProfileId    = $record->valuatedBy;
2072         $email                  = $record->email;
2073         $mobile                 = null;
2074         $subject                = "Notification of successful submission of vehicle";
2075         $templateName   = 'public-general';
2076
2077 //        \Utility\Debug::errorLog('$record->id', $record->id);
2078 //        \Utility\Debug::errorLog('$record->stock->id', $record->stock->id);
2079 //        \Utility\Debug::errorLog('$record->stock->type->id', $record->stock->type->id);
2080 //        \Utility\Debug::errorLog('$record->stock->type->name', $record->stock->type->name);
2081 //        \Utility\Debug::errorLog('$record->stock->type->model->name', $record->stock->type->model->name);
2082 //        \Utility\Debug::errorLog('$record->stock->type->model->make->name', $record->stock->type->model->make->name);
2083
2084
2085         $params['body'] = '<table border="0" cellspacing="0" cellpadding="0" width="600" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:600px; font-family: Arial, Sans-serif; font-size:12px;">
2086                             <tr>
2087                                 <td width="100%" valign="top" style="width:100%;">
2088                                     Good Day ' . $record->firstName . ' ' . $record->familyName . ',
2089                                 </td>
2090                             </tr>
2091                             <tr>
2092                                 <td width="100%" valign="top" style="width:100%;">
2093                                     &nbsp;
2094                                 </td>
2095                             </tr>
2096                             <tr>
2097                                 <td width="100%" valign="top" style="width:100%;">
2098                                     We would like to confirm that the following vehicle was successfully submitted to <a target="blank" href="{APP_HOST}">WePay4Cars</a> for valuation.
2099                                 </td>
2100                             </tr>
2101                             <tr>
2102                                 <td width="100%" valign="top" style="width:100%;">
2103                                     &nbsp;
2104                                 </td>
2105                             </tr>
2106                         </table>
2107                         <table border="0" cellspacing="0" cellpadding="0" width="800" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:800px; font-family: Arial, Sans-serif; font-size:12px;">
2108                             <tr>
2109                                 <td width="10" valign="top" style="width:10px;">&nbsp;</td>
2110                                 <td width="50" valign="top" style="width:50px; font-family: Arial, Sans-serif; font-size:12px;">
2111                                     <b>Year:</b>
2112                                 </td>
2113                                 <td width="180" valign="top" style="width:180px;">
2114                                     ' . $record->stock->vehicleYear->name . '
2115                                 </td>
2116                                 <td width="20" valign="top" style="width:20px;">&nbsp;</td>
2117                             </tr>
2118                             <tr>
2119                                 <td width="10" valign="top" style="width:10px;">&nbsp;</td>
2120                                 <td width="50" valign="top" style="width:50px; font-family: Arial, Sans-serif; font-size:12px;">
2121                                     <b>Make:</b>
2122                                 </td>
2123                                 <td width="180" valign="top" style="width:180px;">
2124                                    ' . $record->stock->type->model->make->name . '
2125                                 </td>
2126                                 <td width="20" valign="top" style="width:20px;">&nbsp;</td>
2127                             </tr>
2128                             <tr>
2129                                 <td width="10" valign="top" style="width:10px;">&nbsp;</td>
2130                                 <td width="50" valign="top" style="width:50px; font-family: Arial, Sans-serif; font-size:12px;">
2131                                     <b>Model:</b>
2132                                 </td>
2133                                 <td width="180" valign="top" style="width:180px;">
2134                                    ' . $record->stock->type->model->name . '
2135                                 </td>
2136                                 <td width="20" valign="top" style="width:20px;">&nbsp;</td>
2137                             </tr>
2138                             <tr>
2139                                 <td width="10" valign="top" style="width:10px;">&nbsp;</td>
2140                                 <td width="50" valign="top" style="width:50px; font-family: Arial, Sans-serif; font-size:12px;">
2141                                     <b>Type:</b>
2142                                 </td>
2143                                 <td width="180" valign="top" style="width:180px;">
2144                                     ' . $record->stock->type->name . '
2145                                 </td>
2146                                 <td width="20" valign="top" style="width:20px;">&nbsp;</td>
2147                             </tr>
2148                             <tr>
2149                                 <td width="10" valign="top" style="width:10px;">&nbsp;</td>
2150                                 <td width="50" valign="top" style="width:50px; font-family: Arial, Sans-serif; font-size:12px;">
2151                                     <b>Reg no:</b>
2152                                 </td>
2153                                 <td width="180" valign="top" style="width:180px;">
2154                                     ' . $record->stock->registrationNumber . '
2155                                 </td>
2156                                 <td width="20" valign="top" style="width:20px;">&nbsp;</td>
2157                             </tr>
2158                         </table>
2159                         <table border="0" cellspacing="0" cellpadding="0" width="600" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:600px; font-family: Arial, Sans-serif; font-size:12px;">
2160                             <tr>
2161                                 <td width="100%" valign="top" style="width:100%;">
2162                                     &nbsp;
2163                                 </td>
2164                             </tr>
2165                             <tr>
2166                                 <td width="100%" valign="top" style="width:100%;">
2167                                     Please note that the price offered on your vehicle is subject to final viewing.
2168                                 </td>
2169                             </tr>
2170                             <tr>
2171                                 <td width="100%" valign="top" style="width:100%;">
2172                                     Your booking for valuation will take place at:
2173                                 </td>
2174                             </tr>
2175                             <tr>
2176                                 <td width="100%" valign="top" style="width:100%;">
2177                                     &nbsp;
2178                                 </td>
2179                             </tr>
2180                         </table>
2181                         <table border="0" cellspacing="0" cellpadding="0" width="600" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:600px; font-family: Arial, Sans-serif; font-size:12px;">
2182                             <tr>
2183                                 <td width="100%" valign="top" style="width:100%; font-family: Arial, Sans-serif; font-size:17px; font-weight:bold;">';
2184         $params['body'] .= $record->stock->company->name . ' ( ' . null != $record->stock->company->contact->office ? null != $record->stock->company->contact->office : $record->stock->company->contact->mobile . ' ) ';
2185         $params['body'] .=  '</td>
2186                             </tr>
2187                             <tr>
2188                                 <td width="100%" valign="top" style="width:100%;">
2189                                     &nbsp;
2190                                 </td>
2191                             </tr>
2192                             <tr>
2193                                 <td width="100%" valign="top" style="width:100%;font-weight:bold;font-size:14px;">
2194                                     Date / Time:
2195                                 </td>
2196                             </tr>
2197                             <tr>
2198                                 <td width="100%" valign="top" style="width:100%;">
2199                                     ' . $appointmentDate->format('Y-m-d') . '
2200                                 </td>
2201                             </tr>
2202                             <tr>
2203                                 <td width="100%" valign="top" style="width:100%;">
2204                                     ' . $valuationAppointmentsEntry->timeSlot->timeSlotDisplayName . '
2205                                 </td>
2206                             </tr>
2207                             <tr>
2208                                 <td width="100%" valign="top" style="width:100%;">
2209                                     &nbsp;
2210                                 </td>
2211                             </tr>
2212                             <tr>
2213                                 <td width="100%" valign="top" style="width:100%;font-weight:bold;font-size:14px;">
2214                                     Your Address:
2215                                 </td>
2216                             </tr>
2217                             <tr>
2218                                 <td width="100%" valign="top" style="width:100%;">
2219                                     ' . $record->customerAddressStreet . '
2220                                 </td>
2221                             </tr>
2222                             <tr>
2223                                 <td width="100%" valign="top" style="width:100%;">
2224                                     ' . $record->customerAddressStreetName . '
2225                                 </td>
2226                             </tr>
2227                             <tr>
2228                                 <td width="100%" valign="top" style="width:100%;">
2229                                     ' . $record->customerAddressSuburb . '
2230                                 </td>
2231                             </tr>
2232                             <tr>
2233                                 <td width="100%" valign="top" style="width:100%;">
2234                                     ' . $record->customerAddressCity . '
2235                                 </td>
2236                             </tr>
2237                             <tr>
2238                                 <td width="100%" valign="top" style="width:100%;">
2239                                     ' . $record->customerAddressPostalCode . '
2240                                 </td>
2241                             </tr>
2242                             <tr>
2243                                 <td width="100%" valign="top" style="width:100%;">
2244                                     &nbsp;
2245                                 </td>
2246                             </tr>
2247                             <tr>
2248                                 <td width="100%" valign="top" style="width:100%;font-weight:bold;font-size:14px;">
2249                                     Email:
2250                                 </td>
2251                             </tr>
2252                             <tr>
2253                                 <td width="100%" valign="top" style="width:100%;">
2254                                    ' . $record->email . '
2255                                 </td>
2256                             </tr>
2257                         </table>
2258                         <table border="0" cellspacing="0" cellpadding="0" width="600" style="border-collapse:collapse; border-spacing:0; margin:0; padding:0; width:600px; font-family: Arial, Sans-serif; font-size:12px;">
2259                             <tr>
2260                                 <td width="100%" valign="top" style="width:100%;">
2261                                     &nbsp;
2262                                 </td>
2263                             </tr>
2264                             <tr>
2265                                 <td width="100%" valign="top" style="width:100%;">
2266                                     Regards
2267                                 </td>
2268                             </tr>
2269                             <tr>
2270                                 <td width="100%" valign="top" style="width:100%;">
2271                                     WePay4Cars Team
2272                                 </td>
2273                             </tr>
2274                         </table>';
2275         $params['smsBody'] = '';
2276
2277
2278 //        error_log('email body');
2279 //        error_log($params['body']);
2280
2281         $oNotify = new \Utility\Comms\Notification();
2282         $oNotify->sendFromTemplate(
2283             $fromCompanyId,
2284             $fromProfileId,
2285             $toCompanyId,
2286             $toProfileId,
2287             $email,
2288             $mobile,
2289             $subject,
2290             $templateName,
2291             $params
2292         );
2293
2294 //        //Dealership manager (or default contact for the dealer on the B4C system)
2295 //        if(!empty($record->stock->company->contact->email) && null != $record->stock->company->contact->email)
2296 //        {
2297 //            $oNotify = new \Utility\Comms\Notification();
2298 //            $oNotify->sendFromTemplate(
2299 //                $fromCompanyId,
2300 //                $fromProfileId,
2301 //                $toCompanyId,
2302 //                $toProfileId,
2303 //                $record->stock->company->contact->email,
2304 //                null,
2305 //                $subject,
2306 //                $templateName,
2307 //                $params
2308 //            );
2309 //        }
2310 //
2311 //
2312 //        //Valuator
2313 //        if(!empty($record->valuatedBy) && null != $record->valuatedBy)
2314 //        {
2315 //            $oNotify = new \Utility\Comms\Notification();
2316 //            $oNotify->sendFromTemplate(
2317 //                $fromCompanyId,
2318 //                $fromProfileId,
2319 //                $toCompanyId,
2320 //                $toProfileId,
2321 //                $record->valuatedBy->email,
2322 //                null,
2323 //                $subject,
2324 //                $templateName,
2325 //                $params
2326 //            );
2327 //        }
2328
2329
2330     }
2331
2332
2333         /**
2334          * ExecuteAfter: Create.
2335          * Push change to mobile devices.
2336          * @param array                                 $meta
2337          * @param object|null                           $jobRecord
2338          * @param object|null                           $record
2339          * @param \Workspace\Utility\ServiceInputParams $contract
2340          * @return array
2341          */
2342         public function pushCreateAction($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
2343         {
2344                 //-- Pass to backend function so we don't hold up the user response.
2345                 $userId = \Utility\Registry::isAuthenticated()
2346                         ? \Utility\Registry::getAuthParam('id')
2347                         : 0;
2348                 exec("php /var/www/B4C2/public/index.php valuation change 1 " . $record->id . " $userId  > /dev/null &");
2349         }
2350
2351         /**
2352          * ExecuteAfter: Update.
2353          * Push change to mobile devices.
2354          * @param array                                 $meta
2355          * @param object|null                           $jobRecord
2356          * @param object|null                           $record
2357          * @param \Workspace\Utility\ServiceInputParams $contract
2358          * @return array
2359          */
2360         public function pushUpdateAction($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
2361         {
2362                 //-- Pass to backend function so we don't hold up the user response.
2363                 $userId = \Utility\Registry::isAuthenticated()
2364                         ? \Utility\Registry::getAuthParam('id')
2365                         : 0;
2366                 exec("php /var/www/B4C2/public/index.php valuation change 2 " . $record->id . " $userId  > /dev/null &");
2367         }
2368
2369         /**
2370          * ExecuteAfter: Delete.
2371          * Push change to mobile devices.
2372          * @param array                                 $meta
2373          * @param object|null                           $jobRecord
2374          * @param object|null                           $record
2375          * @param \Workspace\Utility\ServiceInputParams $contract
2376          * @return array
2377          */
2378         public function pushDeleteAction($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
2379         {
2380                 //-- Pass to backend function so we don't hold up the user response.
2381                 $userId = \Utility\Registry::isAuthenticated()
2382                         ? \Utility\Registry::getAuthParam('id')
2383                         : 0;
2384                 exec("php /var/www/B4C2/public/index.php valuation change 3 " . $record->id . " $userId  > /dev/null &");
2385         }
2386
2387         /**
2388          * Push change notifications for stock item change.
2389          * @param $changeCode
2390          * @param $id
2391          * @param $skipId
2392          */
2393         public function pushChange($changeCode, $id, $skipId)
2394         {
2395                 //-- Safety check.
2396                 $valuation = $this->em->find('Valuation\\Entity\\Valuation', $id);
2397
2398                 $minDate = new \DateTime('last month');
2399                 if ($minDate->getTimestamp() > $valuation->stock->created->getTimestamp()
2400                     || 8 == $valuation->stock->type->category->id
2401                 )
2402                 {
2403                         //-- Nothing to do, old record.
2404                         return;
2405                 }
2406
2407                 //-- Send it to relevant people.
2408                 $registrations = $this->em->getRepository('Company\\Entity\\DeviceRegistration')
2409                         ->findBy(
2410                                 array(
2411                                         'company' => $valuation->stock->company->id
2412                                 )
2413                         );
2414                 $ids           = array();
2415                 foreach ($registrations as $registration)
2416                 {
2417                         if (/*$registration->profile->id != $skipId
2418                             && */0 < strlen($registration->device->registrationId)
2419                         )
2420                         {
2421                                 $ids[] = $registration->device->registrationId;
2422                         }
2423                 }
2424                 \Utility\Comms\Gcm::send(
2425                         $ids,
2426                         array(
2427                                 'changeCode' => (int) $changeCode,
2428                                 'changeId'   => (int) $valuation->stock->uvi
2429                         )
2430                 );
2431         }
2432
2433     /**
2434      * Contract to list vehicle types according to Category and Year.
2435      * @param object|null $jobRecord
2436      * @param array $input
2437      * @return \Workspace\Contract\UseOnce
2438      */
2439     public function contractDealNotDoneSelection($jobRecord, array $input = array())
2440     {
2441         $options = new \Workspace\UseCase\Options();
2442         $requirement = new \Workspace\UseCase\Requirement();
2443
2444         return new \Workspace\Contract\Recurring($options, $requirement);
2445     }
2446
2447     /**
2448      * List vehicle types according to Category and Year.
2449      * @param object|null $jobRecord
2450      * @param \Workspace\Utility\ServiceInputParams $contract
2451      * @return array
2452      */
2453     public function executeDealNotDoneSelection($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
2454     {
2455         $dql = 'SELECT dnds.id as value,dnds.name as label '
2456             . 'FROM \Valuation\Entity\DealNotDoneSelection dnds '
2457             . ' GROUP BY dnds.name'
2458             . ' ORDER BY dnds.id';
2459         $dataGet = $this->em->createQuery($dql)
2460             ->getArrayResult();
2461
2462 //        \Utility\Debug::errorLog("dataGet", $dataGet);
2463
2464         $data = array();
2465
2466         foreach($dataGet as $dataProcess)
2467         {
2468             array_push($data,array(
2469                 'value' => $dataProcess['value'],
2470                 'label' => $dataProcess['label']
2471             ));
2472         }
2473
2474         return $contract->success('Data Collected.', $data);
2475
2476     }
2477
2478
2479 }