Compare commits

...

78 commits

Author SHA1 Message Date
c03c793d04 Add hash generator service and test command #639 2021-11-23 01:08:21 +08:00
26293e4239 Merge branch '560-display-category-name-if-sku-is-null-in-mobile' into 'master'
Resolve "Display category name if sku is null in mobile"

Closes #560

See merge request jankstudio/resq!665
2021-05-10 07:58:27 +00:00
Korina Cordero
317fd0fdf3 Display category name if sku is null. #560 2021-05-10 07:56:56 +00:00
292aae5fa9 Merge branch '559-wrong-link-to-edit-jo-form-in-dashboard-popup' into 'master'
Resolve "Wrong link to edit JO form in dashboard popup"

Closes #559

See merge request jankstudio/resq!664
2021-05-10 07:08:33 +00:00
Korina Cordero
c2be829653 Fix edit link for JO. #559 2021-05-10 07:06:39 +00:00
2f918c49cc Merge branch '551-check-for-null-sku-for-warranty' into 'master'
Add checking for sku. #551

Closes #551

See merge request jankstudio/resq!663
2021-05-10 06:26:48 +00:00
Korina Cordero
d02f0f7d51 Add checking for sku. #551 2021-05-10 06:25:59 +00:00
273cd0bd59 Merge branch '558-add-entities-and-ui-for-one-time-promo' into 'master'
Resolve "Add entities and UI for One Time Promo"

Closes #558

See merge request jankstudio/resq!661
2021-05-10 06:01:40 +00:00
Korina Cordero
02bf16e787 Add checking if invoice has items before getting customer tags. #558 2021-05-10 03:52:00 +00:00
Korina Cordero
d99bfedb01 Add promo logger service. #558 2021-05-10 03:36:54 +00:00
441553f90d Merge branch '555-log-warranty-data-sent-via-api' into 'master'
Fix the saving of warranty data. #555

Closes #555

See merge request jankstudio/resq!662
2021-05-07 07:55:11 +00:00
Korina Cordero
03360a2ae9 Add logging when one time discount has been availed for mobile. Add removal of promo from customer when one time discount has been availed for mobile. #558 2021-05-07 07:48:22 +00:00
Korina Cordero
df05316612 Add logging when one time discount has been availed. Add removal of promo from customer when one time discount has been availed. #558 2021-05-07 07:20:08 +00:00
Korina Cordero
23ca110a0b Fix the saving of warranty data. #555 2021-05-06 11:14:31 +00:00
Korina Cordero
f1c45af22e Add computation for customer tags in invoice. #558 2021-05-06 11:09:49 +00:00
Korina Cordero
c41c824744 Add the customer tag to JO form. #558 2021-05-06 06:55:34 +00:00
Korina Cordero
bbc0647925 Add tag details. #558 2021-05-06 03:45:51 +00:00
Korina Cordero
6ac92eba30 Add customer tags to customer form. #558 2021-05-05 10:33:46 +00:00
Korina Cordero
601b23afdf Add CRUD for customer tag. #558 2021-05-05 09:18:35 +00:00
Korina Cordero
59f29b223d Add entities for the customer tag and promo log. #558 2021-05-05 06:03:48 +00:00
5d5ccb6645 Merge branch '555-log-warranty-data-sent-via-api' into 'master'
Resolve "Log warranty data sent via API"

Closes #555

See merge request jankstudio/resq!658
2021-05-04 07:38:09 +00:00
Korina Cordero
63bc3a1aa6 Merge branch 'master' of gitlab.com:jankstudio/resq into 555-log-warranty-data-sent-via-api 2021-05-04 07:35:12 +00:00
0713bd9441 Merge branch '551-check-for-null-sku-for-warranty' into 'master'
Resolve "Check for null sku for warranty"

Closes #551

See merge request jankstudio/resq!654
2021-05-04 03:46:38 +00:00
Korina Cordero
f96540253a Added logging if blob download encounters errors. Add bulk download script. #551 2021-05-03 10:18:39 +00:00
Korina Cordero
b2e23e8ed9 Changed filename format for the file to retrieve. #551 2021-05-03 09:01:52 +00:00
Korina Cordero
87a9ec726e Composer update. #551 2021-05-03 06:56:18 +00:00
Korina Cordero
5c825ed9f4 Merge branch 'master' of gitlab.com:jankstudio/resq into 551-check-for-null-sku-for-warranty 2021-05-03 06:49:32 +00:00
Korina Cordero
c0a877e398 Add logging when creating warranty from command. #555 2021-04-30 10:30:44 +00:00
Korina Cordero
e235667952 Add logging for warranty creation for rider API and JO fulfillment. #555 2021-04-30 09:31:10 +00:00
Korina Cordero
c1d54ec626 Add logging when warranty is created via admin panel. #555 2021-04-30 08:45:18 +00:00
Korina Cordero
d2cae08fb0 Add logging for warranty creation in mobile API. #555 2021-04-30 08:12:00 +00:00
Korina Cordero
7ec5ba439c Add source to WarrantyAPILog. #555 2021-04-30 07:25:51 +00:00
Korina Cordero
42c2b52690 Merge branch 'master' of gitlab.com:jankstudio/resq into 555-log-warranty-data-sent-via-api 2021-04-30 06:34:13 +00:00
Korina Cordero
c6a0b96c90 Add action field to WarrantyAPILog. #555 2021-04-30 06:07:37 +00:00
22cd4c1320 Merge branch '556-enable-logging-via-monolog' into 'master'
Fix send sms bug causing 500 error #556

Closes #556

See merge request jankstudio/resq!660
2021-04-29 13:31:39 +00:00
d6357b32c7 Fix send sms bug causing 500 error #556 2021-04-29 21:31:03 +08:00
5432355e8b Merge branch '556-enable-logging-via-monolog' into 'master'
Resolve "Enable logging via monolog"

Closes #556

See merge request jankstudio/resq!659
2021-04-29 13:24:49 +00:00
726ace3207 Add monolog to composer #556 2021-04-29 21:23:53 +08:00
Korina Cordero
22047911e5 Add logging for register. #555 2021-04-29 10:04:03 +00:00
Korina Cordero
18b0417403 Add logging for creation of warranty. #555 2021-04-29 08:11:13 +00:00
Korina Cordero
24806d8b42 Merge branch '551-check-for-null-sku-for-warranty' of gitlab.com:jankstudio/resq into 555-log-warranty-data-sent-via-api 2021-04-29 03:37:09 +00:00
09614a1296 Merge branch '554-additional-hub-filters' into 'master'
Resolve "Additional Hub Filters"

Closes #554

See merge request jankstudio/resq!657
2021-04-28 07:28:39 +00:00
Korina Cordero
50f5896014 Removing logging of no rider out of controller and into service. #554 2021-04-28 06:00:23 +00:00
Korina Cordero
4337864c2c Add filter for rider availability. #554 2021-04-28 03:45:33 +00:00
Korina Cordero
140ea8c738 Add emergency filter. #554 2021-04-27 09:38:29 +00:00
Korina Cordero
63b989034d Add payment method filter. #554 2021-04-27 08:25:08 +00:00
Korina Cordero
0717df5fff Add saving of payment methods for hub. Fix issues found with notification number. #554 2021-04-27 06:16:40 +00:00
Korina Cordero
12798e00be Add payment methods to hub entity and form. #554 2021-04-27 04:14:48 +00:00
Korina Cordero
01cdd7ef03 Add checking for mobile number. #553 2021-04-27 02:42:06 +00:00
Korina Cordero
3c9070673f Add sending of SMS to hub if hub gets filtered out for no stock. #553 2021-04-26 07:48:51 +00:00
Korina Cordero
3a5d57e35c Merge branch '543-autoassign-revisions' of gitlab.com:jankstudio/resq into 552-add-notification-number-to-hub 2021-04-26 03:06:01 +00:00
Korina Cordero
f24f3e2bb9 Add notification number to hub. #552 2021-04-23 06:07:21 +00:00
Korina Cordero
17f800196d Merge branch 'master' of gitlab.com:jankstudio/resq into 543-autoassign-revisions 2021-04-21 03:25:55 +00:00
Korina Cordero
f7983e4c1d Add hub round robin to requestJobOrder. #543 2021-04-21 03:22:51 +00:00
Korina Cordero
a13c364934 Fix issues found during testing of warranty creation. #551 2021-04-20 06:42:36 +00:00
Korina Cordero
c97755cce0 Allow setting of battery information to null. #551 2021-04-20 03:22:07 +00:00
Korina Cordero
00c65d1e56 Add checking for empty sku. #551 2021-04-19 10:30:56 +00:00
Korina Cordero
9e1d855433 Fix load serials script to save everything. #549 2021-04-19 06:16:13 +00:00
Korina Cordero
699c135f33 Add script to get file from motiv. #549 2021-04-16 05:44:01 +00:00
Korina Cordero
60a4d0bb60 Add script to get the warranty file from storage. #549 2021-04-13 07:20:09 +00:00
Korina Cordero
6bc24c4756 Remove checking for jo type in newRequestJobOrder. #543 2021-03-30 09:03:19 +00:00
Korina Cordero
789d376d91 Merge branch 'master' of gitlab.com:jankstudio/resq into 543-autoassign-revisions 2021-03-30 02:04:17 +00:00
Korina Cordero
a5aef93ccb Add logging of hub if hub has no available rider. #543 2021-03-22 07:16:30 +00:00
Korina Cordero
4966e7e0c6 Add logging for filtered hubs. #543 2021-03-17 07:12:25 +00:00
Korina Cordero
2db7c6791f Add entity for logging of filtered hubs. #543 2021-03-17 03:09:33 +00:00
Korina Cordero
0ecc55cf56 Have admin panel use the HubSelector service when getting closest hubs. #543 2021-03-16 09:31:19 +00:00
Korina Cordero
c69a18d89b Add command to reset hub jo count in redis. #543 2021-03-16 08:19:20 +00:00
Korina Cordero
50e15cd770 Update hub_jo_count when hub is assigned or reassigned via admin panel. #543 2021-03-16 07:50:18 +00:00
Korina Cordero
0115328801 Add arranging of hubs, based on job orders assigned to hub. #543 2021-03-16 06:33:40 +00:00
Korina Cordero
1abaad1727 Add HubDistributor service. #543 2021-03-15 10:09:11 +00:00
Korina Cordero
0f245e9038 Fixes to issues found during testing. #543 2021-03-15 08:32:37 +00:00
Korina Cordero
498c88ce38 Add jo type, date, and inventory filters. #543 2021-03-15 03:46:13 +00:00
Korina Cordero
de74290624 Rename inventory flag. Fix find function. #543 2021-03-12 11:43:39 +00:00
Korina Cordero
d812e34797 Fix compilation error. #543 2021-03-12 07:02:26 +00:00
Korina Cordero
9a6ca7ae5d Add inventory manager service to HubSelector. #543 2021-03-12 06:54:09 +00:00
Korina Cordero
156742ea3a Add functions for the queries in HubSelector. #543 2021-03-11 09:56:07 +00:00
Korina Cordero
4efef6d397 Add HubSelector service. #543 2021-03-10 10:49:31 +00:00
Korina Cordero
09d04a8a7e Add hub criteria object. #543 2021-03-10 08:27:23 +00:00
61 changed files with 6796 additions and 1631 deletions

View file

@ -57,6 +57,7 @@ COUNTRY_CODE=+insert_country_code_here
# redis hash # redis hash
LATEST_ACTIVE_JO=latest_active_jo LATEST_ACTIVE_JO=latest_active_jo
HUB_JO_KEY=hub_jo_count
# dashboard # dashboard
DASHBOARD_ENABLE=set_to_true_or_false DASHBOARD_ENABLE=set_to_true_or_false

View file

