Resolve "Transition branch for CMB and Resq merging" #1181

Merged
korina.cordero merged 258 commits from 329-transition-branch-for-cmb-and-resq-merging into master 2020-04-03 02:49:26 +00:00
143 changed files with 24484 additions and 7981 deletions

View file

@ -15,7 +15,7 @@ APP_SECRET=b344cd6cd151ae1d61403ed55806c5ce
# Configure your db driver and server_version in config/packages/doctrine.yaml
DATABASE_URL=mysql://db_user:db_password@127.0.0.1:3306/db_name
###< doctrine/doctrine-bundle ###
GMAPS_API_KEY=insertgmapsapikeyhere
GMAPS_API_KEY=insert_gmapsapikey_here
# rising tide sms gateway
RT_USER=rt_user
@ -28,6 +28,8 @@ RT_SHORTCODE=1234
MQTT_IP_ADDRESS=localhost
MQTT_PORT=8883
MQTT_CERT=/location/of/cert/file.crt
MQTT_WS_HOST=insert_ip_here
MQTT_WS_PORT=8083
# redis client
REDIS_CLIENT_SCHEME=tcp
@ -36,17 +38,22 @@ REDIS_CLIENT_PORT=6379
REDIS_CLIENT_PASSWORD=foobared
# privacy policy ids
POLICY_PROMO=insertpromopolicyidhere
POLICY_THIRD_PARTY=insertthirdpartypolicyidhere
POLICY_MOBILE=insertmobilepolicyidhere
POLICY_PROMO=insert_promopolicyid_here
POLICY_THIRD_PARTY=insert_thirdpartypolicyid_here
POLICY_MOBILE=insert_mobilepolicyid_here
# OTP
OTP_MODE=settotestorrandom
OTP_MODE=set_to_test_or_random
# geofence
GEOFENCE_ENABLE=settotrueorfalse
GEOFENCE_ENABLE=set_to_true_or_false
# unknown manufacturer and vehicle ids
CVU_MFG_ID=insertmfgidforunknownvehicles
CVU_BRAND_ID=insertbrandidforunknownvehicles
CVU_MFG_ID=insert_mfgid_for_unknown_vehicles
CVU_BRAND_ID=insert_brandid_for_unknown_vehicles
# country code prefix
COUNTRY_CODE=+insert_country_code_here
# dashboard
DASHBOARD_ENABLE=set_to_true_or_false

1
.gitignore vendored
View file

@ -7,6 +7,7 @@
/sql/
/pem/
/migration/
/kml/
###< symfony/framework-bundle ###
*.swp

View file

@ -17,6 +17,7 @@
"predis/predis": "^1.1",
"sensio/framework-extra-bundle": "^5.1",
"setasign/fpdf": "^1.8",
"symfony/asset": "^4.0",
"symfony/console": "^4.0",
"symfony/debug": "^4.0",
"symfony/filesystem": "^4.0",

2139
composer.lock generated

File diff suppressed because it is too large Load diff

View file

@ -242,6 +242,10 @@ access_keys:
label: Edit
- id: joborder.cancel
label: Cancel
- id: jo_onestep.form
label: One-step Process
- id: jo_onestep.edit
label: One-step Process Edit
- id: support
label: Customer Support Access

229
config/cmb.services.yaml Normal file
View file

