text changes to registration mail content
[namibia] / module / Stock / src / Stock / Service / Utility.php
1 <?php
2 namespace Stock\Service;
3 use Utility\Debug;
4
5
6 /**
7  * Manage accessory data.
8  * @author andre.fourie
9  */
10 class Utility extends \Workspace\Service\Workflow
11 {
12
13
14
15         public function deviceTransUnionFromMmCode(\Workspace\Utility\ServiceInputParams $contract)
16         {
17                 $tu = new \Utility\Comms\TransUnion();
18                 if (!isset($contract->data->Filter['mmCode'])
19                         || !isset($contract->data->Filter['vehicleYear']))
20                 {
21                         return $contract->deviceError(
22                                         'Required fields not provided',
23                                         'Requires `mmCode` and `vehicleYear`. Optionally accepts `mileage` and `condition`.'
24                                         );
25                 }
26                 $this->em = \Utility\Registry::getEntityManager();
27                 $data = $tu->searchByMmCode(
28                                 $contract->data->Filter['mmCode'],
29                                 $this->em->getRepository('\Stock\Entity\Year')
30                                         ->find($contract->data->Filter['vehicleYear'])
31                                         ->name,
32                                 isset($contract->data->Filter['mileage'])
33                                         ? $contract->data->Filter['mileage']
34                                         : null,
35                                 isset($contract->data->Filter['condition'])
36                                         ? $this->em->getRepository('\Stock\Entity\Condition')
37                                                 ->find($contract->data->Filter['condition'])
38                                                 ->name
39                                         : null
40                                 );
41                 if (is_null($data) || empty($data))
42                 {
43                         return $contract->deviceError(
44                                         'API call to remote host failed.',
45                                         'No data could be retrieved from remote service.'
46                                         );
47                 }
48                 return $contract->deviceSuccess('Data retrieved.', $data);
49         }
50
51
52         /**
53          * Contract to acquire TransUnion data.
54          * @param object|null $jobRecord
55          * @param array $input
56          * @return \Workspace\Contract\Recurring
57          */
58         public function contractTransUnionFromMmCode($jobRecord, array $input = array())
59         {
60
61                 $options = new \Workspace\UseCase\Options();
62                 $requirement = new \Workspace\UseCase\Requirement();
63                 $requirement->addRequiredInput(array(
64                                 'Filter' => array(
65                                                 'type'        => 'Id',
66                                                 'vehicleYear' => 'Id'
67                                 )
68                 ));
69                 $requirement->addOptionalInput(array(
70                                 'Filter' => array(
71                                                 'stockId'     => 'Id'
72                                 )
73                 ));
74                 return new \Workspace\Contract\Recurring($options, $requirement);
75         }
76
77         /**
78          * Acquire TransUnion data.
79          * @param object|null $jobRecord
80          * @param \Workspace\Utility\ServiceInputParams $contract
81          * @return array
82          */
83         public function executeTransUnionFromMmCode($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
84         {
85
86                 $tu = new \Utility\Comms\TransUnion();
87                 if (!isset($contract->data->Filter['type'])
88                         || !isset($contract->data->Filter['vehicleYear']))
89                 {
90                         return $contract->error(
91                                         'Required fields not provided',
92                                         'Requires `type` and `vehicleYear`. Optionally accepts `km` and `condition`.'
93                                         );
94                 }
95                 $this->em = \Utility\Registry::getEntityManager();
96                 $data = $tu->searchByMmCode(
97                                 $this->em->getRepository('\Stock\Entity\Type')
98                                         ->find($contract->data->Filter['type'])
99                                         ->mmCode,
100                                 $this->em->getRepository('\Stock\Entity\Year')
101                                         ->find($contract->data->Filter['vehicleYear'])
102                                         ->name,
103                                 null,
104                                 null
105                                 );
106
107                 if (is_null($data) || empty($data) || false == $data)
108                 {
109                         return $contract->error(
110                                         'API call to remote host failed.',
111                                         'No data could be retrieved from remote service.',
112                                         array()
113                                         );
114                 }
115                 if (isset($contract->data->Filter['stockId'])
116                         && is_numeric($contract->data->Filter['stockId'])
117                         && 0 < $contract->data->Filter['stockId']
118                         && isset($data['VehicleDetails'])
119                         && isset($data['VehicleDetails'][0])
120                         && isset($data['VehicleDetails'][0]['Value']))
121                 {
122                         $jobRecord = $this->em->find('Stock\\Entity\\Stock', $contract->data->Filter['stockId']);
123                         $jobRecord->oldTradePrice  = $jobRecord->tradePrice;
124                         $jobRecord->oldRetailPrice = $jobRecord->retailPrice;
125             $jobRecord->oldListPrice  = $jobRecord->listPrice;
126                         $jobRecord->tradePrice  = 0.00 + $data['VehicleDetails'][0]['Value']['TradePrice'];
127                         $jobRecord->retailPrice = 0.00 + $data['VehicleDetails'][0]['Value']['RetailPrice'];
128             $jobRecord->listPrice = 0.00 + $data['VehicleDetails'][0]['Value']['NewPrice'];
129                         $this->em->flush($jobRecord);
130                 }
131                 return $contract->success('Data retrieved.', $data);
132         }
133
134
135         /**
136          * Contract to acquire TransUnionHPI data.
137          * @param object|null $jobRecord
138          * @param array $input
139          * @return \Workspace\Contract\Recurring
140          */
141         public function contractTransUnionForHPI($jobRecord, array $input = array())
142         {
143                 $options = new \Workspace\UseCase\Options();
144                 $requirement = new \Workspace\UseCase\Requirement();
145                 $requirement->addRequiredInput(array(
146                                 'Filter' => array(
147                                                 'username'        => 'String255',
148                                                 'pass'                    => 'String255',
149                                                 'stock'                   => 'Id'
150                                 )
151                 ));
152                 return new \Workspace\Contract\Recurring($options, $requirement);
153
154         }
155
156         /**
157          * Acquire TransUnionHPI data.
158          * @param object|null $jobRecord
159          * @param \Workspace\Utility\ServiceInputParams $contract
160          * @return array
161          */
162         public function executeTransUnionForHPI($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
163         {
164         ini_set('memory_limit','-1');
165
166
167                 $data[] = 'false';
168                 $username = $contract->data->Filter['username'];
169                 $password = $contract->data->Filter['pass'];
170                 $stockId = $contract->data->Filter['stock'];
171                 $jobRecord = $this->em->find('Stock\\Entity\\Stock', $stockId);
172
173                 #-> Chat to TU.
174                 $authData = \Utility\Registry::getAuthData();
175                 $client =  new \Zend\Soap\Client(
176 //            "https://autoinsight.transunion.co.za/AISConvergedB2BWrapper/AISConvergedB2BWrapper.asmx?wsdl", //LIVE
177 //            "http://secureuat.decisionsystems.co.za/AISConvergedB2BWrapper/AISConvergedB2BWrapper.asmx?wsdl", //QA
178                         "https://autotest.transunion.co.za/AISConvergedB2BWrapper/AISConvergedB2BWrapper.asmx?wsdl", //new LIVE oct 2016
179                         array(
180                                 'soap_version' => SOAP_1_1
181                         )
182                 );
183                 $query = array(
184                                 'ExtensionData'                 => null,
185                                 'Colour'                                => !is_null($jobRecord->exteriorColour)
186                                                                                                 ? $jobRecord->exteriorColour->name
187                                                                                                 : '',
188                                 'Condition'                     => !is_null($jobRecord->condition)
189                                                                                                 ? $jobRecord->condition->name
190                                                                                                 : '',
191                                 'CustomerProductId'     => 0,
192                                 'EngineNumber'                  => !is_null($jobRecord->engineNumber)
193                                                                                                 ? (string) strtoupper($jobRecord->engineNumber)
194                                                                                                 : '',
195                                 'GuideMonth'                    => 1,
196                                 'GuideYear'                     => $jobRecord->vehicleYear->name,
197                                 'LoginId'                               => (string) $username,
198                                 'Password'                              => (string) $password,
199                                 'RegistrationNumber'    => strtoupper($jobRecord->registrationNumber),
200                                 'RegistrationYear'              => $jobRecord->type->introYear->name,
201                                 'RequestorPerson'               => $authData['firstName'] . ' ' . $authData['familyName'],
202                                 'RequestorTelNumber'    => $authData['mobile'],
203                                 'VehicleCode'                   => (string) $jobRecord->type->mmCode,
204                                 'VehicleMileage'                => !is_null($jobRecord->km)
205                                                                                                 ? $jobRecord->km
206                                                                                                 : 0,
207                                 'VinOrChasisNumber'     => !is_null($jobRecord->vinNumber)
208                                                                                                 ? strtoupper($jobRecord->vinNumber)
209                                                                                                 : ''
210                 );
211                 if ('' == $query['Colour'])
212                 {
213                         unset($query['Colour']);
214                 }
215                 if ('' == $query['Condition'])
216                 {
217                         unset($query['Condition']);
218                 }
219                 if ('' == $query['EngineNumber'])
220                 {
221                         unset($query['EngineNumber']);
222                 }
223                 if ('' == $query['EngineNumber'])
224                 {
225                         unset($query['EngineNumber']);
226                 }
227                 if ('' == $query['RegistrationNumber'])
228                 {
229                         unset($query['RegistrationNumber']);
230                 }
231                 if ('' == $query['VinOrChasisNumber'])
232                 {
233                         unset($query['VinOrChasisNumber']);
234                 }
235                 try
236                 {
237 //            \Utility\Debug::errorLog('sending HPI', '---------------------');
238
239                         $res = $client->call("AISConvergedB2B", array(
240                                         'AISConvergedB2B' => array(
241                                                         'query' => $query
242                                         )
243                         ));
244                 }
245                 catch (\Exception $e)
246                 {
247                         #-> Log entry.
248                         ini_set('memory_limit','512M');
249                         \Utility\Debug::errorLog('Exception on HPI request', '');
250                         \Utility\Debug::errorLog('TU HPI request exception', "$e");
251                         $message = 'Could not connect to service.';
252                         $log = new \Stock\Entity\TuhpiLog();
253                         $log->stock     = $jobRecord;
254                         $log->status    = $message;
255                         $this->em->persist($log);
256                         $this->em->flush($log);
257                         throw new \Exception($message);
258                 }
259                 if (isset($res->AISConvergedB2BResult) && is_object($res->AISConvergedB2BResult)
260                                 && (!isset($res->AISConvergedB2BResult->ErrorCode) || empty($res->AISConvergedB2BResult->ErrorCode)))
261                 {
262                         $this->res = $res->AISConvergedB2BResult;
263                 }
264                 else
265                 {
266                         ini_set('memory_limit','512M');
267                         \Utility\Debug::errorLog('No result on HPI request', '');
268                         \Utility\Debug::errorLog('query', $query);
269                         \Utility\Debug::errorLog('result', $res);
270                         $message = isset($res->AISConvergedB2BResult->ErrorMessage)
271                                 ? $res->AISConvergedB2BResult->ErrorMessage
272                                 : 'Could not collect HPI report.';
273                         #-> Log entry.
274                         $log = new \Stock\Entity\TuhpiLog();
275                         $log->stock     = $jobRecord;
276                         $log->status    = $message;
277                         $this->em->persist($log);
278                         $this->em->flush($log);
279                         throw new \Exception($message);
280                 }
281
282 //        \Utility\Debug::errorLog('query', $query);
283 //        \Utility\Debug::errorLog('result', $this->res);
284
285                 #-> Save to DB.
286                 $data = array(
287                                 'stock' => $jobRecord,
288                                 'transactionNumber' => isset($this->res->TransactionNumber)
289                                         ? $this->res->TransactionNumber
290                                         : '',
291                                 // Finance Information
292                                 'f_financeProvider' => $this->getVal('Finance', 'Finance', 'FinanceProvider'),
293                                 'f_financeBranch' => $this->getVal('Finance', 'Finance', 'FinanceBranch'),
294                                 'f_agreementOrAccountNumber' => $this->getVal('Finance', 'Finance', 'AgreementOrAccountNumber'),
295                                 'f_agreementType' => $this->getVal('Finance', 'Finance', 'AgreementType'),
296                                 'f_telephoneNumber' => $this->getVal('Finance', 'Finance', 'TelNumber'),
297                                 'f_resultCode' => $this->getVal('Finance', 'Finance', ''),
298                                 // Finance History
299                                 'fh_data' => $this->getItVal('FinanceHistory', 'FinanceHistory', array(
300                                                 'financeHouse' => 'FinanceHouse',
301                                                 'agreementOrAccountNumber' => 'AgreementOrAccountNumber',
302                                                 'agreementType' => 'AgreementType',
303                                                 'telephoneNumber' => 'TelephoneNumber',
304                                                 'startDate' => 'StartDate',
305                                                 'endDate' => 'EndDate',
306                                                 'resultCode' => 'ResultCode'
307                                 )),
308                                 // Accident History
309                                 'ah_data' => $this->getItVal('AccidentHistory', 'AccidentHistory', array(
310                                                 'source' => 'Source',
311                                                 'assessmentDate' => 'AssessmentDate',
312                                                 'vehicleDescription' => 'VehicleDescription',
313                                                 'vinMatch' => 'VinMatch',
314                                                 'regMatch' => 'RegMatch',
315                                                 'estimatedRepairCost' => 'EstimatedRepairCost',
316                                                 'assessmentNumber' => 'AssessmentNumber',
317                                                 'engineMatch' => 'EngineMatch',
318                                                 'estimatePercentageOfRetailValue' => 'EstimatePercentageOfRetailValue',
319                                                 'resultCode' => 'ResultCode'
320                                 )),
321                                 // Stolen Information
322                                 'si_policeStation' => $this->getVal('StolenInfo', 'Stolen', 'PoliceStation'),
323                                 'si_caseNumber' => $this->getVal('StolenInfo', 'Stolen', 'CaseNumber'),
324                                 'si_dateStolen' => $this->getVal('StolenInfo', 'Stolen', 'DateStolen'),
325                                 'si_vinMatch' => $this->getVal('StolenInfo', 'Stolen', 'VinMatch'),
326                                 'si_engineMatch' => $this->getVal('StolenInfo', 'Stolen', 'EngineMatch'),
327                                 'si_registrationMatch' => $this->getVal('StolenInfo', 'Stolen', 'RegistrationMatch'),
328                                 'si_resultCode' => $this->getVal('StolenInfo', 'Stolen', 'ResultCode'),
329                                 // Alert Information
330                                 'ai_company' => $this->getVal('AlertInfo', 'Alert', 'Company'),
331                                 'ai_referenceNumber' => $this->getVal('AlertInfo', 'Alert', 'ReferenceNumber'),
332                                 'ai_alertReason' => $this->getVal('AlertInfo', 'Alert', 'AlertReason'),
333                                 'ai_telephoneNumber' => $this->getVal('AlertInfo', 'Alert', 'TelephoneNumber'),
334                                 'ai_resultCode' => $this->getVal('AlertInfo', 'Alert', 'ResultCode'),
335                                 // IVID History Information
336                                 'ivid_responseCode' => $this->getVal('IVIDHistory', 'IVIDHistory', 'ResponseCode'),
337                                 'ivid_responseDescription' => $this->getVal('IVIDHistory', 'IVIDHistory', 'ResponseDescription'),
338                                 'ivid_referenceNumber' => $this->getVal('IVIDHistory', 'IVIDHistory', 'ReferenceNumber'),
339                                 'ivid_contactNumber' => $this->getVal('IVIDHistory', 'IVIDHistory', 'CcontactNumber'),
340                                 'ivid_resultCode' => $this->getVal('IVIDHistory', 'IVIDHistory', 'ResultCode'),
341                                 // Microdot Information
342                                 'mi_company' => $this->getVal('MicrodotInfo', 'Microdot', 'Company'),
343                                 'mi_referenceNumber' => $this->getVal('MicrodotInfo', 'Microdot', 'ReferenceNumber'),
344                                 'mi_contactNumber' => $this->getVal('MicrodotInfo', 'Microdot', 'ContactNumber'),
345                                 'mi_dateApplied' => $this->getVal('MicrodotInfo', 'Microdot', 'DateApplied'),
346                                 'mi_resultCode' => $this->getVal('MicrodotInfo', 'Microdot', 'ResultCode'),
347                                 // VESA Information
348                                 'vesa_CertificateNumber' => $this->getVal('VesaInfo', 'Vesa', 'CertificateNumber'),
349                                 'vesa_dateFitted' => $this->getVal('VesaInfo', 'Vesa', 'DateFitted'),
350                                 'vesa_brandName' => $this->getVal('VesaInfo', 'Vesa', 'BrandName'),
351                                 'vesa_brandModel' => $this->getVal('VesaInfo', 'Vesa', 'BrandModel'),
352                                 'vesa_deviceDescriptionType' => $this->getVal('VesaInfo', 'Vesa', 'DeviceDescriptionType'),
353                                 'vesa_resultCode' => $this->getVal('VesaInfo', 'Vesa', 'ResultCode'),
354                                 // Registration History
355                                 'rh_data' => $this->getItVal('RegistrationHistory', 'RegistrationHistory', array(
356                                                 'dateRegistered' => 'DateRegistered',
357                                                 'registrationNumber' => 'RegistrationNumber',
358                                                 'resultCode' => 'ResultCode'
359                                 )),
360                                 // Enquiry History
361                                 'eh_data' => $this->getItVal('EnquiryHistory', 'EnquiriesHistory', array(
362                                                 'source' => 'Source',
363                                                 'transactionDate' => 'TransactionDate',
364                                                 'resultCode' => 'ResultCode'
365                                 )),
366                                 // Mileage History
367                                 'mh_data' => $this->getItVal('MileageHistory', 'MileageHistory', array(
368                                                 'source' => 'Source',
369                                                 'vehicleMileage' => 'VehicleMileage',
370                                                 'dateRegistered' => 'DateRegistered',
371                                                 'resultCode' => 'ResultCode'
372                                 )),
373                                 // VehicleOptionCodes
374                                 'vc_month' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'Month', 0),
375                                 'vc_year' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'Year', 0),
376                                 'vc_newOptionCode' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'NewOptionCode', 0),
377                                 'vc_usedOptionCode' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'UsedOptionCode', 0),
378                                 'vc_maximumRange' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'MaximumRange', 0),
379                                 'vc_minimunRange' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'MinimunRange', 0),
380                                 'vc_newPrice' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'NewPrice', 0),
381                                 'vc_retailPrice' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'RetailPrice', 0),
382                                 'vc_tradePrice' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'TradePrice', 0),
383                                 'vc_resultCode' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'ResultCode'),
384                                 // VehicleConfirmationInfo
385                                 'vci_HPINumber' => $this->getRtVal('VehicleConfirmationInfo', 'HPINumber'),
386                                 'vci_matchColour' => $this->getRtVal('VehicleConfirmationInfo', 'MatchColour'),
387                                 'vci_matchEngineNumber' => $this->getRtVal('VehicleConfirmationInfo', 'MatchEngineNumber'),
388                                 'vci_matchManufacturer' => $this->getRtVal('VehicleConfirmationInfo', 'MatchManufacturer'),
389                                 'vci_matchModel' => $this->getRtVal('VehicleConfirmationInfo', 'MatchModel'),
390                                 'vci_matchString' => $this->getRtVal('VehicleConfirmationInfo', 'MatchString'),
391                                 'vci_matchVehicleRegistration' => $this->getRtVal('VehicleConfirmationInfo', 'MatchVehicleRegistration'),
392                                 'vci_matchVinorChassis' => $this->getRtVal('VehicleConfirmationInfo', 'MatchVinorChassis'),
393                                 'vci_matchYear' => $this->getRtVal('VehicleConfirmationInfo', 'MatchYear'),
394                                 // VehicleValueInfo
395                                 'vvi_guideMonth' => $this->getRtVal('VehicleValueInfo',  'GuideMonth', 0),
396                                 'vvi_guideYear' => $this->getRtVal('VehicleValueInfo',  'GuideYear', 0),
397                                 'vvi_newListPrice' => $this->getRtVal('VehicleValueInfo',  'NewListPrice', 0),
398                                 'vvi_retailPrice' => $this->getRtVal('VehicleValueInfo',  'RetailPrice', 0),
399                                 'vvi_tradePrice' => $this->getRtVal('VehicleValueInfo',  'TradePrice', 0),
400                                 'vvi_costPrice' => $this->getRtVal('VehicleValueInfo',  'CostPrice', 0),
401                                 'vvi_adjustedRetailPrice_mileageAndCondition' => $this->getRtVal('VehicleValueInfo',  'AdjustedRetailPrice_MileageAndCondition', 0),
402                                 'vvi_AdjustedTradePrice_MileageAndCondition' => $this->getRtVal('VehicleValueInfo',  'AdjustedTradePrice_MileageAndCondition', 0),
403                                 'vvi_adjustedRetailPrice' => $this->getRtVal('VehicleValueInfo',  'AdjustedRetailPrice', 0),
404                                 'vvi_adjustedTradePrice' => $this->getRtVal('VehicleValueInfo',  'AdjustedTradePrice', 0),
405                                 'vvi_estimatedRetailPrice' => $this->getRtVal('VehicleValueInfo',  'EstimatedRetailPrice', 0),
406                                 'vvi_estimatedTradePrice' => $this->getRtVal('VehicleValueInfo',  'EstimatedTradePrice', 0),
407                                 'vvi_estimatedCostPrice' => $this->getRtVal('VehicleValueInfo',  'EstimatedCostPrice', 0),
408                                 'vvi_adjustedEstimatedRetailPrice_mileageAndCondition' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedRetailPrice_MileageAndCondition', 0),
409                                 'vvi_adjustedEstimatedTradePrice_mileageAndCondition' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedTradePrice_MileageAndCondition', 0),
410                                 'vvi_adjustedEstimatedcostprice_mileageandcondition' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedCostPrice_MileageAndCondition', 0),
411                                 'vvi_adjustedEstimatedRetailPrice' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedRetailPrice', 0),
412                                 'vvi_adjustedEstimatedTradePrice' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedTradePrice', 0),
413                                 'vvi_adjustedEstimatedCostPrice' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedCostPrice', 0),
414                                 'vvi_resultCode' => $this->getRtVal('VehicleValueInfo',  'ResultCode'),
415                                 // Error codes
416                                 'error_code' => null,
417                 'hpi_type' => 'HPI'
418                 );
419
420 //        \Utility\Debug::errorLog('data', $data);
421
422                 $rep = new \Stock\Entity\Tuhpi();
423                 $rep->fromArray($data);
424                 $this->em->persist($rep);
425                 $this->em->flush($rep);
426
427                 #-> Log entry.
428                 $log = new \Stock\Entity\TuhpiLog();
429                 $log->tuhpi     = $rep;
430                 $log->stock     = $jobRecord;
431                 $log->status    = 'Success';
432                 $this->em->persist($log);
433                 $this->em->flush($log);
434                 return $contract->success('Data retrieved.', array('id' => $rep->id));
435         }
436
437     /**
438      * Contract to acquire TransUnionHPI data.
439      * @param object|null $jobRecord
440      * @param array $input
441      * @return \Workspace\Contract\Recurring
442      */
443     public function contractTransUnionForHPIAccident($jobRecord, array $input = array())
444     {
445         $options = new \Workspace\UseCase\Options();
446         $requirement = new \Workspace\UseCase\Requirement();
447         $requirement->addRequiredInput(array(
448             'Filter' => array(
449                 'username'        => 'String255',
450                 'pass'                    => 'String255',
451                 'stock'                   => 'Id'
452             )
453         ));
454         return new \Workspace\Contract\Recurring($options, $requirement);
455
456     }
457
458     /**
459      * Acquire TransUnionHPI data.
460      * @param object|null $jobRecord
461      * @param \Workspace\Utility\ServiceInputParams $contract
462      * @return array
463      */
464     public function executeTransUnionForHPIAccident($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
465     {
466         ini_set('memory_limit','-1');
467
468         $data[] = 'false';
469
470 //        \Utility\Debug::errorLog('$contract->data', $contract->data);
471
472         $username = $contract->data->Filter['username'];
473         $password = $contract->data->Filter['pass'];
474         $stockId = $contract->data->Filter['stock'];
475         $jobRecord = $this->em->find('Stock\\Entity\\Stock', $stockId);
476
477         #-> Chat to TU.
478         $authData = \Utility\Registry::getAuthData();
479         $client =  new \Zend\Soap\Client(
480 //                      "https://autoinsight.transunion.co.za/AISConvergedB2BWrapper/AISConvergedB2BWrapper.asmx?wsdl", //LIVE
481 //            "http://secureuat.decisionsystems.co.za/AISConvergedB2BWrapper/AISConvergedB2BWrapper.asmx?wsdl", //QA
482                         "https://autotest.transunion.co.za/AISConvergedB2BWrapper/AISConvergedB2BWrapper.asmx?wsdl", //new LIVE oct 2016
483
484             array(
485                 'soap_version' => SOAP_1_1
486             )
487         );
488         $query = array(
489             'ExtensionData'                     => null,
490             'Colour'                            => !is_null($jobRecord->exteriorColour)
491                 ? $jobRecord->exteriorColour->name
492                 : '',
493             'Condition'                         => !is_null($jobRecord->condition)
494                 ? $jobRecord->condition->name
495                 : '',
496             'CustomerProductId'         => 0,
497             'EngineNumber'                      => !is_null($jobRecord->engineNumber)
498                 ? (string) strtoupper($jobRecord->engineNumber)
499                 : '',
500             'GuideMonth'                        => 1,
501             'GuideYear'                         => $jobRecord->vehicleYear->name,
502 //            'LoginId'                                 => (string) $username,
503 //            'Password'                                => (string) $password,
504                         'LoginId'                               => (string) "187681",
505                         'Password'                              => (string) "Bid187681#",
506             'RegistrationNumber'        => strtoupper($jobRecord->registrationNumber),
507             'RegistrationYear'          => $jobRecord->type->introYear->name,
508             'RequestorPerson'           => $authData['firstName'] . ' ' . $authData['familyName'],
509             'RequestorTelNumber'        => $authData['mobile'],
510             'VehicleCode'                       => (string) $jobRecord->type->mmCode,
511             'VehicleMileage'            => !is_null($jobRecord->km)
512                 ? $jobRecord->km
513                 : 0,
514             'VinOrChasisNumber'         => !is_null($jobRecord->vinNumber)
515                 ? strtoupper($jobRecord->vinNumber)
516                 : ''
517         );
518         if ('' == $query['Colour'])
519         {
520             unset($query['Colour']);
521         }
522         if ('' == $query['Condition'])
523         {
524             unset($query['Condition']);
525         }
526         if ('' == $query['EngineNumber'])
527         {
528             unset($query['EngineNumber']);
529         }
530         if ('' == $query['EngineNumber'])
531         {
532             unset($query['EngineNumber']);
533         }
534         if ('' == $query['RegistrationNumber'])
535         {
536             unset($query['RegistrationNumber']);
537         }
538         if ('' == $query['VinOrChasisNumber'])
539         {
540             unset($query['VinOrChasisNumber']);
541         }
542         try
543         {
544 //            \Utility\Debug::errorLog('sending HPI', '---------------------');
545
546             $res = $client->call("AISConvergedB2B", array(
547                 'AISConvergedB2B' => array(
548                     'query' => $query
549                 )
550             ));
551         }
552         catch (\Exception $e)
553         {
554             #-> Log entry.
555             ini_set('memory_limit','512M');
556             \Utility\Debug::errorLog('Exception on HPI request', '');
557             \Utility\Debug::errorLog('TU HPI request exception', "$e");
558             $message = 'Could not connect to service.';
559             $log = new \Stock\Entity\TuhpiLog();
560             $log->stock         = $jobRecord;
561             $log->status        = $message;
562             $this->em->persist($log);
563             $this->em->flush($log);
564             throw new \Exception($message);
565         }
566         if (isset($res->AISConvergedB2BResult) && is_object($res->AISConvergedB2BResult)
567             && (!isset($res->AISConvergedB2BResult->ErrorCode) || empty($res->AISConvergedB2BResult->ErrorCode)))
568         {
569             $this->res = $res->AISConvergedB2BResult;
570         }
571         else
572         {
573             ini_set('memory_limit','512M');
574             \Utility\Debug::errorLog('No result on HPI request', '');
575             \Utility\Debug::errorLog('query Accident', $query);
576             \Utility\Debug::errorLog('result Accident', $res);
577             $message = isset($res->AISConvergedB2BResult->ErrorMessage)
578                 ? $res->AISConvergedB2BResult->ErrorMessage
579                 : 'Could not collect HPI report.';
580             #-> Log entry.
581             $log = new \Stock\Entity\TuhpiLog();
582             $log->stock         = $jobRecord;
583             $log->status        = $message;
584             $this->em->persist($log);
585             $this->em->flush($log);
586             throw new \Exception($message);
587         }
588
589 //        \Utility\Debug::errorLog('query Accident', $query);
590 //        \Utility\Debug::errorLog('result Accident', $this->res);
591
592
593         $datatest = array(// Accident History
594             'ah_data' => $this->getItVal('AccidentHistory', 'AccidentHistory', array(
595                 'source' => 'Source',
596                 'assessmentDate' => 'AssessmentDate',
597                 'vehicleDescription' => 'VehicleDescription',
598                 'vinMatch' => 'VinMatch',
599                 'regMatch' => 'RegMatch',
600                 'estimatedRepairCost' => 'EstimatedRepairCost',
601                 'assessmentNumber' => 'AssessmentNumber',
602                 'engineMatch' => 'EngineMatch',
603                 'estimatePercentageOfRetailValue' => 'EstimatePercentageOfRetailValue',
604                 'resultCode' => 'ResultCode'
605             )));
606
607 //        \Utility\Debug::errorLog('$datatest', $datatest);
608
609         #-> Save to DB.
610         $data = array(
611             'stock' => $jobRecord,
612             'transactionNumber' => isset($this->res->TransactionNumber)
613                 ? $this->res->TransactionNumber
614                 : '',
615             // Finance Information
616             'f_financeProvider' => $this->getVal('Finance', 'Finance', 'FinanceProvider'),
617             'f_financeBranch' => $this->getVal('Finance', 'Finance', 'FinanceBranch'),
618             'f_agreementOrAccountNumber' => $this->getVal('Finance', 'Finance', 'AgreementOrAccountNumber'),
619             'f_agreementType' => $this->getVal('Finance', 'Finance', 'AgreementType'),
620             'f_telephoneNumber' => $this->getVal('Finance', 'Finance', 'TelNumber'),
621             'f_resultCode' => $this->getVal('Finance', 'Finance', ''),
622             // Finance History
623             'fh_data' => $this->getItVal('FinanceHistory', 'FinanceHistory', array(
624                 'financeHouse' => 'FinanceHouse',
625                 'agreementOrAccountNumber' => 'AgreementOrAccountNumber',
626                 'agreementType' => 'AgreementType',
627                 'telephoneNumber' => 'TelephoneNumber',
628                 'startDate' => 'StartDate',
629                 'endDate' => 'EndDate',
630                 'resultCode' => 'ResultCode'
631             )),
632             // Accident History
633             'ah_data' => $this->getItVal('AccidentHistory', 'AccidentHistory', array(
634                 'source' => 'Source',
635                 'assessmentDate' => 'AssessmentDate',
636                 'vehicleDescription' => 'VehicleDescription',
637                 'vinMatch' => 'VinMatch',
638                 'regMatch' => 'RegMatch',
639                 'estimatedRepairCost' => 'EstimatedRepairCost',
640                 'assessmentNumber' => 'AssessmentNumber',
641                 'engineMatch' => 'EngineMatch',
642                 'estimatePercentageOfRetailValue' => 'EstimatePercentageOfRetailValue',
643                 'resultCode' => 'ResultCode'
644             )),
645             // Stolen Information
646             'si_policeStation' => $this->getVal('StolenInfo', 'Stolen', 'PoliceStation'),
647             'si_caseNumber' => $this->getVal('StolenInfo', 'Stolen', 'CaseNumber'),
648             'si_dateStolen' => $this->getVal('StolenInfo', 'Stolen', 'DateStolen'),
649             'si_vinMatch' => $this->getVal('StolenInfo', 'Stolen', 'VinMatch'),
650             'si_engineMatch' => $this->getVal('StolenInfo', 'Stolen', 'EngineMatch'),
651             'si_registrationMatch' => $this->getVal('StolenInfo', 'Stolen', 'RegistrationMatch'),
652             'si_resultCode' => $this->getVal('StolenInfo', 'Stolen', 'ResultCode'),
653             // Alert Information
654             'ai_company' => $this->getVal('AlertInfo', 'Alert', 'Company'),
655             'ai_referenceNumber' => $this->getVal('AlertInfo', 'Alert', 'ReferenceNumber'),
656             'ai_alertReason' => $this->getVal('AlertInfo', 'Alert', 'AlertReason'),
657             'ai_telephoneNumber' => $this->getVal('AlertInfo', 'Alert', 'TelephoneNumber'),
658             'ai_resultCode' => $this->getVal('AlertInfo', 'Alert', 'ResultCode'),
659             // IVID History Information
660             'ivid_responseCode' => $this->getVal('IVIDHistory', 'IVIDHistory', 'ResponseCode'),
661             'ivid_responseDescription' => $this->getVal('IVIDHistory', 'IVIDHistory', 'ResponseDescription'),
662             'ivid_referenceNumber' => $this->getVal('IVIDHistory', 'IVIDHistory', 'ReferenceNumber'),
663             'ivid_contactNumber' => $this->getVal('IVIDHistory', 'IVIDHistory', 'CcontactNumber'),
664             'ivid_resultCode' => $this->getVal('IVIDHistory', 'IVIDHistory', 'ResultCode'),
665             // Microdot Information
666             'mi_company' => $this->getVal('MicrodotInfo', 'Microdot', 'Company'),
667             'mi_referenceNumber' => $this->getVal('MicrodotInfo', 'Microdot', 'ReferenceNumber'),
668             'mi_contactNumber' => $this->getVal('MicrodotInfo', 'Microdot', 'ContactNumber'),
669             'mi_dateApplied' => $this->getVal('MicrodotInfo', 'Microdot', 'DateApplied'),
670             'mi_resultCode' => $this->getVal('MicrodotInfo', 'Microdot', 'ResultCode'),
671             // VESA Information
672             'vesa_CertificateNumber' => $this->getVal('VesaInfo', 'Vesa', 'CertificateNumber'),
673             'vesa_dateFitted' => $this->getVal('VesaInfo', 'Vesa', 'DateFitted'),
674             'vesa_brandName' => $this->getVal('VesaInfo', 'Vesa', 'BrandName'),
675             'vesa_brandModel' => $this->getVal('VesaInfo', 'Vesa', 'BrandModel'),
676             'vesa_deviceDescriptionType' => $this->getVal('VesaInfo', 'Vesa', 'DeviceDescriptionType'),
677             'vesa_resultCode' => $this->getVal('VesaInfo', 'Vesa', 'ResultCode'),
678             // Registration History
679             'rh_data' => $this->getItVal('RegistrationHistory', 'RegistrationHistory', array(
680                 'dateRegistered' => 'DateRegistered',
681                 'registrationNumber' => 'RegistrationNumber',
682                 'resultCode' => 'ResultCode'
683             )),
684             // Enquiry History
685             'eh_data' => $this->getItVal('EnquiryHistory', 'EnquiriesHistory', array(
686                 'source' => 'Source',
687                 'transactionDate' => 'TransactionDate',
688                 'resultCode' => 'ResultCode'
689             )),
690             // Mileage History
691             'mh_data' => $this->getItVal('MileageHistory', 'MileageHistory', array(
692                 'source' => 'Source',
693                 'vehicleMileage' => 'VehicleMileage',
694                 'dateRegistered' => 'DateRegistered',
695                 'resultCode' => 'ResultCode'
696             )),
697             // VehicleOptionCodes
698             'vc_month' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'Month', 0),
699             'vc_year' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'Year', 0),
700             'vc_newOptionCode' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'NewOptionCode', 0),
701             'vc_usedOptionCode' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'UsedOptionCode', 0),
702             'vc_maximumRange' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'MaximumRange', 0),
703             'vc_minimunRange' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'MinimunRange', 0),
704             'vc_newPrice' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'NewPrice', 0),
705             'vc_retailPrice' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'RetailPrice', 0),
706             'vc_tradePrice' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'TradePrice', 0),
707             'vc_resultCode' => $this->getVal('VehicleOptionCodesPrice', 'VehicleOptionCode', 'ResultCode'),
708             // VehicleConfirmationInfo
709             'vci_HPINumber' => $this->getRtVal('VehicleConfirmationInfo', 'HPINumber'),
710             'vci_matchColour' => $this->getRtVal('VehicleConfirmationInfo', 'MatchColour'),
711             'vci_matchEngineNumber' => $this->getRtVal('VehicleConfirmationInfo', 'MatchEngineNumber'),
712             'vci_matchManufacturer' => $this->getRtVal('VehicleConfirmationInfo', 'MatchManufacturer'),
713             'vci_matchModel' => $this->getRtVal('VehicleConfirmationInfo', 'MatchModel'),
714             'vci_matchString' => $this->getRtVal('VehicleConfirmationInfo', 'MatchString'),
715             'vci_matchVehicleRegistration' => $this->getRtVal('VehicleConfirmationInfo', 'MatchVehicleRegistration'),
716             'vci_matchVinorChassis' => $this->getRtVal('VehicleConfirmationInfo', 'MatchVinorChassis'),
717             'vci_matchYear' => $this->getRtVal('VehicleConfirmationInfo', 'MatchYear'),
718             // VehicleValueInfo
719             'vvi_guideMonth' => $this->getRtVal('VehicleValueInfo',  'GuideMonth', 0),
720             'vvi_guideYear' => $this->getRtVal('VehicleValueInfo',  'GuideYear', 0),
721             'vvi_newListPrice' => $this->getRtVal('VehicleValueInfo',  'NewListPrice', 0),
722             'vvi_retailPrice' => $this->getRtVal('VehicleValueInfo',  'RetailPrice', 0),
723             'vvi_tradePrice' => $this->getRtVal('VehicleValueInfo',  'TradePrice', 0),
724             'vvi_costPrice' => $this->getRtVal('VehicleValueInfo',  'CostPrice', 0),
725             'vvi_adjustedRetailPrice_mileageAndCondition' => $this->getRtVal('VehicleValueInfo',  'AdjustedRetailPrice_MileageAndCondition', 0),
726             'vvi_AdjustedTradePrice_MileageAndCondition' => $this->getRtVal('VehicleValueInfo',  'AdjustedTradePrice_MileageAndCondition', 0),
727             'vvi_adjustedRetailPrice' => $this->getRtVal('VehicleValueInfo',  'AdjustedRetailPrice', 0),
728             'vvi_adjustedTradePrice' => $this->getRtVal('VehicleValueInfo',  'AdjustedTradePrice', 0),
729             'vvi_estimatedRetailPrice' => $this->getRtVal('VehicleValueInfo',  'EstimatedRetailPrice', 0),
730             'vvi_estimatedTradePrice' => $this->getRtVal('VehicleValueInfo',  'EstimatedTradePrice', 0),
731             'vvi_estimatedCostPrice' => $this->getRtVal('VehicleValueInfo',  'EstimatedCostPrice', 0),
732             'vvi_adjustedEstimatedRetailPrice_mileageAndCondition' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedRetailPrice_MileageAndCondition', 0),
733             'vvi_adjustedEstimatedTradePrice_mileageAndCondition' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedTradePrice_MileageAndCondition', 0),
734             'vvi_adjustedEstimatedcostprice_mileageandcondition' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedCostPrice_MileageAndCondition', 0),
735             'vvi_adjustedEstimatedRetailPrice' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedRetailPrice', 0),
736             'vvi_adjustedEstimatedTradePrice' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedTradePrice', 0),
737             'vvi_adjustedEstimatedCostPrice' => $this->getRtVal('VehicleValueInfo',  'AdjustedEstimatedCostPrice', 0),
738             'vvi_resultCode' => $this->getRtVal('VehicleValueInfo',  'ResultCode'),
739             // Error codes
740             'error_code' => null,
741             'hpi_type' => 'ACC'
742         );
743
744 //        \Utility\Debug::errorLog('data', $data);
745
746         $rep = new \Stock\Entity\Tuhpi();
747         $rep->fromArray($data);
748         $this->em->persist($rep);
749         $this->em->flush($rep);
750
751         #-> Log entry.
752         $log = new \Stock\Entity\TuhpiLog();
753         $log->tuhpi     = $rep;
754         $log->stock     = $jobRecord;
755         $log->status    = 'Success';
756         $this->em->persist($log);
757         $this->em->flush($log);
758         return $contract->success('Data retrieved.', array('id' => $rep->id));
759     }
760
761         private $res = null;
762
763         private function getRtVal($root, $param, $default = '')
764         {
765                 return isset($this->res->$root->$param)
766                                 ? $this->res->$root->$param
767                                 : $default;
768         }
769
770         private function getVal($root, $parent, $param, $default = '')
771         {
772                 return isset($this->res->$root->$parent->$param)
773                                 ? $this->res->$root->$parent->$param
774                                 : $default;
775         }
776
777         private function getItVal($root, $parent, $map)
778         {
779                 if (isset($this->res->$root->$parent)
780 //                                      && is_array($this->res->$root->$parent)
781                                         && !empty($this->res->$root->$parent))
782                 {
783             $data = array();
784
785             if(is_array($this->res->$root->$parent))
786             {
787 //                \Utility\Debug::errorLog('--------------------------- is_array', '---------------------------');
788
789                 foreach ($this->res->$root->$parent as $item)
790                 {
791                     $entry = array();
792                     foreach ($map as $field => $param)
793                     {
794                         $entry[$field] = isset($item->$param)
795                             ? $item->$param
796                             : null;
797                     }
798                     $data[] = $entry;
799                 }
800             }
801             else
802             {
803 //                \Utility\Debug::errorLog('--------------------------- not array', '---------------------------');
804
805                 foreach ($this->res->$root as $item)
806                 {
807 //                    \Utility\Debug::errorLog('$item', $item);
808
809 //                    if(!property_exists($item,'ValidationMessages'))
810                     {
811                         $entry = array();
812                         foreach ($item as $field => $param)
813                         {
814 //                            \Utility\Debug::errorLog('$field', $field);
815 //                            \Utility\Debug::errorLog('$param', $param);
816
817                             $entry[lcfirst($field)] = isset($param)
818                                 ? $param
819                                 : null;
820                         }
821                         $data[] = $entry;
822                     }
823
824
825                 }
826
827             }
828
829 //            \Utility\Debug::errorLog('$data', $data);
830                         return $data;
831                 }
832                 else
833                 {
834                         return array();
835                 }
836         }
837
838
839         /**
840          * Contract to list vehicle makes according to Category and Year.
841          * @param object|null $jobRecord
842          * @param array $input
843          * @return \Workspace\Contract\Recurring
844          */
845         public function contractListMakes($jobRecord, array $input = array())
846         {
847                 $options = new \Workspace\UseCase\Options();
848                 $requirement = new \Workspace\UseCase\Requirement();
849                 $requirement->addRequiredInput(array(
850                                 'Filter' => array(
851                                                 'category' => 'Id',
852                                                 'year'     => 'Id'
853                                 )
854                 ));
855                 return new \Workspace\Contract\Recurring($options, $requirement);
856         }
857
858         /**
859          * List vehicle makes according to Category and Year.
860          * @param object|null $jobRecord
861          * @param \Workspace\Utility\ServiceInputParams $contract
862          * @return array
863          */
864         public function executeListMakes($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
865         {
866                 $dql = 'SELECT DISTINCT mk.id as value, mk.name as label '
867                          . 'FROM \Stock\Entity\Type tp '
868                          . 'JOIN tp.model md '
869                          . 'JOIN md.make mk '
870                          . 'WHERE IDENTITY(tp.category) = :category'
871                          . ' AND IDENTITY(tp.introYear) <= :year'
872                          . ' AND ('
873                          . '  IDENTITY(tp.discYear) >= :year'
874                          . '  OR tp.discYear IS NULL'
875                          . ' )';
876
877                 $data = $this->em->createQuery($dql)
878                         ->setParameter('category', $contract->data->Filter['category'])
879                         ->setParameter('year', $contract->data->Filter['year'])
880                         ->getArrayResult();
881                 return $contract->success('Data Collected.', $data);
882         }
883
884
885         /**
886          * Contract to list vehicle models according to Category and Year.
887          * @param object|null $jobRecord
888          * @param array $input
889          * @return \Workspace\Contract\UseOnce
890          */
891         public function contractListModels($jobRecord, array $input = array())
892         {
893                 $options = new \Workspace\UseCase\Options();
894                 $requirement = new \Workspace\UseCase\Requirement();
895                 $requirement->addRequiredInput(array(
896                                 'Filter' => array(
897                                                 'category' => 'Id',
898                                                 'year'     => 'Id',
899                                                 'make'     => 'Id'
900                                 )
901                 ));
902                 return new \Workspace\Contract\Recurring($options, $requirement);
903         }
904
905         /**
906          * List vehicle models according to Category and Year.
907          * @param object|null $jobRecord
908          * @param \Workspace\Utility\ServiceInputParams $contract
909          * @return array
910          */
911         public function executeListModels($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
912         {
913                 $dql = 'SELECT DISTINCT md.id as value, md.name as label '
914                          . 'FROM \Stock\Entity\Type tp '
915                          . 'JOIN tp.model md '
916                          . 'WHERE IDENTITY(md.make) = :make'
917                          . ' AND IDENTITY(tp.category) = :category'
918                          . ' AND IDENTITY(tp.introYear) <= :year'
919                          . ' AND ('
920                          . '  IDENTITY(tp.discYear) >= :year'
921                          . '  OR tp.discYear IS NULL'
922                          . ' )';
923                 $data = $this->em->createQuery($dql)
924                         ->setParameter('make', $contract->data->Filter['make'])
925                         ->setParameter('category', $contract->data->Filter['category'])
926                         ->setParameter('year', $contract->data->Filter['year'])
927                         ->getArrayResult();
928                 return $contract->success('Data Collected.', $data);
929         }
930
931
932         /**
933          * Contract to list vehicle types according to Category and Year.
934          * @param object|null $jobRecord
935          * @param array $input
936          * @return \Workspace\Contract\UseOnce
937          */
938         public function contractListTypes($jobRecord, array $input = array())
939         {
940                 $options = new \Workspace\UseCase\Options();
941                 $requirement = new \Workspace\UseCase\Requirement();
942                 $requirement->addRequiredInput(array(
943                                 'Filter' => array(
944                                                 'category' => 'Id',
945                                                 'year'     => 'Id',
946                                                 'model'    => 'Id'
947                                 )
948                 ));
949                 return new \Workspace\Contract\Recurring($options, $requirement);
950         }
951
952         /**
953          * List vehicle types according to Category and Year.
954          * @param object|null $jobRecord
955          * @param \Workspace\Utility\ServiceInputParams $contract
956          * @return array
957          */
958         public function executeListTypes($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
959         {
960
961                 /*
962                  SELECT
963                         tp.id AS value,
964                         TRIM(LEADING '0' FROM tp.mm_code) AS mmCode,
965                         tp.name AS label,
966                         iy.name AS typeIntroYear,
967                         dy.name AS typeDiscYear
968                 FROM
969                         vehicle_type tp
970                                 LEFT JOIN
971                         vehicle_year iy ON tp.intro_vehicle_year_id = iy.id
972                                 LEFT JOIN
973                         vehicle_year dy ON tp.disc_vehicle_year_id = dy.id
974                 WHERE
975                         tp.vehicle_model_id = 111
976                                 AND tp.vehicle_category_id = 2
977                                 AND iy.name < 2015
978                                 AND (dy.name >= 2015 OR dy.name IS NULL)
979                 GROUP BY 2 , 3 , 4
980                 ORDER BY mmCode , tp.id;
981                  */
982
983         /*$dql = 'SELECT DISTINCT tp.id as value, tp.name as label, iy.name as typeIntroYear, dy.name as typeDiscYear '
984             . 'FROM \Stock\Entity\Type tp '
985             . 'LEFT JOIN tp.introYear iy '
986             . 'LEFT JOIN tp.discYear dy '
987             . 'WHERE IDENTITY(tp.model) = :model'
988             . ' AND IDENTITY(tp.category) = :category'
989             . ' AND iy.id <= :year'
990             . ' AND ('
991             . '  dy.id >= :year'
992             . '  OR tp.discYear IS NULL'
993             . ' )';*/
994                 $dql = 'SELECT max(tp.id) as value, tp.name as label, iy.name as typeIntroYear, dy.name as typeDiscYear, tp.mmCode as mmCode '
995                         . 'FROM \Stock\Entity\Type tp '
996                         . 'LEFT JOIN tp.introYear iy '
997                         . 'LEFT JOIN tp.discYear dy '
998                         . 'WHERE IDENTITY(tp.model) = :model'
999                         . ' AND IDENTITY(tp.category) = :category'
1000                         . ' AND iy.id <= :year'
1001                         . ' AND ('
1002                         . '  dy.id >= :year'
1003                         . '  OR tp.discYear IS NULL'
1004                         . ' )'
1005                         . ' GROUP BY tp.mmCode, tp.name, iy.name, dy.name'
1006                         . ' ORDER BY tp.name';
1007         $dataGet = $this->em->createQuery($dql)
1008             ->setParameter('model', $contract->data->Filter['model'])
1009             ->setParameter('category', $contract->data->Filter['category'])
1010             ->setParameter('year', $contract->data->Filter['year'])
1011             ->getArrayResult();
1012
1013                 //Debug::errorLog("dataGet", $dataGet);
1014
1015         $data = array();
1016
1017         foreach($dataGet as $dataProcess)
1018         {
1019             $typeDiscYear = '';
1020
1021             if('' != $dataProcess['typeDiscYear'])
1022             {
1023                 $typeDiscYear = $dataProcess['typeDiscYear'];
1024             }
1025
1026             array_push($data,array(
1027                 'value' => $dataProcess['value'],
1028                 'label' => $dataProcess['label'] . ' (' . $dataProcess['typeIntroYear'] . ' - ' . $typeDiscYear . ')'
1029             ));
1030         }
1031
1032         return $contract->success('Data Collected.', $data);
1033
1034 //              $dql = 'SELECT DISTINCT tp.id as value, tp.name as label '
1035 //                       . 'FROM \Stock\Entity\Type tp '
1036 //                       . 'WHERE IDENTITY(tp.model) = :model'
1037 //                       . ' AND IDENTITY(tp.category) = :category'
1038 //                       . ' AND IDENTITY(tp.introYear) <= :year'
1039 //                       . ' AND ('
1040 //                       . '  IDENTITY(tp.discYear) >= :year'
1041 //                       . '  OR tp.discYear IS NULL'
1042 //                       . ' )';
1043 //              $data = $this->em->createQuery($dql)
1044 //                      ->setParameter('model', $contract->data->Filter['model'])
1045 //                      ->setParameter('category', $contract->data->Filter['category'])
1046 //                      ->setParameter('year', $contract->data->Filter['year'])
1047 //                      ->getArrayResult();
1048 //              return $contract->success('Data Collected.', $data);
1049         }
1050 }