2 namespace Valuation\Service;
3 use Doctrine\Common\Util\Debug;
7 * Manage Valuation data.
10 class Valuation extends \Valuation\DataBin\Valuation
14 public function initNewItem(\Valuation\Entity\Valuation $valuation)
19 * Route newly added item to initial state.
20 * @param \Valuation\Entity\Valuation
21 * @param string|null $previousState
22 * @param array|null $routingData
25 public function routeNewItem(\Valuation\Entity\Valuation $valuation, $previousState, $routingData)
29 $status = \Utility\Registry::checkOnce('NewValuationItem.Status', 'This.NewValuation');
30 $data = \Utility\Registry::checkOnce('Service.Valuation.Context', array());
32 if ('PriceGuide.NewItemFromValuation' == $status)
34 $valuation->previousState = 'Pending Valuation';
36 if ('This.Stock' == $status)
38 $valuation->previousState = 'Pending Valuation';
41 'Destination' => $status,
48 * Deal Done for stats.
49 * @param \Valuation\Entity\Valuation
50 * @param string|null $previousState
51 * @param array|null $routingData
54 public function directRouteMoveToDealDone(\Valuation\Entity\Valuation $valuation, $previousState)
56 //Write hit to Stats logs (need stock or valuation stock id and profile id)
57 $today = new \DateTime();
59 //\Utility\Debug::errorLog('New dealDone', $test);
61 $em = \Utility\Registry::getEntityManager();
62 $loghit = new \Statistical\Entity\Statistical();
64 'stock' => $em->getRepository('\Stock\Entity\Stock')->find($valuation->stock->id),
66 'dealnotdone' => false,
67 'tradecentre' => false,
68 'fromProfile' => $em->getRepository('\User\Entity\Profile')->find($valuation->stock->createdBy->id),
71 $loghit->fromArray($loghitData);
72 $em->persist($loghit);
73 $valuation->stock->previousState = $valuation->stock->jobState;
74 $valuation->stock->jobState = 'Stock';
81 * Deal Not Done for stats.
82 * @param \Valuation\Entity\Valuation
83 * @param string|null $previousState
86 public function directRouteMoveToDealNotDone(\Valuation\Entity\Valuation $valuation, $previousState)
89 // Add XML to Higher Gear
92 if ($valuation->isPublic)
94 // remove +27 and add 0 like -> +2711xxxx becomes 011xxx
95 $mobileNumber = $valuation->mobile;
96 $mobileNumFormat = substr($mobileNumber, 3);
97 $mobileNumFormat = 0 . $mobileNumFormat;
103 <?xml version="1.0"?>
104 <?ADF version="1.0"?>
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>
118 <interiorcolor>' . $valuation->stock->exteriorColour->name . '</interiorcolor>
119 <exteriorcolor>' . $valuation->stock->interiorColour->name . '</exteriorcolor>
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>
134 <comments></comments>
138 <vendorname>bid4cars.co.za</vendorname>
140 <name part="full">unknown</name>
141 <email>dm1408082@highergear.net</email>
146 <name>' . $valuation->stock->company->name . '</name>
152 $mailer = new \Utility\Comms\Email();
154 'From' => \Utility\Registry::getConfigParam('sourceEmailAddress'),
155 'To' => 'dm1408082@highergear.net',
156 'Subject' => 'Deal Not Done Valuation XML',
157 'Body' => $xmlTemplateDnd
161 $mailer = new \Utility\Comms\Email();
163 'From' => \Utility\Registry::getConfigParam('sourceEmailAddress'),
164 'To' => 'b4c@nirph.com',
165 'Subject' => 'Deal Not Done Valuation XML',
166 'Body' => $xmlTemplateDnd
170 #-> Log notification entry.
171 $em = \Utility\Registry::getEntityManager();
173 $log = new \Utility\Entity\NotificationLog();
175 'emailTo' => 'dm1408082@highergear.net',
176 'emailSubject' => 'Deal Not Done Valuation XML',
177 'emailBody' => $xmlTemplateDnd,
183 $log->fromArray($logData);
188 $log = new \Utility\Entity\NotificationLog();
190 'emailTo' => 'b4c@nirph.com',
191 'emailSubject' => 'Deal Not Done Valuation XML',
192 'emailBody' => $xmlTemplateDnd,
198 $log->fromArray($logData);
205 //Write hit to Stats logs (need stock or valuation stock id and profile id)
206 $today = new \DateTime();
208 //\Utility\Debug::errorLog('dealNotDone new', $test);
210 $em = \Utility\Registry::getEntityManager();
211 $loghit = new \Statistical\Entity\Statistical();
213 'stock' => $em->getRepository('\Stock\Entity\Stock')->find($valuation->stock->id),
215 'dealnotdone' => true,
216 'tradecentre' => false,
217 'fromProfile' => $em->getRepository('\User\Entity\Profile')->find($valuation->stock->createdBy->id),
221 $loghit->fromArray($loghitData);
222 $em->persist($loghit);
225 if ('Price Guide' == $valuation->jobState)
227 $this->workflowNode->handover('Price Guide', $valuation->id);
229 $workflow = \Utility\Registry::getServiceManager()
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) = '
240 . ' AND o.status != \'Archived\''
244 return 'This.Archived';
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
255 public function routePriceGuideHandover(\Valuation\Entity\Valuation $valuation, $previousState, $routingData)
257 return $valuation->previousState != 'New Valuation'
258 ? 'This.' . str_replace(' ', '', $valuation->previousState)
259 : 'This.PendingValuation';
263 * Route item to Offer Accepted status.
265 * @param \Valuation\Entity\Valuation $valuation
266 * @param string|null $previousState
269 public function directRouteMoveToOfferAccepted(\Valuation\Entity\Valuation $valuation, $previousState)
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');
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'
289 ->setParameter('priceGuideId', $priceGuide->id)
290 ->setParameter('highestOffer', $valuation->stock->highestOffer)
293 #-> Set offer as accepted and send notification.
294 if (0 < count($result))
296 $item = array_shift($result);
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);
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
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,
331 $item->profile->email,
333 'Price Guide Offer Accepted',
334 'price-guide-offer-accepted',
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,
346 'Price Guide Offer Accepted',
347 'price-guide-offer-accepted',
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,
357 'info@bid4cars.co.za',
359 'Price Guide Offer Accepted',
360 'price-guide-offer-accepted',
364 #-> Notify other bidders.
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
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'
381 ->setParameter('priceGuideId', $priceGuide->id)
383 foreach ($result as $offer)
385 if ($item->id == $offer->id)
389 $offer->status = 'Expired';
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,
399 $offer->profile->email,
401 'price-guide-offer-declined',
405 \Utility\Debug::errorLog('take this to stock ', $valuation->stock->id);
410 * Route item to Stock status.
412 * @param \Valuation\Entity\Valuation $valuation
413 * @param string|null $previousState
416 public function directRouteMoveToKeepForStock(\Valuation\Entity\Valuation $valuation, $previousState)
418 //Write hit to Stats logs (need stock or valuation stock id and profile id)
419 $today = new \DateTime();
421 //\Utility\Debug::errorLog('directRouteMoveToKeepForStock new', $test);
423 $em = \Utility\Registry::getEntityManager();
424 $loghit = new \Statistical\Entity\Statistical();
426 'stock' => $em->getRepository('\Stock\Entity\Stock')->find($valuation->stock->id),
428 'dealnotdone' => false,
429 'tradecentre' => false,
430 'fromProfile' => $em->getRepository('\User\Entity\Profile')->find($valuation->stock->createdBy->id),
434 $loghit->fromArray($loghitData);
435 $em->persist($loghit);
438 #-> Get price guide entry.
439 $priceGuide = $valuation->stock->priceGuide;
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'
451 ->setParameter('priceGuideId', $priceGuide->id)
452 ->setParameter('highestOffer', $valuation->stock->highestOffer)
456 #-> Send notification.
457 if (0 < count($result))
460 $item = array_shift($result);
463 $oNotify = new \Utility\Comms\Notification();
464 $oNotify->sendFromTemplate(
465 $priceGuide->stock->company->id,
466 $priceGuide->stock->createdBy->id,
469 $item->profile->email,
471 'Vehicle retained for stock',
472 'price-guide-keep-stock',
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
491 #-> Notify other bidders.
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
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'
508 ->setParameter('priceGuideId', $priceGuide->id)
510 foreach ($result as $offer)
512 $offer->status = 'Expired';
514 if ($item->id == $offer->id)
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,
526 $offer->profile->email,
528 'price-guide-offer-declined',
532 return 'Stock.Handover';
536 * Route item that is received back from Price Guide Workflow.
537 * @param \Valuation\Entity\Valuation $valuation
538 * @param string $previousState
540 public function directRouteMoveToArchive(\Valuation\Entity\Valuation $valuation, $previousState)
542 $userId = \Utility\Registry::isAuthenticated()
543 ? \Utility\Registry::getAuthParam('id')
545 exec("php /var/www/B4C2/public/index.php valuation change 3 " . $valuation->id . " $userId > /dev/null &");
546 return 'This.Archived';
550 * Route item that is received back from Price Guide Workflow.
551 * @param \Valuation\Entity\Valuation $valuation
552 * @param string $previousState
554 public function directRouteUnArchive(\Valuation\Entity\Valuation $valuation, $previousState)
556 $userId = \Utility\Registry::isAuthenticated()
557 ? \Utility\Registry::getAuthParam('id')
559 exec("php /var/www/B4C2/public/index.php valuation change 1 " . $valuation->id . " $userId > /dev/null &");
560 return 'This.' . str_replace(' ', '', $valuation->previousState);
564 * ExecuteAfter: CreateNew, CreatePending, CreateComplete, CreatePriceGuide, CreateStock.
565 * Set the valuation link on stock item.
567 * @param object|null $jobRecord
568 * @param object|null $record
569 * @param \Workspace\Utility\ServiceInputParams $contract
572 public function setStockLink($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
577 ? $jobRecord->stock->valuation = $jobRecord
578 : $record->stock->valuation = $record;
581 // do a check here for input
586 // valuation = $record, stock = $record->stock->refNum
588 if (!\Utility\Registry::isAuthenticated())
590 // set valuations flag to is-public true
591 $record->isPublic = true;
592 $this->em->flush($record);
598 * ExecuteAfter: CreateNew, CreatePending, CreateComplete, CreatePriceGuide, CreateStock.
599 * Set the valuation link on stock item.
601 * @param object|null $jobRecord
602 * @param object|null $record
603 * @param \Workspace\Utility\ServiceInputParams $contract
606 public function setStockLinkCustomer($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
609 ? $jobRecord->stock->valuation = $jobRecord
610 : $record->stock->valuation = $record;
613 // do a check here for input
618 // valuation = $record, stock = $record->stock->refNum
620 if (!\Utility\Registry::isAuthenticated())
622 // set valuations flag to is-public-customer true
623 $record->isPublicCustomer = true;
624 $this->em->flush($record);
626 // error_log($record->id);
627 // error_log($record->isPublicCustomer);
628 // error_log($record->stock->id);
630 $customerPublicValuationEntry = $this->em->getRepository('\\Valuation\\Entity\\CustomerPublicValuation')
632 'valuation' => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
633 'stock' => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
637 if(empty($customerPublicValuationEntry))
639 $customerPublicValuationEntry = new \Valuation\Entity\CustomerPublicValuation();
643 $custHash = md5($record->id . $record->stock->id . date('Y-m-d H:i'));
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
653 $customerPublicValuationEntry->fromArray($customerPublicValuationArray);
654 $this->em->persist($customerPublicValuationEntry);
658 catch (\Exception $e)
660 error_log('Could not insert customer valuation hash.<br>' . $e);
669 * ExecuteAfter: CreateComplete, RouteMoveToComplete.
671 * @param object|null $jobRecord
672 * @param object|null $record
673 * @param \Workspace\Utility\ServiceInputParams $contract
676 public function sendToSales($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
678 $record = !is_null($record)
682 if ($record->isPublic)
684 // remove +27 and add 0 -> +2711xxxx becomes 011xxx
685 $mobileNumber = $record->mobile;
686 $mobileNumFormat = substr($mobileNumber, 3);
687 $mobileNumFormat = 0 . $mobileNumFormat;
690 // Removed - keep for refrence
691 /* <street>' . $record->street . '</street>
692 <city>' . $citynew . '</city>
693 <regioncode>' . $record->region->name . '</regioncode>
694 <postalcode></postalcode>
696 dm105171@highergear.net
701 <?xml version="1.0"?>
702 <?ADF version="1.0"?>
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>
716 <interiorcolor>' . $record->stock->exteriorColour->name . '</interiorcolor>
717 <exteriorcolor>' . $record->stock->interiorColour->name . '</exteriorcolor>
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>
732 <comments>' . $record->amountOffered . '</comments>
736 <vendorname>bid4cars.co.za</vendorname>
738 <name part="full">unknown</name>
739 <email>dm705161@highergear.net</email>
744 <name>' . $record->stock->company->name . '</name>
751 $mailer = new \Utility\Comms\Email();
753 'From' => \Utility\Registry::getConfigParam('sourceEmailAddress'),
754 'To' => 'dm705161@highergear.net',
755 'Subject' => 'New Public Valuation XML',
756 'Body' => $xmlTemplate
759 $mailer = new \Utility\Comms\Email();
761 'From' => \Utility\Registry::getConfigParam('sourceEmailAddress'),
762 'To' => 'b4c@nirph.com',
763 'Subject' => 'New Public Valuation XML',
764 'Body' => $xmlTemplate
768 #-> Log notification entry.
769 $em = \Utility\Registry::getEntityManager();
771 $log = new \Utility\Entity\NotificationLog();
773 'emailTo' => 'dm705161@highergear.net',
774 'emailSubject' => 'New Public Valuation XML',
775 'emailBody' => $xmlTemplate,
781 $log->fromArray($logData);
786 $log = new \Utility\Entity\NotificationLog();
788 'emailTo' => 'b4c@nirph.com',
789 'emailSubject' => 'New Public Valuation XML',
790 'emailBody' => $xmlTemplate,
796 $log->fromArray($logData);
802 if (0.0 < $record->requiredPrice && is_null($record->tradeRetailRequested))
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
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'])
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);
824 $salesProfileId = $contract->data->Valuation['salesProfile'];
825 $amountOffered = $contract->data->Valuation['amountOffered'];
826 $salesComments = isset($contract->data->Valuation['salesComments'])
827 ? $contract->data->Valuation['salesComments']
830 $record->managerProfile = $this->em->getReference(
831 '\User\Entity\Profile', \Utility\Registry::getAuthParam('id')
833 if ('Price Guide' == $record->jobState)
835 $record->previousState = 'Complete Valuation';
840 * Get data ready for notifcation
842 $tmpRecord = null == $jobRecord ? $record->toArray() : $jobRecord->toArray();
843 $record = null == $jobRecord ? $record : $jobRecord;
846 * Get sales person data
848 $em = \Utility\Registry::getEntityManager();
849 $salesPerson = $em->getRepository('\User\Entity\Profile')->find($salesProfileId);
851 $toProfileId = $salesProfileId;
852 $toCompanyId = $salesPerson->company->id;
853 $email = $salesPerson->email;
854 $mobile = $salesPerson->mobile;
857 $templateName = 'valuation-completed';
862 $type = $record->stock->type;
870 $make = $type->model->make->name;
871 $model = $type->model->name;
877 $authData = \Utility\Registry::getAuthData();
878 $fromCompanyId = isset($authData['company']['id']) ? $authData['company']['id'] : null;
879 $fromProfileId = isset($authData['id']) ? $authData['id'] : null;
882 * Set template parameters
885 $params['firstName'] = (string)$salesPerson->firstName;
886 $params['familyName'] = (string)$salesPerson->familyName;
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;
903 $pdf = new \Valuation\Pdf\Pdf002();
905 'jobRecord' => $record
907 $writer = new \Utility\Export\PdfTemplate($pdf);
908 $attachments = array($record->valuationNumber . '.pdf' => $writer->output(''));
911 $oNotify = new \Utility\Comms\Notification();
912 $oNotify->sendFromTemplate(
913 $fromCompanyId, $fromProfileId,
914 $toCompanyId, $toProfileId,
922 if (!is_null($record->xmlRpcClient)
923 && $record->xmlRpcClient->triggerSentToSales
926 exec("php /var/www/B4C2/public/index.php xmlrpc sentToSales "
928 . " >>/log/php.log &");
933 * ExecuteAfter: CreateNew.
934 * Add item to queue for mobile.
936 * @param object|null $jobRecord
937 * @param object|null $record
938 * @param \Workspace\Utility\ServiceInputParams $contract
941 public function sendToMobileQueue($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
944 if (isset($contract->data->Valuation['valuators'])
945 && !empty($contract->data->Valuation['valuators'])
951 : $record->id, array('queueStatus' => 1)
958 * ExecuteAfter: CreateNew, Update.
959 * Send sms notifications to selected valuators for new item to valuate.
961 * @param object|null $jobRecord
962 * @param object|null $record
963 * @param \Workspace\Utility\ServiceInputParams $contract
966 public function sendToValuators($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
968 $record = !is_null($record)
971 $record->queueStatus = 1;
973 if (0.0 < $record->requiredPrice && is_null($record->tradeRetailRequested))
975 $record->tradeRetailRequested = true;
976 $this->em->flush($record);
979 $data = \Utility\Comms\TransUnion::searchByMmCode(
980 $record->stock->type->mmCode,
981 $record->stock->vehicleYear->name
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'])
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);
998 if (isset($contract->data->Valuation['valuators'])
999 && !empty($contract->data->Valuation['valuators'])
1002 $record = !is_null($record)
1005 $stock = null == $jobRecord ? $record->stock : $jobRecord->stock;
1006 $record = null == $jobRecord ? $record->toArray() : $jobRecord->toArray();
1009 if (\Utility\Registry::get('IsDeviceApiCall', false))
1011 $fromCompanyId = $stock->company->id;
1012 $fromProfileId = $stock->createdBy->id;
1013 $params['firstName'] = $stock->createdBy->firstName;
1014 $params['familyName'] = $stock->createdBy->familyName;
1018 $authData = \Utility\Registry::getAuthData();
1020 $fromCompanyId = isset($authData['company']['id']) ? $authData['company']['id'] : null;
1021 $fromProfileId = isset($authData['id']) ? $authData['id'] : null;
1023 $params['firstName'] = $authData['firstName'];
1024 $params['familyName'] = $authData['familyName'];
1026 $params['customer_name'] = $record['firstName'];
1027 $params['customer_family_name'] = $record['familyName'];
1028 $params['vehicle_reg'] = is_null($stock->registrationNumber)
1030 : $stock->registrationNumber;
1032 for ($i = 0; $i < count($contract->data->Valuation['valuators']); $i++)
1034 $valuator = $this->em->getRepository('\User\Entity\Profile')
1035 ->find($contract->data->Valuation['valuators'][$i]);
1036 $valuator = $valuator->toArray();
1038 $toCompanyId = $fromCompanyId;
1039 $toProfileId = $valuator['id'];
1041 $mobile = $valuator['mobile'];
1043 $templateName = 'valuation-mobile-new';
1045 $oNotify = new \Utility\Comms\Notification();
1046 $oNotify->sendFromTemplate(
1047 $fromCompanyId, $fromProfileId,
1048 $toCompanyId, $toProfileId,
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
1069 public function checkCreatedBy($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1073 $record = !is_null($record)
1078 // Route to the Main Member Public Centre (profile) chosen by Region
1079 if ($record->isPublic && !\Utility\Registry::isAuthenticated() && isset($contract->data->Stock['publicCentre']))
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')
1086 'company' => $publicCentre,
1087 'mainMemberPublicCentre' => 1
1089 if (!is_null($profile))
1091 $record->stock->createdBy = $profile;
1092 $record->createdBy = $profile;
1095 $record->sighted = false;
1096 $record->licenseDiscExpired = false;
1097 $this->em->flush($record);
1100 if ($record->isPublic && \Utility\Registry::isAuthenticated())
1102 $record->createdBy = $this->em->getReference('\User\Entity\Profile', \Utility\Registry::getAuthParam('id'));
1103 $this->em->flush($record);
1105 if (isset($contract->data->Valuation['requiredPrice'])
1106 && is_numeric($contract->data->Valuation['requiredPrice'])
1107 && 0.0 < $contract->data->Valuation['requiredPrice']
1110 if (is_null($record->tradeRetailRequested)
1111 && \Utility\Registry::isAuthenticated()
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
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'])
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);
1135 if (!\Utility\Registry::isAuthenticated())
1137 $stock = null == $jobRecord ? $record->stock : $jobRecord->stock;
1138 $record = null == $jobRecord ? $record->toArray() : $jobRecord->toArray();
1141 $fromCompanyId = null;
1142 $fromProfileId = null;
1145 //\Utility\Debug::errorLog('$stock->vehicleYear', $stock->vehicleYear->name);
1148 $params['first_name'] = $record['firstName'];
1149 $params['family_name'] = $record['familyName'];
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)
1157 : $stock->registrationNumber;
1159 $oNotify = new \Utility\Comms\Notification();
1160 $oNotify->sendFromTemplate(
1163 $record['email'], null,
1164 'Notification of successful submission of vehicle',
1165 'public-submission',
1168 // Removed info@ to 'mohau@bid4cars.co.za', and 'dineo@bid4cars.co.za'
1169 $oNotify->sendFromTemplate(
1172 'mohau@bid4cars.co.za', null,
1173 'Notification of successful submission of vehicle',
1174 'public-submission',
1178 $oNotify->sendFromTemplate(
1181 'dineo@bid4cars.co.za', null,
1182 'Notification of successful submission of vehicle',
1183 'public-submission',
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
1200 public function setValuatorFromAuth($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1203 ? $record->valuatedBy = $this->em->getReference(
1204 '\User\Entity\Profile', \Utility\Registry::getAuthParam('id')
1206 : $jobRecord->valuatedBy = $this->em->getReference(
1207 '\User\Entity\Profile', \Utility\Registry::getAuthParam('id')
1213 * ExecuteAfter: CreateComplete, RouteMoveToComplete.
1214 * @param array $meta
1215 * @param object|null $jobRecord
1216 * @param object|null $record
1217 * @param \Workspace\Utility\ServiceInputParams $contract
1220 public function setPreviousStateToComplete($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1222 $jobRecord->previousState = 'Complete Valuation';
1223 $this->em->flush($jobRecord);
1225 $record = null == $jobRecord
1226 ? $record->toArray()
1227 : $jobRecord->toArray();
1229 $valuationId = $record['id'];
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 '
1238 ->setParameter('ValuationID', $valuationId)
1241 $StockID = $result[0]['stock']['id'];
1246 * ConditionalContract: Update.
1247 * @param array $meta
1248 * @param object|null $jobRecord
1249 * @param object|null $record
1250 * @param \Workspace\Contract\AbstractBase $contract
1253 public function noEditOnPgItemWithOffers($meta, $jobRecord, $record, \Workspace\Contract\AbstractBase $contract)
1255 if ('Price Guide' == $jobRecord->jobState
1256 && 0 < $jobRecord->stock->numberOfOffers
1259 throw new \Exception('Valuation in status Price Guide with offers may not be edited.');
1263 public function generateHistoryList($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1265 $record = null == $jobRecord
1266 ? $record->toArray()
1267 : $jobRecord->toArray();
1269 $valuationId = $record['id'];
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 '
1278 ->setParameter('ValuationID', $valuationId)
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 = '
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 '
1297 ->setParameter('StockID', $StockID)
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');
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 '
1321 ->setParameter('stockTypeID', $stockTypeID)
1322 ->setParameter('vehicleYearID', $vehicleYearID)
1323 ->setParameter('dateFrom', $dateFrom)
1324 ->setParameter('dateTo', $today)
1329 $existing = array();
1330 foreach ($result as $pricingHistory)
1332 $StockDamageTotal = $pricingHistory['damageTotal'];
1333 $StockTradePrice = $pricingHistory['tradePrice'];
1334 $StockListPrice = $pricingHistory['listPrice'];
1335 $StockKMS = $pricingHistory['km'];
1336 if ($StockKMS == '' || is_null($StockKMS))
1341 $PriceguideHighestOffer = $pricingHistory['highestOffer'];
1343 $highestBid = $pricingHistory['highestBid'];
1345 // Priceguide && Auction
1346 if ($PriceguideHighestOffer != 0 && $highestBid != 0)
1348 $priceGuideOffers = $pricingHistory['priceGuide']['offers'];
1349 if (is_array($priceGuideOffers))
1352 foreach ($priceGuideOffers as $priceGuideOffer)
1354 if ($priceGuideOffer['amount'] > $highestAmnt)
1356 $highestAmnt = $priceGuideOffer['amount'];
1357 $priceGuideOffersCreatedDate = $priceGuideOffer['created'];
1362 'date' => $priceGuideOffersCreatedDate,
1363 'trade' => $StockTradePrice,
1364 'listPrice' => $StockListPrice,
1365 'totalRecon' => $StockDamageTotal,
1367 'pricegOffer' => $PriceguideHighestOffer,
1368 'auctionWinningBid' => $highestBid,
1369 'stockId' => $StockID
1371 $hash = md5(serialize($data));
1372 if (!isset($existing[$hash]))
1374 $existing[$hash] = true;
1375 $entry = new \Stock\Entity\PricingHistory();
1376 $entry->fromArray($data);
1377 $this->em->persist($entry);
1378 $this->em->flush($entry);
1384 if ($PriceguideHighestOffer != 0 && $highestBid == 0)
1386 $priceGuideOffers = $pricingHistory['priceGuide']['offers'];
1387 if (is_array($priceGuideOffers))
1390 foreach ($priceGuideOffers as $priceGuideOffer)
1392 if ($priceGuideOffer['amount'] > $highestAmnt)
1394 $highestAmnt = $priceGuideOffer['amount'];
1395 $priceGuideOffersCreatedDate = $priceGuideOffer['created'];
1399 'date' => $priceGuideOffersCreatedDate, // changes all the time
1400 'trade' => $StockTradePrice,
1401 'listPrice' => $StockListPrice,
1402 'totalRecon' => $StockDamageTotal,
1404 'pricegOffer' => $PriceguideHighestOffer,
1405 'auctionWinningBid' => 0.0,
1406 'stockId' => $StockID
1409 $hash = md5(serialize($data));
1410 if (!isset($existing[$hash]))
1412 $existing[$hash] = true;
1413 $entry = new \Stock\Entity\PricingHistory();
1414 $entry->fromArray($data);
1415 $this->em->persist($entry);
1416 $this->em->flush($entry);
1423 if ($PriceguideHighestOffer == 0 && $highestBid != 0)
1425 $date = $pricingHistory['auction']['created'];
1427 'date' => $date, // changes all the time
1428 'trade' => $StockTradePrice,
1429 'listPrice' => $StockListPrice,
1430 'totalRecon' => $StockDamageTotal,
1432 'pricegOffer' => 0.0,
1433 'auctionWinningBid' => $highestBid,
1434 'stockId' => $StockID
1436 $hash = md5(serialize($data));
1437 if (!isset($existing[$hash]))
1439 $existing[$hash] = true;
1440 $entry = new \Stock\Entity\PricingHistory();
1441 $entry->fromArray($data);
1442 $this->em->persist($entry);
1443 $this->em->flush($entry);
1459 * Contract to use current highest price guide offer.
1460 * @param object|null $jobRecord
1461 * @param array $input
1462 * @return \Workspace\Contract\UseOnce
1464 public function contractUseOffer($jobRecord, array $input = array())
1466 $options = new \Workspace\UseCase\Options();
1467 $requirement = new \Workspace\UseCase\Requirement();
1468 $requirement->addRequiredInput(array(
1469 'Valuation' => array(
1473 return new \Workspace\Contract\UseOnce($options, $requirement);
1477 * Use current highest price guide offer
1478 * @param object|null $jobRecord
1479 * @param \Workspace\Utility\ServiceInputParams $contract
1482 public function executeUseOffer($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
1484 #-> Do we have an existing offer in use?
1485 $existingOffer = $this->em->getRepository('PriceGuide\Entity\Offer')
1487 'priceGuideStock' => $jobRecord->stock->priceGuide->id,
1488 'status' => 'Offer in Use'
1490 if (is_object($existingOffer))
1492 #-> Have existing offer, change status of offer back to Updateable Offer.
1493 $existingOffer->status = 'Updateable Offer';
1494 $this->em->flush($existingOffer);
1498 $existingOffer = false;
1501 #-> Get the new highest offer.
1502 $highestOffer = $this->em->getRepository('PriceGuide\Entity\Offer')
1504 'priceGuideStock' => $jobRecord->stock->priceGuide->id,
1505 'status' => 'Updateable Offer'
1511 if ($existingOffer && $existingOffer->id == $highestOffer->id)
1513 $existingOffer = false;
1515 $highestOffer->status = 'Offer in Use';
1516 $this->em->flush($highestOffer);
1519 #-> Notify owner of offer now in use.
1520 $auth = \Utility\Registry::getAuthData();
1521 $oNotify = new \Utility\Comms\Notification();
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
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',
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',
1551 #-> Notify authed user & owner of previous offer used that it is no longer in use.
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',
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',
1575 return $contract->success('Current Highest Offer is now in use.', array());
1578 public function updateCustomVehicles($meta, $jobRecord, $contract, $data)
1580 $contract->data = $this->addCustomVehicles($meta, $contract->data);
1581 return $contract->data;
1585 * ExecuteBefore: Create
1586 * @param array $meta
1587 * @param array $data
1589 public function addCustomVehicles($meta, $data)
1592 #-> Check if we have a custom vehicle
1594 //\Utility\Debug::errorLog('Stock manualy added on before exe', $data->Stock);
1596 if ($data->Stock['category'] == '8')
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'
1604 ->getScalarResult();
1605 $newVersion = $versions[0]['createVersion'] > $versions[0]['updateVersion']
1606 ? $versions[0]['createVersion'] + 1
1607 : $versions[0]['updateVersion'] + 1;
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();
1618 // Do a check if this make exists
1619 if ('' != $makeManual && $makeManual != $data->Stock['make'])
1621 $make = $em->getRepository('\Stock\Entity\Make')
1623 'name' => $makeManual
1628 // Else add Make Manual
1629 $make = new \Stock\Entity\Make();
1631 'name' => $makeManual,
1632 'created' => $today,
1633 'createVersion' => $newVersion
1636 $make->fromArray($makeData);
1637 $em->persist($make);
1641 $makeId = $make->id;
1645 $makeId = $data->Stock['make'];
1650 if ('' != $modelManual && $modelManual != $data->Stock['model'])
1652 // Do a check if this model exists
1653 $model = $em->getRepository('\Stock\Entity\Model')
1656 'name' => $makeManual
1659 if (is_null($model))
1662 $model = new \Stock\Entity\Model();
1664 'make' => $em->getRepository('\Stock\Entity\Make')->find($makeId),
1665 'name' => $modelManual,
1666 'created' => $today,
1667 'createVersion' => $newVersion
1671 $model->fromArray($modelData);
1672 $em->persist($model);
1676 $modelId = $model->id;
1680 $modelId = $data->Stock['model'];
1684 if ('' != $typeManual && $typeManual != $data->Stock['type'])
1686 // Do a check if this type exists
1687 $type = $em->getRepository('\Stock\Entity\Type')
1689 'model' => $modelId,
1690 'category' => $category,
1691 'name' => $typeManual
1697 $type = new \Stock\Entity\Type();
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
1710 $type->fromArray($typeData);
1711 $em->persist($type);
1716 $typeId = $type->id;
1718 #-> Update data with new ids
1719 $data->Stock['type'] = $typeId;
1729 * ExecuteAfter: Create
1730 * @param array $meta
1731 * @param array $data
1733 public function sendEmailToValuator($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1735 // error_log('sendEmailToValuator');
1737 // do a check here for input
1743 // \Utility\Debug::errorLog('$record', $record->id);
1745 $profileEntry = $this->em->getRepository('\\User\\Entity\\Profile')
1747 'company' => $record->stock->company->id,
1748 'permissions' => '7',
1752 if(!is_null($profileEntry))
1754 foreach ($profileEntry as $profile)
1756 // \Utility\Debug::errorLog('$profile', $profile->id);
1758 $toCompanyId = $record->stock->company->id;
1759 $toProfileId = $profile->id;
1760 $email = $profile->email;
1762 $subject = "Public Valuation for " . $record->firstName . " " . $record->familyName;
1763 $templateName = 'public-general';
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;">
1767 <td width="100%" valign="top" style="width:100%;">
1772 <td width="100%" valign="top" style="width:100%;">
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;">
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:
1785 <td width="100%" valign="top" style="width:100%;">';
1786 $params['body'] .= $record->stock->registrationNumber;
1787 $params['body'] .= ' </td>
1790 <td width="100%" valign="top" style="width:100%;">';
1791 $params['body'] .= $record->stock->vehicleYear->name;
1792 $params['body'] .= ' </td>
1795 <td width="100%" valign="top" style="width:100%;">';
1796 $params['body'] .= $record->stock->type->model->make->name;
1797 $params['body'] .= ' </td>
1800 <td width="100%" valign="top" style="width:100%;">';
1801 $params['body'] .= $record->stock->type->model->name;
1802 $params['body'] .= ' </td>
1805 <td width="100%" valign="top" style="width:100%;">';
1806 $params['body'] .= $record->stock->type->name;
1807 $params['body'] .= ' </td>
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;">
1812 <td width="100%" valign="top" style="width:100%;">
1817 <td width="100%" valign="top" style="width:100%;">
1822 <td width="100%" valign="top" style="width:100%;">
1828 $params['smsBody'] = '';
1830 // error_log('email body');
1831 // error_log($params['body']);
1833 $oNotify = new \Utility\Comms\Notification();
1834 $oNotify->sendFromTemplate(
1854 * ExecuteAfter: Create
1855 * @param array $meta
1856 * @param array $data
1858 public function sendPublicCustomerEmail($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1860 // error_log('sendPublicCustomerEmail');
1863 ? $jobRecord->stock->valuation = $jobRecord
1864 : $record->stock->valuation = $record;
1867 // do a check here for input
1873 $record->valuatedBy = isset($authData['id']) ? $authData['id'] : null;
1874 $this->em->flush($record);
1877 // // valuation = $record, stock = $record->stock->refNum
1879 // if (!\Utility\Registry::isAuthenticated())
1881 // // set valuations flag to is-public true
1882 // $record->isPublic = true;
1883 // $this->em->flush($record);
1886 $customerPublicValuationEntry = $this->em->getRepository('\\Valuation\\Entity\\CustomerPublicValuation')
1888 'valuation' => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
1889 'stock' => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
1894 $fromCompanyId = isset($authData['company']['id']) ? $authData['company']['id'] : null;
1895 $fromProfileId = isset($authData['id']) ? $authData['id'] : null;
1897 $toCompanyId = $fromCompanyId;
1898 $toProfileId = $record->valuatedBy;
1899 $email = $record->email;
1901 $subject = "Valuation for " . $record->firstName . " " . $record->familyName;
1902 $templateName = 'public-general';
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;">
1906 <td width="100%" valign="top" style="width:100%;">
1907 Good Day ' . $record->firstName . ' ' . $record->familyName . ',
1911 <td width="100%" valign="top" style="width:100%;">
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>.
1923 <td width="100%" valign="top" style="width:100%;">
1924 We would be interested at a price of around R' . $record->amountOffered . '
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;">
1930 <td width="100%" valign="top" style="width:100%;">
1931 Please click on the below link to continue with the valuation process.
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>
1944 <td width="100%" valign="top" style="width:100%;">
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;">
1951 <td width="100%" valign="top" style="width:100%;">
1956 <td width="100%" valign="top" style="width:100%;">
1961 <td width="100%" valign="top" style="width:100%;">
1966 $params['smsBody'] = '';
1969 // error_log('email body');
1970 // error_log($params['body']);
1972 $oNotify = new \Utility\Comms\Notification();
1973 $oNotify->sendFromTemplate(
1988 * ExecuteAfter: Create
1989 * @param array $meta
1990 * @param array $data
1992 public function setAppointmentData($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
1994 // error_log('setAppointmentData');
1996 // is_null($jobRecord)
1997 // ? $jobRecord->stock->valuation = $jobRecord
1998 // : $record->stock->valuation = $record;
1999 // $this->em->flush();
2001 // do a check here for input
2006 // \Utility\Debug::errorLog('$contract', $contract->data->Valuation);
2008 // [valuatorSelected] => 561
2009 // [dateSelected] => 2015-09-24
2010 // [timeIdSelected] => 5
2014 $valuationAppointmentsEntry = $this->em->getRepository('\\Valuation\\Entity\\ValuationAppointments')
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']),
2024 if(is_null($valuationAppointmentsEntry) && empty($valuationAppointmentsEntry))
2026 $valuationAppointmentsEntry = new \Valuation\Entity\ValuationAppointments();
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'])
2036 $valuationAppointmentsEntry->fromArray($valuationAppointmentsData);
2037 $this->em->persist($valuationAppointmentsEntry);
2042 $record->valuatedBy = isset($authData['id']) ? $authData['id'] : null;
2043 $this->em->flush($record);
2046 // // valuation = $record, stock = $record->stock->refNum
2048 // if (!\Utility\Registry::isAuthenticated())
2050 // // set valuations flag to is-public true
2051 // $record->isPublic = true;
2052 // $this->em->flush($record);
2055 $customerPublicValuationEntry = $this->em->getRepository('\\Valuation\\Entity\\CustomerPublicValuation')
2057 'valuation' => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
2058 'stock' => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
2063 // \Utility\Debug::errorLog('$valuationAppointmentsEntry->appointmentDate', $valuationAppointmentsEntry->appointmentDate);
2065 $appointmentDate = new \DateTime($valuationAppointmentsEntry->appointmentDate->date);
2067 $fromCompanyId = isset($authData['company']['id']) ? $authData['company']['id'] : null;
2068 $fromProfileId = isset($authData['id']) ? $authData['id'] : null;
2070 $toCompanyId = $fromCompanyId;
2071 $toProfileId = $record->valuatedBy;
2072 $email = $record->email;
2074 $subject = "Notification of successful submission of vehicle";
2075 $templateName = 'public-general';
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);
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;">
2087 <td width="100%" valign="top" style="width:100%;">
2088 Good Day ' . $record->firstName . ' ' . $record->familyName . ',
2092 <td width="100%" valign="top" style="width:100%;">
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.
2102 <td width="100%" valign="top" style="width:100%;">
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;">
2109 <td width="10" valign="top" style="width:10px;"> </td>
2110 <td width="50" valign="top" style="width:50px; font-family: Arial, Sans-serif; font-size:12px;">
2113 <td width="180" valign="top" style="width:180px;">
2114 ' . $record->stock->vehicleYear->name . '
2116 <td width="20" valign="top" style="width:20px;"> </td>
2119 <td width="10" valign="top" style="width:10px;"> </td>
2120 <td width="50" valign="top" style="width:50px; font-family: Arial, Sans-serif; font-size:12px;">
2123 <td width="180" valign="top" style="width:180px;">
2124 ' . $record->stock->type->model->make->name . '
2126 <td width="20" valign="top" style="width:20px;"> </td>
2129 <td width="10" valign="top" style="width:10px;"> </td>
2130 <td width="50" valign="top" style="width:50px; font-family: Arial, Sans-serif; font-size:12px;">
2133 <td width="180" valign="top" style="width:180px;">
2134 ' . $record->stock->type->model->name . '
2136 <td width="20" valign="top" style="width:20px;"> </td>
2139 <td width="10" valign="top" style="width:10px;"> </td>
2140 <td width="50" valign="top" style="width:50px; font-family: Arial, Sans-serif; font-size:12px;">
2143 <td width="180" valign="top" style="width:180px;">
2144 ' . $record->stock->type->name . '
2146 <td width="20" valign="top" style="width:20px;"> </td>
2149 <td width="10" valign="top" style="width:10px;"> </td>
2150 <td width="50" valign="top" style="width:50px; font-family: Arial, Sans-serif; font-size:12px;">
2153 <td width="180" valign="top" style="width:180px;">
2154 ' . $record->stock->registrationNumber . '
2156 <td width="20" valign="top" style="width:20px;"> </td>
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;">
2161 <td width="100%" valign="top" style="width:100%;">
2166 <td width="100%" valign="top" style="width:100%;">
2167 Please note that the price offered on your vehicle is subject to final viewing.
2171 <td width="100%" valign="top" style="width:100%;">
2172 Your booking for valuation will take place at:
2176 <td width="100%" valign="top" style="width:100%;">
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;">
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>
2188 <td width="100%" valign="top" style="width:100%;">
2193 <td width="100%" valign="top" style="width:100%;font-weight:bold;font-size:14px;">
2198 <td width="100%" valign="top" style="width:100%;">
2199 ' . $appointmentDate->format('Y-m-d') . '
2203 <td width="100%" valign="top" style="width:100%;">
2204 ' . $valuationAppointmentsEntry->timeSlot->timeSlotDisplayName . '
2208 <td width="100%" valign="top" style="width:100%;">
2213 <td width="100%" valign="top" style="width:100%;font-weight:bold;font-size:14px;">
2218 <td width="100%" valign="top" style="width:100%;">
2219 ' . $record->customerAddressStreet . '
2223 <td width="100%" valign="top" style="width:100%;">
2224 ' . $record->customerAddressStreetName . '
2228 <td width="100%" valign="top" style="width:100%;">
2229 ' . $record->customerAddressSuburb . '
2233 <td width="100%" valign="top" style="width:100%;">
2234 ' . $record->customerAddressCity . '
2238 <td width="100%" valign="top" style="width:100%;">
2239 ' . $record->customerAddressPostalCode . '
2243 <td width="100%" valign="top" style="width:100%;">
2248 <td width="100%" valign="top" style="width:100%;font-weight:bold;font-size:14px;">
2253 <td width="100%" valign="top" style="width:100%;">
2254 ' . $record->email . '
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;">
2260 <td width="100%" valign="top" style="width:100%;">
2265 <td width="100%" valign="top" style="width:100%;">
2270 <td width="100%" valign="top" style="width:100%;">
2275 $params['smsBody'] = '';
2278 // error_log('email body');
2279 // error_log($params['body']);
2281 $oNotify = new \Utility\Comms\Notification();
2282 $oNotify->sendFromTemplate(
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)
2297 // $oNotify = new \Utility\Comms\Notification();
2298 // $oNotify->sendFromTemplate(
2303 // $record->stock->company->contact->email,
2313 // if(!empty($record->valuatedBy) && null != $record->valuatedBy)
2315 // $oNotify = new \Utility\Comms\Notification();
2316 // $oNotify->sendFromTemplate(
2321 // $record->valuatedBy->email,
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
2342 public function pushCreateAction($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
2344 //-- Pass to backend function so we don't hold up the user response.
2345 $userId = \Utility\Registry::isAuthenticated()
2346 ? \Utility\Registry::getAuthParam('id')
2348 exec("php /var/www/B4C2/public/index.php valuation change 1 " . $record->id . " $userId > /dev/null &");
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
2360 public function pushUpdateAction($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
2362 //-- Pass to backend function so we don't hold up the user response.
2363 $userId = \Utility\Registry::isAuthenticated()
2364 ? \Utility\Registry::getAuthParam('id')
2366 exec("php /var/www/B4C2/public/index.php valuation change 2 " . $record->id . " $userId > /dev/null &");
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
2378 public function pushDeleteAction($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
2380 //-- Pass to backend function so we don't hold up the user response.
2381 $userId = \Utility\Registry::isAuthenticated()
2382 ? \Utility\Registry::getAuthParam('id')
2384 exec("php /var/www/B4C2/public/index.php valuation change 3 " . $record->id . " $userId > /dev/null &");
2388 * Push change notifications for stock item change.
2389 * @param $changeCode
2393 public function pushChange($changeCode, $id, $skipId)
2396 $valuation = $this->em->find('Valuation\\Entity\\Valuation', $id);
2398 $minDate = new \DateTime('last month');
2399 if ($minDate->getTimestamp() > $valuation->stock->created->getTimestamp()
2400 || 8 == $valuation->stock->type->category->id
2403 //-- Nothing to do, old record.
2407 //-- Send it to relevant people.
2408 $registrations = $this->em->getRepository('Company\\Entity\\DeviceRegistration')
2411 'company' => $valuation->stock->company->id
2415 foreach ($registrations as $registration)
2417 if (/*$registration->profile->id != $skipId
2418 && */0 < strlen($registration->device->registrationId)
2421 $ids[] = $registration->device->registrationId;
2424 \Utility\Comms\Gcm::send(
2427 'changeCode' => (int) $changeCode,
2428 'changeId' => (int) $valuation->stock->uvi
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
2439 public function contractDealNotDoneSelection($jobRecord, array $input = array())
2441 $options = new \Workspace\UseCase\Options();
2442 $requirement = new \Workspace\UseCase\Requirement();
2444 return new \Workspace\Contract\Recurring($options, $requirement);
2448 * List vehicle types according to Category and Year.
2449 * @param object|null $jobRecord
2450 * @param \Workspace\Utility\ServiceInputParams $contract
2453 public function executeDealNotDoneSelection($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
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)
2462 // \Utility\Debug::errorLog("dataGet", $dataGet);
2466 foreach($dataGet as $dataProcess)
2468 array_push($data,array(
2469 'value' => $dataProcess['value'],
2470 'label' => $dataProcess['label']
2474 return $contract->success('Data Collected.', $data);