@ -0,0 +1,229 @@
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
map_default:
latitude: 14.6091
longitude: 121.0223
image_upload_directory: '%kernel.project_dir%/public/uploads'
job_order_refresh_interval: 300000
api_acl_file: 'api_acl.yaml'
api_access_key: 'api_access_keys'
app_acl_file: 'acl.yaml'
app_access_key: 'access_keys'
cvu_brand_id: "%env(CVU_BRAND_ID)%"
country_code: "%env(COUNTRY_CODE)%"
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/*'
exclude: '../src/{Entity,Migrations,Tests,Menu,Access}'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
App\Menu\Generator:
arguments:
$router: "@router.default"
$cache_dir: "%kernel.cache_dir%"
$config_dir: "%kernel.root_dir%/../config"
Catalyst\AuthBundle\Service\ACLGenerator:
arguments:
$router: "@router.default"
$cache_dir: "%kernel.cache_dir%"
$config_dir: "%kernel.root_dir%/../config"
$acl_file: "%app_acl_file%"
Catalyst\AuthBundle\Service\ACLVoter:
arguments:
$user_class: "App\\Entity\\User"
tags: ['security.voter']
Catalyst\AuthBundle\Service\UserChecker:
App\Service\FileUploader:
arguments:
$target_dir: '%image_upload_directory%'
App\Service\MapTools:
arguments:
$em: "@doctrine.orm.entity_manager"
$gmaps_api_key: "%env(GMAPS_API_KEY)%"
App\Service\RisingTideGateway:
arguments:
$em: "@doctrine.orm.entity_manager"
$user: "%env(RT_USER)%"
$pass: "%env(RT_PASS)%"
$usage_type: "%env(RT_USAGE_TYPE)%"
$shortcode: "%env(RT_SHORTCODE)%"
App\Service\MQTTClient:
arguments:
$redis_client: "@App\\Service\\RedisClientProvider"
$key: "mqtt_events"
App\Service\APNSClient:
arguments:
$redis_client: "@App\\Service\\RedisClientProvider"
App\Service\RedisClientProvider:
arguments:
$scheme: "%env(REDIS_CLIENT_SCHEME)%"
$host: "%env(REDIS_CLIENT_HOST)%"
$port: "%env(REDIS_CLIENT_PORT)%"
$password: "%env(REDIS_CLIENT_PASSWORD)%"
App\Service\GeofenceTracker:
arguments:
$geofence_flag: "%env(GEOFENCE_ENABLE)%"
App\Service\WarrantyHandler:
arguments:
$em: "@doctrine.orm.entity_manager"
App\Command\SetCustomerPrivacyPolicyCommand:
arguments:
$policy_promo: "%env(POLICY_PROMO)%"
$policy_third_party: "%env(POLICY_THIRD_PARTY)%"
$policy_mobile: "%env(POLICY_MOBILE)%"
App\Command\CreateCustomerFromWarrantyCommand:
arguments:
$cvu_mfg_id: "%env(CVU_MFG_ID)%"
$cvu_brand_id: "%env(CVU_BRAND_ID)%"
# rider tracker service
App\Service\RiderTracker:
arguments:
$redis_client: "@App\\Service\\RedisClientProvider"
Catalyst\APIBundle\Security\APIKeyUserProvider:
arguments:
$em: "@doctrine.orm.entity_manager"
Catalyst\APIBundle\Security\APIKeyAuthenticator:
arguments:
$em: "@doctrine.orm.entity_manager"
Catalyst\APIBundle\Command\UserCreateCommand:
arguments:
$em: "@doctrine.orm.entity_manager"
tags: ['console.command']
Catalyst\APIBundle\Command\TestCommand:
tags: ['console.command']
Catalyst\APIBundle\Command\TestAPICommand:
tags: ['console.command']
Catalyst\APIBundle\Access\Voter:
arguments:
$acl_gen: "@Catalyst\\APIBundle\\Access\\Generator"
$user_class: "Catalyst\\APIBundle\\Entity\\User"
tags: ['security.voter']
Catalyst\APIBundle\Access\Generator:
arguments:
$router: "@router.default"
$cache_dir: "%kernel.cache_dir%"
$config_dir: "%kernel.root_dir%/../config"
$acl_file: "%api_acl_file%"
Catalyst\MenuBundle\Menu\Generator:
arguments:
$router: "@router.default"
$cache_dir: "%kernel.cache_dir%"
$config_dir: "%kernel.root_dir%/../config"
Catalyst\MenuBundle\Listener\MenuAnnotationListener:
arguments:
$menu_name: "main_menu"
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
# invoice generator
App\Service\InvoiceGenerator\CMBInvoiceGenerator: ~
# invoice generator interface
App\Service\InvoiceGeneratorInterface: "@App\\Service\\InvoiceGenerator\\CMBInvoiceGenerator"
# job order generator
App\Service\JobOrderHandler\CMBJobOrderHandler:
arguments:
$country_code: "%env(COUNTRY_CODE)%"
#job order generator interface
App\Service\JobOrderHandlerInterface: "@App\\Service\\JobOrderHandler\\CMBJobOrderHandler"
# customer generator
App\Service\CustomerHandler\CMBCustomerHandler:
arguments:
$country_code: "%env(COUNTRY_CODE)%"
# customer generator interface
App\Service\CustomerHandlerInterface: "@App\\Service\\CustomerHandler\\CMBCustomerHandler"
# rider assignment
App\Service\RiderAssignmentHandler\CMBRiderAssignmentHandler: ~
# rider assignment interface
App\Service\RiderAssignmentHandlerInterface: "@App\\Service\\RiderAssignmentHandler\\CMBRiderAssignmentHandler"
# rider API service
App\Service\RiderAPIHandler\CMBRiderAPIHandler:
arguments:
$country_code: "%env(COUNTRY_CODE)%"
# rider API interface
App\Service\RiderAPIHandlerInterface: "@App\\Service\\RiderAPIHandler\\CMBRiderAPIHandler"
# map manager
#App\Service\GISManager\Bing: ~
App\Service\GISManager\OpenStreet: ~
#App\Service\GISManager\Google: ~
#App\Service\GISManagerInterface: "@App\\Service\\GISManager\\Bing"
App\Service\GISManagerInterface: "@App\\Service\\GISManager\\OpenStreet"
#App\Service\GISManagerInterface: "@App\\Service\\GISManager\\Google"
App\EventListener\JobOrderActiveCacheListener:
arguments:
$jo_cache: "@App\\Service\\JobOrderCache"
$mqtt: "@App\\Service\\MQTTClient"
tags:
- name: 'doctrine.orm.entity_listener'
event: 'postUpdate'
entity: 'App\Entity\JobOrder'
- name: 'doctrine.orm.entity_listener'
event: 'postRemove'
entity: 'App\Entity\JobOrder'
- name: 'doctrine.orm.entity_listener'
event: 'postPersist'
entity: 'App\Entity\JobOrder'
App\Service\JobOrderCache:
arguments:
$redis_prov: "@App\\Service\\RedisClientProvider"
$active_jo_key: "%env(LOCATION_JO_ACTIVE_KEY)%"
App\Service\RiderCache:
arguments:
$redis_prov: "@App\\Service\\RedisClientProvider"
$loc_key: "%env(LOCATION_RIDER_ACTIVE_KEY)%"
$status_key: "%env(STATUS_RIDER_KEY)%"

View file

@ -98,6 +98,10 @@ main_menu:
acl: joborder.menu
label: Job Order
icon: flaticon-calendar-3
- id: jo_onestep_form
acl: jo_onestep.form
label: One-step Process
parent: joborder
- id: jo_in
acl: jo_in.list
label: Incoming

View file

@ -19,6 +19,7 @@ doctrine:
point: CrEOF\Spatial\DBAL\Types\Geometry\PointType
polygon: CrEOF\Spatial\DBAL\Types\Geometry\PolygonType
linestring: CrEOF\Spatial\DBAL\Types\Geometry\LineStringType
multipolygon: CrEOF\Spatial\DBAL\Types\Geometry\MultiPolygonType
orm:
auto_generate_proxy_classes: '%kernel.debug%'
naming_strategy: doctrine.orm.naming_strategy.underscore

View file

@ -21,6 +21,11 @@ security:
methods: [GET]
security: false
tracker:
pattern: ^\/track\/
methods: [GET]
security: false
api:
pattern: ^\/api\/
security: false

View file

@ -4,3 +4,6 @@ twig:
strict_variables: '%kernel.debug%'
globals:
gmaps_api_key: "%env(GMAPS_API_KEY)%"
mqtt_host: "%env(MQTT_WS_HOST)%"
mqtt_port: "%env(MQTT_WS_PORT)%"
dashboard_enable: "%env(DASHBOARD_ENABLE)%"

228
config/resq.services.yaml Normal file
View file

@ -0,0 +1,228 @@
# Put parameters here that don't need to change on each machine where the app is deployed
# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
parameters:
map_default:
latitude: 14.6091
longitude: 121.0223
image_upload_directory: '%kernel.project_dir%/public/uploads'
job_order_refresh_interval: 300000
api_acl_file: 'api_acl.yaml'
api_access_key: 'api_access_keys'
app_acl_file: 'acl.yaml'
app_access_key: 'access_keys'
cvu_brand_id: "%env(CVU_BRAND_ID)%"
country_code: "%env(COUNTRY_CODE)%"
services:
# default configuration for services in *this* file
_defaults:
autowire: true # Automatically injects dependencies in your services.
autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
public: false # Allows optimizing the container by removing unused services; this also means
# fetching services directly from the container via $container->get() won't work.
# The best practice is to be explicit about your dependencies anyway.
# makes classes in src/ available to be used as services
# this creates a service per class whose id is the fully-qualified class name
App\:
resource: '../src/*'
exclude: '../src/{Entity,Migrations,Tests,Menu,Access}'
# controllers are imported separately to make sure services can be injected
# as action arguments even if you don't extend any base controller class
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
# add more service definitions when explicit configuration is needed
# please note that last definitions always *replace* previous ones
App\Menu\Generator:
arguments:
$router: "@router.default"
$cache_dir: "%kernel.cache_dir%"
$config_dir: "%kernel.root_dir%/../config"
Catalyst\AuthBundle\Service\ACLGenerator:
arguments:
$router: "@router.default"
$cache_dir: "%kernel.cache_dir%"
$config_dir: "%kernel.root_dir%/../config"
$acl_file: "%app_acl_file%"
Catalyst\AuthBundle\Service\ACLVoter:
arguments:
$user_class: "App\\Entity\\User"
tags: ['security.voter']
Catalyst\AuthBundle\Service\UserChecker:
App\Service\FileUploader:
arguments:
$target_dir: '%image_upload_directory%'
App\Service\MapTools:
arguments:
$em: "@doctrine.orm.entity_manager"
$gmaps_api_key: "%env(GMAPS_API_KEY)%"
App\Service\RisingTideGateway:
arguments:
$em: "@doctrine.orm.entity_manager"
$user: "%env(RT_USER)%"
$pass: "%env(RT_PASS)%"
$usage_type: "%env(RT_USAGE_TYPE)%"
$shortcode: "%env(RT_SHORTCODE)%"
App\Service\MQTTClient:
arguments:
$redis_client: "@App\\Service\\RedisClientProvider"
$key: "mqtt_events"
App\Service\APNSClient:
arguments:
$redis_client: "@App\\Service\\RedisClientProvider"
App\Service\RedisClientProvider:
arguments:
$scheme: "%env(REDIS_CLIENT_SCHEME)%"
$host: "%env(REDIS_CLIENT_HOST)%"
$port: "%env(REDIS_CLIENT_PORT)%"
$password: "%env(REDIS_CLIENT_PASSWORD)%"
App\Service\GeofenceTracker:
arguments:
$geofence_flag: "%env(GEOFENCE_ENABLE)%"
App\Service\WarrantyHandler:
arguments:
$em: "@doctrine.orm.entity_manager"
App\Command\SetCustomerPrivacyPolicyCommand:
arguments:
$policy_promo: "%env(POLICY_PROMO)%"
$policy_third_party: "%env(POLICY_THIRD_PARTY)%"
$policy_mobile: "%env(POLICY_MOBILE)%"
App\Command\CreateCustomerFromWarrantyCommand:
arguments:
$cvu_mfg_id: "%env(CVU_MFG_ID)%"
$cvu_brand_id: "%env(CVU_BRAND_ID)%"
# rider tracker service
App\Service\RiderTracker:
arguments:
$redis_client: "@App\\Service\\RedisClientProvider"
Catalyst\APIBundle\Security\APIKeyUserProvider:
arguments:
$em: "@doctrine.orm.entity_manager"
Catalyst\APIBundle\Security\APIKeyAuthenticator:
arguments:
$em: "@doctrine.orm.entity_manager"
Catalyst\APIBundle\Command\UserCreateCommand:
arguments:
$em: "@doctrine.orm.entity_manager"
tags: ['console.command']
Catalyst\APIBundle\Command\TestCommand:
tags: ['console.command']
Catalyst\APIBundle\Command\TestAPICommand:
tags: ['console.command']
Catalyst\APIBundle\Access\Voter:
arguments:
$acl_gen: "@Catalyst\\APIBundle\\Access\\Generator"
$user_class: "Catalyst\\APIBundle\\Entity\\User"
tags: ['security.voter']
Catalyst\APIBundle\Access\Generator:
arguments:
$router: "@router.default"
$cache_dir: "%kernel.cache_dir%"
$config_dir: "%kernel.root_dir%/../config"
$acl_file: "%api_acl_file%"
Catalyst\MenuBundle\Menu\Generator:
arguments:
$router: "@router.default"
$cache_dir: "%kernel.cache_dir%"
$config_dir: "%kernel.root_dir%/../config"
Catalyst\MenuBundle\Listener\MenuAnnotationListener:
arguments:
$menu_name: "main_menu"
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
# invoice generator
App\Service\InvoiceGenerator\ResqInvoiceGenerator: ~
# invoice generator interface
App\Service\InvoiceGeneratorInterface: "@App\\Service\\InvoiceGenerator\\ResqInvoiceGenerator"
# job order generator
App\Service\JobOrderHandler\ResqJobOrderHandler:
arguments:
$country_code: "%env(COUNTRY_CODE)%"
#job order generator interface
App\Service\JobOrderHandlerInterface: "@App\\Service\\JobOrderHandler\\ResqJobOrderHandler"
# customer generator
App\Service\CustomerHandler\ResqCustomerHandler:
arguments:
$country_code: "%env(COUNTRY_CODE)%"
# customer generator interface
App\Service\CustomerHandlerInterface: "@App\\Service\\CustomerHandler\\ResqCustomerHandler"
# rider assignment
App\Service\RiderAssignmentHandler\ResqRiderAssignmentHandler: ~
# rider assignment interface
App\Service\RiderAssignmentHandlerInterface: "@App\\Service\\RiderAssignmentHandler\\ResqRiderAssignmentHandler"
# rider API service
App\Service\RiderAPIHandler\ResqRiderAPIHandler:
arguments:
$country_code: "%env(COUNTRY_CODE)%"
App\Service\RiderAPIHandlerInterface: "@App\\Service\\RiderAPIHandler\\ResqRiderAPIHandler"
# map manager
#App\Service\GISManager\Bing: ~
App\Service\GISManager\OpenStreet: ~
#App\Service\GISManager\Google: ~
#App\Service\GISManagerInterface: "@App\\Service\\GISManager\\Bing"
App\Service\GISManagerInterface: "@App\\Service\\GISManager\\OpenStreet"
#App\Service\GISManagerInterface: "@App\\Service\\GISManager\\Google"
App\EventListener\JobOrderActiveCacheListener:
arguments:
$jo_cache: "@App\\Service\\JobOrderCache"
$mqtt: "@App\\Service\\MQTTClient"
tags:
- name: 'doctrine.orm.entity_listener'
event: 'postUpdate'
entity: 'App\Entity\JobOrder'
- name: 'doctrine.orm.entity_listener'
event: 'postRemove'
entity: 'App\Entity\JobOrder'
- name: 'doctrine.orm.entity_listener'
event: 'postPersist'
entity: 'App\Entity\JobOrder'
App\Service\JobOrderCache:
arguments:
$redis_prov: "@App\\Service\\RedisClientProvider"
$active_jo_key: "%env(LOCATION_JO_ACTIVE_KEY)%"
App\Service\RiderCache:
arguments:
$redis_prov: "@App\\Service\\RedisClientProvider"
$loc_key: "%env(LOCATION_RIDER_ACTIVE_KEY)%"
$status_key: "%env(STATUS_RIDER_KEY)%"

View file

@ -3,7 +3,3 @@
# controller: App\Controller\DefaultController::index
#
#
home:
path: /
controller: App\Controller\HomeController::index

8
config/routes/home.yaml Normal file
View file

@ -0,0 +1,8 @@
home:
path: /
controller: App\Controller\HomeController::index
rider_locations:
path: /rider_locations
controller: App\Controller\HomeController::getRiderLocations

View file

@ -34,3 +34,12 @@ hub_delete:
controller: App\Controller\HubController::destroy
methods: [DELETE]
hub_nearest:
path: /ajax/nearest_hubs
controller: App\Controller\HubController::nearest
methods: [GET]
hub_riders:
path: /ajax/hubs/riders
controller: App\Controller\HubController::getHubRiders
methods: [GET]

View file

@ -175,3 +175,34 @@ jo_reject_hub:
path: /job-order/{id}/reject-hub
controller: App\Controller\JobOrderController::rejectHubSubmit
methods: [POST]
jo_onestep_form:
path: /job-order/onestep
controller: App\Controller\JobOrderController::oneStepForm
methods: [GET]
jo_onestep_submit:
path: /job-order/onestep
controller: App\Controller\JobOrderController::oneStepSubmit
methods: [POST]
jo_onestep_edit_form:
path: /job-order/onestep/{id}/edit
controller: App\Controller\JobOrderController::oneStepEditForm
methods: [GET]
jo_onestep_edit_submit:
path: /job-order/onestep/{id}/edit
controller: App\Controller\JobOrderController::oneStepEditSubmit
methods: [POST]
jo_ajax_popup:
path: /job-order/{id}/popup
controller: App\Controller\JobOrderController::popupInfo
methods: [GET]
jo_tracker:
path: /track/{id}
controller: App\Controller\JobOrderController::tracker
methods: [GET]

View file

@ -36,3 +36,8 @@ rider_delete:
path: /riders/{id}
controller: App\Controller\RiderController::destroy
methods: [DELETE]
rider_ajax_popup:
path: /riders/{id}/popup
controller: App\Controller\RiderController::popupInfo
methods: [GET]

View file

@ -76,6 +76,7 @@ services:
App\Service\MQTTClient:
arguments:
$redis_client: "@App\\Service\\RedisClientProvider"
$key: "mqtt_events"
App\Service\APNSClient:
arguments:
@ -87,7 +88,6 @@ services:
$host: "%env(REDIS_CLIENT_HOST)%"
$port: "%env(REDIS_CLIENT_PORT)%"
$password: "%env(REDIS_CLIENT_PASSWORD)%"
$env_flag: "dev"
App\Service\GeofenceTracker:
arguments:
@ -108,6 +108,11 @@ services:
$cvu_mfg_id: "%env(CVU_MFG_ID)%"
$cvu_brand_id: "%env(CVU_BRAND_ID)%"
# rider tracker service
App\Service\RiderTracker:
arguments:
$redis_client: "@App\\Service\\RedisClientProvider"
Catalyst\APIBundle\Security\APIKeyUserProvider:
arguments:
$em: "@doctrine.orm.entity_manager"
@ -151,3 +156,94 @@ services:
$menu_name: "main_menu"
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
# CMB invoice generator
App\Service\InvoiceGenerator\CMBInvoiceGenerator: ~
# Resq invoice generator
#App\Service\InvoiceGenerator\ResqInvoiceGenerator: ~
# invoice generator interface
App\Service\InvoiceGeneratorInterface: "@App\\Service\\InvoiceGenerator\\CMBInvoiceGenerator"
#App\Service\InvoiceGeneratorInterface: "@App\\Service\\InvoiceGenerator\\ResqInvoiceGenerator"
# Resq job order generator
#App\Service\JobOrderHandler\ResqJobOrderHandler:
# arguments:
# $country_code: "%env(COUNTRY_CODE)%"
# CMB job order generator
App\Service\JobOrderHandler\CMBJobOrderHandler:
arguments:
$country_code: "%env(COUNTRY_CODE)%"
#job order generator interface
App\Service\JobOrderHandlerInterface: "@App\\Service\\JobOrderHandler\\CMBJobOrderHandler"
#App\Service\JobOrderHandlerInterface: "@App\\Service\\JobOrderHandler\\ResqJobOrderHandler"
# CMB customer generator
App\Service\CustomerHandler\CMBCustomerHandler:
arguments:
$country_code: "%env(COUNTRY_CODE)%"
# Resq customer generator
#App\Service\CustomerHandler\ResqCustomerHandler:
# arguments:
# $country_code: "%env(COUNTRY_CODE)%"
# customer generator interface
App\Service\CustomerHandlerInterface: "@App\\Service\\CustomerHandler\\CMBCustomerHandler"
#App\Service\CustomerHandlerInterface: "@App\\Service\\CustomerHandler\\ResqCustomerHandler"
# rider assignment
#App\Service\RiderAssignmentHandler\CMBRiderAssignmentHandler: ~
# rider assignment interface
App\Service\RiderAssignmentHandlerInterface: "@App\\Service\\RiderAssignmentHandler\\CMBRiderAssignmentHandler"
# rider API service
App\Service\RiderAPIHandler\CMBRiderAPIHandler:
arguments:
$country_code: "%env(COUNTRY_CODE)%"
#App\Service\RiderAPIHandler\ResqRiderAPIHandler:
# arguments:
# $country_code: "%env(COUNTRY_CODE)%"
# rider API interface
App\Service\RiderAPIHandlerInterface: "@App\\Service\\RiderAPIHandler\\CMBRiderAPIHandler"
# map manager
#App\Service\GISManager\Bing: ~
App\Service\GISManager\OpenStreet: ~
#App\Service\GISManager\Google: ~
#App\Service\GISManagerInterface: "@App\\Service\\GISManager\\Bing"
App\Service\GISManagerInterface: "@App\\Service\\GISManager\\OpenStreet"
#App\Service\GISManagerInterface: "@App\\Service\\GISManager\\Google"
App\EventListener\JobOrderActiveCacheListener:
arguments:
$jo_cache: "@App\\Service\\JobOrderCache"
$mqtt: "@App\\Service\\MQTTClient"
tags:
- name: 'doctrine.orm.entity_listener'
event: 'postUpdate'
entity: 'App\Entity\JobOrder'
- name: 'doctrine.orm.entity_listener'
event: 'postRemove'
entity: 'App\Entity\JobOrder'
- name: 'doctrine.orm.entity_listener'
event: 'postPersist'
entity: 'App\Entity\JobOrder'
App\Service\JobOrderCache:
arguments:
$redis_prov: "@App\\Service\\RedisClientProvider"
$active_jo_key: "%env(LOCATION_JO_ACTIVE_KEY)%"
App\Service\RiderCache:
arguments:
$redis_prov: "@App\\Service\\RedisClientProvider"
$loc_key: "%env(LOCATION_RIDER_ACTIVE_KEY)%"
$status_key: "%env(STATUS_RIDER_KEY)%"

View file

@ -0,0 +1,8 @@
DELETE FROM battery;
DELETE FROM battery_manufacturer;
DELETE FROM battery_manufacturer;
DELETE FROM battery_model;
DELETE FROM battery_size;
DELETE FROM vehicle;
DELETE FROM vehicle_manufacturer;
DELETE FROM battery_vehicle;

View file

@ -295,3 +295,67 @@ span.has-danger,
.btn-icon {
margin-right: .5em;
}
.marker-pin {
width: 30px;
height: 30px;
border-radius: 50% 50% 50% 0;
background: #c30b82;
position: absolute;
transform: rotate(-45deg);
left: 50%;
top: 50%;
margin: -15px 0 0 -15px;
}
.marker-pin::after {
content: '';
width: 24px;
height: 24px;
margin: 3px 0 0 3px;
background: #fff;
position: absolute;
border-radius: 50%;
}
.map-div-icon i {
position: absolute;
width: 22px;
font-size: 22px;
left: 0;
right: 0;
margin: 10px auto;
text-align: center;
}
.map-div-icon i.awesome {
margin: 12px auto;
font-size: 17px;
}
.map-info {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
z-index: 9999;
padding: 1.5em;
width: 100%;
}
.map-info > .m-portlet {
margin-bottom: 0;
}
.map-info .m-portlet__body {
padding: 1.5rem;
}
.map-info .rider-image {
width: 4.8rem;
border-radius: 50%;
}
.map-info .m-badge {
border-radius: 0;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

View file

@ -0,0 +1,171 @@
class DashboardMap {
constructor(options, rider_markers, cust_markers) {
this.options = options;
this.rider_markers = rider_markers;
this.cust_markers = cust_markers;
// layer groups
this.layer_groups = {
'rider_available': L.layerGroup(),
'rider_active_jo': L.layerGroup(),
'customer': L.layerGroup()
};
}
initialize() {
// main map
this.map = L.map(this.options.div_id).setView(
[this.options.center_lat, this.options.center_lng],
this.options.zoom
);
// add tile layer
var streets = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/streets-v11',
accessToken: this.options.access_token
}).addTo(this.map);
// layer groups
this.layer_groups.rider_available.addTo(this.map);
this.layer_groups.rider_active_jo.addTo(this.map);
this.layer_groups.customer.addTo(this.map);
// base layer
var baseMaps = {
'Streets': streets
};
if (this.options.display_overlay) {
// overlay layer
var overlayMaps = {
'Available Riders' : this.layer_groups.rider_available,
'JO Riders' : this.layer_groups.rider_active_jo,
'Customers' : this.layer_groups.customer
}
L.control.layers(baseMaps, overlayMaps).addTo(this.map);
}
return this.map;
}
putMarker(id, lat, lng, markers, icon, layer_group, popup_url) {
var my = this;
// existing marker
if (markers.hasOwnProperty(id)) {
markers[id].setLatLng(L.latLng(lat, lng));
return;
}
// new marker
markers[id] = L.marker(
[lat, lng],
{ icon: icon }
).addTo(layer_group);
if (my.options.enable_popup) {
markers[id].bindPopup('Loading...');
// bind ajax for popup
markers[id].on('click', function(e) {
var popup = e.target.getPopup();
var url = popup_url.replace('[id]', id);
console.log(url);
$.get(url).done(function(data) {
popup.setContent(data);
popup.update();
});
});
}
}
putCustomerMarker(id, lat, lng) {
this.putMarker(
id,
lat,
lng,
this.cust_markers,
this.options.icons.customer,
this.layer_groups.customer,
this.options.cust_popup_url
);
}
removeCustomerMarker(id) {
console.log('removing customer marker for ' + id);
var layer_group = this.layer_groups.customer;
var markers = this.cust_markers;
// no customer marker with that id
if (!markers.hasOwnProperty(id)) {
console.log('no such marker to remove');
return;
}
layer_group.removeLayer(markers[id]);
}
putRiderAvailableMarker(id, lat, lng) {
this.putMarker(
id,
lat,
lng,
this.rider_markers,
this.options.icons.rider_available,
this.layer_groups.rider_available,
this.options.rider_popup_url
);
}
putRiderActiveJOMarker(id, lat, lng) {
this.putMarker(
id,
lat,
lng,
this.rider_markers,
this.options.icons.rider_active_jo,
this.layer_groups.rider_active_jo,
this.options.rider_popup_url
);
}
loadLocations(location_url) {
console.log(this.rider_markers);
var my = this;
$.ajax({
url: location_url,
}).done(function(response) {
// clear all markers
my.layer_groups.rider_available.clearLayers();
my.layer_groups.rider_active_jo.clearLayers();
my.layer_groups.customer.clearLayers();
// get riders and job orders
var riders = response.riders;
var jos = response.jos;
// job orders
$.each(jos, function(id, data) {
var lat = data.latitude;
var lng = data.longitude;
my.putCustomerMarker(id, lat, lng);
});
// riders
$.each(riders, function(id, data) {
var lat = data.latitude;
var lng = data.longitude;
if (data.has_jo)
my.putRiderActiveJOMarker(id, lat, lng);
else
my.putRiderAvailableMarker(id, lat, lng);
});
// console.log(rider_markers);
});
}
}

View file

@ -0,0 +1,114 @@
class MapEventHandler {
constructor(options, dashmap) {
this.options = options;
this.dashmap = dashmap;
}
connect(user_id, host, port) {
var d = new Date();
var client_id = "dash-" + user_id + "-" + d.getMonth() + "-" + d.getDate() + "-" + d.getHours() + "-" + d.getMinutes() + "-" + d.getSeconds() + "-" + d.getMilliseconds();
console.log(client_id);
this.mqtt = new Paho.MQTT.Client(host, port, client_id);
var options = {
// useSSL: true,
timeout: 3,
invocationContext: this,
onSuccess: this.onConnect.bind(this),
};
this.mqtt.onMessageArrived = this.onMessage.bind(this);
console.log('connecting to mqtt server...');
this.mqtt.connect(options);
}
onConnect(icontext) {
console.log('mqtt connected!');
var my = icontext.invocationContext;
// subscribe to rider locations
if (my.options.track_rider) {
console.log('subscribing to ' + my.options.channels.rider_location);
my.mqtt.subscribe(my.options.channels.rider_location);
}
// subscribe to jo locations
if (my.options.track_jo) {
console.log('subscribing to ' + my.options.channels.jo_location);
my.mqtt.subscribe(my.options.channels.jo_location);
my.mqtt.subscribe(my.options.channels.jo_status);
}
}
onMessage(msg) {
// console.log(msg);
console.log('received message');
var channel = msg.destinationName;
var chan_split = channel.split('/');
var payload = msg.payloadString;
// handle different channels
switch (chan_split[0]) {
case "rider":
this.handleRider(chan_split, payload);
break;
case "jo":
this.handleJobOrder(chan_split, payload);
break;
}
}
handleRider(chan_split, payload) {
console.log("rider message");
switch (chan_split[2]) {
case "location":
console.log("got location for rider " + chan_split[1] + " - " + payload);
var pl_split = payload.split(':');
console.log(pl_split);
// check for correct format
if (pl_split.length != 2)
break;
var lat = parseFloat(pl_split[0]);
var lng = parseFloat(pl_split[1]);
this.dashmap.putRiderAvailableMarker(chan_split[1], lat, lng);
break;
}
}
handleJobOrder(chan_split, payload) {
console.log("jo message");
var id = chan_split[1];
switch (chan_split[2]) {
case "location":
// var my = this;
console.log("got location for jo " + id + " - " + payload);
var pl_split = payload.split(':');
// check for correct format
if (pl_split.length != 2)
break;
var lat = parseFloat(pl_split[0]);
var lng = parseFloat(pl_split[1]);
// move marker
console.log(lat + ' - ' + lng);
this.dashmap.putCustomerMarker(id, lat, lng);
break;
case "status":
switch (payload) {
case 'cancel':
case 'fulfill':
case 'delete':
this.dashmap.removeCustomerMarker(id);
break;
}
}
}
}

View file

@ -46,5 +46,7 @@ class AdjustLongLatCommand extends Command
}
$em->flush();
return 0;
}
}

View file

@ -71,5 +71,7 @@ class ComputeWarrantyExpiryDateCommand extends Command
$this->em->clear();
}
return 0;
}
}

View file

@ -290,6 +290,8 @@ class CreateCustomerFromWarrantyCommand extends Command
//$output->writeln('Total warranties with no mobile number: ' . $total_inv_warr);
$output->writeln('Total customers added: ' . $total_cust_added);
$output->writeln('Total customer vehicles added: ' . $total_cv_added);
return 0;
}
protected function getDefaultVehicle()

View file

@ -76,5 +76,7 @@ class FulfillOldJobOrderCommand extends Command
}
$em->flush();
return 0;
}
}

View file

@ -79,5 +79,7 @@ class FulfillPendingJobOrderCommand extends Command
}
$em->flush();
return 0;
}
}

View file

@ -100,5 +100,7 @@ class GenerateBatteryCompatibilityCommand extends Command
fwrite($json_file, json_encode($this->vmfg_index, JSON_PRETTY_PRINT));
fclose($json_file);
return 0;
}
}

View file

@ -211,5 +211,7 @@ class GenerateWarrantyFromJobOrderCommand extends Command
$em->detach($row[0]);
$em->clear();
}
return 0;
}
}

View file

@ -174,5 +174,7 @@ class ImportBatteryPriceCommand extends Command
}
$em->flush();
return 0;
}
}

View file

@ -0,0 +1,317 @@
<?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 Doctrine\ORM\EntityManagerInterface;
use App\Entity\Battery;
use App\Entity\BatteryManufacturer;
use App\Entity\BatteryModel;
use App\Entity\BatterySize;
class ImportCMBBatteryDataCommand extends Command
{
const F_BATT_CODE = 1;
const F_BATT_DESC = 2;
const F_BATT_PRICE = 3;
protected $em;
protected $bmanu_hash;
protected $bmodel_hash;
protected $bsize_hash;
protected $batt_hash;
public function __construct(EntityManagerInterface $om)
{
$this->em = $om;
// load existing batteries and sizes
$this->loadBatteryManufacturers();
$this->loadBatteryModels();
$this->loadBatteries();
$this->loadBatterySizes();
parent::__construct();
}
protected function configure()
{
$this->setName('cmbbatterydata:import')
->setDescription('Import a CSV file with battery data.')
->setHelp('Adds the battery data based on imported CSV.')
->addArgument('file', InputArgument::REQUIRED, 'Path to the CSV file.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$csv_file = $input->getArgument('file');
// attempt to open file
try
{
$fh = fopen($csv_file, "r");
}
catch (Exception $e)
{
throw new Exception('The file "' . $csv_file . '" could be read.');
}
// get entity manager
$em = $this->em;
// loop through the rows
$row_num = 0;
error_log('Processing battery csv file...');
while (($fields = fgetcsv($fh)) !== false)
{
// data starts at row 2
if ($row_num < 2)
{
$row_num++;
continue;
}
// battery info
$code = trim($fields[self::F_BATT_CODE]);
$desc = trim($fields[self::F_BATT_DESC]);
$price = trim($fields[self::F_BATT_PRICE]);
$clean_price = trim($price, '$');
$battery_info = explode(' ', $desc);
// if battery_info has 3 elements, get the last two
// [0] = battery manufacturer
// [1] = battery model
// [2] = battery size
// if only 2, get both
// [0] = battery manufacturer and battery model
// [1] = battery size
// if 4,
// [0] = battery manufacturer
// concatenate [1] and [2] for the battery model
// [3] = battery size
$battery_manufacturer = '';
$battery_model = '';
$battery_size = '';
if (count($battery_info) == 3)
{
// sample: Century Marathoner 120-7L
$battery_manufacturer = trim($battery_info[0]);
$battery_model = trim($battery_info[1]);
$battery_size = trim($battery_info[2]);
}
if (count($battery_info) == 2)
{
// sample: Marshall DIN55R
$battery_manufacturer = trim($battery_info[0]);
$battery_model = trim($battery_info[0]);
$battery_size = trim($battery_info[1]);
}
if (count($battery_info) == 4)
{
// sample: Motolite Classic Wetcharged DIN100L
$battery_manufacturer = trim($battery_info[0]);
$battery_model = trim($battery_info[1]) . ' ' . trim($battery_info[2]);
$battery_size = trim($battery_info[3]);
}
// check if battery size has ()
// if so, trim it to ignore the parenthesis and what's after (.
$pos = stripos($battery_size, '(');
if ($pos == true)
{
$sizes = explode('(', $battery_size);
$clean_size = trim($sizes[0]);
}
else
{
$clean_size = $battery_size;
}
//error_log('battery manufacturer ' . $battery_manufacturer);
//error_log('battery model ' . $battery_model);
//error_log('battery size ' . $battery_size);
// normalize the manufacturer, model and size for the hash
// when we add to db for manufacturer, model, and size, we do not use the normalized versions
$normalized_manu = $this->normalizeName($battery_manufacturer);
$normalized_model = $this->normalizeName($battery_model);
$normalized_size = $this->normalizeName($clean_size);
// save battery manufacturer if not yet in system
if (!isset($this->bmanu_hash[$normalized_manu]))
{
$this->addBatteryManufacturer($battery_manufacturer);
}
// save battery model if not yet in system
if (!isset($this->bmodel_hash[$normalized_model]))
{
$this->addBatteryModel($battery_model);
}
// save battery size if not yet in system
if (!isset($this->bsize_hash[$normalized_size]))
{
$this->addBatterySize($clean_size);
}
// save battery if not yet in system
if (!isset($this->batt_hash[$normalized_manu][$normalized_model][$normalized_size]))
{
$this->addBattery($normalized_manu, $normalized_model, $normalized_size, $code, $clean_price);
}
}
return 0;
}
protected function addBatteryManufacturer($name)
{
$batt_manufacturer = new BatteryManufacturer();
$batt_manufacturer->setName($name);
$this->em->persist($batt_manufacturer);
$this->em->flush();
// add new manufacturer to hash
$normalized_name = $this->normalizeName($name);
$this->bmanu_hash[$normalized_name] = $batt_manufacturer;
}
protected function addBatteryModel($name)
{
$batt_model = new BatteryModel();
$batt_model->setName($name);
$this->em->persist($batt_model);
$this->em->flush();
// add new model to hash
$normalized_name = $this->normalizeName($name);
$this->bmodel_hash[$normalized_name] = $batt_model;
}
protected function addBatterySize($name)
{
if (!empty($name))
{
// save to db
$batt_size = new BatterySize();
$batt_size->setName($name);
$this->em->persist($batt_size);
$this->em->flush();
// add new size into hash
$normalized_name = $this->normalizeName($name);
$this->bsize_hash[$normalized_name] = $batt_size;
}
}
protected function addBattery($manufacturer, $brand, $size, $code, $price)
{
// save to db
$bmanu = $this->bmanu_hash[$manufacturer];
$bmodel = $this->bmodel_hash[$brand];
$bsize = $this->bsize_hash[$size];
$battery = new Battery();
$battery->setManufacturer($bmanu)
->setModel($bmodel)
->setSize($bsize)
->setWarrantyPrivate(21)
->setWarrantyCommercial(6)
->setWarrantyTnv(12)
->setProductCode($code)
->setSAPCode($code)
->setSellingPrice($price);
$this->em->persist($battery);
$this->em->flush();
// insert into hash
$this->batt_hash[$brand][$brand][$size] = $battery;
// add battery into battery manufacturer, battery model, and battery size
$bmanu->addBattery($battery);
$bmodel->addBattery($battery);
$bsize->addBattery($battery);
$this->em->persist($bmanu);
$this->em->persist($bmodel);
$this->em->persist($bsize);
$this->em->flush();
}
protected function loadBatteryManufacturers()
{
$this->bmanu_hash = [];
$batt_manufacturers = $this->em->getRepository(BatteryManufacturer::class)->findAll();
foreach ($batt_manufacturers as $batt_manu)
{
$name = $this->normalizeName($batt_manu->getName());
$this->bmanu_hash[$name] = $batt_manu;
}
}
protected function loadBatteryModels()
{
$this->bmodel_hash = [];
$batt_models = $this->em->getRepository(BatteryModel::class)->findAll();
foreach ($batt_models as $batt_model)
{
$name = $this->normalizeName($batt_model->getName());
$this->bmodel_hash[$name] = $batt_model;
}
}
protected function loadBatterySizes()
{
$this->bsize_hash = [];
$batt_sizes = $this->em->getRepository(BatterySize::class)->findAll();
foreach ($batt_sizes as $batt_size)
{
$name = $this->normalizeName($batt_size->getName());
$this->bsize_hash[$name] = $batt_size;
}
}
protected function loadBatteries()
{
$this->batt_hash = [];
$batts = $this->em->getRepository(Battery::class)->findAll();
foreach ($batts as $batt)
{
$brand = $this->normalizeName($batt->getManufacturer()->getName());
$model = $this->normalizeName($batt->getModel()->getName());
$size = $this->normalizeName($batt->getSize()->getName());
$this->batt_hash[$brand][$model][$size] = $batt;
}
}
protected function normalizeName($name)
{
$normalized_key = trim(strtolower($name));
return $normalized_key;
}
}

View file

@ -0,0 +1,113 @@
<?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 Doctrine\ORM\EntityManagerInterface;
use App\Entity\BatterySize;
class ImportCMBBatteryTradeInPriceCommand extends Command
{
const F_SIZE_DESC = 2;
const F_TRADEIN_PRICE = 3;
protected $em;
protected $bsize_hash;
public function __construct(EntityManagerInterface $om)
{
$this->em = $om;
// load existing sizes
$this->loadBatterySizes();
parent::__construct();
}
protected function configure()
{
$this->setName('cmbbatterydata:importtradeinprice')
->setDescription('Import a CSV file with trade in prices.')
->setHelp('Adds the battery tradein prices to existing batteries based on imported CSV.')
->addArgument('file', InputArgument::REQUIRED, 'Path to the CSV file.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$csv_file = $input->getArgument('file');
// attempt to open file
try
{
$fh = fopen($csv_file, "r");
}
catch (Exception $e)
{
throw new Exception('The file "' . $csv_file . '" could be read.');
}
// get entity manager
$em = $this->em;
// loop through the rows
$row_num = 0;
error_log('Processing battery tradein price csv file...');
while (($fields = fgetcsv($fh)) !== false)
{
// data starts at row 2
if ($row_num < 2)
{
$row_num++;
continue;
}
// tradein price info
// battery price info
$desc = trim($fields[self::F_SIZE_DESC]);
$price = trim($fields[self::F_TRADEIN_PRICE]);
$clean_price = trim($price, '$');
$size_info = explode(' ', $desc);
$size = $size_info[1];
if (isset($this->bsize_hash[$size]))
{
$battery_size = $this->bsize_hash[$size];
// use TIPriceMotolite
$battery_size->setTIPriceMotolite($clean_price);
$this->em->persist($battery_size);
$this->em->flush();
}
else
{
error_log('Cannot find battery size ' . $size);
}
}
return 0;
}
protected function loadBatterySizes()
{
$this->bsize_hash = [];
$batt_sizes = $this->em->getRepository(BatterySize::class)->findAll();
foreach ($batt_sizes as $batt_size)
{
$name = $batt_size->getName();
$this->bsize_hash[$name] = $batt_size;
}
}
}

View file

@ -0,0 +1,449 @@
<?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 Doctrine\ORM\EntityManagerInterface;
use App\Entity\BatteryManufacturer;
use App\Entity\BatteryModel;
use App\Entity\BatterySize;
use App\Entity\Battery;
use App\Entity\VehicleManufacturer;
use App\Entity\Vehicle;
class ImportCMBVehicleCompatibilityCommand extends Command
{
// field index in csv file
const F_VEHICLE_MANUFACTURER = 1;
const F_VEHICLE_MAKE = 2;
const F_VEHICLE_YEAR = 3;
const F_BATT_SDFC = 4;
const F_BATT_ULTRAMAX = 5;
const F_BATT_MOTOLITE = 6;
const F_BATT_MARATHONER = 7;
const F_BATT_EXCEL = 8;
const STR_CENTURY = 'Century';
const STR_MOTOLITE = 'Motolite';
const STR_MARSHALL = 'Marshall';
const STR_SDFC = 'SDFC';
const STR_MARATHONER = 'Marathoner';
const STR_WETCHARGED = 'Classic WetCharged';
const STR_ULTRAMAX = 'ULTRAMAX';
const STR_EXCEL = 'Excel';
const STR_PRESENT = 'Present';
const STR_M_42 = 'M-42';
const STR_M42 = 'M42';
protected $em;
protected $bmanu_hash;
protected $bmodel_hash;
protected $bsize_hash;
protected $batt_hash;
protected $vmanu_hash;
protected $vmake_hash;
public function __construct(EntityManagerInterface $om)
{
$this->em = $om;
// load existing battery data
$this->loadBatteryManufacturers();
$this->loadBatteryModels();
$this->loadBatterySizes();
$this->loadBatteries();
// load existing vehicle data
$this->loadVehicleManufacturers();
$this->loadVehicleMakes();
parent::__construct();
}
protected function configure()
{
$this->setName('cmbvehiclecompatibility:import')
->setDescription('Retrieve from a CSV file battery and vehicle information.')
->setHelp('Creates battery manufacturers, models, sizes, vehicle makes, and models based on data from imported CSV.')
->addArgument('file', InputArgument::REQUIRED, 'Path to the CSV file.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$csv_file = $input->getArgument('file');
// attempt to open file
try
{
$fh = fopen($csv_file, "r");
}
catch (Exception $e)
{
throw new Exception('The file "' . $csv_file . '" could be read.');
}
// get entity manager
$em = $this->em;
$row_num = 0;
error_log('Processing vehicle compatibility csv file...');
while (($fields = fgetcsv($fh)) !== false)
{
$comp_batteries = [];
if ($row_num < 2)
{
$row_num++;
continue;
}
// initialize size battery array for cases where the battery size has '/'
$sdfc_sizes = [];
$ultramax_sizes = [];
$motolite_sizes = [];
$marathoner_sizes = [];
$excel_sizes = [];
// battery info
$sdfc_size = trim($fields[self::F_BATT_SDFC]);
$ultramax_size = trim($fields[self::F_BATT_ULTRAMAX]);
$motolite_size = trim($fields[self::F_BATT_MOTOLITE]);
$marathoner_size = trim($fields[self::F_BATT_MARATHONER]);
$excel_size = trim($fields[self::F_BATT_EXCEL]);
// check the sizes for '/'
$pos = stripos($sdfc_size, '/');
if ($pos == false)
{
// no '/' in size
$sdfc_sizes[] = $this->normalizeName($sdfc_size);
}
else
{
// we have '/' in size so we have to explode
$sizes = explode('/', $sdfc_size);
foreach ($sizes as $size)
{
$sdfc_sizes[] = $this->normalizeName($size);
}
}
$pos = stripos($motolite_size, '/');
if ($pos == false)
{
// no '/' in size
$motolite_sizes[] = $this->normalizeName($motolite_size);
}
else
{
// we have '/' in size so we have to explode
$sizes = explode('/', $motolite_size);
foreach ($sizes as $size)
{
$motolite_sizes[] = $this->normalizeName($size);
}
}
$pos = stripos($marathoner_size, '/');
if ($pos == false)
{
// no '/' in size
$marathoner_sizes[] = $this->normalizeName($marathoner_size);
}
else
{
// we have '/' in size so we have to explode
$sizes = explode('/', $marathoner_size);
foreach ($sizes as $size)
{
$marathoner_sizes[] = $this->normalizeName($size);
}
}
$pos = stripos($ultramax_size, '/');
if ($pos == false)
{
// no '/' in size
$ultramax_sizes[] = $this->normalizeName($ultramax_size);
}
else
{
// we have '/' in size so we have to explode
$sizes = explode('/', $ultramax_size);
foreach ($sizes as $size)
{
$ultramax_sizes[] = $this->normalizeName($size);
}
}
$pos = stripos($excel_size, '/');
if ($pos == false)
{
// no '/' in size
$excel_sizes[] = $this->normalizeName($excel_size);
}
else
{
// we have '/' in size so we have to explode
$sizes = explode('/', $excel_size);
foreach ($sizes as $size)
{
$excel_sizes[] = $this->normalizeName($size);
}
}
// normalize the battery manufacturers and battery models
$norm_century = $this->normalizeName(self::STR_CENTURY);
$norm_sdfc = $this->normalizeName(self::STR_SDFC);
$norm_motolite = $this->normalizeName(self::STR_MOTOLITE);
$norm_wetcharged = $this->normalizeName(self::STR_WETCHARGED);
$norm_marathoner = $this->normalizeName(self::STR_MARATHONER);
$norm_ultramax = $this->normalizeName(self::STR_ULTRAMAX);
$norm_excel = $this->normalizeName(self::STR_EXCEL);
//foreach($sdfc_sizes as $size)
//{
// error_log('sdfc size ' . $size);
//}
//foreach($motolite_sizes as $size)
//{
// error_log('motolite size ' . $size);
//}
//foreach($marathoner_sizes as $size)
//{
// error_log('marathoner size ' . $size);
//}
// vehicle info
$manufacturer = trim($fields[self::F_VEHICLE_MANUFACTURER]);
$make = trim($fields[self::F_VEHICLE_MAKE]);
$year = trim($fields[self::F_VEHICLE_YEAR]);
// vehicle data
// check if vehicle manufacturer has been added
if (!isset($this->vmanu_hash[$manufacturer]))
$this->addVehicleManufacturer($manufacturer);
// check if vehicle make has been added
if (!isset($this->vmake_hash[$manufacturer][$make]))
{
foreach($sdfc_sizes as $size)
{
if (!(empty($size)))
{
if (isset($this->batt_hash[$norm_century][$norm_sdfc][$size]))
$comp_batteries[] = $this->batt_hash[$norm_century][$norm_sdfc][$size];
else
error_log('Not in the system: ' . $norm_century . ' ' . $norm_sdfc . ' ' . $size);
}
}
foreach($ultramax_sizes as $size)
{
if (!(empty($size)))
{
if (isset($this->batt_hash[$norm_ultramax][$norm_ultramax][$size]))
$comp_batteries[] = $this->batt_hash[$norm_ultramax][$norm_ultramax][$size];
else
error_log('Not in the system: ' . $norm_ultramax . ' ' . $norm_ultramax . ' ' . $size);
}
}
foreach($motolite_sizes as $size)
{
if (!(empty($size)))
{
if (isset($this->batt_hash[$norm_motolite][$norm_wetcharged][$size]))
$comp_batteries[] = $this->batt_hash[$norm_motolite][$norm_wetcharged][$size];
else
error_log('Not in the system: ' . $norm_motolite . ' ' . $norm_wetcharged . ' ' . $size);
}
}
foreach($marathoner_sizes as $size)
{
if (!(empty($size)))
{
if (isset($this->batt_hash[$norm_century][$norm_marathoner][$size]))
$comp_batteries[] = $this->batt_hash[$norm_century][$norm_marathoner][$size];
else
error_log('Not in the system: ' . $norm_century . ' ' . $norm_marathoner . ' ' . $size);
}
}
foreach($excel_sizes as $size)
{
if (!(empty($size)))
{
if (isset($this->batt_hash[$norm_excel][$norm_excel][$size]))
$comp_batteries[] = $this->batt_hash[$norm_excel][$norm_excel][$size];
else
error_log('Not in the system: ' . $norm_excel . ' ' . $norm_excel . ' ' . $size);
}
}
$this->addVehicleMake($manufacturer, $make, $year, $comp_batteries);
}
$row_num++;
}
return 0;
}
protected function addVehicleManufacturer($name)
{
// save to db
$vehicle_manufacturer = new VehicleManufacturer();
$vehicle_manufacturer->setName($name);
$this->em->persist($vehicle_manufacturer);
$this->em->flush();
// add to hash
$this->vmanu_hash[$name] = $vehicle_manufacturer;
}
protected function addVehicleMake($manufacturer, $make, $year, $batteries)
{
// save to db
$vehicle = new Vehicle();
$vmanu = $this->vmanu_hash[$manufacturer];
// parse year from and year to
$year_from = '';
$year_to = '';
if (!empty($year))
{
$model_years = explode('-', $year);
$year_from = $model_years[0];
if (!empty($year_to))
$year_to = $model_years[1];
// check if $year_to is the string "Present"
// if so, set to 0, for now
if ($year_to == self::STR_PRESENT)
$year_to = 0;
}
$vehicle->setManufacturer($vmanu)
->setMake($make)
->setModelYearFrom($year_from)
->setModelYearTo($year_to);
// add vehicle to battery
foreach ($batteries as $battery)
{
$battery->addVehicle($vehicle);
$this->em->persist($battery);
}
// add vehicle to manufacturer
$vmanu->addVehicle($vehicle);
$this->em->persist($vmanu);
$this->em->persist($vehicle);
$this->em->flush();
// add to hash
$this->vmake_hash[$manufacturer][$make] = $vehicle;
}
protected function loadBatteryManufacturers()
{
$this->bmanu_hash = [];
$batt_manufacturers = $this->em->getRepository(BatteryManufacturer::class)->findAll();
foreach ($batt_manufacturers as $batt_manu)
{
$name = $this->normalizeName($batt_manu->getName());
$this->bmanu_hash[$name] = $batt_manu;
}
}
protected function loadBatteryModels()
{
$this->bmodel_hash = [];
$batt_models = $this->em->getRepository(BatteryModel::class)->findAll();
foreach ($batt_models as $batt_model)
{
$name = $this->normalizeName($batt_model->getName());
$this->bmodel_hash[$name] = $batt_model;
}
}
protected function loadBatterySizes()
{
$this->bsize_hash = [];
$batt_sizes = $this->em->getRepository(BatterySize::class)->findAll();
foreach ($batt_sizes as $batt_size)
{
$name = $this->normalizeName($batt_size->getName());
$this->bsize_hash[$name] = $batt_size;
}
}
protected function loadBatteries()
{
$this->batt_hash = [];
$batts = $this->em->getRepository(Battery::class)->findAll();
foreach ($batts as $batt)
{
$brand = $this->normalizeName($batt->getManufacturer()->getName());
$model = $this->normalizeName($batt->getModel()->getName());
$size = $this->normalizeName($batt->getSize()->getName());
$this->batt_hash[$brand][$model][$size] = $batt;
}
}
protected function loadVehicleManufacturers()
{
$this->vmanu_hash = [];
$vmanus = $this->em->getRepository(VehicleManufacturer::class)->findAll();
foreach ($vmanus as $vmanu)
{
$name = $vmanu->getName();
$this->vmanu_hash[$name] = $vmanu;
}
}
protected function loadVehicleMakes()
{
$this->vmake_hash = [];
$vmakes = $this->em->getRepository(Vehicle::class)->findAll();
foreach ($vmakes as $vmake)
{
$manufacturer = $vmake->getManufacturer()->getName();
$make = $vmake->getMake();
$this->vmake_hash[$manufacturer][$make] = $vmake;
}
}
protected function normalizeName($name)
{
// check for M-42. Need to convert to M42
if (strcasecmp($name, self::STR_M_42) == 0)
{
$normalized_key = strtolower(self::STR_M42);
}
else
{
$normalized_key = trim(strtolower($name));
}
return $normalized_key;
}
}

View file

@ -479,5 +479,7 @@ class ImportCustomerCommand extends Command
}
fclose($cust_file);
fclose($cv_file);
return 0;
}
}

View file

@ -35,5 +35,7 @@ class ImportKMLFileCommand extends Command
$kml_file = $input->getArgument('file');
$this->importer->getMapData($kml_file);
return 0;
}
}

View file

@ -544,6 +544,8 @@ class ImportLegacyJobOrderCommand extends Command
fclose($warr_outfile);
fclose($jo_outfile);
fclose($jorow_outfile);
return 0;
}
protected function initializeMaxFieldCounters()

View file

@ -168,7 +168,8 @@ class ImportOutletsCommand extends Command
{
$output->writeln("Errors occurred! Please check the CSV file is in the proper format.");
}
return 0;
}
protected function setObject($obj, $fields)

View file

@ -163,6 +163,7 @@ class ImportPartnersCommand extends Command
$row_num++;
}
return 0;
}
}

View file

@ -145,6 +145,8 @@ class ImportSAPBatteryCommand extends Command
{
$this->writeDupeReport($report_file, $dupe_brands, $dupe_sizes, $dupe_batteries);
}
return 0;
}
protected function initBatteryHash()

View file

@ -221,6 +221,6 @@ class ImportVehicleBatteryCommand extends Command
$em->flush();
// print_r($batteries);
return 0;
}
}

View file

@ -317,6 +317,6 @@ class ImportVehicleCompatibilityCommand extends Command
$em->flush();
// print_r($batteries);
return 0;
}
}

View file

@ -161,8 +161,7 @@ class MergeDuplicateVehiclesCommand extends Command
$em->flush();
}
}
// print_r($dupes);
return 0;
}
}

View file

@ -0,0 +1,70 @@
<?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 Doctrine\DBAL\Connection;
use Doctrine\ORM\EntityManagerInterface;
use App\Service\JobOrderCache;
use App\Entity\JobOrder;
use App\Ramcar\JOStatus;
use DateTime;
class RefreshJobOrderCacheCommand extends Command
{
protected $em;
protected $jo_cache;
public function __construct(EntityManagerInterface $om, JobOrderCache $jo_cache)
{
$this->em = $om;
$this->jo_cache = $jo_cache;
parent::__construct();
}
protected function configure()
{
$this->setName('joborder:refresh_cache')
->setDescription('Refresh active job order cache from database.')
->setHelp('Refresh active job order cache from database.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$date = new DateTime();
$date->modify('-3 day');
$status_list = [
JOStatus::PENDING,
JOStatus::RIDER_ASSIGN,
JOStatus::ASSIGNED,
JOStatus::IN_TRANSIT,
JOStatus::IN_PROGRESS,
];
$qb = $this->em->getRepository(JobOrder::class)
->createQueryBuilder('jo');
$res = $qb->select('jo')
->where('jo.status IN (:statuses)')
->andWhere('jo.date_schedule >= :date')
->setParameter('statuses', $status_list, Connection::PARAM_STR_ARRAY)
->setParameter('date', $date)
->getQuery()
->execute();
// fulfill each
foreach ($res as $jo)
{
$this->jo_cache->addActiveJobOrder($jo);
}
return 0;
}
}

View file

@ -142,5 +142,7 @@ class ReportRiderTime extends Command
}
fclose($fh);
return 0;
}
}

View file

@ -0,0 +1,61 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\EntityManagerInterface;
use App\Service\RedisClientProvider;
use App\Entity\RiderSession;
class SeedRiderSessionsCommand extends Command
{
protected $em;
protected $redis;
public function __construct(EntityManagerInterface $om, RedisClientProvider $redis)
{
$this->em = $om;
$this->redis = $redis->getRedisClient();
parent::__construct();
}
protected function configure()
{
$this->setName('rider:session:seed')
->setDescription('Seed current rider sessions')
->setHelp('Seed current rider sessions');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// get all rider sessions
$r_sessions = $this->em->getRepository(RiderSession::class)->findAll();
foreach ($r_sessions as $session)
{
// get session id
$session_id = $session->getID();
// get rider id
if ($session->getRider() != null)
{
$rider_id = $session->getRider()->getID();
// key for redis
$redis_key = 'rider.id.' . $session_id;
//$output->writeln('key: ' . $redis_key);
// set to redis cache
$this->redis->set($redis_key, $rider_id);
}
}
return 0;
}
}

View file

@ -80,5 +80,7 @@ class SetCustomerPrivacyPolicyCommand extends Command
}
$this->em->flush();
return 0;
}
}

View file

@ -66,5 +66,7 @@ class TestGeneralSearchCommand extends Command
echo "Last Name: " . $warranty->getLastName() . "\n";
echo "First Name: " . $warranty->getFirstName() . "\n";
}
return 0;
}
}

View file

@ -40,5 +40,7 @@ class TestGeofenceCommand extends Command
echo "In geofence\n";
else
echo "NOT in geofence\n";
return 0;
}
}

View file

@ -35,5 +35,7 @@ class TestHubCounterCommand extends Command
$available_rc = $this->hc->getAvailableRiderCount($hub_id);
echo "Available Riders in Hub: " . $available_rc . "\n";
return 0;
}
}

View file

@ -36,5 +36,7 @@ class TestJobOrderManagerCommand extends Command
echo "Job Order successfully updated" . "\n";
else
echo "Job Order not updated" . "\n";
return 0;
}
}

View file

@ -34,5 +34,7 @@ class TestRegAPNSCommand extends Command
{
$push_id = $input->getArgument('push_id');
$this->apns->sendReg($push_id, 'Test Delay', 'Body');
return 0;
}
}

View file

@ -42,5 +42,7 @@ class TestRiderTrackerCommand extends Command
{
echo "Invalid rider id." . "\n";
}
return 0;
}
}

View file

@ -63,5 +63,7 @@ class UpdateCustomerVehicleBatteryCommand extends Command
}
}
}
return 0;
}
}

View file

@ -94,5 +94,7 @@ class UpdateCustomerVehicleWarrantyCommand extends Command
$this->em->detach($row[0]);
}
return 0;
}
}

View file

@ -96,5 +96,7 @@ class UploadCleanupCommand extends Command
$output->writeln('Deleted ' . $i . ' orphaned file(s). Done!');
else
$output->writeln('No files found. Done!');
return 0;
}
}

View file

@ -67,5 +67,7 @@ class UserCreateCommand extends Command
$em->persist($user);
$em->flush();
return 0;
}
}

View file

@ -24,7 +24,7 @@ use App\Ramcar\TransactionOrigin;
use App\Ramcar\TradeInType;
use App\Ramcar\JOEventType;
use App\Service\InvoiceCreator;
use App\Service\InvoiceGeneratorInterface;
use App\Service\RisingTideGateway;
use App\Service\MQTTClient;
use App\Service\GeofenceTracker;
@ -817,7 +817,7 @@ class APIController extends Controller
return $res->getReturnResponse();
}
public function requestJobOrder(Request $req, InvoiceCreator $ic, GeofenceTracker $geo)
public function requestJobOrder(Request $req, InvoiceGeneratorInterface $ic, GeofenceTracker $geo)
{
// check required parameters and api key
$required_params = [
@ -979,7 +979,7 @@ class APIController extends Controller
$icrit->addEntry($batt, $trade_in, 1);
// send to invoice generator
$invoice = $ic->processCriteria($icrit);
$invoice = $ic->generateInvoice($icrit);
$jo->setInvoice($invoice);
$em->persist($jo);
@ -1026,7 +1026,7 @@ class APIController extends Controller
return $res->getReturnResponse();
}
public function getEstimate(Request $req, InvoiceCreator $ic)
public function getEstimate(Request $req, InvoiceGeneratorInterface $ic)
{
// $this->debugRequest($req);
@ -1126,7 +1126,7 @@ class APIController extends Controller
$icrit->addEntry($batt, $trade_in, 1);
// send to invoice generator
$invoice = $ic->processCriteria($icrit);
$invoice = $ic->generateInvoice($icrit);
// make invoice json data
$data = [

View file

@ -2,134 +2,54 @@
namespace App\Controller;
use App\Ramcar\CustomerClassification;
use App\Ramcar\FuelType;
use App\Ramcar\VehicleStatusCondition;
use App\Ramcar\CrudException;
use App\Service\CustomerHandlerInterface;
use App\Entity\Customer;
use App\Entity\CustomerVehicle;
use App\Entity\MobileNumber;
use App\Entity\Vehicle;
use App\Entity\VehicleManufacturer;
use App\Entity\Battery;
use App\Entity\BatteryManufacturer;
use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
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 CustomerController extends Controller
{
/**
* @Menu(selected="customer_list")
*/
public function index()
public function index(CustomerHandlerInterface $cust_handler)
{
$this->denyAccessUnlessGranted('customer.list', null, 'No access.');
return $this->render('customer/list.html.twig');
$params = $cust_handler->initializeCustomerIndexForm();
$template = $params['template'];
return $this->render($template);
}
public function rows(Request $req)
public function rows(Request $req, CustomerHandlerInterface $cust_handler)
{
$this->denyAccessUnlessGranted('customer.list', null, 'No access.');
// build query
$tqb = $this->getDoctrine()
->getRepository(Customer::class)
->createQueryBuilder('q');
$qb = $this->getDoctrine()
->getRepository(Customer::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $tqb->select('COUNT(q)');
// add filters to count query
$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');
// add filters to query
$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.first_name', 'asc');
}
// get rows for this page
$obj_rows = $query->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery()
->getResult();
$params = $cust_handler->getCustomers($req);
$meta = $params['meta'];
$rows = $params['rows'];
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow->getID();
$row['title'] = $orow->getTitle();
$row['first_name'] = $orow->getFirstName();
$row['last_name'] = $orow->getLastName();
$row['customer_classification'] = CustomerClassification::getName($orow->getCustomerClassification());
$row['flag_mobile_app'] = $orow->hasMobileApp();
$row['app_mobile_number'] = $orow->hasMobileApp() && !empty($orow->getMobileSessions()) ? $orow->getMobileSessions()[0]->getPhoneNumber() : '';
$row['flag_active'] = $orow->isActive();
$row['flag_csat'] = $orow->isCSAT();
// TODO: properly add mobile numbers and plate numbers as searchable/sortable fields, use doctrine events
$row['mobile_numbers'] = implode("<br>", $orow->getMobileNumberList());
$row['plate_numbers'] = implode("<br>", $orow->getPlateNumberList());
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
foreach ($rows as $key => $data) {
// add crud urls
if ($this->isGranted('customer.update'))
$row['meta']['update_url'] = $this->generateUrl('customer_update', ['id' => $row['id']]);
if ($this->isGranted('customer.delete'))
$row['meta']['delete_url'] = $this->generateUrl('customer_delete', ['id' => $row['id']]);
$cust_id = $rows[$key]['id'];
$rows[] = $row;
if ($this->isGranted('customer.update'))
$rows[$key]['meta']['update_url'] = $this->generateUrl('customer_update', ['id' => $cust_id]);
if ($this->isGranted('customer.delete'))
$rows[$key]['meta']['delete_url'] = $this->generateUrl('customer_delete', ['id' => $cust_id]);
}
// response
@ -139,347 +59,119 @@ class CustomerController extends Controller
]);
}
protected function fillDropdownParameters(&$params)
{
$em = $this->getDoctrine()->getManager();
$params['bmfgs'] = $em->getRepository(BatteryManufacturer::class)->findAll();
$params['vmfgs'] = $em->getRepository(VehicleManufacturer::class)->findAll();
$params['classifications'] = CustomerClassification::getCollection();
$params['fuel_types'] = FuelType::getCollection();
$params['status_conditions'] = VehicleStatusCondition::getCollection();
$params['years'] = $this->generateYearOptions();
$params['batteries'] = $em->getRepository(Battery::class)->findAll();
}
/**
* @Menu(selected="customer_list")
*/
public function addForm()
public function addForm(CustomerHandlerInterface $cust_handler)
{
$this->denyAccessUnlessGranted('customer.add', null, 'No access.');
$params['obj'] = new Customer();
$params['mode'] = 'create';
$params = $cust_handler->initializeAddCustomerForm();
// get dropdown parameters
$this->fillDropdownParameters($params);
$template = $params['template'];
// response
return $this->render('customer/form.html.twig', $params);
return $this->render($template, $params);
}
protected function setObject($obj, $req)
{
// set and save values
$obj->setTitle($req->request->get('title'))
->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setCustomerClassification($req->request->get('customer_classification'))
->setCustomerNotes($req->request->get('customer_notes'))
->setEmail($req->request->get('email'))
->setIsCSAT($req->request->get('flag_csat') ? true : false)
->setActive($req->request->get('flag_active') ? true : false);
// phone numbers
$obj->setPhoneMobile($req->request->get('phone_mobile'))
->setPhoneLandline($req->request->get('phone_landline'))
->setPhoneOffice($req->request->get('phone_office'))
->setPhoneFax($req->request->get('phone_fax'));
}
public function addSubmit(Request $req, ValidatorInterface $validator)
public function addSubmit(Request $req, CustomerHandlerInterface $cust_handler)
{
$this->denyAccessUnlessGranted('customer.add', null, 'No access.');
// create new row
$em = $this->getDoctrine()->getManager();
$row = new Customer();
$result = $cust_handler->addCustomer($req);
$this->setObject($row, $req);
// initialize error lists
$error_array = [];
$nerror_array = [];
$verror_array = [];
// error_log(print_r($req->request->all(), true));
// custom validation for vehicles
$vehicles = json_decode($req->request->get('vehicles'));
if (!empty($vehicles)) {
foreach ($vehicles as $vehicle) {
// check if vehicle exists
$vobj = $em->getRepository(Vehicle::class)->find($vehicle->vehicle);
if (empty($vobj)) {
$verror_array[$vehicle->index]['vehicle'] = 'Invalid vehicle specified.';
} else {
$cust_vehicle = new CustomerVehicle();
$cust_vehicle->setName($vehicle->name)
->setVehicle($vobj)
->setPlateNumber($vehicle->plate_number)
->setModelYear($vehicle->model_year)
->setColor($vehicle->color)
->setStatusCondition($vehicle->status_condition)
->setFuelType($vehicle->fuel_type)
->setActive($vehicle->flag_active)
->setCustomer($row);
// if specified, check if battery exists
if ($vehicle->battery) {
// check if battery exists
$bobj = $em->getRepository(Battery::class)->find($vehicle->battery);
if (empty($bobj)) {
$verror_array[$vehicle->index]['battery'] = 'Invalid battery specified.';
} else {
// check if warranty expiration was specified
$warr_ex = DateTime::createFromFormat("d M Y", $vehicle->warranty_expiration);
if (!$warr_ex)
$warr_ex = null;
$cust_vehicle->setHasMotoliteBattery(true)
->setCurrentBattery($bobj)
->setWarrantyCode($vehicle->warranty_code)
->setWarrantyExpiration($warr_ex);
}
} else {
$cust_vehicle->setHasMotoliteBattery(false);
}
$verrors = $validator->validate($cust_vehicle);
// add errors to list
foreach ($verrors as $error) {
if (!isset($verror_array[$vehicle->index]))
$verror_array[$vehicle->index] = [];
$verror_array[$vehicle->index][$error->getPropertyPath()] = $error->getMessage();
}
// add to entity
if (!isset($verror_array[$vehicle->index])) {
$row->addVehicle($cust_vehicle);
}
}
}
}
// validate
$errors = $validator->validate($row);
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array) || !empty($nerror_array) || !empty($verror_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array,
'nerrors' => $nerror_array,
'verrors' => $verror_array
], 422);
} else {
// validated! save the entity
$em->persist($row);
$em->flush();
if (isset($result['id']))
{
$id = $result['id'];
// return successful response
return $this->json([
'success' => 'Changes have been saved!',
'id' => $row->getID()
'id' => $id
]);
}
}
/**
* @Menu(selected="customer_list")
*/
public function updateForm($id)
{
$this->denyAccessUnlessGranted('customer.update', null, 'No access.');
$params['mode'] = 'update';
// get row data
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(Customer::class)->find($id);
// make sure this row exists
if (empty($row))
throw $this->createNotFoundException('The item does not exist');
// get dropdown parameters
$this->fillDropdownParameters($params);
$params['obj'] = $row;
// response
return $this->render('customer/form.html.twig', $params);
}
protected function updateVehicles($em, Customer $cust, $vehicles)
{
$vehicle_ids = [];
foreach ($vehicles as $vehicle)
{
// check if customer vehicle exists
if (!empty($vehicle->id))
{
$cust_vehicle = $em->getRepository(CustomerVehicle::class)->find($vehicle->id);
if ($cust_vehicle == null)
throw new CrudException("Could not find customer vehicle.");
}
// this is a new vehicle
else
{
$cust_vehicle = new CustomerVehicle();
$cust_vehicle->setCustomer($cust);
$cust->addVehicle($cust_vehicle);
$em->persist($cust_vehicle);
}
// vehicle, because they could have changed vehicle type
$vobj = $em->getRepository(Vehicle::class)->find($vehicle->vehicle);
if ($vobj == null)
throw new CrudException("Could not find vehicle.");
// TODO: validate details
$cust_vehicle->setName($vehicle->name)
->setVehicle($vobj)
->setPlateNumber($vehicle->plate_number)
->setModelYear($vehicle->model_year)
->setColor($vehicle->color)
->setStatusCondition($vehicle->status_condition)
->setFuelType($vehicle->fuel_type)
->setActive($vehicle->flag_active);
// if specified, check if battery exists
if ($vehicle->battery)
{
// check if battery exists
$bobj = $em->getRepository(Battery::class)->find($vehicle->battery);
if ($bobj == null)
throw new CrudException("Could not find battery.");
// check if warranty expiration was specified
$warr_ex = DateTime::createFromFormat("d M Y", $vehicle->warranty_expiration);
if (!$warr_ex)
$warr_ex = null;
$cust_vehicle->setHasMotoliteBattery(true)
->setCurrentBattery($bobj)
->setWarrantyCode($vehicle->warranty_code)
->setWarrantyExpiration($warr_ex);
}
else
{
$cust_vehicle->setHasMotoliteBattery(false);
}
// add to list of vehicles to keep
$vehicle_ids[$cust_vehicle->getID()] = true;
}
// cleanup
// delete all vehicles not in list
$cvs = $cust->getVehicles();
foreach ($cvs as $cv)
{
if (!isset($vehicle_ids[$cv->getID()]))
{
$cust->removeVehicle($cv);
$em->remove($cv);
}
}
}
public function updateSubmit(Request $req, ValidatorInterface $validator, $id)
{
$this->denyAccessUnlessGranted('customer.update', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$cust = $em->getRepository(Customer::class)->find($id);
// make sure this row exists
if (empty($cust))
throw $this->createNotFoundException('The item does not exist');
$this->setObject($cust, $req);
// initialize error lists
$error_array = [];
$nerror_array = [];
$verror_array = [];
// TODO: validate mobile numbers
// TODO: validate vehicles
// custom validation for vehicles
$vehicles = json_decode($req->request->get('vehicles'));
$this->updateVehicles($em, $cust, $vehicles);
// validate
$errors = $validator->validate($cust);
// add errors to list
foreach ($errors as $error)
{
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array) || !empty($nerror_array) || !empty($verror_array))
{
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array,
'nerrors' => $nerror_array,
'verrors' => $verror_array
], 422);
}
else
{
// validated! save the entity. do a persist anyway to save child entities
$em->persist($cust);
$em->flush();
$error_array = $result['error_array'];
$nerror_array = $result['nerror_array'];
$verror_array = $result['verror_array'];
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array,
'nerrors' => $nerror_array,
'verrors' => $verror_array
], 422);
}
}
/**
* @Menu(selected="customer_list")
*/
public function updateForm($id, CustomerHandlerInterface $cust_handler)
{
$this->denyAccessUnlessGranted('customer.update', null, 'No access.');
$params = $cust_handler->initializeUpdateCustomerForm($id);
$template = $params['template'];
// response
return $this->render($template, $params);
}
public function updateSubmit(Request $req, CustomerHandlerInterface $cust_handler, $id)
{
$this->denyAccessUnlessGranted('customer.update', null, 'No access.');
try
{
$result = $cust_handler->updateCustomer($req, $id);
}
catch (CrudException $e)
{
throw new CrudException($e->getMessage());
}
if (isset($result['id']))
{
$id = $result['id'];
// return successful response
return $this->json([
'success' => 'Changes have been saved!',
'id' => $cust->getID()
'id' => $id
]);
}
}
else
{
$error_array = $result['error_array'];
$nerror_array = $result['nerror_array'];
$verror_array = $result['verror_array'];
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array,
'nerrors' => $nerror_array,
'verrors' => $verror_array
], 422);
}
}
public function destroy($id)
public function destroy($id, CustomerHandlerInterface $cust_handler)
{
$this->denyAccessUnlessGranted('customer.delete', null, 'No access.');
// get row data
$em = $this->getDoctrine()->getManager();
$row = $em->getRepository(Customer::class)->find($id);
if (empty($row))
throw $this->createNotFoundException('The item does not exist');
// delete this row
$em->remove($row);
$em->flush();
try
{
$cust_handler->deleteCustomer($id);
}
catch (NotFoundHttpException $e)
{
throw $this->createNotFoundException($e->getMessage());
}
// response
$response = new Response();
@ -487,113 +179,17 @@ class CustomerController extends Controller
$response->send();
}
protected function generateYearOptions()
{
$start_year = 1950;
return range($start_year, date("Y") + 1);
}
public function getCustomerVehicles(Request $req)
public function getCustomerVehicles(Request $req, CustomerHandlerInterface $cust_handler)
{
if (!$this->isGranted('jo_in.list')) {
$exception = $this->createAccessDeniedException('No access.');
throw $exception;
}
// get search term
$term = $req->query->get('search');
$results = $cust_handler->getCustomerVehicles($req);
// get querybuilder
$qb = $this->getDoctrine()
->getRepository(CustomerVehicle::class)
->createQueryBuilder('q');
/*
// build expression now since we're reusing it
$vehicle_label = $qb->expr()->concat(
'q.plate_number',
$qb->expr()->literal(' - '),
'c.first_name',
$qb->expr()->literal(' '),
'c.last_name',
$qb->expr()->literal(' (+63'),
'c.phone_mobile',
$qb->expr()->literal(')')
);
*/
// count total records
$tquery = $qb->select('COUNT(q)');
// add filters to count query
if (!empty($term)) {
$tquery->where('q.plate_number like :search')
->setParameter('search', $term . '%');
/*
$tquery->where('match_against (q.plate_number, :search \'in boolean mode\') > 0.1')
->setParameter('search', $term . '*');
*/
/*
$tquery->where('q.plate_number LIKE :filter')
->setParameter('filter', '%' . $term . '%');
*/
}
$total = $tquery->getQuery()
->getSingleScalarResult();
// pagination vars
$page = $req->query->get('page') ?? 1;
$perpage = 20;
$offset = ($page - 1) * $perpage;
$pages = ceil($total / $perpage);
$has_more_pages = $page < $pages ? true : false;
// build main query
$query = $qb->select('q');
/*
->addSelect($vehicle_label . ' as vehicle_label')
->addSelect('c.first_name as cust_first_name')
->addSelect('c.last_name as cust_last_name');
*/
// add filters if needed
if (!empty($term)) {
$query->where('q.plate_number like :search')
->setParameter('search', $term . '%');
/*
$query->where('match_against (q.plate_number, :search \'in boolean mode\') > 0.1')
->setParameter('search', $term . '*');
*/
/*
$query->where('q.plate_number LIKE :filter')
->setParameter('filter', '%' . $term . '%');
*/
}
// get rows
$query_obj = $query->orderBy('q.plate_number', 'asc')
->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery();
// error_log($query_obj->getSql());
$obj_rows = $query_obj->getResult();
// build vehicles array
$vehicles = [];
// get country code from services.yaml
$country_code = $this->getParameter('country_code');
foreach ($obj_rows as $cv) {
$cust = $cv->getCustomer();
$vehicles[] = [
'id' => $cv->getID(),
'text' => $cv->getPlateNumber() . ' ' . $cust->getFirstName() . ' ' . $cust->getLastName() . ' (' . $country_code . $cust->getPhoneMobile() . ')',
];
}
$vehicles = $results['vehicles'];
$has_more_pages = $results['has_more_pages'];
// response
return $this->json([
@ -605,85 +201,26 @@ class CustomerController extends Controller
]);
}
public function getCustomerVehicleInfo(Request $req)
public function getCustomerVehicleInfo(Request $req, CustomerHandlerInterface $cust_handler)
{
$this->denyAccessUnlessGranted('jo_in.list', null, 'No access.');
// get id
$id = $req->query->get('id');
$result = $cust_handler->getCustomerVehicleInfo($req);
// get row data
$em = $this->getDoctrine()->getManager();
$obj = $em->getRepository(CustomerVehicle::class)->find($id);
// make sure this row exists
if (empty($obj)) {
if ($result == null)
{
return $this->json([
'success' => false,
'error' => 'The item does not exist'
]);
}
$customer = $obj->getCustomer();
$vehicle = $obj->getVehicle();
$battery = $obj->getCurrentBattery();
// build response
$row = [
'customer' => [
'id' => $customer->getID(),
'first_name' => $customer->getFirstName(),
'last_name' => $customer->getLastName(),
'customer_notes' => $customer->getCustomerNotes(),
'phone_mobile' => $customer->getPhoneMobile(),
'phone_landline' => $customer->getPhoneLandline(),
'phone_office' => $customer->getPhoneOffice(),
'phone_fax' => $customer->getPhoneFax(),
],
'vehicle' => [
'id' => $vehicle->getID(),
'mfg_name' => $vehicle->getManufacturer()->getName(),
'make' => $vehicle->getMake(),
'model_year_from' => $vehicle->getModelYearFrom(),
'model_year_to' => $vehicle->getModelYearTo(),
'model_year' => $obj->getModelYear(),
'color' => $obj->getColor(),
'plate_number' => $obj->getPlateNumber(),
//'fuel_type' => $obj->getFuelType(),
//'status_condition' => $obj->getStatusCondition(),
]
];
if (!empty($battery)) {
$row['battery'] = [
'id' => $battery->getID(),
'mfg_name' => $battery->getManufacturer()->getName(),
'model_name' => $battery->getModel()->getName(),
'size_name' => $battery->getSize()->getName(),
'prod_code' => $battery->getProductCode(),
'warranty_code' => $obj->getWarrantyCode(),
'warranty_expiration' => $obj->getWarrantyExpiration() ? $obj->getWarrantyExpiration()->format("d M Y") : "",
'has_motolite_battery' => $obj->hasMotoliteBattery(),
'is_active' => $obj->isActive()
];
}
// response
return $this->json([
'success' => true,
'data' => $row
]);
}
// check if datatable filter is present and append to query
protected function setQueryFilters($datatable, &$query) {
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->join('q.vehicles', 'cv')
->where('q.first_name LIKE :filter')
->orWhere('q.last_name LIKE :filter')
->orWhere('q.customer_classification LIKE :filter')
->orWhere('cv.plate_number LIKE :filter')
->setParameter('filter', $datatable['query']['data-rows-search'] . '%');
else
{
// response
return $this->json([
'success' => true,
'data' => $result
]);
}
}
}