@ -10,10 +10,16 @@
"ext-iconv": "*", "ext-iconv": "*",
"catalyst/auth-bundle": "dev-master", "catalyst/auth-bundle": "dev-master",
"catalyst/menu-bundle": "dev-master", "catalyst/menu-bundle": "dev-master",
"composer/package-versions-deprecated": "1.11.99.4",
"creof/doctrine2-spatial": "^1.2", "creof/doctrine2-spatial": "^1.2",
"data-dog/audit-bundle": "^0.1.10", "data-dog/audit-bundle": "^0.1.10",
"doctrine/common": "^2",
"doctrine/doctrine-bundle": "^2",
"doctrine/doctrine-migrations-bundle": "^2",
"doctrine/orm": "^2",
"edwinhoksberg/php-fcm": "^1.0", "edwinhoksberg/php-fcm": "^1.0",
"guzzlehttp/guzzle": "^6.3", "guzzlehttp/guzzle": "^6.3",
"hashids/hashids": "^4.1",
"microsoft/azure-storage-blob": "^1.5", "microsoft/azure-storage-blob": "^1.5",
"predis/predis": "^1.1", "predis/predis": "^1.1",
"sensio/framework-extra-bundle": "^5.1", "sensio/framework-extra-bundle": "^5.1",
@ -25,9 +31,8 @@
"symfony/flex": "^1.0", "symfony/flex": "^1.0",
"symfony/framework-bundle": "^4.0", "symfony/framework-bundle": "^4.0",
"symfony/maker-bundle": "^1.0", "symfony/maker-bundle": "^1.0",
"symfony/orm-pack": "^1.0", "symfony/monolog-bundle": "^3.7",
"symfony/process": "^4.0", "symfony/process": "^4.0",
"symfony/profiler-pack": "^1.0",
"symfony/security-bundle": "^4.0", "symfony/security-bundle": "^4.0",
"symfony/translation": "^4.0", "symfony/translation": "^4.0",
"symfony/twig-bundle": "^4.0", "symfony/twig-bundle": "^4.0",
@ -37,7 +42,9 @@
"require-dev": { "require-dev": {
"doctrine/doctrine-fixtures-bundle": "^3.0", "doctrine/doctrine-fixtures-bundle": "^3.0",
"symfony/dotenv": "^4.0", "symfony/dotenv": "^4.0",
"symfony/thanks": "^1.0" "symfony/stopwatch": "^4.0",
"symfony/thanks": "^1.0",
"symfony/web-profiler-bundle": "^4.0"
}, },
"config": { "config": {
"preferred-install": { "preferred-install": {

4374
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -488,3 +488,17 @@ access_keys:
label: Update label: Update
- id: sap_csize.delete - id: sap_csize.delete
label: Delete label: Delete
- id: customer_tag
label: Customer Tags Access
acls:
- id: customer_tag.menu
label: Menu
- id: customer_tag.list
label: List
- id: customer_tag.add
label: Add
- id: customer_tag.update
label: Update
- id: customer_tag.delete
label: Delete

View file

@ -14,4 +14,5 @@ return [
Catalyst\APIBundle\CatalystAPIBundle::class => ['all' => true], Catalyst\APIBundle\CatalystAPIBundle::class => ['all' => true],
Catalyst\AuthBundle\CatalystAuthBundle::class => ['all' => true], Catalyst\AuthBundle\CatalystAuthBundle::class => ['all' => true],
Catalyst\MenuBundle\CatalystMenuBundle::class => ['all' => true], Catalyst\MenuBundle\CatalystMenuBundle::class => ['all' => true],
Symfony\Bundle\MonologBundle\MonologBundle::class => ['all' => true],
]; ];

View file

@ -185,6 +185,10 @@ main_menu:
acl: static_content.list acl: static_content.list
label: Static Content label: Static Content
parent: support parent: support
- id: customertag_list
acl: customer_tag.list
label: Customer Tags
parent: support
- id: service - id: service
acl: service.menu acl: service.menu

View file

@ -0,0 +1,19 @@
monolog:
handlers:
main:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug
channels: ["!event"]
# uncomment to get logging in your browser
# you may have to allow bigger header sizes in your Web server configuration
#firephp:
# type: firephp
# level: info
#chromephp:
# type: chromephp
# level: info
console:
type: console
process_psr_3_messages: false
channels: ["!event", "!doctrine", "!console"]

View file

@ -0,0 +1,8 @@
# As of Symfony 5.1, deprecations are logged in the dedicated "deprecation" channel when it exists
#monolog:
# channels: [deprecation]
# handlers:
# deprecation:
# type: stream
# channels: [deprecation]
# path: php://stderr

View file

@ -0,0 +1,17 @@
monolog:
handlers:
main:
type: fingers_crossed
action_level: error
handler: nested
excluded_http_codes: [404, 405]
buffer_size: 50 # How many messages should be saved? Prevent memory leaks
nested:
type: stream
path: php://stderr
level: debug
formatter: monolog.formatter.json
console:
type: console
process_psr_3_messages: false
channels: ["!event", "!doctrine"]

View file

@ -0,0 +1,12 @@
monolog:
handlers:
main:
type: fingers_crossed
action_level: error
handler: nested
excluded_http_codes: [404, 405]
channels: ["!event"]
nested:
type: stream
path: "%kernel.logs_dir%/%kernel.environment%.log"
level: debug

View file

@ -0,0 +1,34 @@
customertag_list:
path: /customer_tags
controller: App\Controller\CustomerTagController::index
customertag_rows:
path: /customer_tags/rows
controller: App\Controller\CustomerTagController::rows
methods: [POST]
customertag_create:
path: /customer_tags/create
controller: App\Controller\CustomerTagController::addForm
methods: [GET]
customertag_create_submit:
path: /customer_tags/create
controller: App\Controller\CustomerTagController::addSubmit
methods: [POST]
customertag_update:
path: /customer_tags/{id}
controller: App\Controller\CustomerTagController::updateForm
methods: [GET]
customertag_update_submit:
path: /customer_tags/{id}
controller: App\Controller\CustomerTagController::updateSubmit
methods: [POST]
customertag_delete:
path: /customer_tags/{id}
controller: App\Controller\CustomerTagController::destroy
methods: [DELETE]

View file

@ -266,3 +266,31 @@ services:
event: 'postPersist' event: 'postPersist'
entity: 'App\Entity\CustomerVehicle' entity: 'App\Entity\CustomerVehicle'
# hub service
App\Service\HubSelector:
arguments:
$em: "@doctrine.orm.entity_manager"
$im: "@App\\Service\\InventoryManager"
$hub_distributor: "@App\\Service\\HubDistributor"
$hub_filter_logger: "@App\\Service\\HubFilterLogger"
# hub distributor
App\Service\HubDistributor:
arguments:
$redis: "@App\\Service\\RedisClientProvider"
$hub_jo_key: "%env(HUB_JO_KEY)%"
# hub filter logger
App\Service\HubFilterLogger:
arguments:
$em: "@doctrine.orm.entity_manager"
# warranty api logger
App\Service\WarrantyAPILogger:
arguments:
$em: "@doctrine.orm.entity_manager"
# promo logger
App\Service\PromoLogger:
arguments:
$em: "@doctrine.orm.entity_manager"

View file

@ -16,20 +16,25 @@ use App\Entity\JobOrder;
use App\Entity\Warranty; use App\Entity\Warranty;
use App\Entity\SAPBattery; use App\Entity\SAPBattery;
use App\Service\WarrantyAPILogger;
use App\Ramcar\ServiceType; use App\Ramcar\ServiceType;
use App\Ramcar\WarrantyStatus; use App\Ramcar\WarrantyStatus;
use App\Ramcar\WarrantySource;
use DoctrineExtensions\Query\Mysql\DateFormat; use DoctrineExtensions\Query\Mysql\DateFormat;
class GenerateWarrantyFromJobOrderCommand extends Command class GenerateWarrantyFromJobOrderCommand extends Command
{ {
protected $em; protected $em;
protected $logger;
protected $sapbatt_hash; protected $sapbatt_hash;
protected $warranties_hash; protected $warranties_hash;
public function __construct(EntityManagerInterface $em) public function __construct(EntityManagerInterface $em, WarrantyAPILogger $logger)
{ {
$this->em = $em; $this->em = $em;
$this->logger = $logger;
$this->loadSAPBatteries(); $this->loadSAPBatteries();
@ -209,7 +214,27 @@ class GenerateWarrantyFromJobOrderCommand extends 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) VALUES ' . $values . "\n";
echo $sql_statement; echo $sql_statement;
$db = $this->em->getConnection();
$stmt = $db->prepare($sql_statement);
$stmt->execute();
// log warranty creation
$log_data = [
'battery_model_id' => $bty_model_id,
'battery_size_id' => $bty_size_id,
'warranty_class' => $warranty_class,
'plate_number' => $cleaned_plate_number,
'date_create' => $date_create,
'date_purchase' => $date_purchase,
'date_expire' => $date_expire,
'sap_code' => $sap_code,
'first_name' => $first_name,
'last_name' => $last_name,
'mobile_number' => $mobile_number,
];
$this->logger->logWarrantyInfo($log_data, '', 'internal', 'create', WarrantySource::COMMAND);
} }
else else

View file

@ -0,0 +1,39 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use App\Service\RedisClientProvider;
class ResetHubJoCountCommand extends Command
{
protected $redis;
public function __construct(RedisClientProvider $redis)
{
$this->redis = $redis->getRedisClient();
parent::__construct();
}
protected function configure()
{
$this->setName('hub:jo:reset')
->setDescription('Reset hub\'s job order count')
->setHelp('Reset hub\'s job order count');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$key = 'hub_jo_count';
$this->redis->del($key);
return 0;
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use App\Service\HashGenerator;
class TestHashGeneratorCommand extends Command
{
protected $hash;
protected function configure()
{
$this->setName('test:hash')
->setDescription('Test hash generator.')
->setHelp('Test hash generator service.');
}
public function __construct(HashGenerator $hash)
{
$this->hash = $hash;
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$orig_id = 39095;
error_log('original id - ' . $orig_id);
$hash_id = $this->hash->getHash($orig_id);
error_log('hash id - ' . $hash_id);
$id = $this->hash->getID($hash_id);
error_log('id - ' . $id);
return 0;
}
}

View file

@ -28,6 +28,9 @@ use App\Ramcar\TradeInType;
use App\Ramcar\JOEventType; use App\Ramcar\JOEventType;
use App\Ramcar\AdvanceOrderSlot; use App\Ramcar\AdvanceOrderSlot;
use App\Ramcar\AutoAssignStatus; use App\Ramcar\AutoAssignStatus;
use App\Ramcar\HubCriteria;
use App\Ramcar\WillingToWaitContent;
use App\Ramcar\WarrantySource;
use App\Service\InvoiceGeneratorInterface; use App\Service\InvoiceGeneratorInterface;
use App\Service\RisingTideGateway; use App\Service\RisingTideGateway;
@ -37,6 +40,11 @@ use App\Service\RiderTracker;
use App\Service\MapTools; use App\Service\MapTools;
use App\Service\InventoryManager; use App\Service\InventoryManager;
use App\Service\RiderAssignmentHandlerInterface; use App\Service\RiderAssignmentHandlerInterface;
use App\Service\HubSelector;
use App\Service\HubDistributor;
use App\Service\HubFilterLogger;
use App\Service\WarrantyAPILogger;
use App\Service\PromoLogger;
use App\Entity\MobileSession; use App\Entity\MobileSession;
use App\Entity\Customer; use App\Entity\Customer;
@ -844,7 +852,9 @@ class APIController extends Controller implements LoggedController
public function requestJobOrder(Request $req, InvoiceGeneratorInterface $ic, GeofenceTracker $geo, public function requestJobOrder(Request $req, InvoiceGeneratorInterface $ic, GeofenceTracker $geo,
MapTools $map_tools, InventoryManager $im, MQTTClient $mclient, MapTools $map_tools, InventoryManager $im, MQTTClient $mclient,
RiderAssignmentHandlerInterface $rah) RiderAssignmentHandlerInterface $rah, HubSelector $hub_select,
HubDistributor $hub_dist, HubFilterLogger $hub_filter_logger,
PromoLogger $promo_logger)
{ {
// check required parameters and api key // check required parameters and api key
$required_params = [ $required_params = [
@ -917,6 +927,14 @@ class APIController extends Controller implements LoggedController
} }
$jo->setServiceType($stype); $jo->setServiceType($stype);
// check if willing to wait is true or not
$will_wait = $req->request->get('willing_to_wait');
// check for 'false' text
if ($will_wait === false || $will_wait === 0 || $will_wait === '0' || $will_wait == 'false')
$jo->setWillWait(WillingToWaitContent::NOT_WILLING_TO_WAIT);
else
$jo->setWillWait(WillingToWaitContent::WILLING_TO_WAIT);
// validate warranty // validate warranty
$warr = $req->request->get('warranty'); $warr = $req->request->get('warranty');
if (!WarrantyClass::validate($warr)) if (!WarrantyClass::validate($warr))
@ -1009,49 +1027,73 @@ class APIController extends Controller implements LoggedController
$invoice = $ic->generateInvoice($icrit); $invoice = $ic->generateInvoice($icrit);
$jo->setInvoice($invoice); $jo->setInvoice($invoice);
// assign hub and rider
if (($jo->getServiceType() == ServiceType::BATTERY_REPLACEMENT_NEW) || // TODO: set this properly, since the other flags
($jo->getServicetype() == ServiceType::BATTERY_REPLACEMENT_WARRANTY)) // are on default values
$hub_criteria = new HubCriteria();
$hub_criteria->setPoint($jo->getCoordinates())
->setJoType($jo->getServiceType());
// add battery to items
$sku = $batt->getSAPCode();
if (!empty($sku))
$hub_criteria->addItem($batt->getSAPCode(), 1);
// add payment method to criteria
if (!empty($jo->getModeOfPayment()))
$hub_criteria->setPaymentMethod($jo->getModeOfPayment());
// check if willing to wait is true or not
if ($jo->getWillWait() == WillingToWaitContent::NOT_WILLING_TO_WAIT)
{ {
// get nearest hub $hub_criteria->setEmergency(true);
// $nearest_hub = $this->findNearestHubWithInventory($jo, $batt, $em, $map_tools, $im);
$nearest_hub = $this->findNearestHub($jo, $em, $map_tools);
}
else
{
$nearest_hub = $this->findNearestHub($jo, $em, $map_tools);
} }
if (!empty($nearest_hub)) // find nearest hubs
$nearest_hubs = $hub_select->find($hub_criteria);
if (!empty($nearest_hubs))
{ {
// go through the hub list, find the nearest hub
// with an available rider
//error_log('found nearest hub ' . $nearest_hub->getID()); //error_log('found nearest hub ' . $nearest_hub->getID());
// assign rider foreach ($nearest_hubs as $nearest_hub)
$available_riders = $nearest_hub->getAvailableRiders();
if (count($available_riders) > 0)
{ {
$assigned_rider = null; $available_riders = $nearest_hub['hub']->getAvailableRiders();
if (count($available_riders) > 1) if (count($available_riders) >= 1)
{ {
// TODO: the setting of riders into an array $assigned_rider = null;
// will no longer be necessary when the contents if (count($available_riders) == 1)
// of randomizeRider changes
$riders = [];
foreach ($available_riders as $rider)
{ {
$riders[] = $rider; $assigned_rider = $available_riders[0];
}
else
{
// TODO: the setting of riders into an array
// will no longer be necessary when the contents
// of randomizeRider changes
$riders = [];
foreach ($available_riders as $rider)
{
$riders[] = $rider;
}
$assigned_rider = $this->randomizeRider($riders);
} }
$assigned_rider = $this->randomizeRider($riders); $jo->setHub($nearest_hub['hub']);
} $jo->setRider($assigned_rider);
else $jo->setStatus(JOStatus::ASSIGNED);
$assigned_rider = $available_riders[0]; $jo->setStatusAutoAssign(AutoAssignStatus::HUB_AND_RIDER_ASSIGNED);
//error_log('found rider ' . $assigned_rider->getID());
$jo->setHub($nearest_hub);
$jo->setRider($assigned_rider);
$jo->setStatus(JOStatus::ASSIGNED);
$assigned_rider->setAvailable(false); $assigned_rider->setAvailable(false);
// update redis hub_jo_count for hub
$hub_dist->incrementJoCountForHub($nearest_hub['hub']);
// break out of loop
break;
}
} }
} }
@ -1120,6 +1162,37 @@ class APIController extends Controller implements LoggedController
'invoice' => $invoice_data 'invoice' => $invoice_data
]; ];
// check service type
if ($jo->getServiceType() == ServiceType::BATTERY_REPLACEMENT_NEW)
{
$customer = $cv->getCustomer();
$customer_tags = $customer->getCustomerTagObjects();
if (!empty($customer_tags))
{
foreach ($customer_tags as $customer_tag)
{
// TODO: not too comfy with this being hardcoded
if ($customer_tag->getID() == 'CAR_CLUB_PROMO')
{
// remove associated entity
$customer->removeCustomerTag($customer_tag);
// log the availment of promo from customer
$created_by = $req->query->get('api_key');;
$cust_id = $jo->getCustomer()->getID();
$cust_fname = $jo->getCustomer()->getFirstName();
$cust_lname = $jo->getCustomer()->getLastName();
$jo_id = $jo->getID();
$invoice_id = $jo->getInvoice()->getID();
// TODO: check if we store total price of invoice or just the discounted amount
$amount = $jo->getInvoice()->getTotalPrice();
$this->promo_logger->logPromoInfo($created_by, $cust_id, $cust_fname, $cust_lname, $jo_id,
$invoice_id, $amount);
}
}
}
}
// set data // set data
$res->setData($data); $res->setData($data);
@ -2330,7 +2403,9 @@ class APIController extends Controller implements LoggedController
public function newRequestJobOrder(Request $req, InvoiceGeneratorInterface $ic, GeofenceTracker $geo, public function newRequestJobOrder(Request $req, InvoiceGeneratorInterface $ic, GeofenceTracker $geo,
MapTools $map_tools, InventoryManager $im, MQTTClient $mclient, MapTools $map_tools, InventoryManager $im, MQTTClient $mclient,
RiderAssignmentHandlerInterface $rah) RiderAssignmentHandlerInterface $rah, HubSelector $hub_select,
HubDistributor $hub_dist, HubFilterLogger $hub_filter_logger,
PromoLogger $promo_logger)
{ {
// check required parameters and api key // check required parameters and api key
$required_params = [ $required_params = [
@ -2419,6 +2494,14 @@ class APIController extends Controller implements LoggedController
} }
$jo->setServiceType($stype); $jo->setServiceType($stype);
// check if willing to wait is true or not
$will_wait = $req->request->get('willing_to_wait');
// check for 'false' text
if ($will_wait === false || $will_wait === 0 || $will_wait === '0' || $will_wait == 'false')
$jo->setWillWait(WillingToWaitContent::NOT_WILLING_TO_WAIT);
else
$jo->setWillWait(WillingToWaitContent::WILLING_TO_WAIT);
// validate warranty // validate warranty
$warr = $req->request->get('warranty'); $warr = $req->request->get('warranty');
if (!WarrantyClass::validate($warr)) if (!WarrantyClass::validate($warr))
@ -2515,50 +2598,72 @@ class APIController extends Controller implements LoggedController
// check if hub is null // check if hub is null
if ($hub == null) if ($hub == null)
{ {
// find nearest hub // TODO: set this properly, since the other flags
if (($jo->getServiceType() == ServiceType::BATTERY_REPLACEMENT_NEW) || // are on default values
($jo->getServicetype() == ServiceType::BATTERY_REPLACEMENT_WARRANTY)) $hub_criteria = new HubCriteria();
$hub_criteria->setPoint($jo->getCoordinates())
->setJoType($jo->getServiceType());
// add battery to items
$sku = $batt->getSAPCode();
if (!empty($sku))
$hub_criteria->addItem($batt->getSAPCode(), 1);
// add payment method to criteria
if (!empty($jo->getModeOfPayment()))
$hub_criteria->setPaymentMethod($jo->getModeOfPayment());
// check if willing to wait is true or not
if ($jo->getWillWait() == WillingToWaitContent::NOT_WILLING_TO_WAIT)
{ {
// get nearest hub $hub_criteria->setEmergency(true);
// $nearest_hub = $this->findNearestHubWithInventory($jo, $batt, $em, $map_tools, $im);
$nearest_hub = $this->findNearestHub($jo, $em, $map_tools);
}
else
{
$nearest_hub = $this->findNearestHub($jo, $em, $map_tools);
} }
if (!empty($nearest_hub)) // find nearest hubs
$nearest_hubs = $hub_select->find($hub_criteria);
if (!empty($nearest_hubs))
{ {
// go through the hub list, find the nearest hub
// with an available rider
//error_log('found nearest hub ' . $nearest_hub->getID()); //error_log('found nearest hub ' . $nearest_hub->getID());
// assign rider foreach ($nearest_hubs as $nearest_hub)
$available_riders = $nearest_hub->getAvailableRiders();
if (count($available_riders) > 0)
{ {
$assigned_rider = null; $available_riders = $nearest_hub['hub']->getAvailableRiders();
if (count($available_riders) > 1) if (count($available_riders) >= 1)
{ {
// TODO: the setting of riders into an array $assigned_rider = null;
// will no longer be necessary when the contents if (count($available_riders) == 1)
// of randomizeRider changes
$riders = [];
foreach ($available_riders as $rider)
{ {
$riders[] = $rider; $assigned_rider = $available_riders[0];
}
else
{
// TODO: the setting of riders into an array
// will no longer be necessary when the contents
// of randomizeRider changes
$riders = [];
foreach ($available_riders as $rider)
{
$riders[] = $rider;
}
$assigned_rider = $this->randomizeRider($riders);
} }
$assigned_rider = $this->randomizeRider($riders); $jo->setHub($nearest_hub['hub']);
$jo->setRider($assigned_rider);
$jo->setStatus(JOStatus::ASSIGNED);
$jo->setStatusAutoAssign(AutoAssignStatus::HUB_AND_RIDER_ASSIGNED);
$assigned_rider->setAvailable(false);
// update redis hub_jo_count for hub
$hub_dist->incrementJoCountForHub($nearest_hub['hub']);
// break out of loop
break;
} }
else
$assigned_rider = $available_riders[0];
//error_log('found rider ' . $assigned_rider->getID());
$jo->setHub($nearest_hub);
$jo->setRider($assigned_rider);
$jo->setStatus(JOStatus::ASSIGNED);
$jo->setStatusAutoAssign(AutoAssignStatus::HUB_AND_RIDER_ASSIGNED);
$assigned_rider->setAvailable(false);
} }
} }
} }
@ -2581,7 +2686,10 @@ class APIController extends Controller implements LoggedController
$jo->setStatusAutoAssign(AutoAssignStatus::HUB_ASSIGNED); $jo->setStatusAutoAssign(AutoAssignStatus::HUB_ASSIGNED);
if ($date_schedule != null) if ($date_schedule != null)
$jo->setDateSchedule($date_schedule); $jo->setDateSchedule($date_schedule);
// update redis hub_jo_count for hub
$hub_dist->incrementJoCountForHub($hub);
} }
$em->persist($jo); $em->persist($jo);
@ -2666,6 +2774,38 @@ class APIController extends Controller implements LoggedController
'invoice' => $invoice_data 'invoice' => $invoice_data
]; ];
// need to check for customer tag/promo
// check service type
if ($jo->getServiceType() == ServiceType::BATTERY_REPLACEMENT_NEW)
{
$customer = $cv->getCustomer();
$customer_tags = $customer->getCustomerTagObjects();
if (!empty($customer_tags))
{
foreach ($customer_tags as $customer_tag)
{
// TODO: not too comfy with this being hardcoded
if ($customer_tag->getID() == 'CAR_CLUB_PROMO')
{
// remove associated entity
$customer->removeCustomerTag($customer_tag);
// log the availment of promo from customer
$created_by = $req->query->get('api_key');;
$cust_id = $jo->getCustomer()->getID();
$cust_fname = $jo->getCustomer()->getFirstName();
$cust_lname = $jo->getCustomer()->getLastName();
$jo_id = $jo->getID();
$invoice_id = $jo->getInvoice()->getID();
// TODO: check if we store total price of invoice or just the discounted amount
$amount = $jo->getInvoice()->getTotalPrice();
$promo_logger->logPromoInfo($created_by, $cust_id, $cust_fname, $cust_lname, $jo_id,
$invoice_id, $amount);
}
}
}
}
// set data // set data
$res->setData($data); $res->setData($data);
@ -2856,8 +2996,8 @@ class APIController extends Controller implements LoggedController
'date_purchase' => $date_purchase_cust, 'date_purchase' => $date_purchase_cust,
'invoice' => $invoice_url, 'invoice' => $invoice_url,
'warr_card' => $warr_card_url, 'warr_card' => $warr_card_url,
'dealer_name' => $warr->getDealerName() ?? '', 'dealer_name' => $warr->getDealerName() ?? '',
'dealer_address' => $warr->getDealerAddress() ?? '', 'dealer_address' => $warr->getDealerAddress() ?? '',
]; ];
} }
else else
@ -2877,8 +3017,8 @@ class APIController extends Controller implements LoggedController
'date_purchase' => $today->format('Y-m-d'), 'date_purchase' => $today->format('Y-m-d'),
'invoice' => '', 'invoice' => '',
'warr_card' => '', 'warr_card' => '',
'dealer_name' => '', 'dealer_name' => '',
'dealer_address' => '', 'dealer_address' => '',
]; ];
} }
} }
@ -2905,7 +3045,17 @@ class APIController extends Controller implements LoggedController
} }
$sku = $warr_serial->getSKU(); $sku = $warr_serial->getSKU();
$batt = $em->getRepository(SAPBattery::class)->find($sku); $batt = null;
$cat_name = '';
if ($sku != null)
$batt = $em->getRepository(SAPBattery::class)->find($sku);
else
{
// get the category name of the serial
$cat_name = $warr_serial->getMetaInfo('category_name');
error_log($cat_name);
}
// TODO: put this in a config file // TODO: put this in a config file
$image_url = $req->getSchemeAndHttpHost() . '/battery/generic.png'; $image_url = $req->getSchemeAndHttpHost() . '/battery/generic.png';
if ($batt != null) if ($batt != null)
@ -2919,7 +3069,7 @@ class APIController extends Controller implements LoggedController
else else
{ {
$battery = [ $battery = [
'brand' => '', 'brand' => $cat_name,
'size' => '', 'size' => '',
'image_url' => '', 'image_url' => '',
]; ];
@ -2979,7 +3129,8 @@ class APIController extends Controller implements LoggedController
return $serial . '/' . $filename; return $serial . '/' . $filename;
} }
public function warrantyRegister($serial, EntityManagerInterface $em, Request $req, KernelInterface $kernel, RisingTideGateway $rt, TranslatorInterface $trans) public function warrantyRegister($serial, EntityManagerInterface $em, Request $req, KernelInterface $kernel, RisingTideGateway $rt,
TranslatorInterface $trans, WarrantyAPILogger $logger)
{ {
// check required parameters and api key // check required parameters and api key
$required_params = [ $required_params = [
@ -3001,22 +3152,37 @@ class APIController extends Controller implements LoggedController
$inv_filename = $this->handlePictureUpload($invoice, $upload_dir, $serial, 'invoice'); $inv_filename = $this->handlePictureUpload($invoice, $upload_dir, $serial, 'invoice');
$wcard_filename = $this->handlePictureUpload($warr_card, $upload_dir, $serial, 'wcard'); $wcard_filename = $this->handlePictureUpload($warr_card, $upload_dir, $serial, 'wcard');
$user_id = $req->query->get('api_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';
$source = WarrantySource::MOBILE;
$res = $this->checkParamsAndKey($req, $em, $required_params); $res = $this->checkParamsAndKey($req, $em, $required_params);
if ($res->isError()) if ($res->isError())
{
$logger->logWarrantyInfo($log_data, $res->getErrorMessage(), $user_id, $action, $source);
return $res->getReturnResponse(); return $res->getReturnResponse();
}
// update customer information // update customer information
// $cust = $this->updateCustomerInfo($req, $em); // $cust = $this->updateCustomerInfo($req, $em);
// update warranty // update warranty
$res = $this->updateWarranty($res, $em, $trans, $req, $serial, $inv_filename, $wcard_filename); $res = $this->updateWarranty($res, $em, $rt, $trans, $req, $serial, $inv_filename, $wcard_filename,
$logger, $log_data, $user_id, $action, $source);
$em->flush(); $em->flush();
return $res->getReturnResponse(); return $res->getReturnResponse();
} }
protected function updateWarranty($res, $em, $trans, $req, $serial, $inv_filename = null, $wcard_filename = null) protected function updateWarranty($res, $em, $rt, $trans, $req, $serial, $inv_filename = null, $wcard_filename = null,
$logger, $log_data, $user_id, $action, $source)
{ {
// get serial // get serial
$warr_serial = $em->getRepository(WarrantySerial::class)->find($serial); $warr_serial = $em->getRepository(WarrantySerial::class)->find($serial);
@ -3024,6 +3190,7 @@ class APIController extends Controller implements LoggedController
{ {
$res->setError(true) $res->setError(true)
->setErrorMessage('Invalid warranty serial code.'); ->setErrorMessage('Invalid warranty serial code.');
$logger->logWarrantyInfo($log_data, $res->getErrorMessage(), $user_id, $action, $source);
return $res; return $res;
} }
@ -3048,7 +3215,8 @@ class APIController extends Controller implements LoggedController
if (!$is_customer_warranty) if (!$is_customer_warranty)
{ {
$res->setError(true) $res->setError(true)
->setErrorMessage('Warranty registred to a vehicle not in your list of vehicles.'); ->setErrorMessage('Warranty registered to a vehicle not in your list of vehicles.');
$logger->logWarrantyInfo($log_data, $res->getErrorMessage(), $user_id, $action, $source);
return $res; return $res;
} }
@ -3060,14 +3228,20 @@ class APIController extends Controller implements LoggedController
$sms_msg = $trans->trans('warranty_register_confirm'); $sms_msg = $trans->trans('warranty_register_confirm');
} }
// check if sku is null
// get sap battery // get sap battery
$sku = $warr_serial->getSKU(); $sku = $warr_serial->getSKU();
$sap_bty = $em->getRepository(SAPBattery::class)->find($sku); $sap_bty = null;
if ($sap_bty == null) if ($sku != null)
{ {
$res->setError(true) $sap_bty = $em->getRepository(SAPBattery::class)->find($sku);
->setErrorMessage('Could not find battery entry for warranty.'); if ($sap_bty == null)
return $res; {
$res->setError(true)
->setErrorMessage('Could not find battery entry for warranty.');
$logger->logWarrantyInfo($log_data, $res->getErrorMessage(), $user_id, $action, $source);
return $res;
}
} }
// default date purchase to today // default date purchase to today
@ -3080,6 +3254,7 @@ class APIController extends Controller implements LoggedController
{ {
$res->setError(true) $res->setError(true)
->setErrorMessage('Invalid date format for date of purchase.'); ->setErrorMessage('Invalid date format for date of purchase.');
$logger->logWarrantyInfo($log_data, $res->getErrorMessage(), $user_id, $action, $source);
return $res; return $res;
} }
@ -3124,6 +3299,8 @@ class APIController extends Controller implements LoggedController
// set data to retrun to user // set data to retrun to user
$res->setData($data); $res->setData($data);
$logger->logWarrantyInfo($log_data, '', $user_id, $action, $source);
// send sms // send sms
error_log('sending sms to - ' . $this->session->getPhoneNumber()); error_log('sending sms to - ' . $this->session->getPhoneNumber());
$rt->sendSMS($this->session->getPhoneNumber(), 'MOTOLITE', $sms_msg); $rt->sendSMS($this->session->getPhoneNumber(), 'MOTOLITE', $sms_msg);

View file

@ -14,6 +14,7 @@ use Catalyst\APIBundle\Controller\APIController;
use Catalyst\APIBundle\Response\APIResponse; use Catalyst\APIBundle\Response\APIResponse;
use App\Service\RisingTideGateway; use App\Service\RisingTideGateway;
use App\Service\WarrantyAPILogger;
use App\Entity\WarrantySerial; use App\Entity\WarrantySerial;
use App\Entity\Warranty; use App\Entity\Warranty;
@ -32,6 +33,7 @@ use App\Ramcar\WarrantyClass;
use App\Ramcar\WarrantyStatus; use App\Ramcar\WarrantyStatus;
use App\Ramcar\FuelType; use App\Ramcar\FuelType;
use App\Ramcar\VehicleStatusCondition; use App\Ramcar\VehicleStatusCondition;
use App\Ramcar\WarrantySource;
use DateTime; use DateTime;
@ -73,13 +75,14 @@ class CustomerWarrantyController extends APIController
return $missing; return $missing;
} }
protected function checkRequiredParams(Request $req, $params) protected function checkRequiredParams(Request $req, $params, $logger, $log_data, $user_id, $action, $source)
{ {
// check required parameters // check required parameters
$missing = $this->checkMissingParameters($req, $params); $missing = $this->checkMissingParameters($req, $params);
if (count($missing) > 0) if (count($missing) > 0)
{ {
$miss_string = implode(', ', $missing); $miss_string = implode(', ', $missing);
$logger->logWarrantyInfo($log_data, 'Missing parameter(s): ' . $miss_string, $user_id, $action, $source);
return new APIResponse(false, 'Missing parameter(s): ' . $miss_string); return new APIResponse(false, 'Missing parameter(s): ' . $miss_string);
} }
@ -96,16 +99,32 @@ class CustomerWarrantyController extends APIController
return preg_replace('/\s+/', '', strtoupper($plate_num)); return preg_replace('/\s+/', '', strtoupper($plate_num));
} }
public function check($serial, EntityManagerInterface $em, Request $req) public function check($serial, EntityManagerInterface $em, Request $req, WarrantyAPILogger $logger)
{ {
$user_id = $_SERVER['HTTP_X_CATA_API_KEY'];
$log_data = [
'serial' => $serial,
];
$action = 'check';
$source = WarrantySource::CAPI;
// check required parameters // check required parameters
$required_params = []; $required_params = [];
$res = $this->checkRequiredParams($req, $required_params); $res = $this->checkRequiredParams($req, $required_params, $logger, $log_data, $user_id, $action, $source);
if (!$res) if (!$res)
return $res; return $res;
error_log('check warranty serial'); error_log('check warranty serial');
//$keys = array_keys($_SERVER);
//foreach ($keys as $key)
//{
// error_log($key);
//}
//error_log($_SERVER['HTTP_X_CATA_API_KEY']);
// TODO: add logging for the other scenarios
// check if warranty serial is there // check if warranty serial is there
$warr_serial = $em->getRepository(WarrantySerial::class)->find($serial); $warr_serial = $em->getRepository(WarrantySerial::class)->find($serial);
$warr = $em->getRepository(Warranty::class)->findOneBy(['serial' => $serial]); $warr = $em->getRepository(Warranty::class)->findOneBy(['serial' => $serial]);
@ -232,7 +251,18 @@ class CustomerWarrantyController extends APIController
} }
$sku = $warr_serial->getSKU(); $sku = $warr_serial->getSKU();
$batt = $em->getRepository(SAPBattery::class)->find($sku); // check if sku is null
$batt = null;
$cat_name = '';
if ($sku != null)
$batt = $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 // TODO: put this in a config file
$image_url = $req->getSchemeAndHttpHost() . '/battery/generic.png'; $image_url = $req->getSchemeAndHttpHost() . '/battery/generic.png';
if ($batt != null) if ($batt != null)
@ -246,7 +276,7 @@ class CustomerWarrantyController extends APIController
else else
{ {
$battery = [ $battery = [
'brand' => '', 'brand' => $cat_name,
'size' => '', 'size' => '',
'image_url' => '', 'image_url' => '',
]; ];
@ -275,18 +305,40 @@ class CustomerWarrantyController extends APIController
} }
public function register($serial, EntityManagerInterface $em, Request $req, KernelInterface $kernel, RisingTideGateway $rt, TranslatorInterface $trans) public function register($serial, EntityManagerInterface $em, Request $req, KernelInterface $kernel, RisingTideGateway $rt, TranslatorInterface $trans,
WarrantyAPILogger $logger)
{ {
error_log('HERE - register'); error_log('HERE - register');
// check required parameters // check required parameters
// TODO: maybe add vmake_id? since warranty cannot be created with no vmake
// TODO: maye also add mobile and email since customer creation won't let mobile and email be null
// set up information for logging
// get user from header
$user_id = $_SERVER['HTTP_X_CATA_API_KEY'];
$log_data = [
'serial' => $serial,
'plate_number' => $req->request->get('plate_num'),
'first_name' => $req->request->get('first_name'),
'last_name' => $req->request->get('last_name'),
'vmake_id' => $req->request->get('vmake_id'),
'contact_number' => $req->request->get('contact_num'),
'email' => $req->request->get('email'),
'invoice' => $req->request->get('invoice'),
];
$action = 'create/update';
$source = WarrantySource::CAPI;
error_log('SOURCE: ' . $source);
$required_params = [ $required_params = [
'first_name', 'first_name',
'last_name', 'last_name',
'plate_num' 'plate_num'
]; ];
$res = $this->checkRequiredParams($req, $required_params); $res = $this->checkRequiredParams($req, $required_params, $logger, $log_data, $user_id, $action, $source);
if (!$res)
return $res; if (!$res)
return $res;
// file uploads // file uploads
$invoice = $req->files->get('invoice'); $invoice = $req->files->get('invoice');
@ -299,12 +351,13 @@ class CustomerWarrantyController extends APIController
$wcard_filename = $this->handlePictureUpload($warr_card, $upload_dir, $serial, 'wcard'); $wcard_filename = $this->handlePictureUpload($warr_card, $upload_dir, $serial, 'wcard');
// do actual registering // do actual registering
$res = $this->updateWarranty($em, $rt, $trans, $req, $serial, $inv_filename, $wcard_filename); $res = $this->updateWarranty($em, $rt, $trans, $req, $serial, $inv_filename, $wcard_filename,
$logger, $log_data, $user_id, $action, $source);
// flush to db // flush to db
$em->flush(); $em->flush();
return $res; return $res;
return new APIResponse(true, 'Warranty registered.'); return new APIResponse(true, 'Warranty registered.');
} }
@ -340,7 +393,8 @@ class CustomerWarrantyController extends APIController
return $serial . '/' . $filename; return $serial . '/' . $filename;
} }
protected function updateWarranty($em, $rt, $trans, $req, $serial, $inv_filename = null, $wcard_filename = null) protected function updateWarranty($em, $rt, $trans, $req, $serial, $inv_filename = null, $wcard_filename = null,
$logger, $log_data, $user_id, $action, $source)
{ {
$plate_num = $this->cleanPlateNumber($req->request->get('plate_num')); $plate_num = $this->cleanPlateNumber($req->request->get('plate_num'));
@ -349,6 +403,7 @@ class CustomerWarrantyController extends APIController
$warr_serial = $em->getRepository(WarrantySerial::class)->find($serial); $warr_serial = $em->getRepository(WarrantySerial::class)->find($serial);
if ($warr_serial == null) if ($warr_serial == null)
{ {
$logger->logWarrantyInfo($log_data, 'Invalid warranty serial code..', $user_id, $action, $source);
return new APIResponse(false, 'Invalid warranty serial code.'); return new APIResponse(false, 'Invalid warranty serial code.');
} }
@ -364,6 +419,7 @@ class CustomerWarrantyController extends APIController
if ($plate_num != $warr_plate_num) if ($plate_num != $warr_plate_num)
{ {
$logger->logWarrantyInfo($log_data, 'Plate number does not match vehicle registered to warranty.', $user_id, $action, $source);
return new APIResponse(false, 'Plate number does not match vehicle registered to warranty.'); return new APIResponse(false, 'Plate number does not match vehicle registered to warranty.');
} }
@ -381,10 +437,17 @@ class CustomerWarrantyController extends APIController
error_log('sap battery check'); error_log('sap battery check');
// get sap battery // get sap battery
$sku = $warr_serial->getSKU(); $sku = $warr_serial->getSKU();
$sap_bty = $em->getRepository(SAPBattery::class)->find($sku); $sap_bty = null;
if ($sap_bty == null)
// check if sku is null
if ($sku != null)
{ {
return new APIResponse(false, 'Could not find battery entry for warranty.'); $sap_bty = $em->getRepository(SAPBattery::class)->find($sku);
if ($sap_bty == null)
{
$logger->logWarrantyInfo($log_data, 'Cound not find battery entry for warranty.', $user_id, $action, $source);
return new APIResponse(false, 'Could not find battery entry for warranty.');
}
} }
// vehicle fetch // vehicle fetch
@ -395,6 +458,7 @@ class CustomerWarrantyController extends APIController
$vehicle = $em->getRepository(Vehicle::class)->find($vmake_id); $vehicle = $em->getRepository(Vehicle::class)->find($vmake_id);
if ($vehicle == null) if ($vehicle == null)
{ {
$logger->logWarrantyInfo($log_data, 'Could not find vehicle specified for warranty.', $user_id, $action, $source);
return new APIResponse(false, 'Could not find vehicle specified for warranty.'); return new APIResponse(false, 'Could not find vehicle specified for warranty.');
} }
} }
@ -403,15 +467,20 @@ class CustomerWarrantyController extends APIController
// default date purchase to today // default date purchase to today
// NOTE: might need to change this later // NOTE: might need to change this later
$date_pur = new DateTime(); $date_pur = new DateTime();
$date_pur_cust = new DateTime();
// get date purchase specified by customer // get date purchase specified by customer
$date_pur_cust = DateTime::createFromFormat('Y-m-d', $req->request->get('date_purchase')); if (!empty($req->request->get('date_purchase')))
if (!$date_pur_cust)
{ {
return new APIResponse(false, 'Invalid date format for date of purchase.'); $date_pur_cust = DateTime::createFromFormat('Y-m-d', $req->request->get('date_purchase'));
if (!$date_pur_cust)
{
$logger->logWarrantyInfo($log_data, 'Invalid date format for date of purchase.', $user_id, $action, $source);
return new APIResponse(false, 'Invalid date format for date of purchase.');
}
} }
// chstomer check // customer check
$priv_promo = $req->request->get('priv_promo', false); $priv_promo = $req->request->get('priv_promo', false);
if ($cust == null) if ($cust == null)
{ {
@ -483,14 +552,15 @@ class CustomerWarrantyController extends APIController
$em->persist($warr); $em->persist($warr);
$logger->logWarrantyInfo($log_data, '', $user_id, $action, $source);
// TODO: check if we need to do anyting else // TODO: check if we need to do anyting else
$data = []; $data = [];
// send sms confirmation // send sms confirmation
$this->sendSMSConfirmation($rt, $req->request->get('contact_num'), $sms_message); $this->sendSMSConfirmation($rt, $req->request->get('contact_num'), $sms_message);
return new APIResponse(true, 'Warranty registered.', $data); return new APIResponse(true, 'Warranty registered.', $data);
} }
protected function sendSMSConfirmation($rt, $num, $message) protected function sendSMSConfirmation($rt, $num, $message)

