initial commit
[namibia] / module / Valuation / src / Valuation / Service / XmlRpc.php
1 <?php
2 namespace Valuation\Service;
3
4 class XmlRpc
5 {
6
7
8         /**
9          * @var \Doctrine\ORM\EntityManager
10          */
11         protected $em           = null;
12         /**
13          * @var \Valuation\Entity\XmlRpc
14          */
15         protected $client       = null;
16         /**
17          * @var \Valuation\Entity\Valuation
18          */
19         protected $valuation = null;
20
21
22
23
24         /**
25          * Utility to log api requests.
26          * @param string $methodName
27          * @param array $packet
28          * @param string $status
29          */
30         protected function logRequest($methodName, array $packet, $status = 'OK')
31         {
32                 $log = new \Valuation\Entity\XmlRpcRequestLog();
33                 $log->fromArray(array(
34                                 'xmlRpcClient'  => $this->client,
35                                 'clientApiId'   => isset($packet['apiId'])
36                                                                         ? $packet['apiId']
37                                                                         : null,
38                                 'ipAddress'     => $_SERVER['REMOTE_ADDR'],
39                                 'valuation'     => $this->valuation,
40                                 'methodName'    => $methodName,
41                                 'packet'                => serialize($packet),
42                                 'status'                => $status
43                 ));
44                 $this->em->persist($log);
45                 $this->em->flush($log);
46         }
47
48
49
50         /**
51          * @param string $apiId
52          * @param string $password
53          * @return string
54          */
55         public function Authenticate($ApiId, $Password)
56         {
57                 $this->em = \Utility\Registry::getEntityManager();
58                 $this->client = $this->em->getRepository('Valuation\\Entity\\XmlRpc')
59                         ->findOneBy(array(
60                                         'clientApiId' => $ApiId
61                         ));
62                 if (is_null($this->client)
63                         || md5($Password) != $this->client->passwordHash
64                         || $this->client->archived)
65                 {
66                         $this->logRequest(__METHOD__, array('apiId' => $ApiId), 'System Authentication Failure');
67                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('System Authentication Failure.', 001);
68                 }
69                 $this->client->ipAddress = $_SERVER['REMOTE_ADDR'];
70                 $this->em->flush($this->client);
71                 $this->logRequest(__METHOD__, array('apiId' => $ApiId));
72                 return $this->client->authToken;
73         }
74
75         protected function checkAuth($AuthToken)
76         {
77                 $this->em = \Utility\Registry::getEntityManager();
78                 $this->client = $this->em->getRepository('Valuation\\Entity\\XmlRpc')
79                         ->findOneBy(array(
80                                         'authToken' => $AuthToken,
81                                         'ipAddress' => $_SERVER['REMOTE_ADDR']
82                         ));
83                 if (is_null($this->client) || $this->client->archived)
84                 {
85                         $this->logRequest(__METHOD__, array('authToken' => $AuthToken), 'System Authentication Failure.');
86                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('System Authentication Failure.', 001);
87                 }
88         }
89
90         protected function tempAuth($email)
91         {
92                 \Utility\Registry::clearAuthData();
93                 \Utility\Registry::clearSessionData();
94                 $user = $this->em->getRepository('\User\Entity\Profile')
95                         ->findOneBy(array('email' => $email));
96                 if (is_null($user) || $user->archived)
97                 {
98                         $this->logRequest(__METHOD__, array('email' => $email), 'User Authentication Failure.');
99                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('User Authentication Failure.', 001);
100                 }
101                 $authData = $user->toArray(array(
102                                 'company', 'tradeCenter', 'group', 'groupDivision', 'permissions',
103                                 'city', 'region', 'contact', 'manager'
104                 ));
105                 if ($authData['company']['jobState'] != 'Active')
106                 {
107                         $this->logRequest(__METHOD__, array('email' => $email), 'Dealership Authentication Failure due to suspension.');
108                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Dealership Authentication Failure due to suspension.', 002);
109                 }
110                 if ($authData['jobState'] != 'Active')
111                 {
112                         $this->logRequest(__METHOD__, array('email' => $email), 'User Authentication Failure due to suspension.');
113                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('User Authentication Failure due to suspension.', 003);
114                 }
115                 \Utility\Registry::setAuthData($authData);
116         }
117
118         protected function getDataList($AuthToken, $entity, $fields = false, $extraFields = '', array $simplify = array())
119         {
120                 list($module, $mid, $short) = explode('\\', $entity);
121                 if (false === $fields)
122                 {
123                         $selection = $short;
124                 }
125                 else
126                 {
127                         $selection = 'partial ' . $short . '.{' . $fields . '}' . $extraFields;
128                 }
129                 $data = $this->em->createQuery(
130                                 'SELECT ' . $selection  . ' FROM ' . $entity . ' ' . $short
131                         )
132                         ->getArrayResult();
133                 $response = array();
134                 if (!empty($simplify))
135                 {
136                         foreach ($data as $i => $row)
137                         {
138                                 $response[$i] = array();
139                                 foreach ($row[0] as $field => $value)
140                                 {
141                                         $response[$i][ucfirst($field)] = $value;
142                                 }
143                                 foreach ($simplify as $field)
144                                 {
145                                         $response[$i][ucfirst($field)] = $row[$field];
146                                 }
147                         }
148                 }
149                 else
150                 {
151                         foreach ($data as $i => $row)
152                         {
153                                 $response[$i] = array();
154                                 foreach ($data[$i] as $field => $value)
155                                 {
156                                         $response[$i][ucfirst($field)] = $value;
157                                 }
158                         }
159                 }
160                 return array('List' => $response);
161         }
162
163         /**
164          * @param string $AuthToken
165          * @return struct
166          */
167         public function GetVehicleYearData($AuthToken)
168         {
169                 $this->checkAuth($AuthToken);
170                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
171                 return $this->getDataList($AuthToken, 'Stock\\Entity\\Year');
172         }
173
174         /**
175          * @param string $AuthToken
176          * @return struct
177          */
178         public function GetVehicleCategoryData($AuthToken)
179         {
180                 $this->checkAuth($AuthToken);
181                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
182                 return $this->getDataList($AuthToken, 'Stock\\Entity\\Category');
183         }
184
185         /**
186          * @param string $AuthToken
187          * @return struct
188          */
189         public function GetVehicleMakeData($AuthToken)
190         {
191                 $this->checkAuth($AuthToken);
192                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
193                 return $this->getDataList(
194                                 $AuthToken,
195                                 'Stock\\Entity\\Make',
196                                 'id,name,created,updated,archived'
197                         );
198         }
199
200         /**
201          * @param string $AuthToken
202          * @return struct
203          */
204         public function GetVehicleModelData($AuthToken)
205         {
206                 $this->checkAuth($AuthToken);
207                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
208                 return $this->getDataList(
209                                 $AuthToken,
210                                 'Stock\\Entity\\Model',
211                                 'id,name,created,updated,archived',
212                                 ', IDENTITY(Model.make) as makeId',
213                                 array('makeId')
214                         );
215         }
216
217         /**
218          * @param string $AuthToken
219          * @return struct
220          */
221         public function GetVehicleTypeData($AuthToken)
222         {
223                 $this->checkAuth($AuthToken);
224                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
225                 return $this->getDataList(
226                                 $AuthToken,
227                                 'Stock\\Entity\\Type',
228                                 'id,name,mmCode,introMonth,discMonth,created,updated,archived',
229                                 ', IDENTITY(Type.model) as modelId , IDENTITY(Type.introYear) as introYearId , IDENTITY(Type.discYear) as discYearId',
230                                 array('modelId', 'introYearId', 'discYearId')
231                         );
232         }
233
234         /**
235          * @param string $AuthToken
236          * @return struct
237          */
238         public function GetVehicleFuelData($AuthToken)
239         {
240                 $this->checkAuth($AuthToken);
241                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
242                 return $this->getDataList($AuthToken, 'Stock\\Entity\\FuelType');
243         }
244
245         /**
246          * @param string $AuthToken
247          * @return struct
248          */
249         public function GetVehicleTransmissionData($AuthToken)
250         {
251                 $this->checkAuth($AuthToken);
252                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
253                 return $this->getDataList($AuthToken, 'Stock\\Entity\\TransmissionType');
254         }
255
256         /**
257          * @param string $AuthToken
258          * @return struct
259          */
260         public function GetVehicleConditionData($AuthToken)
261         {
262                 $this->checkAuth($AuthToken);
263                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
264                 return $this->getDataList($AuthToken, 'Stock\\Entity\\Condition');
265         }
266
267         /**
268          * @param string $AuthToken
269          * @return struct
270          */
271         public function GetVehicleExteriorColourData($AuthToken)
272         {
273                 $this->checkAuth($AuthToken);
274                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
275                 return $this->getDataList($AuthToken, 'Stock\\Entity\\ExteriorColour');
276         }
277
278         /**
279          * @param string $AuthToken
280          * @return struct
281          */
282         public function GetVehicleInteriorColourData($AuthToken)
283         {
284                 $this->checkAuth($AuthToken);
285                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
286                 return $this->getDataList($AuthToken, 'Stock\\Entity\\InteriorColour');
287         }
288
289         /**
290          * @param string $AuthToken
291          * @return struct
292          */
293         public function GetVehicleUpholsteryData($AuthToken)
294         {
295                 $this->checkAuth($AuthToken);
296                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
297                 return $this->getDataList($AuthToken, 'Stock\\Entity\\Upholstery');
298         }
299
300         /**
301          * @param string $AuthToken
302          * @return struct
303          */
304         public function GetVehiclePapersData($AuthToken)
305         {
306                 $this->checkAuth($AuthToken);
307                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
308                 return $this->getDataList($AuthToken, 'Stock\\Entity\\Paper');
309         }
310
311         /**
312          * @param string $AuthToken
313          * @return struct
314          */
315         public function GetVehicleNatisData($AuthToken)
316         {
317                 $this->checkAuth($AuthToken);
318                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
319                 return $this->getDataList($AuthToken, 'Stock\\Entity\\Natis');
320         }
321
322         /**
323          * @param string $AuthToken
324          * @return struct
325          */
326         public function GetVehicleAccessoryData($AuthToken)
327         {
328                 $this->checkAuth($AuthToken);
329                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
330                 return $this->getDataList($AuthToken, 'Stock\\Entity\\Accessory');
331         }
332
333         /**
334          * @param string $AuthToken
335          * @return struct
336          */
337         public function GetVehicleComponentData($AuthToken)
338         {
339                 $this->checkAuth($AuthToken);
340                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
341                 return $this->getDataList($AuthToken, 'Stock\\Entity\\Damage');
342         }
343
344         /*
345          * @param string $AuthToken
346          * @return struct
347          */
348         /*public function GetStockList($AuthToken)
349         {
350                 $this->checkAuth($AuthToken);
351                 if ('GEMS' != $this->client->clientName)
352                 {
353                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Access Denied.', 099);
354                 }
355                 $this->logRequest(__METHOD__, array('authToken' => $AuthToken));
356                 return $this->getDataList($AuthToken, 'Stock\\Entity\\Damage');
357         }*/
358
359         /**
360          * @param string $AuthToken
361          * @param string $email
362          * @param struct $valuation
363          * @return struct
364          */
365         public function CreateValuation($AuthToken, $Email, array $Valuation)
366         {
367                 #-> Authentication.
368                 $this->checkAuth($AuthToken);
369                 $this->tempAuth($Email);
370
371                 #-> Mandatory field checks.
372                 $packet = array(
373                                 'authToken' => $AuthToken,
374                                 'email'         => $Email,
375                                 'valuation' => $Valuation
376                 );
377                 $requiredString = array(
378                                 'CustomerName',
379                                 'CustomerSurname',
380                                 'CustomerMobile',
381                                 'RegistrationNumber'
382                 );
383                 $requiredNumeric = array(
384                                 'Km'
385                 );
386                 $requiredReference = array(
387                                 'VehicleYearId'                         => 'Stock\\Entity\\Year',
388                                 'VehicleTypeId'                         => 'Stock\\Entity\\Type',
389                                 'VehicleFuelTypeId'             => 'Stock\\Entity\\FuelType',
390                                 'VehicleTransmissionTypeId' => 'Stock\\Entity\\TransmissionType'
391                 );
392                 foreach ($requiredString as $field)
393                 {
394                         if (!isset($Valuation[$field]) || 0 == strlen($Valuation[$field]))
395                         {
396                                 $this->logRequest(__METHOD__, $packet, 'Required field not provided or empty: ' . $field);
397                                 throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Required field not provided or empty: ' . $field, 010);
398                         }
399                 }
400                 foreach ($requiredNumeric as $field)
401                 {
402                         if (!isset($Valuation[$field]) || 0 == strlen($Valuation[$field]) || !is_numeric($Valuation[$field]))
403                         {
404                                 $this->logRequest(__METHOD__, $packet, 'Required field not provided or not numeric: ' . $field);
405                                 throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Required field not provided or not numeric: ' . $field, 011);
406                         }
407                 }
408                 foreach ($requiredReference as $field => $entityName)
409                 {
410                         if (!isset($Valuation[$field]) || 0 == strlen($Valuation[$field]) || !is_numeric($Valuation[$field]))
411                         {
412                                 $this->logRequest(__METHOD__, $packet, 'Required field not provided or not numeric: ' . $field);
413                                 throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Required field not provided or not numeric: ' . $field, 013);
414                         }
415                         $record = $this->em->find($entityName, $Valuation[$field]);
416                         if (is_null($record))
417                         {
418                                 $this->logRequest(__METHOD__, $packet, 'Required field not a valid reference: ' . $field);
419                                 throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Required field not a valid reference: ' . $field, 012);
420                         }
421                         $Valuation[$field] = $record;
422                 }
423
424                 #-> Verify remaining fields.
425                 if (isset($Valuation['id']))
426                 {
427                         unset($Valuation['id']);
428                 }
429                 $remainingNumeric = array();
430                 foreach ($remainingNumeric as $field)
431                 {
432                         if (isset($Valuation[$field]) && null != $Valuation[$field] && !is_numeric($Valuation[$field]))
433                         {
434                                 $this->logRequest(__METHOD__, $packet, 'Optional field not null or numeric: ' . $field);
435                                 throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Optional field not null or numeric: ' . $field, 014);
436                         }
437                 }
438                 $remainingReference = array(
439                                 'VehicleConditionId'            => 'Stock\\Entity\\Condition',
440                                 'VehicleExteriorColourId'       => 'Stock\\Entity\\ExteriorColour',
441                                 'VehicleInteriorColourId'       => 'Stock\\Entity\\InteriorColour',
442                                 'VehicleUpholsteryId'           => 'Stock\\Entity\\Upholstery',
443                                 'VehiclePapersId'                       => 'Stock\\Entity\\Paper',
444                                 'VehicleNatisId'                        => 'Stock\\Entity\\Natis'
445                 );
446                 foreach ($remainingReference as $field => $entityName)
447                 {
448                         if (!isset($Valuation[$field]) || 0 == strlen($Valuation[$field]) || !is_numeric($Valuation[$field]))
449                         {
450                                 if (isset($Valuation[$field]))
451                                 {
452                                         unset($Valuation[$field]);
453                                 }
454                                 continue;
455                         }
456                         $record = $this->em->find($entityName, $Valuation[$field]);
457                         if (is_null($record))
458                         {
459                                 $this->logRequest(__METHOD__, $packet, 'Optional field not null or a valid reference: ' . $field);
460                                 throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Optional field not null or a valid reference: ' . $field, 015);
461                         }
462                         $Valuation[$field] = $record;
463                 }
464
465                 #-> Verify valid urls on images.
466                 $urlValidator = new \Zend\Validator\Uri();
467                 for ($i = 1; $i <= 8; $i++)
468                 {
469                         $field = 'VehiclePhoto' . $i . 'URL';
470                         if (isset($Valuation[$field]) && !is_null($Valuation[$field]))
471                         {
472                                 if (!$urlValidator->isValid($Valuation[$field]))
473                                 {
474                                         $this->logRequest(__METHOD__, $packet, 'Optional field not null or valid url: ' . $field);
475                                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Optional field not null or a valid url: ' . $field, 016);
476                                 }
477                         }
478                 }
479
480                 #-> Verify damages collection.
481                 if (isset($Valuation['Damages']))
482                 {
483                         foreach ($Valuation['Damages'] as $i => $damageEntry)
484                         {
485                                 if (!isset($damageEntry['VehicleComponentId']) || 0 == strlen($damageEntry['VehicleComponentId']) || !is_numeric($damageEntry['VehicleComponentId']))
486                                 {
487                                         $this->logRequest(__METHOD__, $packet, 'Damages section required field not provided or not numeric: VehicleComponentId');
488                                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Damages section required field not provided or not numeric: VehicleComponentId', 017);
489                                 }
490                                 $record = $this->em->find('Stock\\Entity\\Damage', $damageEntry['VehicleComponentId']);
491                                 if (is_null($record))
492                                 {
493                                         $this->logRequest(__METHOD__, $packet, 'Damages section required field not a valid reference: VehicleComponentId');
494                                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Damages section required field not a valid reference: VehicleComponentId', 018);
495                                 }
496                                 $Valuation['Damages'][$i]['VehicleComponentId'] = $record;
497                                 if (isset($damageEntry['Amount']) && !is_numeric($damageEntry['Amount']))
498                                 {
499                                         $this->logRequest(__METHOD__, $packet, 'Damages section required field not numeric: Amount');
500                                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Damages section required field not numeric: Amount', 019);
501                                 }
502                         }
503                 }
504
505                 #-> Verify accessories collection.
506                 if (isset($Valuation['Accessories']))
507                 {
508                         foreach ($Valuation['Accessories'] as $i => $accessoryEntry)
509                         {
510                                 if (!isset($accessoryEntry['VehicleAccessoryId']) || 0 == strlen($accessoryEntry['VehicleAccessoryId']) || !is_numeric($accessoryEntry['VehicleAccessoryId']))
511                                 {
512                                         $this->logRequest(__METHOD__, $packet, 'Accessories section required field not provided or not numeric: VehicleAccessoryId');
513                                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Accessories section required field not provided or not numeric: VehicleAccessoryId', 020);
514                                 }
515                                 $record = $this->em->find('Stock\\Entity\\Accessory', $accessoryEntry['VehicleAccessoryId']);
516                                 if (is_null($record))
517                                 {
518                                         $this->logRequest(__METHOD__, $packet, 'Accessories section required field not a valid reference: VehicleAccessoryId');
519                                         throw new \Zend\XmlRpc\Server\Exception\RuntimeException('Accessories section required field not a valid reference: VehicleAccessoryId', 021);
520                                 }
521                                 $Valuation['Accessories'][$i]['VehicleAccessoryId'] = $record;
522                         }
523                 }
524
525                 #-> Collect trade and retail values.
526                 $result = \Utility\Comms\TransUnion::searchByMmCode(
527                                 $Valuation['VehicleTypeId']->mmCode,
528                                 $Valuation['VehicleYearId']->name
529                 );
530                 if (is_array($result)
531                         && isset($result['VehicleDetails'])
532                         && isset($result['VehicleDetails'][0])
533                         && isset($result['VehicleDetails'][0]['Value']))
534                 {
535                         $Valuation['tradePrice'] = $result['VehicleDetails'][0]['Value']['TradePrice'];
536                         $Valuation['retailPrice'] = $result['VehicleDetails'][0]['Value']['RetailPrice'];
537             $Valuation['listPrice'] = $result['VehicleDetails'][0]['Value']['ListPrice'];
538                 }
539                 else
540                 {
541                         $Valuation['tradePrice'] = 0.0;
542                         $Valuation['retailPrice'] = 0.0;
543             $Valuation['listPrice'] = 0.0;
544                 }
545
546                 # ------------------------------------------------------------------------------ #
547                 #-> Validation complete, create stock, damages, accessories and valuation entries.
548                 #-> Create stock entry.
549                 $stock = new \Stock\Entity\Stock();
550                 $stock->tradePrice = $Valuation['tradePrice'];
551                 $stock->retailPrice = $Valuation['retailPrice'];
552         $stock->listPrice = $Valuation['listPrice'];
553                 isset($Valuation['VehicleYearId'])
554                         && $stock->vehicleYear = $Valuation['VehicleYearId'];
555                 isset($Valuation['VehicleTypeId'])
556                         && $stock->type = $Valuation['VehicleTypeId'];
557                 isset($Valuation['RegistrationNumber'])
558                         && $stock->registrationNumber = $Valuation['RegistrationNumber'];
559                 isset($Valuation['VehicleFuelTypeId'])
560                         && $stock->fuelType = $Valuation['VehicleFuelTypeId'];
561                 isset($Valuation['VehicleTransmissionTypeId'])
562                         && $stock->transmissionType = $Valuation['VehicleTransmissionTypeId'];
563                 isset($Valuation['VinNumber'])
564                         && $stock->vinNumber = $Valuation['VinNumber'];
565                 isset($Valuation['EngineNumber'])
566                         && $stock->engineNumber = $Valuation['EngineNumber'];
567                 isset($Valuation['Km'])
568                         && $stock->km = $Valuation['Km'];
569                 isset($Valuation['VehicleConditionId'])
570                         && $stock->condition = $Valuation['VehicleConditionId'];
571                 isset($Valuation['VehicleExteriorColourId'])
572                         && $stock->exteriorColour = $Valuation['VehicleExteriorColourId'];
573                 isset($Valuation['VehicleInteriorColourId'])
574                         && $stock->interiorColour = $Valuation['VehicleInteriorColourId'];
575                 isset($Valuation['VehicleUpholsteryId'])
576                         && $stock->upholstery = $Valuation['VehicleUpholsteryId'];
577                 isset($Valuation['VehiclePapersId'])
578                         && $stock->papers = $Valuation['VehiclePapersId'];
579                 isset($Valuation['VehicleNatisId'])
580                         && $stock->natisc = $Valuation['VehicleNatisId'];
581                 isset($Valuation['natis'])
582                         && $stock->spareKeys = $Valuation['natis'];
583                 isset($Valuation['FullServiceHistory'])
584                         && $stock->fullServiceHistory = $Valuation['FullServiceHistory'];
585                 isset($Valuation['FullServiceHistoryNotes'])
586                         && $stock->fshNotes = $Valuation['FullServiceHistoryNotes'];
587                 isset($Valuation['PreviousRepairs'])
588                         && $stock->previousRepairsNoted = $Valuation['PreviousRepairs'];
589                 isset($Valuation['PreviousRepairsNotes'])
590                         && $stock->previousRepairsNotes = $Valuation['PreviousRepairsNotes'];
591                 isset($Valuation['AccessoryNotes'])
592                         && $stock->accessoryNotes = $Valuation['AccessoryNotes'];
593                 isset($Valuation['DamageNotes'])
594                         && $stock->damageNotes = $Valuation['DamageNotes'];
595
596                 $this->em->persist($stock);
597                 $this->em->flush($stock);
598                 $stock->postInsert();
599                 $this->em->flush($stock);
600
601                 #-> Log images so that we can download them later.
602                 $images = array(
603                                 1 => 'main',
604                                 2 => 'front',
605                                 3 => 'right',
606                                 4 => 'left',
607                                 5 => 'back',
608                                 6 => 'interior',
609                                 7 => 'engine',
610                                 8 => 'natis'
611                 );
612                 $stockImages = null;
613                 for ($i = 1; $i <= 8; $i++)
614                 {
615                         $field = 'VehiclePhoto' . $i . 'URL';
616                         $urlField = $images[$i] . 'ImageUrl';
617                         if (isset($Valuation[$field]) && !is_null($Valuation[$field]))
618                         {
619                                 if (is_null($stockImages))
620                                 {
621                                         $stockImages = new \Stock\Entity\StockImages();
622                                         $stockImages->stock = $stock;
623                                 }
624                                 $stockImages->$urlField = $Valuation[$field];
625                         }
626                 }
627                 if (!is_null($stockImages))
628                 {
629                         $this->em->persist($stockImages);
630                         $this->em->flush($stockImages);
631                 }
632
633                 #-> Log vehicle accessories.
634                 foreach ($Valuation['Accessories'] as $item)
635                 {
636                         $accessory                              = new \Stock\Entity\StockAccessory();
637                         $accessory->stock               = $stock;
638                         $accessory->accessory   = $item['VehicleAccessoryId'];
639                         $this->em->persist($accessory);
640                 }
641                 $this->em->flush();
642
643                 #-> Log vehicle damages.
644                 $total = 0.0;
645                 foreach ($Valuation['Damages'] as $item)
646                 {
647                         $damage                 = new \Stock\Entity\StockDamage();
648                         $damage->stock  = $stock;
649                         $damage->damage = $item['VehicleComponentId'];
650                         $damage->amount = $item['Amount'];
651                         $this->em->persist($damage);
652                         $total += $damage->amount;
653                 }
654                 $stock->damageTotal = $total;
655                 $this->em->flush();
656
657                 #-> Create valuation entry.
658                 $this->valuation = new \Valuation\Entity\Valuation();
659                 $this->valuation->xmlRpcClient                  = $this->client;
660                 $this->valuation->stock                                 = $stock;
661                 $this->valuation->tradeRetailRequested  = true;
662                 $this->valuation->jobState                              = 'New Valuation';
663                 isset($Valuation['ItemId'])
664                         && $this->valuation->sfItemId = $Valuation['ItemId'];
665                 isset($Valuation['CustomerName'])
666                         && $this->valuation->firstName = $Valuation['CustomerName'];
667                 isset($Valuation['CustomerSurname'])
668                         && $this->valuation->familyName = $Valuation['CustomerSurname'];
669                 isset($Valuation['CustomerIdNumber'])
670                         && $this->valuation->idNumber = $Valuation['CustomerIdNumber'];
671                 isset($Valuation['CustomerMobile'])
672                         && $this->valuation->mobile = $Valuation['CustomerMobile'];
673                 isset($Valuation['CustomerEmail'])
674                         && $this->valuation->email = $Valuation['CustomerEmail'];
675                 isset($Valuation['Department'])
676                         && $this->valuation->department = $Valuation['Department'];
677                 $this->em->persist($this->valuation);
678                 $this->em->flush($this->valuation);
679                 $this->valuation->postInsert();
680                 $this->em->flush($this->valuation);
681                 $stock->valuation = $this->valuation;
682                 $this->em->flush($stock);
683
684                 #-> Collect list of valuators to send to.
685                 $userBin = new \User\DataBin\Profile();
686                 $filters = $userBin->getValuationFilters();
687                 $valuators = $this->em->getRepository('User\\Entity\\Profile')
688                         ->findBy($filters);
689                 if (!empty($valuators))
690                 {
691                         $serviceInput = new \Workspace\Utility\ServiceInput();
692                         $valuationService = new \Valuation\Service\Valuation();
693                         $valuationService->setWorkflow(\Utility\Registry::getServiceManager()->get('Valuation'));
694                         $valuationService->generateHistoryList(array(), $this->valuation, $this->valuation, new \Workspace\Utility\ServiceInputParams());
695
696                         $this->valuation->queueStatus = 1;
697                         $this->em->flush($this->valuation);
698                         $authData = \Utility\Registry::getAuthData();
699
700                         $fromCompanyId  = isset($authData['company']['id']) ? $authData['company']['id'] : null;
701                         $fromProfileId  = isset($authData['id']) ? $authData['id'] : null;
702
703                         $params = array();
704                         $params['firstName']                    = $authData['firstName'];
705                         $params['familyName']                   = $authData['familyName'];
706                         $params['customer_name']                = $this->valuation->firstName;
707                         $params['customer_family_name'] = $this->valuation->familyName;
708                         $params['vehicle_reg']                  = is_null($stock->registrationNumber)
709                                 ? ''
710                                 : $stock->registrationNumber;
711                         $oNotify                = new \Utility\Comms\Notification();
712                         $templateName   = 'valuation-mobile-new';
713                         $subject                = null;
714                         $toCompanyId    = $fromCompanyId;
715                         $email                  = null;
716                         foreach ($valuators as $valuator)
717                         {
718                                 $valuator               = $valuator->toArray();
719                                 $toProfileId    = $valuator['id'];
720                                 $mobile                 = $valuator['mobile'];
721                                 $oNotify->sendFromTemplate(
722                                                 $fromCompanyId, $fromProfileId,
723                                                 $toCompanyId, $toProfileId,
724                                                 $email, $mobile,
725                                                 $subject,
726                                                 $templateName,
727                                                 $params
728                                 );
729                         }
730                 }
731
732                 #-> Return.
733                 $this->logRequest(__METHOD__, $packet);
734                 return array(
735                                 'TradePrice'  => $Valuation['tradePrice'],
736                                 'RetailPrice' => $Valuation['retailPrice'],
737                 'ListPrice' => $Valuation['listPrice']
738                 );
739         }
740
741
742 }