View file

@ -5,13 +5,122 @@ namespace App\Controller;
use Catalyst\MenuBundle\Annotation\Menu;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\ORM\EntityManagerInterface;
use App\Service\RiderTracker;
use App\Service\GISManagerInterface;
use App\Service\JobOrderCache;
use App\Service\RiderCache;
use App\Entity\Rider;
class HomeController extends Controller
{
/**
* @Menu(selected="home")
*/
public function index()
public function index(
EntityManagerInterface $em,
RiderTracker $rider_tracker,
GISManagerInterface $gis_manager
)
{
return $this->render('home.html.twig');
// get map
$params['map_js_file'] = $gis_manager->getJSInitFile();
return $this->render('home.html.twig', $params);
}
public function getMapLocations(JobOrderCache $jo_cache)
{
$active_jos = $jo_cache->getAllActiveJobOrders();
// get active JOs from cache
}
public function getRiderLocations(JobOrderCache $jo_cache, RiderCache $rider_cache, EntityManagerInterface $em, RiderTracker $rider_tracker)
{
// get active JOs from cache
$active_jos = $jo_cache->getAllActiveJobOrders();
$riders = $rider_cache->getAllActiveRiders();
// TODO: optimize this
// get all riders and figure out if they have active jos
foreach ($riders as $rider_id => $rider_data)
{
$rider = $em->getRepository(Rider::class)->find($rider_id);
if ($rider == null)
{
unset($riders[$rider_id]);
continue;
}
$jo = $rider->getActiveJobOrder();
if ($jo == null)
$riders[$rider_id]['has_jo'] = false;
else
$riders[$rider_id]['has_jo'] = true;
}
// get active riders from cache
// get all riders
/*
$riders = $em->getRepository(Rider::class)->findAll();
$locations = [];
foreach ($riders as $rider)
{
// get location for each rider
$rider_id = $rider->getID();
$coordinates = $rider_tracker->getRiderLocation($rider_id);
$lat = $coordinates->getLatitude();
$long = $coordinates->getLongitude();
$jo = $rider->getActiveJobOrder();
if ($jo == null)
{
$has_jo = false;
$clat = 0;
$clong = 0;
$jo_data = [];
}
else
{
$has_jo = true;
$cust_loc = $jo->getCoordinates();
$clat = $cust_loc->getLatitude();
$clong = $cust_loc->getLongitude();
$jo_id = $jo->getID();
$jo_data = [
'id' => $jo_id,
'status' => $jo->getStatusText(),
'stype' => $jo->getServiceTypeName(),
'url' => $this->generateUrl('jo_all_form', ['id' => $jo_id]),
'plate' => $jo->getCustomerVehicle()->getPlateNumber(),
'cname' => $jo->getCustomer()->getNameDisplay(),
];
}
// use rider map label as key
$rider_map_label = $rider->getMapLabel();
$locations[$rider_id] = [
'label' => $rider->getMapLabel(),
'loc' => [$lat, $long],
'has_jo' => $has_jo,
'cust_loc' => [$clat, $clong],
'jo' => $jo_data,
];
}
*/
return $this->json([
'jos' => $active_jos,
'riders' => $riders,
]);
}
}