View file

@ -20,12 +20,16 @@ use App\Entity\PrivacyPolicy;
use App\Entity\Customer; use App\Entity\Customer;
use App\Entity\CustomerVehicle; use App\Entity\CustomerVehicle;
use App\Entity\Vehicle; use App\Entity\Vehicle;
use App\Entity\WarrantyAPILog;
use App\Service\WarrantyAPILogger;
use App\Ramcar\NameValue; use App\Ramcar\NameValue;
use App\Ramcar\WarrantyClass; use App\Ramcar\WarrantyClass;
use App\Ramcar\WarrantyStatus; use App\Ramcar\WarrantyStatus;
use App\Ramcar\FuelType; use App\Ramcar\FuelType;
use App\Ramcar\VehicleStatusCondition; use App\Ramcar\VehicleStatusCondition;
use App\Ramcar\WarrantySource;
use DateTime; use DateTime;
@ -142,7 +146,7 @@ class WarrantyController extends APIController
return new APIResponse(true, 'Warranties found.', $data); return new APIResponse(true, 'Warranties found.', $data);
} }
public function register(Request $req, EntityManagerInterface $em) public function register(Request $req, EntityManagerInterface $em, WarrantyAPILogger $logger)
{ {
$this->denyAccessUnlessGranted('warranty.register.battery', null, 'No access.'); $this->denyAccessUnlessGranted('warranty.register.battery', null, 'No access.');
@ -159,10 +163,6 @@ class WarrantyController extends APIController
'battery_size_id', 'battery_size_id',
*/ */
]; ];
$msg = $this->checkRequiredParameters($req, $params);
error_log('msg - ' . $msg);
if ($msg)
return new APIResponse(false, $msg);
$serial = $req->request->get('serial'); $serial = $req->request->get('serial');
$date_expire_string = $req->request->get('date_expire'); $date_expire_string = $req->request->get('date_expire');
@ -175,6 +175,31 @@ class WarrantyController extends APIController
$lname = $req->request->get('last_name', null); $lname = $req->request->get('last_name', null);
$mnum = $req->request->get('mobile_number', null); $mnum = $req->request->get('mobile_number', null);
// set up information for logging
// get user from header
$user_id = $_SERVER['HTTP_X_CATA_API_KEY'];
$log_data = [
'serial' => $serial,
'date_expire' => $date_expire_string,
'date_pur_string' => $date_pur_string,
'warranty_class' => $warr_class,
'plate_number' => $plate,
'sku' => $sku,
'first_name' => $fname,
'last_name' => $lname,
'mobile_number' => $mnum,
];
$action = 'create';
$source = WarrantySource::CAPI;
$msg = $this->checkRequiredParameters($req, $params);
error_log('msg - ' . $msg);
if ($msg)
{
$logger->logWarrantyInfo($log_data, $msg, $user_id, $action, $source);
return new APIResponse(false, $msg);
}
/* /*
$bmodel_id = $req->request->get('battery_model_id'); $bmodel_id = $req->request->get('battery_model_id');
$bsize_id = $req->request->get('battery_size_id'); $bsize_id = $req->request->get('battery_size_id');
@ -183,26 +208,47 @@ class WarrantyController extends APIController
// wrong date expire format // wrong date expire format
$date_expire = DateTime::createFromFormat('Ymd', $date_expire_string); $date_expire = DateTime::createFromFormat('Ymd', $date_expire_string);
if ($date_expire === false) if ($date_expire === false)
{
$logger->logWarrantyInfo($log_data, 'Wrong date format: date_expire.', $user_id, $action, $source);
return new APIResponse(false, 'Wrong date format: date_expire.'); return new APIResponse(false, 'Wrong date format: date_expire.');
}
// wrong date purchase format // wrong date purchase format
$date_pur = DateTime::createFromFormat('Ymd', $date_pur_string); $date_pur = DateTime::createFromFormat('Ymd', $date_pur_string);
if ($date_pur === false) if ($date_pur === false)
{
$logger->logWarrantyInfo($log_data, 'Wrong date format: date_purchase', $user_id, $action, $source);
return new APIResponse(false, 'Wrong date format: date_purchase.'); return new APIResponse(false, 'Wrong date format: date_purchase.');
}
// valid warranty class // valid warranty class
if (!WarrantyClass::validate($warr_class)) if (!WarrantyClass::validate($warr_class))
{
$logger->logWarrantyInfo($log_data, 'Invalid warranty class.', $user_id, $action, $source);
return new APIResponse(false, 'Invalid warranty class.'); return new APIResponse(false, 'Invalid warranty class.');
}
// plate number // plate number
$plate = Warranty::cleanPlateNumber($plate); $plate = Warranty::cleanPlateNumber($plate);
if (!$plate) if (!$plate)
{
$logger->logWarrantyInfo($log_data, 'Invalid plate number.', $user_id, $action, $source);
return new APIResponse(false, 'Invalid plate number.'); return new APIResponse(false, 'Invalid plate number.');
}
// battery // check if sku is blank
$batt = $em->getRepository(SAPBattery::class)->find($sku); if ((empty($sku)) || ($sku == null))
if ($batt == null) $batt = null;
return new APIResponse(false, 'Invalid battery SKU.'); else
{
// battery
$batt = $em->getRepository(SAPBattery::class)->find($sku);
if ($batt == null)
{
$logger->logWarrantyInfo($log_data, 'Invalid battery SKU.', $user_id, $action, $source);
return new APIResponse(false, 'Invalid battery SKU.');
}
}
/* /*
// battery model // battery model
@ -239,6 +285,7 @@ class WarrantyController extends APIController
} }
catch (UniqueConstraintViolationException $e) catch (UniqueConstraintViolationException $e)
{ {
$logger->logWarrantyInfo($log_data, 'Duplicate serial encountered.', $user_id, $action, $source);
return new APIResponse(false, 'Duplicate serial encountered.'); return new APIResponse(false, 'Duplicate serial encountered.');
} }
@ -247,10 +294,13 @@ class WarrantyController extends APIController
'warranty' => $this->generateWarrantyData($warr), 'warranty' => $this->generateWarrantyData($warr),
]; ];
// log creation of warranty data
$logger->logWarrantyInfo($log_data, '', $user_id, $action, $source);
return new APIResponse(true, 'Warranty registered.', $data); return new APIResponse(true, 'Warranty registered.', $data);
} }
public function claim(Request $req, EntityManagerInterface $em, $id) public function claim(Request $req, EntityManagerInterface $em, $id, WarrantyAPILogger $logger)
{ {
$this->denyAccessUnlessGranted('warranty.claim', null, 'No access.'); $this->denyAccessUnlessGranted('warranty.claim', null, 'No access.');
@ -258,26 +308,50 @@ class WarrantyController extends APIController
$params = [ $params = [
'serial', 'serial',
]; ];
$serial = $req->request->get('serial');
// set up information for logging
// get user from header
$user_id = $_SERVER['HTTP_X_CATA_API_KEY'];
$log_data = [
'serial' => $serial,
'id' => $id,
];
$action = 'claim';
$source = WarrantySource::CAPI;
$msg = $this->checkRequiredParameters($req, $params); $msg = $this->checkRequiredParameters($req, $params);
if ($msg) if ($msg)
{
$logger->logWarrantyInfo($log_data, $msg, $user_id, $action, $source);
return new APIResponse(false, $msg); return new APIResponse(false, $msg);
}
// no warranty // no warranty
$warr = $em->getRepository(Warranty::class)->find($id); $warr = $em->getRepository(Warranty::class)->find($id);
if ($warr == null) if ($warr == null)
{
$logger->logWarrantyInfo($log_data, 'No warranty found with that id.', $user_id, $action, $source);
return new APIResponse(false, 'No warranty found with that id.', null, 404); return new APIResponse(false, 'No warranty found with that id.', null, 404);
}
// warranty is not active // warranty is not active
if (!$warr->canClaim()) if (!$warr->canClaim())
{
$logger->logWarrantyInfo($log_data, 'Warranty is not active.', $user_id, $action, $source);
return new APIResponse(false, 'Warranty is not active.'); return new APIResponse(false, 'Warranty is not active.');
}
// check if new serial has been used // check if new serial has been used
$serial = $req->request->get('serial');
$clean_serial = $this->cleanSerial($serial); $clean_serial = $this->cleanSerial($serial);
$check_warr = $em->getRepository(Warranty::class)->findOneBy(['serial' => $clean_serial]); $check_warr = $em->getRepository(Warranty::class)->findOneBy(['serial' => $clean_serial]);
if ($check_warr != null) if ($check_warr != null)
{
$logger->logWarrantyInfo($log_data, 'Serial for replacement has already been used.', $user_id, $action, $source);
return new APIResponse(false, 'Serial for replacement has already been used.'); return new APIResponse(false, 'Serial for replacement has already been used.');
}
// set status to claim // set status to claim
$warr->setStatus(WarrantyStatus::CLAIMED) $warr->setStatus(WarrantyStatus::CLAIMED)
@ -303,6 +377,7 @@ class WarrantyController extends APIController
$em->flush(); $em->flush();
// TODO: claim log // TODO: claim log
$logger->logWarrantyInfo($log_data, '', $user_id, $action, $source);
return new APIResponse(true, 'Warranty claimed successfully.'); return new APIResponse(true, 'Warranty claimed successfully.');
} }
@ -382,10 +457,16 @@ class WarrantyController extends APIController
if (!$plate) if (!$plate)
return new APIResponse(false, 'Invalid plate number.'); return new APIResponse(false, 'Invalid plate number.');
// battery // check if sku is blank
$batt = $em->getRepository(SAPBattery::class)->find($sku); if ((empty($sku)) || ($sku == null))
if ($batt == null) $batt = null;
return new APIResponse(false, 'Invalid battery SKU.'); else
{
// battery
$batt = $em->getRepository(SAPBattery::class)->find($sku);
if ($batt == null)
return new APIResponse(false, 'Invalid battery SKU.');
}
$warr->setSerial($serial) $warr->setSerial($serial)
->setWarrantyClass($warr_class) ->setWarrantyClass($warr_class)
@ -634,6 +715,7 @@ 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
$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);
@ -691,5 +773,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,266 @@
<?php
namespace App\Controller;
use App\Entity\CustomerTag;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Catalyst\MenuBundle\Annotation\Menu;
use DateTime;
class CustomerTagController extends Controller
{
/**
* @Menu(selected="customer_tag_list")
*/
public function index()
{
$this->denyAccessUnlessGranted('customer_tag.list', null, 'No access.');
return $this->render('customer-tag/list.html.twig');
}
public function rows(Request $req)
{
$this->denyAccessUnlessGranted('customer_tag.list', null, 'No access.');
// get query builder
$qb = $this->getDoctrine()
->getRepository(CustomerTag::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();
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// add crud urls
if ($this->isGranted('customer_tag.update'))
$row['meta']['update_url'] = $this->generateUrl('customertag_update', ['id' => $row['id']]);
if ($this->isGranted('customer_tag.delete'))
$row['meta']['delete_url'] = $this->generateUrl('customertag_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
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')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
/**
* @Menu(selected="customer_tag_list")
*/
public function addForm()
{
$this->denyAccessUnlessGranted('customer_tag.add', null, 'No access.');
$params['obj'] = new CustomerTag();
$params['mode'] = 'create';
// response
return $this->render('customer-tag/form.html.twig', $params);
}
public function addSubmit(Request $req, ValidatorInterface $validator)
{
$this->denyAccessUnlessGranted('customer_tag.add', null, 'No access.');
// create new object
$em = $this->getDoctrine()->getManager();
$obj = new CustomerTag();
$tag_details = $req->request->get('tag_details');
$tag_details_json = json_decode($tag_details, true);
$obj->setID($req->request->get('id'))
->setName($req->request->get('name'))
->setTagDetails($tag_details_json);
// 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);
} else {
// validated! save the entity
$em->persist($obj);
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
}
/**
* @Menu(selected="customer_tag_list")
*/
public function updateForm($id)
{
$this->denyAccessUnlessGranted('customer_tag.update', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(CustomerTag::class)->find($id);
// make sure this row exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
$params['obj'] = $obj;
$params['mode'] = 'update';
// response
return $this->render('customer-tag/form.html.twig', $params);
}
public function updateSubmit(Request $req, ValidatorInterface $validator, $id)
{
$this->denyAccessUnlessGranted('customer_tag.update', null, 'No access.');
// get object data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(CustomerTag::class)->find($id);
// make sure this object exists
if (empty($obj))
throw $this->createNotFoundException('The item does not exist');
$tag_details = $req->request->get('tag_details');
$tag_details_json = json_decode($tag_details, true);
$obj->setID($req->request->get('id'))
->setName($req->request->get('name'))
->setTagDetails($tag_details_json);
// 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('customer_tag.delete', null, 'No access.');
// get object data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(CustomerTag::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();
}
}

View file

@ -17,8 +17,12 @@ use DateTime;
use Catalyst\MenuBundle\Annotation\Menu; use Catalyst\MenuBundle\Annotation\Menu;
use App\Service\MapTools;
use App\Service\RiderTracker; use App\Service\RiderTracker;
use App\Service\RisingTideGateway;
use App\Service\HubSelector;
use App\Ramcar\HubCriteria;
use App\Ramcar\ModeOfPayment;
class HubController extends Controller class HubController extends Controller
{ {
@ -128,6 +132,7 @@ class HubController extends Controller
$params = []; $params = [];
$params['obj'] = new Hub(); $params['obj'] = new Hub();
$params['mode'] = 'create'; $params['mode'] = 'create';
$params['payment_methods'] = ModeOfPayment::getCollection();
// response // response
return $this->render('hub/form.html.twig', $params); return $this->render('hub/form.html.twig', $params);
@ -154,7 +159,17 @@ class HubController extends Controller
->setBranchCode($req->request->get('branch_code', '')) ->setBranchCode($req->request->get('branch_code', ''))
->setStatusOpen($req->request->get('status_open', false)) ->setStatusOpen($req->request->get('status_open', false))
->setRiderSlots($req->request->get('rider_slots', 0)) ->setRiderSlots($req->request->get('rider_slots', 0))
->setHubViewFlag($req->request->get('flag_hub_view', false)); ->setHubViewFlag($req->request->get('flag_hub_view', false))
->setNotifNumber($req->request->get('notif_number'))
->clearPaymentMethods();
// set payment methods
$payment_methods = $req->request->get('payment_methods');
if (!empty($payment_methods))
{
$obj->setPaymentMethods($payment_methods);
}
} }
protected function setQueryFilters($datatable, QueryBuilder $query) protected function setQueryFilters($datatable, QueryBuilder $query)
@ -166,7 +181,7 @@ class HubController extends Controller
} }
} }
public function addSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator) public function addSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator, RisingTideGateway $rt)
{ {
$this->denyAccessUnlessGranted('hub.add', null, 'No access.'); $this->denyAccessUnlessGranted('hub.add', null, 'No access.');
@ -176,14 +191,23 @@ class HubController extends Controller
$em = $this->getDoctrine()->getManager(); $em = $this->getDoctrine()->getManager();
$obj = new Hub(); $obj = new Hub();
// initialize error list
$error_array = [];
// validate the notification number
$mobile = $req->request->get('notif_number');
if (!empty($mobile))
{
$is_valid = $rt->validatePhoneNumber($mobile);
if (!$is_valid)
$error_array['notif_number'] = 'Invalid notification number';
}
$this->setObject($obj, $req); $this->setObject($obj, $req);
// validate // validate
$errors = $validator->validate($obj); $errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// 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();
@ -226,12 +250,13 @@ class HubController extends Controller
$params = []; $params = [];
$params['obj'] = $obj; $params['obj'] = $obj;
$params['mode'] = 'update'; $params['mode'] = 'update';
$params['payment_methods'] = ModeOfPayment::getCollection();
// response // response
return $this->render('hub/form.html.twig', $params); return $this->render('hub/form.html.twig', $params);
} }
public function updateSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator, $id) public function updateSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator, $id, RisingTideGateway $rt)
{ {
$this->denyAccessUnlessGranted('hub.update', null, 'No access.'); $this->denyAccessUnlessGranted('hub.update', null, 'No access.');
@ -243,14 +268,23 @@ class HubController extends Controller
if (empty($obj)) if (empty($obj))
throw $this->createNotFoundException('The item does not exist'); throw $this->createNotFoundException('The item does not exist');
// initialize error list
$error_array = [];
// validate the notification number
$mobile = $req->request->get('notif_number');
if (!empty($mobile))
{
$is_valid = $rt->validatePhoneNumber($mobile);
if (!$is_valid)
$error_array['notif_number'] = 'Invalid notification number';
}
$this->setObject($obj, $req); $this->setObject($obj, $req);
// validate // validate
$errors = $validator->validate($obj); $errors = $validator->validate($obj);
// initialize error list
$error_array = [];
// 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();
@ -295,7 +329,7 @@ class HubController extends Controller
$response->send(); $response->send();
} }
public function nearest(MapTools $map_tools, Request $req) public function nearest(HubSelector $hub_selector, Request $req)
{ {
// get lat / long // get lat / long
$lat = $req->query->get('lat'); $lat = $req->query->get('lat');
@ -303,7 +337,12 @@ class HubController extends Controller
// get nearest hubs according to position // get nearest hubs according to position
$point = new Point($long, $lat); $point = new Point($long, $lat);
$result = $map_tools->getClosestHubs($point, 10, date("H:i:s"));
// set up hub criteria
$hub_criteria = new HubCriteria();
$hub_criteria->setPoint($point);
$hub_selector->find($hub_criteria);
//$result = $map_tools->getClosestHubs($point, 10, date("H:i:s"));
$hubs = []; $hubs = [];
foreach ($result as $hub_res) foreach ($result as $hub_res)

View file

@ -23,6 +23,7 @@ use App\Service\MapTools;
use App\Service\MQTTClient; use App\Service\MQTTClient;
use App\Service\APNSClient; use App\Service\APNSClient;
use App\Service\InventoryManager; use App\Service\InventoryManager;
use App\Service\HubSelector;
use App\Service\RiderTracker; use App\Service\RiderTracker;
use App\Service\MotivConnector; use App\Service\MotivConnector;
@ -315,13 +316,13 @@ class JobOrderController extends Controller
/** /**
* @Menu(selected="jo_proc") * @Menu(selected="jo_proc")
*/ */
public function processingForm(MapTools $map_tools, $id, JobOrderHandlerInterface $jo_handler, GISManagerInterface $gis, MotivConnector $motiv) public function processingForm(HubSelector $hub_selector, $id, JobOrderHandlerInterface $jo_handler, GISManagerInterface $gis, MotivConnector $motiv)
{ {
$this->denyAccessUnlessGranted('jo_proc.list', null, 'No access.'); $this->denyAccessUnlessGranted('jo_proc.list', null, 'No access.');
try try
{ {
$params = $jo_handler->initializeProcessingForm($id, $map_tools, $motiv); $params = $jo_handler->initializeProcessingForm($id, $hub_selector, $motiv);
} }
catch (AccessDeniedHttpException $e) catch (AccessDeniedHttpException $e)
{ {
@ -504,14 +505,14 @@ class JobOrderController extends Controller
/** /**
* @Menu(selected="jo_open") * @Menu(selected="jo_open")
*/ */
public function openHubForm(MapTools $map_tools, $id, JobOrderHandlerInterface $jo_handler, public function openHubForm(HubSelector $hub_selector, $id, JobOrderHandlerInterface $jo_handler,
GISManagerInterface $gis) GISManagerInterface $gis)
{ {
$this->denyAccessUnlessGranted('jo_open.list', null, 'No access.'); $this->denyAccessUnlessGranted('jo_open.list', null, 'No access.');
try try
{ {
$params = $jo_handler->initializeHubForm($id, $map_tools); $params = $jo_handler->initializeHubForm($id, $hub_selector);
} }
catch (NotFoundHttpException $e) catch (NotFoundHttpException $e)
{ {
@ -1204,6 +1205,7 @@ class JobOrderController extends Controller
]); ]);
} }
// this is uncalled or does not display in admin panel
/** /**
* @Menu(selected="jo_autoassign") * @Menu(selected="jo_autoassign")
*/ */
@ -1223,6 +1225,7 @@ class JobOrderController extends Controller
return $this->render($template, $params); return $this->render($template, $params);
} }
// this is uncalled or does not display in admin panel
public function autoAssignSubmit(Request $req, JobOrderHandlerInterface $jo_handler, public function autoAssignSubmit(Request $req, JobOrderHandlerInterface $jo_handler,
EntityManagerInterface $em, MapTools $map_tools, EntityManagerInterface $em, MapTools $map_tools,
InventoryManager $im) InventoryManager $im)

View file

@ -12,8 +12,10 @@ use App\Entity\CustomerVehicle;
use App\Ramcar\WarrantyClass; use App\Ramcar\WarrantyClass;
use App\Ramcar\WarrantyStatus; use App\Ramcar\WarrantyStatus;
use App\Ramcar\WarrantySource;
use App\Service\WarrantyHandler; use App\Service\WarrantyHandler;
use App\Service\WarrantyAPILogger;
use Doctrine\ORM\Query; use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\EntityManagerInterface;
@ -149,7 +151,7 @@ class WarrantyController extends Controller
return $this->render('warranty/form.html.twig', $params); return $this->render('warranty/form.html.twig', $params);
} }
public function addSubmit(Request $req, ValidatorInterface $validator) public function addSubmit(Request $req, ValidatorInterface $validator, WarrantyAPILogger $logger)
{ {
$this->denyAccessUnlessGranted('warranty.add', null, 'No access.'); $this->denyAccessUnlessGranted('warranty.add', null, 'No access.');
@ -181,31 +183,52 @@ class WarrantyController extends Controller
} }
// custom validation for battery model // custom validation for battery model
$model = $em->getRepository(BatteryModel::class) // check if battery model is blank
->find($req->request->get('battery_model')); $bmodel = $req->request->get('battery_model');
if (!empty($bmodel))
{
$model = $em->getRepository(BatteryModel::class)
->find($req->request->get('battery_model'));
if (empty($model)) if (empty($model))
$error_array['battery_model'] = 'Invalid model selected.'; $error_array['battery_model'] = 'Invalid model selected.';
else
$obj->setBatteryModel($model);
}
else else
$obj->setBatteryModel($model); $obj->setBatteryModel(NULL);
// custom validation for battery size // custom validation for battery size
$size = $em->getRepository(BatterySize::class) // check if battery size is blank
->find($req->request->get('battery_size')); $bsize = $req->request->get('battery_size');
if (!empty($bsize))
{
$size = $em->getRepository(BatterySize::class)
->find($req->request->get('battery_size'));
if (empty($size)) if (empty($size))
$error_array['battery_size'] = 'Invalid size selected.'; $error_array['battery_size'] = 'Invalid size selected.';
else
$obj->setBatterySize($size);
}
else else
$obj->setBatterySize($size); $obj->setBatterySize(NULL);
// custom validation for SAP battery // custom validation for SAP battery
$sap = $em->getRepository(SAPBattery::class) // check if sap battery is blank
->find($req->request->get('sap_battery')); $sap_battery = $req->request->get('sap_battery');
if (!empty($sap_battery))
{
$sap = $em->getRepository(SAPBattery::class)
->find($req->request->get('sap_battery'));
if (empty($sap)) if (empty($sap))
$error_array['sap_battery'] = 'Invalid SAP battery selected.'; $error_array['sap_battery'] = 'Invalid SAP battery selected.';
else
$obj->setSAPBattery($sap);
}
else else
$obj->setSAPBattery($sap); $obj->setSAPBattery(NULL);
// validate // validate
$errors = $validator->validate($obj); $errors = $validator->validate($obj);
@ -234,6 +257,28 @@ class WarrantyController extends Controller
$em->persist($obj); $em->persist($obj);
$em->flush(); $em->flush();
// log warranty creation
$action = 'create';
$user_id = $this->getUser()->getUsername();
$source = WarrantySource::ADMIN_PANEL;
$log_data = [
'serial' => $req->request->get('serial'),
'warranty_class' => $req->request->get('warranty_class'),
'first_name' => $req->request->get('first_name'),
'last_name' => $req->request->get('last_name'),
'mobile_number' => $req->request->get('mobile_number'),
'date_purchase' => $req->request->get('date_purchase'),
'claim_from' => $req->request->get('claim_from'),
'status' => $req->request->get('status'),
'date_claim' => $req->request->get('date_claim'),
'date_expire' => $req->request->get('date_expire'),
'battery_model' => $req->request->get('battery_model'),
'battery_size' => $req->request->get('battery_size'),
'sap_battery' => $req->request->get('sap_battery'),
'plate_number' => $req->request->get('plate_number'),
];
$logger->logWarrantyInfo($log_data, '', $user_id, $action, $source);
// return successful response // return successful response
return $this->json([ return $this->json([
'success' => 'Changes have been saved!' 'success' => 'Changes have been saved!'
@ -303,31 +348,52 @@ class WarrantyController extends Controller
} }
// custom validation for battery model // custom validation for battery model
$model = $em->getRepository(BatteryModel::class) // check if battery model is blank
->find($req->request->get('battery_model')); $bmodel = $req->request->get('battery_model');
if (!empty($bmodel))
{
$model = $em->getRepository(BatteryModel::class)
->find($req->request->get('battery_model'));
if (empty($model)) if (empty($model))
$error_array['battery_model'] = 'Invalid model selected.'; $error_array['battery_model'] = 'Invalid model selected.';
else
$obj->setBatteryModel($model);
}
else else
$obj->setBatteryModel($model); $obj->setBatteryModel(null);
// custom validation for battery size // custom validation for battery size
$size = $em->getRepository(BatterySize::class) // check if battery size is blank
->find($req->request->get('battery_size')); $bsize = $req->request->get('battery_size');
if (!empty($bsize))
{
$size = $em->getRepository(BatterySize::class)
->find($req->request->get('battery_size'));
if (empty($size)) if (empty($size))
$error_array['battery_size'] = 'Invalid size selected.'; $error_array['battery_size'] = 'Invalid size selected.';
else
$obj->setBatterySize($size);
}
else else
$obj->setBatterySize($size); $obj->setBatterySize(null);
// custom validation for SAP battery // custom validation for SAP battery
$sap = $em->getRepository(SAPBattery::class) // check if sap battery is blank
->find($req->request->get('sap_battery')); $sap_battery = $req->request->get('sap_battery');
if (!empty($sap_battery))
{
$sap = $em->getRepository(SAPBattery::class)
->find($req->request->get('sap_battery'));
if (empty($sap)) if (empty($sap))
$error_array['sap_battery'] = 'Invalid SAP battery selected.'; $error_array['sap_battery'] = 'Invalid SAP battery selected.';
else
$obj->setSAPBattery($sap);
}
else else
$obj->setSAPBattery($sap); $obj->setSAPBattery(null);
// validate // validate
$errors = $validator->validate($obj); $errors = $validator->validate($obj);
@ -598,8 +664,12 @@ class WarrantyController extends Controller
} }
// error_log('Creating warranty for serial ' . $serial . ' and plate number ' . $plate_number); // error_log('Creating warranty for serial ' . $serial . ' and plate number ' . $plate_number);
$user_id = $this->getUser()->getUsername();
$source = WarrantySource::BULK_UPLOAD;
$wh->createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number, $batt_list, $date_purchase, $warranty_class,
$user_id, $source);
$wh->createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number, $batt_list, $date_purchase, $warranty_class);
} }
} }
@ -635,4 +705,5 @@ class WarrantyController extends Controller
// remove spaces and make upper case // remove spaces and make upper case
return strtoupper(str_replace(' ', '', $plate)); return strtoupper(str_replace(' ', '', $plate));
} }
} }

