Merge branch 'master-fix' of gitlab.com:jankstudio/resq into 575-adopt-hub-filtering-branch

This commit is contained in:
Korina Cordero 2021-06-23 09:42:12 +00:00
commit b4c8da134c
43 changed files with 1621 additions and 196 deletions

View file

@ -81,4 +81,5 @@ API_VERSION=insert_api_version_here
#SSL_ENABLE for websockets #SSL_ENABLE for websockets
SSL_ENABLE=set_to_true_or_false SSL_ENABLE=set_to_true_or_false
# for hub filtering round robin
HUB_JO_KEY=hub_jo_count HUB_JO_KEY=hub_jo_count

View file

@ -502,3 +502,17 @@ access_keys:
label: Update label: Update
- id: customer_tag.delete - id: customer_tag.delete
label: Delete label: Delete
- id: dealer
label: Dealer Access
acls:
- id: dealer.menu
label: Menu
- id: dealer.list
label: List
- id: dealer.add
label: Add
- id: dealer.update
label: Update
- id: dealer.delete
label: Delete

View file

@ -62,3 +62,8 @@ access_keys:
acls: acls:
- id: municipality.list - id: municipality.list
label: List label: List
- id: dealer
label: Dealer
acls:
- id: dealer.list
label: List

View file

@ -110,6 +110,10 @@ main_menu:
acl: hub.menu acl: hub.menu
label: Hub label: Hub
parent: location parent: location
- id: dealer_list
acl: dealer.list
label: Dealer
parent: location
- id: geofence_list - id: geofence_list
acl: geofence.menu acl: geofence.menu
label: Geofence label: Geofence

View file

@ -172,3 +172,9 @@ capi_municipality_list:
path: /capi/municipality path: /capi/municipality
controller: App\Controller\CAPI\MunicipalityController::getAll controller: App\Controller\CAPI\MunicipalityController::getAll
methods: [GET] methods: [GET]
# dealer
capi_dealer_list:
path: /capi/dealers
controller: App\Controller\CAPI\DealerController::getAll
methods: [GET]

33
config/routes/dealer.yaml Normal file
View file

@ -0,0 +1,33 @@
dealer_list:
path: /dealers
controller: App\Controller\DealerController::index
dealer_rows:
path: /dealers/rows
controller: App\Controller\DealerController::rows
methods: [POST]
dealer_create:
path: /dealers/create
controller: App\Controller\DealerController::addForm
methods: [GET]
dealer_create_submit:
path: /dealers/create
controller: App\Controller\DealerController::addSubmit
methods: [POST]
dealer_update:
path: /dealers/{id}
controller: App\Controller\DealerController::updateForm
methods: [GET]
dealer_update_submit:
path: /dealers/{id}
controller: App\Controller\DealerController::updateSubmit
methods: [POST]
dealer_delete:
path: /dealers/{id}
controller: App\Controller\DealerController::destroy
methods: [DELETE]

View file

@ -73,9 +73,9 @@ rep_warranty_details_form:
controller: App\Controller\ReportController::warrantyDetailsForm controller: App\Controller\ReportController::warrantyDetailsForm
methods: [GET] methods: [GET]
rep_warranty_details_export_csv: rep_warranty_details_submit:
path: /report/warranty_details_report path: /report/warranty_details_report
controller: App\Controller\ReportController::warrantyDetailsExportCSV controller: App\Controller\ReportController::warrantyDetailsSubmit
methods: [POST] methods: [POST]
rep_jo_details_form: rep_jo_details_form:

View file

@ -216,7 +216,8 @@ class CreateCustomerFromWarrantyCommand extends Command
$new_cust = new Customer(); $new_cust = new Customer();
$new_cust->setFirstName($w_first_name) $new_cust->setFirstName($w_first_name)
->setLastName($w_last_name) ->setLastName($w_last_name)
->setPhoneMobile($w_mobile_num); ->setPhoneMobile($w_mobile_num)
->setCreateSource('CMB_CreateCustomerFromWarranty');
$this->em->persist($new_cust); $this->em->persist($new_cust);

View file

@ -210,9 +210,10 @@ class GenerateWarrantyFromJobOrderCommand extends Command
$values = '(' . $bty_model_id . ',' . $bty_size_id . ',NULL,\'' . $warranty_class . '\',\'' $values = '(' . $bty_model_id . ',' . $bty_size_id . ',NULL,\'' . $warranty_class . '\',\''
. $cleaned_plate_number . '\',\'' . WarrantyStatus::ACTIVE . '\',\'' . $date_create . '\',\'' . $date_purchase . $cleaned_plate_number . '\',\'' . WarrantyStatus::ACTIVE . '\',\'' . $date_create . '\',\'' . $date_purchase
. '\',\'' . $date_expire . '\',NULL,' . '\',\'' . $date_expire . '\',NULL,'
. $sap_code . ',NULL,\'' . $first_name . '\',\'' . $last_name . '\',\'' . $mobile_number . '\',' . 0 . ',NULL' . ');'; . $sap_code . ',NULL,\'' . $first_name . '\',\'' . $last_name . '\',\'' . $mobile_number . '\',' . 0 . ',NULL,\''
. WarrantySource::COMMAND .'\');';
$sql_statement = 'INSERT INTO `warranty` (bty_model_id,bty_size_id,serial,warranty_class,plate_number,status,date_create,date_purchase,date_expire,date_claim,sap_bty_id,claim_id,first_name,last_name,mobile_number,flag_activated,warranty_privacy_policy) VALUES ' . $values . "\n"; $sql_statement = 'INSERT INTO `warranty` (bty_model_id,bty_size_id,serial,warranty_class,plate_number,status,date_create,date_purchase,date_expire,date_claim,sap_bty_id,claim_id,first_name,last_name,mobile_number,flag_activated,warranty_privacy_policy,create_source) VALUES ' . $values . "\n";
echo $sql_statement; echo $sql_statement;

View file

