resq/src/Controller/CustomerAppAPI/WarrantyController.php
2023-04-12 22:52:27 +08:00

614 lines
22 KiB
PHP

<?php
namespace App\Controller\CustomerAppAPI;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use Catalyst\ApiBundle\Component\Response as ApiResponse;
use App\Entity\Warranty;
use App\Entity\WarrantySerial;
use App\Entity\SAPBattery;
use App\Entity\CustomerVehicle;
use App\Service\WarrantyRaffleLogger;
use App\Service\WarrantyAPILogger;
use App\Service\RisingTideGateway;
use App\Ramcar\WarrantySource;
use DateTime;
class WarrantyController extends ApiController
{
public function activateWarranty(Request $req)
{
// validate params
$validity = $this->validateRequest($req, [
'plate_number',
]);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
$plate_number = $req->request->get('plate_number');
// find warranty using plate number
$warranty_results = $this->em->getRepository(Warranty::class)->findBy(
['plate_number' => $plate_number],
['date_create' => 'desc']
);
// check if warranty_results is empty
if (empty($warranty_results)) {
return new ApiResponse(false, 'No warranty found for plate number.');
}
// activate all entries
foreach ($warranty_results as $warranty) {
$warranty->setActivated();
}
$this->em->flush();
// response
return new ApiResponse();
}
public function warrantyCheck($serial, Request $req, WarrantyRaffleLogger $raffle_logger)
{
// validate params
$validity = $this->validateRequest($req);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
// check if warranty serial is there
$serial = $this->cleanSerial($serial);
$warr_serial = $this->em->getRepository(WarrantySerial::class)->find($serial);
$warr = $this->em->getRepository(Warranty::class)->findOneBy(['serial' => $serial]);
$batt = null;
$is_registered = false;
if ($warr_serial == null) {
return new ApiResponse(false, 'Invalid warranty serial code.');
}
$today = new DateTime();
$user_id = $req->query->get('session_key');
$raffle_data = [
'user_id' => $user_id,
'serial' => $serial,
'warranty_id' => null,
'action' => '',
'bmodel_name' => '',
'bsize_name' => '',
'first_name' => '',
'last_name' => '',
'plate_number' => '',
'contact_num' => '',
'email' => '',
'address' => '',
];
$data_sent = [];
// if we have a warranty entry for the serial already
if ($warr != null) {
$warr_plate = $warr->getPlateNumber();
$is_registered = true;
$is_customer_warranty = false;
// check if the warranty is registered to a car owned by the customer
$cust = $this->session->getCustomer();
$is_customer_warranty = $this->checkCustomerPlateNumber($warr_plate, $cust);
// null mobile number should be blank string instead
if ($warr->getMobileNumber() == null)
$mobile_num = '';
else
$mobile_num = $warr->getMobileNumber();
$can_edit = $is_customer_warranty;
// if customer plate number matches the one registered on the warranty
if ($is_customer_warranty) {
// purchase date of customer
if ($warr->getDatePurchaseCustomer() != null)
$date_purchase_cust = $warr->getDatePurchaseCustomer()->format('Y-m-d');
else
$date_purchase_cust = $today->format('Y-m-d');
// invoice
if ($warr->getFileInvoice() != null)
$invoice_url = $req->getSchemeAndHttpHost() . '/warranty_uploads/' . $warr->getFileInvoice();
else
$invoice_url = '';
// warranty card
if ($warr->getFileWarrantyCard() != null)
$warr_card_url = $req->getSchemeAndHttpHost() . '/warranty_uploads/' . $warr->getFileWarrantyCard();
else
$warr_card_url = '';
$customer = [
'first_name' => $warr->getFirstName() ?? '',
'last_name' => $warr->getLastName() ?? '',
'mobile_number' => $mobile_num,
'plate_number' => $warr_plate,
'email' => $warr->getEmail() ?? '',
'contact_num' => $warr->getContactNumber() ?? '',
'address' => $warr->getCustomerAddress() ?? '',
];
$other_data = [
'odometer' => (int) $warr->getOdometer() ?? 0,
'date_purchase' => $date_purchase_cust,
'invoice' => $invoice_url,
'warr_card' => $warr_card_url,
'dealer_name' => $warr->getDealerName() ?? '',
'dealer_address' => $warr->getDealerAddress() ?? '',
'branch_code' => $warr->getDealerBranchCode() ?? '',
];
// set customer info and action for raffle log
$raffle_data['action'] = 'serial_check_customer';
$raffle_data['first_name'] = $customer['first_name'];
$raffle_data['last_name'] = $customer['last_name'];
$raffle_data['plate_number'] = $customer['plate_number'];
$raffle_data['email'] = $customer['email'];
$raffle_data['contact_num'] = $customer['contact_num'];
$raffle_data['address'] = $customer['address'];
$raffle_data['warranty_id'] = $warr->getID();
} else {
// hide customer information if customer is not the one registered
$customer = [
'first_name' => '',
'last_name' => '',
'mobile_number' => '',
'plate_number' => '',
'email' => '',
'contact_num' => '',
'address' => '',
];
$other_data = [
'odometer' => 0,
'date_purchase' => $today->format('Y-m-d'),
'invoice' => '',
'warr_card' => '',
'dealer_name' => '',
'dealer_address' => '',
'branch_code' => '',
];
// set action for raffle log
$raffle_data['action'] = 'serial_check_not_customer';
}
} else {
$can_edit = true;
$customer = [
'first_name' => '',
'last_name' => '',
'mobile_number' => '',
'plate_number' => '',
'email' => '',
'contact_num' => '',
'address' => '',
];
$other_data = [
'odometer' => 0,
'date_purchase' => $today->format('Y-m-d'),
'invoice' => '',
'warr_card' => '',
'dealer_name' => '',
'dealer_address' => '',
'branch_code' => '',
];
// set action for raffle log
$raffle_data['action'] = 'serial_check_customer';
}
$sku = $warr_serial->getSKU();
$batt = null;
$cat_name = '';
if ($sku != null)
$batt = $this->em->getRepository(SAPBattery::class)->find($sku);
else {
// get the category name of the serial
$cat_name = $warr_serial->getMetaInfo('category_name');
}
// TODO: put this in a config file
$image_url = $req->getSchemeAndHttpHost() . '/battery/generic.png';
if ($batt != null) {
$battery = [
'brand' => $batt->getBrand()->getName(),
'size' => $batt->getSize()->getName(),
'image_url' => $image_url,
];
} else {
$battery = [
'brand' => $cat_name,
'size' => '',
'image_url' => '',
];
}
// set the rest of the raffle log entry
$raffle_data['bmodel_name'] = $battery['brand'];
$raffle_data['bsize_name'] = $battery['size'];
// log the raffle log
$raffle_logger->logRaffleInfo($data_sent, $raffle_data);
// response
return new ApiResponse(true, '', [
'is_valid' => true,
'is_registered' => $is_registered,
'can_edit' => $can_edit,
'customer' => $customer,
'battery' => $battery,
'odometer' => $other_data['odometer'],
'invoice' => $other_data['invoice'],
'warr_card' => $other_data['warr_card'],
'date_purchase' => $other_data['date_purchase'],
'dealer_name' => $other_data['dealer_name'],
'dealer_address' => $other_data['dealer_address'],
'branch_code' => $other_data['branch_code'],
'message' => [
'register_error' => 'Warranty serial code has already been registered.',
'edit_error' => 'Sorry, warranty is registered under another vehicle not in your list of vehicles.',
],
]);
}
public function warrantyRegister(
$serial,
Request $req,
KernelInterface $kernel,
RisingTideGateway $rt,
TranslatorInterface $trans,
WarrantyRaffleLogger $raffle_logger,
WarrantyAPILogger $logger
) {
// validate params
$validity = $this->validateRequest($req, [
'first_name',
'last_name',
'plate_number',
'date_purchase',
]);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
// handle file uploads
$invoice = $req->files->get('invoice');
$warr_card = $req->files->get('warr_card');
// normalize serial
$serial = $this->cleanSerial($serial);
// $serial = trim(strtoupper($serial));
// process picture uploads
$upload_dir = $kernel->getProjectDir() . '/public/warranty_uploads';
$inv_filename = $this->handlePictureUpload($invoice, $upload_dir, $serial, 'invoice');
$wcard_filename = $this->handlePictureUpload($warr_card, $upload_dir, $serial, 'wcard');
$user_id = $req->query->get('session_key');
$log_data = [
'plate_number' => $req->request->get('plate_num'),
'first_name' => $req->request->get('first_name'),
'last_name' => $req->request->get('last_name'),
'date_purchase' => $req->request->get('date_purchase'),
];
$action = 'create/update';
$source = WarrantySource::MOBILE;
// update customer information
// $cust = $this->updateCustomerInfo($req, $em);
// update warranty
$res = $this->updateWarranty(
$rt,
$trans,
$req,
$serial,
$inv_filename,
$wcard_filename,
$logger,
$log_data,
$user_id,
$action,
$source,
$raffle_logger
);
if (!$res['success']) {
return new ApiResponse(false, $res['error']);
}
$this->em->flush();
return new ApiResponse();
}
protected function handlePictureUpload($file, $target_dir, $serial, $name)
{
// error_log("handling $name upload");
// no file sent
if ($file == null) {
error_log("handling $name upload - no file");
return null;
}
// create target dir if it doesn't exist
if (!file_exists($target_dir)) {
if (!mkdir($target_dir, 0744, true)) {
error_log('failed to create folder for warranty pictures');
return null;
}
}
// move file
$filename = $name . '.' . $file->getClientOriginalExtension();
$file->move($target_dir . '/' . $serial, $filename);
// error_log("filename - $filename");
// error_log($target_dir . '/' . $serial . '/' . $filename);
return $serial . '/' . $filename;
}
// TODO: put this in a service
protected function cleanSerial($serial)
{
// trim and make everything upper case
$clean_serial = trim(strtoupper($serial));
// remove QR prefix if it exists
// $prefix = substr($clean_serial, 0, 2);
// if ($prefix == 'QR')
// $clean_serial = substr($clean_serial, 2);
return $clean_serial;
}
protected function checkCustomerPlateNumber($plate_number, $cust)
{
// strip spaces and make all caps
$plate_number = preg_replace('/\s+/', '', strtoupper($plate_number));
// if there's no customer linked to session
if ($cust != null) {
// check all the customer vehicles
$cvs = $cust->getVehicles();
foreach ($cvs as $cv) {
$cv_plate = preg_replace('/\s+/', '', strtoupper($cv->getPlateNumber()));
// did we find a match?
if ($cv_plate == $plate_number) {
return true;
}
}
}
return false;
}
protected function updateWarranty($rt, $trans, $req, $serial, $inv_filename = null, $wcard_filename = null, $logger, $log_data, $user_id, $action, $source, $raffle_logger)
{
// prepare raffle log entry
$raffle_data = [
'user_id' => $user_id,
'serial' => $serial,
'warranty_id' => null,
'action' => '',
'bmodel_name' => '',
'bsize_name' => '',
'first_name' => '',
'last_name' => '',
'plate_number' => '',
'contact_num' => '',
'email' => '',
'address' => '',
];
// get serial
$warr_serial = $this->em->getRepository(WarrantySerial::class)->find($serial);
if ($warr_serial == null) {
return [
'success' => false,
'error' => 'Invalid warranty serial code.',
];
}
// check if warranty exists already
$warr = $this->em->getRepository(Warranty::class)->findOneBy(['serial' => $serial]);
// skip warranty if it already exists
if ($warr != null) {
/*
// NOTE: we could not update in the old version
$res->setError(true)
->setErrorMessage('Warranty registration entry already exists.');
return $res;
*/
// check if warranty is registered to a serial owned by customer
$warr_plate = $warr->getPlateNumber();
$cust = $this->session->getCustomer();
$is_customer_warranty = $this->checkCustomerPlateNumber($warr_plate, $cust);
if (!$is_customer_warranty) {
$error_msg = 'Warranty registered to a vehicle not in your list of vehicles.';
// set action to update
$action = 'update';
$logger->logWarrantyInfo($log_data, $error_msg, $user_id, $action, $source);
// response
return [
'success' => false,
'error' => $error_msg,
];
}
$sms_msg = $trans->trans('warranty_update_confirm');
// update raffle data action
$raffle_data['action'] = 'warranty_update';
} else {
$warr = new Warranty();
$sms_msg = $trans->trans('warranty_register_confirm');
// set warranty source
$warr->setCreateSource($source);
// update raffle data action
$raffle_data['action'] = 'warranty_create';
}
// get sap battery
$sku = $warr_serial->getSKU();
$sap_bty = null;
if ($sku != null) {
$sap_bty = $this->em->getRepository(SAPBattery::class)->find($sku);
if ($sap_bty == null) {
$error_msg = 'Could not find battery entry for warranty.';
$logger->logWarrantyInfo($log_data, $error_msg, $user_id, $action, $source);
// response
return [
'success' => false,
'error' => $error_msg,
];
}
}
// default date purchase to today
// NOTE: might need to change this later
$date_pur = new DateTime();
// get date purchase specified by customer
$date_pur_cust = DateTime::createFromFormat('Y-m-d', $req->request->get('date_purchase'));
if (!$date_pur_cust) {
$error_msg = 'Invalid date format for date of purchase.';
$logger->logWarrantyInfo($log_data, $error_msg, $user_id, $action, $source);
// response
return [
'success' => false,
'error' => $error_msg,
];
}
$customer = $this->session->getCustomer();
if ($customer != null) {
$warr->setCustomer($customer);
// get customer vehicles
$vehicle = $this->findCustomerVehicle($customer, $req->request->get('plate_number'));
if ($vehicle != null)
$warr->setVehicle($vehicle);
}
// TODO: make a standard clean plate number service
// clean plate number
$plate = $req->request->get('plate_number');
// upper case and remove spaces
$plate = strtoupper(str_replace(' ', '', $plate));
// remove special characters
$plate = preg_replace('/[^A-Za-z0-9. -]/', '', $plate);
// create or update warranty entry
$warr->setSerial($serial)
->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setEmail($req->request->get('email'))
->setPlateNumber($plate)
// TODO: figure out how to compute date of purchase
->setDatePurchase($date_pur)
// TODO: set status
// ->setStatus()
// TODO: set battery model and size id
// ->setBatterySize()
// ->setBatteryModel()
->setSAPBattery($sap_bty)
->setMobileNumber(substr($this->session->getPhoneNumber(), 2))
->setActivated(true)
// files
->setFileInvoice($inv_filename)
->setFileWarrantyCard($wcard_filename)
// new fields
->setOdometer($req->request->get('odometer', 0))
->setDatePurchaseCustomer($date_pur_cust)
->setContactNumber($req->request->get('contact_num'))
->setCustomerAddress($req->request->get('cust_address'))
->setDealerName($req->request->get('dealer_name'))
->setDealerAddress($req->request->get('dealer_address'))
->setDealerBranchCode($req->request->get('branch_code'))
->setValidated(false);
// TODO: check for date purchase and date expire
$this->em->persist($warr);
// TODO: check if we need to do anyting else
$logger->logWarrantyInfo($log_data, '', $user_id, $action, $source);
// send sms
// error_log('sending sms to - ' . $this->session->getPhoneNumber());
$rt->sendSMS($this->session->getPhoneNumber(), $trans->trans('message.battery_brand_allcaps'), $sms_msg);
// prepare the rest of the raffle log entry
$raffle_data['warranty_id'] = $warr->getID();
$raffle_data['bmodel_name'] = $sap_bty->getBrand()->getName();
$raffle_data['bsize_name'] = $sap_bty->getSize()->getName();
$raffle_data['first_name'] = $req->request->get('first_name', '');
$raffle_data['last_name'] = $req->request->get('last_name', '');
$raffle_data['plate_number'] = $plate;
$raffle_data['contact_num'] = $req->request->get('contact_num', '');
$raffle_data['email'] = $req->request->get('email', '');
$raffle_data['address'] = $req->request->get('cust_address', '');
$data_sent = [
'plate_number' => $req->request->get('plate_number'),
'first_name' => $req->request->get('first_name'),
'last_name' => $req->request->get('last_name'),
'date_purchase' => $req->request->get('date_purchase'),
'address' => $req->request->get('cust_address', ''),
'email' => $req->request->get('email', ''),
'contact_num' => $req->request->get('contact_num', ''),
];
// log raffle data
$raffle_logger->logRaffleInfo($data_sent, $raffle_data);
// response
return [
'success' => true,
];
}
protected function findCustomerVehicle($customer, $plate_number)
{
$clean_plate = Warranty::cleanPlateNumber($plate_number);
if ($clean_plate) {
// find the customer vehicle and get the vehicle
$cv = $this->em->getRepository(CustomerVehicle::class)->findOneBy(['plate_number' => $clean_plate, 'customer' => $customer]);
if ($cv != null) {
$vehicle = $cv->getVehicle();
return $vehicle;
}
}
return null;
}
}