View file

@ -4,7 +4,8 @@ namespace App\DataFixtures;
use App\Entity\Role; use App\Entity\Role;
use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Persistence\ObjectManager;
// use Doctrine\Common\Persistence\ObjectManager;
class RoleFixtures extends Fixture class RoleFixtures extends Fixture
{ {

View file

@ -208,12 +208,20 @@ class Customer
*/ */
protected $create_source; protected $create_source;
// customer tags
/**
* @ORM\ManyToMany(targetEntity="CustomerTag", inversedBy="customers")
* @ORM\JoinTable(name="customer_customer_tags")
*/
protected $customer_tags;
public function __construct() public function __construct()
{ {
$this->numbers = new ArrayCollection(); $this->numbers = new ArrayCollection();
$this->sessions = new ArrayCollection(); $this->sessions = new ArrayCollection();
$this->vehicles = new ArrayCollection(); $this->vehicles = new ArrayCollection();
$this->job_orders = new ArrayCollection(); $this->job_orders = new ArrayCollection();
$this->customer_tags = new ArrayCollection();
$this->customer_classification = CustomerClassification::REGULAR; $this->customer_classification = CustomerClassification::REGULAR;
$this->customer_notes = ''; $this->customer_notes = '';
@ -608,4 +616,36 @@ class Customer
{ {
return $this->create_source; return $this->create_source;
} }
public function addCustomerTag(CustomerTag $customer_tag)
{
$this->customer_tags[$customer_tag->getID()] = $customer_tag;
return $this;
}
public function clearCustomerTags()
{
$this->customer_tags->clear();
return $this;
}
public function getCustomerTags()
{
$str_cust_tags = [];
foreach ($this->customer_tags as $cust_tag)
$str_cust_tags[] = $cust_tag->getID();
return $str_cust_tags;
}
public function getCustomerTagObjects()
{
return $this->customer_tags;
}
public function removeCustomerTag(CustomerTag $customer_tag)
{
$this->customer_tags->removeElement($customer_tag);
$customer_tag->removeCustomer($this);
}
} }

124
src/Entity/CustomerTag.php Normal file
View file

@ -0,0 +1,124 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use DateTime;
/**
* @ORM\Entity
* @ORM\Table(name="customer_tag")
*/
class CustomerTag
{
/**
* @ORM\Id
* @ORM\Column(type="string", length=80, nullable=false, unique=true)
* @Assert\NotBlank()
*/
protected $id;
// name of tag
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $name;
// customers
/**
* @ORM\ManyToMany(targetEntity="Customer", mappedBy="customer_tags", fetch="EXTRA_LAZY")
*/
protected $customers;
// tag details
/**
* @ORM\Column(type="json")
*/
protected $tag_details;
public function __construct()
{
$this->date_create = new DateTime();
$this->customers = new ArrayCollection();
$this->tag_details = [];
}
public function getID()
{
return $this->id;
}
public function setID($id)
{
$this->id = $id;
return $this;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function getDateCreate()
{
return $this->date_create;
}
public function addCustomer(Customer $customer)
{
$this->customers[$customer->getID()] = $customer;
return $this;
}
public function clearCustomers()
{
$this->customers->clear();
return $this;
}
public function getCustomers()
{
return $this->customers;
}
public function removeCustomer(Customer $customer)
{
$this->customers->removeElement($customer);
}
public function addTagDetails($id, $value)
{
$this->tag_details[$id] = $value;
return $this;
}
public function setTagDetails($tag_details)
{
$this->tag_details = $tag_details;
return $this;
}
public function getTagDetails($id)
{
// return null if we don't have it
if (!isset($this->tag_details[$id]))
return null;
return $this->tag_details[$id];
}
public function getAllTagDetails()
{
return json_encode($this->tag_details);
}
}

View file

@ -68,6 +68,18 @@ class Hub
*/ */
protected $flag_hub_view; protected $flag_hub_view;
// notification number to send SMS to if hub doesn't have item
/**
* @ORM\Column(type="string", length=30)
*/
protected $notif_number;
// payment methods
/**
* @ORM\Column(type="array", nullable=true)
*/
protected $payment_methods;
public function __construct() public function __construct()
{ {
$this->time_open = new DateTime(); $this->time_open = new DateTime();
@ -76,6 +88,8 @@ class Hub
$this->outlets = new ArrayCollection(); $this->outlets = new ArrayCollection();
$this->status_open = true; $this->status_open = true;
$this->flag_hub_view = false; $this->flag_hub_view = false;
$this->notif_number = '';
$this->payment_methods = new ArrayCollection();
} }
public function getRiders() public function getRiders()
@ -185,5 +199,38 @@ class Hub
return $this->flag_hub_view; return $this->flag_hub_view;
} }
public function setNotifNumber($notif_number)
{
$this->notif_number = $notif_number;
return $this;
}
public function getNotifNumber()
{
return $this->notif_number;
}
public function getPaymentMethods()
{
return $this->payment_methods;
}
public function setPaymentMethods(array $payment_methods)
{
$this->payment_methods = new ArrayCollection();
foreach ($payment_methods as $payment_method)
{
$this->payment_methods->add($payment_method);
}
return $this;
}
public function clearPaymentMethods()
{
$this->payment_methods = new ArrayCollection();
return $this;
}
} }

View file

@ -0,0 +1,83 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use App\Entity\Hub;
use DateTime;
/**
* @ORM\Entity
* @ORM\Table(name="hub_filter_log")
*/
class HubFilterLog
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// date created
/**
* @ORM\Column(type="datetime")
*/
protected $date_create;
// hub that was not included in results
/**
* @ORM\ManyToOne(targetEntity="Hub", inversedBy="hub_filtered")
* @ORM\JoinColumn(name="hub_filtered_id", referencedColumnName="id", nullable=true)
*/
protected $hub;
// filter that eliminated hub
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $filter_type_id;
public function __construct()
{
$this->date_create = new DateTime();
}
public function getID()
{
return $this->id;
}
public function getDateCreate()
{
return $this->date_create;
}
public function setHub(Hub $hub)
{
$this->hub = $hub;
return $this;
}
public function getHub()
{
return $this->hub;
}
public function setFilterTypeId($filter_type_id)
{
$this->filter_type_id = $filter_type_id;
return $this;
}
public function getFilterTypeId()
{
return $this->filter_type_id;
}
}

168
src/Entity/PromoLog.php Normal file
View file

@ -0,0 +1,168 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use DateTime;
/**
* @ORM\Entity
* @ORM\Table(name="promo_log")
*/
class PromoLog
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// date created
/**
* @ORM\Column(type="datetime")
*/
protected $date_create;
// user that created the JO
/**
* @ORM\Column(type="string", length=80)
*/
protected $created_by;
// customer id
/**
* @ORM\Column(type="integer")
*/
protected $cust_id;
// customer first name
/**
* @ORM\Column(type="string", length=80)
*/
protected $cust_first_name;
// customer last name
/**
* @ORM\Column(type="string", length=80)
*/
protected $cust_last_name;
// job order id
/**
* @ORM\Column(type="integer")
*/
protected $jo_id;
// invoice id
/**
* @ORM\Column(type="integer")
*/
protected $invoice_id;
// total amount
/**
* @ORM\Column(type="decimal", precision=9, scale=2)
*/
protected $amount;
public function __construct()
{
$this->date_create = new DateTime();
}
public function getID()
{
return $this->id;
}
public function setDateCreate(DateTime $date_create)
{
$this->date_create = $date_create;
return $this;
}
public function getDateCreate()
{
return $this->date_create;
}
public function setCreatedBy($created_by)
{
$this->created_by = $created_by;
return $this;
}
public function getCreatedBy()
{
return $this->created_by;
}
public function setCustId($cust_id)
{
$this->cust_id = $cust_id;
return $this;
}
public function getCustId()
{
return $this->cust_id;
}
public function setCustFirstName($cust_first_name)
{
$this->cust_first_name = $cust_first_name;
return $this;
}
public function getCustFirstName()
{
return $this->cust_first_name;
}
public function setCustLastName($cust_last_name)
{
$this->cust_last_name = $cust_last_name;
return $this;
}
public function getCustLastName()
{
return $this->cust_last_name;
}
public function setJoId($jo_id)
{
$this->jo_id = $jo_id;
return $this;
}
public function getJoId()
{
return $this->jo_id;
}
public function setInvoiceId($invoice_id)
{
$this->invoice_id = $invoice_id;
return $this;
}
public function getInvoiceId()
{
return $this->invoice_id;
}
public function setAmount($amount)
{
$this->amount = $amount;
return $this;
}
public function getAmount()
{
return $this->amount;
}
}

View file