@ -18,28 +18,11 @@ use App\Entity\CustomerTag;
class ImportCarClubCustomerDataCommand extends Command class ImportCarClubCustomerDataCommand extends Command
{ {
// field index in csv file // field index in csv file
const F_TIMESTAMP = 0; const F_DPA = 0;
const F_DPA = 1; const F_FIRST_NAME = 1;
const F_FIRST_NAME = 2; const F_LAST_NAME = 2;
const F_MIDDLE_NAME = 3; const F_CAR_CLUB = 3;
const F_LAST_NAME = 4; const F_CONTACT_NUM = 4;
const F_BIRTHDATE = 5;
const F_ADDRESS = 6;
const F_CITY = 7;
const F_REGION = 8;
const F_CAR_CLUB = 9;
const F_POSITION = 10;
const F_MEMBER_NUM = 11;
const F_VEHICLE = 12;
const F_VEHICLE_EXCEL = 13;
const F_BATT_SIZE = 14;
const F_REPLACE_SKED = 15;
const F_DEALER_VISIT = 16;
const F_CONTACT_NUM = 17;
const F_BWI_LOCATION = 18;
const F_SAP_CODE = 19;
const F_SKU = 20;
const F_QTY = 21;
protected $em; protected $em;
protected $cust_tag_hash; protected $cust_tag_hash;
@ -145,54 +128,20 @@ class ImportCarClubCustomerDataCommand extends Command
protected function setOutputInfo($fields, $status, $reason, $cust_id) protected function setOutputInfo($fields, $status, $reason, $cust_id)
{ {
$timestamp = trim($fields[self::F_TIMESTAMP]);
$mname = trim($fields[self::F_MIDDLE_NAME]);
$birthdate = trim($fields[self::F_BIRTHDATE]);
$address = trim($fields[self::F_ADDRESS]);
$city = trim($fields[self::F_CITY]);
$region = trim($fields[self::F_REGION]);
$car_club = trim($fields[self::F_CAR_CLUB]); $car_club = trim($fields[self::F_CAR_CLUB]);
$position = trim($fields[self::F_POSITION]);
$member_number = trim($fields[self::F_MEMBER_NUM]);
$vehicle = trim($fields[self::F_VEHICLE]);
$vehicle_excel = trim($fields[self::F_VEHICLE_EXCEL]);
$batt_size = trim($fields[self::F_BATT_SIZE]);
$replace_sked = trim($fields[self::F_REPLACE_SKED]);
$dealer_visit = trim($fields[self::F_DEALER_VISIT]);
$bwi_location = trim($fields[self::F_BWI_LOCATION]);
$sap_code = trim($fields[self::F_SAP_CODE]);
$sku = trim($fields[self::F_SKU]);
$qty = trim($fields[self::F_QTY]);
$fname = trim($fields[self::F_FIRST_NAME]); $fname = trim($fields[self::F_FIRST_NAME]);
$lname = trim($fields[self::F_LAST_NAME]); $lname = trim($fields[self::F_LAST_NAME]);
$dpa = trim($fields[self::F_DPA]); $dpa = trim($fields[self::F_DPA]);
$contact_number = trim($fields[SELF::F_CONTACT_NUM]); $contact_number = trim($fields[SELF::F_CONTACT_NUM]);
return [ return [
$timestamp,
$dpa, $dpa,
$fname, $fname,
$mname,
$lname, $lname,
$birthdate,
$address,
$city,
$region,
$car_club, $car_club,
$position,
$member_number,
$vehicle,
$vehicle_excel,
$batt_size,
$replace_sked,
$dealer_visit,
$contact_number, $contact_number,
$bwi_location, $status,
$sap_code, $reason,
$sku,
$qty,
$status,
$reason,
$cust_id $cust_id
]; ];
} }
@ -237,17 +186,6 @@ class ImportCarClubCustomerDataCommand extends Command
// clean up contact number // clean up contact number
$valid_contact_numbers = $this->getValidContactNumbers($contact_number); $valid_contact_numbers = $this->getValidContactNumbers($contact_number);
// NOTE: commenting this out because we want to add customers without mobile number
/*
// QUESTION: do we need this?
// QUESTION: why are we not adding those without contact numbers? Add customer, leave contact number blank was what was agreed, right?
if (count($valid_contact_numbers) <= 0)
{
// add info to output array
return $this->setOutputInfo($fields, 'NOT CREATED', 'Missing contact number', 0);
}
*/
// check customer tag // check customer tag
$cust_tag = $this->findCustomerTag($car_club); $cust_tag = $this->findCustomerTag($car_club);
$cust_id = ''; $cust_id = '';
@ -310,28 +248,11 @@ class ImportCarClubCustomerDataCommand extends Command
// write the headers // write the headers
fputcsv($fh, [ fputcsv($fh, [
'Timestamp',
'I have read and understood and agreed to the confidentiality of this form request', 'I have read and understood and agreed to the confidentiality of this form request',
'First Name', 'First Name',
'Middle Name',
'Last Name', 'Last Name',
'Birth date',
'Address',
'City',
'Region',
'Car Club/Organization', 'Car Club/Organization',
'Position in the organization',
'Official Member Number (type NA if not applicable)',
'Vehicles you own? Year - Make -Model - Plate/Conduction number (ex 2017 NISSAN NAVARA ABC 1234) you can indicate all your vehicles',
'If your were given a chance to EXperience the New Motolite Excel, Choose 1 vehicle and it\'s plate/conduction number',
'What is the Battery size of the vehicle you with to EXperience the New Motolite Excel',
'Given a specific date, when can you schedule your replacement?',
'Will you be able to visit our dealer that we will assign nearest to you?',
'Contact Number', 'Contact Number',
'BWI LOCATION',
'SAP CODE',
'SKU',
'QTY',
'Status', 'Status',
'Reason', 'Reason',
'Customer ID', 'Customer ID',

View file

@ -418,7 +418,8 @@ class ImportCustomerCommand extends Command
$fields[self::F_OFFICE_PHONE], $fields[self::F_OFFICE_PHONE],
$fields[self::F_FAX], $fields[self::F_FAX],
$fields[self::F_EMAIL], $fields[self::F_EMAIL],
isset($fields[self::F_NOTES]) ? $fields[self::F_NOTES] : '' isset($fields[self::F_NOTES]) ? $fields[self::F_NOTES] : '',
'CMB_ImportCustomerCommand'
]; ];
$cust_row = str_replace('\\', '\\\\', implode('|', $cust_fields)) . "\n"; $cust_row = str_replace('\\', '\\\\', implode('|', $cust_fields)) . "\n";
fputs($cust_file, $cust_row); fputs($cust_file, $cust_row);

View file

@ -30,6 +30,7 @@ use App\Ramcar\AdvanceOrderSlot;
use App\Ramcar\AutoAssignStatus; use App\Ramcar\AutoAssignStatus;
use App\Ramcar\WarrantySource; use App\Ramcar\WarrantySource;
use App\Ramcar\HubCriteria; use App\Ramcar\HubCriteria;
use App\Ramcar\CustomerSource;
use App\Service\InvoiceGeneratorInterface; use App\Service\InvoiceGeneratorInterface;
use App\Service\RisingTideGateway; use App\Service\RisingTideGateway;
@ -44,7 +45,7 @@ use App\Service\PromoLogger;
use App\Service\HubSelector; use App\Service\HubSelector;
use App\Service\HubDistributor; use App\Service\HubDistributor;
use App\Service\HubFilterLogger; use App\Service\HubFilterLogger;
use App\Entity\MobileSession; use App\Entity\MobileSession;
use App\Entity\Customer; use App\Entity\Customer;
use App\Entity\VehicleManufacturer; use App\Entity\VehicleManufacturer;
@ -420,6 +421,9 @@ class APIController extends Controller implements LoggedController
if ($cust == null) if ($cust == null)
{ {
$cust = new Customer(); $cust = new Customer();
// set customer source
$cust->setCreateSource(CustomerSource::MOBILE);
$em->persist($cust); $em->persist($cust);
$this->session->setCustomer($cust); $this->session->setCustomer($cust);
@ -3197,6 +3201,9 @@ class APIController extends Controller implements LoggedController
{ {
$warr = new Warranty(); $warr = new Warranty();
$sms_msg = $trans->trans('warranty_register_confirm'); $sms_msg = $trans->trans('warranty_register_confirm');
// set warranty source
$warr->setCreateSource($source);
} }
// get sap battery // get sap battery
@ -3228,6 +3235,16 @@ class APIController extends Controller implements LoggedController
return $res; return $res;
} }
$customer = $this->session->getCustomer();
if ($customer != null)
{
$warr->setCustomer($customer);
// get customer vehicles
$vehicle = $this->findCustomerVehicle($em, $customer, $req->request->get('plate_number'));
if ($vehicle != null)
$warr->setVehicle($vehicle);
}
// create or update warranty entry // create or update warranty entry
$warr->setSerial($serial) $warr->setSerial($serial)
@ -3302,6 +3319,23 @@ class APIController extends Controller implements LoggedController
return $cust; return $cust;
} }
protected function findCustomerVehicle($em, $customer, $plate_number)
{
$clean_plate = Warranty::cleanPlateNumber($plate_number);
if ($clean_plate)
{
// find the customer vehicle and get the vehicle
$cv = $em->getRepository(CustomerVehicle::class)->findOneBy(['plate_number' => $clean_plate, 'customer' => $customer]);
if ($cv != null)
{
$vehicle = $cv->getVehicle();
return $vehicle;
}
}
return null;
}
protected function findNearestHub($jo, EntityManagerInterface $em, MapTools $map_tools) protected function findNearestHub($jo, EntityManagerInterface $em, MapTools $map_tools)
{ {
// get the nearest 10 hubs // get the nearest 10 hubs

View file

@ -21,6 +21,7 @@ use DateInterval;
use App\Entity\JobOrder; use App\Entity\JobOrder;
use App\Entity\Hub; use App\Entity\Hub;
use App\Entity\Battery;
use App\Ramcar\ShiftSchedule; use App\Ramcar\ShiftSchedule;
@ -125,7 +126,7 @@ class AnalyticsController extends Controller
// TODO: populate the hour_shift array, depending on the shift selected // TODO: populate the hour_shift array, depending on the shift selected
$hour_shifts = $this->populateHourShift($shift); $hour_shifts = $this->populateHourShift($shift);
error_log(print_r($hour_shifts, true)); // error_log(print_r($hour_shifts, true));
// error_log(print_r($hub_list, true)); // error_log(print_r($hub_list, true));
// $hub_list = [ 6, 4, 36, 7, 8, 126, 127, 18, 12, 9, 60, 10, 21, 135 ]; // $hub_list = [ 6, 4, 36, 7, 8, 126, 127, 18, 12, 9, 60, 10, 21, 135 ];
@ -195,7 +196,7 @@ class AnalyticsController extends Controller
// error_log(print_r($chart_all_weekdays, true)); // error_log(print_r($chart_all_weekdays, true));
error_log(print_r($sched_res, true)); // error_log(print_r($sched_res, true));
// agggregate weekday data // agggregate weekday data
$i = 0; $i = 0;
@ -367,6 +368,22 @@ class AnalyticsController extends Controller
// get job order data (job orders within coverage area) // get job order data (job orders within coverage area)
$jos = $this->generateJobOrderData($conn, $hub, $distance_limit, $date_start, $date_end, $time_start, $time_end); $jos = $this->generateJobOrderData($conn, $hub, $distance_limit, $date_start, $date_end, $time_start, $time_end);
// get most bought battery from these JOs
$batt_id = $this->getHubBattery($conn, $jos);
$batt = $em->getRepository(Battery::class)->find($batt_id);
if ($batt == null)
$batt_data = [
'mfg' => 'None',
'model' => 'None',
'size' => 'None',
];
else
$batt_data = [
'mfg' => $batt->getManufacturer()->getName(),
'model' => $batt->getModel()->getName(),
'size' => $batt->getSize()->getName(),
];
// initialize counters // initialize counters
$c_weekday = []; $c_weekday = [];
$c_day = []; $c_day = [];
@ -433,12 +450,63 @@ class AnalyticsController extends Controller
'data_year' => $chart_year, 'data_year' => $chart_year,
// 'data_weekday' => $chart_weekday, // 'data_weekday' => $chart_weekday,
'c_weekday' => $c_weekday, // sending raw weekday data because we need to process overlaps 'c_weekday' => $c_weekday, // sending raw weekday data because we need to process overlaps
'battery' => $batt_data,
// TODO: refactor this pls // TODO: refactor this pls
]; ];
return $params; return $params;
} }
protected function getHubBattery($conn, $jos)
{
// collect ids
$ids = [];
foreach ($jos as $jo)
{
$ids[] = $jo['id'];
}
// no jos, so no battery
if (count($ids) <= 0)
{
return 0;
}
// ideally we encode the ids, but right now we're assuming they'll be int
$in_text = implode(',', $ids);
// get all the batteries ordered in these JOs
$sql = 'select battery_id, count(*) as total from invoice i,invoice_item item where i.id = item.invoice_id and i.job_order_id in (' . $in_text . ') group by battery_id';
$stmt = $conn->prepare($sql);
$stmt->execute();
$batteries = $stmt->fetchAll();
// error_log(print_r($batteries, true));
// get the most ordered, skipping the null battery
$best_batt_id = 0;
$best_batt_count = 0;
foreach ($batteries as $batt)
{
if ($batt['battery_id'] == null)
continue;
// if current battery is better than our best
if ($best_batt_count < $batt['total'])
{
$best_batt_id = $batt['battery_id'];
$best_batt_count = $batt['total'];
}
}
error_log('BEST - ' . $best_batt_id . ' - ' . $best_batt_count);
return $best_batt_id;
}
protected function generateJobOrderData($conn, $hub, $distance_limit, DateTime $date_start, DateTime $date_end, $time_start, $time_end) protected function generateJobOrderData($conn, $hub, $distance_limit, DateTime $date_start, DateTime $date_end, $time_start, $time_end)
{ {
$hub_coord = $hub->getCoordinates(); $hub_coord = $hub->getCoordinates();
@ -471,7 +539,10 @@ class AnalyticsController extends Controller
$stmt->execute(); $stmt->execute();
$jos = $stmt->fetchAll(); $jos = $stmt->fetchAll();
/*
error_log(count($jos)); error_log(count($jos));
error_log(print_r($jos, true));
*/
return $jos; return $jos;
} }