View file

@ -17,6 +17,9 @@ use DateTime;
use Catalyst\MenuBundle\Annotation\Menu;
use App\Service\MapTools;
use App\Service\RiderTracker;
class HubController extends Controller
{
/**
@ -287,4 +290,87 @@ class HubController extends Controller
$response->setStatusCode(Response::HTTP_OK);
$response->send();
}
public function nearest(MapTools $map_tools, Request $req)
{
// get lat / long
$lat = $req->query->get('lat');
$long = $req->query->get('long');
// get nearest hubs according to position
$point = new Point($long, $lat);
$result = $map_tools->getClosestHubs($point, 10, date("H:i:s"));
$hubs = [];
foreach ($result as $hub_res)
{
$hub = $hub_res['hub'];
$coords = $hub->getCoordinates();
$hubs[] = [
'id' => $hub->getID(),
'long' => $coords->getLongitude(),
'lat' => $coords->getLatitude(),
'label' => $hub->getFullName(),
'name' => $hub->getName(),
'branch' => $hub->getBranch(),
'cnum' => $hub->getContactNumbers(),
'distance' => $hub_res['distance'],
];
}
return $this->json([
'hubs' => $hubs,
]);
}
public function getHubRiders(Request $req, RiderTracker $rider_tracker)
{
// get hub id
$hub_id = $req->query->get('id');
// get hub
$em = $this->getDoctrine()->getManager();
$hub = $em->getRepository(Hub::class)->find($hub_id);
// make sure this row exists
if (empty($hub))
throw $this->createNotFoundException('The item does not exist');
//TODO: get available riders sort by proximity, show 10
$available_riders = $hub->getAvailableRiders();
$riders = [];
// TODO: remove this later when we don't get all available riders
$riders_limit = 5;
$num_riders = 0;
foreach ($available_riders as $rider)
{
if ($num_riders > $riders_limit)
break;
// get location for each rider
$rider_id = $rider->getID();
$coordinates = $rider_tracker->getRiderLocation($rider_id);
$lat = $coordinates->getLatitude();
$long = $coordinates->getLongitude();
$riders[] = [
'id' => $rider->getID(),
'first_name' => $rider->getFirstName(),
'last_name' => $rider->getLastName(),
'contact_num' => $rider->getContactNumber(),
'plate_num' => $rider->getPlateNumber(),
'location' => [$lat, $long],
];
$num_riders++;
}
return $this->json([
'riders' => $riders,
]);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -10,6 +10,7 @@ use App\Entity\User;
use App\Service\FileUploader;
use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
@ -500,4 +501,13 @@ class RiderController extends Controller
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
public function popupInfo(EntityManagerInterface $em, $id)
{
$rider = $em->getRepository(Rider::class)->find($id);
if ($rider == null)
return new Response('No rider data');
return $this->render('rider/popup.html.twig', [ 'rider' => $rider ]);
}
}

View file

@ -60,14 +60,13 @@ class Battery
// product code
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
* @ORM\Column(type="string", length=80, nullable=true)
*/
protected $prod_code;
// sap code
/**
* @ORM\Column(type="string", length=80)
* @ORM\Column(type="string", length=80, nullable=true)
*/
protected $sap_code;

View file

@ -165,6 +165,21 @@ class Customer
*/
protected $privpol_promo;
/**
* @ORM\Column(type="boolean", options={"default":false})
*/
protected $flag_promo_email;
/**
* @ORM\Column(type="boolean", options={"default":false})
*/
protected $flag_promo_sms;
/**
* @ORM\Column(type="boolean", options={"default":false})
*/
protected $flag_dpa_consent;
public function __construct()
{
$this->numbers = new ArrayCollection();
@ -191,6 +206,10 @@ class Customer
$this->priv_promo = 0;
$this->flag_csat = false;
$this->flag_promo_email = false;
$this->flag_promo_sms = false;
$this->flag_dpa_consent = false;
}
public function getID()
@ -231,6 +250,11 @@ class Customer
return $this->last_name;
}
public function getNameDisplay()
{
return $this->first_name . ' ' . $this->last_name;
}
public function setCustomerClassification($customer_classification)
{
$this->customer_classification = $customer_classification;
@ -485,5 +509,36 @@ class Customer
return $this->privpol_promo;
}
public function setPromoEmail($flag_promo_email = true)
{
$this->flag_promo_email = $flag_promo_email;
return $this;
}
public function isPromoEmail()
{
return $this->flag_promo_email;
}
public function setPromoSms($flag_promo_sms = true)
{
$this->flag_promo_sms = $flag_promo_sms;
return $this;
}
public function isPromoSms()
{
return $this->flag_promo_sms;
}
public function setDpaConsent($flag_dpa_consent = true)
{
$this->flag_dpa_consent = $flag_dpa_consent;
return $this;
}
public function isDpaConsent()
{
return $this->flag_dpa_consent;
}
}