@ -73,14 +73,14 @@ class Warranty
// battery model // battery model
/** /**
* @ORM\ManyToOne(targetEntity="BatteryModel", inversedBy="warranties") * @ORM\ManyToOne(targetEntity="BatteryModel", inversedBy="warranties")
* @ORM\JoinColumn(name="bty_model_id", referencedColumnName="id") * @ORM\JoinColumn(name="bty_model_id", referencedColumnName="id", nullable=true)
*/ */
protected $bty_model; protected $bty_model;
// battery size // battery size
/** /**
* @ORM\ManyToOne(targetEntity="BatterySize", inversedBy="warranties") * @ORM\ManyToOne(targetEntity="BatterySize", inversedBy="warranties")
* @ORM\JoinColumn(name="bty_size_id", referencedColumnName="id") * @ORM\JoinColumn(name="bty_size_id", referencedColumnName="id", nullable=true)
*/ */
protected $bty_size; protected $bty_size;
@ -371,7 +371,7 @@ class Warranty
return $this->mobile_number; return $this->mobile_number;
} }
public function setBatteryModel(BatteryModel $model) public function setBatteryModel(BatteryModel $model = null)
{ {
$this->bty_model = $model; $this->bty_model = $model;
return $this; return $this;
@ -382,7 +382,7 @@ class Warranty
return $this->bty_model; return $this->bty_model;
} }
public function setBatterySize(BatterySize $size) public function setBatterySize(BatterySize $size = null)
{ {
$this->bty_size = $size; $this->bty_size = $size;
return $this; return $this;
@ -393,7 +393,7 @@ class Warranty
return $this->bty_size; return $this->bty_size;
} }
public function setSAPBattery(SAPBattery $sap_bty) public function setSAPBattery(SAPBattery $sap_bty = null)
{ {
$this->sap_bty = $sap_bty; $this->sap_bty = $sap_bty;
return $this; return $this;

View file

@ -0,0 +1,163 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use DateTime;
/**
* @ORM\Entity
* @ORM\Table(name="warranty_api_log")
*/
class WarrantyAPILog
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// date created
/**
* @ORM\Column(type="datetime")
*/
protected $date_create;
// user that created warranty
/**
* @ORM\Column(type="string", length=32)
*/
protected $api_user;
// data sent
/**
* @ORM\Column(type="json")
*/
protected $all_data;
// errors
/**
* @ORM\Column(type="array", nullable=true)
*/
protected $errors;
// action
/**
* @ORM\Column(type="string", length=20)
*/
protected $action;
// source
/**
* @ORM\Column(type="string", length=30)
*/
protected $source;
public function __construct()
{
$this->date_create = new DateTime();
$this->errors = new ArrayCollection();
$this->all_data = [];
$this->action = '';
$this->source = '';
}
public function getID()
{
return $this->id;
}
public function setDateCreate(DateTime $date_create)
{
$this->date_create = $date_create;
return $this;
}
public function getDateCreate()
{
return $this->date_create;
}
public function setApiUser($api_user)
{
$this->api_user = $api_user;
return $this;
}
public function getApiUser()
{
return $this->api_user;
}
public function addAllData($id, $value)
{
$this->all_data[$id] = $value;
return $this;
}
public function setAllData($all_data)
{
$this->all_data = $all_data;
return $this;
}
public function getAllData($id)
{
// return null if we don't have it
if (!isset($this->all_data[$id]))
return null;
return $this->all_data[$id];
}
public function getErrors()
{
return $this->errors;
}
public function setErrors(array $errors)
{
$this->errors = new ArrayCollection();
foreach ($errors as $error)
{
$this->errors->add($error);
}
return $this;
}
public function clearErrors()
{
$this->errors = new ArrayCollection();
return $this;
}
public function setAction($action)
{
$this->action = $action;
return $this;
}
public function getAction()
{
return $this->action;
}
public function setSource($source)
{
$this->source = $source;
return $this;
}
public function getSource()
{
return $this->source;
}
}

View file

@ -46,9 +46,16 @@ class WarrantySerial
*/ */
protected $source; protected $source;
// other information
/**
* @ORM\Column(type="json")
*/
protected $meta_info;
public function __construct() public function __construct()
{ {
$this->date_create = new DateTime(); $this->date_create = new DateTime();
$this->meta_info = [];
} }
public function setID($id) public function setID($id)
@ -99,4 +106,19 @@ class WarrantySerial
{ {
return $this->source; return $this->source;
} }
public function addMetaInfo($id, $value)
{
$this->meta_info[$id] = $value;
return $this;
}
public function getMetaInfo($id)
{
// return null if we don't have it
if (!isset($this->meta_info[$id]))
return null;
return $this->meta_info[$id];
}
} }

140
src/Ramcar/HubCriteria.php Normal file
View file

@ -0,0 +1,140 @@
<?php
namespace App\Ramcar;
use CrEOF\Spatial\PHP\Types\Geometry\Point;
use DateTime;
class HubCriteria
{
protected $point; // coordinates of source
protected $limit_results; // number of results to return
protected $limit_distance; // distance limit for search in km
protected $flag_inventory_check; // flag if we need to check for inventory
protected $jo_type; // jo service needed
protected $date_time; // date and time to check if hub is open or not
protected $items; // array of items: items[sku] = quantity to check for
protected $payment_method; // payment method of JO
protected $flag_emergency; // flag if emergency or not
public function __construct()
{
// TODO: default values might still change
$this->limit_results = 10;
$this->limit_distance = 500;
$this->jo_type = '';
$this->date_time = null;
$this->flag_inventory_check = false;
$this->items = [];
$this->payment_method = '';
$flag_emergency = false;
}
public function setPoint(Point $point)
{
$this->point = $point;
return $this;
}
public function getPoint()
{
return $this->point;
}
public function setLimitResults($limit_results)
{
$this->limit_results = $limit_results;
return $this;
}
public function getLimitResults()
{
return $this->limit_results;
}
public function setLimitDistance($limit_distance)
{
$this->limit_distance = $limit_distance;
return $this;
}
public function getLimitDistance()
{
return $this->limit_distance;
}
public function setInventoryCheck($flag_inventory_check = true)
{
$this->flag_inventory_check = $flag_inventory_check;
return $this;
}
public function hasInventoryCheck()
{
return $this->flag_inventory_check;
}
public function setJoType($jo_type)
{
// TODO: validate the jo type
$this->jo_type = $jo_type;
return $this;
}
public function getJoType()
{
return $this->jo_type;
}
public function setDateTime(DateTime $date_time)
{
$this->date_time = $date_time;
return $this;
}
public function getDateTime()
{
return $this->date_time;
}
public function addItem($sku, $quantity)
{
// at this point, sku is assumed to be a valid item
$this->items[$sku] = $quantity;
return $this;
}
public function getItems()
{
return $this->items;
}
public function setItems($items)
{
$this->items = $items;
return $this;
}
public function setPaymentMethod($payment_method)
{
$this->payment_method = $payment_method;
return $this;
}
public function getPaymentMethod()
{
return $this->payment_method;
}
public function setEmergency($flag_emergency = true)
{
$this->flag_emergency = $flag_emergency;
return $this;
}
public function isEmergency()
{
return $this->flag_emergency;
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace App\Ramcar;
class WarrantySource extends NameValue
{
const CAPI = 'capi';
const RAPI = 'rapi';
const ADMIN_PANEL = 'admin_panel';
const BULK_UPLOAD = 'bulk_upload';
const MOBILE = 'mobile';
const COMMAND = 'command';
const COLLECTION = [
'capi' => 'Third Party API',
'rapi' => 'Rider API',
'admin_panel' => 'Admin Panel',
'bulk_upload' => 'Bulk Upload',
'mobile' => 'Mobile API',
'command' => 'Command',
];
}

View file

@ -22,6 +22,7 @@ use App\Entity\Vehicle;
use App\Entity\Battery; use App\Entity\Battery;
use App\Entity\VehicleManufacturer; use App\Entity\VehicleManufacturer;
use App\Entity\BatteryManufacturer; use App\Entity\BatteryManufacturer;
use App\Entity\CustomerTag;
use DateTime; use DateTime;
@ -151,6 +152,9 @@ class ResqCustomerHandler implements CustomerHandlerInterface
$params['obj'] = new Customer(); $params['obj'] = new Customer();
$params['mode'] = 'create'; $params['mode'] = 'create';
// get customer tags
$params['customer_tags'] = $this->em->getRepository(CustomerTag::class)->findAll();
// get dropdown parameters // get dropdown parameters
$this->fillDropdownParameters($params); $this->fillDropdownParameters($params);
@ -307,6 +311,9 @@ class ResqCustomerHandler implements CustomerHandlerInterface
if (empty($row)) if (empty($row))
throw new NotFoundHttpException('The item does not exist'); throw new NotFoundHttpException('The item does not exist');
// get customer tags
$params['customer_tags'] = $em->getRepository(CustomerTag::class)->findAll();
// get dropdown parameters // get dropdown parameters
$this->fillDropdownParameters($params); $this->fillDropdownParameters($params);
@ -541,6 +548,7 @@ class ResqCustomerHandler implements CustomerHandlerInterface
'flag_promo_email' => $customer->isPromoEmail(), 'flag_promo_email' => $customer->isPromoEmail(),
'flag_research_sms' => $customer->isResearchSms(), 'flag_research_sms' => $customer->isResearchSms(),
'flag_research_email' => $customer->isResearchEmail(), 'flag_research_email' => $customer->isResearchEmail(),
'customer_tags' => $customer->getCustomerTags(),
], ],
'vehicle' => [ 'vehicle' => [
'id' => $vehicle->getID(), 'id' => $vehicle->getID(),
@ -603,13 +611,26 @@ class ResqCustomerHandler implements CustomerHandlerInterface
->setPromoEmail($req->request->get('flag_promo_email', false)) ->setPromoEmail($req->request->get('flag_promo_email', false))
->setDpaConsent($is_dpa_checked) ->setDpaConsent($is_dpa_checked)
->setResearchSms($req->request->get('flag_research_sms', false)) ->setResearchSms($req->request->get('flag_research_sms', false))
->setResearchEmail($req->request->get('flag_research_email', false)); ->setResearchEmail($req->request->get('flag_research_email', false))
->clearCustomerTags();
// phone numbers // phone numbers
$obj->setPhoneMobile($req->request->get('phone_mobile')) $obj->setPhoneMobile($req->request->get('phone_mobile'))
->setPhoneLandline($req->request->get('phone_landline')) ->setPhoneLandline($req->request->get('phone_landline'))
->setPhoneOffice($req->request->get('phone_office')) ->setPhoneOffice($req->request->get('phone_office'))
->setPhoneFax($req->request->get('phone_fax')); ->setPhoneFax($req->request->get('phone_fax'));
// set car club flags
$customer_tags = $req->request->get('customer_tags');
if (!empty($customer_tags))
{
foreach($customer_tags as $customer_tag_id)
{
$customer_tag = $this->em->getRepository(CustomerTag::class)->find($customer_tag_id);
if (!empty($customer_tag))
$obj->addCustomerTag($customer_tag);
}
}
} }
protected function fillDropdownParameters(&$params) protected function fillDropdownParameters(&$params)

View file

@ -0,0 +1,27 @@
<?php
namespace App\Service;
use Hashids\Hashids;
class HashGenerator
{
// TODO: set in env file and set in constructor
protected $salt = 'salt that should be in the env file 230498';
protected $length = 15;
public function getHash($id)
{
$hi = new Hashids($this->salt, $this->length);
return $hi->encode($id);
}
public function getID($hash)
{
$hi = new Hashids($this->salt, $this->length);
$id_array = $hi->decode($hash);
// first one should be the id
return $id_array[0];
}
}

View file

@ -0,0 +1,109 @@
<?php
namespace App\Service;
use App\Service\RedisClientProvider;
use App\Entity\Hub;
class HubDistributor
{
protected $redis;
protected $hub_jo_key;
public function __construct(RedisClientProvider $redis, $hub_jo_key)
{
$this->redis = $redis->getRedisClient();
$this->hub_jo_key = $hub_jo_key;
}
public function incrementJoCountForHub(Hub $hub)
{
$key = $hub->getID();
// get current count
$jo_count = $this->redis->hget($this->hub_jo_key, $key);
if ($jo_count == false)
{
// hub not in hash
// add hub to hash
// set to 1 since this is first jo for hub
$this->redis->hset($this->hub_jo_key, $key, 1);
}
else
{
// hub exist in hash
// add to count
$this->redis->hset($this->hub_jo_key, $key, $jo_count + 1);
}
}
public function decrementJoCountForHub(Hub $hub)
{
$key = $hub->getID();
// get current count
$jo_count = $this->redis->hget($this->hub_jo_key, $key);
if ($jo_count)
{
// hub exist in hash
// decrement count
$this->redis->hset($this->hub_jo_key, $key, $jo_count - 1);
}
}
public function arrangeHubs($hubs)
{
if (count($hubs) == 1)
return $hubs;
$arranged_hubs = [];
foreach ($hubs as $hub_data)
{
$hub = $hub_data['hub'];
// need the id of hub
$key = $hub->getID();
// get jo count of hub
$hub_jo_count = $this->redis->hget($this->hub_jo_key, $key);
// check if hub is in hash. if not, hub has no jobs
// but should still be added to results
if ($hub_jo_count != null)
{
$arranged_hubs[] = [
'hub' => $hub,
'db_distance' => $hub_data['db_distance'],
'distance' => $hub_data['distance'],
'duration' => $hub_data['duration'],
'jo_count' => $hub_jo_count,
];
}
else
{
$arranged_hubs[] = [
'hub' => $hub,
'db_distance' => $hub_data['db_distance'],
'distance' => $hub_data['distance'],
'duration' => $hub_data['duration'],
'jo_count' => 0,
];
}
}
usort($arranged_hubs, function($a, $b) {
if ($a['jo_count'] == $b['jo_count'])
return 0;
if ($a['jo_count'] < $b['jo_count'])
return -1;
else
return 1;
});
//error_log('arranged hubs ' . json_encode($arranged_hubs));
return $arranged_hubs;
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Hub;
use App\Entity\HubFilterLog;
class HubFilterLogger
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function logFilteredHub(Hub $hub, $filter_type)
{
$hub_filter_log = new HubFilterLog();
$hub_filter_log->setHub($hub)
->setFilterTypeId($filter_type);
$this->em->persist($hub_filter_log);
$this->em->flush();
}
}

479
src/Service/HubSelector.php Normal file
View file

@ -0,0 +1,479 @@
<?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
use CrEOF\Spatial\PHP\Types\Geometry\Point;
use App\Entity\Hub;
use App\Service\HubDistributor;
use App\Service\InventoryManager;
use App\Service\HubFilterLogger;
use App\Service\RisingTideGateway;
use App\Ramcar\HubCriteria;
use App\Ramcar\ServiceType;
class HubSelector
{
protected $em;
protected $im;
protected $hub_distributor;
protected $hub_filter_logger;
protected $trans;
protected $rt;
public function __construct(EntityManagerInterface $em, InventoryManager $im,
HubDistributor $hub_distributor, HubFilterLogger $hub_filter_logger,
TranslatorInterface $trans, RisingTideGateway $rt)
{
$this->em = $em;
$this->im = $im;
$this->hub_distributor = $hub_distributor;
$this->hub_filter_logger = $hub_filter_logger;
$this->trans = $trans;
$this->rt = $rt;
}
public function find(HubCriteria $criteria)
{
$point = $criteria->getPoint();
$limit_results = $criteria->getLimitResults();
$limit_distance = $criteria->getLimitDistance();
$jo_type = $criteria->getJoType();
$flag_inventory_check = $criteria->hasInventoryCheck();
$items = $criteria->getItems();
$date_time = $criteria->getDateTime();
$payment_method = $criteria->getPaymentMethod();
$flag_emergency = $criteria->isEmergency();
$results = [];
// get all the hubs within distance
$filtered_hubs = $this->getClosestHubs($point, $limit_distance);
//error_log('closest hubs ' . json_encode($filtered_hubs));
if (!$flag_emergency)
{
// filter the first hub results for date and opening times
$hubs_date_time = $this->filterHubsByDateAndTime($filtered_hubs, $date_time);
$filtered_hubs = $hubs_date_time;
// filter jo types
$hubs_jo_type = $this->filterHubsByJoType($filtered_hubs, $jo_type);
$filtered_hubs = $hubs_jo_type;
// filter hubs by payment methods
$hubs_payment_method = $this->filterHubsByPaymentMethod($filtered_hubs, $payment_method);
$filtered_hubs = $hubs_payment_method;
// filter hubs by rider availability
$hubs_rider_availability = $this->filterHubsByRiderAvailability($filtered_hubs);
$filtered_hubs = $hubs_rider_availability;
// inventory filter
$hubs_inventory = $this->filterHubsByInventory($filtered_hubs, $flag_inventory_check,
$jo_type, $items);
$filtered_hubs = $hubs_inventory;
// round robin filter
$hubs_round_robin = $this->filterHubsByRoundRobin($filtered_hubs);
$filtered_hubs = $hubs_round_robin;
//error_log(json_encode($filtered_hubs));
// max results filter
$hubs_max_result = $this->filterHubsByMaxResults($filtered_hubs, $limit_results);
$filtered_hubs = $hubs_max_result;
}
$results = $filtered_hubs;
error_log(json_encode($results));
return $results;
}
protected function filterHubsByRoundRobin($hubs)
{
if (empty($hubs))
return $hubs;
$results = [];
// call hub distributor service
$arranged_hubs = $this->hub_distributor->arrangeHubs($hubs);
$results = $arranged_hubs;
return $results;
}
protected function filterHubsByMaxResults($hubs, $limit_result)
{
if (empty($hubs))
return $hubs;
if (empty($limit_result))
return $hubs;
$results = [];
for ($i = 0; $i < count($hubs); $i++)
{
if ($i < $limit_result)
$results[] = $hubs[$i];
else
$this->hub_filter_logger->logFilteredHub($hubs[$i]['hub'], 'max_results');
}
return $results;
}
protected function filterHubsByJoType($hubs, $jo_type)
{
if (empty($hubs))
return $hubs;
if (empty($jo_type))
return $hubs;
$results = [];
foreach ($hubs as $hub_data)
{
$hub = $hub_data['hub'];
// TODO: for now, have this return true
$has_jo_type = true;
// check if hub offers the jo_type
// TODO: add service to hub
if ($has_jo_type)
$results[] = [
'hub' => $hub,
'db_distance' => $hub_data['db_distance'],
'distance' => $hub_data['distance'],
'duration' => $hub_data['duration'],
];
else
$this->hub_filter_logger->logFilteredHub($hub, 'job_order_type');
}
return $results;
}
protected function filterHubsByPaymentMethod($hubs, $payment_method)
{
if (empty($hubs))
return $hubs;
if (empty($payment_method))
return $hubs;
$results = [];
foreach ($hubs as $hub_data)
{
$hub = $hub_data['hub'];
// name of payment method is what is saved
$payment_methods = $hub->getPaymentMethods();
if ($payment_methods != null)
{
$flag_found_pmethod = false;
foreach ($payment_methods as $pmethod)
{
if ($pmethod == $payment_method)
{
$results[] = [
'hub' => $hub,
'db_distance' => $hub_data['db_distance'],
'distance' => $hub_data['distance'],
'duration' => $hub_data['duration'],
];
}
$flag_found_pmethod = true;
}
if (!$flag_found_pmethod)
$this->hub_filter_logger->logFilteredHub($hub, 'no_payment_method');
}
else
$this->hub_filter_logger->logFilteredHub($hub, 'no_payment_method');
}
return $results;
}
protected function filterHubsByRiderAvailability($hubs)
{
if (empty($hubs))
return $hubs;
$results = [];
foreach ($hubs as $hub_data)
{
$hub = $hub_data['hub'];
// get hub's riders
$riders = $hub->getRiders();
$avail_rider_count = 0;
foreach ($riders as $rider)
{
if ($rider->isAvailable())
$avail_rider_count = $avail_rider_count + 1;
}
error_log('HUB ' . $hub->getID() . ' RIDER COUNT' . $avail_rider_count);
if ($avail_rider_count > 0)
$results[] = [
'hub' => $hub,
'db_distance' => $hub_data['db_distance'],
'distance' => $hub_data['distance'],
'duration' => $hub_data['duration'],
];
else
$this->hub_filter_logger->logFilteredHub($hub, 'no_available_rider');
}
return $results;
}
protected function filterHubsByDateAndTime($hubs, $date_time)
{
if (empty($hubs))
return $hubs;
if ($date_time == null)
return $hubs;
$results = [];
foreach ($hubs as $hub_data)
{
// go through each hub's opening times to check if hub is open
// for the specified time
// get hub opening and closing times
// TODO: maybe in the future, might also have to check if hub
// is open/available on date/day
$hub = $hub_data['hub'];
$time_open = $hub->getTimeOpen()->format("H:i:s");
$time_close = $hub->getTimeClose()->format("H:i:s");
$filter_time = $date_time->format("H:i:s");
if (($filter_time >= $time_open) &&
($filter_time <= $time_close))
{
$results[] = [
'hub' => $hub,
'db_distance' => $hub_data['db_distance'],
'distance' => $hub_data['distance'],
'duration' => $hub_data['duration'],
];
}
else
$this->hub_filter_logger->logFilteredHub($hub, 'date_and_time');
}
return $results;
}
protected function filterHubsByInventory($hubs, $flag_inventory_check, $jo_type, $items)
{
if (empty($hubs))
return $hubs;
if (!$flag_inventory_check)
return $hubs;
$results = [];
if ($flag_inventory_check)
{
foreach ($hubs as $hub_data)
{
$hub = $hub_data['hub'];
if ($jo_type == ServiceType::BATTERY_REPLACEMENT_NEW)
{
// call inventory
$has_items = $this->checkInventory($items, $hub);
if ($has_items)
$results[] = [
'hub' => $hub,
'db_distance' => $hub_data['db_distance'],
'distance' => $hub_data['distance'],
'duration' => $hub_data['duration'],
];
else
{
// get the skus for the message
$sku_text = '';
foreach ($items as $key => $value)
{
$sku_text .= ' ' . $key;
}
// send SMS to hub
$message = str_replace('item_display', trim($sku_text), $this->trans->trans('no_inventory_message'));
error_log($message);
$this->sendSMSMessage($hub, $items);
$this->hub_filter_logger->logFilteredHub($hub, 'no_inventory');
}
}
if ($jo_type == ServiceType::BATTERY_REPLACEMENT_WARRANTY)
{
// call inventory
$has_items = $this->checkInventory($items, $hub);
if ($has_items)
$results[] = [
'hub' => $hub,
'db_distance' => $hub_data['db_distance'],
'distance' => $hub_data['distance'],
'duration' => $hub_data['duration'],
];
else
{
// get the skus for the message
$sku_text = '';
foreach ($items as $key => $value)
{
$sku_text .= ' ' . $key;
}
// send SMS to hub
$message = str_replace('item_display', trim($sku_text), $this->trans->trans('no_inventory_message'));
error_log($message);
$this->sendSMSMessage($hub, $items);
$this->hub_filter_logger->logFilteredHub($hub, 'no_inventory');
}
}
}
}
return $results;
}
protected function sendSMSMessage($hub, $items)
{
// compose message
// get the skus for the message
$sku_text = '';
foreach ($items as $key => $value)
{
$sku_text .= ' ' . $key;
}
$message = str_replace('item_display', trim($sku_text), $this->trans->trans('no_inventory_message'));
// get hub notification number
$number = $hub->getNotifNumber();
if (!empty($number))
{
// send SMS message
$mobile_number = '63' . $number;
error_log('sending sms to - ' . $mobile_number);
$this->rt->sendSMS($mobile_number, 'MOTOLITE', $message);
}
}
protected function getClosestHubs(Point $point, $limit_distance)
{
// get closest hubs based on st_distance function from db
$query_string = 'SELECT h, st_distance(h.coordinates, point(:lng, :lat)) as dist FROM App\Entity\Hub h WHERE h.status_open = true ORDER BY dist';
$query = $this->em->createQuery($query_string)
->setParameter('lat', $point->getLatitude())
->setParameter('lng', $point->getLongitude());
// error_log($query->getSql());
$result = $query->getResult();
$hubs = [];
$hubs_data = [];
foreach ($result as $row)
{
$hubs[] = $row[0];
// get coordinates of hub
$hub_coordinates = $row[0]->getCoordinates();
$cust_lat = $point->getLatitude();
$cust_lng = $point->getLongitude();
$hub_lat = $hub_coordinates->getLatitude();
$hub_lng = $hub_coordinates->getLongitude();
// get distance in kilometers from customer point to hub point
$dist = $this->distance($cust_lat, $cust_lng, $hub_lat, $hub_lng);
if ($dist < $limit_distance)
{
$hubs_data[] = [
'hub' => $row[0],
'db_distance' => $row['dist'],
'distance' => $dist,
'duration' => 0,
];
}
else
{
$this->hub_filter_logger->logFilteredHub($row[0], 'distance');
}
}
return $hubs_data;
}
protected function checkInventory($items, $hub)
{
// check if hub has all items
$skus = [];
$branch_codes[] = $hub->getBranchCode();
$result = false;
foreach ($items as $key=> $value)
{
// add sap code of item/battery into array since
// getBranchesInventory takes in an array of hubs/branches
// and an array of skus
// $items as format: $items[sku] = quantity
$skus[] = $key;
}
// call InventoryManager's getBranchesInventory to check if hub has all items
$branches_with_items = $this->im->getBranchesInventory($branch_codes, $skus);
if (!empty($branches_with_items))
{
// check if branch has enough quantity for item
foreach ($branches_with_items as $branch)
{
// get quantity from call
$qty_available = $branch['Quantity'];
// get the quantity request
$sku_requested = $branch['SapCode'];
$qty_requested = $items[$sku_requested];
if ($qty_available >= $qty_requested)
$result = true;
}
}
// return true or false
return $result;
}
// convert db distance to kilometers
protected function distance($lat1, $lon1, $lat2, $lon2)
{
if (($lat1 == $lat2) && ($lon1 == $lon2))
return 0;
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
return round(($miles * 1.609344), 1);
}
}

View file

@ -71,6 +71,7 @@ class InventoryManager
// check if the response is empty // check if the response is empty
$results = []; $results = [];
//error_log($response);
if (!empty($response)) if (!empty($response))
$results = json_decode($response, true); $results = json_decode($response, true);

View file

@ -19,6 +19,7 @@ use App\Entity\InvoiceItem;
use App\Entity\User; use App\Entity\User;
use App\Entity\Battery; use App\Entity\Battery;
use App\Entity\Promo; use App\Entity\Promo;
use App\Entity\Customer;
use App\Service\InvoiceGeneratorInterface; use App\Service\InvoiceGeneratorInterface;
@ -66,6 +67,15 @@ class ResqInvoiceGenerator implements InvoiceGeneratorInterface
$stype = $criteria->getServiceType(); $stype = $criteria->getServiceType();
$cv = $criteria->getCustomerVehicle(); $cv = $criteria->getCustomerVehicle();
$has_coolant = $criteria->hasCoolant(); $has_coolant = $criteria->hasCoolant();
$cust_tag_info = [];
if ($stype == ServiceType::BATTERY_REPLACEMENT_NEW)
{
// check if criteria has entries
$entries = $criteria->getEntries();
if (!empty($entries))
$cust_tag_info = $this->getCustomerTagInfo($cv);
}
// error_log($stype); // error_log($stype);
switch ($stype) switch ($stype)
{ {
@ -81,7 +91,7 @@ class ResqInvoiceGenerator implements InvoiceGeneratorInterface
$this->processBatteries($total, $criteria, $invoice); $this->processBatteries($total, $criteria, $invoice);
$this->processTradeIns($total, $criteria, $invoice); $this->processTradeIns($total, $criteria, $invoice);
*/ */
$this->processDiscount($total, $criteria, $invoice); $this->processDiscount($total, $criteria, $invoice, $cust_tag_info);
break; break;
case ServiceType::BATTERY_REPLACEMENT_WARRANTY: case ServiceType::BATTERY_REPLACEMENT_WARRANTY:
@ -404,45 +414,95 @@ class ResqInvoiceGenerator implements InvoiceGeneratorInterface
} }
} }
protected function processDiscount(&$total, InvoiceCriteria $criteria, Invoice $invoice) protected function processDiscount(&$total, InvoiceCriteria $criteria, Invoice $invoice, $cust_tag_info)
{ {
$promos = $criteria->getPromos(); if (empty($cust_tag_info))
if (count($promos) < 1)
return;
// NOTE: only get first promo because only one is applicable anyway
$promo = $promos[0];
$rate = $promo->getDiscountRate();
$apply_to = $promo->getDiscountApply();
switch ($apply_to)
{ {
case DiscountApply::SRP: error_log('empty cust tag');
$discount = round($total['sell_price'] * $rate, 2); $promos = $criteria->getPromos();
break; if (count($promos) < 1)
case DiscountApply::OPL: return;
// $discount = round($total['sell_price'] * 0.6 / 0.7 * $rate, 2);
$discount = round($total['sell_price'] * (1 - 1.5 / 0.7 * $rate), 2);
break;
}
// if discount is higher than 0, display in invoice // NOTE: only get first promo because only one is applicable anyway
if ($discount > 0) $promo = $promos[0];
$rate = $promo->getDiscountRate();
$apply_to = $promo->getDiscountApply();
switch ($apply_to)
{
case DiscountApply::SRP:
$discount = round($total['sell_price'] * $rate, 2);
break;
case DiscountApply::OPL:
// $discount = round($total['sell_price'] * 0.6 / 0.7 * $rate, 2);
$discount = round($total['sell_price'] * (1 - 1.5 / 0.7 * $rate), 2);
break;
}
// if discount is higher than 0, display in invoice
if ($discount > 0)
{
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Promo discount')
->setQuantity(1)
->setPrice(-1 * $discount);
$invoice->addItem($item);
}
$total['discount'] = $discount;
$total['total_price'] -= $discount;
// process
$invoice->setPromo($promo);
}
else
{ {
$item = new InvoiceItem(); // since only one promo can only be used, we prioritize the tag promos
$item->setInvoice($invoice) // TODO: need to test this for multiple tags
->setTitle('Promo discount') $total_discount_amount = 0;
->setQuantity(1) $total_amount = $total['total_price'];
->setPrice(-1 * $discount); foreach ($cust_tag_info as $ct_info)
$invoice->addItem($item); {
// check discount type
$discount_type = '';
$discount_value = 0;
$discount_amount = 0;
$discounted_total = 0;
if (isset($ct_info['discount_type']))
$discount_type = $ct_info['discount_type'];
if (isset($ct_info['discount_value']))
{
$discount_value = $ct_info['discount_value'];
}
if ($discount_type == 'percent')
{
$discount = round(($discount_value / 100), 2);
$discount_amount = $total_amount * $discount;
$discounted_total = $total_amount - $discount_amount;
}
else
{
// assume fixed amount for this
$discount = $discount_value;
$discounted_total = $total_amount - $discount;
}
$total_discount_amount += $discounted_total;
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle($ct_info['invoice_display'])
->setQuantity(1)
->setPrice(-1 * $total_discount_amount);
$invoice->addItem($item);
}
$total['discount'] = $total_discount_amount;
$total['total_price'] -= $total_discount_amount;
} }
$total['discount'] = $discount;
$total['total_price'] -= $discount;
// process
$invoice->setPromo($promo);
} }
protected function processJumpstart(&$total, $invoice) protected function processJumpstart(&$total, $invoice)
@ -663,6 +723,7 @@ class ResqInvoiceGenerator implements InvoiceGeneratorInterface
$cv = $criteria->getCustomerVehicle(); $cv = $criteria->getCustomerVehicle();
$has_coolant = $criteria->hasCoolant(); $has_coolant = $criteria->hasCoolant();
// error_log($stype); // error_log($stype);
$cust_tag_info = [];
switch ($stype) switch ($stype)
{ {
case ServiceType::JUMPSTART_TROUBLESHOOT: case ServiceType::JUMPSTART_TROUBLESHOOT:
@ -677,7 +738,7 @@ class ResqInvoiceGenerator implements InvoiceGeneratorInterface
$this->processBatteries($total, $criteria, $invoice); $this->processBatteries($total, $criteria, $invoice);
$this->processTradeIns($total, $criteria, $invoice); $this->processTradeIns($total, $criteria, $invoice);
*/ */
$this->processDiscount($total, $criteria, $invoice); $this->processDiscount($total, $criteria, $invoice, $cust_tag_info);
break; break;
case ServiceType::BATTERY_REPLACEMENT_WARRANTY: case ServiceType::BATTERY_REPLACEMENT_WARRANTY:
@ -719,4 +780,33 @@ class ResqInvoiceGenerator implements InvoiceGeneratorInterface
return $invoice; return $invoice;
} }
protected function getCustomerTagInfo($cv)
{
$cust_tag_info = [];
// get customer and customer tags using customer vehicle
$customer = $cv->getCustomer();
$customer_tags = $customer->getCustomerTagObjects();
if (!empty($customer_tags))
{
foreach ($customer_tags as $customer_tag)
{
// TODO: can we keep the tag ids hardcoded?
// check tag details
$cust_tag_type = $customer_tag->getTagDetails('type');
// TODO: might have to make this statement be more generic?
if (($cust_tag_type != null) && ($cust_tag_type == 'one-time-discount'))
{
$cust_tag_info[] = [
'type' => $cust_tag_type,
'discount_type' => $customer_tag->getTagDetails('discount_type'),
'discount_amount' => $customer_tag->getTagDetails('discount_amount'),
'discount_value' => $customer_tag->getTagDetails('discount_value'),
'invoice_display' => $customer_tag->getTagDetails('invoice_display'),
];
}
}
}
return $cust_tag_info;
}
} }