View file

@ -154,10 +154,17 @@ class CustomerController extends APIController
else else
{ {
// customer not found // customer not found
// get the api_user that made the call so that it gets added to the source
// source becomes CAPI_USER_<insert name of api user here>
$user_id = $_SERVER['HTTP_X_CATA_API_KEY'];
$username = $this->getUser()->getName();
$source = 'CAPI_USER_' . $username;
$new_cust = new Customer(); $new_cust = new Customer();
$new_cust->setFirstName($first_name) $new_cust->setFirstName($first_name)
->setLastName($last_name) ->setLastName($last_name)
->setPhoneMobile($mobile_number); ->setPhoneMobile($mobile_number)
->setCreateSource($source);
$em->persist($new_cust); $em->persist($new_cust);

View file

@ -106,6 +106,7 @@ class CustomerWarrantyController extends APIController
'serial' => $serial, 'serial' => $serial,
]; ];
$action = 'check'; $action = 'check';
// TODO: we need to modify this later.
$source = WarrantySource::CAPI; $source = WarrantySource::CAPI;
// check required parameters // check required parameters
@ -315,7 +316,11 @@ class CustomerWarrantyController extends APIController
'invoice' => $req->request->get('invoice'), 'invoice' => $req->request->get('invoice'),
]; ];
$action = 'create/update'; $action = 'create/update';
$source = WarrantySource::CAPI;
// get the api_user that made the call so that it gets added to the source
// source becomes CAPI_USER_<insert name of api user here>
$username = $this->getUser()->getName();
$source = 'CAPI_USER_' . $username;
error_log('SOURCE: ' . $source); error_log('SOURCE: ' . $source);
@ -425,6 +430,9 @@ class CustomerWarrantyController extends APIController
{ {
$warr = new Warranty(); $warr = new Warranty();
$sms_message = $trans->trans('warranty_register_confirm'); $sms_message = $trans->trans('warranty_register_confirm');
// set warranty's create source
$warr->setCreateSource($source);
} }
error_log('sap battery check'); error_log('sap battery check');
@ -484,7 +492,8 @@ class CustomerWarrantyController extends APIController
->setEmail($req->request->get('email')) ->setEmail($req->request->get('email'))
->setCreateSource('web_warranty') ->setCreateSource('web_warranty')
->setPrivacyPromo($priv_promo) ->setPrivacyPromo($priv_promo)
->setPhoneMobile($req->request->get('contact_num')); ->setPhoneMobile($req->request->get('contact_num'))
->setCreateSource($source);
$em->persist($cust); $em->persist($cust);
} }
@ -578,5 +587,4 @@ class CustomerWarrantyController extends APIController
$rt->sendSMS($clean_num, 'MOTOLITE', $message); $rt->sendSMS($clean_num, 'MOTOLITE', $message);
} }
} }

View file

@ -0,0 +1,53 @@
<?php
namespace App\Controller\CAPI;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\APIBundle\Controller\APIController;
use Catalyst\APIBundle\Response\APIResponse;
use App\Entity\Dealer;
use Catalyst\APIBundle\Access\Generator as ACLGenerator;
class DealerController extends APIController
{
protected $acl_gen;
public function __construct(ACLGenerator $acl_gen)
{
$this->acl_gen = $acl_gen;
}
public function getAll(EntityManagerInterface $em)
{
// get all dealer data order by dealer name
$this->denyAccessUnlessGranted('dealer.list', null, 'No access.');
$results = $em->getRepository(Dealer::class)->findBy([], ['name' => 'ASC']);
$dealers = [];
foreach($results as $res)
{
$dealer_id = $res->getId();
$dealer_name = $res->getName();
$dealer_address = $res->getAddress();
$dealer_branch_code = $res->getBranchCode();
$dealers[$dealer_id] = [
'id' => $dealer_id,
'name' => $dealer_name,
'address' => $dealer_address,
'branch_code' => $dealer_branch_code,
];
}
$data = [
'dealers' => $dealers,
];
return new APIResponse(true, 'Dealers loaded.', $data);
}
}

View file

@ -191,7 +191,12 @@ class WarrantyController extends APIController
'mobile_number' => $mnum, 'mobile_number' => $mnum,
]; ];
$action = 'create'; $action = 'create';
$source = WarrantySource::CAPI;
// get the api_user that made the call so that it gets added to the source
// source becomes CAPI_USER_<insert name of api user here>
$username = $this->getUser()->getName();
$source = 'CAPI_USER_' . $username;
$msg = $this->checkRequiredParameters($req, $params); $msg = $this->checkRequiredParameters($req, $params);
error_log('msg - ' . $msg); error_log('msg - ' . $msg);
@ -275,7 +280,8 @@ class WarrantyController extends APIController
->setSAPBattery($batt) ->setSAPBattery($batt)
->setDatePurchase($date_pur) ->setDatePurchase($date_pur)
->setDateClaim(null) ->setDateClaim(null)
->setDateExpire($date_expire); ->setDateExpire($date_expire)
->setCreateSource($source);
try try
{ {
@ -321,7 +327,12 @@ class WarrantyController extends APIController
'id' => $id, 'id' => $id,
]; ];
$action = 'claim'; $action = 'claim';
$source = WarrantySource::CAPI;
// get the api_user that made the call so that it gets added to the source
// source becomes CAPI_USER_<insert name of api user here>
$username = $this->getAPIUsername($em, $user_id);
$source = 'CAPI_USER_' . $username;
$msg = $this->checkRequiredParameters($req, $params); $msg = $this->checkRequiredParameters($req, $params);
if ($msg) if ($msg)
@ -370,7 +381,8 @@ class WarrantyController extends APIController
->setDatePurchase($warr->getDatePurchase()) ->setDatePurchase($warr->getDatePurchase())
->setDateClaim(null) ->setDateClaim(null)
->setDateExpire($warr->getDateExpire()) ->setDateExpire($warr->getDateExpire())
->setClaimedFrom($warr); ->setClaimedFrom($warr)
->setCreateSource($source);
$em->persist($new_warr); $em->persist($new_warr);
@ -716,10 +728,12 @@ class WarrantyController extends APIController
$w_last_name = $warranty->getLastName(); $w_last_name = $warranty->getLastName();
$new_cust = new Customer(); $new_cust = new Customer();
// TODO: add customer source // add customer source
$cust_source = $warranty->getCreateSource();
$new_cust->setFirstName($w_first_name) $new_cust->setFirstName($w_first_name)
->setLastName($w_last_name) ->setLastName($w_last_name)
->setPhoneMobile($w_mobile_num); ->setPhoneMobile($w_mobile_num)
->setCreateSource($cust_source);
$em->persist($new_cust); $em->persist($new_cust);
@ -774,5 +788,4 @@ class WarrantyController extends APIController
$customers = $em->getRepository(Customer::class)->findBy(['phone_mobile' => $number]); $customers = $em->getRepository(Customer::class)->findBy(['phone_mobile' => $number]);
return $customers; return $customers;
} }
} }

View file

