Refactor customer form and fix bugs

This commit is contained in:
Kendrick Chan 2018-02-02 02:48:00 +08:00
parent fc4cb9ba7f
commit ddb642a95f
3 changed files with 156 additions and 159 deletions

View file

@ -6,6 +6,8 @@ use App\Ramcar\BaseController;
use App\Ramcar\CustomerClassification; use App\Ramcar\CustomerClassification;
use App\Ramcar\FuelType; use App\Ramcar\FuelType;
use App\Ramcar\VehicleStatusCondition; use App\Ramcar\VehicleStatusCondition;
use App\Ramcar\CrudException;
use App\Entity\Customer; use App\Entity\Customer;
use App\Entity\CustomerVehicle; use App\Entity\CustomerVehicle;
use App\Entity\MobileNumber; use App\Entity\MobileNumber;
@ -339,118 +341,36 @@ class CustomerController extends BaseController
return $this->render('customer/form.html.twig', $params); return $this->render('customer/form.html.twig', $params);
} }
public function updateSubmit(Request $req, ValidatorInterface $validator, $id) protected function updateVehicles($em, Customer $cust, $vehicles)
{ {
$this->denyAccessUnlessGranted('customer.update', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(Customer::class)->find($id);
// make sure this row exists
if (empty($row))
throw $this->createNotFoundException('The item does not exist');
// set and save values
$row->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setCustomerClassification($req->request->get('customer_classification'))
->setCustomerNotes($req->request->get('customer_notes'));
// initialize error lists
$error_array = [];
$nerror_array = [];
$verror_array = [];
// initialize child id lists
$number_ids = [];
$vehicle_ids = []; $vehicle_ids = [];
// custom validation for mobile numbers foreach ($vehicles as $vehicle)
$numbers = json_decode($req->request->get('mobile_numbers'));
if (!empty($numbers)) {
foreach ($numbers as $key => $number) {
// check if number exists
$mobile_number = $em->getRepository(MobileNumber::class)->find($number->id);
// this is a new number
if (empty($mobile_number)) {
$mobile_number = new MobileNumber();
$mobile_number->setID($number->id)
->setDateRegistered(DateTime::createFromFormat("d M Y - h:i A", $number->date_registered))
->setCustomer($row);
if (!empty($number->date_confirmed)) {
$mobile_number->setDateConfirmed(DateTime::createFromFormat("d M Y - h:i A", $number->date_confirmed))
->setConfirmed();
} else {
$mobile_number->setConfirmed(false);
}
$nerrors = $validator->validate($mobile_number);
// add errors to list
foreach ($nerrors as $error) {
if (!isset($nerror_array[$key]))
$nerror_array[$key] = [];
$nerror_array[$key][$error->getPropertyPath()] = $error->getMessage();
}
if (!isset($nerror_array[$key])) {
$row->addMobileNumber($mobile_number);
}
}
// add to list of numbers to keep
$number_ids[] = $mobile_number->getID();
}
}
// delete all numbers not in list
if (count($number_ids) > 0)
{ {
$qb = $em->createQueryBuilder();
$del_numbers = $qb->select('m')
->from(MobileNumber::class, 'm')
->where($qb->expr()->notIn('m.id', $number_ids))
->getQuery()
->getResult();
if (!empty($del_numbers)) {
foreach ($del_numbers as $dn) {
$em->remove($dn);
}
}
}
// custom validation for vehicles
$vehicles = json_decode($req->request->get('vehicles'));
if (!empty($vehicles)) {
foreach ($vehicles as $vehicle) {
$cust_vehicle = false;
$is_new_vehicle = false;
// check if customer vehicle exists // check if customer vehicle exists
if (!empty($vehicle->id)) { if (!empty($vehicle->id))
{
$cust_vehicle = $em->getRepository(CustomerVehicle::class)->find($vehicle->id); $cust_vehicle = $em->getRepository(CustomerVehicle::class)->find($vehicle->id);
} if ($cust_vehicle == null)
throw new CrudException("Could not find customer vehicle.");
}
// this is a new vehicle // this is a new vehicle
if (empty($cust_vehicle)) { else
{
$cust_vehicle = new CustomerVehicle(); $cust_vehicle = new CustomerVehicle();
$cust_vehicle->setCustomer($row); $cust_vehicle->setCustomer($cust);
$is_new_vehicle = true; $cust->addVehicle($cust_vehicle);
$em->persist($cust_vehicle);
} }
// check if vehicle exists // vehicle, because they could have changed vehicle type
$vobj = $em->getRepository(Vehicle::class)->find($vehicle->vehicle); $vobj = $em->getRepository(Vehicle::class)->find($vehicle->vehicle);
if ($vobj == null)
throw new CrudException("Could not find vehicle.");
// TODO: validate details
if (empty($vobj)) {
$verror_array[$vehicle->index]['vehicle'] = 'Invalid vehicle specified.';
} else {
$cust_vehicle->setName($vehicle->name) $cust_vehicle->setName($vehicle->name)
->setVehicle($vobj) ->setVehicle($vobj)
->setPlateNumber($vehicle->plate_number) ->setPlateNumber($vehicle->plate_number)
@ -461,13 +381,13 @@ class CustomerController extends BaseController
->setActive($vehicle->flag_active); ->setActive($vehicle->flag_active);
// if specified, check if battery exists // if specified, check if battery exists
if ($vehicle->battery) { if ($vehicle->battery)
{
// check if battery exists // check if battery exists
$bobj = $em->getRepository(Battery::class)->find($vehicle->battery); $bobj = $em->getRepository(Battery::class)->find($vehicle->battery);
if ($bobj == null)
throw new CrudException("Could not find battery.");
if (empty($bobj)) {
$verror_array[$vehicle->index]['battery'] = 'Invalid battery specified.';
} else {
// check if warranty expiration was specified // check if warranty expiration was specified
$warr_ex = DateTime::createFromFormat("d M Y", $vehicle->warranty_expiration); $warr_ex = DateTime::createFromFormat("d M Y", $vehicle->warranty_expiration);
if (!$warr_ex) if (!$warr_ex)
@ -478,57 +398,125 @@ class CustomerController extends BaseController
->setWarrantyCode($vehicle->warranty_code) ->setWarrantyCode($vehicle->warranty_code)
->setWarrantyExpiration($warr_ex); ->setWarrantyExpiration($warr_ex);
} }
} else { else
{
$cust_vehicle->setHasMotoliteBattery(false); $cust_vehicle->setHasMotoliteBattery(false);
} }
$verrors = $validator->validate($cust_vehicle);
// add errors to list
foreach ($verrors as $error) {
if (!isset($verror_array[$vehicle->index]))
$verror_array[$vehicle->index] = [];
$verror_array[$vehicle->index][$error->getPropertyPath()] = $error->getMessage();
}
if (!isset($verror_array[$vehicle->index]) && $is_new_vehicle) {
$row->addVehicle($cust_vehicle);
}
// add to list of vehicles to keep // add to list of vehicles to keep
$vehicle_ids[] = $cust_vehicle->getID(); $vehicle_ids[$cust_vehicle->getID()] = true;
}
}
} }
// cleanup
if (count($vehicle_ids) > 0) if (count($vehicle_ids) > 0)
{ {
// delete all vehicles not in list // delete all vehicles not in list
$qb = $em->createQueryBuilder(); $cvs = $cust->getVehicles();
$del_vehicles = $qb->select('cv') foreach ($cvs as $cv)
->from(CustomerVehicle::class, 'cv') {
->where($qb->expr()->notIn('cv.id', $vehicle_ids)) if (!isset($vehicle_ids[$cv->getID()]))
->getQuery() $em->remove($cv);
->getResult(); }
}
}
if (!empty($del_vehicles)) { public function updateNumbers($em, Customer $cust, $numbers)
foreach ($del_vehicles as $dv) { {
$em->remove($dv); $number_ids = [];
foreach ($numbers as $key => $number)
{
// check if number exists
$mobile_number = $em->getRepository(MobileNumber::class)->find($number->id);
// this is a new number
if (empty($mobile_number))
{
$mobile_number = new MobileNumber();
$mobile_number->setID($number->id)
->setDateRegistered(DateTime::createFromFormat("d M Y - h:i A", $number->date_registered))
->setCustomer($cust);
if (!empty($number->date_confirmed))
{
$mobile_number->setDateConfirmed(DateTime::createFromFormat("d M Y - h:i A", $number->date_confirmed))
->setConfirmed();
}
else
{
$mobile_number->setConfirmed(false);
}
if (!isset($nerror_array[$key]))
{
$cust->addMobileNumber($mobile_number);
}
}
// add to list of numbers to keep
$number_ids[] = $mobile_number->getID();
}
// cleanup
if (count($number_ids) > 0)
{
// delete all not in list
$mns = $cust->getMobileNumbers();
foreach ($mns as $mn)
{
if (!isset($number_ids[$mn->getID()]))
$em->remove($mn);
} }
} }
} }
public function updateSubmit(Request $req, ValidatorInterface $validator, $id)
{
$this->denyAccessUnlessGranted('customer.update', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$cust = $em->getRepository(Customer::class)->find($id);
// make sure this row exists
if (empty($cust))
throw $this->createNotFoundException('The item does not exist');
// set and save values
$cust->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setCustomerClassification($req->request->get('customer_classification'))
->setCustomerNotes($req->request->get('customer_notes'));
// initialize error lists
$error_array = [];
$nerror_array = [];
$verror_array = [];
// TODO: validate mobile numbers
// TODO: validate vehicles
// custom validation for mobile numbers
$numbers = json_decode($req->request->get('mobile_numbers'));
$this->updateNumbers($em, $cust, $numbers);
// custom validation for vehicles
$vehicles = json_decode($req->request->get('vehicles'));
$this->updateVehicles($em, $cust, $vehicles);
// validate // validate
$errors = $validator->validate($row); $errors = $validator->validate($cust);
// add errors to list // add errors to list
foreach ($errors as $error) { foreach ($errors as $error)
{
$error_array[$error->getPropertyPath()] = $error->getMessage(); $error_array[$error->getPropertyPath()] = $error->getMessage();
} }
// check if any errors were found // check if any errors were found
if (!empty($error_array) || !empty($nerror_array) || !empty($verror_array)) { if (!empty($error_array) || !empty($nerror_array) || !empty($verror_array))
{
// return validation failure response // return validation failure response
return $this->json([ return $this->json([
'success' => false, 'success' => false,
@ -536,9 +524,11 @@ class CustomerController extends BaseController
'nerrors' => $nerror_array, 'nerrors' => $nerror_array,
'verrors' => $verror_array 'verrors' => $verror_array
], 422); ], 422);
} else { }
else
{
// validated! save the entity. do a persist anyway to save child entities // validated! save the entity. do a persist anyway to save child entities
$em->persist($row); $em->persist($cust);
$em->flush(); $em->flush();
// return successful response // return successful response

View file

@ -0,0 +1,7 @@
<?php
namespace App\Ramcar;
class CrudException extends \Exception
{
}

View file

@ -86,7 +86,7 @@
<label data-field="customer_notes"> <label data-field="customer_notes">
Customer Notes Customer Notes
</label> </label>
<textarea name="customer_notes" class="form-control m-input" value="{{ obj.getCustomerNotes() }}" data-name="customer_notes" rows="4"></textarea> <textarea name="customer_notes" class="form-control m-input" data-name="customer_notes" rows="4">{{ obj.getCustomerNotes() }}</textarea>
<div class="form-control-feedback hide" data-field="customer_notes"></div> <div class="form-control-feedback hide" data-field="customer_notes"></div>
</div> </div>
</div> </div>