View file

@ -25,6 +25,7 @@ use App\Entity\Rider;
use App\Entity\JORejection; use App\Entity\JORejection;
use App\Entity\Warranty; use App\Entity\Warranty;
use App\Entity\Customer; use App\Entity\Customer;
use App\Entity\CustomerTag;
use App\Ramcar\InvoiceCriteria; use App\Ramcar\InvoiceCriteria;
use App\Ramcar\ServiceType; use App\Ramcar\ServiceType;
@ -40,6 +41,8 @@ use App\Ramcar\JORejectionReason;
use App\Ramcar\CustomerNotWaitReason; use App\Ramcar\CustomerNotWaitReason;
use App\Ramcar\NoTradeInReason; use App\Ramcar\NoTradeInReason;
use App\Ramcar\WillingToWaitContent; use App\Ramcar\WillingToWaitContent;
use App\Ramcar\HubCriteria;
use App\Ramcar\WarrantySource;
use App\Service\InvoiceGeneratorInterface; use App\Service\InvoiceGeneratorInterface;
use App\Service\JobOrderHandlerInterface; use App\Service\JobOrderHandlerInterface;
@ -49,6 +52,9 @@ use App\Service\MQTTClient;
use App\Service\APNSClient; use App\Service\APNSClient;
use App\Service\MapTools; use App\Service\MapTools;
use App\Service\RisingTideGateway; use App\Service\RisingTideGateway;
use App\Service\HubSelector;
use App\Service\HubDistributor;
use App\Service\PromoLogger;
use CrEOF\Spatial\PHP\Types\Geometry\Point; use CrEOF\Spatial\PHP\Types\Geometry\Point;
@ -70,13 +76,16 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
protected $country_code; protected $country_code;
protected $wh; protected $wh;
protected $rt; protected $rt;
protected $hub_dist;
protected $promo_logger;
protected $template_hash; protected $template_hash;
public function __construct(Security $security, EntityManagerInterface $em, public function __construct(Security $security, EntityManagerInterface $em,
InvoiceGeneratorInterface $ic, ValidatorInterface $validator, InvoiceGeneratorInterface $ic, ValidatorInterface $validator,
TranslatorInterface $translator, RiderAssignmentHandlerInterface $rah, TranslatorInterface $translator, RiderAssignmentHandlerInterface $rah,
string $country_code, WarrantyHandler $wh, RisingTideGateway $rt) string $country_code, WarrantyHandler $wh, RisingTideGateway $rt,
HubDistributor $hub_dist, PromoLogger $promo_logger)
{ {
$this->em = $em; $this->em = $em;
$this->ic = $ic; $this->ic = $ic;
@ -87,6 +96,8 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
$this->country_code = $country_code; $this->country_code = $country_code;
$this->wh = $wh; $this->wh = $wh;
$this->rt = $rt; $this->rt = $rt;
$this->hub_dist = $hub_dist;
$this->promo_logger = $promo_logger;
$this->loadTemplates(); $this->loadTemplates();
} }
@ -287,10 +298,13 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
$em = $this->em; $em = $this->em;
$jo = $em->getRepository(JobOrder::class)->find($id); $jo = $em->getRepository(JobOrder::class)->find($id);
// flag for new job order for the customer tags
$flag_new_jo = false;
if (empty($jo)) if (empty($jo))
{ {
// new job order // new job order
$jo = new JobOrder(); $jo = new JobOrder();
$flag_new_jo = true;
} }
// find customer // find customer
@ -463,6 +477,7 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
$em->persist($event); $em->persist($event);
$em->flush(); $em->flush();
} }
} }
@ -471,6 +486,41 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
if ($jo != null) if ($jo != null)
{ {
$data['job_order'] = $jo; $data['job_order'] = $jo;
// need to get the customer tags but only if new JO
if ($flag_new_jo)
{
// check service type
if ($jo->getServiceType() == ServiceType::BATTERY_REPLACEMENT_NEW)
{
$customer = $cust_vehicle->getCustomer();
$customer_tags = $customer->getCustomerTagObjects();
if (!empty($customer_tags))
{
foreach ($customer_tags as $customer_tag)
{
// TODO: not too comfy with this being hardcoded
if ($customer_tag->getID() == 'CAR_CLUB_PROMO')
{
// remove associated entity
$customer->removeCustomerTag($customer_tag);
// log the availment of promo from customer
$created_by = $jo->getCreatedBy()->getUsername();
$cust_id = $jo->getCustomer()->getID();
$cust_fname = $jo->getCustomer()->getFirstName();
$cust_lname = $jo->getCustomer()->getLastName();
$jo_id = $jo->getID();
$invoice_id = $jo->getInvoice()->getID();
// TODO: check if we store total price of invoice or just the discounted amount
$amount = $jo->getInvoice()->getTotalPrice();
$this->promo_logger->logPromoInfo($created_by, $cust_id, $cust_fname, $cust_lname, $jo_id,
$invoice_id, $amount);
}
}
}
}
}
} }
return $data; return $data;
@ -755,6 +805,9 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
'event' => 'outlet_assign' 'event' => 'outlet_assign'
]; ];
$mclient->sendEvent($obj, $payload); $mclient->sendEvent($obj, $payload);
// update redis hub jo count
$this->hub_dist->incrementJoCountForHub($hub);
} }
return $error_array; return $error_array;
@ -1016,7 +1069,9 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
} }
} }
$this->wh->createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number, $batt_list, $date_purchase, $warranty_class); $user_id = $user->getUsername();
$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);
} }
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());
@ -1124,6 +1179,9 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
$more_reason = $req->request->get('not_wait_notes'); $more_reason = $req->request->get('not_wait_notes');
} }
// get previously assigned hub, if any
$old_hub = $obj->getHub();
if (empty($error_array)) if (empty($error_array))
{ {
// rider mqtt event // rider mqtt event
@ -1197,6 +1255,13 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
'event' => 'outlet_assign' 'event' => 'outlet_assign'
]; ];
$mclient->sendEvent($obj, $payload); $mclient->sendEvent($obj, $payload);
// update redis hub_jo_count for hub
// decrement old hub's count and increment new hub's count
if ($old_hub != null)
$this->hub_dist->decrementJoCountForHub($old_hub);
if ($hub != null)
$this->hub_dist->incrementJoCountForHub($hub);
} }
return $error_array; return $error_array;
@ -1632,6 +1697,7 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
return $params; return $params;
} }
// CMB code
public function initializeOneStepEditForm($id, $map_tools) public function initializeOneStepEditForm($id, $map_tools)
{ {
$em = $this->em; $em = $this->em;
@ -1812,7 +1878,7 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
} }
// initialize dispatch/processing job order form // initialize dispatch/processing job order form
public function initializeProcessingForm($id, $map_tools, $motiv) public function initializeProcessingForm($id, HubSelector $hub_selector, $motiv)
{ {
$em = $this->em; $em = $this->em;
@ -1878,8 +1944,44 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
// get rejection reasons // get rejection reasons
$params['rejection_reasons'] = JORejectionReason::getCollection(); $params['rejection_reasons'] = JORejectionReason::getCollection();
// get battery (if any)
$skus = [];
$items = [];
$invoice = $obj->getInvoice();
$inv_items = $invoice->getItems();
foreach ($inv_items as $inv_item)
{
$batt = $inv_item->getBattery();
if ($batt == null)
continue;
$skus[] = $batt->getSapCode();
$item_count = 1;
if (!empty($batt->getSapCode()))
{
$sap_code = $batt->getSapCode();
if (isset($items[$sap_code]))
$items[$sap_code] = $item_count + 1;
else
$items[$sap_code] = $item_count;
}
}
// get closest hubs // get closest hubs
$hubs = $map_tools->getClosestHubs($obj->getCoordinates(), 50, date("H:i:s")); // set hub criteria
$hub_criteria = new HubCriteria();
$hub_criteria->setPoint($obj->getCoordinates())
->setLimitResults(50)
->setPaymentMethod($obj->getModeOfPayment())
->setJoType($obj->getServiceType());
// check if emergency or not
$willing_to_wait = $obj->getWillWait();
if ($willing_to_wait == WillingToWaitContent::NOT_WILLING_TO_WAIT)
$hub_criteria->setEmergency(true);
$hubs = $hub_selector->find($hub_criteria);
//$hubs = $map_tools->getClosestHubs($obj->getCoordinates(), 50, date("H:i:s"));
$params['hubs'] = []; $params['hubs'] = [];
@ -1946,19 +2048,6 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
// get template to display // get template to display
$params['template'] = $this->getTwigTemplate('jo_processing_form'); $params['template'] = $this->getTwigTemplate('jo_processing_form');
// get battery (if any)
$skus = [];
$invoice = $obj->getInvoice();
$inv_items = $invoice->getItems();
foreach ($inv_items as $inv_item)
{
$batt = $inv_item->getBattery();
if ($batt == null)
continue;
$skus[] = $batt->getSapCode();
}
// get inventory // get inventory
$mres = $motiv->getInventory($branch_codes, $skus); $mres = $motiv->getInventory($branch_codes, $skus);
foreach ($mres as $mres_item) foreach ($mres as $mres_item)
@ -2103,7 +2192,7 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
} }
// initialize hub form // initialize hub form
public function initializeHubForm($id, $map_tools) public function initializeHubForm($id, HubSelector $hub_selector)
{ {
$em = $this->em; $em = $this->em;
@ -2128,7 +2217,11 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
$params['rejection_reasons'] = JORejectionReason::getCollection(); $params['rejection_reasons'] = JORejectionReason::getCollection();
// get closest hubs // get closest hubs
$hubs = $map_tools->getClosestHubs($obj->getCoordinates(), 50, date("H:i:s")); $hub_criteria = new HubCriteria();
$hub_criteria->setPoint($obj->getCoordinates())
->setLimitResults(50);
$hubs = $hub_selector->find($hub_criteria);
//$hubs = $map_tools->getClosestHubs($obj->getCoordinates(), 50, date("H:i:s"));
$params['status_cancelled'] = JOStatus::CANCELLED; $params['status_cancelled'] = JOStatus::CANCELLED;
$params['hubs'] = []; $params['hubs'] = [];
@ -2681,6 +2774,9 @@ class ResqJobOrderHandler implements JobOrderHandlerInterface
$fac_hubs[$hub->getID()] = $hub->getName() . ' - ' . $hub->getBranch(); $fac_hubs[$hub->getID()] = $hub->getName() . ' - ' . $hub->getBranch();
} }
// list of customer tags
$params['customer_tags'] = $em->getRepository(CustomerTag::class)->findAll();
// name values // name values
$params['service_types'] = ServiceType::getCollection(); $params['service_types'] = ServiceType::getCollection();
$params['warranty_classes'] = WarrantyClass::getCollection(); $params['warranty_classes'] = WarrantyClass::getCollection();

View file

@ -7,6 +7,7 @@ use Symfony\Component\HttpFoundation\Request;
use App\Service\MQTTClient; use App\Service\MQTTClient;
use App\Service\APNSClient; use App\Service\APNSClient;
use App\Service\MapTools; use App\Service\MapTools;
use App\Service\HubSelector;
use App\Entity\JobOrder; use App\Entity\JobOrder;
@ -67,7 +68,7 @@ interface JobOrderHandlerInterface
public function initializeAllForm(int $id); public function initializeAllForm(int $id);
// initialize dispatch/processing job order form // initialize dispatch/processing job order form
public function initializeProcessingForm(int $id, MapTools $map_tools, $motiv); public function initializeProcessingForm(int $id, HubSelector $hub_selector, $motiv);
// initialize assign job order form // initialize assign job order form
public function initializeAssignForm(int $id); public function initializeAssignForm(int $id);
@ -76,7 +77,7 @@ interface JobOrderHandlerInterface
public function initializeFulfillmentForm(int $id); public function initializeFulfillmentForm(int $id);
// initialize hub form // initialize hub form
public function initializeHubForm(int $id, MapTools $map_tools); public function initializeHubForm(int $id, HubSelector $hub_selector);
// initialize rider form // initialize rider form
public function initializeRiderForm(int $id); public function initializeRiderForm(int $id);

View file

@ -0,0 +1,34 @@
<?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\PromoLog;
class PromoLogger
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function logPromoInfo($created_by, $cust_id, $cust_fname, $cust_lname, $jo_id,
$invoice_id, $amount)
{
$log_entry = new PromoLog();
$log_entry->setCreatedBy($created_by)
->setCustId($cust_id)
->setCustFirstName($cust_fname)
->setCustLastName($cust_lname)
->setJoId($jo_id)
->setInvoiceId($invoice_id)
->setAmount($amount);
$this->em->persist($log_entry);
$this->em->flush();
}
}

View file

@ -13,6 +13,7 @@ use App\Ramcar\JOEventType;
use App\Ramcar\InvoiceStatus; use App\Ramcar\InvoiceStatus;
use App\Ramcar\ModeOfPayment; use App\Ramcar\ModeOfPayment;
use App\Ramcar\InvoiceCriteria; use App\Ramcar\InvoiceCriteria;
use App\Ramcar\WarrantySource;
use App\Service\RiderAPIHandlerInterface; use App\Service\RiderAPIHandlerInterface;
use App\Service\RedisClientProvider; use App\Service\RedisClientProvider;
@ -598,7 +599,10 @@ class ResqRiderAPIHandler implements RiderAPIHandlerInterface
} }
} }
$this->wh->createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number, $batt_list, $date_purchase, $warranty_class); // for riders, use rider session id
$user_id = $this->session->getID();
$source = WarrantySource::RAPI;
$this->wh->createWarranty($serial, $plate_number, $first_name, $last_name, $mobile_number, $batt_list, $date_purchase, $warranty_class, $user_id, $source);
} }
// send mqtt event (fulfilled) // send mqtt event (fulfilled)

View file

@ -83,4 +83,28 @@ class RisingTideGateway
error_log($result); error_log($result);
} }
public function validatePhoneNumber($mobile)
{
// check valid number
$num = trim($mobile);
// should be 10 digits
if (strlen($num) != 10)
return false;
// should start with '9'
if ($num[0] != '9')
return false;
// should be numeric
if (!is_numeric($num))
return false;
// should not be 9900000000
if ($num == '9900000000')
return false;
return true;
}
} }

View file

@ -0,0 +1,35 @@
<?php
namespace App\Service;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\WarrantyAPILog;
class WarrantyAPILogger
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function logWarrantyInfo($log_data, $error, $user_id, $action, $source)
{
$log_entry = new WarrantyAPILog();
$err_aray = [];
$err_array[] = $error;
$log_entry->setApiUser($user_id)
->setErrors($err_array)
->setAllData($log_data)
->setAction($action)
->setSource($source);
$this->em->persist($log_entry);
$this->em->flush();
}
}

View file