@ -0,0 +1,271 @@
<?php
namespace App\Controller;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Catalyst\MenuBundle\Annotation\Menu;
use App\Entity\Dealer;
class DealerController extends Controller
{
/**
* @Menu(selected="dealer_list")
*/
public function index()
{
$this->denyAccessUnlessGranted('dealer.list', null, 'No access.');
return $this->render('dealer/list.html.twig');
}
public function rows(Request $req)
{
$this->denyAccessUnlessGranted('dealer.list', null, 'No access.');
// get query builder
$qb = $this->getDoctrine()
->getRepository(Dealer::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $qb->select('COUNT(q)');
$this->setQueryFilters($datatable, $tquery);
$total = $tquery->getQuery()
->getSingleScalarResult();
// get current page number
$page = $datatable['pagination']['page'] ?? 1;
$perpage = $datatable['pagination']['perpage'];
$offset = ($page - 1) * $perpage;
// add metadata
$meta = [
'page' => $page,
'perpage' => $perpage,
'pages' => ceil($total / $perpage),
'total' => $total,
'sort' => 'asc',
'field' => 'id'
];
// build query
$query = $qb->select('q');
$this->setQueryFilters($datatable, $query);
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
$order = $datatable['sort']['sort'] ?? 'asc';
$query->orderBy('q.' . $datatable['sort']['field'], $order);
} else {
$query->orderBy('q.id', 'asc');
}
// get rows for this page
$obj_rows = $query->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery()
->getResult();
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow->getID();
$row['name'] = $orow->getName();
$row['address'] = $orow->getAddress();
$row['branch_code'] = $orow->getBranchCode();
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// add crud urls
if ($this->isGranted('dealer.update'))
$row['meta']['update_url'] = $this->generateUrl('dealer_update', ['id' => $row['id']]);
if ($this->isGranted('dealer.delete'))
$row['meta']['delete_url'] = $this->generateUrl('dealer_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
/**
* @Menu(selected="dealer_list")
*/
public function addForm()
{
$this->denyAccessUnlessGranted('dealer.add', null, 'No access.');
$params = [];
$params['obj'] = new Dealer();
$params['mode'] = 'create';
// response
return $this->render('dealer/form.html.twig', $params);
}
public function addSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator)
{
$this->denyAccessUnlessGranted('dealer.add', null, 'No access.');
// create new object
$em = $this->getDoctrine()->getManager();
$obj = new Dealer();
$this->setObject($obj, $req);
// validate
$errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->persist($obj);
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
/**
* @Menu(selected="dealer_list")
*/
public function updateForm($id)
{
$this->denyAccessUnlessGranted('dealer.update', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(Dealer::class)->find($id);
// make sure this row exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
$params = [];
$params['obj'] = $obj;
$params['mode'] = 'update';
// response
return $this->render('dealer/form.html.twig', $params);
}
public function updateSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator, $id)
{
$this->denyAccessUnlessGranted('dealer.update', null, 'No access.');
// get object data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(Dealer::class)->find($id);
// make sure this object exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
$this->setObject($obj, $req);
// validate
$errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
public function destroy($id)
{
$this->denyAccessUnlessGranted('dealer.delete', null, 'No access.');
// get object data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(Dealer::class)->find($id);
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
// delete this object
$em->remove($obj);
$em->flush();
// response
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->send();
}
protected function setObject(Dealer $obj, Request $req)
{
// set and save values
$obj->setName($req->request->get('name'))
->setAddress($req->request->get('address', ''))
->setBranchCode($req->request->get('branch_code', ''));
}
protected function setQueryFilters($datatable, QueryBuilder $query)
{
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->where('q.name LIKE :filter')
->orWhere('q.address LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
}

View file

@ -683,33 +683,80 @@ class ReportController extends Controller
/** /**
* @Menu(selected="outlet_list") * @Menu(selected="outlet_list")
*/ */
public function warrantyDetailsExportCSV(Request $resq, EntityManagerInterface $em) public function warrantyDetailsSubmit(Request $req, EntityManagerInterface $em)
{ {
$data = $this->getWarrantyDetailsData($em); $data = $this->getWarrantyDetailsData($req, $em);
$resp = new StreamedResponse(); $resp = new StreamedResponse();
$resp->setCallback(function() use ($data) { $resp->setCallback(function() use ($data) {
// csv output // csv output
$csv_handle = fopen('php://output', 'w+'); $csv_handle = fopen('php://output', 'w+');
fputcsv($csv_handle, [ fputcsv($csv_handle, [
'Customer ID',
'Customer First Name',
'Customer Last Name',
'Customer Is Confirmed?',
'Customer Classification',
'Customer Has Mobile App?',
'Customer Title',
'Customer Is Active?',
'Customer Mobile Phone',
'Customer Landline Phone',
'Customer Office Phone',
'Customer Fax Phone',
'Customer Email Address',
'Customer Notes',
'Customer Has Third Party Privacy Policy?',
'Customer Has Promo Privacy Policy?',
'Customer Is CSAT',
'Customer Mobile App Privacy Policy ID',
'Customer Third Party Policy ID',
'Customer Promo Privacy ID',
'Customer DPA Consent',
'Customer Date Created',
'Customer SMS Research Flag',
'Customer Email Research Flag',
'Customer Create Source',
'Vehicle ID',
'Vehicle Manufacturer ID',
'Vehicle Make',
'Vehicle Model Year From',
'Vehicle Model Year To',
'Vehicle Mobile App Flag',
'Warranty ID', 'Warranty ID',
'Serial', 'Warranty Battery Model ID',
'Battery Model', 'Warranty Battery Size ID',
'Battery Size', 'Warranty Serial',
'Warranty Class', 'Warranty Class',
'Plate Number', 'Warranty Plate Number',
'Status', 'Warranty Status',
'Date Created', 'Warranty Date Created',
'Date Purchased', 'Warranty Date Purchased',
'Expiry Date', 'Warranty Expiry Date',
'Date Claimed', 'Warranty Date Claimed',
'SAP Battery ID', 'Warranty SAP Battery ID',
'Claim ID', 'Warranty Claim ID',
'Last Name', 'Warranty First Name',
'First Name', 'Warranty Last Name',
'Mobile Number', 'Warranty Mobile Number',
'Privacy Policy Number', 'Warranty Is Activated?',
'Activated?', 'Warranty Privacy Policy Number',
'Warranty Email Address',
'Warranty Vehicle ID',
'Warranty Customer ID',
'Warranty File Invoice',
'Warranty File Card',
'Warranty Vehicle Model Year',
'Warranty Odometer',
'Warranty Dealer Name',
'Warranty Dealer Address',
'Warranty Contact Number',
'Warranty Customer Address',
'Warranty Customer Date Purchase',
'Warranty Is Validated?',
'Warranty Province ID',
'Warranty Municipality ID',
'Warranty Create Source',
]); ]);
foreach ($data as $row) foreach ($data as $row)
@ -1421,23 +1468,53 @@ class ReportController extends Controller
return $results; return $results;
} }
protected function getWarrantyDetailsData(EntityManagerInterface $em) protected function getWarrantyDetailsData(Request $req, EntityManagerInterface $em)
{ {
$bm_hash = $this->loadBatteryModels($em); $bm_hash = $this->loadBatteryModels($em);
$bs_hash = $this->loadBatterySizes($em); $bs_hash = $this->loadBatterySizes($em);
// get dates
$raw_date_start = $req->request->get('date_start');
$raw_date_end = $req->request->get('date_end');
$date_start = DateTime::createFromFormat('m/d/Y', $raw_date_start);
$date_end = DateTime::createFromFormat('m/d/Y', $raw_date_end);
$date_start->setTime(0,0);
$date_end->setTime(23,59);
// convert to string in the correct format so we can plug it in the query
$str_date_start = $date_start->format('Y-m-d H:i:s');
$str_date_end = $date_end->format('Y-m-d H:i:s');
$results = []; $results = [];
$conn = $em->getConnection(); $conn = $em->getConnection();
$sql = 'SELECT w.id, w.serial, w.warranty_class, w.plate_number, $sql = 'SELECT w.id AS w_id, w.serial, w.warranty_class, w.plate_number,
w.status, w.date_create, w.date_purchase, w.date_expire, w.status, w.date_create as w_date_create, w.date_purchase, w.date_expire,
w.date_claim, w.sap_bty_id, w.claim_id, w.first_name, w.date_claim, w.sap_bty_id, w.claim_id, w.first_name,
w.last_name, w.mobile_number, w.flag_activated, w.last_name, w.mobile_number, w.flag_activated,
w.warranty_privacy_policy, w.bty_model_id, w.bty_size_id w.warranty_privacy_policy, w.bty_model_id, w.bty_size_id,
FROM warranty w'; w.email as w_email, w.vehicle_id, w.customer_id, w.file_invoice,
w.file_warr_card, w.v_model_year, w.odometer, w.dealer_name,
w.dealer_address, w.contact_num, w.cust_address,
w.date_purchase_cust, w.flag_validated, w.province_id,
w.municipality_id, w.create_source AS w_create_source, c.id AS c_id,
c.first_name AS c_fname, c.last_name AS c_lname, c.flag_confirmed,
c.customer_classification, c.flag_mobile_app, c.title, c.flag_active,
c.phone_mobile, c.phone_landline, c.phone_office, c.phone_fax,
c.email AS c_email, c.customer_notes, c.priv_third_party, c.priv_promo,
c.flag_csat, c.policy_mobile_app_id, c.policy_third_party_id,
c.policy_promo_id, c.flag_dpa_consent, c.date_create AS c_date_create,
c.flag_research_sms, c.flag_research_email, c.create_source AS c_create_source,
v.id AS v_id, v.manufacturer_id, v.make, v.model_year_from,
v.model_year_to, v.flag_mobile
FROM warranty w LEFT JOIN customer c ON w.customer_id = c.id
LEFT JOIN vehicle v ON w.vehicle_id = v.id
WHERE w.date_create >= :start_date
AND w.date_create <= :end_date';
$stmt = $conn->prepare($sql); $stmt = $conn->prepare($sql);
$stmt->execute(); $stmt->execute(['start_date' => $str_date_start, 'end_date' => $str_date_end]);
$query_results = $stmt->fetchAll(); $query_results = $stmt->fetchAll();
@ -1461,24 +1538,71 @@ class ReportController extends Controller
} }
$results[] = [ $results[] = [
'id' => $row['id'], 'cust_id' => $row['c_id'],
'serial' => $row['serial'], 'cust_first_name' => $row['c_fname'],
'battery_model' => $bmodel_name, 'cust_last_name' => $row['c_lname'],
'battery_size' => $bsize_name, 'cust_flag_confirm' => $row['flag_confirmed'],
'warranty_class' => $row['warranty_class'], 'cust_classification' => $row['customer_classification'],
'plate_number' => $row['plate_number'], 'cust_flag_mobile_app' => $row['flag_mobile_app'],
'status' => $row['status'], 'cust_title' => $row['title'],
'date_create' => $row['date_create'], 'cust_flag_active' => $row['flag_active'],
'date_purchase' => $row['date_purchase'], 'cust_phone_mobile' => $row['phone_mobile'],
'date_expire' => $row['date_expire'], 'cust_phone_landline' => $row['phone_landline'],
'date_claim' => $row['date_claim'], 'cust_phone_office' => $row['phone_office'],
'sap_bty_id' => $row['sap_bty_id'], 'cust_phone_fax' => $row['phone_fax'],
'claim_id' => $row['claim_id'], 'cust_email' => $row['c_email'],
'last_name' => $row['last_name'], 'cust_notes' => $row['customer_notes'],
'first_name' => $row['first_name'], 'cust_priv_third_party' => $row['priv_third_party'],
'mobile_number' => $row['mobile_number'], 'cust_priv_promo' => $row['priv_promo'],
'privacy_policy' => $row['warranty_privacy_policy'], 'cust_flag_csat' => $row['flag_csat'],
'flag_activated' => (boolean) $row['flag_activated'], 'cust_policy_mobile_app_id' => $row['policy_mobile_app_id'],
'cust_policy_third_party_id' => $row['policy_third_party_id'],
'cust_policy_promo_id' => $row['policy_promo_id'],
'cust_flag_dpa_consent' => $row['flag_dpa_consent'],
'cust_date_create' => $row['c_date_create'],
'cust_flag_research_sms' => $row['flag_research_sms'],
'cust_flag_research_email' => $row['flag_research_email'],
'cust_create_source' => $row['c_create_source'],
'v_id' => $row['v_id'],
'v_manufacturer_id' => $row['manufacturer_id'],
'v_make' => $row['make'],
'v_model_year_from' => $row['model_year_from'],
'v_model_year_to' => $row['model_year_to'],
'v.flag_mobile' => $row['flag_mobile'],
'warr_id' => $row['w_id'],
'warr_battery_model' => $bmodel_name,
'warr_battery_size' => $bsize_name,
'warr_serial' => $row['serial'],
'warr_class' => $row['warranty_class'],
'warr_plate_number' => $row['plate_number'],
'warr_status' => $row['status'],
'warr_date_create' => $row['w_date_create'],
'warr_date_purchase' => $row['date_purchase'],
'warr_date_expire' => $row['date_expire'],
'warr_date_claim' => $row['date_claim'],
'warr_sap_bty_id' => $row['sap_bty_id'],
'warr_claim_id' => $row['claim_id'],
'warr_first_name' => $row['first_name'],
'warr_last_name' => $row['last_name'],
'warr_mobile_number' => $row['mobile_number'],
'warr_flag_activated' => (boolean) $row['flag_activated'],
'warr_privacy_policy' => $row['warranty_privacy_policy'],
'warr_email' => $row['w_email'],
'warr_vehicle_id' =>$row['vehicle_id'],
'warr_customer_id' => $row['customer_id'],
'warr_file_invoice' => $row['file_invoice'],
'warr_file_warr_card' => $row['file_warr_card'],
'warr_v_model_year' => $row['v_model_year'],
'warr_odometer' => $row['odometer'],
'warr_dealer_name' => $row['dealer_name'],
'warr_dealer_address' => $row['dealer_address'],
'warr_contact_number' => $row['contact_num'],
'warr_customer_address' => $row['cust_address'],
'warr_customer_date_purchase' => $row['date_purchase_cust'],
'warr_flag_validated' => $row['flag_validated'],
'warr_province_id' => $row['province_id'],
'warr_municipality_id' => $row['municipality_id'],
'warr_create_source' => $row['w_create_source'],
]; ];
} }

View file

@ -314,7 +314,7 @@ class TicketController extends Controller
if (empty($obj)) if (empty($obj))
throw $this->createNotFoundException('The item does not exist'); throw $this->createNotFoundException('The item does not exist');
$em = $this->getDoctrine()->getManager(); // $em = $this->getDoctrine()->getManager();
$customer = $obj->getCustomer(); $customer = $obj->getCustomer();
$job_order = $obj->getJobOrder(); $job_order = $obj->getJobOrder();
@ -337,6 +337,28 @@ class TicketController extends Controller
$params['redirect_url'] = $cust_update_url; $params['redirect_url'] = $cust_update_url;
} }
// optimized get related tickets
$rel_tix = [];
// one query for each so we use indeces
if (!empty($obj->getFirstName()) && !empty($obj->getLastName()))
$rel_tix[] = $em->getRepository(Ticket::class)->findBy(['first_name' => $obj->getFirstName(), 'last_name' => $obj->getLastName()]);
if (!empty($obj->getContactNumber()))
$rel_tix[] = $em->getRepository(Ticket::class)->findBy(['contact_num' => $obj->getContactNumber()]);
if (!empty($obj->getPlateNumber()))
$rel_tix[] = $em->getRepository(Ticket::class)->findBy(['plate_number' => $obj->getPlateNumber()]);
$consolidated_rel_tix = [];
foreach ($rel_tix as $rel_tickets)
{
foreach ($rel_tickets as $rticket)
{
$rtid = $rticket->getID();
$consolidated_rel_tix[$rtid] = $rticket;
}
}
$params['related_tickets'] = $consolidated_rel_tix;
/*
// get related tickets // get related tickets
$qb = $em->getRepository(Ticket::class) $qb = $em->getRepository(Ticket::class)
->createQueryBuilder('q'); ->createQueryBuilder('q');
@ -353,6 +375,8 @@ class TicketController extends Controller
$params['related_tickets'] = $query->getQuery() $params['related_tickets'] = $query->getQuery()
->getResult(); ->getResult();
*/
$params['obj'] = $obj; $params['obj'] = $obj;

View file

@ -176,7 +176,8 @@ class WarrantyController extends Controller
->setMobileNumber($req->request->get('mobile_number')) ->setMobileNumber($req->request->get('mobile_number'))
->setDatePurchase($date_purchase) ->setDatePurchase($date_purchase)
->setClaimedFrom($req->request->get('claim_from')) ->setClaimedFrom($req->request->get('claim_from'))
->setStatus($req->request->get('status')); ->setStatus($req->request->get('status'))
->setCreateSource(WarrantySource::ADMIN_PANEL);
if ($date_claim) if ($date_claim)
{ {

81
src/Entity/Dealer.php Normal file
View file

@ -0,0 +1,81 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
* @ORM\Table(name="dealer")
*/
class Dealer
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// name of dealer
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $name;
// address
/**
* @ORM\Column(type="text")
* @Assert\NotBlank()
*/
protected $address;
// branch code of dealer
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $branch_code;
public function getId()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function setAddress($address)
{
$this->address = $address;
return $this;
}
public function getAddress()
{
return $this->address;
}
public function setBranchCode($branch_code)
{
$this->branch_code = $branch_code;
return $this;
}
public function getBranchCode()
{
return $this->branch_code;
}
}

View file

@ -12,7 +12,12 @@ use DateTime;
/** /**
* @ORM\Entity * @ORM\Entity
* @ORM\Table(name="ticket") * @ORM\Table(name="ticket", indexes={
* @ORM\Index(columns={"contact_num"}),
* @ORM\Index(columns={"plate_number"}),
* @ORM\Index(columns={"first_name"}),
* @ORM\Index(columns={"last_name"})
* })
*/ */
class Ticket class Ticket
{ {

View file

@ -232,6 +232,11 @@ class Warranty
*/ */
protected $municipality_id; protected $municipality_id;
/**
* @ORM\Column(type="string", length=80, options={"default": "legacy"})
*/
protected $create_source;
public function __construct() public function __construct()
{ {
$this->date_create = new DateTime(); $this->date_create = new DateTime();
@ -242,6 +247,7 @@ class Warranty
$this->email = ''; $this->email = '';
$this->odometer = 0; $this->odometer = 0;
$this->flag_validated = false; $this->flag_validated = false;
$this->create_source = 'unknown';
} }
public function getID() public function getID()
@ -658,4 +664,16 @@ class Warranty
{ {
return $this->municipality_id; return $this->municipality_id;
} }
public function setCreateSource($source)
{
$this->create_source = $source;
return $this;
}
public function getCreateSource()
{
return $this->create_source;
}
} }

View file

@ -0,0 +1,16 @@
<?php
namespace App\Ramcar;
class CustomerSource extends NameValue
{
const MOBILE = 'mobile_api';
const ADMIN_PANEL = 'admin_panel';
const LEGACY = 'legacy';
const COLLECTION = [
'mobile_api' => 'Mobile API',
'admin_panel' => 'Admin Panel',
'legacy' => 'Legacy',
];
}

View file

@ -10,6 +10,7 @@ class WarrantySource extends NameValue
const BULK_UPLOAD = 'bulk_upload'; const BULK_UPLOAD = 'bulk_upload';
const MOBILE = 'mobile'; const MOBILE = 'mobile';
const COMMAND = 'command'; const COMMAND = 'command';
const UNKNOWN = 'unknown';
const COLLECTION = [ const COLLECTION = [
'capi' => 'Third Party API', 'capi' => 'Third Party API',
@ -18,6 +19,7 @@ class WarrantySource extends NameValue
'bulk_upload' => 'Bulk Upload', 'bulk_upload' => 'Bulk Upload',
'mobile' => 'Mobile API', 'mobile' => 'Mobile API',
'command' => 'Command', 'command' => 'Command',
'unknown' => 'Unknown',
]; ];
} }

View file

@ -15,6 +15,7 @@ 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\Ramcar\CrudException;
use App\Ramcar\CustomerSource;
use App\Entity\Customer; use App\Entity\Customer;
use App\Entity\CustomerVehicle; use App\Entity\CustomerVehicle;
@ -189,6 +190,9 @@ class ResqCustomerHandler implements CustomerHandlerInterface
$this->setObject($row, $req); $this->setObject($row, $req);
// set customer source only when new customer
$row->setCreateSource(CustomerSource::ADMIN_PANEL);
// custom validation for vehicles // custom validation for vehicles
$vehicles = json_decode($req->request->get('vehicles')); $vehicles = json_decode($req->request->get('vehicles'));

View file

@ -1070,7 +1070,7 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
$user_id = $user->getUsername(); $user_id = $user->getUsername();
$source = WarrantySource::ADMIN_PANEL; $source = WarrantySource::ADMIN_PANEL;
$this->wh->createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number, $batt_list, $date_purchase, $warranty_class, $user_id, $source); $this->wh->createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number, $batt_list, $date_purchase, $warranty_class, $user_id, $source, $obj->getCustomer(), $obj->getCustomerVehicle()->getVehicle());
} }
else else
error_log('Invalid plate number for warranty. Plate number = ' . $obj->getCustomerVehicle()->getPlateNumber()); error_log('Invalid plate number for warranty. Plate number = ' . $obj->getCustomerVehicle()->getPlateNumber());