View file

@ -67,14 +67,12 @@ class CustomerVehicle
// vehicle status (new / second-hand)
/**
* @ORM\Column(type="string", length=15)
* @Assert\NotBlank()
*/
protected $status_condition;
// fuel type - diesel, gas
/**
* @ORM\Column(type="string", length=15)
* @Assert\NotBlank()
*/
protected $fuel_type;

View file

@ -319,4 +319,10 @@ class Rider
{
return $this->sessions;
}
public function getMapLabel()
{
$map_label = $this->first_name .' ' . $this->last_name;
return $map_label;
}
}

View file

@ -0,0 +1,105 @@
<?php
namespace App\EventListener;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use App\Service\JobOrderCache;
use App\Ramcar\JOStatus;
use App\Entity\JobOrder;
class JobOrderActiveCacheListener
{
protected $key;
protected $mqtt;
public function __construct(JobOrderCache $jo_cache, $mqtt)
{
$this->jo_cache = $jo_cache;
$this->mqtt = $mqtt;
}
// when a new job order comes in
public function postPersist(JobOrder $jo, LifecycleEventArgs $args)
{
$status = $jo->getStatus();
switch ($status)
{
// active
case JOStatus::PENDING:
case JOStatus::RIDER_ASSIGN:
case JOStatus::ASSIGNED:
case JOStatus::IN_TRANSIT:
case JOStatus::IN_PROGRESS:
$this->processActiveJO($jo);
break;
// inactive
case JOStatus::CANCELLED:
$this->processInactiveJO($jo, 'cancel');
break;
case JOStatus::FULFILLED:
$this->processInactiveJO($jo, 'fulfill');
break;
}
}
// when a job order is updated
public function postUpdate(JobOrder $jo, LifecycleEventArgs $args)
{
$status = $jo->getStatus();
switch ($status)
{
// active
case JOStatus::PENDING:
case JOStatus::RIDER_ASSIGN:
case JOStatus::ASSIGNED:
case JOStatus::IN_TRANSIT:
case JOStatus::IN_PROGRESS:
$this->processActiveJO($jo);
break;
// inactive
case JOStatus::CANCELLED:
$this->processInactiveJO($jo, 'cancel');
break;
case JOStatus::FULFILLED:
$this->processInactiveJO($jo, 'fulfill');
break;
}
}
// when a job order is deleted
public function postRemove(JobOrder $jo, LifecycleEventArgs $args)
{
$this->processInactiveJO($jo, 'delete');
}
protected function processActiveJO($jo)
{
// save in cache
$this->jo_cache->addActiveJobOrder($jo);
// publish to mqtt
$coords = $jo->getCoordinates();
// TODO: do we put the key in config?
$this->mqtt->publish(
'jo/' . $jo->getID() . '/location',
$coords->getLatitude() . ':' . $coords->getLongitude()
);
}
protected function processInactiveJO($jo, $status = 'cancel')
{
// remove from redis cache
$this->jo_cache->removeActiveJobOrder($jo);
// TODO: publich to mqtt
$this->mqtt->publish(
'jo/' . $jo->getID() . '/status',
$status
);
}
}

View file

@ -0,0 +1,16 @@
<?php
namespace App\Ramcar;
class CMBModeOfPayment extends NameValue
{
const CASH = 'cash';
const CREDIT_CARD = 'credit_card';
const BANK_TRANSFER = 'bank_transfer';
const COLLECTION = [
'cash' => 'Cash',
'credit_card' => 'Credit Card',
'bank_transfer' => 'Bank Transfer',
];
}

View file

@ -0,0 +1,16 @@
<?php
namespace App\Ramcar;
class CMBServiceType extends NameValue
{
const BATTERY_REPLACEMENT_NEW = 'battery_new';
const BATTERY_REPLACEMENT_WARRANTY = 'battery_warranty';
const JUMPSTART = 'jumpstart';
const COLLECTION = [
'battery_new' => 'Battery Sales',
'battery_warranty' => 'Under Warranty',
'jumpstart' => 'Jumpstart',
];
}

View file

@ -0,0 +1,13 @@
<?php
namespace App\Ramcar;
class CMBTradeInType extends NameValue
{
const YES = 'yes';
const COLLECTION = [
'yes' => 'Yes',
];
}

View file

@ -0,0 +1,15 @@
<?php
namespace App\Ramcar;
class CMBWarrantyClass extends NameValue
{
const WTY_PASSENGER = 'passenger';
const WTY_COMMERCIAL = 'commercial';
const COLLECTION = [
'passenger' => 'Passenger',
'commercial' => 'Commercial',
];
}

View file