@ -11,6 +11,8 @@ use App\Entity\SAPBattery;
use App\Entity\BatteryModel; use App\Entity\BatteryModel;
use App\Entity\CustomerVehicle; use App\Entity\CustomerVehicle;
use App\Service\WarrantyAPILogger;
use App\Ramcar\WarrantyClass; use App\Ramcar\WarrantyClass;
use DateTime; use DateTime;
@ -19,18 +21,23 @@ use DateInterval;
class WarrantyHandler class WarrantyHandler
{ {
protected $em; protected $em;
protected $logger;
public function __construct(EntityManagerInterface $em) public function __construct(EntityManagerInterface $em, WarrantyAPILogger $logger)
{ {
$this->em = $em; $this->em = $em;
$this->logger = $logger;
} }
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) $batt_list, DateTime $date_purchase, $warranty_class, $user_id, $source)
{ {
// new warranty // new warranty
$warranty = new Warranty(); $warranty = new Warranty();
$bmodel_name = '';
$bsize_name ='';
$sap_batt_id = '';
foreach ($batt_list as $battery) foreach ($batt_list as $battery)
{ {
// get the battery model and battery size // get the battery model and battery size
@ -43,10 +50,12 @@ class WarrantyHandler
if ($bty_model != null) if ($bty_model != null)
{ {
$warranty->setBatteryModel($bty_model); $warranty->setBatteryModel($bty_model);
$bmodel_name = $bty_model->getName();
} }
if ($bty_size != null) if ($bty_size != null)
{ {
$warranty->setBatterySize($bty_size); $warranty->setBatterySize($bty_size);
$bsize_name = $bty_size->getName();
} }
$sap_code = $battery->getSAPCode(); $sap_code = $battery->getSAPCode();
@ -57,6 +66,7 @@ class WarrantyHandler
if ($sap_battery != null) if ($sap_battery != null)
{ {
$warranty->setSAPBattery($sap_battery); $warranty->setSAPBattery($sap_battery);
$sap_batt_id = $sap_battery->getID();
} }
} }
} }
@ -87,6 +97,22 @@ class WarrantyHandler
$this->em->persist($warranty); $this->em->persist($warranty);
$this->em->flush(); $this->em->flush();
// log warranty creation
$action = 'create';
$log_data = [
'serial' => $serial,
'warranty_class' => $warranty_class,
'first_name' => $first_name,
'last_name' => $last_name,
'mobile_number' => $mobile_number,
'date_purchase' => $date_purchase->format('d-M-y'),
'date_expire' => $date_expire->format('d-M-y'),
'battery_model' => $bmodel_name,
'battery_size' => $bsize_name,
'sap_battery' => $sap_batt_id,
'plate_number' => $plate_number,
];
$this->logger->logWarrantyInfo($log_data, '', $user_id, $action, $source);
// update customer vehicle with warranty info // update customer vehicle with warranty info
$this->updateCustomerVehicle($serial, $batt_list, $plate_number, $date_expire); $this->updateCustomerVehicle($serial, $batt_list, $plate_number, $date_expire);

View file