View file

@ -602,7 +602,7 @@ class ResqRiderAPIHandler implements RiderAPIHandlerInterface
// for riders, use rider session id // for riders, use rider session id
$user_id = $this->session->getID(); $user_id = $this->session->getID();
$source = WarrantySource::RAPI; $source = WarrantySource::RAPI;
$this->wh->createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number, $batt_list, $date_purchase, $warranty_class, $user_id, $source); $this->wh->createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number, $batt_list, $date_purchase, $warranty_class, $user_id, $source, $jo->getCustomer(), $jo->getCustomerVehicle()->getVehicle());
} }
// send mqtt event (fulfilled) // send mqtt event (fulfilled)

View file

@ -30,7 +30,8 @@ class WarrantyHandler
} }
public function createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number, public function createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number,
$batt_list, DateTime $date_purchase, $warranty_class, $user_id, $source) $batt_list, DateTime $date_purchase, $warranty_class, $user_id,
$source, $customer, $cust_vehicle)
{ {
// new warranty // new warranty
$warranty = new Warranty(); $warranty = new Warranty();
@ -93,7 +94,10 @@ class WarrantyHandler
->setLastName($last_name) ->setLastName($last_name)
->setMobileNumber($mobile_number) ->setMobileNumber($mobile_number)
->setDatePurchase($date_purchase) ->setDatePurchase($date_purchase)
->setWarrantyClass($warranty_class); ->setWarrantyClass($warranty_class)
->setCreateSource($source)
->setCustomer($customer)
->setVehicle($cust_vehicle);
$this->em->persist($warranty); $this->em->persist($warranty);
$this->em->flush(); $this->em->flush();
@ -361,7 +365,8 @@ class WarrantyHandler
public function cleanPlateNumber($plate) public function cleanPlateNumber($plate)
{ {
// remove spaces and make upper case // TODO: make this more like Warranty's static cleanPlateNumber?
// remove spaces and make upper case
return strtoupper(str_replace(' ', '', $plate)); return strtoupper(str_replace(' ', '', $plate));
} }

View file

@ -98,6 +98,10 @@
<div id="month-all-weekday-chart-{{ hub.id }}" style="height: 400px;"> <div id="month-all-weekday-chart-{{ hub.id }}" style="height: 400px;">
</div> </div>
<div class="shift-table">
<b>Recommended Extra Battery Inventory</b> - {{ hub.battery.mfg }} - {{ hub.battery.model }} - {{ hub.battery.size }}
</div>
<table class="shift-table"> <table class="shift-table">
<thead> <thead>
<tr> <tr>

View file

@ -0,0 +1,154 @@
{% extends 'base.html.twig' %}
{% block body %}
<!-- BEGIN: Subheader -->
<div class="m-subheader">
<div class="d-flex align-items-center">
<div class="mr-auto">
<h3 class="m-subheader__title">Dealers</h3>
</div>
</div>
</div>
<!-- END: Subheader -->
<div class="m-content">
<!--Begin::Section-->
<div class="row">
<div class="col-xl-12">
<div class="m-portlet m-portlet--mobile">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<span class="m-portlet__head-icon">
<i class="fa fa-building"></i>
</span>
<h3 class="m-portlet__head-text">
{% if mode == 'update' %}
Edit Dealer
<small>{{ obj.getName() }}</small>
{% else %}
New Dealer
{% endif %}
</h3>
</div>
</div>
</div>
<form id="row-form" class="m-form m-form--label-align-right" method="post" action="{{ mode == 'update' ? url('dealer_update_submit', {'id': obj.getId()}) : url('dealer_create_submit') }}">
<div class="m-portlet__body">
<div class="tab-content">
<div class="tab-pane active" id="dealer-info" role="tabpanel">
<div class="form-group m-form__group row no-border">
<div class="col-lg-6">
<label for="name" data-field="name">
Name
</label>
<input type="text" name="name" class="form-control m-input" value="{{ obj.getName() }}">
<div class="form-control-feedback hide" data-field="name"></div>
</div>
<div class="col-lg-6">
<label for="branch_code" data-field="branch_code">
Branch Code
</label>
<input type="text" name="branch_code" class="form-control m-input" value="{{ obj.getBranchCode() }}">
<div class="form-control-feedback hide" data-field="branch_code"></div>
</div>
</div>
<div class="form-group m-form__group row no-border">
<div class="col-lg-6">
<label for="address" data-field="address">
Address
</label>
<textarea class="form-control m-input" id="address" rows="4" name="address">{{ obj.getAddress }}</textarea>
<div class="form-control-feedback hide" data-field="address"></div>
</div>
</div>
</div>
</div>
</div>
<div class="m-portlet__foot m-portlet__foot--fit">
<div class="m-form__actions m-form__actions--solid m-form__actions--right">
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-success">Submit</button>
<a href="{{ url('dealer_list') }}" class="btn btn-secondary">Back</a>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
$(function() {
$("#row-form").submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
method: "POST",
url: form.prop('action'),
data: form.serialize()
}).done(function(response) {
// remove all error classes
removeErrors();
swal({
title: 'Done!',
text: 'Your changes have been saved!',
type: 'success',
onClose: function() {
window.location.href = "{{ url('dealer_list') }}";
}
});
}).fail(function(response) {
if (response.status == 422) {
var errors = response.responseJSON.errors;
var firstfield = false;
// remove all error classes first
removeErrors();
// display errors contextually
$.each(errors, function(field, msg) {
var formfield = $("[name='" + field + "']");
var label = $("label[data-field='" + field + "']");
var msgbox = $(".form-control-feedback[data-field='" + field + "']");
// add error classes to bad fields
formfield.addClass('form-control-danger');
label.addClass('has-danger');
msgbox.html(msg).addClass('has-danger').removeClass('hide');
// check if this field comes first in DOM
var domfield = formfield.get(0);
if (!firstfield || (firstfield && firstfield.compareDocumentPosition(domfield) === 2)) {
firstfield = domfield;
}
});
// focus on first bad field
firstfield.focus();
// scroll to above that field to make it visible
$('html, body').animate({
scrollTop: $(firstfield).offset().top - 200
}, 100);
}
});
});
// remove all error classes
function removeErrors() {
$(".form-control-danger").removeClass('form-control-danger');
$("[data-field]").removeClass('has-danger');
$(".form-control-feedback[data-field]").addClass('hide');
}
});
</script>
{% endblock %}