@ -104,7 +104,7 @@ class InvoiceCriteria
return $this->entries;
}
public function setCustomerVehicle(CustomerVehicle $cv)
public function setCustomerVehicle(CustomerVehicle $cv = null)
{
$this->cv = $cv;
return $this;

View file

@ -0,0 +1,699 @@
<?php
namespace App\Service\CustomerHandler;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use App\Ramcar\CustomerClassification;
use App\Ramcar\CrudException;
use App\Service\CustomerHandlerInterface;
use App\Entity\Customer;
use App\Entity\CustomerVehicle;
use App\Entity\Vehicle;
use App\Entity\Battery;
use App\Entity\VehicleManufacturer;
use App\Entity\BatteryManufacturer;
use DateTime;
class CMBCustomerHandler implements CustomerHandlerInterface
{
protected $em;
protected $validator;
protected $country_code;
protected $template_hash;
public function __construct(EntityManagerInterface $em, ValidatorInterface $validator,
string $country_code)
{
$this->em = $em;
$this->validator = $validator;
$this->country_code = $country_code;
$this->loadTemplates();
}
// initialize form to display customer list
public function initializeCustomerIndexForm()
{
$params['template'] = $this->getTwigTemplate('cust_list');
return $params;
}
// get customers
public function getCustomers(Request $req)
{
// build query
$tqb = $this->em->getRepository(Customer::class)
->createQueryBuilder('q');
$qb = $this->em->getRepository(Customer::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $tqb->select('COUNT(q)');
// add filters to count query
$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');
// add filters to query
$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.first_name', '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['title'] = $orow->getTitle();
$row['first_name'] = $orow->getFirstName();
$row['last_name'] = $orow->getLastName();
$row['customer_classification'] = CustomerClassification::getName($orow->getCustomerClassification());
$row['flag_mobile_app'] = $orow->hasMobileApp();
$row['app_mobile_number'] = $orow->hasMobileApp() && !empty($orow->getMobileSessions()) ? $orow->getMobileSessions()[0]->getPhoneNumber() : '';
$row['flag_active'] = $orow->isActive();
$row['flag_csat'] = $orow->isCSAT();
// TODO: properly add mobile numbers and plate numbers as searchable/sortable fields, use doctrine events
// prepend the country code before each mobile number
$mobile_number_list = [];
$mobile_numbers = $orow->getMobileNumberList();
foreach ($mobile_numbers as $mobile_number)
{
$mobile_number_list[] = $this->country_code . $mobile_number;
}
$row['mobile_numbers'] = implode("<br>", $mobile_number_list);
$row['plate_numbers'] = implode("<br>", $orow->getPlateNumberList());
$rows[] = $row;
}
$params['meta'] = $meta;
$params['rows'] = $rows;
return $params;
}
// initialize add customer form
public function initializeAddCustomerForm()
{
$params['obj'] = new Customer();
$params['mode'] = 'create';
// get dropdown parameters
$this->fillDropdownParameters($params);
// get template to display
$params['template'] = $this->getTwigTemplate('cust_add_form');
// return params
return $params;
}
// add new customer and customer vehicle, if any
public function addCustomer(Request $req)
{
// create new row
$em = $this->em;
$row = new Customer();
$this->setObject($row, $req);
// initialize error lists
$error_array = [];
$nerror_array = [];
$verror_array = [];
// custom validation for vehicles
$vehicles = json_decode($req->request->get('vehicles'));
if (!empty($vehicles))
{
foreach ($vehicles as $vehicle)
{
// check if vehicle exists
$vobj = $em->getRepository(Vehicle::class)->find($vehicle->vehicle);
if (empty($vobj))
{
$verror_array[$vehicle->index]['vehicle'] = 'Invalid vehicle specified.';
}
else
{
$cust_vehicle = new CustomerVehicle();
$cust_vehicle->setName($vehicle->name)
->setVehicle($vobj)
->setPlateNumber($vehicle->plate_number)
->setModelYear($vehicle->model_year)
->setColor('')
->setStatusCondition('')
->setFuelType('')
->setActive($vehicle->flag_active)
->setCustomer($row);
// if specified, check if battery exists
if ($vehicle->battery)
{
// check if battery exists
$bobj = $em->getRepository(Battery::class)->find($vehicle->battery);
if (empty($bobj))
{
$verror_array[$vehicle->index]['battery'] = 'Invalid battery specified.';
}
else
{
// check if warranty expiration was specified
$warr_ex = DateTime::createFromFormat("d M Y", $vehicle->warranty_expiration);
if (!$warr_ex)
$warr_ex = null;
$cust_vehicle->setHasMotoliteBattery(true)
->setCurrentBattery($bobj)
->setWarrantyCode($vehicle->warranty_code)
->setWarrantyExpiration($warr_ex);
}
}
else
{
$cust_vehicle->setHasMotoliteBattery(false);
}
$verrors = $this->validator->validate($cust_vehicle);
// add errors to list
foreach ($verrors as $error)
{
if (!isset($verror_array[$vehicle->index]))
$verror_array[$vehicle->index] = [];
$verror_array[$vehicle->index][$error->getPropertyPath()] = $error->getMessage();
}
// add to entity
if (!isset($verror_array[$vehicle->index]))
{
$row->addVehicle($cust_vehicle);
}
}
}
}
// validate
$errors = $this->validator->validate($row);
// add errors to list
foreach ($errors as $error)
{
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
$result = [];
// check if any errors were found
if (!empty($error_array) || !empty($nerror_array) || !empty($verror_array))
{
// return all error_arrays
$result = [
'error_array' => $error_array,
'nerror_array' => $nerror_array,
'verror_array' => $verror_array,
];
}
else
{
// validated! save the entity
$em->persist($row);
$em->flush();
$result = [
'id' => $row->getID(),
];
}
return $result;
}
// initialize update customer form
public function initializeUpdateCustomerForm($id)
{
$params['mode'] = 'update';
// get row data
$em = $this->em;
$row = $em->getRepository(Customer::class)->find($id);
// make sure this row exists
if (empty($row))
throw new NotFoundHttpException('The item does not exist');
// get dropdown parameters
$this->fillDropdownParameters($params);
// get template to display
$params['template'] = $this->getTwigTemplate('cust_update_form');
$params['obj'] = $row;
return $params;
}
// update customer and customer vehicle
public function updateCustomer(Request $req, $id)
{
// get row data
$em = $this->em;
$cust = $em->getRepository(Customer::class)->find($id);
// make sure this row exists
if (empty($cust))
throw $this->createNotFoundException('The item does not exist');
$this->setObject($cust, $req);
// initialize error lists
$error_array = [];
$nerror_array = [];
$verror_array = [];
// TODO: validate mobile numbers
// TODO: validate vehicles
// custom validation for vehicles
$vehicles = json_decode($req->request->get('vehicles'));
try
{
$this->updateVehicles($em, $cust, $vehicles);
}
catch (CrudException $e)
{
throw new CrudException($e->getMessage());
}
// validate
$errors = $this->validator->validate($cust);
// add errors to list
foreach ($errors as $error)
{
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
$result = [];
if (!empty($error_array) || !empty($nerror_array) || !empty($verror_array))
{
// return all error_arrays
$result = [
'error_array' => $error_array,
'nerror_array' => $nerror_array,
'verror_array' => $verror_array,
];
}
else
{
// validated! save the entity. do a persist anyway to save child entities
$em->persist($cust);
$em->flush();
$result = [
'id' => $cust->getID(),
];
}
return $result;
}
// delete customer
public function deleteCustomer(int $id)
{
// get row data
$em = $this->em;
$row = $em->getRepository(Customer::class)->find($id);
if (empty($row))
throw new NotFoundHttpException('The item does not exist');
// delete this row
$em->remove($row);
$em->flush();
}
// get customer vehicles
public function getCustomerVehicles(Request $req)
{
// get search term
$term = $req->query->get('search');
// get querybuilder
$qb = $this->em
->getRepository(CustomerVehicle::class)
->createQueryBuilder('q');
/*
// build expression now since we're reusing it
$vehicle_label = $qb->expr()->concat(
'q.plate_number',
$qb->expr()->literal(' - '),
'c.first_name',
$qb->expr()->literal(' '),
'c.last_name',
$qb->expr()->literal(' (+63'),
'c.phone_mobile',
$qb->expr()->literal(')')
);
*/
// count total records
$tquery = $qb->select('COUNT(q)');
// add filters to count query
if (!empty($term)) {
$tquery->where('q.plate_number like :search')
->setParameter('search', $term . '%');
/*
$tquery->where('match_against (q.plate_number, :search \'in boolean mode\') > 0.1')
->setParameter('search', $term . '*');
*/
/*
$tquery->where('q.plate_number LIKE :filter')
->setParameter('filter', '%' . $term . '%');
*/
}
$total = $tquery->getQuery()
->getSingleScalarResult();
// pagination vars
$page = $req->query->get('page') ?? 1;
$perpage = 20;
$offset = ($page - 1) * $perpage;
$pages = ceil($total / $perpage);
$has_more_pages = $page < $pages ? true : false;
// build main query
$query = $qb->select('q');
/*
->addSelect($vehicle_label . ' as vehicle_label')
->addSelect('c.first_name as cust_first_name')
->addSelect('c.last_name as cust_last_name');
*/
// add filters if needed
if (!empty($term)) {
$query->where('q.plate_number like :search')
->setParameter('search', $term . '%');
/*
$query->where('match_against (q.plate_number, :search \'in boolean mode\') > 0.1')
->setParameter('search', $term . '*');
*/
/*
$query->where('q.plate_number LIKE :filter')
->setParameter('filter', '%' . $term . '%');
*/
}
// get rows
$query_obj = $query->orderBy('q.plate_number', 'asc')
->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery();
// error_log($query_obj->getSql());
$obj_rows = $query_obj->getResult();
// build vehicles array
$vehicles = [];
foreach ($obj_rows as $cv) {
$cust = $cv->getCustomer();
$vehicles[] = [
'id' => $cv->getID(),
'text' => $cv->getPlateNumber() . ' ' . $cust->getFirstName() . ' ' . $cust->getLastName() . ' ('. $this->country_code . $cust->getPhoneMobile() . ')',
];
}
$results = [
'vehicles' => $vehicles,
'has_more_pages' => $has_more_pages,
];
return $results;
}
// get customer vehicle info
public function getCustomerVehicleInfo(Request $req)
{
// get id
$id = $req->query->get('id');
// get row data
$em = $this->em;
$obj = $em->getRepository(CustomerVehicle::class)->find($id);
// make sure this row exists
if (empty($obj)) {
return null;
}
$customer = $obj->getCustomer();
$vehicle = $obj->getVehicle();
$battery = $obj->getCurrentBattery();
// build response
$row = [
'customer' => [
'id' => $customer->getID(),
'first_name' => $customer->getFirstName(),
'last_name' => $customer->getLastName(),
'customer_notes' => $customer->getCustomerNotes(),
'phone_mobile' => $customer->getPhoneMobile(),
'phone_landline' => $customer->getPhoneLandline(),
'phone_office' => $customer->getPhoneOffice(),
'phone_fax' => $customer->getPhoneFax(),
],
'vehicle' => [
'id' => $vehicle->getID(),
'mfg_id' => $vehicle->getManufacturer()->getID(),
'mfg_name' => $vehicle->getManufacturer()->getName(),
'make' => $vehicle->getMake(),
'model_year_from' => $vehicle->getModelYearFrom(),
'model_year_to' => $vehicle->getModelYearTo(),
'model_year' => $obj->getModelYear(),
'color' => $obj->getColor(),
'plate_number' => $obj->getPlateNumber(),
]
];
if (!empty($battery)) {
$row['battery'] = [
'id' => $battery->getID(),
'mfg_name' => $battery->getManufacturer()->getName(),
'model_name' => $battery->getModel()->getName(),
'size_name' => $battery->getSize()->getName(),
'prod_code' => $battery->getProductCode(),
'warranty_code' => $obj->getWarrantyCode(),
'warranty_expiration' => $obj->getWarrantyExpiration() ? $obj->getWarrantyExpiration()->format("d M Y") : "",
'has_motolite_battery' => $obj->hasMotoliteBattery(),
'is_active' => $obj->isActive()
];
}
return $row;
}
protected function getTwigTemplate($id)
{
if (isset($this->template_hash[$id]))
{
return $this->template_hash[$id];
}
return null;
}
protected function setObject($obj, $req)
{
// set and save values
$obj->setTitle($req->request->get('title'))
->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setCustomerClassification($req->request->get('customer_classification'))
->setCustomerNotes($req->request->get('customer_notes'))
->setEmail($req->request->get('email'))
->setIsCSAT($req->request->get('flag_csat') ? true : false)
->setActive($req->request->get('flag_active') ? true : false);
// phone numbers
$obj->setPhoneMobile($req->request->get('phone_mobile'))
->setPhoneLandline($req->request->get('phone_landline'))
->setPhoneOffice($req->request->get('phone_office'))
->setPhoneFax($req->request->get('phone_fax'));
}
protected function fillDropdownParameters(&$params)
{
$em = $this->em;
$params['bmfgs'] = $em->getRepository(BatteryManufacturer::class)->findAll();
$params['vmfgs'] = $em->getRepository(VehicleManufacturer::class)->findAll();
$params['classifications'] = CustomerClassification::getCollection();
$params['years'] = $this->generateYearOptions();
$params['batteries'] = $em->getRepository(Battery::class)->findAll();
}
protected function generateYearOptions()
{
$start_year = 1950;
return range($start_year, date("Y") + 1);
}
protected function loadTemplates()
{
$this->template_hash = [];
// add all twig templates for customer to hash
$this->template_hash['cust_add_form'] = 'customer/cmb.form.html.twig';
$this->template_hash['cust_update_form'] = 'customer/cmb.form.html.twig';
$this->template_hash['cust_list'] = 'customer/list.html.twig';
}
protected function updateVehicles($em, Customer $cust, $vehicles)
{
$vehicle_ids = [];
foreach ($vehicles as $vehicle)
{
// check if customer vehicle exists
if (!empty($vehicle->id))
{
$cust_vehicle = $em->getRepository(CustomerVehicle::class)->find($vehicle->id);
if ($cust_vehicle == null)
throw new CrudException("Could not find customer vehicle.");
}
// this is a new vehicle
else
{
$cust_vehicle = new CustomerVehicle();
$cust_vehicle->setCustomer($cust);
$cust->addVehicle($cust_vehicle);
$em->persist($cust_vehicle);
}
// vehicle, because they could have changed vehicle type
$vobj = $em->getRepository(Vehicle::class)->find($vehicle->vehicle);
if ($vobj == null)
throw new CrudException("Could not find vehicle.");
// TODO: validate details
$cust_vehicle->setName($vehicle->name)
->setVehicle($vobj)
->setPlateNumber($vehicle->plate_number)
->setModelYear($vehicle->model_year)
->setColor('')
->setStatusCondition('')
->setFuelType('')
->setActive($vehicle->flag_active);
// if specified, check if battery exists
if ($vehicle->battery)
{
// check if battery exists
$bobj = $em->getRepository(Battery::class)->find($vehicle->battery);
if ($bobj == null)
throw new CrudException("Could not find battery.");
// check if warranty expiration was specified
$warr_ex = DateTime::createFromFormat("d M Y", $vehicle->warranty_expiration);
if (!$warr_ex)
$warr_ex = null;
$cust_vehicle->setHasMotoliteBattery(true)
->setCurrentBattery($bobj)
->setWarrantyCode($vehicle->warranty_code)
->setWarrantyExpiration($warr_ex);
}
else
{
$cust_vehicle->setHasMotoliteBattery(false);
}
// add to list of vehicles to keep
$vehicle_ids[$cust_vehicle->getID()] = true;
}
// cleanup
// delete all vehicles not in list
$cvs = $cust->getVehicles();
foreach ($cvs as $cv)
{
if (!isset($vehicle_ids[$cv->getID()]))
{
$cust->removeVehicle($cv);
$em->remove($cv);
}
}
}
// check if datatable filter is present and append to query
protected function setQueryFilters($datatable, &$query) {
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->join('q.vehicles', 'cv')
->where('q.first_name LIKE :filter')
->orWhere('q.last_name LIKE :filter')
->orWhere('q.customer_classification LIKE :filter')
->orWhere('cv.plate_number LIKE :filter')
->setParameter('filter', $datatable['query']['data-rows-search'] . '%');
}
}
}

View file

@ -0,0 +1,707 @@
<?php
namespace App\Service\CustomerHandler;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use App\Service\CustomerHandlerInterface;
use App\Ramcar\CustomerClassification;
use App\Ramcar\FuelType;
use App\Ramcar\VehicleStatusCondition;
use App\Ramcar\CrudException;
use App\Entity\Customer;
use App\Entity\CustomerVehicle;
use App\Entity\Vehicle;
use App\Entity\Battery;
use App\Entity\VehicleManufacturer;
use App\Entity\BatteryManufacturer;
use DateTime;
class ResqCustomerHandler implements CustomerHandlerInterface
{
protected $em;
protected $validator;
protected $country_code;
protected $template_hash;
public function __construct(EntityManagerInterface $em, ValidatorInterface $validator,
string $country_code)
{
$this->em = $em;
$this->validator = $validator;
$this->country_code = $country_code;
$this->loadTemplates();
}
// initialize form to display customer list
public function initializeCustomerIndexForm()
{
$params['template'] = $this->getTwigTemplate('cust_list');
return $params;
}
// get customers
public function getCustomers(Request $req)
{
// build query
$tqb = $this->em->getRepository(Customer::class)
->createQueryBuilder('q');
$qb = $this->em->getRepository(Customer::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $tqb->select('COUNT(q)');
// add filters to count query
$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');
// add filters to query
$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.first_name', '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['title'] = $orow->getTitle();
$row['first_name'] = $orow->getFirstName();
$row['last_name'] = $orow->getLastName();
$row['customer_classification'] = CustomerClassification::getName($orow->getCustomerClassification());
$row['flag_mobile_app'] = $orow->hasMobileApp();
$row['app_mobile_number'] = $orow->hasMobileApp() && !empty($orow->getMobileSessions()) ? $orow->getMobileSessions()[0]->getPhoneNumber() : '';
$row['flag_active'] = $orow->isActive();
$row['flag_csat'] = $orow->isCSAT();
// TODO: properly add mobile numbers and plate numbers as searchable/sortable fields, use doctrine events
// prepend the country code before each mobile number
$mobile_number_list = [];
$mobile_numbers = $orow->getMobileNumberList();
foreach ($mobile_numbers as $mobile_number)
{
$mobile_number_list[] = $this->country_code . $mobile_number;
}
$row['mobile_numbers'] = implode("<br>", $mobile_number_list);
$row['plate_numbers'] = implode("<br>", $orow->getPlateNumberList());
$rows[] = $row;
}
$params['meta'] = $meta;
$params['rows'] = $rows;
return $params;
}
// initialize add customer form
public function initializeAddCustomerForm()
{
$params['obj'] = new Customer();
$params['mode'] = 'create';
// get dropdown parameters
$this->fillDropdownParameters($params);
// get template to display
$params['template'] = $this->getTwigTemplate('cust_add_form');
// return params
return $params;
}
// add new customer and customer vehicle, if any
public function addCustomer(Request $req)
{
// create new row
$em = $this->em;
$row = new Customer();
$this->setObject($row, $req);
// initialize error lists
$error_array = [];
$nerror_array = [];
$verror_array = [];
// custom validation for vehicles
$vehicles = json_decode($req->request->get('vehicles'));
if (!empty($vehicles))
{
foreach ($vehicles as $vehicle)
{
// check if vehicle exists
$vobj = $em->getRepository(Vehicle::class)->find($vehicle->vehicle);
if (empty($vobj))
{
$verror_array[$vehicle->index]['vehicle'] = 'Invalid vehicle specified.';
}
else
{
$cust_vehicle = new CustomerVehicle();
$cust_vehicle->setName($vehicle->name)
->setVehicle($vobj)
->setPlateNumber($vehicle->plate_number)
->setModelYear($vehicle->model_year)
->setColor($vehicle->color)
->setStatusCondition($vehicle->status_condition)
->setFuelType($vehicle->fuel_type)
->setActive($vehicle->flag_active)
->setCustomer($row);
// if specified, check if battery exists
if ($vehicle->battery)
{
// check if battery exists
$bobj = $em->getRepository(Battery::class)->find($vehicle->battery);
if (empty($bobj))
{
$verror_array[$vehicle->index]['battery'] = 'Invalid battery specified.';
}
else
{
// check if warranty expiration was specified
$warr_ex = DateTime::createFromFormat("d M Y", $vehicle->warranty_expiration);
if (!$warr_ex)
$warr_ex = null;
$cust_vehicle->setHasMotoliteBattery(true)
->setCurrentBattery($bobj)
->setWarrantyCode($vehicle->warranty_code)
->setWarrantyExpiration($warr_ex);
}
}
else
{
$cust_vehicle->setHasMotoliteBattery(false);
}
$verrors = $this->validator->validate($cust_vehicle);
// add errors to list
foreach ($verrors as $error)
{
if (!isset($verror_array[$vehicle->index]))
$verror_array[$vehicle->index] = [];
$verror_array[$vehicle->index][$error->getPropertyPath()] = $error->getMessage();
}
// add to entity
if (!isset($verror_array[$vehicle->index]))
{
$row->addVehicle($cust_vehicle);
}
}
}
}
// validate
$errors = $this->validator->validate($row);
// add errors to list
foreach ($errors as $error)
{
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
$result = [];
if (!empty($error_array) || !empty($nerror_array) || !empty($verror_array))
{
// return all error_arrays
$result = [
'error_array' => $error_array,
'nerror_array' => $nerror_array,
'verror_array' => $verror_array,
];
}
else
{
// validated! save the entity
$em->persist($row);
$em->flush();
$result = [
'id' => $row->getID(),
];
}
return $result;
}
// initialize update customer form
public function initializeUpdateCustomerForm($id)
{
$params['mode'] = 'update';
// get row data
$em = $this->em;
$row = $em->getRepository(Customer::class)->find($id);
// make sure this row exists
if (empty($row))
throw new NotFoundHttpException('The item does not exist');
// get dropdown parameters
$this->fillDropdownParameters($params);
// get template to display
$params['template'] = $this->getTwigTemplate('cust_update_form');
$params['obj'] = $row;
return $params;
}
// update customer and customer vehicle
public function updateCustomer(Request $req, $id)
{
// get row data
$em = $this->em;
$cust = $em->getRepository(Customer::class)->find($id);
// make sure this row exists
if (empty($cust))
throw $this->createNotFoundException('The item does not exist');
$this->setObject($cust, $req);
// initialize error lists
$error_array = [];
$nerror_array = [];
$verror_array = [];
// TODO: validate mobile numbers
// TODO: validate vehicles
// custom validation for vehicles
$vehicles = json_decode($req->request->get('vehicles'));
$this->updateVehicles($em, $cust, $vehicles);
// validate
$errors = $this->validator->validate($cust);
// add errors to list
foreach ($errors as $error)
{
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
$result = [];
if (!empty($error_array) || !empty($nerror_array) || !empty($verror_array))
{
// return all error_arrays
$result = [
'error_array' => $error_array,
'nerror_array' => $nerror_array,
'verror_array' => $verror_array,
];
}
else
{
// validated! save the entity. do a persist anyway to save child entities
$em->persist($cust);
$em->flush();
$result = [
'id' => $cust->getID(),
];
}
return $result;
}
// delete customer
public function deleteCustomer(int $id)
{
// get row data
$em = $this->em;
$row = $em->getRepository(Customer::class)->find($id);
if (empty($row))
throw new NotFoundHttpException('The item does not exist');
// delete this row
$em->remove($row);
$em->flush();
}
// get customer vehicles
public function getCustomerVehicles(Request $req)
{
// get search term
$term = $req->query->get('search');
// get querybuilder
$qb = $this->em
->getRepository(CustomerVehicle::class)
->createQueryBuilder('q');
/*
// build expression now since we're reusing it
$vehicle_label = $qb->expr()->concat(
'q.plate_number',
$qb->expr()->literal(' - '),
'c.first_name',
$qb->expr()->literal(' '),
'c.last_name',
$qb->expr()->literal(' (+63'),
'c.phone_mobile',
$qb->expr()->literal(')')
);
*/
// count total records
$tquery = $qb->select('COUNT(q)');
// add filters to count query
if (!empty($term)) {
$tquery->where('q.plate_number like :search')
->setParameter('search', $term . '%');
/*
$tquery->where('match_against (q.plate_number, :search \'in boolean mode\') > 0.1')
->setParameter('search', $term . '*');
*/
/*
$tquery->where('q.plate_number LIKE :filter')
->setParameter('filter', '%' . $term . '%');
*/
}
$total = $tquery->getQuery()
->getSingleScalarResult();
// pagination vars
$page = $req->query->get('page') ?? 1;
$perpage = 20;
$offset = ($page - 1) * $perpage;
$pages = ceil($total / $perpage);
$has_more_pages = $page < $pages ? true : false;
// build main query
$query = $qb->select('q');
/*
->addSelect($vehicle_label . ' as vehicle_label')
->addSelect('c.first_name as cust_first_name')
->addSelect('c.last_name as cust_last_name');
*/
// add filters if needed
if (!empty($term)) {
$query->where('q.plate_number like :search')
->setParameter('search', $term . '%');
/*
$query->where('match_against (q.plate_number, :search \'in boolean mode\') > 0.1')
->setParameter('search', $term . '*');
*/
/*
$query->where('q.plate_number LIKE :filter')
->setParameter('filter', '%' . $term . '%');
*/
}
// get rows
$query_obj = $query->orderBy('q.plate_number', 'asc')
->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery();
// error_log($query_obj->getSql());
$obj_rows = $query_obj->getResult();
// build vehicles array
$vehicles = [];
foreach ($obj_rows as $cv) {
$cust = $cv->getCustomer();
$vehicles[] = [
'id' => $cv->getID(),
'text' => $cv->getPlateNumber() . ' ' . $cust->getFirstName() . ' ' . $cust->getLastName() . ' ('. $this->country_code . $cust->getPhoneMobile() . ')',
];
}
$results = [
'vehicles' => $vehicles,
'has_more_pages' => $has_more_pages,
];
return $results;
}
// get customer vehicle info
public function getCustomerVehicleInfo(Request $req)
{
// get id
$id = $req->query->get('id');
// get row data
$em = $this->em;
$obj = $em->getRepository(CustomerVehicle::class)->find($id);
// make sure this row exists
if (empty($obj)) {
return null;
}
$customer = $obj->getCustomer();
$vehicle = $obj->getVehicle();
$battery = $obj->getCurrentBattery();
// build response
$row = [
'customer' => [
'id' => $customer->getID(),
'first_name' => $customer->getFirstName(),
'last_name' => $customer->getLastName(),
'customer_notes' => $customer->getCustomerNotes(),
'phone_mobile' => $customer->getPhoneMobile(),
'phone_landline' => $customer->getPhoneLandline(),
'phone_office' => $customer->getPhoneOffice(),
'phone_fax' => $customer->getPhoneFax(),
'email' => $customer->getEmail(),
'flag_dpa_consent' => $customer->isDpaConsent(),
'flag_promo_sms' => $customer->isPromoSms(),
'flag_promo_email' => $customer->isPromoEmail(),
],
'vehicle' => [
'id' => $vehicle->getID(),
'mfg_name' => $vehicle->getManufacturer()->getName(),
'make' => $vehicle->getMake(),
'model_year_from' => $vehicle->getModelYearFrom(),
'model_year_to' => $vehicle->getModelYearTo(),
'model_year' => $obj->getModelYear(),
'color' => $obj->getColor(),
'plate_number' => $obj->getPlateNumber(),
'fuel_type' => $obj->getFuelType(),
'status_condition' => $obj->getStatusCondition(),
]
];
if (!empty($battery)) {
$row['battery'] = [
'id' => $battery->getID(),
'mfg_name' => $battery->getManufacturer()->getName(),
'model_name' => $battery->getModel()->getName(),
'size_name' => $battery->getSize()->getName(),
'prod_code' => $battery->getProductCode(),
'warranty_code' => $obj->getWarrantyCode(),
'warranty_expiration' => $obj->getWarrantyExpiration() ? $obj->getWarrantyExpiration()->format("d M Y") : "",
'has_motolite_battery' => $obj->hasMotoliteBattery(),
'is_active' => $obj->isActive()
];
}
return $row;
}
protected function getTwigTemplate($id)
{
if (isset($this->template_hash[$id]))
{
return $this->template_hash[$id];
}
return null;
}
protected function setObject($obj, $req)
{
// set and save values
$obj->setTitle($req->request->get('title'))
->setFirstName($req->request->get('first_name'))
->setLastName($req->request->get('last_name'))
->setCustomerClassification($req->request->get('customer_classification'))
->setCustomerNotes($req->request->get('customer_notes'))
->setEmail($req->request->get('email'))
->setIsCSAT($req->request->get('flag_csat') ? true : false)
->setActive($req->request->get('flag_active') ? true : false)
->setPromoSms($req->request->get('flag_promo_sms', false))
->setPromoEmail($req->request->get('flag_promo_email', false))
->setDpaConsent($req->request->get('flag_dpa_consent', false));
// phone numbers
$obj->setPhoneMobile($req->request->get('phone_mobile'))
->setPhoneLandline($req->request->get('phone_landline'))
->setPhoneOffice($req->request->get('phone_office'))
->setPhoneFax($req->request->get('phone_fax'));
}
protected function fillDropdownParameters(&$params)
{
$em = $this->em;
$params['bmfgs'] = $em->getRepository(BatteryManufacturer::class)->findAll();
$params['vmfgs'] = $em->getRepository(VehicleManufacturer::class)->findAll();
$params['classifications'] = CustomerClassification::getCollection();
$params['fuel_types'] = FuelType::getCollection();
$params['status_conditions'] = VehicleStatusCondition::getCollection();
$params['years'] = $this->generateYearOptions();
$params['batteries'] = $em->getRepository(Battery::class)->findAll();
}
protected function generateYearOptions()
{
$start_year = 1950;
return range($start_year, date("Y") + 1);
}
protected function loadTemplates()
{
$this->template_hash = [];
// add all twig templates for customer to hash
$this->template_hash['cust_add_form'] = 'customer/form.html.twig';
$this->template_hash['cust_update_form'] = 'customer/form.html.twig';
$this->template_hash['cust_list'] = 'customer/list.html.twig';
}
protected function updateVehicles($em, Customer $cust, $vehicles)
{
$vehicle_ids = [];
foreach ($vehicles as $vehicle)
{
// check if customer vehicle exists
if (!empty($vehicle->id))
{
$cust_vehicle = $em->getRepository(CustomerVehicle::class)->find($vehicle->id);
if ($cust_vehicle == null)
throw new CrudException("Could not find customer vehicle.");
}
// this is a new vehicle
else
{
$cust_vehicle = new CustomerVehicle();
$cust_vehicle->setCustomer($cust);
$cust->addVehicle($cust_vehicle);
$em->persist($cust_vehicle);
}
// vehicle, because they could have changed vehicle type
$vobj = $em->getRepository(Vehicle::class)->find($vehicle->vehicle);
if ($vobj == null)
throw new CrudException("Could not find vehicle.");
// TODO: validate details
$cust_vehicle->setName($vehicle->name)
->setVehicle($vobj)
->setPlateNumber($vehicle->plate_number)
->setModelYear($vehicle->model_year)
->setColor($vehicle->color)
->setStatusCondition($vehicle->status_condition)
->setFuelType($vehicle->fuel_type)
->setActive($vehicle->flag_active);
// if specified, check if battery exists
if ($vehicle->battery)
{
// check if battery exists
$bobj = $em->getRepository(Battery::class)->find($vehicle->battery);
if ($bobj == null)
throw new CrudException("Could not find battery.");
// check if warranty expiration was specified
$warr_ex = DateTime::createFromFormat("d M Y", $vehicle->warranty_expiration);
if (!$warr_ex)
$warr_ex = null;
$cust_vehicle->setHasMotoliteBattery(true)
->setCurrentBattery($bobj)
->setWarrantyCode($vehicle->warranty_code)
->setWarrantyExpiration($warr_ex);
}
else
{
$cust_vehicle->setHasMotoliteBattery(false);
}
// add to list of vehicles to keep
$vehicle_ids[$cust_vehicle->getID()] = true;
}
// cleanup
// delete all vehicles not in list
$cvs = $cust->getVehicles();
foreach ($cvs as $cv)
{
if (!isset($vehicle_ids[$cv->getID()]))
{
$cust->removeVehicle($cv);
$em->remove($cv);
}
}
}
// check if datatable filter is present and append to query
protected function setQueryFilters($datatable, &$query) {
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->join('q.vehicles', 'cv')
->where('q.first_name LIKE :filter')
->orWhere('q.last_name LIKE :filter')
->orWhere('q.customer_classification LIKE :filter')
->orWhere('cv.plate_number LIKE :filter')
->setParameter('filter', $datatable['query']['data-rows-search'] . '%');
}
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\Request;
interface CustomerHandlerInterface
{
// initialize form to display customer list
public function initializeCustomerIndexForm();
// get customers
public function getCustomers(Request $req);
// initialize add customer form
public function initializeAddCustomerForm();
// add new customer and customer vehicle, if any
public function addCustomer(Request $req);
// initialize update customer form
public function initializeUpdateCustomerForm(int $id);
// update customer and customer vehicle
public function updateCustomer(Request $req, int $id);
// delete customer
public function deleteCustomer(int $id);
// get customer vehicles
public function getCustomerVehicles(Request $req);
// get customer vehicle info
public function getCustomerVehicleInfo(Request $req);
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Service\GISManager;
use App\Service\GISManagerInterface;
class Bing implements GISManagerInterface
{
const JS_INIT_FILE = 'initBingMap.js';
public function getJSInitFile()
{
// return the bing map js file: initBingMap.js
return self::JS_INIT_FILE;
}
public function getJSJOFile()
{
}
}

View file

@ -0,0 +1,21 @@
<?php
namespace App\Service\GISManager;
use App\Service\GISManagerInterface;
class Google implements GISManagerInterface
{
const JS_INIT_FILE = 'initGoogleMap.js';
public function getJSInitFile()
{
// return the google map js file: initGoogleMap.js
return self::JS_INIT_FILE;
}
public function getJSJOFile()
{
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace App\Service\GISManager;
use App\Service\GISManagerInterface;
class OpenStreet implements GISManagerInterface
{
const JS_INIT_FILE = 'initOpenStreetMap.js';
const JS_JO_FILE = 'joOpenStreetMap.js';
public function getJSInitFile()
{
// return the openstreet map js file: initOpenStreetMap.js
return self::JS_INIT_FILE;
}
public function getJSJOFile()
{
return self::JS_JO_FILE;
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace App\Service;
interface GISManagerInterface
{
// returns the actual JS file
public function getJSInitFile();
// return the JS file for JO map
public function getJSJOFile();
}

View file

@ -0,0 +1,632 @@
<?php
namespace App\Service\InvoiceGenerator;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Doctrine\ORM\EntityManagerInterface;
use App\Ramcar\InvoiceCriteria;
use App\Ramcar\InvoiceStatus;
use App\Ramcar\CMBTradeInType;
use App\Ramcar\DiscountApply;
use App\Ramcar\CMBServiceType;
use App\Ramcar\FuelType;
use App\Entity\Invoice;
use App\Entity\InvoiceItem;
use App\Entity\Battery;
use App\Entity\Promo;
use App\Entity\User;
use App\Service\InvoiceGeneratorInterface;
use Doctrine\Common\Util\Debug;
class CMBInvoiceGenerator implements InvoiceGeneratorInterface
{
const TAX_RATE = 0.00;
const SERVICE_FEE = 300;
const RECHARGE_FEE = 300;
const TROUBLESHOOTING_FEE = 150;
const BATT_REPLACEMENT_FEE = 0;
const WARRANTY_FEE = 0;
const OTHER_SERVICES_FEE = 200;
const COOLANT_FEE = 1600;
const REFUEL_FEE_GAS = 260;
const REFUEL_FEE_DIESEL = 220;
private $security;
protected $em;
protected $validator;
// creates invoice based on the criteria sent
public function __construct(Security $security, EntityManagerInterface $em,
ValidatorInterface $validator)
{
$this->security = $security;
$this->em = $em;
$this->validator = $validator;
}
public function generateInvoice(InvoiceCriteria $criteria)
{
// initialize
$invoice = new Invoice();
$total = [
'sell_price' => 0.0,
'vat' => 0.0,
'vat_ex_price' => 0.0,
'ti_rate' => 0.0,
'total_price' => 0.0,
'discount' => 0.0,
];
$stype = $criteria->getServiceType();
$cv = $criteria->getCustomerVehicle();
$has_coolant = $criteria->hasCoolant();
switch ($stype)
{
case CMBServiceType::JUMPSTART:
$this->processJumpstart($total, $invoice);
break;
//case ServiceType::JUMPSTART_WARRANTY:
// $this->processJumpstartWarranty($total, $invoice);
case CMBServiceType::BATTERY_REPLACEMENT_NEW:
$this->processEntries($total, $criteria, $invoice);
/*
$this->processBatteries($total, $criteria, $invoice);
$this->processTradeIns($total, $criteria, $invoice);
*/
$this->processDiscount($total, $criteria, $invoice);
break;
case CMBServiceType::BATTERY_REPLACEMENT_WARRANTY:
$this->processWarranty($total, $criteria, $invoice);
break;
//case ServiceType::POST_RECHARGED:
// $this->processRecharge($total, $invoice);
// break;
//case ServiceType::POST_REPLACEMENT:
// $this->processReplacement($total, $invoice);
// break;
//case ServiceType::TIRE_REPAIR:
// $this->processTireRepair($total, $invoice, $cv);
// $this->processOtherServices($total, $invoice, $stype);
// break;
//case ServiceType::OVERHEAT_ASSISTANCE:
// $this->processOverheat($total, $invoice, $cv, $has_coolant);
// break;
//case ServiceType::EMERGENCY_REFUEL:
// error_log('processing refuel');
// $ftype = $criteria->getCustomerVehicle()->getFuelType();
// $this->processRefuel($total, $invoice, $cv);
// break;
}
// TODO: check if any promo is applied
// apply discounts
$promos = $criteria->getPromos();
// get current user
$user = $this->security->getUser();
if ($user != null)
{
$invoice->setCreatedBy($user);
}
$invoice->setTotalPrice($total['total_price'])
->setVATExclusivePrice($total['vat_ex_price'])
->setVAT($total['vat'])
->setDiscount($total['discount'])
->setTradeIn($total['ti_rate'])
->setStatus(InvoiceStatus::DRAFT);
// dump
//Debug::dump($invoice, 1);
return $invoice;
}
// generate invoice criteria
public function generateInvoiceCriteria($jo, $promo_id, $invoice_items, &$error_array)
{
$em = $this->em;
// instantiate the invoice criteria
$criteria = new InvoiceCriteria();
$criteria->setServiceType($jo->getServiceType())
->setCustomerVehicle($jo->getCustomerVehicle());
$ierror = $this->invoicePromo($criteria, $promo_id);
if (!$ierror && !empty($invoice_items))
{
// check for trade-in so we can mark it for mobile app
foreach ($invoice_items as $item)
{
// get first trade-in
if (!empty($item['trade_in']))
{
$jo->getTradeInType($item['trade_in']);
break;
}
}
$ierror = $this->invoiceBatteries($criteria, $invoice_items);
}
if ($ierror)
{
$error_array['invoice'] = $ierror;
}
else
{
// generate the invoice
$iobj = $this->generateInvoice($criteria);
// validate
$ierrors = $this->validator->validate($iobj);
// add errors to list
foreach ($ierrors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if invoice already exists for JO
$old_invoice = $jo->getInvoice();
if ($old_invoice != null)
{
// remove old invoice
$em->remove($old_invoice);
$em->flush();
}
// add invoice to JO
$jo->setInvoice($iobj);
$em->persist($iobj);
}
}
protected function getTaxAmount($price)
{
$vat_ex_price = $this->getTaxExclusivePrice($price);
return $price - $vat_ex_price;
// return round($vat_ex_price * self::TAX_RATE, 2);
}
protected function getTaxExclusivePrice($price)
{
return round($price / (1 + self::TAX_RATE), 2);
}
protected function getTradeInRate($ti)
{
$size = $ti['size'];
$trade_in = $ti['trade_in'];
if ($trade_in == null)
return 0;
switch ($trade_in)
{
// TODO: for now, tradein uses getTIPriceMotolite.
// Might need to modify later
case CMBTradeInType::YES:
return $size->getTIPriceMotolite();
}
return 0;
}
public function invoicePromo(InvoiceCriteria $criteria, $promo_id)
{
// return error if there's a problem, false otherwise
// check service type
$stype = $criteria->getServiceType();
if ($stype != CMBServiceType::BATTERY_REPLACEMENT_NEW)
return null;
if (empty($promo_id))
{
return false;
}
// check if this is a valid promo
$promo = $this->em->getRepository(Promo::class)->find($promo_id);
if (empty($promo))
return 'Invalid promo specified.';
$criteria->addPromo($promo);
return false;
}
public function invoiceBatteries(InvoiceCriteria $criteria, $items)
{
// check service type
$stype = $criteria->getServiceType();
if ($stype != CMBServiceType::BATTERY_REPLACEMENT_NEW && $stype != CMBServiceType::BATTERY_REPLACEMENT_WARRANTY)
return null;
// return error if there's a problem, false otherwise
if (!empty($items))
{
foreach ($items as $item)
{
// check if this is a valid battery
$battery = $this->em->getRepository(Battery::class)->find($item['battery']);
if (empty($battery))
{
$error = 'Invalid battery specified.';
return $error;
}
// quantity
$qty = $item['quantity'];
if ($qty < 1)
continue;
/*
// add to criteria
$criteria->addBattery($battery, $qty);
*/
// if this is a trade in, add trade in
if (!empty($item['trade_in']) && CMBTradeInType::validate($item['trade_in']))
$trade_in = $item['trade_in'];
else
$trade_in = null;
$criteria->addEntry($battery, $trade_in, $qty);
}
}
return null;
}
protected function processEntries(&$total, InvoiceCriteria $criteria, Invoice $invoice)
{
// error_log('processing entries...');
$entries = $criteria->getEntries();
$con_batts = [];
$con_tis = [];
foreach ($entries as $entry)
{
$batt = $entry['battery'];
$qty = $entry['qty'];
$trade_in = $entry['trade_in'];
$size = $batt->getSize();
// consolidate batteries
$batt_id = $batt->getID();
if (!isset($con_batts[$batt_id]))
$con_batts[$batt->getID()] = [
'batt' => $batt,
'qty' => 0
];
$con_batts[$batt_id]['qty']++;
// no trade-in
if ($trade_in == null)
continue;
// consolidate trade-ins
$ti_key = $size->getID() . '|' . $trade_in;
if (!isset($con_tis[$ti_key]))
$con_tis[$ti_key] = [
'size' => $size,
'trade_in' => $trade_in,
'qty' => 0
];
$con_tis[$ti_key]['qty']++;
}
$this->processBatteries($total, $con_batts, $invoice);
$this->processTradeIns($total, $con_tis, $invoice);
}
protected function processBatteries(&$total, $con_batts, Invoice $invoice)
{
// process batteries
foreach ($con_batts as $con_data)
{
$batt = $con_data['batt'];
$qty = $con_data['qty'];
$sell_price = $batt->getSellingPrice();
$vat = $this->getTaxAmount($sell_price);
// $vat_ex_price = $this->getTaxExclusivePrice($sell_price);
$total['sell_price'] += $sell_price * $qty;
$total['vat'] += $vat * $qty;
$total['vat_ex_price'] += ($sell_price - $vat) * $qty;
$total['total_price'] += $sell_price * $qty;
// add item
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle($batt->getModel()->getName() . ' ' . $batt->getSize()->getName())
->setQuantity($qty)
->setPrice($sell_price)
->setBattery($batt);
$invoice->addItem($item);
}
}
protected function processTradeIns(&$total, $con_tis, Invoice $invoice)
{
foreach ($con_tis as $ti)
{
$qty = $ti['qty'];
$ti_rate = $this->getTradeInRate($ti);
$total['ti_rate'] += $ti_rate * $qty;
$total['total_price'] -= $ti_rate * $qty;
// add item
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Trade-in ' . CMBTradeInType::getName($ti['trade_in']) . ' ' . $ti['size']->getName() . ' battery')
->setQuantity($qty)
->setPrice($ti_rate * -1);
$invoice->addItem($item);
}
}
protected function processDiscount(&$total, InvoiceCriteria $criteria, Invoice $invoice)
{
$promos = $criteria->getPromos();
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:
$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);
}
protected function processJumpstart(&$total, $invoice)
{
// add troubleshooting fee
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Troubleshooting fee')
->setQuantity(1)
->setPrice(self::TROUBLESHOOTING_FEE);
$invoice->addItem($item);
$total['sell_price'] = self::TROUBLESHOOTING_FEE;
$total['vat_ex_price'] = self::TROUBLESHOOTING_FEE;
$total['total_price'] = self::TROUBLESHOOTING_FEE;
}
protected function processJumpstartWarranty(&$total, $invoice)
{
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Troubleshooting fee')
->setQuantity(1)
->setPrice(0.00);
$invoice->addItem($item);
}
protected function processRecharge(&$total, $invoice)
{
// add recharge fee
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Recharge fee')
->setQuantity(1)
->setPrice(self::RECHARGE_FEE);
$invoice->addItem($item);
$total['sell_price'] = self::RECHARGE_FEE;
$total['vat_ex_price'] = self::RECHARGE_FEE;
$total['total_price'] = self::RECHARGE_FEE;
}
protected function processReplacement(&$total, $invoice)
{
// add recharge fee
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Battery replacement')
->setQuantity(1)
->setPrice(self::BATT_REPLACEMENT_FEE);
$invoice->addItem($item);
}
protected function processWarranty(&$total, InvoiceCriteria $criteria, $invoice)
{
// error_log('processing warranty');
$entries = $criteria->getEntries();
foreach ($entries as $entry)
{
$batt = $entry['battery'];
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle($batt->getModel()->getName() . ' ' . $batt->getSize()->getName() . ' - Service Unit')
->setQuantity(1)
->setPrice(self::WARRANTY_FEE)
->setBattery($batt);
$invoice->addItem($item);
}
}
protected function processOtherServices(&$total, $invoice, $stype)
{
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Service - ' . CMBServiceType::getName($stype))
->setQuantity(1)
->setPrice(self::OTHER_SERVICES_FEE);
$invoice->addItem($item);
$total['total_price'] = 200.00;
}
protected function processOverheat(&$total, $invoice, $cv, $has_coolant)
{
// free if they have a motolite battery
if ($cv->hasMotoliteBattery())
$fee = 0;
else
$fee = self::SERVICE_FEE;
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Service - Overheat Assistance')
->setQuantity(1)
->setPrice($fee);
$invoice->addItem($item);
$total_price = $fee;
if ($has_coolant)
{
$coolant = new InvoiceItem();
$coolant->setInvoice($invoice)
->setTitle('4L Coolant')
->setQuantity(1)
->setPrice(self::COOLANT_FEE);
$invoice->addItem($coolant);
$total_price += self::COOLANT_FEE;
//$total_price += 1600;
}
$vat_ex_price = $this->getTaxExclusivePrice($total_price);
$vat = $total_price - $vat_ex_price;
$total['total_price'] = $total_price;
$total['vat_ex_price'] = $vat_ex_price;
$total['vat'] = $vat;
}
protected function processTireRepair(&$total, $invoice, $cv)
{
// free if they have a motolite battery
if ($cv->hasMotoliteBattery())
$fee = 0;
else
$fee = self::SERVICE_FEE;
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Service - Flat Tire')
->setQuantity(1)
->setPrice($fee);
$invoice->addItem($item);
$total_price = $fee;
$vat_ex_price = $this->getTaxExclusivePrice($total_price);
$vat = $total_price - $vat_ex_price;
$total['total_price'] = $total_price;
$total['vat_ex_price'] = $vat_ex_price;
$total['vat'] = $vat;
}
protected function processRefuel(&$total, $invoice, $cv)
{
// free if they have a motolite battery
if ($cv->hasMotoliteBattery())
$fee = 0;
else
$fee = self::SERVICE_FEE;
$ftype = $cv->getFuelType();
$item = new InvoiceItem();
// service charge
$item->setInvoice($invoice)
->setTitle('Service - ' . CMBServiceType::getName(CMBServiceType::EMERGENCY_REFUEL))
->setQuantity(1)
->setPrice($fee);
$invoice->addItem($item);
$total_price = $fee;
// $total['total_price'] = 200.00;
$gas_price = self::REFUEL_FEE_GAS;
$diesel_price = self::REFUEL_FEE_DIESEL;
$fuel = new InvoiceItem();
error_log('fuel type - ' . $ftype);
switch ($ftype)
{
case FuelType::GAS:
$fuel->setInvoice($invoice)
->setTitle('4L Fuel - Gas')
->setQuantity(1)
->setPrice($gas_price);
$invoice->addItem($fuel);
$total_price += $gas_price;
break;
case FuelType::DIESEL:
$fuel->setInvoice($invoice)
->setTitle('4L Fuel - Diesel')
->setQuantity(1)
->setPrice($diesel_price);
$total_price += $diesel_price;
$invoice->addItem($fuel);
break;
default:
// NOTE: should never get to this point
$fuel->setInvoice($invoice)
->setTitle('Fuel - Unknown')
->setQuantity(1)
->setPrice(0);
$total_price += 0.00;
$invoice->addItem($fuel);
break;
}
$vat_ex_price = $this->getTaxExclusivePrice($total_price);
$vat = $total_price - $vat_ex_price;
$total['total_price'] = $total_price;
$total['vat_ex_price'] = $vat_ex_price;
$total['vat'] = $vat;
}
}

View file

@ -1,8 +1,14 @@
<?php
namespace App\Service;
namespace App\Service\InvoiceGenerator;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Doctrine\ORM\EntityManagerInterface;
use App\Ramcar\InvoiceCriteria;
use App\Ramcar\InvoiceStatus;
use App\Ramcar\TradeInType;
use App\Ramcar\DiscountApply;
use App\Ramcar\ServiceType;
@ -11,32 +17,195 @@ use App\Ramcar\FuelType;
use App\Entity\Invoice;
use App\Entity\InvoiceItem;
use App\Entity\User;
use App\Entity\Battery;
use App\Service\InvoiceGeneratorInterface;
use Doctrine\Common\Util\Debug;
class InvoiceCreator
class ResqInvoiceGenerator implements InvoiceGeneratorInterface
{
const VAT_RATE = 0.12;
const TAX_RATE = 0.12;
const SERVICE_FEE = 300;
const RECHARGE_FEE = 300;
const TROUBLESHOOTING_FEE = 150;
const BATT_REPLACEMENT_FEE = 0;
const WARRANTY_FEE = 0;
const OTHER_SERVICES_FEE = 200;
const COOLANT_FEE = 1600;
const REFUEL_FEE_GAS = 260;
const REFUEL_FEE_DIESEL = 220;
private $security;
protected $em;
protected $validator;
// creates invoice based on the criteria sent
public function __construct()
public function __construct(Security $security, EntityManagerInterface $em,
ValidatorInterface $validator)
{
$this->security = $security;
$this->em = $em;
$this->validator = $validator;
}
public function getVATAmount($price)
public function generateInvoice(InvoiceCriteria $criteria)
{
$vat_ex_price = $this->getVATExclusivePrice($price);
// initialize
$invoice = new Invoice();
$total = [
'sell_price' => 0.0,
'vat' => 0.0,
'vat_ex_price' => 0.0,
'ti_rate' => 0.0,
'total_price' => 0.0,
'discount' => 0.0,
];
$stype = $criteria->getServiceType();
$cv = $criteria->getCustomerVehicle();
$has_coolant = $criteria->hasCoolant();
// error_log($stype);
switch ($stype)
{
case ServiceType::JUMPSTART_TROUBLESHOOT:
$this->processJumpstart($total, $invoice);
break;
case ServiceType::JUMPSTART_WARRANTY:
$this->processJumpstartWarranty($total, $invoice);
case ServiceType::BATTERY_REPLACEMENT_NEW:
$this->processEntries($total, $criteria, $invoice);
/*
$this->processBatteries($total, $criteria, $invoice);
$this->processTradeIns($total, $criteria, $invoice);
*/
$this->processDiscount($total, $criteria, $invoice);
break;
case ServiceType::BATTERY_REPLACEMENT_WARRANTY:
$this->processWarranty($total, $criteria, $invoice);
break;
case ServiceType::POST_RECHARGED:
$this->processRecharge($total, $invoice);
break;
case ServiceType::POST_REPLACEMENT:
$this->processReplacement($total, $invoice);
break;
case ServiceType::TIRE_REPAIR:
$this->processTireRepair($total, $invoice, $cv);
// $this->processOtherServices($total, $invoice, $stype);
break;
case ServiceType::OVERHEAT_ASSISTANCE:
$this->processOverheat($total, $invoice, $cv, $has_coolant);
break;
case ServiceType::EMERGENCY_REFUEL:
error_log('processing refuel');
$ftype = $criteria->getCustomerVehicle()->getFuelType();
$this->processRefuel($total, $invoice, $cv);
break;
}
// TODO: check if any promo is applied
// apply discounts
$promos = $criteria->getPromos();
// get current user
$user = $this->security->getUser();
if ($user != null)
{
$invoice->setCreatedBy($user);
}
$invoice->setTotalPrice($total['total_price'])
->setVATExclusivePrice($total['vat_ex_price'])
->setVAT($total['vat'])
->setDiscount($total['discount'])
->setTradeIn($total['ti_rate'])
->setStatus(InvoiceStatus::DRAFT);
// dump
//Debug::dump($invoice, 1);
return $invoice;
}
// generate invoice criteria
public function generateInvoiceCriteria($jo, $promo_id, $invoice_items, &$error_array)
{
$em = $this->em;
// instantiate the invoice criteria
$criteria = new InvoiceCriteria();
$criteria->setServiceType($jo->getServiceType())
->setCustomerVehicle($jo->getCustomerVehicle());
$ierror = $this->invoicePromo($criteria, $promo_id);
if (!$ierror && !empty($invoice_items))
{
// check for trade-in so we can mark it for mobile app
foreach ($invoice_items as $item)
{
// get first trade-in
if (!empty($item['trade_in']))
{
$jo->getTradeInType($item['trade_in']);
break;
}
}
$ierror = $this->invoiceBatteries($criteria, $invoice_items);
}
if ($ierror)
{
$error_array['invoice'] = $ierror;
}
else
{
// generate the invoice
$iobj = $this->generateInvoice($criteria);
// validate
$ierrors = $this->validator->validate($iobj);
// add errors to list
foreach ($ierrors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if invoice already exists for JO
$old_invoice = $jo->getInvoice();
if ($old_invoice != null)
{
// remove old invoice
$em->remove($old_invoice);
$em->flush();
}
// add invoice to JO
$jo->setInvoice($iobj);
$em->persist($iobj);
}
}
protected function getTaxAmount($price)
{
$vat_ex_price = $this->getTaxExclusivePrice($price);
return $price - $vat_ex_price;
// return round($vat_ex_price * self::VAT_RATE, 2);
// return round($vat_ex_price * self::TAX_RATE, 2);
}
public function getVATExclusivePrice($price)
protected function getTaxExclusivePrice($price)
{
return round($price / (1 + self::VAT_RATE), 2);
return round($price / (1 + self::TAX_RATE), 2);
}
public function getTradeInRate($ti)
protected function getTradeInRate($ti)
{
$size = $ti['size'];
$trade_in = $ti['trade_in'];
@ -57,6 +226,75 @@ class InvoiceCreator
return 0;
}
public function invoicePromo(InvoiceCriteria $criteria, $promo_id)
{
// return error if there's a problem, false otherwise
// check service type
$stype = $criteria->getServiceType();
if ($stype != ServiceType::BATTERY_REPLACEMENT_NEW)
return null;
if (empty($promo_id))
{
return false;
}
// check if this is a valid promo
$promo = $this->em->getRepository(Promo::class)->find($promo_id);
if (empty($promo))
return 'Invalid promo specified.';
$criteria->addPromo($promo);
return false;
}
public function invoiceBatteries(InvoiceCriteria $criteria, $items)
{
// check service type
$stype = $criteria->getServiceType();
if ($stype != ServiceType::BATTERY_REPLACEMENT_NEW && $stype != ServiceType::BATTERY_REPLACEMENT_WARRANTY)
return null;
// return error if there's a problem, false otherwise
if (!empty($items))
{
foreach ($items as $item)
{
// check if this is a valid battery
$battery = $this->em->getRepository(Battery::class)->find($item['battery']);
if (empty($battery))
{
$error = 'Invalid battery specified.';
return $error;
}
// quantity
$qty = $item['quantity'];
if ($qty < 1)
continue;
/*
// add to criteria
$criteria->addBattery($battery, $qty);
*/
// if this is a trade in, add trade in
if (!empty($item['trade_in']) && TradeInType::validate($item['trade_in']))
$trade_in = $item['trade_in'];
else
$trade_in = null;
$criteria->addEntry($battery, $trade_in, $qty);
}
}
return null;
}
protected function processEntries(&$total, InvoiceCriteria $criteria, Invoice $invoice)
{
// error_log('processing entries...');
@ -109,8 +347,8 @@ class InvoiceCreator
$qty = $con_data['qty'];
$sell_price = $batt->getSellingPrice();
$vat = $this->getVATAmount($sell_price);
// $vat_ex_price = $this->getVATExclusivePrice($sell_price);
$vat = $this->getTaxAmount($sell_price);
// $vat_ex_price = $this->getTaxExclusivePrice($sell_price);
$total['sell_price'] += $sell_price * $qty;
$total['vat'] += $vat * $qty;
@ -192,22 +430,22 @@ class InvoiceCreator
$invoice->setPromo($promo);
}
public function processJumpstart(&$total, $invoice)
protected function processJumpstart(&$total, $invoice)
{
// add troubleshooting fee
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Troubleshooting fee')
->setQuantity(1)
->setPrice(150.00);
->setPrice(self::TROUBLESHOOTING_FEE);
$invoice->addItem($item);
$total['sell_price'] = 150.00;
$total['vat_ex_price'] = 150.00;
$total['total_price'] = 150.00;
$total['sell_price'] = self::TROUBLESHOOTING_FEE;
$total['vat_ex_price'] = self::TROUBLESHOOTING_FEE;
$total['total_price'] = self::TROUBLESHOOTING_FEE;
}
public function processJumpstartWarranty(&$total, $invoice)
protected function processJumpstartWarranty(&$total, $invoice)
{
$item = new InvoiceItem();
$item->setInvoice($invoice)
@ -217,33 +455,33 @@ class InvoiceCreator
$invoice->addItem($item);
}
public function processRecharge(&$total, $invoice)
protected function processRecharge(&$total, $invoice)
{
// add recharge fee
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Recharge fee')
->setQuantity(1)
->setPrice(300.00);
->setPrice(self::RECHARGE_FEE);
$invoice->addItem($item);
$total['sell_price'] = 300.00;
$total['vat_ex_price'] = 300.00;
$total['total_price'] = 300.00;
$total['sell_price'] = self::RECHARGE_FEE;
$total['vat_ex_price'] = self::RECHARGE_FEE;
$total['total_price'] = self::RECHARGE_FEE;
}
public function processReplacement(&$total, $invoice)
protected function processReplacement(&$total, $invoice)
{
// add recharge fee
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Battery replacement')
->setQuantity(1)
->setPrice(0.00);
->setPrice(self::BATT_REPLACEMENT_FEE);
$invoice->addItem($item);
}
public function processWarranty(&$total, InvoiceCriteria $criteria, $invoice)
protected function processWarranty(&$total, InvoiceCriteria $criteria, $invoice)
{
// error_log('processing warranty');
$entries = $criteria->getEntries();
@ -254,25 +492,25 @@ class InvoiceCreator
$item->setInvoice($invoice)
->setTitle($batt->getModel()->getName() . ' ' . $batt->getSize()->getName() . ' - Service Unit')
->setQuantity(1)
->setPrice(0.00)
->setPrice(self::WARRANTY_FEE)
->setBattery($batt);
$invoice->addItem($item);
}
}
public function processOtherServices(&$total, $invoice, $stype)
protected function processOtherServices(&$total, $invoice, $stype)
{
$item = new InvoiceItem();
$item->setInvoice($invoice)
->setTitle('Service - ' . ServiceType::getName($stype))
->setQuantity(1)
->setPrice(200.00);
->setPrice(self::OTHER_SERVICES_FEE);
$invoice->addItem($item);
$total['total_price'] = 200.00;
}
public function processOverheat(&$total, $invoice, $cv, $has_coolant)
protected function processOverheat(&$total, $invoice, $cv, $has_coolant)
{
// free if they have a motolite battery
if ($cv->hasMotoliteBattery())
@ -295,20 +533,21 @@ class InvoiceCreator
$coolant->setInvoice($invoice)
->setTitle('4L Coolant')
->setQuantity(1)
->setPrice(1600);
->setPrice(self::COOLANT_FEE);
$invoice->addItem($coolant);
$total_price += 1600;
$total_price += self::COOLANT_FEE;
//$total_price += 1600;
}
$vat_ex_price = $this->getVATExclusivePrice($total_price);
$vat_ex_price = $this->getTaxExclusivePrice($total_price);
$vat = $total_price - $vat_ex_price;
$total['total_price'] = $total_price;
$total['vat_ex_price'] = $vat_ex_price;
$total['vat'] = $vat;
}
public function processTireRepair(&$total, $invoice, $cv)
protected function processTireRepair(&$total, $invoice, $cv)
{
// free if they have a motolite battery
if ($cv->hasMotoliteBattery())
@ -324,14 +563,14 @@ class InvoiceCreator
$invoice->addItem($item);
$total_price = $fee;
$vat_ex_price = $this->getVATExclusivePrice($total_price);
$vat_ex_price = $this->getTaxExclusivePrice($total_price);
$vat = $total_price - $vat_ex_price;
$total['total_price'] = $total_price;
$total['vat_ex_price'] = $vat_ex_price;
$total['vat'] = $vat;
}
public function processRefuel(&$total, $invoice, $cv)
protected function processRefuel(&$total, $invoice, $cv)
{
// free if they have a motolite battery
if ($cv->hasMotoliteBattery())
@ -351,8 +590,8 @@ class InvoiceCreator
$total_price = $fee;
// $total['total_price'] = 200.00;
$gas_price = 260;
$diesel_price = 220;
$gas_price = self::REFUEL_FEE_GAS;
$diesel_price = self::REFUEL_FEE_DIESEL;
$fuel = new InvoiceItem();
//error_log('fuel type - ' . $ftype);
@ -385,7 +624,7 @@ class InvoiceCreator
break;
}
$vat_ex_price = $this->getVATExclusivePrice($total_price);
$vat_ex_price = $this->getTaxExclusivePrice($total_price);
$vat = $total_price - $vat_ex_price;
$total['total_price'] = $total_price;
$total['vat_ex_price'] = $vat_ex_price;

View file

@ -0,0 +1,18 @@
<?php
namespace App\Service;
use App\Entity\Invoice;
use App\Entity\JobOrder;
use App\Ramcar\InvoiceCriteria;
interface InvoiceGeneratorInterface
{
// generate invoice using a criteria
public function generateInvoice(InvoiceCriteria $criteria);
// generate invoice criteria
public function generateInvoiceCriteria(JobOrder $jo, int $promo_id, array $invoice_items, array &$error_array);
}

View file

@ -0,0 +1,66 @@
<?php
namespace App\Service;
use App\Service\RedisClientProvider;
use App\Entity\JobOrder;
class JobOrderCache
{
protected $redis;
protected $active_jo_key;
public function __construct(RedisClientProvider $redis_prov, $active_jo_key)
{
$this->redis = $redis_prov->getRedisClient();
$this->active_jo_key = $active_jo_key;
}
public function addActiveJobOrder(JobOrder $jo)
{
$coords = $jo->getCoordinates();
$this->redis->geoadd(
$this->active_jo_key,
$coords->getLongitude(),
$coords->getLatitude(),
$jo->getID()
);
}
public function getAllActiveJobOrders()
{
$all_jo = $this->redis->georadius(
$this->active_jo_key,
0,
0,
41000,
'km',
['WITHCOORD' => true]
);
$jo_locs = [];
foreach ($all_jo as $jo_data)
{
$id = $jo_data[0];
$lng = $jo_data[1][0];
$lat = $jo_data[1][1];
$jo_locs[$id] = [
'longitude' => $lng,
'latitude' => $lat,
];
}
// error_log(print_r($all_jo, true));
return $jo_locs;
}
public function removeActiveJobOrder(JobOrder $jo)
{
$this->redis->zrem(
$this->active_jo_key,
$jo->getID()
);
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,101 @@
<?php
namespace App\Service;
use Symfony\Component\HttpFoundation\Request;
use App\Service\MQTTClient;
use App\Service\APNSClient;
use App\Service\MapTools;
use App\Entity\JobOrder;
interface JobOrderHandlerInterface
{
// TODO: event sending has been moved to rider assignment handler for cmb. Might need
// to consider resq implementation for event sending for the other methods.
// get job order rows
public function getRows(Request $req, string $tier);
// get job orders
public function getJobOrders(Request $req);
// generate job order
public function generateJobOrder(Request $req, int $id);
// process one step job order
public function processOneStepJobOrder(Request $req, int $id);
// dispatch job order
public function dispatchJobOrder(Request $req, int $id, MQTTClient $mclient);
// assign job order
public function assignJobOrder(Request $req, int $id);
// fulfill job order
public function fulfillJobOrder(Request $req, int $id);
// cancel job order
public function cancelJobOrder(Request $req, int $id, MQTTClient $mclient);
// set hub for job order
public function setHub(Request $req, int $id, MQTTClient $mclient);
// reject hub for job order
public function rejectHub(Request $req, int $id);
// set rider for job order
public function setRider(Request $req, int $id, MQTTClient $mclient);
// unlock processor
public function unlockProcessor(int $id);
// unlock assignor
public function unlockAssignor(int $id);
// initialize incoming job order form
public function initializeIncomingForm();
// initialize open edit job order form
public function initializeOpenEditForm(int $id);
// initialize incoming vehicle form
public function initializeIncomingVehicleForm(int $cvid);
// initialize all job orders form for a specific job order id
public function initializeAllForm(int $id);
// initialize dispatch/processing job order form
public function initializeProcessingForm(int $id, MapTools $map_tools);
// initialize assign job order form
public function initializeAssignForm(int $id);
// initialize fulflll job order form
public function initializeFulfillmentForm(int $id);
// initialize hub form
public function initializeHubForm(int $id, MapTools $map_tools);
// initialize rider form
public function initializeRiderForm(int $id);
// initialize one step form
public function initializeOneStepForm();
// initialize one step edit form
public function initializeOneStepEditForm(int $id, MapTools $map_tools);
// generate pdf form for job order
public function generatePDFForm(Request $req, int $id, string $proj_path);
// get template to display
public function getTwigTemplate(string $id);
// update customer vehicle battery warranty info
public function updateVehicleBattery(JobOrder $jo);
// check if service type is new battery
public function checkIfNewBattery(JobOrder $jo);
}

View file

@ -45,6 +45,7 @@ class JobOrderManager
{
$new_battery = $item->getBattery();
$cust_vehicle->setCurrentBattery($new_battery);
$cust_vehicle->setHasMotoliteBattery(true);
}
$this->em->flush();

View file

@ -9,14 +9,15 @@ class MQTTClient
{
const PREFIX = 'motolite.control.';
const RIDER_PREFIX = 'motorider_';
const REDIS_KEY = 'events';
// protected $mclient;
protected $redis;
protected $key;
public function __construct(RedisClientProvider $redis_client)
public function __construct(RedisClientProvider $redis_client, $key)
{
$this->redis = $redis_client->getRedisClient();
$this->key = $key;
}
public function __destruct()
@ -29,7 +30,7 @@ class MQTTClient
// $this->mclient->publish($channel, $message);
$data = $channel . '|' . $message;
$this->redis->lpush(self::REDIS_KEY, $data);
$this->redis->lpush($this->key, $data);
}
public function sendEvent(JobOrder $job_order, $payload)

View file

@ -84,10 +84,23 @@ class MapTools
{
//error_log($row[0]->getName() . ' - ' . $row['dist']);
$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);
$final_data[] = [
'hub' => $row[0],
'db_distance' => $row['dist'],
'distance' => 0,
'distance' => $dist,
'duration' => 0,
];
}
@ -135,4 +148,18 @@ class MapTools
return $final_data;
*/
}
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);
}
}

Some files were not shown because too many files have changed in this diff Show more