@ -44,6 +44,9 @@
"doctrine/dbal": { "doctrine/dbal": {
"version": "v2.6.3" "version": "v2.6.3"
}, },
"doctrine/deprecations": {
"version": "v0.5.3"
},
"doctrine/doctrine-bundle": { "doctrine/doctrine-bundle": {
"version": "1.6", "version": "1.6",
"recipe": { "recipe": {
@ -96,7 +99,10 @@
"version": "v1.0.1" "version": "v1.0.1"
}, },
"doctrine/reflection": { "doctrine/reflection": {
"version": "v1.0.0" "version": "1.2.2"
},
"doctrine/sql-formatter": {
"version": "1.1.2"
}, },
"edwinhoksberg/php-fcm": { "edwinhoksberg/php-fcm": {
"version": "1.0.0" "version": "1.0.0"
@ -110,8 +116,11 @@
"guzzlehttp/psr7": { "guzzlehttp/psr7": {
"version": "1.4.2" "version": "1.4.2"
}, },
"jdorn/sql-formatter": { "hashids/hashids": {
"version": "v1.2.17" "version": "4.1.0"
},
"laminas/laminas-zendframework-bridge": {
"version": "1.1.1"
}, },
"microsoft/azure-storage-blob": { "microsoft/azure-storage-blob": {
"version": "1.5.2" "version": "1.5.2"
@ -119,6 +128,9 @@
"microsoft/azure-storage-common": { "microsoft/azure-storage-common": {
"version": "1.5.1" "version": "1.5.1"
}, },
"monolog/monolog": {
"version": "2.2.0"
},
"nikic/php-parser": { "nikic/php-parser": {
"version": "v4.1.0" "version": "v4.1.0"
}, },
@ -188,6 +200,9 @@
"symfony/dependency-injection": { "symfony/dependency-injection": {
"version": "v4.0.2" "version": "v4.0.2"
}, },
"symfony/deprecation-contracts": {
"version": "v2.4.0"
},
"symfony/doctrine-bridge": { "symfony/doctrine-bridge": {
"version": "v4.0.2" "version": "v4.0.2"
}, },
@ -227,15 +242,15 @@
"ref": "18f6fdceb63737d991efbb37ae9619a6f6c978c8" "ref": "18f6fdceb63737d991efbb37ae9619a6f6c978c8"
} }
}, },
"symfony/http-client-contracts": {
"version": "v2.4.0"
},
"symfony/http-foundation": { "symfony/http-foundation": {
"version": "v4.0.2" "version": "v4.0.2"
}, },
"symfony/http-kernel": { "symfony/http-kernel": {
"version": "v4.0.2" "version": "v4.0.2"
}, },
"symfony/inflector": {
"version": "v4.0.2"
},
"symfony/maker-bundle": { "symfony/maker-bundle": {
"version": "1.0", "version": "1.0",
"recipe": { "recipe": {
@ -245,18 +260,36 @@
"ref": "fadbfe33303a76e25cb63401050439aa9b1a9c7f" "ref": "fadbfe33303a76e25cb63401050439aa9b1a9c7f"
} }
}, },
"symfony/mime": { "symfony/monolog-bridge": {
"version": "v4.3.0" "version": "v5.2.5"
}, },
"symfony/orm-pack": { "symfony/monolog-bundle": {
"version": "v1.0.5" "version": "3.7",
"recipe": {
"repo": "github.com/symfony/recipes",
"branch": "master",
"version": "3.7",
"ref": "329f6a5ef2e7aa033f802be833ef8d1268dd0848"
},
"files": [
"config/packages/dev/monolog.yaml",
"config/packages/prod/deprecations.yaml",
"config/packages/prod/monolog.yaml",
"config/packages/test/monolog.yaml"
]
}, },
"symfony/polyfill-ctype": { "symfony/polyfill-ctype": {
"version": "v1.9.0" "version": "v1.9.0"
}, },
"symfony/polyfill-intl-grapheme": {
"version": "v1.23.1"
},
"symfony/polyfill-intl-idn": { "symfony/polyfill-intl-idn": {
"version": "v1.11.0" "version": "v1.11.0"
}, },
"symfony/polyfill-intl-normalizer": {
"version": "v1.23.0"
},
"symfony/polyfill-mbstring": { "symfony/polyfill-mbstring": {
"version": "v1.6.0" "version": "v1.6.0"
}, },
@ -266,15 +299,21 @@
"symfony/polyfill-php73": { "symfony/polyfill-php73": {
"version": "v1.11.0" "version": "v1.11.0"
}, },
"symfony/polyfill-php80": {
"version": "v1.23.1"
},
"symfony/polyfill-php81": {
"version": "v1.23.0"
},
"symfony/process": { "symfony/process": {
"version": "v4.4.9" "version": "v4.4.9"
}, },
"symfony/profiler-pack": {
"version": "v1.0.3"
},
"symfony/property-access": { "symfony/property-access": {
"version": "v4.0.2" "version": "v4.0.2"
}, },
"symfony/property-info": {
"version": "v5.3.8"
},
"symfony/routing": { "symfony/routing": {
"version": "4.0", "version": "4.0",
"recipe": { "recipe": {
@ -311,6 +350,9 @@
"symfony/stopwatch": { "symfony/stopwatch": {
"version": "v4.0.2" "version": "v4.0.2"
}, },
"symfony/string": {
"version": "v5.3.10"
},
"symfony/thanks": { "symfony/thanks": {
"version": "v1.1.0" "version": "v1.1.0"
}, },

View file

@ -0,0 +1,155 @@
{% 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">Customer Tags</h3>
</div>
</div>
</div>
<!-- END: Subheader -->
<div class="m-content">
<!--Begin::Section-->
<div class="row">
<div class="col-xl-10">
<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 Customer Tag
<small>{{ obj.getName }}</small>
{% else %}
New Customer Tag
{% endif %}
</h3>
</div>
</div>
</div>
<form id="row-form" class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed" method="post" action="{{ mode == 'update' ? url('customertag_update_submit', {'id': obj.getId}) : url('customertag_create_submit') }}">
<div class="m-portlet__body">
<div class="form-group m-form__group row no-border">
<div class="col-lg-6">
<label for="id" data-field="id">
Customer Tag ID
</label>
<input type="text" name="id" class="form-control m-input" value="{{ obj.getID }}">
<div class="form-control-feedback hide" data-field="id"></div>
<span class="m-form__help">Unique identifier for this customer tag</span>
</div>
</div>
<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>
<div class="form-group m-form__group row no-border">
<div class="col-lg-6">
<label for="tag_details" data-field="tag_details">
Tag Details
</label>
<input type="text" name="tag_details" class="form-control m-input" value="{{ obj.getAllTagDetails|default('') }}">
<div class="form-control-feedback hide" data-field="tag_details"></div>
<span class="m-form__help">JSON format e.g. {"type":"discount", "discount_type":"percent", ...}</span>
</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('customertag_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('customertag_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,143 @@
{% 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">
Customer Tags
</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('customertag_create') }}" class="btn btn-focus m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">
<span>
<i class="la la-star-o"></i>
<span>New Customer Tag</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("customertag_rows") }}',
method: 'POST',
}
},
saveState: {
cookie: false,
webstorage: false
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
columns: [
{
field: 'id',
title: 'ID',
width: 250
},
{
field: 'name',
title: 'Name'
},
{
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

@ -160,6 +160,19 @@
</span> </span>
<div class="form-control-feedback hide" data-field="flag_active"></div> <div class="form-control-feedback hide" data-field="flag_active"></div>
</div> </div>
<div class="col-lg-4">
<div class="col-lg-12 form-group-inner">
<div class="m-checkbox-list">
{% for customer_tag in customer_tags %}
<label class="m-checkbox">
<input type="checkbox" name="customer_tags[]" value="{{ customer_tag.getID() }}"{{ customer_tag.getID() in obj.getCustomerTags() ? ' checked' : '' }}>
{{ customer_tag.getName() }}
<span></span>
</label>
{% endfor %}
</div>
</div>
</div>
</div> </div>
</div> </div>

View file

@ -90,6 +90,18 @@
<input type="text" name="branch_code" class="form-control m-input" value="{{ obj.getBranchCode() }}"> <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 class="form-control-feedback hide" data-field="branch_code"></div>
</div> </div>
<div class="col-lg-6">
<label for="notif_number" data-field="notif_number">
Notification Number
</label>
<div class="input-group m-input-group">
<span class="input-group-addon">{% trans %}country_code_prefix{% endtrans %}</span>
<input type="text" name="notif_number" class="form-control m-input" value="{{ obj.getNotifNumber|default('') }}" data-name="notif_number">
<div class="form-control-feedback hide" data-field="notif_number"></div>
</div>
</div>
</div>
<div class="form-group m-form__group row no-border">
<div class="col-lg-3"> <div class="col-lg-3">
<label for="rider_slots" data-field="rider_slots"> <label for="rider_slots" data-field="rider_slots">
Number of Riders Per Slot Number of Riders Per Slot
@ -142,6 +154,22 @@
</span> </span>
</div> </div>
</div> </div>
<div class="form-group m-form__group row no-border">
<div class="col-lg-6">
<label data-field="payment_method">Payment Methods</label>
<div class="m-checkbox-list">
{% for key, value in payment_methods %}
<label class="m-checkbox">
<input type="checkbox" name="payment_methods[]" value="{{ key }}"{{ key in obj.getPaymentMethods ? ' checked' : '' }}>
{{ value }}
<span></span>
</label>
{% endfor %}
</div>
<div class="form-control-feedback hide" data-field="payment_methods"></div>
<span class="m-form__help">Check all payment methods that apply</span>
</div>
</div>
<div class="form-group m-form__group row"> <div class="form-group m-form__group row">
<div class="col-lg-12"> <div class="col-lg-12">
<label> <label>

View file

@ -201,11 +201,29 @@
</div> </div>
<div class="col-lg-3"> <div class="col-lg-3">
{% if is_granted('customer.dpa') %} {% if is_granted('customer.dpa') %}
<input type="checkbox" name="flag_dpa_consent" id="flag-dpa-consent" value="1"{{ obj.getCustomer ? obj.getCustomer.isDpaConsent ? ' checked' }} i> <input type="checkbox" name="flag_dpa_consent" id="flag-dpa-consent" value="1"{{ obj.getCustomer ? obj.getCustomer.isDpaConsent ? ' checked' }} >
<label class="switch-label">With DPA Consent</label> <label class="switch-label">With DPA Consent</label>
<div class="form-control-feedback hide" data-field="flag_dpa_consent"></div> <div class="form-control-feedback hide" data-field="flag_dpa_consent"></div>
{% endif %} {% endif %}
</div> </div>
<div class="col-lg-3">
<div class="col-lg-12 form-group-inner">
<div class="m-checkbox-list">
{% for customer_tag in customer_tags %}
<label class="m-checkbox">
{% if obj.getCustomer %}
<input type="checkbox" name="customer_tags[]" value="{{ customer_tag.getID() }}"{{ customer_tag.getID() in obj.getCustomer.getCustomerTags() ? ' checked' : '' }} disabled>
{{ customer_tag.getName() }}
{% else %}
<input type="checkbox" name="customer_tags[]" value="{{ customer_tag.getID() }}" disabled>
{{ customer_tag.getName() }}
{% endif %}
<span></span>
</label>
{% endfor %}
</div>
</div>
</div>
</div> </div>
</div> </div>
<div class="m-form__section"> <div class="m-form__section">
@ -1370,6 +1388,18 @@ $(function() {
if (vdata.customer.flag_research_email === true) { if (vdata.customer.flag_research_email === true) {
$("#flag-research-email").prop("checked", true); $("#flag-research-email").prop("checked", true);
} }
if (vdata.customer.customer_tags.length > 0) {
var checkboxes = document.getElementsByName("customer_tags[]");
for (var x = 0; checkboxes.length > x; x++)
{
if (vdata.customer.customer_tags.indexOf(checkboxes[x].value) !== -1) {
checkboxes[x].checked = true;
}
else {
checkboxes[x].checked = false;
}
}
}
// set hidden customer id // set hidden customer id
$("#cid").val(vdata.customer.id); $("#cid").val(vdata.customer.id);
@ -1417,6 +1447,12 @@ $(function() {
$("#flag-promo-email").prop("checked", false); $("#flag-promo-email").prop("checked", false);
$("#flag-research-sms").prop("checked", false); $("#flag-research-sms").prop("checked", false);
$("#flag-research-email").prop("checked", false); $("#flag-research-email").prop("checked", false);
var checkboxes = document.getElementsByName("customer_tags[]");
for (var x = 0; checkboxes.length > x; x++)
{
checkboxes[x].checked = false;
}
} }
// datepicker // datepicker

View file

@ -4,7 +4,7 @@
{% set cust = jo.getCustomer %} {% set cust = jo.getCustomer %}
{% set cv = jo.getCustomerVehicle %} {% set cv = jo.getCustomerVehicle %}
<br> <br>
<a href="{{ url('jo_onestep_edit_form', {'id': jo.getID}) }}">Job Order #{{ jo.getID }}</a><br> <a href="{{ url('jo_open_edit_form', {'id': jo.getID}) }}">Job Order #{{ jo.getID }}</a><br>
{{ jo.getServiceTypeName }}<br> {{ jo.getServiceTypeName }}<br>
{{ jo.getStatusText }}<br><br> {{ jo.getStatusText }}<br><br>
{{ cust.getNameDisplay }}<br> {{ cust.getNameDisplay }}<br>
@ -17,7 +17,7 @@
{% set customer = job_order.getCustomer %} {% set customer = job_order.getCustomer %}
{% set cust_vehicle = job_order.getCustomerVehicle %} {% set cust_vehicle = job_order.getCustomerVehicle %}
<br> <br>
<a href="{{ url('jo_onestep_edit_form', {'id': job_order.getID}) }}">Job Order #{{ job_order.getID }}</a><br> <a href="{{ url('jo_open_edit_form', {'id': job_order.getID}) }}">Job Order #{{ job_order.getID }}</a><br>
{{ customer.getNameDisplay }}<br> {{ customer.getNameDisplay }}<br>
{{ cust_vehicle.getPlateNumber }} {{ cust_vehicle.getPlateNumber }}
{% endfor %} {% endfor %}

View file

@ -98,6 +98,7 @@
SAP Battery SAP Battery
</label> </label>
<select name="sap_battery" class="form-control m-input"> <select name="sap_battery" class="form-control m-input">
<option value=""></option>
{% for sap_battery in sap_batts %} {% for sap_battery in sap_batts %}
<option value="{{ sap_battery.getID }}"{{ obj.getSAPBattery.getID|default(0) == sap_battery.getID ? ' selected' }}>{{ sap_battery.getID }}</option> <option value="{{ sap_battery.getID }}"{{ obj.getSAPBattery.getID|default(0) == sap_battery.getID ? ' selected' }}>{{ sap_battery.getID }}</option>
{% endfor %} {% endfor %}
@ -109,6 +110,7 @@
Battery Model Battery Model
</label> </label>
<select name="battery_model" class="form-control m-input"> <select name="battery_model" class="form-control m-input">
<option value=""></option>
{% for model in batt_models %} {% for model in batt_models %}
<option value="{{ model.getID }}"{{ obj.getBatteryModel.getID|default(0) == model.getID ? ' selected' }}>{{ model.getName }}</option> <option value="{{ model.getID }}"{{ obj.getBatteryModel.getID|default(0) == model.getID ? ' selected' }}>{{ model.getName }}</option>
{% endfor %} {% endfor %}

View file

@ -13,6 +13,7 @@ add_cust_vehicle_battery_info: This vehicle is using a Motolite battery
jo_title_pdf: Motolite Res-Q Job Order jo_title_pdf: Motolite Res-Q Job Order
country_code_prefix: '+63' country_code_prefix: '+63'
delivery_instructions_label: Delivery Instructions delivery_instructions_label: Delivery Instructions
no_inventory_message: No stock for [item_display]
# images # images
image_logo_login: /assets/images/logo-resq.png image_logo_login: /assets/images/logo-resq.png

View file

@ -0,0 +1,57 @@
<?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/warranty';
//$sas_token = 'sp=r&st=2021-03-18T08:26:36Z&se=2021-04-29T16:26:36Z&spr=https&sv=2020-02-10&sr=c&sig=Rwl3aCNThXEzuPjNB9sTvZzsx84ULDylyS1WtPwgyzg%3D';
$blob_url = 'https://popappshopprodstorage.blob.core.windows.net';
//$sas_token = 'sp=r&st=2021-03-20T17:09:13Z&se=2021-04-01T01:09:13Z&spr=https&sv=2020-02-10&sr=c&sig=pU2fxj6eXALfGTTrsmaJ7W0QtdstyR88Xs5lvMJ35xQ%3D';
$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 start date from argument: 04-01-21 format
$start_date = $argv[1];
$current_date = new DateTime();
$end_date = $current_date->format('m-d-y');
$flag_done_processing = false;
$proc_date = $start_date;
while (!$flag_done_processing) {
$filename = 'warrantylogs' . $proc_date . '.csv';
echo $filename, PHP_EOL;
try {
// NOTE: via download blob
$res = $blob_client->getBlob('warranty', $filename);
// print_r($res);
file_put_contents("/tmp/output.txt", $res->getContentStream(), FILE_APPEND);
} catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// change proc_date to next day
$next_date = DateTime::createFromFormat('m-d-y', $proc_date);
$next_date->modify('+1 day');
$proc_date = $next_date->format('m-d-y');
if ($end_date == $proc_date) {
$flag_done_processing = true;
}
}

View file

@ -0,0 +1,52 @@
<?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/warranty';
//$sas_token = 'sp=r&st=2021-03-18T08:26:36Z&se=2021-04-29T16:26:36Z&spr=https&sv=2020-02-10&sr=c&sig=Rwl3aCNThXEzuPjNB9sTvZzsx84ULDylyS1WtPwgyzg%3D';
$blob_url = 'https://popappshopprodstorage.blob.core.windows.net';
//$sas_token = 'sp=r&st=2021-03-20T17:09:13Z&se=2021-04-01T01:09:13Z&spr=https&sv=2020-02-10&sr=c&sig=pU2fxj6eXALfGTTrsmaJ7W0QtdstyR88Xs5lvMJ35xQ%3D';
$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);
$current_date = new DateTime();
$current_date->modify("-1 day");
$date = $current_date->format('m-d-y');
$filename = 'warrantylogs' . $date . '.csv';
//print_r($filename);
try {
// NOTE: via download blob
$res = $blob_client->getBlob('warranty', $filename);
// print_r($res);
file_put_contents("/tmp/output.txt", $res->getContentStream());
} catch (Exception $e) {
file_put_contents("/tmp/serial_download_error.txt", $filename . "\n" . $e->getMessage() . "\n" . "\n", FILE_APPEND);
}
/*
// NOTE: getting via url
echo $blob_client->getPsrPrimaryUri() . "\n";
$url = $blob_client->getPsrPrimaryUri() . '?' . $sas_token;
$url = $blob_url . '?' . $sas_token;
file_put_contents('output.txt', fopen($url, 'r'));
*/

View file

@ -10,7 +10,7 @@ $pass = $argv[4];
$db = new PDO($dsn, $user, $pass); $db = new PDO($dsn, $user, $pass);
// prepared statement // prepared statement
$sth = $db->prepare('insert into warranty_serial (id, sku, date_create, source) values (:serial, :sku, :date_create, :source)'); $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
@ -25,16 +25,41 @@ while (($row = fgetcsv($csv)) !== false)
continue; continue;
} }
/*
$serial = trim(strtoupper($row[0])); $serial = trim(strtoupper($row[0]));
$sku = trim($row[1]); $sku = trim($row[1]);
$date_create = $row[2]; $date_create = $row[2];
$ref_id = $row[3]; $ref_id = $row[3]; */
// sample of line in output file:
// 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
$serial = trim(strtoupper($row[0]));
$sku = trim($row[1]);
$dispatch_status = trim($row[2]);
$date_create = $row[3];
$inventory_status = trim($row[4]);
$cat_id = trim($row[5]);
$cat_name = trim($row[6]);
$meta_info = [
'dispatch_status' => $dispatch_status,
'inventory_status' => $inventory_status,
'category_id' => $cat_id,
'category_name' => $cat_name,
];
$info = json_encode($meta_info);
if ($sku == 'N/A')
$sku = null;
$res = $sth->execute([ $res = $sth->execute([
':serial' => $serial, ':serial' => $serial,
':sku' => $sku, ':sku' => $sku,
':date_create' => $date_create, ':date_create' => $date_create,
':source' => $source ':source' => $source,
':meta_info' => $info,
]); ]);
if (!$res) if (!$res)

View file

@ -1,11 +1,204 @@
DispatcheDate,Sku,SerialNumber PV1000240341,N/A,Dispatch,In,2021-04-12T01:12:16.5930000+08:00
2020-08-07 05:32:04.537,WMGL23DL-CPNMB-L,MGS706202004 PV1000240344,N/A,Dispatch,In,2021-04-12T01:12:16.6100000+08:00
2020-08-07 05:32:04.537,WMGL23DL-CPNMB-L,MGS706202005 PV1000240335,N/A,Dispatch,In,2021-04-12T01:12:16.5630000+08:00
2020-08-07 05:32:04.537,WMGL23DL-CPNMB-L,MGS706202006 PV1000240345,N/A,Dispatch,In,2021-04-12T01:12:16.5930000+08:00
2020-08-08 09:27:14.480,WMXX26EL-CPN00-LX,MXS808202001 PV1000240338,N/A,Dispatch,In,2021-04-12T01:12:16.5930000+08:00
2020-08-08 09:31:48.737,WMXX26EL-CPN00-LX,MXS808202002 PV1000240340,N/A,Dispatch,In,2021-04-12T01:12:16.5930000+08:00
2020-08-08 10:27:08.117,WMXX26EL-CPN00-LX,MXS808202003 PV1000240337,N/A,Dispatch,In,2021-04-12T01:12:16.5770000+08:00
2020-08-08 10:41:10.060,WMXX26EL-CPN00-LX,MXS808202004 PV1000240334,N/A,Dispatch,In,2021-04-12T01:12:16.6100000+08:00
2020-08-08 10:41:10.060,WMXX26EL-CPN00-LX,MXS808202005 PV1000240330,N/A,Dispatch,In,2021-04-12T01:12:16.5630000+08:00
2020-08-08 10:41:10.060,WMXX26EL-CPN00-LX,MXS808202006 PV1000240342,N/A,Dispatch,In,2021-04-12T01:12:16.6100000+08:00
2020-10-05 13:53:57.000,ECHD26AL-SPN00-LX,CH2000012625 PV1000240343,N/A,Dispatch,In,2021-04-12T01:12:16.6100000+08:00
PV1000240336,N/A,Dispatch,In,2021-04-12T01:12:16.5630000+08:00
PV1000240339,N/A,Dispatch,In,2021-04-12T01:12:16.5470000+08:00
PV1000240332,N/A,Dispatch,In,2021-04-12T01:12:16.5770000+08:00
PV1000240333,N/A,Dispatch,In,2021-04-12T01:12:16.6100000+08:00
PV1000240324,N/A,Dispatch,In,2021-04-12T01:12:16.5770000+08:00
PV1000240326,N/A,Dispatch,In,2021-04-12T01:12:16.5770000+08:00
MX2000056889,N/A,Dispatch,In,2021-04-12T02:58:37.8900000+08:00
MX2000056874,N/A,Dispatch,In,2021-04-12T02:58:37.9070000+08:00
MX2000056888,N/A,Dispatch,In,2021-04-12T02:58:37.9070000+08:00
MX2000056887,N/A,Dispatch,In,2021-04-12T02:58:37.9070000+08:00
MX2000056881,N/A,Dispatch,In,2021-04-12T02:58:37.9070000+08:00
MX2000056880,N/A,Dispatch,In,2021-04-12T02:58:37.9230000+08:00
MX2000056879,N/A,Dispatch,In,2021-04-12T02:58:37.9370000+08:00
MX2000056886,N/A,Dispatch,In,2021-04-12T02:58:37.9370000+08:00
MX2000056890,N/A,Dispatch,In,2021-04-12T02:58:37.9370000+08:00
MX2000056885,N/A,Dispatch,In,2021-04-12T02:58:37.9370000+08:00
MG3102419196,N/A,Dispatch,In,2021-04-12T02:58:38.2200000+08:00
MG3102419202,N/A,Dispatch,In,2021-04-12T02:58:38.2330000+08:00
MG3102419197,N/A,Dispatch,In,2021-04-12T02:58:38.2330000+08:00
MG3102419203,N/A,Dispatch,In,2021-04-12T02:58:38.2200000+08:00
MG3102419198,N/A,Dispatch,In,2021-04-12T02:58:38.2200000+08:00
PV1000225903,N/A,Dispatch,In,2021-04-11T23:45:21.0630000+08:00
PV1000225928,N/A,Dispatch,In,2021-04-11T23:45:21.0500000+08:00
PV1000225905,N/A,Dispatch,In,2021-04-11T23:45:20.9870000+08:00
PV1000225909,N/A,Dispatch,In,2021-04-11T23:45:21.0330000+08:00
PV1000225918,N/A,Dispatch,In,2021-04-11T23:45:21.1900000+08:00
PV1000225911,N/A,Dispatch,In,2021-04-11T23:45:21.1100000+08:00
PV1000225933,N/A,Dispatch,In,2021-04-11T23:45:21.0170000+08:00
PV1000225939,N/A,Dispatch,In,2021-04-11T23:45:21.0500000+08:00
PV1000225940,N/A,Dispatch,In,2021-04-11T23:45:21.2030000+08:00
PV1000225934,N/A,Dispatch,In,2021-04-11T23:45:21.0500000+08:00
PV1000225916,N/A,Dispatch,In,2021-04-11T23:45:21.0630000+08:00
PV1000225915,N/A,Dispatch,In,2021-04-11T23:45:21+08:00
PV1000225937,N/A,Dispatch,In,2021-04-11T23:45:21+08:00
PV1000225929,N/A,Dispatch,In,2021-04-11T23:45:21.0170000+08:00
PV1000225906,N/A,Dispatch,In,2021-04-11T23:45:21.1100000+08:00
PV1000225938,N/A,Dispatch,In,2021-04-11T23:45:21.0970000+08:00
PV1000225902,N/A,Dispatch,In,2021-04-11T23:45:21.0800000+08:00
PV1000225914,N/A,Dispatch,In,2021-04-11T23:45:21+08:00
PV1000225932,N/A,Dispatch,In,2021-04-11T23:45:21+08:00
PV1000225908,N/A,Dispatch,In,2021-04-11T23:45:21.0630000+08:00
PV1000225907,N/A,Dispatch,In,2021-04-11T23:45:21.0800000+08:00
PV1000225910,N/A,Dispatch,In,2021-04-11T23:45:20.9870000+08:00
PV1000225917,N/A,Dispatch,In,2021-04-11T23:45:21.0330000+08:00
PV1000225921,N/A,Dispatch,In,2021-04-11T23:45:21.0330000+08:00
PV1000225913,N/A,Dispatch,In,2021-04-11T23:45:20.9870000+08:00
PV1000225919,N/A,Dispatch,In,2021-04-11T23:45:21.0800000+08:00
PV1000225935,N/A,Dispatch,In,2021-04-11T23:45:21.0970000+08:00
PV1000225900,N/A,Dispatch,In,2021-04-11T23:45:21.0330000+08:00
PV1000225904,N/A,Dispatch,In,2021-04-11T23:45:21.1100000+08:00
PV1000225931,N/A,Dispatch,In,2021-04-11T23:45:21.0970000+08:00
PV1000225897,N/A,Dispatch,In,2021-04-11T23:45:21.0800000+08:00
PV1000225901,N/A,Dispatch,In,2021-04-11T23:45:20.9870000+08:00
PV1000225930,N/A,Dispatch,In,2021-04-11T23:45:21.2030000+08:00
PV1000225926,N/A,Dispatch,In,2021-04-11T23:45:21.1900000+08:00
PV1000225898,N/A,Dispatch,In,2021-04-11T23:45:21.0630000+08:00
PV1000225927,N/A,Dispatch,In,2021-04-11T23:45:21.0970000+08:00
PV1000225896,N/A,Dispatch,In,2021-04-11T23:45:21.0330000+08:00
PV1000225924,N/A,Dispatch,In,2021-04-11T23:45:21.0500000+08:00
PV1000225983,N/A,Dispatch,In,2021-04-11T23:45:20.9700000+08:00
PV1000225925,N/A,Dispatch,In,2021-04-11T23:45:21.0170000+08:00
PV1000225985,N/A,Dispatch,In,2021-04-11T23:45:20.9700000+08:00
PV1000225912,N/A,Dispatch,In,2021-04-11T23:45:20.9870000+08:00
PV1000225980,N/A,Dispatch,In,2021-04-11T23:45:20.9700000+08:00
PV1000225982,N/A,Dispatch,In,2021-04-11T23:45:20.9700000+08:00
PV1000225922,N/A,Dispatch,In,2021-04-11T23:45:21.1900000+08:00
PV1000225923,N/A,Dispatch,In,2021-04-11T23:45:21.0800000+08:00
PV1000225984,N/A,Dispatch,In,2021-04-11T23:45:20.9700000+08:00
PV1000225899,N/A,Dispatch,In,2021-04-11T23:45:20.9870000+08:00
PV1000225920,N/A,Dispatch,In,2021-04-11T23:45:21.0500000+08:00
MES215591711,N/A,Dispatch,In,2021-04-11T22:36:43.9830000+08:00
MES215591707,N/A,Dispatch,In,2021-04-11T22:36:43.9670000+08:00
MES215591708,N/A,Dispatch,In,2021-04-11T22:36:43.9830000+08:00
MES215591699,N/A,Dispatch,In,2021-04-11T22:36:43.8600000+08:00
MES215591700,N/A,Dispatch,In,2021-04-11T22:36:43.8430000+08:00
MES215591718,N/A,Dispatch,In,2021-04-11T22:36:44.0770000+08:00
MES215591733,N/A,Dispatch,In,2021-04-11T22:36:44.0770000+08:00
MES215591725,N/A,Dispatch,In,2021-04-11T22:36:44.0600000+08:00
MES215591723,N/A,Dispatch,In,2021-04-11T22:36:44.0930000+08:00
MES215591724,N/A,Dispatch,In,2021-04-11T22:36:44.0930000+08:00
MES215591712,N/A,Dispatch,In,2021-04-11T22:36:44.0130000+08:00
MES215591716,N/A,Dispatch,In,2021-04-11T22:36:44.0300000+08:00
MES215591713,N/A,Dispatch,In,2021-04-11T22:36:44.0130000+08:00
MES215591714,N/A,Dispatch,In,2021-04-11T22:36:44.0300000+08:00
MES215591719,N/A,Dispatch,In,2021-04-11T22:36:44.0130000+08:00
MES215591721,N/A,Dispatch,In,2021-04-11T22:36:44.0300000+08:00
MES215591720,N/A,Dispatch,In,2021-04-11T22:36:44.0300000+08:00
MES215591722,N/A,Dispatch,In,2021-04-11T22:36:44.0470000+08:00
MES215591715,N/A,Dispatch,In,2021-04-11T22:36:44.0470000+08:00
MES215591709,N/A,Dispatch,In,2021-04-11T22:36:44+08:00
MES215591710,N/A,Dispatch,In,2021-04-11T22:36:44+08:00
MES215591704,N/A,Dispatch,In,2021-04-11T22:36:43.9670000+08:00
MES215591706,N/A,Dispatch,In,2021-04-11T22:36:43.9830000+08:00
MES215591698,N/A,Dispatch,In,2021-04-11T22:36:43.8430000+08:00
MES215591705,N/A,Dispatch,In,2021-04-11T22:36:43.8600000+08:00
MES215591732,N/A,Dispatch,In,2021-04-11T22:36:44.0770000+08:00
MES215591731,N/A,Dispatch,In,2021-04-11T22:36:44.0770000+08:00
MES215591717,N/A,Dispatch,In,2021-04-11T22:36:44.0470000+08:00
MES215591727,N/A,Dispatch,In,2021-04-11T22:36:44.0470000+08:00
MES215591695,N/A,Dispatch,In,2021-04-11T22:36:43.9530000+08:00
MES215591701,N/A,Dispatch,In,2021-04-11T22:36:44+08:00
MES215591702,N/A,Dispatch,In,2021-04-11T22:36:44+08:00
MES215591689,N/A,Dispatch,In,2021-04-11T22:36:43.8430000+08:00
MES215591692,N/A,Dispatch,In,2021-04-11T22:36:43.8600000+08:00
MES215591696,N/A,Dispatch,In,2021-04-11T22:36:43.9670000+08:00
MES215591697,N/A,Dispatch,In,2021-04-11T22:36:43.9670000+08:00
MES215591703,N/A,Dispatch,In,2021-04-11T22:36:44+08:00
MES215591690,N/A,Dispatch,In,2021-04-11T22:36:43.8430000+08:00
MES215591693,N/A,Dispatch,In,2021-04-11T22:36:43.8600000+08:00
MES215591681,N/A,Dispatch,In,2021-04-11T22:36:43.8270000+08:00
MES215591683,N/A,Dispatch,In,2021-04-11T22:36:43.9530000+08:00
MES215591687,N/A,Dispatch,In,2021-04-11T22:36:43.9530000+08:00
MES215591686,N/A,Dispatch,In,2021-04-11T22:36:43.9530000+08:00
MES215591688,N/A,Dispatch,In,2021-04-11T22:36:44.0130000+08:00
MES215591685,N/A,Dispatch,In,2021-04-11T22:36:43.8730000+08:00
MES215591682,N/A,Dispatch,In,2021-04-11T22:36:43.8270000+08:00
MES215591684,N/A,Dispatch,In,2021-04-11T22:36:43.8430000+08:00
MES215591691,N/A,Dispatch,In,2021-04-11T22:36:43.8600000+08:00
MES215591694,N/A,Dispatch,In,2021-04-11T22:36:43.9670000+08:00
MG3101407704,N/A,Dispatch,In,2021-04-12T00:39:47.1870000+08:00
MG3101407702,N/A,Dispatch,In,2021-04-12T00:39:47.1870000+08:00
MG3101407703,N/A,Dispatch,In,2021-04-12T00:39:47.1870000+08:00
MG3101407701,N/A,Dispatch,In,2021-04-12T00:39:47.1870000+08:00
MG3101407705,N/A,Dispatch,In,2021-04-12T00:39:47.1700000+08:00
MG2000112754,N/A,Dispatch,In,2021-04-12T00:40:11.3670000+08:00
MX2000067982,N/A,Dispatch,In,2021-04-12T00:33:42.1830000+08:00
MX2000067975,N/A,Dispatch,In,2021-04-12T00:33:42.4670000+08:00
MX2000067983,N/A,Dispatch,In,2021-04-12T00:33:42.1830000+08:00
MX2000067979,N/A,Dispatch,In,2021-04-12T00:33:42.4500000+08:00
MX2000067984,N/A,Dispatch,In,2021-04-12T00:33:42.1700000+08:00
MX2000067972,N/A,Dispatch,In,2021-04-12T00:33:42.3730000+08:00
MX2000067971,N/A,Dispatch,In,2021-04-12T00:33:42.4330000+08:00
MX2000067977,N/A,Dispatch,In,2021-04-12T00:33:42.4500000+08:00
MX2000067981,N/A,Dispatch,In,2021-04-12T00:33:42.4670000+08:00
MX2000067974,N/A,Dispatch,In,2021-04-12T00:33:42.4500000+08:00
MX2000067978,N/A,Dispatch,In,2021-04-12T00:33:42.4670000+08:00
MX2000067989,N/A,Dispatch,In,2021-04-12T00:33:42.1700000+08:00
MX2000067980,N/A,Dispatch,In,2021-04-12T00:33:42.1830000+08:00
MX2000067976,N/A,Dispatch,In,2021-04-12T00:33:42.1830000+08:00
MX2000067973,N/A,Dispatch,In,2021-04-12T00:33:42.2170000+08:00
MX2000067985,N/A,Dispatch,In,2021-04-12T00:33:42.1530000+08:00
MX2000067990,N/A,Dispatch,In,2021-04-12T00:33:42.1700000+08:00
MX2000067987,N/A,Dispatch,In,2021-04-12T00:33:42.1700000+08:00
MX2000067992,N/A,Dispatch,In,2021-04-12T00:33:42.5270000+08:00
MX2000067988,N/A,Dispatch,In,2021-04-12T00:33:41.9330000+08:00
MX2000067986,N/A,Dispatch,In,2021-04-12T00:33:42.1700000+08:00
MX2000068005,N/A,Dispatch,In,2021-04-12T00:33:42.4800000+08:00
MX2000068006,N/A,Dispatch,In,2021-04-12T00:33:42.4800000+08:00
MX2000068010,N/A,Dispatch,In,2021-04-12T00:33:42.4970000+08:00
MX2000067994,N/A,Dispatch,In,2021-04-12T00:33:42.8570000+08:00
MX2000067991,N/A,Dispatch,In,2021-04-12T00:33:42.5270000+08:00
MX2000067995,N/A,Dispatch,In,2021-04-12T00:33:42.5130000+08:00
MX2000067997,N/A,Dispatch,In,2021-04-12T00:33:42.5270000+08:00
MX2000067999,N/A,Dispatch,In,2021-04-12T00:33:42.5730000+08:00
MX2000068003,N/A,Dispatch,In,2021-04-12T00:33:42.5130000+08:00
MX2000068015,N/A,Dispatch,In,2021-04-12T00:33:42.9500000+08:00
MX2000068020,N/A,Dispatch,In,2021-04-12T00:33:42.9500000+08:00
MX2000068028,N/A,Dispatch,In,2021-04-12T00:33:42.9030000+08:00
MX2000068024,N/A,Dispatch,In,2021-04-12T00:33:42.9330000+08:00
MX2000068029,N/A,Dispatch,In,2021-04-12T00:33:42.9200000+08:00
MX2000068026,N/A,Dispatch,In,2021-04-12T00:33:42.9200000+08:00
MX2000068023,N/A,Dispatch,In,2021-04-12T00:33:42.9330000+08:00
MX2000068019,N/A,Dispatch,In,2021-04-12T00:33:42.9800000+08:00
MX2000068018,N/A,Dispatch,In,2021-04-12T00:33:42.9800000+08:00
MX2000068014,N/A,Dispatch,In,2021-04-12T00:33:42.9800000+08:00
MX2000068022,N/A,Dispatch,In,2021-04-12T00:33:42.9330000+08:00
MX2000068017,N/A,Dispatch,In,2021-04-12T00:33:42.9670000+08:00
MX2000068011,N/A,Dispatch,In,2021-04-12T00:33:42.9500000+08:00
MX2000068012,N/A,Dispatch,In,2021-04-12T00:33:42.9670000+08:00
MX2000068008,N/A,Dispatch,In,2021-04-12T00:33:42.4800000+08:00
MX2000068009,N/A,Dispatch,In,2021-04-12T00:33:42.4800000+08:00
MX2000068004,N/A,Dispatch,In,2021-04-12T00:33:42.4970000+08:00
MX2000067993,N/A,Dispatch,In,2021-04-12T00:33:42.5430000+08:00
MX2000068016,N/A,Dispatch,In,2021-04-12T00:33:42.9670000+08:00
MX2000068013,N/A,Dispatch,In,2021-04-12T00:33:42.9670000+08:00
MX2000068025,N/A,Dispatch,In,2021-04-12T00:33:42.9030000+08:00
MX2000068021,N/A,Dispatch,In,2021-04-12T00:33:42.9500000+08:00
MX2000068007,N/A,Dispatch,In,2021-04-12T00:33:42.4970000+08:00
MX2000068002,N/A,Dispatch,In,2021-04-12T00:33:42.5130000+08:00
MX2000068000,N/A,Dispatch,In,2021-04-12T00:33:42.5600000+08:00
MX2000067998,N/A,Dispatch,In,2021-04-12T00:33:42.5270000+08:00
MX2000068001,N/A,Dispatch,In,2021-04-12T00:33:42.5130000+08:00
MX2000067996,N/A,Dispatch,In,2021-04-12T00:33:42.5130000+08:00
MX2000067967,N/A,Dispatch,In,2021-04-12T00:33:42.9030000+08:00
MX2000067969,N/A,Dispatch,In,2021-04-12T00:33:42.8870000+08:00
MX2000067968,N/A,Dispatch,In,2021-04-12T00:33:42.8570000+08:00
MX2000067970,N/A,Dispatch,In,2021-04-12T00:33:42.8870000+08:00
MX2000067965,N/A,Dispatch,In,2021-04-12T00:33:42.8730000+08:00
MX2000067966,N/A,Dispatch,In,2021-04-12T00:33:42.8870000+08:00
MX2000067964,N/A,Dispatch,In,2021-04-12T00:33:42.8870000+08:00
MX2000067963,N/A,Dispatch,In,2021-04-12T00:33:42.9030000+08:00
MX2000068030,N/A,Dispatch,In,2021-04-12T00:33:42.9200000+08:00
MX2000068027,N/A,Dispatch,In,2021-04-12T00:33:42.9200000+08:00

View file

@ -7,20 +7,29 @@ require_once(__DIR__ . '/../../vendor/autoload.php');
use MicrosoftAzure\Storage\Blob\BlobRestProxy; use MicrosoftAzure\Storage\Blob\BlobRestProxy;
use MicrosoftAzure\Storage\Common\ServiceException; use MicrosoftAzure\Storage\Common\ServiceException;
$blob_url = 'https://popappshopprodstorage.blob.core.windows.net/warranty'; //$blob_url = 'https://popappshopprodstorage.blob.core.windows.net/warranty';
$sas_token = 'sp=r&st=2021-03-18T08:26:36Z&se=2021-04-29T16:26:36Z&spr=https&sv=2020-02-10&sr=c&sig=Rwl3aCNThXEzuPjNB9sTvZzsx84ULDylyS1WtPwgyzg%3D'; //$sas_token = 'sp=r&st=2021-03-18T08:26:36Z&se=2021-04-29T16:26:36Z&spr=https&sv=2020-02-10&sr=c&sig=Rwl3aCNThXEzuPjNB9sTvZzsx84ULDylyS1WtPwgyzg%3D';
$blob_url = 'https://popappshopprodstorage.blob.core.windows.net'; $blob_url = 'https://popappshopprodstorage.blob.core.windows.net';
$sas_token = 'sp=r&st=2021-03-20T17:09:13Z&se=2021-04-01T01:09:13Z&spr=https&sv=2020-02-10&sr=c&sig=pU2fxj6eXALfGTTrsmaJ7W0QtdstyR88Xs5lvMJ35xQ%3D'; //$sas_token = 'sp=r&st=2021-03-20T17:09:13Z&se=2021-04-01T01:09:13Z&spr=https&sv=2020-02-10&sr=c&sig=pU2fxj6eXALfGTTrsmaJ7W0QtdstyR88Xs5lvMJ35xQ%3D';
$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"; $conn_string = "BlobEndpoint=$blob_url;\nSharedAccessSignature=$sas_token";
$blob_client = BlobRestProxy::createBlobService($conn_string); $blob_client = BlobRestProxy::createBlobService($conn_string);
$current_date = new DateTime();
$current_date->modify("-1 day");
$date = $current_date->format('m-d-Y');
$filename = 'warrantylogs' . $date . '.csv';
//print_r($filename);
// NOTE: via download blob // NOTE: via download blob
$res = $blob_client->getBlob('warranty', 'Sample Result.csv'); $res = $blob_client->getBlob('warranty', $filename);
// print_r($res); // print_r($res);
file_put_contents("output.txt", $res->getContentStream()); file_put_contents("output.txt", $res->getContentStream());