View file

@ -0,0 +1,151 @@
{% extends 'base.html.twig' %}
{% block body %}
<!-- BEGIN: Subheader -->
<div class="m-subheader">
<div class="d-flex align-items-center">
<div class="mr-auto">
<h3 class="m-subheader__title">
Dealers
</h3>
</div>
</div>
</div>
<!-- END: Subheader -->
<div class="m-content">
<!--Begin::Section-->
<div class="row">
<div class="col-xl-12">
<div class="m-portlet m-portlet--mobile">
<div class="m-portlet__body">
<div class="m-form m-form--label-align-right m--margin-top-20 m--margin-bottom-30">
<div class="row align-items-center">
<div class="col-xl-8 order-2 order-xl-1">
<div class="form-group m-form__group row align-items-center">
<div class="col-md-4">
<div class="m-input-icon m-input-icon--left">
<input type="text" class="form-control m-input m-input--solid" placeholder="Search..." id="data-rows-search">
<span class="m-input-icon__icon m-input-icon__icon--left">
<span><i class="la la-search"></i></span>
</span>
</div>
</div>
</div>
</div>
<div class="col-xl-4 order-1 order-xl-2 m--align-right">
<a href="{{ url('dealer_create') }}" class="btn btn-focus m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
<span>
<i class="fa fa-building"></i>
<span>New Dealer</span>
</span>
</a>
<div class="m-separator m-separator--dashed d-xl-none"></div>
</div>
</div>
</div>
<!--begin: Datatable -->
<div id="data-rows"></div>
<!--end: Datatable -->
</div>
</div>
</div>
</div>
</div>
{% endblock %}
{% block scripts %}
<script>
$(function() {
var options = {
data: {
type: 'remote',
source: {
read: {
url: '{{ url("dealer_rows") }}',
method: 'POST',
}
},
saveState: {
cookie: false,
webstorage: false
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
columns: [
{
field: 'id',
title: 'ID',
width: 30
},
{
field: 'name',
title: 'Dealer'
},
{
field: 'address',
title: 'Address'
},
{
field: 'branch_code',
title: 'Branch Code'
},
{
field: 'Actions',
width: 110,
title: 'Actions',
sortable: false,
overflow: 'visible',
template: function (row, index, datatable) {
var actions = '';
if (row.meta.update_url != '') {
actions += '<a href="' + row.meta.update_url + '" class="m-portlet__nav-link btn m-btn m-btn--hover-accent m-btn--icon m-btn--icon-only m-btn--pill btn-edit" data-id="' + row.name + '" title="Edit"><i class="la la-edit"></i></a>';
}
if (row.meta.delete_url != '') {
actions += '<a href="' + row.meta.delete_url + '" class="m-portlet__nav-link btn m-btn m-btn--hover-danger m-btn--icon m-btn--icon-only m-btn--pill btn-delete" data-id="' + row.name + '" title="Delete"><i class="la la-trash"></i></a>';
}
return actions;
},
}
],
search: {
onEnter: false,
input: $('#data-rows-search'),
delay: 400
}
};
var table = $("#data-rows").mDatatable(options);
$(document).on('click', '.btn-delete', function(e) {
var url = $(this).prop('href');
var id = $(this).data('id');
var btn = $(this);
e.preventDefault();
swal({
title: 'Confirmation',
html: 'Are you sure you want to delete <strong>' + id + '</strong>?',
type: 'warning',
showCancelButton: true
}).then((result) => {
if (result.value) {
$.ajax({
method: "DELETE",
url: url
}).done(function(response) {
table.row(btn.parents('tr')).remove();
table.reload();
});
}
});
});
});
</script>
{% endblock %}

View file

@ -21,30 +21,65 @@
<div class="m-portlet__head-caption"> <div class="m-portlet__head-caption">
<div class="m-portlet__head-title"> <div class="m-portlet__head-title">
<span class="m-portlet__head-icon"> <span class="m-portlet__head-icon">
<i class="fa fa-upload"></i> <i class="fa fa-calendar"></i>
</span> </span>
<h3 class="m-portlet__head-text"> <h3 class="m-portlet__head-text">
Generate Warranty Details CSV File Select a date range
</h3> </h3>
</div> </div>
</div> </div>
</div> </div>
<form id="upload_form" class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed" method="post" action="{{ url('rep_warranty_details_export_csv') }}" enctype="multipart/form-data"> <form id="row-form" autocomplete="off" class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed" method="post" action="{{ url('rep_warranty_details_submit') }}">
<div class="m-portlet__body"> <div class="m-portlet__body">
<div class="m-portlet__foot m-portlet__foot--fit"> <div class="form-group m-form__group row">
<div class="m-form__actions m-form__actions--solid m-form__actions--right"> <div class="input-daterange input-group" id="date-range">
<div class="row"> <input role="presentation" type="text" class="form-control m-input" name="date_start" placeholder="Start date" />
<div class="col-lg-12"> <div class="input-group-append">
<button type="submit" class="btn btn-success">Export to CSV</button> <span class="input-group-text"><i class="la la-ellipsis-h"></i></span>
</div> </div>
<input role="presentation" type="text" class="form-control" name="date_end" placeholder="End date" />
</div>
</div>
</div>
<div class="m-portlet__foot m-portlet__foot--fit">
<div class="m-form__actions m-form__actions--solid m-form__actions--right">
<div class="row">
<div class="col-lg-12">
<button type="submit" class="btn btn-success">Submit</button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</form> </form>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
{% endblock %} {% endblock %}
{% block scripts %}
<script>
$(function() {
$("#date-range").datepicker({
orientation: "bottom"
});
$("#row-form").submit(function(e) {
var form = $(this);
if (!$("[name='date_start']").val() || !$("[name='date_end']").val()) {
e.preventDefault();
swal({
title: 'Whoops!',
text: 'Please fill in both date fields.',
type: 'warning'
});
return false;
}
});
});
</script>
{% endblock %}

View file

@ -20,14 +20,20 @@ $conn_string = "BlobEndpoint=$blob_url;\nSharedAccessSignature=$sas_token";
$blob_client = BlobRestProxy::createBlobService($conn_string); $blob_client = BlobRestProxy::createBlobService($conn_string);
$current_date = new DateTime(); // get date argument
$current_date->modify("-1 day"); $proc_date = $argv[1];
$date = $current_date->format('m-d-y'); error_log($proc_date);
$filename = 'warrantylogs' . $date . '.csv'; //$current_date = new DateTime();
//print_r($filename); //$current_date->modify("-1 day");
//$date = $current_date->format('m-d-Y');
$filename = 'warrantylogs' . $proc_date . '.csv';
error_log($filename);
/*
try { try {
// NOTE: via download blob // NOTE: via download blob
$res = $blob_client->getBlob('warranty', $filename); $res = $blob_client->getBlob('warranty', $filename);
@ -36,8 +42,7 @@ try {
file_put_contents("/tmp/warranty_download_serial.txt", $res->getContentStream()); file_put_contents("/tmp/warranty_download_serial.txt", $res->getContentStream());
} catch (Exception $e) { } catch (Exception $e) {
file_put_contents("/tmp/serial_download_error.txt", $filename . "\n" . $e->getMessage() . "\n" . "\n", FILE_APPEND); file_put_contents("/tmp/serial_download_error.txt", $filename . "\n" . $e->getMessage() . "\n" . "\n", FILE_APPEND);
} } */
/* /*
// NOTE: getting via url // NOTE: getting via url

View file

@ -0,0 +1,49 @@
<?php
// NOTE: reference: https://github.com/Azure/azure-storage-php/blob/master/samples/BlobSamples.php
require_once(__DIR__ . '/../../vendor/autoload.php');
use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Common\ServiceException;
$blob_url = 'https://popappshopprodstorage.blob.core.windows.net';
$sas_token = 'sp=r&st=2021-04-13T03:48:30Z&se=2022-04-01T11:48:30Z&spr=https&sv=2020-02-10&sr=c&sig=L6VDl40qRXhQb7w8JVkj3r7x2Xkt72pQaQ8AH2M5CRk%3D';
$conn_string = "BlobEndpoint=$blob_url;\nSharedAccessSignature=$sas_token";
$blob_client = BlobRestProxy::createBlobService($conn_string);
// get date argument, output file argument, overwrite_flag argument
$proc_date = $argv[1];
$output_file = $argv[2];
$flag_overwrite = $argv[3];
error_log($proc_date);
$filename = 'warrantylogs' . $proc_date . '.csv';
error_log($filename);
try {
// NOTE: via download blob
$res = $blob_client->getBlob('warranty', $filename);
// print_r($res);
if ($flag_overwrite > 0)
{
file_put_contents($output_file, $res->getContentStream());
}
else
{
file_put_contents($output_file, "\r\n", FILE_APPEND);
file_put_contents($output_file, $res->getContentStream(), FILE_APPEND);
}
} catch (Exception $e) {
file_put_contents("/tmp/serial_download_error.txt", $filename . "\n" . $e->getMessage() . "\n" . "\n", FILE_APPEND);
}

View file

@ -0,0 +1,106 @@
<?php
require_once(__DIR__ . '/../../vendor/autoload.php');
use Symfony\Component\Dotenv\Dotenv;
// get database information from .env
function getDatabaseInfo()
{
$dotenv = new Dotenv();
$dotenv->loadEnv(__DIR__.'/../../.env');
$db_info = $_ENV['DATABASE_URL'];
// sample format of db_info: mysql://db_user:db_password@127.0.0.1:3306/resq?charset=utf8
// dsn for PDO needs to be: mysql:host=127.0.0.1:3306;dbname=resq;charset=UTF8
preg_match('/^mysql:\/\/(.*):(.*)@(.*):(.*)\/(.*)\?(.*)/', $db_info, $result);
$db_type = 'mysql:host=';
$user = $result[1];
$pass = $result[2];
$ip_port = $result[3] . ':' . $result[4] . ';';
$db_name = 'dbname=' . $result[5] . ';';
$charset = $result[6];
$dsn = $db_type . $ip_port . $db_name . $charset;
$db_data = array($dsn, $user, $pass);
return $db_data;
}
// load csv
$csv = fopen($argv[1], 'r');
$output_file = $argv[2];
$output_fh = fopen($output_file, "w");
if (!file_exists($argv[1]))
{
$err_message = "No csv input file found." . "\n";
fwrite($output_fh, $err_message);
fclose($output_fh);
exit();
}
list($dsn, $user, $pass) = getDatabaseInfo();
// error_log($dsn);
// error_log($user);
// error_log($pass);
// connect to db
$db = new PDO($dsn, $user, $pass);
// prepared statement
$sth = $db->prepare('insert into dealer (name, address, branch_code) values (:name, :address, :branch_code)');
$rownum = 0;
while (($row = fgetcsv($csv)) !== false)
{
// dealer csv file has a header
if ($rownum < 1)
{
// skip header
$rownum++;
continue;
}
// sample of line in csv file
// columns are name, address, branch code
// BATPARTS Marcos Branch,"Km. 16 Marcos Hi-way corner Mahogany Street, Santolan, Pasig",ZN03576282
$dealer_name = trim(strtoupper($row[0]));
$dealer_address = trim(strtoupper($row[1]));
$dealer_branch_code = trim(strtoupper($row[2]));
// error_log('name ' . $dealer_name . ' address ' . $dealer_address . ' branch code ' . $dealer_branch_code);
error_log('Processing ' . $dealer_name);
$res = $sth->execute([
':name' => $dealer_name,
':address' => $dealer_address,
':branch_code' => $dealer_branch_code,
]);
if (!$res)
{
// log error
$err = $sth->errorInfo();
$log_message = "$dealer_name - ERROR - " . $err[2] . "\n";
}
else
{
// log successful adding of dealer
$log_message = "$dealer_name - SUCCESS - " . "\n";
}
fwrite($output_fh, $log_message);
$rownum++;
}
// close file
fclose($csv);
fclose($output_fh);
?>

View file

@ -1,10 +1,48 @@
<?php <?php
require_once(__DIR__ . '/../../vendor/autoload.php');
use Symfony\Component\Dotenv\Dotenv;
// TODO: this whole thing needs to be refactored
// load csv // load csv
$csv = fopen($argv[1], 'r'); $csv = fopen($argv[1], 'r');
$dsn = $argv[2]; $output_file = $argv[2];
$user = $argv[3];
$pass = $argv[4]; $output_fh = fopen($output_file, "w");
if (!file_exists($argv[1]))
{
$err_message = "No csv input file found." . "\n";
fwrite($output_fh, $err_message);
fclose($output_fh);
exit();
}
// get username and password
$dotenv = new Dotenv();
$dotenv->loadEnv(__DIR__.'/../../.env');
$db_info = $_ENV['DATABASE_URL'];
// sample format of db_info: mysql://db_user:db_password@127.0.0.1:3306/resq?charset=utf8
// dsn for PDO needs to be: mysql:host=127.0.0.1:3306;dbname=resq;charset=UTF8
preg_match('/^mysql:\/\/(.*):(.*)@(.*):(.*)\/(.*)\?(.*)/', $db_info, $result);
$db_type = 'mysql:host=';
$user = $result[1];
$pass = $result[2];
$ip_port = $result[3] . ':' . $result[4] . ';';
$db_name = 'dbname=' . $result[5] . ';';
$charset = $result[6];
$dsn = $db_type . $ip_port . $db_name . $charset;
//error_log($dsn);
//error_log($user);
//error_log($pass);
// connect to db // connect to db
$db = new PDO($dsn, $user, $pass); $db = new PDO($dsn, $user, $pass);
@ -13,33 +51,90 @@ $db = new PDO($dsn, $user, $pass);
$sth = $db->prepare('insert into warranty_serial (id, sku, date_create, source, meta_info) values (:serial, :sku, :date_create, :source, :meta_info)'); $sth = $db->prepare('insert into warranty_serial (id, sku, date_create, source, meta_info) values (:serial, :sku, :date_create, :source, :meta_info)');
// go through rows // go through rows
$counter = 0;
$source = 'motiv'; $source = 'motiv';
while (($row = fgetcsv($csv)) !== false) while (($row = fgetcsv($csv)) !== false)
{ {
// skip first line // TODO: verify if these are still the headers if there are headers
if ($counter == 0) // possible lines in output file:
// (1) header in csv file
// SerialNumber,Sku,DispatchStatus,CreatedDate,InventoryStatus,CategoryID,CategoryName
// (2) No available data
// (3) CH2000012071,WCHD23BL-CPN00-LX,0,2020-08-11 04:05:27.090,0,4,CHAMPION MF
// (4) Empty line
// (5) empty sku
// check if No available data
if ($row[0] == 'No available data')
{ {
$counter++; // skip the line
error_log('No available data, skipping the line...');
continue; continue;
} }
/* // check if empty line
$serial = trim(strtoupper($row[0])); if ($row == array(null))
$sku = trim($row[1]); {
$date_create = $row[2]; // skip
$ref_id = $row[3]; */ error_log('Skipping empty line...');
continue;
}
// check if empty serial
if (empty($row[0]))
{
$err_message = "Empty serial. " . "\n";
fwrite($output_fh, $err_message);
continue;
}
// sample of line in output file: // sample of line in output file:
// serial number, sku, dispatch status, created date, inventory status, category id, category name // serial number, sku, dispatch status, created date, inventory status, category id, category name
// CH2000012071,WCHD23BL-CPN00-LX,0,2020-08-11 04:05:27.090,0,4,CHAMPION MF // CH2000012071,WCHD23BL-CPN00-LX,0,2020-08-11 04:05:27.090,0,4,CHAMPION MF
// MG2000313690,N/A,1,2021-05-14T23:47:30.6430000+08:00,0,10,GOLD
$serial = trim(strtoupper($row[0])); $serial = trim(strtoupper($row[0]));
$sku = trim($row[1]); $sku = trim(strtoupper($row[1]));
$dispatch_status = trim($row[2]); $dispatch_status = trim($row[2]);
$date_create = $row[3]; $str_date_create = trim($row[3]);
$inventory_status = trim($row[4]); $inventory_status = trim($row[4]);
$cat_id = trim($row[5]); $cat_id = trim($row[5]);
$cat_name = trim($row[6]); $cat_name = trim(strtoupper($row[6]));
error_log('Processing ' . $serial . ' and ' . $sku);
// since some people cannot follow simple instructions...
// check the date format on the string
// try 2021-05-15T08:35:46+08:00 format on str_date_create
$date_create = DateTime::createFromFormat('Y-m-d\TH:i:sP', $str_date_create);
if ($date_create == false)
{
// try this format: 2021-05-15T08:47:20.3330000+08:00
// get the date, time and timezone from str_date_create
$str_date_time = substr($str_date_create, 0, 19);
$str_timezone = substr($str_date_create, 27);
$str_datetime_tz = $str_date_time . $str_timezone;
// create DateTime object
// sample: 2021-05-15T12:16:06+08:00
$date_create = DateTime::createFromFormat('Y-m-d\TH:i:sP', $str_datetime_tz);
// check if datetime object was created
// if not, someone f*cked up and we have no date create
if ($date_create == false)
{
// log the serial
$message = "$serial - ERROR - " . "Invalid date format for create date." . "\n";
fwrite($output_fh, $message);
continue;
}
}
$created_date = $date_create->format('Y-m-d H:i:s');
//error_log($str_date_time);
//error_log($str_timezone);
//error_log($str_datetime_tz);
//error_log($date_create->format('Y-m-d H:i:s'));
$meta_info = [ $meta_info = [
'dispatch_status' => $dispatch_status, 'dispatch_status' => $dispatch_status,
@ -56,19 +151,27 @@ while (($row = fgetcsv($csv)) !== false)
$res = $sth->execute([ $res = $sth->execute([
':serial' => $serial, ':serial' => $serial,
':sku' => $sku, ':sku' => $sku,
':date_create' => $date_create, ':date_create' => $created_date,
':source' => $source, ':source' => $source,
':meta_info' => $info, ':meta_info' => $info,
]); ]);
if (!$res) if (!$res)
{ {
// log the error
$err = $sth->errorInfo(); $err = $sth->errorInfo();
echo "Error ($serial) - " . $err[2] . "\n"; $err_message = "$serial - ERROR - " . $err[2] . "\n";
fwrite($output_fh, $err_message);
}
else
{
// log successful adding of serial
$message = "$serial - SUCCESS - " . "\n";
fwrite($output_fh, $message);
} }
} }
// close file // close file
fclose($csv); fclose($csv);
fclose($output_fh);

View file

@ -1,4 +1,4 @@
#!/bin/bash #!/bin/bash
touch /tmp/warranty_download_serial.txt touch /tmp/warranty_download_serial.txt
/usr/bin/php /usr/share/nginx/html/resqapi/utils/get_warranty_serial/get_serials.php /usr/bin/php /usr/share/nginx/html/resqapi/utils/get_warranty_serial/get_serials.php `date +%m-%d-%Y`
/usr/bin/php /usr/share/nginx/html/resqapi/utils/load_warranty_serial/load_serials.php /tmp/warranty_download_serial.txt "mysql:host=localhost;dbname=resq;charset=UTF8" resq Motolite456 /usr/bin/php /usr/share/nginx/html/resqapi/utils/load_warranty_serial/load_serials.php /tmp/warranty_download_serial.txt "mysql:host=localhost;dbname=resq;charset=UTF8"

9
utils/warranty_motiv_local.sh Executable file
View file

@ -0,0 +1,9 @@
#!/bin/bash
#touch /tmp/warranty_download_serial.csv
proc_date=`date +%m-%d-%y -d "1 day ago"`
download_file="/tmp/warranty_download_serial_$proc_date.csv"
load_status_file="/tmp/warranty_load_status_$proc_date.txt"
echo $download_file
echo $load_status_file
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php $proc_date $download_file 1
/usr/bin/php /var/www/resq/utils/load_warranty_serial/load_serials.php $download_file $load_status_file

View file

@ -0,0 +1,40 @@
#!/bin/bash
touch /tmp/warranty_download_serial.csv
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-03-21 /tmp/warranty_download_serial.csv 1
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-04-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-05-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-06-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-07-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-08-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-09-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-10-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-11-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-12-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-13-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-14-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-15-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-16-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-17-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-18-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-19-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-20-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-21-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-22-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-23-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-24-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-25-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-26-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-27-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-28-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-29-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-30-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-31-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-01-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-02-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-03-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-04-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-05-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-06-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-07-21 /tmp/warranty_download_serial.csv 0
touch /tmp/warranty_load_status.txt
/usr/bin/php /var/www/resq/utils/load_warranty_serial/load_serials.php /tmp/warranty_download_serial.csv /tmp/warranty_load_status.txt

View file

@ -1,4 +1,9 @@
#!/bin/bash #!/bin/bash
touch /tmp/warranty_download_serial.txt proc_date=`date +%m-%d-%y -d "1 day ago"`
/usr/bin/php /var/www/resq/utils/get_warranty_serial/get_serials.php download_file="/tmp/warranty_download_serial_$proc_date.csv"
/usr/bin/php /var/www/resq/utils/load_warranty_serial/load_serials.php /tmp/warranty_download_serial.txt "mysql:host=172.18.203.191:3306;dbname=resq;charset=UTF8" resq Motolite456 load_status_file="/tmp/warranty_load_status_$proc_date.txt"
#echo $download_file
#echo $load_status_file
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php $proc_date $download_file 1
/usr/bin/php /var/www/resq/utils/load_warranty_serial/load_serials.php $download_file $load_status_file

View file

@ -0,0 +1,40 @@
#!/bin/bash
touch /tmp/warranty_download_serial.csv
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-03-21 /tmp/warranty_download_serial.csv 1
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-04-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-05-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-06-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-07-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-08-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-09-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-10-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-11-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-12-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-13-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-14-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-15-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-16-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-17-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-18-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-19-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-20-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-21-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-22-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-23-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-24-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-25-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-26-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-27-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-28-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-29-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-30-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 05-31-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-01-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-02-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-03-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-04-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-05-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-06-21 /tmp/warranty_download_serial.csv 0
/usr/bin/php /var/www/resq/utils/get_warranty_serial/new_get_serials.php 06-07-21 /tmp/warranty_download_serial.csv 0
touch /tmp/warranty_load_status.txt
/usr/bin/php /var/www/resq/utils/load_warranty_serial/load_serials.php /tmp/warranty_download_serial.csv /tmp/warranty_load_status.txt