previousState = 'Pending Valuation';
}
if ('This.Stock' == $status)
{
$valuation->previousState = 'Pending Valuation';
}
return array(
'Destination' => $status,
'Data' => $data
);
}
/**
* Deal Done for stats.
* @param \Valuation\Entity\Valuation
* @param string|null $previousState
* @param array|null $routingData
* @return string
*/
public function directRouteMoveToDealDone(\Valuation\Entity\Valuation $valuation, $previousState)
{
//Write hit to Stats logs (need stock or valuation stock id and profile id)
$today = new \DateTime();
//$test = "123";
//\Utility\Debug::errorLog('New dealDone', $test);
$em = \Utility\Registry::getEntityManager();
$loghit = new \Statistical\Entity\Statistical();
$loghitData = array(
'stock' => $em->getRepository('\Stock\Entity\Stock')->find($valuation->stock->id),
'dealdone' => true,
'dealnotdone' => false,
'tradecentre' => false,
'fromProfile' => $em->getRepository('\User\Entity\Profile')->find($valuation->stock->createdBy->id),
'created' => $today
);
$loghit->fromArray($loghitData);
$em->persist($loghit);
$valuation->stock->previousState = $valuation->stock->jobState;
$valuation->stock->jobState = 'Stock';
$em->flush();
return 'This.Stock';
}
/**
* Deal Not Done for stats.
* @param \Valuation\Entity\Valuation
* @param string|null $previousState
* @return string
*/
public function directRouteMoveToDealNotDone(\Valuation\Entity\Valuation $valuation, $previousState)
{
// Add XML to Higher Gear
if ($valuation->isPublic)
{
// remove +27 and add 0 like -> +2711xxxx becomes 011xxx
$mobileNumber = $valuation->mobile;
$mobileNumFormat = substr($mobileNumber, 3);
$mobileNumFormat = 0 . $mobileNumFormat;
/* xml template */
$xmlTemplateDnd = '
2013-07-10 19:52:42.38
' . $valuation->stock->vehicleYear->name . '
' . $valuation->stock->type->model->make->name . '
' . $valuation->stock->type->model->name . '
' . $valuation->stock->km . '
' . $valuation->stock->type->doors . '
' . $valuation->stock->transmissionType->name . '
' . $valuation->stock->vinNumber . '
' . $valuation->stock->stockNumber . '
' . $valuation->stock->exteriorColour->name . '
' . $valuation->stock->interiorColour->name . '
' . $valuation->firstName . '
' . $valuation->familyName . '
' . $mobileNumFormat . '
' . $mobileNumFormat . '
' . $valuation->email . '
' . $valuation->requiredPrice . '
' . $valuation->amountOffered . '
99999
bid4cars.co.za
unknown
dm1408082@highergear.net
' . $valuation->stock->company->name . '
';
$mailer = new \Utility\Comms\Email();
$mailer->send(array(
'From' => \Utility\Registry::getConfigParam('sourceEmailAddress'),
'To' => 'dm1408082@highergear.net',
'Subject' => 'Deal Not Done Valuation XML',
'Body' => $xmlTemplateDnd
));
$mailer = new \Utility\Comms\Email();
$mailer->send(array(
'From' => \Utility\Registry::getConfigParam('sourceEmailAddress'),
'To' => 'b4c@nirph.com',
'Subject' => 'Deal Not Done Valuation XML',
'Body' => $xmlTemplateDnd
));
#-> Log notification entry.
$em = \Utility\Registry::getEntityManager();
$log = new \Utility\Entity\NotificationLog();
$logData = array(
'emailTo' => 'dm1408082@highergear.net',
'emailSubject' => 'Deal Not Done Valuation XML',
'emailBody' => $xmlTemplateDnd,
'smsTo' => '',
'smsBody' => '',
'apiMsgId' => ''
);
$log->fromArray($logData);
$em->persist($log);
$em->flush();
$log = new \Utility\Entity\NotificationLog();
$logData = array(
'emailTo' => 'b4c@nirph.com',
'emailSubject' => 'Deal Not Done Valuation XML',
'emailBody' => $xmlTemplateDnd,
'smsTo' => '',
'smsBody' => '',
'apiMsgId' => ''
);
$log->fromArray($logData);
$em->persist($log);
$em->flush();
}
//Write hit to Stats logs (need stock or valuation stock id and profile id)
$today = new \DateTime();
//$test = "123";
//\Utility\Debug::errorLog('dealNotDone new', $test);
$em = \Utility\Registry::getEntityManager();
$loghit = new \Statistical\Entity\Statistical();
$loghitData = array(
'stock' => $em->getRepository('\Stock\Entity\Stock')->find($valuation->stock->id),
'dealdone' => false,
'dealnotdone' => true,
'tradecentre' => false,
'fromProfile' => $em->getRepository('\User\Entity\Profile')->find($valuation->stock->createdBy->id),
'created' => $today
);
$loghit->fromArray($loghitData);
$em->persist($loghit);
$em->flush();
if ('Price Guide' == $valuation->jobState)
{
$this->workflowNode->handover('Price Guide', $valuation->id);
$workflow = \Utility\Registry::getServiceManager()
->get('PriceGuide');
$priceGuide = $this->em->getRepository('\PriceGuide\Entity\PriceGuide')
->findOneBy(array('valuation' => $valuation->id), array('id' => 'DESC'));
$workflow->loadJob($priceGuide->id);
$workflow->changeState('This.Archived');
$this->em->createQuery(
'UPDATE \PriceGuide\Entity\Offer o '
. "SET o.status = 'Archived' "
. 'WHERE IDENTITY(o.priceGuideStock) = '
. $priceGuide->id
. ' AND o.status != \'Archived\''
)
->execute();
}
return 'This.Archived';
}
/**
* Route item that is received back from Price Guide Workflow.
* @param \Valuation\Entity\Valuation $valuation
* @param string $previousState
* @param array|null $routingData
* @return string
*/
public function routePriceGuideHandover(\Valuation\Entity\Valuation $valuation, $previousState, $routingData)
{
return $valuation->previousState != 'New Valuation'
? 'This.' . str_replace(' ', '', $valuation->previousState)
: 'This.PendingValuation';
}
/**
* Route item to Offer Accepted status.
*
* @param \Valuation\Entity\Valuation $valuation
* @param string|null $previousState
* @return string
*/
public function directRouteMoveToOfferAccepted(\Valuation\Entity\Valuation $valuation, $previousState)
{
#-> Set price guide entry to accepted.
$priceGuide = $valuation->stock->priceGuide;
$wPriceGuide = \Utility\Registry::getServiceManager()->get('PriceGuide');
$oPriceGuide = new \Valuation\Service\Valuation();
$oPriceGuide->setWorkflow($wPriceGuide);
$wPriceGuide->loadJob($priceGuide->id);
$wPriceGuide->changeState('This.OfferAccepted');
#-> Locate relevant Offer.
$result = $this->em->createQuery(
'SELECT offer, company, profile '
. 'FROM \PriceGuide\Entity\Offer offer '
. 'JOIN offer.company company '
. 'JOIN offer.profile profile '
. 'WHERE IDENTITY(offer.priceGuideStock) = :priceGuideId'
. ' AND offer.amount = :highestOffer '
. 'ORDER BY offer.created ASC'
)
->setParameter('priceGuideId', $priceGuide->id)
->setParameter('highestOffer', $valuation->stock->highestOffer)
->getResult();
#-> Set offer as accepted and send notification.
if (0 < count($result))
{
$item = array_shift($result);
$item->status = 'Offer Accepted';
$this->em->flush($item);
$hours = \Utility\Definitions\Locale::getPriceGuideOpenDays();
$hoursRemaining = floor((($item->created->getTimestamp() + (3600 * $hours)) - time()) / 3600);
$params = array(
'firstName' => $item->profile->firstName,
'familyName' => $item->profile->familyName,
'highestOfferAmount' => 'R' . $item->amount,
'dealershipName' => $priceGuide->company->name,
'registeredName' => $priceGuide->company->name,
'contactPerson' => $priceGuide->company->contact->firstName
. ' ' . $priceGuide->company->contact->familyName,
'contactNumber' => $priceGuide->company->contact->mobile,
'contactEmail' => $priceGuide->company->contact->email,
'year' => $valuation->stock->vehicleYear->name,
'make' => $valuation->stock->type->model->make->name,
'model' => $valuation->stock->type->model->name,
'type' => $valuation->stock->type->name,
'trade' => 'Trade price: R' . $valuation->stock->tradePrice,
'retail' => 'Retail price: R' . $valuation->stock->retailPrice,
'list' => 'List price: R' . $valuation->stock->listPrice,
'registrationNumber' => $valuation->stock->registrationNumber,
'daysRemaining' => '0 days, ' . $hoursRemaining . ' hours',
'referenceNumber' => $valuation->stock->referenceNumber
);
$auth = \Utility\Registry::getAuthData();
$oNotify = new \Utility\Comms\Notification();
// Send to Trader whose offer was accepted.
$oNotify->sendFromTemplate(
$priceGuide->stock->company->id,
$priceGuide->stock->createdBy->id,
$item->company->id,
$item->profile->id,
$item->profile->email,
null,
'Price Guide Offer Accepted',
'price-guide-offer-accepted',
$params);
// Send to User that accepted the offer.
$params['firstName'] = $auth['firstName'];
$params['familyName'] = $auth['familyName'];
$oNotify->sendFromTemplate(
$priceGuide->stock->company->id,
$priceGuide->stock->createdBy->id,
$item->company->id,
$auth['id'],
$auth['email'],
null,
'Price Guide Offer Accepted',
'price-guide-offer-accepted',
$params);
// Send to B4C admin.
$params['firstName'] = $item->profile->firstName;
$params['familyName'] = $item->profile->familyName;
$oNotify->sendFromTemplate(
$priceGuide->stock->company->id,
$priceGuide->stock->createdBy->id,
null,
null,
'info@bid4cars.co.za',
null,
'Price Guide Offer Accepted',
'price-guide-offer-accepted',
$params);
}
#-> Notify other bidders.
$params = array(
'year' => $valuation->stock->vehicleYear->name,
'make' => $valuation->stock->type->model->make->name,
'model' => $valuation->stock->type->model->name,
'type' => $valuation->stock->type->name,
'regNo' => $valuation->stock->registrationNumber,
'referenceNumber' => $valuation->stock->referenceNumber
);
$result = $this->em->createQuery(
'SELECT offer, company, profile '
. 'FROM \PriceGuide\Entity\Offer offer '
. 'JOIN offer.company company '
. 'JOIN offer.profile profile '
. 'WHERE IDENTITY(offer.priceGuideStock) = :priceGuideId '
. 'ORDER BY offer.created ASC'
)
->setParameter('priceGuideId', $priceGuide->id)
->getResult();
foreach ($result as $offer)
{
if ($item->id == $offer->id)
{
continue;
}
$offer->status = 'Expired';
$this->em->flush();
$params['firstName'] = $offer->profile->firstName;
$params['familyName'] = $offer->profile->familyName;
$params['offerAmount'] = 'R' . $offer->amount;
$oNotify->sendFromTemplate(
$priceGuide->stock->company->id,
$priceGuide->stock->createdBy->id,
$offer->company->id,
$offer->profile->id,
$offer->profile->email,
null, null,
'price-guide-offer-declined',
$params
);
}
\Utility\Debug::errorLog('take this to stock ', $valuation->stock->id);
return 'This.Stock';
}
/**
* Route item to Stock status.
*
* @param \Valuation\Entity\Valuation $valuation
* @param string|null $previousState
* @return string
*/
public function directRouteMoveToKeepForStock(\Valuation\Entity\Valuation $valuation, $previousState)
{
//Write hit to Stats logs (need stock or valuation stock id and profile id)
$today = new \DateTime();
//$test = "123";
//\Utility\Debug::errorLog('directRouteMoveToKeepForStock new', $test);
$em = \Utility\Registry::getEntityManager();
$loghit = new \Statistical\Entity\Statistical();
$loghitData = array(
'stock' => $em->getRepository('\Stock\Entity\Stock')->find($valuation->stock->id),
'dealdone' => true,
'dealnotdone' => false,
'tradecentre' => false,
'fromProfile' => $em->getRepository('\User\Entity\Profile')->find($valuation->stock->createdBy->id),
'created' => $today
);
$loghit->fromArray($loghitData);
$em->persist($loghit);
$em->flush();
#-> Get price guide entry.
$priceGuide = $valuation->stock->priceGuide;
#-> Locate relevant Offer.
$result = $this->em->createQuery(
'SELECT offer, company, profile '
. 'FROM \PriceGuide\Entity\Offer offer '
. 'JOIN offer.company company '
. 'JOIN offer.profile profile '
. 'WHERE IDENTITY(offer.priceGuideStock) = :priceGuideId'
. ' AND offer.amount = :highestOffer '
. 'ORDER BY offer.created ASC'
)
->setParameter('priceGuideId', $priceGuide->id)
->setParameter('highestOffer', $valuation->stock->highestOffer)
->getResult();
#-> Send notification.
if (0 < count($result))
{
$item = array_shift($result);
$oNotify = new \Utility\Comms\Notification();
$oNotify->sendFromTemplate(
$priceGuide->stock->company->id,
$priceGuide->stock->createdBy->id,
$item->company->id,
$item->profile->id,
$item->profile->email,
null,
'Vehicle retained for stock',
'price-guide-keep-stock',
array(
'firstName' => $item->profile->firstName,
'familyName' => $item->profile->familyName,
'highestOfferAmount' => 'R' . $item->amount,
'dealershipName' => $priceGuide->company->name,
'year' => $valuation->stock->vehicleYear->name,
'make' => $valuation->stock->type->model->make->name,
'model' => $valuation->stock->type->model->name,
'type' => $valuation->stock->type->name,
'trade' => 'Trade price: R' . $valuation->stock->tradePrice,
'retail' => 'Retail price: R' . $valuation->stock->retailPrice,
'list' => 'List price: R' . $valuation->stock->listPrice,
'registrationNumber' => $valuation->stock->registrationNumber,
'referenceNumber' => $valuation->stock->referenceNumber
));
}
#-> Notify other bidders.
$params = array(
'year' => $valuation->stock->vehicleYear->name,
'make' => $valuation->stock->type->model->make->name,
'model' => $valuation->stock->type->model->name,
'type' => $valuation->stock->type->name,
'regNo' => $valuation->stock->registrationNumber,
'referenceNumber' => $valuation->stock->referenceNumber
);
$result = $this->em->createQuery(
'SELECT offer, company, profile '
. 'FROM \PriceGuide\Entity\Offer offer '
. 'JOIN offer.company company '
. 'JOIN offer.profile profile '
. 'WHERE IDENTITY(offer.priceGuideStock) = :priceGuideId '
. 'ORDER BY offer.created ASC'
)
->setParameter('priceGuideId', $priceGuide->id)
->getResult();
foreach ($result as $offer)
{
$offer->status = 'Expired';
$this->em->flush();
if ($item->id == $offer->id)
{
continue;
}
$params['firstName'] = $offer->profile->firstName;
$params['familyName'] = $offer->profile->familyName;
$params['offerAmount'] = 'R' . $offer->amount;
$oNotify->sendFromTemplate(
$priceGuide->stock->company->id,
$priceGuide->stock->createdBy->id,
$offer->company->id,
$offer->profile->id,
$offer->profile->email,
null, null,
'price-guide-offer-declined',
$params
);
}
return 'Stock.Handover';
}
/**
* Route item that is received back from Price Guide Workflow.
* @param \Valuation\Entity\Valuation $valuation
* @param string $previousState
*/
public function directRouteMoveToArchive(\Valuation\Entity\Valuation $valuation, $previousState)
{
$userId = \Utility\Registry::isAuthenticated()
? \Utility\Registry::getAuthParam('id')
: 0;
exec("php /var/www/B4C2/public/index.php valuation change 3 " . $valuation->id . " $userId > /dev/null &");
return 'This.Archived';
}
/**
* Route item that is received back from Price Guide Workflow.
* @param \Valuation\Entity\Valuation $valuation
* @param string $previousState
*/
public function directRouteUnArchive(\Valuation\Entity\Valuation $valuation, $previousState)
{
$userId = \Utility\Registry::isAuthenticated()
? \Utility\Registry::getAuthParam('id')
: 0;
exec("php /var/www/B4C2/public/index.php valuation change 1 " . $valuation->id . " $userId > /dev/null &");
return 'This.' . str_replace(' ', '', $valuation->previousState);
}
/**
* ExecuteAfter: CreateNew, CreatePending, CreateComplete, CreatePriceGuide, CreateStock.
* Set the valuation link on stock item.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function setStockLink($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
!is_null($jobRecord)
? $jobRecord->stock->valuation = $jobRecord
: $record->stock->valuation = $record;
$this->em->flush();
// do a check here for input
$record = $record
? $record
: $jobRecord;
// valuation = $record, stock = $record->stock->refNum
if (!\Utility\Registry::isAuthenticated())
{
// set valuations flag to is-public true
$record->isPublic = true;
$this->em->flush($record);
}
}
/**
* ExecuteAfter: CreateNew, CreatePending, CreateComplete, CreatePriceGuide, CreateStock.
* Set the valuation link on stock item.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function setStockLinkCustomer($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
!is_null($jobRecord)
? $jobRecord->stock->valuation = $jobRecord
: $record->stock->valuation = $record;
$this->em->flush();
// do a check here for input
$record = $record
? $record
: $jobRecord;
// valuation = $record, stock = $record->stock->refNum
if (!\Utility\Registry::isAuthenticated())
{
// set valuations flag to is-public-customer true
$record->isPublicCustomer = true;
$this->em->flush($record);
// error_log($record->id);
// error_log($record->isPublicCustomer);
// error_log($record->stock->id);
$customerPublicValuationEntry = $this->em->getRepository('\\Valuation\\Entity\\CustomerPublicValuation')
->findOneBy(array(
'valuation' => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
'stock' => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
'archived' => false
));
if(empty($customerPublicValuationEntry))
{
$customerPublicValuationEntry = new \Valuation\Entity\CustomerPublicValuation();
}
$custHash = md5($record->id . $record->stock->id . date('Y-m-d H:i'));
$customerPublicValuationArray = array(
'valuation' => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
'stock' => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
'customerHash' => $custHash
);
try{
$customerPublicValuationEntry->fromArray($customerPublicValuationArray);
$this->em->persist($customerPublicValuationEntry);
$this->em->flush();
}
catch (\Exception $e)
{
error_log('Could not insert customer valuation hash.
' . $e);
}
}
}
/**
* ExecuteAfter: CreateComplete, RouteMoveToComplete.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function sendToSales($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
$record = !is_null($record)
? $record
: $jobRecord;
if ($record->isPublic)
{
// remove +27 and add 0 -> +2711xxxx becomes 011xxx
$mobileNumber = $record->mobile;
$mobileNumFormat = substr($mobileNumber, 3);
$mobileNumFormat = 0 . $mobileNumFormat;
// Removed - keep for refrence
/* ' . $record->street . '
' . $citynew . '
' . $record->region->name . '
dm105171@highergear.net
*/
/* xml template */
$xmlTemplate = '
2013-07-10 19:52:42.38
' . $record->stock->vehicleYear->name . '
' . $record->stock->type->model->make->name . '
' . $record->stock->type->model->name . '
' . $record->stock->km . '
' . $record->stock->type->doors . '
' . $record->stock->transmissionType->name . '
' . $record->stock->vinNumber . '
' . $record->stock->stockNumber . '
' . $record->stock->exteriorColour->name . '
' . $record->stock->interiorColour->name . '
' . $record->firstName . '
' . $record->familyName . '
' . $mobileNumFormat . '
' . $mobileNumFormat . '
' . $record->email . '
' . $record->stock->valuation->requiredPrice . '
' . $record->stock->valuation->amountOffered . '
' . $record->amountOffered . '
99999
bid4cars.co.za
unknown
dm705161@highergear.net
' . $record->stock->company->name . '
';
$mailer = new \Utility\Comms\Email();
$mailer->send(array(
'From' => \Utility\Registry::getConfigParam('sourceEmailAddress'),
'To' => 'dm705161@highergear.net',
'Subject' => 'New Public Valuation XML',
'Body' => $xmlTemplate
));
$mailer = new \Utility\Comms\Email();
$mailer->send(array(
'From' => \Utility\Registry::getConfigParam('sourceEmailAddress'),
'To' => 'b4c@nirph.com',
'Subject' => 'New Public Valuation XML',
'Body' => $xmlTemplate
));
#-> Log notification entry.
$em = \Utility\Registry::getEntityManager();
$log = new \Utility\Entity\NotificationLog();
$logData = array(
'emailTo' => 'dm705161@highergear.net',
'emailSubject' => 'New Public Valuation XML',
'emailBody' => $xmlTemplate,
'smsTo' => '',
'smsBody' => '',
'apiMsgId' => ''
);
$log->fromArray($logData);
$em->persist($log);
$em->flush();
$log = new \Utility\Entity\NotificationLog();
$logData = array(
'emailTo' => 'b4c@nirph.com',
'emailSubject' => 'New Public Valuation XML',
'emailBody' => $xmlTemplate,
'smsTo' => '',
'smsBody' => '',
'apiMsgId' => ''
);
$log->fromArray($logData);
$em->persist($log);
$em->flush();
}
if (0.0 < $record->requiredPrice && is_null($record->tradeRetailRequested))
{
$record->tradeRetailRequested = true;
$this->em->flush($record);
$data = \Utility\Comms\TransUnion::searchByMmCode(
$record->stock->type->mmCode,
$record->stock->vehicleYear->name
);
if (is_array($data) && isset($data['VehicleDetails'])
&& isset($data['VehicleDetails'][0])
&& isset($data['VehicleDetails'][0]['Value'])
&& isset($data['VehicleDetails'][0]['Value']['RetailPrice'])
&& isset($data['VehicleDetails'][0]['Value']['TradePrice'])
&& isset($data['VehicleDetails'][0]['Value']['ListPrice'])
)
{
$record->stock->retailPrice = $data['VehicleDetails'][0]['Value']['RetailPrice'];
$record->stock->tradePrice = $data['VehicleDetails'][0]['Value']['TradePrice'];
$record->stock->listPrice = $data['VehicleDetails'][0]['Value']['ListPrice'];
$this->em->flush($record->stock);
}
}
$salesProfileId = $contract->data->Valuation['salesProfile'];
$amountOffered = $contract->data->Valuation['amountOffered'];
$salesComments = isset($contract->data->Valuation['salesComments'])
? $contract->data->Valuation['salesComments']
: '';
$record->managerProfile = $this->em->getReference(
'\User\Entity\Profile', \Utility\Registry::getAuthParam('id')
);
if ('Price Guide' == $record->jobState)
{
$record->previousState = 'Complete Valuation';
}
$this->em->flush();
/*
* Get data ready for notifcation
*/
$tmpRecord = null == $jobRecord ? $record->toArray() : $jobRecord->toArray();
$record = null == $jobRecord ? $record : $jobRecord;
/*
* Get sales person data
*/
$em = \Utility\Registry::getEntityManager();
$salesPerson = $em->getRepository('\User\Entity\Profile')->find($salesProfileId);
$toProfileId = $salesProfileId;
$toCompanyId = $salesPerson->company->id;
$email = $salesPerson->email;
$mobile = $salesPerson->mobile;
$subject = null;
$templateName = 'valuation-completed';
/*
* Get vehicle data
*/
$type = $record->stock->type;
if (is_null($type))
{
$make = 'N/A';
$model = 'N/A';
$type = 'N/A';
}
$make = $type->model->make->name;
$model = $type->model->name;
$type = $type->name;
/*
* Get auth data
*/
$authData = \Utility\Registry::getAuthData();
$fromCompanyId = isset($authData['company']['id']) ? $authData['company']['id'] : null;
$fromProfileId = isset($authData['id']) ? $authData['id'] : null;
/*
* Set template parameters
*/
$params = array();
$params['firstName'] = (string)$salesPerson->firstName;
$params['familyName'] = (string)$salesPerson->familyName;
$params['customer.name'] = $tmpRecord['firstName'];
$params['customer.familyName'] = $tmpRecord['familyName'];
$params['dateCreated'] = date('Y-m-d H:i');
$params['refNo'] = (string)$record->stock->referenceNumber;
$params['valNo'] = (string)$tmpRecord['valuationNumber'];
$params['year'] = (string)$record->stock->vehicleYear->name;
$params['make'] = $make;
$params['model'] = $model;
$params['type'] = $type;
$params['regNo'] = (string)$record->stock->registrationNumber;
$params['salesComments'] = $record->salesComments;
/*
* Attach PDF
*/
$pdf = new \Valuation\Pdf\Pdf002();
$pdf->process(array(
'jobRecord' => $record
), array());
$writer = new \Utility\Export\PdfTemplate($pdf);
$attachments = array($record->valuationNumber . '.pdf' => $writer->output(''));
$oNotify = new \Utility\Comms\Notification();
$oNotify->sendFromTemplate(
$fromCompanyId, $fromProfileId,
$toCompanyId, $toProfileId,
$email, null,
$subject,
$templateName,
$params,
$attachments
);
if (!is_null($record->xmlRpcClient)
&& $record->xmlRpcClient->triggerSentToSales
)
{
exec("php /var/www/B4C2/public/index.php xmlrpc sentToSales "
. $record->id
. " >>/log/php.log &");
}
}
/**
* ExecuteAfter: CreateNew.
* Add item to queue for mobile.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function sendToMobileQueue($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
if (isset($contract->data->Valuation['valuators'])
&& !empty($contract->data->Valuation['valuators'])
)
{
$this->update(
!is_null($jobRecord)
? $jobRecord->id
: $record->id, array('queueStatus' => 1)
);
}
}
/**
* ExecuteAfter: CreateNew, Update.
* Send sms notifications to selected valuators for new item to valuate.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function sendToValuators($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
$record = !is_null($record)
? $record
: $jobRecord;
$record->queueStatus = 1;
$this->em->flush();
if (0.0 < $record->requiredPrice && is_null($record->tradeRetailRequested))
{
$record->tradeRetailRequested = true;
$this->em->flush($record);
$data = \Utility\Comms\TransUnion::searchByMmCode(
$record->stock->type->mmCode,
$record->stock->vehicleYear->name
);
if (is_array($data) && isset($data['VehicleDetails'])
&& isset($data['VehicleDetails'][0])
&& isset($data['VehicleDetails'][0]['Value'])
&& isset($data['VehicleDetails'][0]['Value']['RetailPrice'])
&& isset($data['VehicleDetails'][0]['Value']['TradePrice'])
&& isset($data['VehicleDetails'][0]['Value']['ListPrice'])
)
{
$record->stock->retailPrice = $data['VehicleDetails'][0]['Value']['RetailPrice'];
$record->stock->tradePrice = $data['VehicleDetails'][0]['Value']['TradePrice'];
$record->stock->listPrice = $data['VehicleDetails'][0]['Value']['ListPrice'];
$this->em->flush($record->stock);
}
}
if (isset($contract->data->Valuation['valuators'])
&& !empty($contract->data->Valuation['valuators'])
)
{
$record = !is_null($record)
? $record
: $jobRecord;
$stock = null == $jobRecord ? $record->stock : $jobRecord->stock;
$record = null == $jobRecord ? $record->toArray() : $jobRecord->toArray();
$params = array();
if (\Utility\Registry::get('IsDeviceApiCall', false))
{
$fromCompanyId = $stock->company->id;
$fromProfileId = $stock->createdBy->id;
$params['firstName'] = $stock->createdBy->firstName;
$params['familyName'] = $stock->createdBy->familyName;
}
else
{
$authData = \Utility\Registry::getAuthData();
$fromCompanyId = isset($authData['company']['id']) ? $authData['company']['id'] : null;
$fromProfileId = isset($authData['id']) ? $authData['id'] : null;
$params['firstName'] = $authData['firstName'];
$params['familyName'] = $authData['familyName'];
}
$params['customer_name'] = $record['firstName'];
$params['customer_family_name'] = $record['familyName'];
$params['vehicle_reg'] = is_null($stock->registrationNumber)
? ' '
: $stock->registrationNumber;
for ($i = 0; $i < count($contract->data->Valuation['valuators']); $i++)
{
$valuator = $this->em->getRepository('\User\Entity\Profile')
->find($contract->data->Valuation['valuators'][$i]);
$valuator = $valuator->toArray();
$toCompanyId = $fromCompanyId;
$toProfileId = $valuator['id'];
$email = null;
$mobile = $valuator['mobile'];
$subject = null;
$templateName = 'valuation-mobile-new';
$oNotify = new \Utility\Comms\Notification();
$oNotify->sendFromTemplate(
$fromCompanyId, $fromProfileId,
$toCompanyId, $toProfileId,
$email, $mobile,
$subject,
$templateName,
$params
);
}
}
}
/**
* ExecuteAfter: SendToPriceGuide.
* Populate correct createdBy in case of public submission.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function checkCreatedBy($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
$record = !is_null($record)
? $record
: $jobRecord;
// Route to the Main Member Public Centre (profile) chosen by Region
if ($record->isPublic && !\Utility\Registry::isAuthenticated() && isset($contract->data->Stock['publicCentre']))
{
$publicCentre = $contract->data->Stock['publicCentre'];
$company = $this->em->getReference('\Company\Entity\Company', $publicCentre);
$record->stock->company = $company;
/* $profile = $this->em->getRepository('User\Entity\Profile')
->findOneBy(array(
'company' => $publicCentre,
'mainMemberPublicCentre' => 1
));
if (!is_null($profile))
{
$record->stock->createdBy = $profile;
$record->createdBy = $profile;
} */
$record->sighted = false;
$record->licenseDiscExpired = false;
$this->em->flush($record);
}
if ($record->isPublic && \Utility\Registry::isAuthenticated())
{
$record->createdBy = $this->em->getReference('\User\Entity\Profile', \Utility\Registry::getAuthParam('id'));
$this->em->flush($record);
}
if (isset($contract->data->Valuation['requiredPrice'])
&& is_numeric($contract->data->Valuation['requiredPrice'])
&& 0.0 < $contract->data->Valuation['requiredPrice']
)
{
if (is_null($record->tradeRetailRequested)
&& \Utility\Registry::isAuthenticated()
)
{
$record->tradeRetailRequested = true;
$this->em->flush($record);
$data = \Utility\Comms\TransUnion::searchByMmCode(
$record->stock->type->mmCode,
$record->stock->vehicleYear->name
);
if (is_array($data) && isset($data['VehicleDetails'])
&& isset($data['VehicleDetails'][0])
&& isset($data['VehicleDetails'][0]['Value'])
&& isset($data['VehicleDetails'][0]['Value']['RetailPrice'])
&& isset($data['VehicleDetails'][0]['Value']['TradePrice'])
&& isset($data['VehicleDetails'][0]['Value']['ListPrice'])
)
{
$record->stock->retailPrice = $data['VehicleDetails'][0]['Value']['RetailPrice'];
$record->stock->tradePrice = $data['VehicleDetails'][0]['Value']['TradePrice'];
$record->stock->listPrice = $data['VehicleDetails'][0]['Value']['ListPrice'];
$this->em->flush($record->stock);
}
}
if (!\Utility\Registry::isAuthenticated())
{
$stock = null == $jobRecord ? $record->stock : $jobRecord->stock;
$record = null == $jobRecord ? $record->toArray() : $jobRecord->toArray();
$fromCompanyId = null;
$fromProfileId = null;
//\Utility\Debug::errorLog('$stock->vehicleYear', $stock->vehicleYear->name);
$params = array();
$params['first_name'] = $record['firstName'];
$params['family_name'] = $record['familyName'];
$params['year'] = $stock->vehicleYear->name;
$params['make'] = $stock->type->model->make->name;
$params['model'] = $stock->type->model->name;
$params['type'] = $stock->type->name;
$params['reg_no'] = is_null($stock->registrationNumber)
? ''
: $stock->registrationNumber;
$oNotify = new \Utility\Comms\Notification();
$oNotify->sendFromTemplate(
null, null,
null, null,
$record['email'], null,
'Notification of successful submission of vehicle',
'public-submission',
$params
);
// Removed info@ to 'mohau@bid4cars.co.za', and 'dineo@bid4cars.co.za'
$oNotify->sendFromTemplate(
null, null,
null, null,
'mohau@bid4cars.co.za', null,
'Notification of successful submission of vehicle',
'public-submission',
$params
);
$oNotify->sendFromTemplate(
null, null,
null, null,
'dineo@bid4cars.co.za', null,
'Notification of successful submission of vehicle',
'public-submission',
$params
);
}
}
}
/**
* ExecuteAfter: CreatePending, CreateComplete, CreatePriceGuide, CreateStock.
* Set the valuator from session authentication data.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function setValuatorFromAuth($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
!is_null($record)
? $record->valuatedBy = $this->em->getReference(
'\User\Entity\Profile', \Utility\Registry::getAuthParam('id')
)
: $jobRecord->valuatedBy = $this->em->getReference(
'\User\Entity\Profile', \Utility\Registry::getAuthParam('id')
);
$this->em->flush();
}
/**
* ExecuteAfter: CreateComplete, RouteMoveToComplete.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function setPreviousStateToComplete($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
$jobRecord->previousState = 'Complete Valuation';
$this->em->flush($jobRecord);
$record = null == $jobRecord
? $record->toArray()
: $jobRecord->toArray();
$valuationId = $record['id'];
$result = $this->em->createQuery(
'SELECT valuations, st '
. 'FROM \Valuation\Entity\Valuation valuations '
. 'JOIN valuations.stock st '
. 'WHERE valuations.id = :ValuationID '
)
->setParameter('ValuationID', $valuationId)
->getArrayResult();
$StockID = $result[0]['stock']['id'];
}
/**
* ConditionalContract: Update.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Contract\AbstractBase $contract
* @return array
*/
public function noEditOnPgItemWithOffers($meta, $jobRecord, $record, \Workspace\Contract\AbstractBase $contract)
{
if ('Price Guide' == $jobRecord->jobState
&& 0 < $jobRecord->stock->numberOfOffers
)
{
throw new \Exception('Valuation in status Price Guide with offers may not be edited.');
}
}
public function generateHistoryList($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
$record = null == $jobRecord
? $record->toArray()
: $jobRecord->toArray();
$valuationId = $record['id'];
$result = $this->em->createQuery(
'SELECT valuations, st '
. 'FROM \Valuation\Entity\Valuation valuations '
. 'JOIN valuations.stock st '
. 'WHERE valuations.id = :ValuationID '
)
->setParameter('ValuationID', $valuationId)
->getArrayResult();
#-> Clear any existing history for this vehicle.
$StockID = $result[0]['stock']['id'];
$this->em->createQuery(
'DELETE FROM \Stock\Entity\PricingHistory pricingHistory '
. 'WHERE pricingHistory.stockId = '
. $StockID
)
->execute();
$result = $this->em->createQuery(
'SELECT stock, st, vy '
. 'FROM \Stock\Entity\Stock stock '
. 'LEFT JOIN stock.type st '
. 'LEFT JOIN stock.vehicleYear vy '
. 'WHERE stock.id = :StockID '
)
->setParameter('StockID', $StockID)
->getArrayResult();
$stockTypeID = $result[0]['type']['id'];
$vehicleYearID = $result[0]['vehicleYear']['id'];
$today = new \DateTime();
$dateFrom = clone $today;
$dateFrom->modify('-3 months');
$result = $this->em->createQuery(
'SELECT stock, priceguide, auction, st, po, cb, bids '
. 'FROM \Stock\Entity\Stock stock '
. 'LEFT JOIN stock.priceGuide priceguide WITH priceguide.created BETWEEN :dateFrom AND :dateTo '
. 'LEFT JOIN stock.auction auction WITH auction.created BETWEEN :dateFrom AND :dateTo '
. 'LEFT JOIN stock.type st '
. 'LEFT JOIN priceguide.offers po '
. 'LEFT JOIN auction.currentBid cb '
. 'LEFT JOIN auction.bids bids '
. 'WHERE st.id = :stockTypeID '
. 'AND IDENTITY(stock.vehicleYear) = :vehicleYearID '
. 'AND (stock.highestBid > 0 OR stock.highestOffer > 0) '
. 'AND stock.archived = 0 '
. 'ORDER by auction.created, priceguide.created ASC '
)
->setParameter('stockTypeID', $stockTypeID)
->setParameter('vehicleYearID', $vehicleYearID)
->setParameter('dateFrom', $dateFrom)
->setParameter('dateTo', $today)
->getArrayResult();
$i = 0;
$x = 0;
$existing = array();
foreach ($result as $pricingHistory)
{
$StockDamageTotal = $pricingHistory['damageTotal'];
$StockTradePrice = $pricingHistory['tradePrice'];
$StockListPrice = $pricingHistory['listPrice'];
$StockKMS = $pricingHistory['km'];
if ($StockKMS == '' || is_null($StockKMS))
{
$StockKMS = 0;
}
// price guide
$PriceguideHighestOffer = $pricingHistory['highestOffer'];
// Auction
$highestBid = $pricingHistory['highestBid'];
// Priceguide && Auction
if ($PriceguideHighestOffer != 0 && $highestBid != 0)
{
$priceGuideOffers = $pricingHistory['priceGuide']['offers'];
if (is_array($priceGuideOffers))
{
$highestAmnt = 0.0;
foreach ($priceGuideOffers as $priceGuideOffer)
{
if ($priceGuideOffer['amount'] > $highestAmnt)
{
$highestAmnt = $priceGuideOffer['amount'];
$priceGuideOffersCreatedDate = $priceGuideOffer['created'];
}
}
$data = array(
'date' => $priceGuideOffersCreatedDate,
'trade' => $StockTradePrice,
'listPrice' => $StockListPrice,
'totalRecon' => $StockDamageTotal,
'km' => $StockKMS,
'pricegOffer' => $PriceguideHighestOffer,
'auctionWinningBid' => $highestBid,
'stockId' => $StockID
);
$hash = md5(serialize($data));
if (!isset($existing[$hash]))
{
$existing[$hash] = true;
$entry = new \Stock\Entity\PricingHistory();
$entry->fromArray($data);
$this->em->persist($entry);
$this->em->flush($entry);
$x++;
}
}
}
// Price Guide only
if ($PriceguideHighestOffer != 0 && $highestBid == 0)
{
$priceGuideOffers = $pricingHistory['priceGuide']['offers'];
if (is_array($priceGuideOffers))
{
$highestAmnt = 0.0;
foreach ($priceGuideOffers as $priceGuideOffer)
{
if ($priceGuideOffer['amount'] > $highestAmnt)
{
$highestAmnt = $priceGuideOffer['amount'];
$priceGuideOffersCreatedDate = $priceGuideOffer['created'];
}
}
$data = array(
'date' => $priceGuideOffersCreatedDate, // changes all the time
'trade' => $StockTradePrice,
'listPrice' => $StockListPrice,
'totalRecon' => $StockDamageTotal,
'km' => $StockKMS,
'pricegOffer' => $PriceguideHighestOffer,
'auctionWinningBid' => 0.0,
'stockId' => $StockID
);
$hash = md5(serialize($data));
if (!isset($existing[$hash]))
{
$existing[$hash] = true;
$entry = new \Stock\Entity\PricingHistory();
$entry->fromArray($data);
$this->em->persist($entry);
$this->em->flush($entry);
$x++;
}
}
}
// Auction only
if ($PriceguideHighestOffer == 0 && $highestBid != 0)
{
$date = $pricingHistory['auction']['created'];
$data = array(
'date' => $date, // changes all the time
'trade' => $StockTradePrice,
'listPrice' => $StockListPrice,
'totalRecon' => $StockDamageTotal,
'km' => $StockKMS,
'pricegOffer' => 0.0,
'auctionWinningBid' => $highestBid,
'stockId' => $StockID
);
$hash = md5(serialize($data));
if (!isset($existing[$hash]))
{
$existing[$hash] = true;
$entry = new \Stock\Entity\PricingHistory();
$entry->fromArray($data);
$this->em->persist($entry);
$this->em->flush($entry);
$x++;
}
}
if ($x > 10)
{
break;
}
}
}
/**
* Contract to use current highest price guide offer.
* @param object|null $jobRecord
* @param array $input
* @return \Workspace\Contract\UseOnce
*/
public function contractUseOffer($jobRecord, array $input = array())
{
$options = new \Workspace\UseCase\Options();
$requirement = new \Workspace\UseCase\Requirement();
$requirement->addRequiredInput(array(
'Valuation' => array(
'id' => 'Id'
)
));
return new \Workspace\Contract\UseOnce($options, $requirement);
}
/**
* Use current highest price guide offer
* @param object|null $jobRecord
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function executeUseOffer($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
{
#-> Do we have an existing offer in use?
$existingOffer = $this->em->getRepository('PriceGuide\Entity\Offer')
->findOneBy(array(
'priceGuideStock' => $jobRecord->stock->priceGuide->id,
'status' => 'Offer in Use'
));
if (is_object($existingOffer))
{
#-> Have existing offer, change status of offer back to Updateable Offer.
$existingOffer->status = 'Updateable Offer';
$this->em->flush($existingOffer);
}
else
{
$existingOffer = false;
}
#-> Get the new highest offer.
$highestOffer = $this->em->getRepository('PriceGuide\Entity\Offer')
->findOneBy(array(
'priceGuideStock' => $jobRecord->stock->priceGuide->id,
'status' => 'Updateable Offer'
),
array(
'amount' => 'DESC',
'created' => 'ASC'
));
if ($existingOffer && $existingOffer->id == $highestOffer->id)
{
$existingOffer = false;
}
$highestOffer->status = 'Offer in Use';
$this->em->flush($highestOffer);
#-> Notify owner of offer now in use.
$auth = \Utility\Registry::getAuthData();
$oNotify = new \Utility\Comms\Notification();
$params = array(
'firstName' => $highestOffer->profile->firstName,
'familyName' => $highestOffer->profile->familyName,
'offerAmount' => $highestOffer->amount,
'year' => $jobRecord->stock->vehicleYear->name,
'make' => $jobRecord->stock->type->model->make->name,
'model' => $jobRecord->stock->type->model->name,
'type' => $jobRecord->stock->type->name,
'regNo' => $jobRecord->stock->registrationNumber,
'referenceNumber' => $jobRecord->stock->referenceNumber
);
$oNotify->sendFromTemplate(
$jobRecord->stock->company->id, $auth['id'],
$highestOffer->company->id, $highestOffer->profile->id,
$highestOffer->profile->email, null, null,
'price-guide-offer-used',
$params
);
#-> Notify authed user of offer now in use.
$params['firstName'] = $auth['firstName'];
$params['familyName'] = $auth['familyName'];
$oNotify->sendFromTemplate(
$jobRecord->stock->company->id, $auth['id'],
$jobRecord->stock->company->id, $auth['id'],
$auth['email'], null, null,
'price-guide-offer-used',
$params
);
#-> Notify authed user & owner of previous offer used that it is no longer in use.
if ($existingOffer)
{
$params['firstName'] = $highestOffer->profile->firstName;
$params['familyName'] = $highestOffer->profile->familyName;
$params['offerAmount'] = $existingOffer->amount;
$oNotify->sendFromTemplate(
$jobRecord->stock->company->id, $auth['id'],
$highestOffer->company->id, $highestOffer->profile->id,
$highestOffer->profile->email, null, null,
'price-guide-offer-dropped',
$params
);
$params['firstName'] = $auth['firstName'];
$params['familyName'] = $auth['familyName'];
$oNotify->sendFromTemplate(
$jobRecord->stock->company->id, $auth['id'],
$jobRecord->stock->company->id, $auth['id'],
$auth['email'], null, null,
'price-guide-offer-dropped',
$params
);
}
return $contract->success('Current Highest Offer is now in use.', array());
}
public function updateCustomVehicles($meta, $jobRecord, $contract, $data)
{
$contract->data = $this->addCustomVehicles($meta, $contract->data);
return $contract->data;
}
/**
* ExecuteBefore: Create
* @param array $meta
* @param array $data
*/
public function addCustomVehicles($meta, $data)
{
#-> Check if we have a custom vehicle
//\Utility\Debug::errorLog('Stock manualy added on before exe', $data->Stock);
if ($data->Stock['category'] == '8')
{
#-> Get latest version.
$versions = $this->em->createQuery(
'SELECT MAX(vehicleType.createVersion) AS createVersion,'
. ' MAX(vehicleType.updateVersion) AS updateVersion '
. 'FROM Stock\\Entity\\Type vehicleType'
)
->getScalarResult();
$newVersion = $versions[0]['createVersion'] > $versions[0]['updateVersion']
? $versions[0]['createVersion'] + 1
: $versions[0]['updateVersion'] + 1;
#-> Create make, model, type entries
$makeManual = $data->Stock['makeManual'];
$modelManual = $data->Stock['modelManual'];
$typeManual = $data->Stock['typeManual'];
$category = $data->Stock['category'];
$today = new \DateTime();
$em = \Utility\Registry::getEntityManager();
// Make
// Do a check if this make exists
if ('' != $makeManual && $makeManual != $data->Stock['make'])
{
$make = $em->getRepository('\Stock\Entity\Make')
->findOneBy(array(
'name' => $makeManual
));
if (is_null($make))
{
// Else add Make Manual
$make = new \Stock\Entity\Make();
$makeData = array(
'name' => $makeManual,
'created' => $today,
'createVersion' => $newVersion
);
$make->fromArray($makeData);
$em->persist($make);
$em->flush();
}
// get make id back
$makeId = $make->id;
}
else
{
$makeId = $data->Stock['make'];
}
// Model
if ('' != $modelManual && $modelManual != $data->Stock['model'])
{
// Do a check if this model exists
$model = $em->getRepository('\Stock\Entity\Model')
->findOneBy(array(
'make' => $makeId,
'name' => $makeManual
));
if (is_null($model))
{
// Add Model Manual
$model = new \Stock\Entity\Model();
$modelData = array(
'make' => $em->getRepository('\Stock\Entity\Make')->find($makeId),
'name' => $modelManual,
'created' => $today,
'createVersion' => $newVersion
);
$model->fromArray($modelData);
$em->persist($model);
$em->flush();
}
//get model id back
$modelId = $model->id;
}
else
{
$modelId = $data->Stock['model'];
}
// Type
if ('' != $typeManual && $typeManual != $data->Stock['type'])
{
// Do a check if this type exists
$type = $em->getRepository('\Stock\Entity\Type')
->findOneBy(array(
'model' => $modelId,
'category' => $category,
'name' => $typeManual
));
if (is_null($type))
{
// Add Type Manual
$type = new \Stock\Entity\Type();
$typeData = array(
'model' => $em->getRepository('\Stock\Entity\Model')->find($modelId),
'category' => $em->getRepository('\Stock\Entity\Category')->find($category),
'name' => $typeManual,
'mmCode' => 'other',
'introYear' => $em->getRepository('\Stock\Entity\Year')->find(1),
'introMonth' => '1',
'created' => $today,
'createVersion' => $newVersion
);
$type->fromArray($typeData);
$em->persist($type);
$em->flush();
}
//get model id back
$typeId = $type->id;
#-> Update data with new ids
$data->Stock['type'] = $typeId;
}
}
return $data;
}
/**
* ExecuteAfter: Create
* @param array $meta
* @param array $data
*/
public function sendEmailToValuator($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
// error_log('sendEmailToValuator');
// do a check here for input
$record = $record
? $record
: $jobRecord;
// \Utility\Debug::errorLog('$record', $record->id);
$profileEntry = $this->em->getRepository('\\User\\Entity\\Profile')
->findBy(array(
'company' => $record->stock->company->id,
'permissions' => '7',
'archived' => 0
));
if(!is_null($profileEntry))
{
foreach ($profileEntry as $profile)
{
// \Utility\Debug::errorLog('$profile', $profile->id);
$toCompanyId = $record->stock->company->id;
$toProfileId = $profile->id;
$email = $profile->email;
$mobile = null;
$subject = "Public Valuation for " . $record->firstName . " " . $record->familyName;
$templateName = 'public-general';
$params['body'] = '
A new public valuation request has been submitted, please log into Bid4Cars to view the valuation:
|
';
$params['body'] .= $record->stock->registrationNumber;
$params['body'] .= ' |
';
$params['body'] .= $record->stock->vehicleYear->name;
$params['body'] .= ' |
';
$params['body'] .= $record->stock->type->model->make->name;
$params['body'] .= ' |
';
$params['body'] .= $record->stock->type->model->name;
$params['body'] .= ' |
';
$params['body'] .= $record->stock->type->name;
$params['body'] .= ' |
';
$params['smsBody'] = '';
// error_log('email body');
// error_log($params['body']);
$oNotify = new \Utility\Comms\Notification();
$oNotify->sendFromTemplate(
null,
null,
$toCompanyId,
$toProfileId,
$email,
$mobile,
$subject,
$templateName,
$params
);
}
}
}
/**
* ExecuteAfter: Create
* @param array $meta
* @param array $data
*/
public function sendPublicCustomerEmail($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
// error_log('sendPublicCustomerEmail');
is_null($jobRecord)
? $jobRecord->stock->valuation = $jobRecord
: $record->stock->valuation = $record;
$this->em->flush();
// do a check here for input
$record = $record
? $record
: $jobRecord;
$record->valuatedBy = isset($authData['id']) ? $authData['id'] : null;
$this->em->flush($record);
// // valuation = $record, stock = $record->stock->refNum
//
// if (!\Utility\Registry::isAuthenticated())
// {
// // set valuations flag to is-public true
// $record->isPublic = true;
// $this->em->flush($record);
// }
$customerPublicValuationEntry = $this->em->getRepository('\\Valuation\\Entity\\CustomerPublicValuation')
->findOneBy(array(
'valuation' => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
'stock' => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
'archived' => false
));
$fromCompanyId = isset($authData['company']['id']) ? $authData['company']['id'] : null;
$fromProfileId = isset($authData['id']) ? $authData['id'] : null;
$toCompanyId = $fromCompanyId;
$toProfileId = $record->valuatedBy;
$email = $record->email;
$mobile = null;
$subject = "Valuation for " . $record->firstName . " " . $record->familyName;
$templateName = 'public-general';
$params['body'] = '
Good Day ' . $record->firstName . ' ' . $record->familyName . ',
|
|
Thank you for making use of amountOffered . '
|
';
$params['smsBody'] = '';
// error_log('email body');
// error_log($params['body']);
$oNotify = new \Utility\Comms\Notification();
$oNotify->sendFromTemplate(
$fromCompanyId,
$fromProfileId,
$toCompanyId,
$toProfileId,
$email,
$mobile,
$subject,
$templateName,
$params
);
}
/**
* ExecuteAfter: Create
* @param array $meta
* @param array $data
*/
public function setAppointmentData($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
// error_log('setAppointmentData');
// is_null($jobRecord)
// ? $jobRecord->stock->valuation = $jobRecord
// : $record->stock->valuation = $record;
// $this->em->flush();
// do a check here for input
$record = $record
? $record
: $jobRecord;
// \Utility\Debug::errorLog('$contract', $contract->data->Valuation);
// [valuatorSelected] => 561
// [dateSelected] => 2015-09-24
// [timeIdSelected] => 5
$valuationAppointmentsEntry = $this->em->getRepository('\\Valuation\\Entity\\ValuationAppointments')
->findOneBy(array(
'valuation' => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
'valuator' => $this->em->getReference('\\User\Entity\Profile', $contract->data->Valuation['valuatorSelected']),
'timeSlot' => $this->em->getReference('\\Valuation\Entity\ValuationTimeSlots', $contract->data->Valuation['timeIdSelected']),
'appointmentDate' => new \DateTime($contract->data->Valuation['dateSelected']),
'archived' => false
));
if(is_null($valuationAppointmentsEntry) && empty($valuationAppointmentsEntry))
{
$valuationAppointmentsEntry = new \Valuation\Entity\ValuationAppointments();
}
$valuationAppointmentsData = array(
'valuation' => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
'valuator' => $this->em->getReference('\\User\Entity\Profile', $contract->data->Valuation['valuatorSelected']),
'timeSlot' => $this->em->getReference('\\Valuation\Entity\ValuationTimeSlots', $contract->data->Valuation['timeIdSelected']),
'appointmentDate' => new \DateTime($contract->data->Valuation['dateSelected'])
);
$valuationAppointmentsEntry->fromArray($valuationAppointmentsData);
$this->em->persist($valuationAppointmentsEntry);
$this->em->flush();
$record->valuatedBy = isset($authData['id']) ? $authData['id'] : null;
$this->em->flush($record);
// // valuation = $record, stock = $record->stock->refNum
//
// if (!\Utility\Registry::isAuthenticated())
// {
// // set valuations flag to is-public true
// $record->isPublic = true;
// $this->em->flush($record);
// }
$customerPublicValuationEntry = $this->em->getRepository('\\Valuation\\Entity\\CustomerPublicValuation')
->findOneBy(array(
'valuation' => $this->em->getReference('\\Valuation\Entity\Valuation', $record->id),
'stock' => $this->em->getReference('\\Stock\Entity\Stock', $record->stock->id),
'archived' => false
));
// \Utility\Debug::errorLog('$valuationAppointmentsEntry->appointmentDate', $valuationAppointmentsEntry->appointmentDate);
$appointmentDate = new \DateTime($valuationAppointmentsEntry->appointmentDate->date);
$fromCompanyId = isset($authData['company']['id']) ? $authData['company']['id'] : null;
$fromProfileId = isset($authData['id']) ? $authData['id'] : null;
$toCompanyId = $fromCompanyId;
$toProfileId = $record->valuatedBy;
$email = $record->email;
$mobile = null;
$subject = "Notification of successful submission of vehicle";
$templateName = 'public-general';
// \Utility\Debug::errorLog('$record->id', $record->id);
// \Utility\Debug::errorLog('$record->stock->id', $record->stock->id);
// \Utility\Debug::errorLog('$record->stock->type->id', $record->stock->type->id);
// \Utility\Debug::errorLog('$record->stock->type->name', $record->stock->type->name);
// \Utility\Debug::errorLog('$record->stock->type->model->name', $record->stock->type->model->name);
// \Utility\Debug::errorLog('$record->stock->type->model->make->name', $record->stock->type->model->make->name);
$params['body'] = '
Good Day ' . $record->firstName . ' ' . $record->familyName . ',
|
|
We would like to confirm that the following vehicle was successfully submitted to WePay4Cars for valuation.
|
|
|
Year:
|
' . $record->stock->vehicleYear->name . '
|
|
|
Make:
|
' . $record->stock->type->model->make->name . '
|
|
|
Model:
|
' . $record->stock->type->model->name . '
|
|
|
Type:
|
' . $record->stock->type->name . '
|
|
|
Reg no:
|
' . $record->stock->registrationNumber . '
|
|
|
Please note that the price offered on your vehicle is subject to final viewing.
|
Your booking for valuation will take place at:
|
|
';
$params['body'] .= $record->stock->company->name . ' ( ' . null != $record->stock->company->contact->office ? null != $record->stock->company->contact->office : $record->stock->company->contact->mobile . ' ) ';
$params['body'] .= ' |
|
Date / Time:
|
' . $appointmentDate->format('Y-m-d') . '
|
' . $valuationAppointmentsEntry->timeSlot->timeSlotDisplayName . '
|
|
Your Address:
|
' . $record->customerAddressStreet . '
|
' . $record->customerAddressStreetName . '
|
' . $record->customerAddressSuburb . '
|
' . $record->customerAddressCity . '
|
' . $record->customerAddressPostalCode . '
|
|
Email:
|
' . $record->email . '
|
';
$params['smsBody'] = '';
// error_log('email body');
// error_log($params['body']);
$oNotify = new \Utility\Comms\Notification();
$oNotify->sendFromTemplate(
$fromCompanyId,
$fromProfileId,
$toCompanyId,
$toProfileId,
$email,
$mobile,
$subject,
$templateName,
$params
);
// //Dealership manager (or default contact for the dealer on the B4C system)
// if(!empty($record->stock->company->contact->email) && null != $record->stock->company->contact->email)
// {
// $oNotify = new \Utility\Comms\Notification();
// $oNotify->sendFromTemplate(
// $fromCompanyId,
// $fromProfileId,
// $toCompanyId,
// $toProfileId,
// $record->stock->company->contact->email,
// null,
// $subject,
// $templateName,
// $params
// );
// }
//
//
// //Valuator
// if(!empty($record->valuatedBy) && null != $record->valuatedBy)
// {
// $oNotify = new \Utility\Comms\Notification();
// $oNotify->sendFromTemplate(
// $fromCompanyId,
// $fromProfileId,
// $toCompanyId,
// $toProfileId,
// $record->valuatedBy->email,
// null,
// $subject,
// $templateName,
// $params
// );
// }
}
/**
* ExecuteAfter: Create.
* Push change to mobile devices.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function pushCreateAction($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
//-- Pass to backend function so we don't hold up the user response.
$userId = \Utility\Registry::isAuthenticated()
? \Utility\Registry::getAuthParam('id')
: 0;
exec("php /var/www/B4C2/public/index.php valuation change 1 " . $record->id . " $userId > /dev/null &");
}
/**
* ExecuteAfter: Update.
* Push change to mobile devices.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function pushUpdateAction($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
//-- Pass to backend function so we don't hold up the user response.
$userId = \Utility\Registry::isAuthenticated()
? \Utility\Registry::getAuthParam('id')
: 0;
exec("php /var/www/B4C2/public/index.php valuation change 2 " . $record->id . " $userId > /dev/null &");
}
/**
* ExecuteAfter: Delete.
* Push change to mobile devices.
* @param array $meta
* @param object|null $jobRecord
* @param object|null $record
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function pushDeleteAction($meta, $jobRecord, $record, \Workspace\Utility\ServiceInputParams $contract)
{
//-- Pass to backend function so we don't hold up the user response.
$userId = \Utility\Registry::isAuthenticated()
? \Utility\Registry::getAuthParam('id')
: 0;
exec("php /var/www/B4C2/public/index.php valuation change 3 " . $record->id . " $userId > /dev/null &");
}
/**
* Push change notifications for stock item change.
* @param $changeCode
* @param $id
* @param $skipId
*/
public function pushChange($changeCode, $id, $skipId)
{
//-- Safety check.
$valuation = $this->em->find('Valuation\\Entity\\Valuation', $id);
$minDate = new \DateTime('last month');
if ($minDate->getTimestamp() > $valuation->stock->created->getTimestamp()
|| 8 == $valuation->stock->type->category->id
)
{
//-- Nothing to do, old record.
return;
}
//-- Send it to relevant people.
$registrations = $this->em->getRepository('Company\\Entity\\DeviceRegistration')
->findBy(
array(
'company' => $valuation->stock->company->id
)
);
$ids = array();
foreach ($registrations as $registration)
{
if (/*$registration->profile->id != $skipId
&& */0 < strlen($registration->device->registrationId)
)
{
$ids[] = $registration->device->registrationId;
}
}
\Utility\Comms\Gcm::send(
$ids,
array(
'changeCode' => (int) $changeCode,
'changeId' => (int) $valuation->stock->uvi
)
);
}
/**
* Contract to list vehicle types according to Category and Year.
* @param object|null $jobRecord
* @param array $input
* @return \Workspace\Contract\UseOnce
*/
public function contractDealNotDoneSelection($jobRecord, array $input = array())
{
$options = new \Workspace\UseCase\Options();
$requirement = new \Workspace\UseCase\Requirement();
return new \Workspace\Contract\Recurring($options, $requirement);
}
/**
* List vehicle types according to Category and Year.
* @param object|null $jobRecord
* @param \Workspace\Utility\ServiceInputParams $contract
* @return array
*/
public function executeDealNotDoneSelection($jobRecord, \Workspace\Utility\ServiceInputParams $contract)
{
$dql = 'SELECT dnds.id as value,dnds.name as label '
. 'FROM \Valuation\Entity\DealNotDoneSelection dnds '
. ' GROUP BY dnds.name'
. ' ORDER BY dnds.id';
$dataGet = $this->em->createQuery($dql)
->getArrayResult();
// \Utility\Debug::errorLog("dataGet", $dataGet);
$data = array();
foreach($dataGet as $dataProcess)
{
array_push($data,array(
'value' => $dataProcess['value'],
'label' => $dataProcess['label']
));
}
return $contract->success('Data Collected.', $data);
}
}