Compare commits

..

No commits in common. "master" and "730-resq-2-0" have entirely different histories.

179 changed files with 785 additions and 15796 deletions

3
.gitignore vendored
View file

@ -12,6 +12,3 @@
*.swp
/public/warranty_uploads/*
.vscode
*__pycache__
/public/assets/images/insurance-premiums.png

View file

@ -17,10 +17,6 @@
{
"type": "vcs",
"url": "git@gitlab.com:jankstudio1/catalyst-2/menu-bundle.git"
},
{
"type": "vcs",
"url": "https://github.com/arcticzero/php-fcm.git"
}
],
"require": {
@ -32,7 +28,7 @@
"doctrine/doctrine-bundle": "^2",
"doctrine/doctrine-migrations-bundle": "^2",
"doctrine/orm": "^2",
"edwinhoksberg/php-fcm": "dev-notif-priority-hotfix",
"edwinhoksberg/php-fcm": "^1.0",
"guzzlehttp/guzzle": "^6.3",
"hashids/hashids": "^4.1",
"jankstudio/catalyst-api-bundle": "dev-master",

36
composer.lock generated
View file

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "653f8558c75614dd65421cb3eb48c29b",
"content-hash": "6e52016d46fa06387dbd9db37e6feb93",
"packages": [
{
"name": "composer/package-versions-deprecated",
@ -1772,26 +1772,26 @@
},
{
"name": "edwinhoksberg/php-fcm",
"version": "dev-notif-priority-hotfix",
"version": "v1.2.0",
"source": {
"type": "git",
"url": "https://github.com/ArcticZero/php-fcm.git",
"reference": "eabbfbc5df8df908ea7d13f0446202fda81e65fd"
"url": "https://github.com/EdwinHoksberg/php-fcm.git",
"reference": "660bbe4ae71e02090f16b11b4a993dfebab83f7f"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/ArcticZero/php-fcm/zipball/eabbfbc5df8df908ea7d13f0446202fda81e65fd",
"reference": "eabbfbc5df8df908ea7d13f0446202fda81e65fd",
"url": "https://api.github.com/repos/EdwinHoksberg/php-fcm/zipball/660bbe4ae71e02090f16b11b4a993dfebab83f7f",
"reference": "660bbe4ae71e02090f16b11b4a993dfebab83f7f",
"shasum": ""
},
"require": {
"guzzlehttp/guzzle": "^6.3 || ^7.0",
"php": ">= 7.3"
"php": ">= 7.2"
},
"require-dev": {
"mockery/mockery": "^1.5",
"php-coveralls/php-coveralls": "^2.5",
"phpunit/phpunit": "^9.5"
"mockery/mockery": "^1.0",
"php-coveralls/php-coveralls": "^2.3",
"phpunit/phpunit": "^6.5"
},
"type": "library",
"autoload": {
@ -1799,11 +1799,7 @@
"Fcm\\": "src/"
}
},
"scripts": {
"test": [
"XDEBUG_MODE=coverage vendor/bin/phpunit -c phpunit.dist.xml"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
@ -1816,16 +1812,17 @@
"description": "A library for sending Firebase cloud messages and managing user topic subscriptions, device groups and devices.",
"homepage": "https://github.com/EdwinHoksberg/php-fcm",
"keywords": [
"fcm",
"FCM",
"Firebase Cloud Messaging",
"firebase",
"firebase cloud messaging",
"google",
"notifications"
],
"support": {
"source": "https://github.com/ArcticZero/php-fcm/tree/master"
"issues": "https://github.com/EdwinHoksberg/php-fcm/issues",
"source": "https://github.com/EdwinHoksberg/php-fcm/tree/v1.2.0"
},
"time": "2023-07-19T09:04:27+00:00"
"time": "2021-01-19T01:15:30+00:00"
},
{
"name": "friendsofphp/proxy-manager-lts",
@ -7956,7 +7953,6 @@
"aliases": [],
"minimum-stability": "stable",
"stability-flags": {
"edwinhoksberg/php-fcm": 20,
"jankstudio/catalyst-api-bundle": 20,
"jankstudio/catalyst-auth-bundle": 20,
"jankstudio/catalyst-menu-bundle": 20,

View file

@ -586,17 +586,3 @@ access_keys:
label: Update
- id: ownership_type.delete
label: Delete
- id: customer_location
label: Customer Location Access
acls:
- id: cust_location.menu
label: Menu
- id: cust_location.list
label: List
- id: cust_location.add
label: Add
- id: cust_location.update
label: Update
- id: cust_location.delete
label: Delete

View file

@ -249,7 +249,3 @@ main_menu:
acl: ownership_type.menu
label: Ownership Types
parent: database
- id: customer_location_list
acl: cust_location.menu
label: Customer Locations
parent: database

View file

@ -277,8 +277,6 @@ catalyst_auth:
label: Fulfill Cancelled JO
- id: jo_resq_proc.list
label: RESQ Dispatch
- id: jo_resq_all.list
label: RESQ All
- id: support
label: Customer Support Access
@ -620,59 +618,6 @@ catalyst_auth:
- id: ownership_type.delete
label: Delete
- id: service_offering
label: Service Offering Access
acls:
- id: service_offering.menu
label: Menu
- id: service_offering.list
label: List
- id: service_offering.add
label: Add
- id: service_offering.update
label: Update
- id: service_offering.delete
label: Delete
- id: price_tier
label: Price Tier
acls:
- id: price_tier.menu
label: Menu
- id: price_tier.list
label: List
- id: price_tier.add
label: Add
- id: price_tier.update
label: Update
- id: price_tier.delete
label: Delete
- id: item_type
label: Item Type
acls:
- id: item_type.menu
label: Menu
- id: item_type.list
label: List
- id: item_type.add
label: Add
- id: item_type.update
label: Update
- id: item_type.delete
label: Delete
- id: item
label: Item
acls:
- id: item.menu
label: Menu
- id: item_pricing
label: Item Pricing
acls:
- id: item_pricing.update
label: Update
api:
user_entity: "App\\Entity\\ApiUser"
acl_data:
@ -751,16 +696,6 @@ catalyst_auth:
acls:
- id: warrantyserial.upload
label: Upload
- id: hub
label: Hub Access
acls:
- id: hub.list
label: List
- id: joborder
label: Job Order Access
acls:
- id: joborder.find
label: Find Job Order
- id: tapi_vmanufacturer
label: Third Party Vehicle Manufacturer Access
@ -941,4 +876,4 @@ catalyst_auth:
- id: cust_api_v2.warranty.check
label: Check Status
- id: cust_api_v2.warranty.register
label: Register
label: Register

View file

@ -168,16 +168,12 @@ catalyst_menu:
acl: jo_hub.list
label: '[menu.joborder.hubview]'
parent: joborder
- id: jo_resq_all
acl: jo_resq_all.list
label: '[menu.joborder.resqall]'
parent: joborder
- id: support
acl: support.menu
label: '[menu.support]'
icon: flaticon-support
order: 11
order: 10
- id: customer_list
acl: customer.list
label: '[menu.support.customers]'
@ -223,7 +219,7 @@ catalyst_menu:
acl: service.menu
label: '[menu.service]'
icon: flaticon-squares
order: 12
order: 11
- id: service_list
acl: service.list
label: '[menu.service.services]'
@ -233,7 +229,7 @@ catalyst_menu:
acl: partner.menu
label: '[menu.partner]'
icon: flaticon-network
order: 13
order: 12
- id: partner_list
acl: partner.list
label: '[menu.partner.partners]'
@ -247,7 +243,7 @@ catalyst_menu:
acl: motolite_event.menu
label: '[menu.motolite_event]'
icon: flaticon-event-calendar-symbol
order: 14
order: 13
- id: motolite_event_list
acl: motolite_event.list
label: '[menu.motolite_event.events]'
@ -257,7 +253,7 @@ catalyst_menu:
acl: analytics.menu
label: '[menu.analytics]'
icon: flaticon-graphic
order: 15
order: 14
- id: analytics_forecast_form
acl: analytics.forecast
label: '[menu.analytics.forecasting]'
@ -267,7 +263,7 @@ catalyst_menu:
acl: database.menu
label: '[menu.database]'
icon: fa fa-database
order: 16
order: 15
- id: ticket_type_list
acl: ticket_type.menu
label: '[menu.database.tickettypes]'
@ -283,26 +279,4 @@ catalyst_menu:
- id: ownership_type_list
acl: ownership_type.menu
label: '[menu.database.ownershiptypes]'
parent: database
- id: service_offering_list
acl: service_offering.menu
label: '[menu.database.serviceofferings]'
parent: database
- id: item_type_list
acl: item_type.menu
label: '[menu.database.itemtypes]'
parent: database
- id: item
acl: item.menu
label: Item Management
icon: fa fa-boxes
order: 10
- id: price_tier_list
acl: price_tier.list
label: Price Tiers
parent: item
- id: item_pricing
acl: item_pricing.update
label: Item Pricing
parent: item
parent: database

View file

@ -53,16 +53,8 @@ security:
pattern: ^\/test_capi\/
security: false
insurance:
pattern: ^\/insurance\/
security: false
paymongo:
pattern: ^\/paymongo\/
security: false
cust_api_v2:
pattern: ^\/apiv2\/(?!register|register\/|number_confirm|number_confirm\/|code_validate|code_validate\/|resend_code|resend_code\/|version_check|version_check\/|account|account\/|account_code_validate|account_code_validate\/|account_resend_code|account_resend_code\/)
pattern: ^\/apiv2\/(?!register|register\/|number_confirm|number_confirm\/|code_validate|code_validate\/|resend_code|resend_code\/)
provider: api_v2_provider
access_denied_handler: Catalyst\ApiBundle\Service\AccessDeniedHandler
stateless: true
@ -71,7 +63,7 @@ security:
- Catalyst\ApiBundle\Security\Authenticator
cust_api_v2_guest:
pattern: ^\/apiv2\/(register|register\/|number_confirm|number_confirm\/|code_validate|code_validate\/|resend_code|resend_code\/|version_check|version_check\/|account|account\/|account_code_validate|account_code_validate\/|account_resend_code|account_resend_code\/)
pattern: ^\/apiv2\/(register|register\/|number_confirm|number_confirm\/|code_validate|code_validate\/|resend_code|resend_code\/)
security: false
warranty_api:

View file

@ -45,11 +45,6 @@ apiv2_cust_vehicle_add:
controller: App\Controller\CustomerAppAPI\VehicleController::addVehicle
methods: [POST]
apiv2_cust_vehicle_info:
path: /apiv2/vehicles/{id}
controller: App\Controller\CustomerAppAPI\VehicleController::getVehicle
methods: [GET]
apiv2_cust_vehicle_update:
path: /apiv2/vehicles/{id}
controller: App\Controller\CustomerAppAPI\VehicleController::updateVehicle
@ -249,67 +244,4 @@ apiv2_partner_review_tags:
apiv2_rider_review_tags:
path: /apiv2/review_tags/rider
controller: App\Controller\CustomerAppAPI\ReviewTagController::getRiderReviewTags
# account deletion
apiv2_account_delete:
path: /apiv2/account_delete
controller: App\Controller\CustomerAppAPI\AccountController::deleteAccount
methods: [POST]
apiv2_account_delete_resend_code:
path: /apiv2/account_delete_resend_code
controller: App\Controller\CustomerAppAPI\AccountController:resendCode
methods: [POST]
apiv2_account_delete_code_validate:
path: /apiv2/account_delete_code_validate
controller: App\Controller\CustomerAppAPI\AccountController::validateDeleteCode
methods: [POST]
# trade-in support
apiv2_cust_vehicle_trade_in_estimate:
path: /apiv2/vehicles/{id}/trade_in_estimate
controller: App\Controller\CustomerAppAPI\VehicleController::getTradeInEstimate
methods: [GET]
# insurance
apiv2_insurance_vehicle_maker_list:
path: /apiv2/insurance/vehicles/makers
controller: App\Controller\CustomerAppAPI\InsuranceController::getVehicleMakers
methods: [GET]
apiv2_insurance_vehicle_model_list:
path: /apiv2/insurance/vehicles/models/{maker_id}
controller: App\Controller\CustomerAppAPI\InsuranceController::getVehicleModels
methods: [GET]
apiv2_insurance_vehicle_trim_list:
path: /apiv2/insurance/vehicles/trims/{model_id}
controller: App\Controller\CustomerAppAPI\InsuranceController::getVehicleTrims
methods: [GET]
apiv2_insurance_vehicle_mv_type_list:
path: /apiv2/insurance/mvtypes
controller: App\Controller\CustomerAppAPI\InsuranceController::getMVTypes
methods: [GET]
apiv2_insurance_vehicle_client_type_list:
path: /apiv2/insurance/clienttypes
controller: App\Controller\CustomerAppAPI\InsuranceController::getClientTypes
methods: [GET]
apiv2_insurance_application_create:
path: /apiv2/insurance/application
controller: App\Controller\CustomerAppAPI\InsuranceController::createApplication
methods: [POST]
apiv2_insurance_premiums_banner:
path: /apiv2/insurance/premiums_banner
controller: App\Controller\CustomerAppAPI\InsuranceController::getPremiumsBanner
methods: [GET]
apiv2_insurance_body_types:
path: /apiv2/insurance/body_types
controller: App\Controller\CustomerAppAPI\InsuranceController::getBodyTypes
methods: [GET]
controller: App\Controller\CustomerAppAPI\ReviewTagController::getRiderReviewTags

View file

@ -194,16 +194,3 @@ capi_warranty_serial_upload:
path: /capi/warranty_serial/upload
controller: App\Controller\CAPI\WarrantySerialController::uploadWarrantySerialFile
methods: [POST]
# pullout form system
# hub
capi_hub_list:
path: /capi/hubs
controller: App\Controller\CAPI\HubController::getAll
methods: [GET]
# job order details
capi_job_order:
path: /capi/job_order/{id}
controller: App\Controller\CAPI\JobOrderController::getJobOrder
methods: [GET]

View file

@ -94,24 +94,3 @@ capi_rider_jo_start:
path: /rider_api/start
controller: App\Controller\CAPI\RiderAppController::startJobOrder
methods: [POST]
# trade-ins
capi_rider_battery_sizes:
path: /rider_api/battery_sizes
controller: App\Controller\CAPI\RiderAppController::getBatterySizes
methods: [GET]
capi_rider_trade_in_types:
path: /rider_api/trade_in_types
controller: App\Controller\CAPI\RiderAppController::getTradeInTypes
methods: [GET]
capi_rider_battery_info:
path: /rider_api/battery/{serial}
controller: App\Controller\CAPI\RiderAppController::getBatteryInfo
methods: [GET]
capi_rider_update_jo:
path: /rider_api/job_order/update
controller: App\Controller\CAPI\RiderAppController::updateJobOrder
methods: [POST]

View file

@ -1,35 +0,0 @@
customer_location_list:
path: /customer-locations
controller: App\Controller\CustomerLocationController::index
methods: [GET]
customer_location_rows:
path: /customer-locations/rowdata
controller: App\Controller\CustomerLocationController::datatableRows
methods: [POST]
customer_location_add_form:
path: /customer-locations/newform
controller: App\Controller\CustomerLocationController::addForm
methods: [GET]
customer_location_add_submit:
path: /customer-locations
controller: App\Controller\CustomerLocationController::addSubmit
methods: [POST]
customer_location_update_form:
path: /customer-locations/{id}
controller: App\Controller\CustomerLocationController::updateForm
methods: [GET]
customer_location_update_submit:
path: /customer-locations/{id}
controller: App\Controller\CustomerLocationController::updateSubmit
methods: [POST]
customer_location_delete:
path: /customer-locations/{id}
controller: App\Controller\CustomerLocationController::deleteSubmit
methods: [DELETE]

View file

@ -1,6 +1,6 @@
# insurance
insurance_listener:
path: /insurance/listen
path: /api/insurance/listen
controller: App\Controller\InsuranceController::listen
methods: [POST]

View file

@ -1,14 +0,0 @@
item_pricing:
path: /item-pricing
controller: App\Controller\ItemPricingController::index
methods: [GET]
item_pricing_update:
path: /item-pricing
controller: App\Controller\ItemPricingController::formSubmit
methods: [POST]
item_pricing_prices:
path: /item-pricing/{pt_id}/{it_id}/prices
controller: App\Controller\ItemPricingController::itemPrices
methods: [GET]

View file

@ -1,34 +0,0 @@
item_type_list:
path: /item-types
controller: App\Controller\ItemTypeController::index
methods: [GET]
item_type_rows:
path: /item-types/rowdata
controller: App\Controller\ItemTypeController::datatableRows
methods: [POST]
item_type_add_form:
path: /item-types/newform
controller: App\Controller\ItemTypeController::addForm
methods: [GET]
item_type_add_submit:
path: /item-types
controller: App\Controller\ItemTypeController::addSubmit
methods: [POST]
item_type_update_form:
path: /item-types/{id}
controller: App\Controller\ItemTypeController::updateForm
methods: [GET]
item_type_update_submit:
path: /item-types/{id}
controller: App\Controller\ItemTypeController::updateSubmit
methods: [POST]
item_type_delete:
path: /item-types/{id}
controller: App\Controller\ItemTypeController::deleteSubmit
methods: [DELETE]

View file

@ -267,8 +267,3 @@ jo_geofence:
path: /ajax/job-order/geofence
controller: App\Controller\JobOrderController::checkGeofence
methods: [GET]
jo_all_view_form:
path: /job-order/all/view/{id}
controller: App\Controller\JobOrderController::allViewForm
methods: [GET]

View file

@ -1,16 +0,0 @@
# paymongo
paymongo_listener:
path: /paymongo/listen
controller: App\Controller\PayMongoController::listen
methods: [POST]
paymongo_payment_success:
path: /paymongo/success
controller: App\Controller\PayMongoController::paymentSuccess
methods: [GET]
paymongo_payment_cancelled:
path: /paymongo/cancelled
controller: App\Controller\PayMongoController::paymentCancelled
methods: [GET]

View file

@ -1,34 +0,0 @@
price_tier_list:
path: /price-tiers
controller: App\Controller\PriceTierController::index
methods: [GET]
price_tier_rows:
path: /price-tiers/rows
controller: App\Controller\PriceTierController::datatableRows
methods: [POST]
price_tier_add_form:
path: /price-tiers/newform
controller: App\Controller\PriceTierController::addForm
methods: [GET]
price_tier_add_submit:
path: /price-tiers
controller: App\Controller\PriceTierController::addSubmit
methods: [POST]
price_tier_update_form:
path: /price-tiers/{id}
controller: App\Controller\PriceTierController::updateForm
methods: [GET]
price_tier_update_submit:
path: /price-tiers/{id}
controller: App\Controller\PriceTierController::updateSubmit
methods: [POST]
price_tier_delete:
path: /price-tiers/{id}
controller: App\Controller\PriceTierController::deleteSubmit
methods: [DELETE]

View file

@ -7,17 +7,3 @@ jo_resq_proc_rows:
path: /resq-job-order/processing-rows
controller: App\Controller\ResqJobOrderController::datatableRows
methods: [POST]
defaults:
tier: "proc"
jo_resq_all:
path: /resq-job-order/all
controller: App\Controller\ResqJobOrderController::listAll
methods: [GET]
jo_resq_all_rows:
path: /resq-job-orer/all
controller: App\Controller\ResqJobOrderController::datatableRows
methods: [POST]
defaults:
tier: "all"

View file

@ -1,34 +0,0 @@
service_offering_list:
path: /service-offerings
controller: App\Controller\ServiceOfferingController::index
methods: [GET]
service_offering_rows:
path: /service-offerings/rowdata
controller: App\Controller\ServiceOfferingController::datatableRows
methods: [POST]
service_offering_add_form:
path: /service-offerings/newform
controller: App\Controller\ServiceOfferingController::addForm
methods: [GET]
service_offering_add_submit:
path: /service-offerings
controller: App\Controller\ServiceOfferingController::addSubmit
methods: [POST]
service_offering_update_form:
path: /service-offerings/{id}
controller: App\Controller\ServiceOfferingController::updateForm
methods: [GET]
service_offering_update_submit:
path: /service-offerings/{id}
controller: App\Controller\ServiceOfferingController::updateSubmit
methods: [POST]
service_offering_delete:
path: /service-offerings/{id}
controller: App\Controller\ServiceOfferingController::deleteSubmit
methods: [DELETE]

View file

@ -51,7 +51,7 @@ tapi_vehicle_make_list:
tapi_battery_list:
path: /tapi/vehicles/{vid}/compatible_batteries
controller: App\Controller\TAPI\BatteryController::getCompatibleBatteries
methods: [POST]
methods: [GET]
# promos
tapi_promo_list:

View file

@ -13,10 +13,6 @@ parameters:
cvu_brand_id: "%env(CVU_BRAND_ID)%"
country_code: "%env(COUNTRY_CODE)%"
api_version: "%env(API_VERSION)%"
android_app_version: "%env(ANDROID_APP_VERSION)%"
ios_app_version: "%env(IOS_APP_VERSION)%"
insurance_premiums_banner_url: "%env(INSURANCE_PREMIUMS_BANNER_URL)%"
enabled_hub_filters: "%env(ENABLED_HUB_FILTERS)%"
services:
# default configuration for services in *this* file
@ -110,12 +106,6 @@ services:
arguments:
$callback_url: "%env(WARRANTY_SERIAL_CALLBACK_URL)%"
App\Command\ProcessLatePaymongoTransactionsCommand:
arguments:
$em: "@doctrine.orm.entity_manager"
$paymongo: "@App\\Service\\PayMongoConnector"
$webhook_id: "%env(PAYMONGO_WEBHOOK_ID)%"
# rider tracker service
App\Service\RiderTracker:
arguments:
@ -125,10 +115,7 @@ services:
App\Service\InvoiceGenerator\ResqInvoiceGenerator: ~
# invoice generator interface
App\Service\InvoiceGeneratorInterface: "@App\\Service\\InvoiceManager"
# invoice manager
App\Service\InvoiceManager: ~
App\Service\InvoiceGeneratorInterface: "@App\\Service\\InvoiceGenerator\\ResqInvoiceGenerator"
# job order generator
App\Service\JobOrderHandler\ResqJobOrderHandler:
@ -224,23 +211,6 @@ services:
$username: "%env(INSURANCE_USERNAME)%"
$password: "%env(INSURANCE_PASSWORD)%"
# entity listener for gateway transactions
App\EntityListener\GatewayTransactionListener:
arguments:
$em: "@doctrine.orm.entity_manager"
$ic: "@App\\Service\\InsuranceConnector"
tags:
- name: doctrine.orm.entity_listener
event: 'postUpdate'
entity: 'App\Entity\GatewayTransaction'
# paymongo connector
App\Service\PayMongoConnector:
arguments:
$base_url: "%env(PAYMONGO_BASE_URL)%"
$public_key: "%env(PAYMONGO_PUBLIC_KEY)%"
$secret_key: "%env(PAYMONGO_SECRET_KEY)%"
# entity listener for customer vehicle warranty code history
App\EntityListener\CustomerVehicleSerialListener:
arguments:
@ -318,41 +288,3 @@ services:
arguments:
$server_key: "%env(FCM_SERVER_KEY)%"
$sender_id: "%env(FCM_SENDER_ID)%"
# price tier manager
App\Service\PriceTierManager:
arguments:
$em: "@doctrine.orm.entity_manager"
# hub filters
App\Service\HubFilter\BaseHubFilter:
arguments:
$hub_filter_logger: "@App\\Service\\HubFilterLogger"
$em: "@doctrine.orm.entity_manager"
$rt: "@App\\Service\\RisingTideGateway"
$trans: "@Symfony\\Contracts\\Translation\\TranslatorInterface"
App\Service\HubFilter\Filters\DateAndTimeHubFilter:
public: true
App\Service\HubFilter\Filters\JoTypeHubFilter:
public: true
App\Service\HubFilter\Filters\MaxResultsHubFilter:
public: true
App\Service\HubFilter\Filters\PaymentMethodHubFilter:
public: true
App\Service\HubFilter\Filters\RiderAvailabilityHubFilter:
public: true
App\Service\HubFilter\Filters\InventoryHubFilter:
public: true
arguments:
$im: "@App\\Service\\InventoryManager"
App\Service\HubFilter\Filters\RoundRobinHubFilter:
public: true
arguments:
$hub_distributor: "@App\\Service\\HubDistributor"

View file

@ -1,74 +0,0 @@
$(function() {
// export table to csv
$(document).on('click', '[data-export-csv]', async function(e) {
const el = e.target.closest('[data-export-csv]');
const oldLabel = el.innerHTML;
// set loading status
el.disabled = true;
el.innerHTML = 'Exporting...';
const formData = new FormData();
formData.append('datatable[pagination][page]', 1);
formData.append('datatable[pagination][perpage]', 10000000);
// get all rows
const response = await fetch(el.dataset.url, {
method: el.dataset.method,
body: formData,
});
const result = await response.json();
if (response.status === 200) {
// empty set returned
if (parseInt(result.meta.total) === 0) {
swal({
title: 'Whoops',
html: 'No data to export!',
type: 'warning',
});
}
// build csv data
const csvRows = [];
const fieldList = el.dataset.fields.split(',');
csvRows.push(el.dataset.headers);
result.data.forEach((row) => {
const fieldData = [];
fieldList.forEach((field) => {
fieldData.push('"' + row[field] + '"');
});
csvRows.push(fieldData.join(','));
});
const csvData = csvRows.join('\n');
// build the csv file
const csvFile = new Blob([csvData], {
type: 'text/csv',
});
// create a link to the file and download it
const url = window.URL.createObjectURL(csvFile);
const a = document.createElement('a');
a.href = url;
a.download = el.dataset.filename + '.csv';
a.click();
} else {
// something went wrong on the server
swal({
title: 'Whoops',
html: 'An error has occurred while retrieving data.',
type: 'error',
});
}
// remove loading status
el.disabled = false;
el.innerHTML = oldLabel;
});
});

BIN
public/battery/enduro_mobile.jpg Executable file → Normal file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 13 KiB

BIN
public/battery/excel_mobile.jpg Executable file → Normal file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 14 KiB

BIN
public/battery/gold_mobile.jpg Executable file → Normal file

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

View file

@ -43,7 +43,7 @@ class GenerateBatteryCompatibilityCommand extends Command
$vehicles = $vm->getVehicles();
foreach ($vehicles as $vehicle)
{
$batteries = $vehicle->getActiveBatteries();
$batteries = $vehicle->getBatteries();
$comp_batt = [];
foreach ($batteries as $battery)
{

View file

@ -1,136 +0,0 @@
<?php
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;
use Doctrine\ORM\EntityManagerInterface;
use App\Ramcar\TransactionStatus;
use App\Entity\GatewayTransaction;
use App\Service\PayMongoConnector;
use DateTime;
class ProcessLatePaymongoTransactionsCommand extends Command
{
protected $em;
protected $paymongo;
protected $webhook_id;
public function __construct(EntityManagerInterface $em, PayMongoConnector $paymongo, $webhook_id)
{
$this->em = $em;
$this->paymongo = $paymongo;
$this->webhook_id = $webhook_id;
parent::__construct();
}
protected function configure()
{
$this->setName('paymongo:checkpending')
->setDescription('Check for any late PayMongo transactions and process if needed.')
->setHelp('Check for any late PayMongo transactions and process if needed.')
->addOption('force', 'f', InputOption::VALUE_NONE, 'Ignore webhook status and process anyway.');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$force = $input->getOption('force');
// if we aren't forcing, check webhook status first
if (!$force) {
$output->writeln('Checking webhook status...');
// check if webhook is disabled
$webhook = $this->paymongo->getWebhook($this->webhook_id);
if ($webhook['success'] && $webhook['response']['data']['attributes']['status'] === 'enabled') {
$output->writeln('<info>Webhook is enabled, no need to do anything.</info>');
return 0;
} else {
$output->writeln('<comment>Webhook is disabled! Logging event and attempting to re-enable...</comment>');
// attempt re-enabling of webhook
$result = $this->paymongo->enableWebhook($this->webhook_id);
if ($result['success'] && $result['response']['data']['attributes']['status'] ?? null === 'enabled') {
$output->writeln('<info>Webhook ' . $this->webhook_id . ' re-enabled!</info>');
// log event
$this->paymongo->log('WEBHOOK RE-ENABLED', "[]", json_encode($result['response'], JSON_PRETTY_PRINT), 'webhook');
} else {
$output->writeln('<comment>Webhook ' . $this->webhook_id . ' could not be re-enabled.</comment>');
// log event
$this->paymongo->log('WEBHOOK FAILURE', "[]", json_encode($result['response'], JSON_PRETTY_PRINT), 'webhook');
}
}
}
$output->writeln('Fetching all late pending transactions...');
// set date threshold to 24 hours ago
$date_threshold = (new DateTime())->modify('-24 hours');
$transactions = $this->em->getRepository(GatewayTransaction::class)
->createQueryBuilder('t')
->select('t')
->where('t.status = :status')
->andWhere('t.date_create <= :date_threshold')
->setParameter('status', TransactionStatus::PENDING)
->setParameter('date_threshold', $date_threshold)
->getQuery()
->getResult();
$output->writeln('Found '. count($transactions) . ' rows matching criteria.');
$x = 0;
foreach ($transactions as $trans) {
// check paymongo status
$checkout = $this->paymongo->getCheckout($trans->getExtTransactionId());
if ($checkout['success']) {
// check if we have any payments made
$payments = $checkout['response']['data']['attributes']['payments'] ?? [];
if (!empty($payments)) {
$amount_paid = 0;
// for good measure, we get all successful payments and add them up
foreach ($payments as $payment) {
if ($payment['attributes']['status'] === TransactionStatus::PAID) {
$amount_paid = bcadd($amount_paid, $payment['attributes']['amount']);
}
}
// this transaction is fully paid, so we mark it as paid
if (bccomp($trans->getAmount(), $amount_paid) <= 0) {
$trans->setStatus(TransactionStatus::PAID);
$trans->setDatePay(new DateTime());
$this->em->flush();
$output->writeln('Marked transaction '. $trans->getID() . ' as paid.');
$x++;
} else {
$output->writeln('<comment>Insufficient payment amount (' . $amount_paid . '/' . $trans->getAmount() . ') for this transaction: ' . $trans->getID() . '</comment>');
}
} else {
$output->writeln('<comment>No payments found for transaction: ' . $trans->getID() . '</comment>');
}
} else {
$output->writeln('<comment>Checkout not found: ' . $checkout['error']['message'] . '</comment>');
}
}
$output->writeln('<info>Done! Processed ' . $x . ' rows.</info>');
return 0;
}
}

View file

@ -1,80 +0,0 @@
<?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\Service\JobOrderManager;
class SetJobOrderCustNewCommand extends Command
{
protected $em;
protected $jo_manager;
public function __construct(EntityManagerInterface $em, JobOrderManager $jo_manager)
{
$this->em = $em;
$this->jo_manager = $jo_manager;
parent::__construct();
}
protected function configure()
{
$this->setName('joborder:setcustomernew')
->setDescription('Set job order\'s customer new flag for existing job orders.')
->setHelp('Set job order\'s customer new flag for existing job orders');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$em = $this->em;
// pdo connection
$db = $em->getConnection();
// get all the ids for all job orders
$all_query_sql = 'SELECT id AS jo_id, customer_id AS cust_id FROM job_order ORDER BY id';
$all_query_stmt = $db->prepare($all_query_sql);
$all_query_stmt->execute();
$all_jo_results = $all_query_stmt->fetchAll();
$output->writeln('Processing job orders...');
foreach ($all_jo_results as $jo_row)
{
// for each jo id, get the customer id
$jo_id = $jo_row['jo_id'];
$cust_id = $jo_row['cust_id'];
// check how many JOs have that customer id
$jo_count = $this->jo_manager->getCustomerJobOrderCount($cust_id);
// if one or less, set flag_cust_new to true
if ($jo_count <= 1)
$this->updateCustNew($db, $jo_id);
}
$output->writeln('All done!');
return 0;
}
protected function updateCustNew($db, $jo_id)
{
$update_jo_sql = 'UPDATE job_order SET flag_cust_new = :flag_cust_new WHERE id = :jo_id';
$update_jo_stmt = $db->prepare($update_jo_sql);
$update_jo_stmt->execute([
'flag_cust_new' => true,
'jo_id' => $jo_id
]);
}
}

File diff suppressed because it is too large Load diff

View file

@ -49,8 +49,6 @@ use App\Service\HubDistributor;
use App\Service\HubFilterLogger;
use App\Service\HubFilteringGeoChecker;
use App\Service\HashGenerator;
use App\Service\JobOrderManager;
use App\Service\PriceTierManager;
use App\Entity\MobileSession;
use App\Entity\Customer;
@ -825,8 +823,7 @@ class APIController extends Controller implements LoggedController
// batteries
$batt_list = [];
// $batts = $vehicle->getBatteries();
$batts = $vehicle->getActiveBatteries();
$batts = $vehicle->getBatteries();
foreach ($batts as $batt)
{
// TODO: Add warranty_tnv to battery information
@ -869,7 +866,7 @@ class APIController extends Controller implements LoggedController
MapTools $map_tools, InventoryManager $im, MQTTClient $mclient,
RiderAssignmentHandlerInterface $rah, PromoLogger $promo_logger,
HubSelector $hub_select, HubDistributor $hub_dist, HubFilterLogger $hub_filter_logger,
HubFilteringGeoChecker $hub_geofence, JobOrderManager $jo_manager)
HubFilteringGeoChecker $hub_geofence)
{
// check required parameters and api key
$required_params = [
@ -930,15 +927,7 @@ class APIController extends Controller implements LoggedController
->setErrorMessage('No customer information found');
return $res->getReturnResponse();
}
// check if customer has more than one job order already
$flag_cust_new = false;
$cust_jo_count = $jo_manager->getCustomerJobOrderCount($cust->getID());
if ($cust_jo_count <= 1)
$flag_cust_new = true;
$jo->setCustomer($cust);
$jo->setCustNew($flag_cust_new);
// validate service type
$stype = $req->request->get('service_type');
@ -1036,18 +1025,7 @@ class APIController extends Controller implements LoggedController
break;
}
// right now, the app does not include trade-ins but this might change in the future
if (empty($trade_in))
$icrit->addEntry($batt, null, 1);
else
$icrit->addEntry($batt, $trade_in, 1);
// set if taxable
$icrit->setIsTaxable();
// set JO source
// old app doesn't have separate jumpstart
$icrit->setSource(TransactionOrigin::CALL);
$icrit->addEntry($batt, $trade_in, 1);
// send to invoice generator
$invoice = $ic->generateInvoice($icrit);
@ -1328,13 +1306,6 @@ class APIController extends Controller implements LoggedController
$icrit->addBattery($batt);
*/
// set taxable
$icrit->setIsTaxable(true);
// set JO source
// old app doesn't have separate jumpstart
$icrit->setSource(TransactionOrigin::CALL);
// check trade-in
// only allow motolite, other, none
$trade_in = $req->request->get('trade_in');
@ -1349,11 +1320,7 @@ class APIController extends Controller implements LoggedController
break;
}
// right now, the app does not include trade-ins but this might change in the future
if (empty($trade_in))
$icrit->addEntry($batt, null, 1);
else
$icrit->addEntry($batt, $trade_in, 1);
$icrit->addEntry($batt, $trade_in, 1);
// send to invoice generator
$invoice = $ic->generateInvoice($icrit);
@ -2742,7 +2709,7 @@ class APIController extends Controller implements LoggedController
MapTools $map_tools, InventoryManager $im, MQTTClient $mclient,
RiderAssignmentHandlerInterface $rah, PromoLogger $promo_logger,
HubSelector $hub_select, HubDistributor $hub_dist, HubFilterLogger $hub_filter_logger,
HubFilteringGeoChecker $hub_geofence, JobOrderManager $jo_manager)
HubFilteringGeoChecker $hub_geofence)
{
// check required parameters and api key
$required_params = [
@ -2867,15 +2834,7 @@ class APIController extends Controller implements LoggedController
// ->setErrorMessage('No customer information found');
// return $res->getReturnResponse();
// }
// check if customer has more than one job order already
$flag_cust_new = false;
$cust_jo_count = $jo_manager->getCustomerJobOrderCount($cust->getID());
if ($cust_jo_count <= 1)
$flag_cust_new = true;
$jo->setCustomer($cust);
$jo->setCustNew($flag_cust_new);
// validate service type
$stype = $req->request->get('service_type');
@ -2905,17 +2864,6 @@ class APIController extends Controller implements LoggedController
$icrit = new InvoiceCriteria();
$icrit->setServiceType($stype);
// set taxable
$icrit->setIsTaxable(true);
// set JO source
// old app doesn't have separate jumpstart
$icrit->setSource(TransactionOrigin::CALL);
// set price tier
$pt_id = $this->pt_manager->getPriceTier($jo->getCoordinates());
$icrit->setPriceTier($pt_id);
// check promo
$promo_id = $req->request->get('promo_id');
if (!empty($promo_id))
@ -2984,11 +2932,7 @@ class APIController extends Controller implements LoggedController
break;
}
// right now, the app does not include trade-ins but this might change in the future
if (empty($trade_in))
$icrit->addEntry($batt, null, 1);
else
$icrit->addEntry($batt, $trade_in, 1);
$icrit->addEntry($batt, $trade_in, 1);
// send to invoice generator
$invoice = $ic->generateInvoice($icrit);

View file

@ -326,7 +326,7 @@ class APIRoleController extends Controller
protected function padAPIACLHierarchy(&$params)
{
// get acl keys hierarchy
$api_acl_data = $this->api_acl_gen->getACL('api');
$api_acl_data = $this->api_acl_gen->getACL();
$params['api_acl_hierarchy'] = $api_acl_data['hierarchy'];
}

View file

@ -117,7 +117,6 @@ class BatteryController extends Controller
$row['height'] = $orow[0]->getHeight();
$row['total_height'] = $orow[0]->getTotalHeight();
$row['image_file'] = $orow[0]->getImageFile();
$row['flag_active'] = $orow[0]->isActive();
// add row metadata
$row['meta'] = [
@ -183,8 +182,7 @@ class BatteryController extends Controller
->setHeight($req->request->get('height'))
->setTotalHeight($req->request->get('total_height'))
->setSellingPrice($req->request->get('sell_price'))
->setImageFile($req->request->get('image_file'))
->setActive($req->request->get('flag_active', false));
->setImageFile($req->request->get('image_file'));
// initialize error list
$error_array = [];
@ -310,7 +308,6 @@ class BatteryController extends Controller
->setTotalHeight($req->request->get('total_height'))
->setSellingPrice($req->request->get('sell_price'))
->setImageFile($req->request->get('image_file'))
->setActive($req->request->get('flag_active', false))
->clearVehicles();
// initialize error list
@ -427,7 +424,7 @@ class BatteryController extends Controller
$bmodel_id = $req->query->get('model_id');
$bsize_id = $req->query->get('size_id');
// find the battery using model and size and battery must be active
// find the battery using model and size
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('SELECT b FROM App\Entity\Battery b
JOIN b.model bm
@ -435,8 +432,7 @@ class BatteryController extends Controller
JOIN b.manufacturer bmfg
WHERE bm.id = :bm_id
AND bs.id = :bs_id
AND bmfg.id = :bmfg_id
AND b.flag_active = true')
AND bmfg.id = :bmfg_id')
->setParameter('bmfg_id', $bmfg_id)
->setParameter('bm_id', $bmodel_id)
->setParameter('bs_id', $bsize_id);

View file

@ -270,7 +270,7 @@ class BatteryManufacturerController extends Controller
// get row data
$em = $this->getDoctrine()->getManager();
$all_batts = $em->getRepository(Battery::class)->findBy(['flag_active' => true]);
$all_batts = $em->getRepository(Battery::class)->findAll();
foreach ($all_batts as $battery)
{

View file

@ -7,7 +7,7 @@ use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Entity\SAPBattery;
use App\Entity\SAPBatterySize;

View file

@ -9,6 +9,7 @@ use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
//use Catalyst\ApiBundle\Response\APIResponse;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use App\Entity\Customer;
@ -19,7 +20,7 @@ use App\Service\HashGenerator;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class CustomerController extends ApiController
class CustomerController extends APIController
{
protected $acl_gen;

View file

@ -11,7 +11,7 @@ use Doctrine\ORM\EntityManagerInterface;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Service\RisingTideGateway;
use App\Service\WarrantyAPILogger;
@ -40,7 +40,7 @@ use DateTime;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
// third party API
class CustomerWarrantyController extends ApiController
class CustomerWarrantyController extends APIController
{
protected $acl_gen;

View file

@ -7,13 +7,13 @@ use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Entity\Dealer;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class DealerController extends ApiController
class DealerController extends APIController
{
protected $acl_gen;

View file

@ -1,53 +0,0 @@
<?php
namespace App\Controller\CAPI;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use App\Entity\Hub;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class HubController extends ApiController
{
protected $acl_gen;
public function __construct(ACLGenerator $acl_gen)
{
$this->acl_gen = $acl_gen;
}
public function getAll(EntityManagerInterface $em)
{
// get all hub data order by name
$this->denyAccessUnlessGranted('hub.list', null, 'No access.');
$results = $em->getRepository(Hub::class)->findBy([], ['name' => 'ASC']);
$hubs = [];
foreach($results as $res)
{
$hub_id = $res->getId();
$hub_name = $res->getName();
$hub_address = $res->getAddress();
$hub_branch_code = $res->getBranchCode();
$hubs[$hub_id] = [
'id' => $hub_id,
'name' => $hub_name,
'address' => $hub_address,
'branch_code' => $hub_branch_code,
];
}
$data = [
'hubs' => $hubs,
];
return new APIResponse(true, 'Hubs loaded.', $data);
}
}

View file

@ -1,139 +0,0 @@
<?php
namespace App\Controller\CAPI;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use App\Entity\JobOrder;
use App\Entity\Warranty;
use App\Ramcar\JOStatus;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class JobOrderController extends ApiController
{
protected $acl_gen;
public function __construct(ACLGenerator $acl_gen)
{
$this->acl_gen = $acl_gen;
}
public function getJobOrder($id, EntityManagerInterface $em)
{
$this->denyAccessUnlessGranted('joborder.find', null, 'No access.');
$jo = $em->getRepository(JobOrder::class)->find($id);
if ($jo == null)
return new APIResponse(false, 'No job order found with that number.', null, 404);
$data = $this->generateJobOrderData($jo, $em);
return new APIResponse(true, 'Job order found.', $data);
}
protected function generateJobOrderData($jo, EntityManagerInterface $em)
{
// customer vehicle
$cv = $jo->getCustomerVehicle();
// customer information
$customer = $jo->getCustomer();
// hub
$hub_name = '';
$hub = $jo->getHub();
if ($hub != null)
$hub_name = $hub->getName();
// check if JO is fulfilled, if not, we leave date_purchase blank
$date_purchase = '';
$serial = '';
$status = $jo->getStatus();
if ($status == JOStatus::FULFILLED)
{
if ($jo->getDateFulfill() != null)
$date_purchase = $jo->getDateFulfill()->format('M d, Y H:i');
// find warranty to get the serial using plate number
$serial = $this->getSerialFromWarranty($cv->getPlateNumber(), $em);
}
$jo_data = [
'id' => $jo->getID(),
'first_name' => $customer->getFirstName(),
'last_name' => $customer->getLastName(),
'mobile_number' => $customer->getPhoneMobile(),
'email' => $customer->getEmail(),
'plate_number' => $cv->getPlateNumber(),
'date_purchase' => $date_purchase,
'address' => $jo->getDeliveryAddress(),
'hub' => $hub_name,
'serial' => $serial,
];
// invoice items
$items = [];
$jo_items = $jo->getInvoice()->getItems();
$non_battery_item_titles = ['Promo discount', 'Trade-in', 'Service'];
foreach ($jo_items as $item)
{
$item_title = $item->getTitle();
// check if title has Promo discount, Trade-in, or Service
$flag_battery = $this->checkIfBatteryInvoiceItem($item_title, $non_battery_item_titles);
if ($flag_battery == true)
{
$items[] = [
'title' => $item->getTitle(),
];
}
}
$jo_data['items'] = $items;
return $jo_data;
}
protected function checkIfBatteryInvoiceItem($item_title, $non_battery_item_titles)
{
foreach ($non_battery_item_titles as $nb_item_title)
{
$pos_result = stripos($item_title, $nb_item_title);
// if found, invoice item is not a battery item
if ($pos_result !== false)
return false;
}
return true;
}
protected function getSerialFromWarranty($plate_number, EntityManagerInterface $em)
{
// NOTE: Modify the search for the latest warranty. This seems hacky.
// get latest warranty using plate number
$warranty_results = $em->getRepository(Warranty::class)->findBy(
['plate_number' => $plate_number],
['date_create' => 'desc']
);
$serial = '';
if (!empty($warranty_results))
{
// get first entry
$warranty = current($warranty_results);
$serial = $warranty->getSerial();
}
return $serial;
}
}

View file

@ -7,13 +7,13 @@ use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Entity\Municipality;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class MunicipalityController extends ApiController
class MunicipalityController extends APIController
{
protected $acl_gen;

View file

@ -8,14 +8,14 @@ use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Entity\PrivacyPolicy;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
// third party API
class PrivacyPolicyController extends ApiController
class PrivacyPolicyController extends APIController
{
protected $acl_gen;

View file

@ -23,9 +23,7 @@ use App\Entity\BatterySize;
use App\Entity\RiderAPISession;
use App\Entity\User;
use App\Entity\ApiUser as APIUser;
use App\Entity\JobOrder;
use App\Entity\SAPBattery;
use App\Entity\WarrantySerial;
use App\Service\RedisClientProvider;
use App\Service\RiderCache;
use App\Service\MQTTClient;
@ -36,7 +34,6 @@ use App\Service\JobOrderHandlerInterface;
use App\Service\InvoiceGeneratorInterface;
use App\Service\RisingTideGateway;
use App\Service\RiderTracker;
use App\Service\PriceTierManager;
use App\Ramcar\ServiceType;
use App\Ramcar\TradeInType;
@ -51,7 +48,7 @@ use App\Ramcar\DeliveryStatus;
use DateTime;
// third party API for rider
class RiderAppController extends ApiController
class RiderAppController extends APIController
{
/*
public function register(Request $req, EntityManagerInterface $em, RedisClientProvider $redis)
@ -289,9 +286,8 @@ class RiderAppController extends ApiController
// do we have a job order?
// $jo = $rider->getActiveJobOrder();
// NOTE: we do not include job orders that have been cancelled
$jo = $rider->getCurrentJobOrder();
if ($jo == null || $jo->getStatus() == JOStatus::CANCELLED)
if ($jo == null)
{
$data = [
'job_order' => null
@ -386,7 +382,6 @@ class RiderAppController extends ApiController
'flag_coolant' => $jo->hasCoolant(),
'has_motolite' => $cv->hasMotoliteBattery(),
'delivery_status' => $jo->getDeliveryStatus(),
'flag_sealant' => $jo->hasSealant(),
]
];
}
@ -413,11 +408,6 @@ class RiderAppController extends ApiController
if (!empty($msg))
return new APIResponse(false, $msg);
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// TODO: refactor this into a jo handler class, so we don't have to repeat for control center
// set jo status to in transit
@ -468,11 +458,6 @@ class RiderAppController extends ApiController
// TODO: this is a workaround for requeue, because rider app gets stuck in accept / decline screen
return new APIResponse(true, $msg);
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// requeue it, instead of cancelling it
$jo->requeue();
@ -531,11 +516,6 @@ class RiderAppController extends ApiController
// get rider's current job order
$jo = $rider->getCurrentJobOrder();
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// set delivery status
$jo->setDeliveryStatus(DeliveryStatus::RIDER_DEPART_HUB);
@ -576,11 +556,6 @@ class RiderAppController extends ApiController
// get rider's current job order
$jo = $rider->getCurrentJobOrder();
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// set delivery status
$jo->setDeliveryStatus(DeliveryStatus::RIDER_ARRIVE_HUB_PRE_JO);
@ -621,11 +596,6 @@ class RiderAppController extends ApiController
// get rider's current job order
$jo = $rider->getCurrentJobOrder();
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// set delivery status
$jo->setDeliveryStatus(DeliveryStatus::RIDER_DEPART_HUB_PRE_JO);
@ -666,11 +636,6 @@ class RiderAppController extends ApiController
// get rider's current job order
$jo = $rider->getCurrentJobOrder();
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// set delivery status
$jo->setDeliveryStatus(DeliveryStatus::RIDER_START);
@ -712,11 +677,6 @@ class RiderAppController extends ApiController
// set jo status to in progress
$jo->setStatus(JOStatus::IN_PROGRESS);
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// set delivery status
$jo->setDeliveryStatus(DeliveryStatus::RIDER_ARRIVE);
@ -775,11 +735,6 @@ class RiderAppController extends ApiController
// get rider's current job order
$jo = $rider->getCurrentJobOrder();
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// set delivery status
$jo->setDeliveryStatus(DeliveryStatus::RIDER_ARRIVE_HUB);
@ -803,54 +758,6 @@ class RiderAppController extends ApiController
return new APIResponse(true, 'Rider arrive at hub.', $data);
}
public function getBatterySizes(Request $req, EntityManagerInterface $em)
{
// get capi user
$capi_user = $this->getUser();
if ($capi_user == null)
return new APIResponse(false, 'User not found.');
// get rider id from capi user metadata
$rider = $this->getRiderFromCAPI($capi_user, $em);
if ($rider == null)
return new APIResponse(false, 'No rider found.');
// get sizes
$qb = $em->getRepository(BatterySize::class)
->createQueryBuilder('bs');
$sizes = $qb->select('bs.id, bs.name')
->orderBy('bs.name', 'asc')
->getQuery()
->getResult();
// response
return new APIResponse(true, '', [
'sizes' => $sizes,
]);
}
public function getTradeInTypes(Request $req, EntityManagerInterface $em)
{
// get capi user
$capi_user = $this->getUser();
if ($capi_user == null)
return new APIResponse(false, 'User not found.');
// get rider id from capi user metadata
$rider = $this->getRiderFromCAPI($capi_user, $em);
if ($rider == null)
return new APIResponse(false, 'No rider found.');
// get trade-in types
$types = TradeInType::getCollection();
// response
return new APIResponse(true, '', [
'types' => $types,
]);
}
public function payment(Request $req, EntityManagerInterface $em, JobOrderHandlerInterface $jo_handler,
RisingTideGateway $rt, WarrantyHandler $wh, MQTTClient $mclient, MQTTClientApiv2 $mclientv2, FCMSender $fcmclient, TranslatorInterface $translator)
{
@ -870,22 +777,6 @@ class RiderAppController extends ApiController
if (!empty($msg))
return new APIResponse(false, $msg);
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// need to check if service type is battery sales
// if so, serial is a required parameter
$serial = $req->request->get('serial', '');
if ($jo->getServiceType() == ServiceType::BATTERY_REPLACEMENT_NEW)
{
/*
if (empty($serial))
return new APIResponse(false, 'Missing parameter(s): serial');
*/
}
// set invoice to paid
$jo->getInvoice()->setStatus(InvoiceStatus::PAID);
@ -937,6 +828,7 @@ class RiderAppController extends ApiController
// create warranty
if($jo_handler->checkIfNewBattery($jo))
{
$serial = null;
$warranty_class = $jo->getWarrantyClass();
$first_name = $jo->getCustomer()->getFirstName();
$last_name = $jo->getCustomer()->getLastName();
@ -1020,11 +912,6 @@ class RiderAppController extends ApiController
// get rider's current job order
$jo = $rider->getCurrentJobOrder();
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// set delivery status
$jo->setDeliveryStatus(DeliveryStatus::RIDER_ARRIVE_HUB_POST_JO);
@ -1066,11 +953,6 @@ class RiderAppController extends ApiController
// get rider's current job order
$jo = $rider->getCurrentJobOrder();
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// set delivery status
$jo->setDeliveryStatus(DeliveryStatus::RIDER_DEPART_HUB_POST_JO);
@ -1175,7 +1057,7 @@ class RiderAppController extends ApiController
if ($rider == null)
return new APIResponse(false, 'No rider found.');
$batts = $em->getRepository(Battery::class)->findBy(['flag_active' => true]);
$batts = $em->getRepository(Battery::class)->findAll();
$models = $em->getRepository(BatteryModel::class)->findAll();
$sizes = $em->getRepository(BatterySize::class)->findAll();
@ -1217,178 +1099,7 @@ class RiderAppController extends ApiController
return new APIResponse(true, 'Batteries found.', $data);
}
public function getBatteryInfo(Request $req, $serial, EntityManagerInterface $em)
{
if (empty($serial))
{
return new APIResponse(false, 'Missing parameter(s): serial');
}
// get capi user
$capi_user = $this->getUser();
if ($capi_user == null)
return new APIResponse(false, 'User not found.');
// get rider id from capi user metadata
$rider = $this->getRiderFromCAPI($capi_user, $em);
if ($rider == null)
return new APIResponse(false, 'No rider found.');
// find battery given serial/sap_code and flag_active is true
$serial = $em->getRepository(WarrantySerial::class)->find($serial);
if (empty($serial)) {
return new APIResponse(false, 'Warranty serial number not found.');
}
$sap_battery = $em->getRepository(SAPBattery::class)->find($serial->getSKU());
if (empty($sap_battery)) {
return new APIResponse(false, 'No battery info found.');
}
$battery = [
'id' => $sap_battery->getID(),
'brand' => $sap_battery->getBrand()->getName(),
'size' => $sap_battery->getSize()->getName(),
'size_id' => $sap_battery->getSize()->getID(),
'trade_in_type' => TradeInType::MOTOLITE,
'container_size' => $sap_battery->getContainerSize()->getName(),
];
return new APIResponse(true, 'Battery info found.', [
'battery' => $battery,
]);
}
public function updateJobOrder(Request $req, EntityManagerInterface $em, InvoiceGeneratorInterface $ic, PriceTierManager $pt_manager)
{
$items = json_decode(file_get_contents('php://input'), true);
// get job order id
if (!isset($items['jo_id']))
return new APIResponse(false, 'Missing parameter(s): jo_id');
// validate jo_id
$jo_id = $items['jo_id'];
if (empty($jo_id) || $jo_id == null)
return new APIResponse(false, 'Missing parameter(s): jo_id');
// get capi user
$capi_user = $this->getUser();
if ($capi_user == null)
return new APIResponse(false, 'User not found.');
// get rider id from capi user metadata
$rider = $this->getRiderFromCAPI($capi_user, $em);
if ($rider == null)
return new APIResponse(false, 'No rider found.');
// get the job order
$jo = $em->getRepository(JobOrder::class)->find($jo_id);
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// check if we have trade in items
$ti_items = [];
if (isset($items['trade_in_items']))
{
// validate the trade in items first
$ti_items = $items['trade_in_items'];
$msg = $this->validateTradeInItems($em, $ti_items);
if (!empty($msg))
return new APIResponse(false, $msg);
}
// get the service type
if (!isset($items['stype_id']))
return new APIResponse(false, 'Missing parameter(s): stype_id');
// validate service type
$stype_id = $items['stype_id'];
if (!ServiceType::validate($stype_id))
return new APIResponse(false, 'Invalid service type - ' . $stype_id);
// save service type
$jo->setServiceType($stype_id);
// validate promo if any. Promo not required
$promo = null;
if (isset($items['promo_id']))
{
$promo_id = $items['promo_id'];
$promo = $em->getRepository(Promo::class)->find($promo_id);
if ($promo == null)
return new APIResponse(false, 'Invalid promo id - ' . $promo_id);
}
// get other parameters, if any: has motolite battery, has warranty doc, with coolant, payment method, with sealant
if (isset($items['flag_motolite_battery']))
{
// get customer vehicle from jo
$cv = $jo->getCustomerVehicle();
$has_motolite = $items['flag_motolite_battery'];
if ($has_motolite == 'true')
$cv->setHasMotoliteBattery(true);
else
$cv->setHasMotoliteBattery(false);
$em->persist($cv);
}
if (isset($items['flag_warranty_doc']))
{
// TODO: what do we do?
}
if (isset($items['flag_coolant']))
{
$has_coolant = $items['flag_coolant'];
if ($has_coolant == 'true')
$jo->setHasCoolant(true);
else
$jo->setHasCoolant(false);
}
if (isset($items['mode_of_payment']))
{
$payment_method = $items['payment_method'];
if (!ModeOfPayment::validate($payment_method))
$payment_method = ModeOfPayment::CASH;
$jo->setModeOfPayment($payment_method);
}
if (isset($items['flag_sealant']))
{
$has_sealant = $items['flag_sealant'];
if ($has_sealant == 'true')
$jo->setHasSealant(true);
else
$jo->setHasSealant(false);
}
// get capi user
$capi_user = $this->getUser();
if ($capi_user == null)
return new APIResponse(false, 'User not found.');
// get rider id from capi user metadata
$rider = $this->getRiderFromCAPI($capi_user, $em);
if ($rider == null)
return new APIResponse(false, 'No rider found.');
// need to get the existing invoice items using jo id and invoice id
$existing_ii = $this->getInvoiceItems($em, $jo);
$this->generateUpdatedInvoice($em, $ic, $jo, $existing_ii, $ti_items, $promo, $pt_manager);
$data = [];
return new APIResponse(true, 'Job order updated.', $data);
}
public function changeService(Request $req, EntityManagerInterface $em, InvoiceGeneratorInterface $ic, PriceTierManager $pt_manager)
public function changeService(Request $req, EntityManagerInterface $em, InvoiceGeneratorInterface $ic)
{
// $this->debugRequest($req);
@ -1409,11 +1120,6 @@ class RiderAppController extends ApiController
if (!empty($msg))
return new APIResponse(false, $msg);
// check if JO can be modified first
if (!$this->checkJOProgressionAllowed($em, $jo, $rider)) {
return new APIResponse(false, 'Job order can no longer be modified.');
}
// check service type
$stype_id = $req->request->get('stype_id');
if (!ServiceType::validate($stype_id))
@ -1453,13 +1159,6 @@ class RiderAppController extends ApiController
else
$jo->setHasCoolant(false);
// sealant
$flag_sealant = $req->request->get('flag_sealant', 'false');
if ($flag_sealant == 'true')
$jo->setHasSealant(true);
else
$jo->setHasSealant(false);
// has motolite battery
$cv = $jo->getCustomerVehicle();
$has_motolite = $req->request->get('has_motolite', 'false');
@ -1502,11 +1201,6 @@ class RiderAppController extends ApiController
$crit->setServiceType($stype_id);
$crit->setCustomerVehicle($cv);
$crit->setHasCoolant($jo->hasCoolant());
$crit->setIsTaxable();
// set price tier
$pt_id = $pt_manager->getPriceTier($jo->getCoordinates());
$crit->setPriceTier($pt_id);
if ($promo != null)
$crit->addPromo($promo);
@ -1546,168 +1240,6 @@ class RiderAppController extends ApiController
return new APIResponse(true, 'Job order service changed.', $data);
}
protected function generateUpdatedInvoice(EntityManagerInterface $em, InvoiceGeneratorInterface $ic, JobOrder $jo, $existing_ii, $trade_in_items, $promo, PriceTierManager $pt_manager)
{
// get the service type
$stype = $jo->getServiceType();
// get the source
$source = $jo->getSource();
// get the customer vehicle
$cv = $jo->getCustomerVehicle();
// get coolant if any
$flag_coolant = $jo->hasCoolant();
// get sealant if any
$flag_sealant = $jo->hasSealant();
// check if new promo is null
if ($promo == null)
{
// promo not updated from app so check existing invoice
// get the promo id from existing invoice item
$promo_id = $existing_ii['promo_id'];
if ($promo_id == null)
$promo = null;
else
$promo = $em->getRepository(Promo::class)->find($promo_id);
}
// populate Invoice Criteria
$icrit = new InvoiceCriteria();
$icrit->setServiceType($stype)
->setCustomerVehicle($cv)
->setSource($source)
->setHasCoolant($flag_coolant)
->setHasSealant($flag_sealant)
->setIsTaxable();
// set price tier
$pt_id = $pt_manager->getPriceTier($jo->getCoordinates());
$icrit->setPriceTier($pt_id);
// at this point, all information should be valid
// assuming JO information is already valid since this
// is in the system already
// add promo if any to criteria
if ($promo != null)
$icrit->addPromo($promo);
// get the battery purchased from existing invoice items
// add the batteries ordered to criteria
$ii_items = $existing_ii['invoice_items'];
foreach ($ii_items as $ii_item)
{
$batt_id = $ii_item['batt_id'];
$qty = $ii_item['qty'];
$battery = $em->getRepository(Battery::class)->find($batt_id);
$icrit->addEntry($battery, null, $qty);
}
// add the trade in items to the criteria
foreach ($trade_in_items as $ti_item)
{
$batt_size_id = $ti_item['battery_size_id'];
$qty = $ti_item['qty'];
$trade_in_type = $ti_item['trade_in_type'];
$batt_size = $em->getRepository(BatterySize::class)->find($batt_size_id);
$icrit->addTradeInEntry($batt_size, $trade_in_type, $qty);
}
// call generateInvoice
$invoice = $ic->generateInvoice($icrit);
// remove previous invoice
$old_invoice = $jo->getInvoice();
$em->remove($old_invoice);
$em->flush();
// save new invoice
$jo->setInvoice($invoice);
$em->persist($invoice);
// log event?
$event = new JOEvent();
$event->setDateHappen(new DateTime())
->setTypeID(JOEventType::RIDER_EDIT)
->setJobOrder($jo)
->setRider($jo->getRider());
$em->persist($event);
$em->flush();
}
protected function getInvoiceItems(EntityManagerInterface $em, JobOrder $jo)
{
$jo_id = $jo->getID();
$conn = $em->getConnection();
// need to get the ordered battery id and quantity from invoice item
// and the promo from invoice
$query_sql = 'SELECT ii.battery_id AS battery_id, ii.qty AS qty, i.promo_id AS promo_id
FROM invoice_item ii, invoice i
WHERE ii.invoice_id = i.id
AND i.job_order_id = :jo_id
AND ii.battery_id IS NOT NULL';
$query_stmt = $conn->prepare($query_sql);
$query_stmt->bindValue('jo_id', $jo_id);
$results = $query_stmt->executeQuery();
$promo_id = null;
$invoice_items = [];
while ($row = $results->fetchAssociative())
{
$promo_id = $row['promo_id'];
$invoice_items[] = [
'batt_id' => $row['battery_id'],
'qty' => $row['qty'],
'trade_in' => ''
];
}
$data = [
'promo_id' => $promo_id,
'invoice_items' => $invoice_items
];
return $data;
}
protected function validateTradeInItems(EntityManagerInterface $em, $ti_items)
{
$msg = '';
foreach ($ti_items as $ti_item)
{
$bs_id = $ti_item['battery_size_id'];
$ti_type = $ti_item['trade_in_type'];
// validate the battery size id
$batt_size = $em->getRepository(BatterySize::class)->find($bs_id);
if ($batt_size == null)
{
$msg = 'Invalid battery size for trade in: ' . $bs_id;
return $msg;
}
// validate the trade in type
if (!TradeInType::validate($ti_type))
{
$msg = 'Invalid trade in type: ' . $ti_type;
return $msg;
}
}
return $msg;
}
protected function getCAPIUser($id, EntityManagerInterface $em)
{
$capi_user = $em->getRepository(APIUser::class)->find($id);
@ -1787,42 +1319,6 @@ class RiderAppController extends ApiController
return $msg;
}
protected function checkJOProgressionAllowed(EntityManagerInterface $em, JobOrder $jo, &$rider)
{
$allowed = true;
error_log("JO delivery status is " . $jo->getDeliveryStatus() . " (not allowed: " . DeliveryStatus::CANCELLED . ")");
error_log("JO status is " . $jo->getStatus() . " (not allowed: " . JOStatus::CANCELLED . ")");
// TODO: add more statuses to block if needed, hence. this is a failsafe in case MQTT is not working.
// check delivery status
switch ($jo->getDeliveryStatus())
{
case DeliveryStatus::CANCELLED:
$allowed = false;
break;
}
// check JO status as well
switch ($jo->getStatus())
{
case JOStatus::CANCELLED:
$allowed = false;
break;
}
// if this is the rider's current JO, set to null
if (!$allowed) {
if ($rider->getCurrentJobOrder() === $jo) {
$rider->setCurrentJobOrder();
$em->persist($rider);
$em->flush();
}
}
return $allowed;
}
protected function debugRequest(Request $req)
{
$all = $req->request->all();

View file

@ -8,7 +8,7 @@ use Doctrine\ORM\Query;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Response\APIResponse;
class TestController extends ApiController
class TestController extends APIController
{
public function test()
{

View file

@ -7,13 +7,13 @@ use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Entity\Vehicle;
use App\Entity\VehicleManufacturer;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class VehicleController extends ApiController
class VehicleController extends APIController
{
protected $acl_gen;
@ -48,7 +48,7 @@ class VehicleController extends ApiController
{
$this->denyAccessUnlessGranted('vehicle.list', null, 'No access.');
$mfg = $em->getRepository(VehicleManufacturer::class)->find($mfg_id);
$mfg = $this->em->getRepository(VehicleManufacturer::class)->find($mfg_id);
// manufacturer not found
if ($mfg == null)
@ -69,9 +69,6 @@ class VehicleController extends ApiController
}
// TODO: need to add manufacturer details
$data = [
'vehicles' => $make_data,
];
return new APIResponse(true, 'Vehicles loaded.', $data);
}

View file

@ -8,7 +8,7 @@ use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Entity\Warranty;
use App\Entity\BatteryModel;
@ -36,7 +36,7 @@ use DateTime;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
// third party API
class WarrantyController extends ApiController
class WarrantyController extends APIController
{
protected $acl_gen;
@ -330,7 +330,7 @@ class WarrantyController extends ApiController
// get the api_user that made the call so that it gets added to the source
// source becomes CAPI_USER_<insert name of api user here>
$username = $this->getUser()->getName();
$username = $this->getAPIUsername($em, $user_id);
$source = 'CAPI_USER_' . $username;

View file

@ -11,7 +11,7 @@ use Doctrine\ORM\EntityManagerInterface;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Entity\WarrantySerialQueue;
@ -22,7 +22,7 @@ use DateTime;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
// third party API
class WarrantySerialController extends ApiController
class WarrantySerialController extends APIController
{
protected $acl_gen;
protected $upload_logger;

View file

@ -1,207 +0,0 @@
<?php
namespace App\Controller\CustomerAppAPI;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Translation\TranslatorInterface;
use Catalyst\ApiBundle\Component\Response as ApiResponse;
use App\Entity\CustomerDeleteRequest;
use App\Entity\Customer;
use App\Service\RisingTideGateway;
use DateTime;
class AccountController extends ApiController
{
public function deleteAccount(RisingTideGateway $rt, Request $req, TranslatorInterface $translator)
{
// validate params
$missing = $this->hasMissingParams($req, [
'phone_number',
]);
if ($missing) {
return new ApiResponse(false, $missing);
}
// user input
$phone_number = $req->request->get('phone_number');
$reason = $req->request->get('reason');
// use the test code if we're using a test number or are on test mode
$code = $this->getConfirmCode($phone_number);
$success_msg = 'We have sent a confirmation code to the submitted phone number if it is valid.';
// initialize model
$obj = new CustomerDeleteRequest();
// check if a customer record exists for this phone number
$cust_obj = $this->findCustomerByNumber($phone_number);
if (empty($cust_obj)) {
// return a random id anyway if we don't find this customer
return new ApiResponse(true, $success_msg, [
'request_id' => $obj->getID(),
]);
}
// phone number is valid, we continue building the model
$obj->setPhoneNumber($phone_number);
$obj->setReason($reason);
$obj->setConfirmCode($code);
// send sms to number if not in test mode
if ($this->getOtpMode() != 'test') {
$this->sendConfirmationCode($rt, $phone_number, $code, $translator);
}
// save the model
$obj->setDateCodeSent(new DateTime());
$this->em->persist($obj);
$this->em->flush();
// response
return new ApiResponse(true, $success_msg, [
'request_id' => $obj->getID(),
]);
}
public function validateDeleteCode(Request $req)
{
// validate params
$missing = $this->hasMissingParams($req, [
'request_id',
'code',
]);
if ($missing) {
return new ApiResponse(false, $missing);
}
// user input
$code = $req->request->get('code');
$request_id = $req->request->get('request_id');
// get the request
$obj = $this->em->getRepository(CustomerDeleteRequest::class)->findOneBy([
'id' => $request_id,
'confirm_code' => $code,
'flag_confirmed' => false,
'flag_completed' => false,
]);
if (empty($obj)) {
return new ApiResponse(false, 'Your confirmation code is invalid.');
}
// check if a customer record exists for this phone number
$cust_obj = $this->findCustomerByNumber($obj->getPhoneNumber());
if (empty($cust_obj)) {
return new ApiResponse(false, 'No account exists for this phone number.');
}
// confirm the request
$obj->setConfirmed(true);
$obj->setDateConfirmed(new DateTime());
$obj->setCustomer($cust_obj);
$this->em->flush();
// response
return new ApiResponse(true, 'Your request has been submitted for processing.');
}
public function resendCode(Request $req, RisingTideGateway $rt, TranslatorInterface $translator)
{
// validate params
$missing = $this->hasMissingParams($req, [
'request_id',
]);
if ($missing) {
return new ApiResponse(false, $missing);
}
// user input
$request_id = $req->request->get('request_id');
$now = time();
// get the request
$obj = $this->em->getRepository(CustomerDeleteRequest::class)->findOneBy([
'id' => $request_id,
'flag_confirmed' => false,
'flag_completed' => false,
]);
if (empty($obj)) {
return new ApiResponse(false, 'Invalid request details provided.');
}
// prevent resend spamming
if ($now - $obj->getDateCodeSent()->getTimestamp() < 300) {
return new ApiResponse(false, 'You can only request a confirm code every 5 mins.');
}
$success_msg = 'We have re-sent a confirmation code to the submitted phone number if it is valid.';
// check if a customer record exists for this phone number
$cust_obj = $this->findCustomerByNumber($obj->getPhoneNumber());
if (empty($cust_obj)) {
// return successful without resending code if we don't find this customer
return new ApiResponse(true, $success_msg);
}
// use the test code if we're using a test number or are on test mode
$phone_number = $obj->getPhoneNumber();
$code = $this->getConfirmCode($phone_number);
// send sms to number if not in test mode
if ($this->getOtpMode()!= 'test') {
$this->sendConfirmationCode($rt, $phone_number, $code, $translator);
}
// update last sent timestamp
$obj->setDateCodeSent(new DateTime());
$this->em->flush();
// response
return new ApiResponse(true, $success_msg);
}
protected function getConfirmCode($phone_number)
{
// check for hardcoded phone number for app store testing
$test_numbers = explode(",", $_ENV['TEST_PHONE_NUMBERS']);
if (in_array($phone_number, $test_numbers) || $this->getOtpMode() == 'test') {
$code = "123456";
} else {
// generate code
$code = $this->generateConfirmCode();
}
return $code;
}
protected function generateConfirmCode()
{
return sprintf("%06d", mt_rand(100000, 999999));
}
protected function sendConfirmationCode(RisingTideGateway $rt, $phone_number, $code, TranslatorInterface $translator)
{
// send sms to number
$message = $translator->trans('message.confirmation_code') . ' ' . $code;
$rt->sendSMS($phone_number, $translator->trans('message.battery_brand_allcaps'), $message);
}
protected function findCustomerByNumber($number)
{
$cust_obj = $this->em->getRepository(Customer::class)->findOneBy([
'phone_mobile' => $number,
]);
return $cust_obj;
}
protected function getOtpMode()
{
return $_ENV['OTP_MODE'];
}
}

View file

@ -144,7 +144,6 @@ class ApiController extends BaseApiController
{
// TODO: workaround for now, we get static image of battery based on model name
$filename = trim(strtolower($batt->getModel()->getName())) . '_mobile.jpg';
$filename = str_replace(" ", "_", $filename);
$file_path = $req->getSchemeAndHttpHost() . $this->generateUrl('static_battery_image') . '/' . $filename;
return $file_path;
@ -162,6 +161,6 @@ class ApiController extends BaseApiController
protected function getGeoErrorMessage()
{
return 'Our services are currently limited to some areas in Metro Manila, Baguio, Batangas, Laguna, Cavite, Pampanga, and Palawan. We will update you as soon as we are available in your area. Thank you for understanding. Keep safe!';
return 'Oops! Our service is limited to some areas in Metro Manila, Laguna, Cavite, Pampanga and Baguio only. We will update you as soon as we are able to cover your area';
}
}

View file

@ -12,7 +12,6 @@ class AppController extends ApiController
// validate params
$missing = $this->hasMissingParams($req, [
'version',
'os',
]);
if ($missing) {
@ -22,23 +21,21 @@ class AppController extends ApiController
$need_update = false;
$msg = 'Version is up to date.';
$os = $req->query->get('os');
$api_version = $this->getParameter('api_version');
// putting this in for the future, in case we have diverging versions
//$platform = $req->query->get('platform');
// get only the major version numbers
$app_version = $req->query->get('version');
$app_major = substr($app_version, 0, strripos($app_version, "."));
// putting this in for the future, in case we have diverging versions
$os = $req->query->get('os');
$platform = $req->query->get('platform');
$latest_version = $this->getParameter($os . '_app_version');
$latest_major = substr($latest_version, 0, strripos($latest_version, "."));
$api_v = explode('.', $api_version);
$app_v = explode('.', $app_version);
if ($latest_major < $app_major) {
if ($api_v[0] < $app_v[0]) {
return new ApiResponse(false, 'Invalid application version: ' . $app_version);
}
if ($latest_major > $app_major) {
if ($api_v[0] > $app_v[0]) {
$need_update = true;
$msg = 'Your version is outdated and needs an update to use the latest features RES-Q has to offer.';
}
@ -46,7 +43,6 @@ class AppController extends ApiController
// response
return new ApiResponse(true, '', [
'need_update' => $need_update,
'latest_version' => $latest_version,
'message' => $msg,
]);
}

View file

@ -85,9 +85,7 @@ class AuthController extends ApiController
$otp_mode = $_ENV['OTP_MODE'];
// check for hardcoded phone number for app store testing
$test_numbers = explode(",", $_ENV['TEST_PHONE_NUMBERS']);
if (in_array($phone_number, $test_numbers)) {
if ($phone_number == '639221111111') {
$code = '123456';
$this->session->setConfirmCode($code)
->setPhoneNumber($phone_number);

View file

@ -1,364 +0,0 @@
<?php
namespace App\Controller\CustomerAppAPI;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Catalyst\ApiBundle\Component\Response as ApiResponse;
use App\Service\InsuranceConnector;
use App\Service\PayMongoConnector;
use App\Entity\InsuranceApplication;
use App\Entity\GatewayTransaction;
use App\Entity\CustomerVehicle;
use App\Ramcar\InsuranceApplicationStatus;
use App\Ramcar\InsuranceMVType;
use App\Ramcar\InsuranceClientType;
use App\Ramcar\TransactionStatus;
use App\Ramcar\InsuranceBodyType;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use DateTime;
class InsuranceController extends ApiController
{
protected $client;
public function __construct(EntityManagerInterface $em, KernelInterface $kernel, InsuranceConnector $client)
{
parent::__construct($em, $kernel);
$this->client = $client;
}
public function createApplication(Request $req, PayMongoConnector $paymongo, UrlGeneratorInterface $router)
{
// validate params
$validity = $this->validateRequest($req, [
// internal
'customer_vehicle_id',
// client info
'client_type',
'first_name',
//'middle_name', // not required
'surname',
'corporate_name',
// client contact info
'address_number',
//'address_street', // not required
//'address_building', // not required
'address_barangay',
'address_city',
'address_province',
'zipcode',
'mobile_number',
'email_address',
// car info
'make',
'model',
'series',
'color',
//'plate_number', // NOTE: we get this from the internal cv record instead
'mv_file_number',
'motor_number',
'serial_chasis', // NOTE: this is how it's spelled on their API
'year_model',
'mv_type_id',
'body_type',
//'is_public', // not required, boolean, only show field if mv_type_id in [4, 13]
//'orcr_file', // this is a file
// mv_type_id specific fields
//'vehicle_use_type', // not required, only show field if mv_type_id is not in [4, 13]. accepted values are: 'commercial', 'private'
]);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
// conditionally require is_public or vehicle_use_type
switch ($req->request->get('mv_type_id')) {
case 4:
case 13:
if (empty($req->request->get('is_public'))) {
return new ApiResponse(false, 'Missing required parameter(s): is_public is required when mv_type_id is in [4, 13]');
}
break;
default:
if (empty($req->request->get('vehicle_use_type'))) {
return new ApiResponse(false, 'Missing required parameter(s): vehicle_use_type is required when mv_type_id is not in [4, 13]');
}
break;
}
// require the orcr file
if ($req->files->get('orcr_file') === null) {
return new ApiResponse(false, 'Missing required file: orcr_file');
}
// get our listener url
$notif_url = $router->generate('insurance_listener', [], UrlGeneratorInterface::ABSOLUTE_URL);
// get customer and cv info
$cust = $this->session->getCustomer();
$cv = $this->em->getRepository(CustomerVehicle::class)->find($req->request->get('customer_vehicle_id'));
if ($cv == null) {
return new ApiResponse(false, 'Invalid customer vehicle id.');
}
// confirm that customer vehicle belongs to customer
if ($cv->getCustomer()->getID() != $cust->getID()) {
return new ApiResponse(false, 'Vehicle does not belong to customer.');
}
// process all our inputs first
$input = $req->request->all();
if (!isset($input['is_public'])) {
$input['is_public'] = false;
}
$input['line'] = $this->getLineType($input['mv_type_id'], $input['vehicle_use_type'], $input['is_public']);
// submit insurance application
$result = $this->client->createApplication(
$cv,
$notif_url,
$input,
$req->files->get('orcr_file')
);
if (!$result['success']) {
return new ApiResponse(false, $result['error']['message']);
}
$premium_amount_int = (int)bcmul($result['response']['premium'], 100);
// build checkout item and metadata
$items = [
[
'name' => "Insurance Premium",
'description' => "Premium fee for vehicle insurance",
'quantity' => 1,
'amount' => $premium_amount_int,
'currency' => 'PHP',
],
];
$now = new DateTime();
// create gateway transaction
$gt = new GatewayTransaction();
$gt->setCustomer($cust);
$gt->setDateCreate($now);
$gt->setAmount($premium_amount_int);
$gt->setStatus(TransactionStatus::PENDING);
$gt->setGateway('paymongo'); // TODO: define values elsewhere
$gt->setType('insurance_premium'); // TODO: define values elsewhere
$this->em->persist($gt);
$this->em->flush();
// create paymongo checkout resource
$checkout = $paymongo->createCheckout(
$cust,
$items,
$gt->getID(),
"Motolite RES-Q Vehicle Insurance",
$router->generate('paymongo_payment_success', [], UrlGeneratorInterface::ABSOLUTE_URL),
$router->generate('paymongo_payment_cancelled', [], UrlGeneratorInterface::ABSOLUTE_URL),
['transaction_id' => $gt->getID()], // NOTE: passing this here too for payment resource metadata
);
if (!$checkout['success']) {
return new ApiResponse(false, $checkout['error']['message']);
}
$checkout_url = $checkout['response']['data']['attributes']['checkout_url'];
// add checkout url and id to transaction metadata
$gt->setExtTransactionId($checkout['response']['data']['id']);
$gt->setMetadata([
'checkout_url' => $checkout_url,
]);
// store application in db
$app = new InsuranceApplication();
$app->setDateSubmit($now);
$app->setCustomer($cust);
$app->setCustomerVehicle($cv);
$app->setGatewayTransaction($gt);
$app->setStatus(InsuranceApplicationStatus::CREATED);
$app->setExtTransactionId($result['response']['id']);
$app->setMetadata($input);
$this->em->persist($app);
// save everything
$this->em->flush();
// return
return new ApiResponse(true, '', [
'app_id' => $app->getID(),
'checkout_url' => $checkout_url,
'premium_amount' => (string)$result['response']['premium'],
]);
}
public function getVehicleMakers(Request $req)
{
// validate params
$validity = $this->validateRequest($req);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
// get maker list
$result = $this->client->getVehicleMakers();
if (!$result['success']) {
return new ApiResponse(false, $result['error']['message']);
}
return new ApiResponse(true, '', [
'makers' => $result['response']['data']['vehicleMakers'],
]);
}
public function getVehicleModels($maker_id, Request $req)
{
// validate params
$validity = $this->validateRequest($req);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
// get maker list
$result = $this->client->getVehicleModels($maker_id);
if (!$result['success']) {
return new ApiResponse(false, $result['error']['message']);
}
return new ApiResponse(true, '', [
'models' => $result['response']['data']['vehicleModels'],
]);
}
public function getVehicleTrims($model_id, Request $req)
{
// validate params
$validity = $this->validateRequest($req);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
// get maker list
$result = $this->client->getVehicleTrims($model_id);
if (!$result['success']) {
return new ApiResponse(false, $result['error']['message']);
}
return new ApiResponse(true, '', [
'trims' => $result['response']['data']['vehicleTrims'],
]);
}
public function getMVTypes(Request $req)
{
// validate params
$validity = $this->validateRequest($req);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
return new ApiResponse(true, '', [
'mv_types' => InsuranceMVType::getCollection(),
]);
}
public function getClientTypes(Request $req)
{
// validate params
$validity = $this->validateRequest($req);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
return new ApiResponse(true, '', [
'mv_types' => InsuranceClientType::getCollection(),
]);
}
public function getPremiumsBanner(Request $req)
{
// validate params
$validity = $this->validateRequest($req);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
return new ApiResponse(true, '', [
'url' => $this->getParameter('insurance_premiums_banner_url'),
]);
}
public function getBodyTypes(Request $req)
{
// validate params
$validity = $this->validateRequest($req);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
$bt_collection = InsuranceBodyType::getCollection();
$body_types = [];
// NOTE: formatting it this way to match how insurance third party API returns their own stuff, so it's all handled one way on the app
foreach ($bt_collection as $bt_key => $bt_name) {
$body_types[] = [
'id' => $bt_key,
'name' => $bt_name,
];
}
return new ApiResponse(true, '', [
'body_types' => $body_types,
]);
}
protected function getLineType($mv_type_id, $vehicle_use_type, $is_public = false)
{
$line = '';
// NOTE: this is a bit of a hack since we're hardcoding values, but this is fine for now
switch ($mv_type_id) {
case '3':
$line = 'mcoc';
break;
case '4':
case '13':
if ($is_public) {
$line = 'lcoc';
} else {
$line = 'mcoc';
}
break;
default:
if ($vehicle_use_type === 'commercial') {
$line = 'ccoc';
} else {
$line = 'pcoc';
}
break;
}
return $line;
}
}

View file

@ -4,23 +4,17 @@ namespace App\Controller\CustomerAppAPI;
use Symfony\Component\HttpFoundation\Request;
use Catalyst\ApiBundle\Component\Response as ApiResponse;
use CrEOF\Spatial\PHP\Types\Geometry\Point;
use App\Service\InvoiceGeneratorInterface;
use App\Service\PriceTierManager;
use App\Ramcar\InvoiceCriteria;
use App\Ramcar\TradeInType;
use App\Ramcar\TransactionOrigin;
use App\Entity\CustomerVehicle;
use App\Entity\Promo;
use App\Entity\Battery;
use App\Entity\BatterySize;
use App\Entity\Customer;
use App\Entity\CustomerMetadata;
class InvoiceController extends ApiController
{
public function getEstimate(Request $req, InvoiceGeneratorInterface $ic, PriceTierManager $pt_manager)
public function getEstimate(Request $req, InvoiceGeneratorInterface $ic)
{
// $this->debugRequest($req);
@ -29,6 +23,7 @@ class InvoiceController extends ApiController
'service_type',
'cv_id',
// 'batt_id',
'trade_in',
]);
if (!$validity['is_valid']) {
@ -41,18 +36,6 @@ class InvoiceController extends ApiController
return new ApiResponse(false, 'No customer information found.');
}
// get customer location from customer_metadata using customer id
$lng = $req->request->get('longitude');
$lat = $req->request->get('latitude');
if ((empty($lng)) || (empty($lat)))
{
// use customer metadata location as basis
$coordinates = $this->getCustomerMetadata($cust);
}
else
$coordinates = new Point($lng, $lat);
// make invoice criteria
$icrit = new InvoiceCriteria();
$icrit->setServiceType($req->request->get('service_type'));
@ -98,50 +81,18 @@ class InvoiceController extends ApiController
// check trade-in
// only allow motolite, other, none
$trade_in_batt = $req->request->get('trade_in_batt');
$trade_in_type = $req->request->get('trade_in_type');
switch ($trade_in_type) {
$trade_in = $req->request->get('trade_in');
switch ($trade_in) {
case TradeInType::MOTOLITE:
case TradeInType::OTHER:
break;
default:
$trade_in_type = '';
$trade_in = '';
break;
}
// add the actual battery item first
$icrit->addEntry($batt, null, 1);
// DEBUG
// if we have a trade in, add it as well
if (!empty($trade_in_type) && !empty($trade_in_batt)) {
$ti_batt_obj = $this->em->getRepository(Battery::class)->find($trade_in_batt);
if (!empty($ti_batt_obj)) {
$ti_batt_size_obj = $ti_batt_obj->getSize();
$icrit->addTradeInEntry($ti_batt_size_obj, $trade_in_type, 1);
}
}
// set if taxable
$icrit->setIsTaxable();
// set JO source
$icrit->setSource(TransactionOrigin::MOBILE_APP);
// set price tier
$pt_id = 0;
if ($coordinates != null)
{
error_log('coordinates are not null');
$pt_id = $pt_manager->getPriceTier($coordinates);
}
else
error_log('null?');
$icrit->setPriceTier($pt_id);
$icrit->addEntry($batt, $trade_in, 1);
// send to invoice generator
$invoice = $ic->generateInvoice($icrit);
@ -178,28 +129,4 @@ class InvoiceController extends ApiController
// response
return new ApiResponse(true, '', $data);
}
protected function getCustomerMetadata(Customer $cust)
{
$coordinates = null;
// check if customer already has existing metadata
$c_meta = $this->em->getRepository(CustomerMetadata::class)->findOneBy(['customer' => $cust]);
if ($c_meta != null)
{
$meta_data = $c_meta->getAllMetaInfo();
foreach ($meta_data as $m_info)
{
if ((isset($m_info['longitude'])) && (isset($m_info['latitude'])))
{
$lng = $m_info['longitude'];
$lat = $m_info['latitude'];
$coordinates = new Point($lng, $lat);
}
}
}
return $coordinates;
}
}

View file

@ -20,8 +20,6 @@ use App\Service\HubSelector;
use App\Service\HubDistributor;
use App\Service\HubFilterLogger;
use App\Service\HubFilteringGeoChecker;
use App\Service\JobOrderManager;
use App\Service\PriceTierManager;
use App\Ramcar\ServiceType;
use App\Ramcar\APIRiderStatus;
use App\Ramcar\InvoiceCriteria;
@ -35,7 +33,6 @@ use App\Ramcar\WarrantyClass;
use App\Ramcar\HubCriteria;
use App\Ramcar\DeliveryStatus;
use App\Entity\Battery;
use App\Entity\BatterySize;
use App\Entity\Hub;
use App\Entity\Promo;
use App\Entity\JOEvent;
@ -485,16 +482,13 @@ class JobOrderController extends ApiController
HubSelector $hub_select,
HubDistributor $hub_dist,
HubFilterLogger $hub_filter_logger,
HubFilteringGeoChecker $hub_geofence,
JobOrderManager $jo_manager,
PriceTierManager $pt_manager
HubFilteringGeoChecker $hub_geofence
) {
//error_log("CREATING JOB ORDER WITH PARAMS " . print_r($req->request->all(), true));
// validate params
$validity = $this->validateRequest($req, [
'service_type',
'cv_id',
'trade_in',
'long',
'lat',
'warranty',
@ -506,8 +500,7 @@ class JobOrderController extends ApiController
}
// trade in type
$trade_in_batt = $req->request->get('trade_in_batt');
$trade_in_type = $req->request->get('trade_in_type', '');
$trade_in = $req->request->get('trade_in');
// address
$address = $req->request->get('delivery_address', 'Set by mobile application');
@ -578,8 +571,6 @@ class JobOrderController extends ApiController
$flag_advance_order = true;
// $flag_advance_order = $advance_order ? true : false;
//error_log("RUNNING QUERY NEXT");
$jo = new JobOrder();
$jo->setSource(TransactionOrigin::MOBILE_APP)
->setStatus(JOStatus::PENDING)
@ -587,7 +578,7 @@ class JobOrderController extends ApiController
->setTier1Notes('')
->setTier2Notes('')
->setDeliveryAddress($address)
->setTradeInType($trade_in_type)
->setTradeInType($trade_in)
->setDeliveryInstructions($instructions)
// TODO: error check for valid mode of payment
->setModeOfPayment($req->request->get('mode_of_payment'))
@ -603,16 +594,7 @@ class JobOrderController extends ApiController
// ->setErrorMessage('No customer information found');
// return $res->getReturnResponse();
// }
// check if customer has more than one job order already
$flag_cust_new = false;
$cust_jo_count = $jo_manager->getCustomerJobOrderCount($cust->getID());
if ($cust_jo_count <= 1)
$flag_cust_new = true;
$jo->setCustomer($cust);
$jo->setCustNew($flag_cust_new);
// validate service type
$stype = $req->request->get('service_type');
@ -648,8 +630,6 @@ class JobOrderController extends ApiController
$icrit->addPromo($promo);
}
//error_log("CONTINUING QUERY BUILDING");
// check customer vehicle
$cv = $this->em->getRepository(CustomerVehicle::class)->find($req->request->get('cv_id'));
if ($cv == null) {
@ -680,66 +660,29 @@ class JobOrderController extends ApiController
// check trade-in
// only allow motolite, other, none
switch ($trade_in_type) {
switch ($trade_in) {
case TradeInType::MOTOLITE:
case TradeInType::OTHER:
break;
default:
$trade_in_type = '';
$trade_in = '';
break;
}
// add the actual battery item first
$icrit->addEntry($batt, null, 1);
// if we have a trade in, add it as well
if (!empty($trade_in_type) && !empty($trade_in_batt)) {
$ti_batt_obj = $this->em->getRepository(Battery::class)->find($trade_in_batt);
if (!empty($ti_batt_obj)) {
$ti_batt_size_obj = $ti_batt_obj->getSize();
$icrit->addTradeInEntry($ti_batt_size_obj, $trade_in_type, 1);
}
}
// set taxable
$icrit->setIsTaxable();
// set JO source
$icrit->setSource(TransactionOrigin::MOBILE_APP);
// set price tier
$pt_id = $pt_manager->getPriceTier($jo->getCoordinates());
$icrit->setPriceTier($pt_id);
$icrit->addEntry($batt, $trade_in, 1);
// send to invoice generator
$invoice = $ic->generateInvoice($icrit);
$jo->setInvoice($invoice);
//error_log("GENERATED INVOICE");
// save here first so we have a JO ID which is required for the hub selector
$this->em->persist($invoice);
$this->em->persist($jo);
$this->em->flush();
// assign hub and rider
// check if hub is null
if ($hub == null) {
//error_log("NO HUB");
// TODO: need to factor out the setting of HubCriteria fields
$hub_criteria = new HubCriteria();
$hub_criteria->setPoint($jo->getCoordinates());
// set job order info
$hub_criteria->setJobOrderId($jo->getID())
->setJoType($jo->getServiceType())
->setJoOrigin($jo->getSource())
->setCustomerClass($cust->getCustomerClassification())
->setOrderDate($jo->getDateCreate())
->setServiceType($jo->getServiceType());
// get distance limit for mobile from env
// get value of hub_filter_enable from env
$limit_distance = $_ENV['CUST_DISTANCE_LIMIT'];
@ -777,10 +720,6 @@ class JobOrderController extends ApiController
$hub_criteria->setCustomerId($customer_id);
// set filter flags for inventory and available riders
$hub_criteria->setInventoryCheck();
$hub_criteria->setRidersCheck();
// find nearest hubs
$nearest_hubs = $hub_select->find($hub_criteria);
@ -859,8 +798,6 @@ class JobOrderController extends ApiController
}
}
} else {
//error_log("HAS HUB: " . $hub->getID());
$jo->setHub($hub);
$jo->setStatus(JOStatus::RIDER_ASSIGN);
$jo->setStatusAutoAssign(AutoAssignStatus::HUB_ASSIGNED);
@ -872,10 +809,8 @@ class JobOrderController extends ApiController
$hub_dist->incrementJoCountForHub($hub);
}
//error_log("DONE SELECTING HUB");
// save additional hub related changes
$this->em->persist($jo);
$this->em->persist($invoice);
// add event log for JO
$event = new JOEvent();
@ -986,8 +921,6 @@ class JobOrderController extends ApiController
}
}
//error_log("DONE CREATING JOB ORDER " . $jo->getID());
// response
return new ApiResponse(true, '', [
'jo_id' => $jo->getID(),
@ -1010,15 +943,14 @@ class JobOrderController extends ApiController
HubSelector $hub_select,
HubDistributor $hub_dist,
HubFilterLogger $hub_filter_logger,
HubFilteringGeoChecker $hub_geofence,
JobOrderManager $jo_manager,
PriceTierManager $pt_manager
HubFilteringGeoChecker $hub_geofence
) {
// validate params
$validity = $this->validateRequest($req, [
'service_type',
'cv_id',
// 'batt_id',
'trade_in',
'long',
'lat',
'warranty',
@ -1030,8 +962,7 @@ class JobOrderController extends ApiController
}
// trade in type
$trade_in_batt = $req->request->get('trade_in_batt');
$trade_in_type = $req->request->get('trade_in_type', '');
$trade_in = $req->request->get('trade_in');
// address
$address = $req->request->get('delivery_address', 'Set by mobile application');
@ -1057,7 +988,7 @@ class JobOrderController extends ApiController
->setTier1Notes('')
->setTier2Notes('')
->setDeliveryAddress($address)
->setTradeInType($trade_in_type)
->setTradeInType($trade_in)
->setDeliveryInstructions($instructions)
// TODO: error check for valid mode of payment
->setModeOfPayment($req->request->get('mode_of_payment'));
@ -1067,16 +998,7 @@ class JobOrderController extends ApiController
if ($cust == null) {
return new ApiResponse(false, 'No customer information found.');
}
// check if customer has more than one job order already
$flag_cust_new = false;
$cust_jo_count = $jo_manager->getCustomerJobOrderCount($cust->getID());
if ($cust_jo_count <= 1)
$flag_cust_new = true;
$jo->setCustomer($cust);
$jo->setCustNew($flag_cust_new);
// validate service type
$stype = $req->request->get('service_type');
@ -1142,37 +1064,17 @@ class JobOrderController extends ApiController
// check trade-in
// only allow motolite, other, none
switch ($trade_in_type) {
switch ($trade_in) {
case TradeInType::MOTOLITE:
case TradeInType::OTHER:
break;
default:
$trade_in_type = '';
$trade_in = '';
break;
}
// add the actual battery item first
$icrit->addEntry($batt, null, 1);
// if we have a trade in, add it as well
if (!empty($trade_in_type) && !empty($trade_in_batt)) {
$ti_batt_obj = $this->em->getRepository(Battery::class)->find($trade_in_batt);
if (!empty($ti_batt_obj)) {
$battery_size = $ti_batt_obj->getSize();
$icrit->addTradeInEntry($battery_size, $trade_in_type, 1);
}
}
// set taxable
$icrit->setIsTaxable();
// set JO source
$icrit->setSource(TransactionOrigin::MOBILE_APP);
// set price tier
$pt_id = $pt_manager->getPriceTier($jo->getCoordinates());
$icrit->setPriceTier($pt_id);
$icrit->addEntry($batt, $trade_in, 1);
// send to invoice generator
$invoice = $ic->generateInvoice($icrit);

View file

@ -4,19 +4,11 @@ namespace App\Controller\CustomerAppAPI;
use Symfony\Component\HttpFoundation\Request;
use Catalyst\ApiBundle\Component\Response as ApiResponse;
use CrEOF\Spatial\PHP\Types\Geometry\Point;
use App\Entity\CustomerVehicle;
use App\Entity\JobOrder;
use App\Entity\VehicleManufacturer;
use App\Entity\Vehicle;
use App\Entity\ItemType;
use App\Ramcar\JOStatus;
use App\Ramcar\ServiceType;
use App\Ramcar\TradeInType;
use App\Ramcar\InsuranceApplicationStatus;
use App\Service\PayMongoConnector;
use App\Service\PriceTierManager;
use DateTime;
class VehicleController extends ApiController
@ -115,34 +107,6 @@ class VehicleController extends ApiController
}
public function getVehicle(Request $req, $id, PayMongoConnector $paymongo)
{
// check requirements
$validity = $this->validateRequest($req);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
// get customer vehicle
$cv = $this->em->getRepository(CustomerVehicle::class)->find($id);
// check if it exists
if ($cv == null) {
return new ApiResponse(false, 'Vehicle does not exist.');
}
// check if it's owned by customer
if ($cv->getCustomer()->getID() != $this->session->getCustomer()->getID()) {
return new ApiResponse(false, 'Invalid vehicle.');
}
// response
return new ApiResponse(true, '', [
'vehicle' => $this->generateVehicleInfo($cv, true, $paymongo),
]);
}
public function updateVehicle(Request $req, $id)
{
// check requirements
@ -177,40 +141,7 @@ class VehicleController extends ApiController
]);
}
public function getTradeInEstimate(Request $req, $id)
{
// check requirements
$validity = $this->validateRequest($req);
if (!$validity['is_valid']) {
return new ApiResponse(false, $validity['error']);
}
// get customer vehicle
$cv = $this->em->getRepository(CustomerVehicle::class)->find($id);
// check if it exists
if ($cv == null) {
return new ApiResponse(false, 'Vehicle does not exist.');
}
// check if it's owned by customer
if ($cv->getCustomer()->getID() != $this->session->getCustomer()->getID()) {
return new ApiResponse(false, 'Invalid vehicle.');
}
// check trade in value
$result = $this->getTIEstimateByCV($cv);
// response
return new ApiResponse(true, '', [
'trade_in_batt' => $result['trade_in_batt'],
'trade_in_type' => $result['trade_in_type'],
'trade_in_value' => $result['trade_in_value'],
]);
}
public function listVehicles(Request $req, PayMongoConnector $paymongo)
public function listVehicles(Request $req)
{
// validate params
$validity = $this->validateRequest($req);
@ -231,7 +162,37 @@ class VehicleController extends ApiController
// only get the customer's vehicles whose flag_active is true
$cvs = $this->em->getRepository(CustomerVehicle::class)->findBy(['flag_active' => true, 'customer' => $cust]);
foreach ($cvs as $cv) {
$cv_list[] = $this->generateVehicleInfo($cv, true, $paymongo);
$battery_id = null;
if ($cv->getCurrentBattery() != null)
$battery_id = $cv->getCurrentBattery()->getID();
$wty_ex = null;
if ($cv->getWarrantyExpiration() != null)
$wty_ex = $cv->getWarrantyExpiration()->format('Y-m-d');
$warranty = $this->findWarranty($cv->getPlateNumber());
$cv_name = '';
if ($cv->getName() != null)
$cv_name = $cv->getName();
$cv_list[] = [
'cv_id' => $cv->getID(),
'mfg_id' => $cv->getVehicle()->getManufacturer()->getID(),
'make_id' => $cv->getVehicle()->getID(),
'name' => $cv_name,
'plate_num' => $cv->getPlateNumber(),
'model_year' => $cv->getModelYear(),
'color' => $cv->getColor(),
'condition' => $cv->getStatusCondition(),
'fuel_type' => $cv->getFuelType(),
'wty_code' => $cv->getWarrantyCode(),
'wty_expire' => $wty_ex,
'curr_batt_id' => $battery_id,
'is_motolite' => $cv->hasMotoliteBattery() ? 1 : 0,
'is_active' => $cv->isActive() ? 1 : 0,
'warranty' => $warranty,
];
}
// response
@ -240,7 +201,7 @@ class VehicleController extends ApiController
]);
}
public function getCompatibleBatteries(Request $req, $vid, PriceTierManager $pt_manager)
public function getCompatibleBatteries(Request $req, $vid)
{
// validate params
$validity = $this->validateRequest($req);
@ -255,43 +216,11 @@ class VehicleController extends ApiController
return new ApiResponse(false, 'Invalid vehicle.');
}
// get location from request
$lng = $req->query->get('longitude', '');
$lat = $req->query->get('latitude', '');
$batts = $vehicle->getActiveBatteries();
$pt_id = 0;
if ((!(empty($lng))) && (!(empty($lat))))
{
// get the price tier
$coordinates = new Point($lng, $lat);
$pt_id = $pt_manager->getPriceTier($coordinates);
}
// batteries
$batt_list = [];
$batts = $vehicle->getBatteries();
foreach ($batts as $batt) {
// TODO: Add warranty_tnv to battery information
// check if customer location is in a price tier location
if ($pt_id == 0)
$price = $batt->getSellingPrice();
else
{
// get item type for battery
$item_type = $this->em->getRepository(ItemType::class)->findOneBy(['code' => 'battery']);
if ($item_type == null)
$price = $batt->getSellingPrice();
else
{
$item_type_id = $item_type->getID();
$batt_id = $batt->getID();
// find the item price given price tier id and battery id
$price = $pt_manager->getItemPrice($pt_id, $item_type_id, $batt_id);
}
}
$batt_list[] = [
'id' => $batt->getID(),
'mfg_id' => $batt->getManufacturer()->getID(),
@ -300,7 +229,7 @@ class VehicleController extends ApiController
'model_name' => $batt->getModel()->getName(),
'size_id' => $batt->getSize()->getID(),
'size_name' => $batt->getSize()->getName(),
'price' => $price,
'price' => $batt->getSellingPrice(),
'wty_private' => $batt->getWarrantyPrivate(),
'wty_commercial' => $batt->getWarrantyCommercial(),
'image_url' => $this->getBatteryImageURL($req, $batt),
@ -355,159 +284,6 @@ class VehicleController extends ApiController
// response
return new ApiResponse();
}
protected function getTIEstimateByCV($cv)
{
// compute for trade in value
$trade_in_batt = null;
$trade_in_value = 0;
$trade_in_type = TradeInType::OTHER;
$previous_jo_found = false;
// check for last battery replacement JO
$last_jo = $this->em->getRepository(JobOrder::class)->findOneBy([
'service_type' => [
ServiceType::BATTERY_REPLACEMENT_NEW, ServiceType::BATTERY_REPLACEMENT_WARRANTY
],
'status' => JOStatus::FULFILLED,
'cus_vehicle' => $cv,
], ['date_create' => 'desc']);
if (!empty($last_jo)) {
$items = $last_jo->getInvoice()->getItems();
foreach ($items as $item) {
// find the first battery item and get its trade-in value
$item_battery = $item->getBattery();
if (!empty($item_battery)) {
$trade_in_type = TradeInType::MOTOLITE;
$trade_in_batt = $item_battery->getID();
$previous_jo_found = true;
$size = $item_battery->getSize();
$trade_in_value = $size->getTIPriceMotolite();
break;
}
}
}
// TODO: possibly refactor this bit
// if no valid previous JO is found, base the trade-in value on recommended batteries
if (!$previous_jo_found) {
$comp_batteries = $cv->getVehicle()->getBatteries();
// get the lowest trade-in value from the list of batteries
if (!empty($comp_batteries)) {
foreach ($comp_batteries as $battery) {
$size = $battery->getSize();
$size_ti = $size->getTIPriceOther();
// get the lowest value or set if not set yet
if ($size_ti < $trade_in_value || $trade_in_value == 0) {
$trade_in_value = $size_ti;
$trade_in_batt = $battery->getID();
}
}
}
}
return [
'trade_in_batt' => $trade_in_batt,
'trade_in_type' => $trade_in_type,
'trade_in_value' => $trade_in_value,
];
}
protected function generateVehicleInfo(CustomerVehicle $cv, $include_insurance = false, PayMongoConnector $paymongo)
{
$battery_id = null;
if ($cv->getCurrentBattery() != null)
$battery_id = $cv->getCurrentBattery()->getID();
$wty_ex = null;
if ($cv->getWarrantyExpiration() != null)
$wty_ex = $cv->getWarrantyExpiration()->format('Y-m-d');
$warranty = $this->findWarranty($cv->getPlateNumber());
$cv_name = '';
if ($cv->getName() != null)
$cv_name = $cv->getName();
$row = [
'cv_id' => $cv->getID(),
'mfg_id' => $cv->getVehicle()->getManufacturer()->getID(),
'make_id' => $cv->getVehicle()->getID(),
'name' => $cv_name,
'plate_num' => $cv->getPlateNumber(),
'model_year' => $cv->getModelYear(),
'color' => $cv->getColor(),
'condition' => $cv->getStatusCondition(),
'fuel_type' => $cv->getFuelType(),
'wty_code' => $cv->getWarrantyCode(),
'wty_expire' => $wty_ex,
'curr_batt_id' => $battery_id,
'is_motolite' => $cv->hasMotoliteBattery() ? 1 : 0,
'is_active' => $cv->isActive() ? 1 : 0,
'warranty' => $warranty,
];
// get latest insurance row
if ($include_insurance) {
$insurance = null;
$iobj = $cv->getLatestInsuranceApplication();
if (!empty($iobj)) {
$gt = $iobj->getGatewayTransaction();
$date_complete = $iobj->getDateComplete();
$date_expire = $iobj->getDateExpire();
$status = $iobj->getStatus();
error_log("\r\nTHIS IS THE CURRENT STATUS: " . $status . "\r\n");
// handle the very transient state between a payment being made and receiving the paymongo webhook
// TODO: maybe handle this more elegantly. issue is not sure it is a good idea to update the db for this very transient status as the webhook listener also updates this status right away
switch ($status) {
case InsuranceApplicationStatus::CREATED:
// get latest status on this checkout from paymongo
$checkout = $paymongo->getCheckout($gt->getExtTransactionId());
if ($checkout['success']) {
$payment_intent = $checkout['response']['data']['attributes']['payment_intent'] ?? null;
if (!empty($payment_intent)) {
$intent_status = $payment_intent['attributes']['status'] ?? null;
// TODO: define these paymongo payment intent statuses elsewhere
if ($intent_status === 'processing' || $intent_status === 'succeeded') {
$status = InsuranceApplicationStatus::PAID;
}
}
}
break;
default:
break;
}
$insurance = [
'id' => $iobj->getID(),
'ext_transaction_id' => $iobj->getExtTransactionId(),
'status' => $status,
'coc_url' => $iobj->getCOC(),
'checkout_url' => $gt->getMetadata()['checkout_url'],
'transaction_status' => $gt->getStatus(),
'premium_amount' => (string)bcdiv($gt->getAmount(), 100), // NOTE: hard expressing as string so it's consistent
'date_submit' => $iobj->getDateSubmit()->format('Y-m-d H:i:s'),
'date_complete' => $date_complete ? $date_complete->format('Y-m-d H:i:s') : null,
'date_expire' => $date_expire ? $date_expire->format('Y-m-d H:i:s') : null,
];
// get information changelog
$insurance['changelog'] = $iobj->getMetadata()['changes'] ?? [];
}
$row['latest_insurance'] = $insurance;
}
return $row;
}
protected function checkVehicleRequirements(Request $req)
{

View file

@ -1,253 +0,0 @@
<?php
namespace App\Controller;
use App\Entity\CustomerLocation;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
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 Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Catalyst\MenuBundle\Annotation\Menu;
class CustomerLocationController extends Controller
{
/**
* @Menu(selected="customer_location_list")
* @IsGranted("cust_location.list")
*/
public function index()
{
return $this->render('customer-location/list.html.twig');
}
/**
* @IsGranted("cust_location.list")
*/
public function datatableRows(Request $req)
{
// get query builder
$qb = $this->getDoctrine()
->getRepository(CustomerLocation::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $qb->select('COUNT(q)');
$this->setQueryFilters($datatable, $tquery);
$total = $tquery->getQuery()
->getSingleScalarResult();
// get current page number
$page = $datatable['pagination']['page'] ?? 1;
$perpage = $datatable['pagination']['perpage'];
$offset = ($page - 1) * $perpage;
// add metadata
$meta = [
'page' => $page,
'perpage' => $perpage,
'pages' => ceil($total / $perpage),
'total' => $total,
'sort' => 'asc',
'field' => 'id'
];
// build query
$query = $qb->select('q');
$this->setQueryFilters($datatable, $query);
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
$order = $datatable['sort']['sort'] ?? 'asc';
$query->orderBy('q.' . $datatable['sort']['field'], $order);
} else {
$query->orderBy('q.id', 'asc');
}
// get rows for this page
$obj_rows = $query->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery()
->getResult();
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow->getID();
$row['name'] = $orow->getName();
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// add crud urls
if ($this->isGranted('cust_location.update'))
$row['meta']['update_url'] = $this->generateUrl('customer_location_update_form', ['id' => $row['id']]);
if ($this->isGranted('cust_location.delete'))
$row['meta']['delete_url'] = $this->generateUrl('customer_location_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
/**
* @Menu(selected="customer_location.list")
* @IsGranted("cust_location.add")
*/
public function addForm()
{
$cust_location = new CustomerLocation();
$params = [
'cust_location' => $cust_location,
'mode' => 'create',
];
// response
return $this->render('customer-location/form.html.twig', $params);
}
/**
* @IsGranted("cust_location.add")
*/
public function addSubmit(Request $req, EntityManagerInterface $em, ValidatorInterface $validator)
{
$cust_location = new CustomerLocation();
$this->setObject($cust_location, $req);
// validate
$errors = $validator->validate($cust_location);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->persist($cust_location);
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
/**
* @Menu(selected="customer_location_list")
* @ParamConverter("cust_location", class="App\Entity\CustomerLocation")
* @IsGranted("cust_location.update")
*/
public function updateForm($id, EntityManagerInterface $em, CustomerLocation $cust_location)
{
$params = [];
$params['cust_location'] = $cust_location;
$params['mode'] = 'update';
// response
return $this->render('customer-location/form.html.twig', $params);
}
/**
* @ParamConverter("cust_location", class="App\Entity\CustomerLocation")
* @IsGranted("cust_location.update")
*/
public function updateSubmit(Request $req, EntityManagerInterface $em, ValidatorInterface $validator, CustomerLocation $cust_location)
{
$this->setObject($cust_location, $req);
// validate
$errors = $validator->validate($cust_location);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
/**
* @ParamConverter("cust_location", class="App\Entity\CustomerLocation")
* @IsGranted("cust_location.update")
*/
public function deleteSubmit(EntityManagerInterface $em, CustomerLocation $cust_location)
{
// delete this object
$em->remove($cust_location);
$em->flush();
// response
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->send();
}
protected function setObject(CustomerLocation $obj, Request $req)
{
// set and save values
$obj->setName($req->request->get('name'))
->setCode($req->request->get('code'));
}
protected function setQueryFilters($datatable, QueryBuilder $query)
{
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->where('q.name LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
}

View file

@ -2,128 +2,22 @@
namespace App\Controller;
use App\Ramcar\InsuranceApplicationStatus;
use App\Service\FCMSender;
use App\Service\InsuranceConnector;
use App\Entity\InsuranceApplication;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use DateTime;
class InsuranceController extends Controller
{
protected $ic;
protected $em;
protected $fcmclient;
public function __construct(InsuranceConnector $ic, EntityManagerInterface $em, FCMSender $fcmclient)
{
$this->ic = $ic;
$this->em = $em;
$this->fcmclient = $fcmclient;
}
public function listen(Request $req)
public function listen(Request $req, EntityManagerInterface $em)
{
$payload = $req->request->all();
// log this callback
$this->ic->log('CALLBACK', "[]", json_encode($payload), 'callback');
// if no transaction code given, silently fail
if (empty($payload['transaction_code'])) {
error_log("Invalid insurance callback received: " . print_r($payload, true));
return $this->json([
'success' => true,
]);
}
// get event type and process accordingly
$event_name = $payload['transaction_code'];
switch ($event_name) {
case 'GR002':
return $this->handleAuthenticated($payload);
break;
case 'GR003':
return $this->handleUpdateMade($payload);
break;
default:
break;
}
error_log(print_r($payload, true));
return $this->json([
'success' => true,
'payload' => $payload,
]);
}
protected function handleAuthenticated($payload)
{
$obj = $this->getApplication($payload['id']);
$now = new DateTime();
$expiry = DateTime::createFromFormat("Y-m-d", $payload['expiry_date']);
if (!empty($obj)) {
// mark as completed
$obj->setStatus(InsuranceApplicationStatus::COMPLETED);
$obj->setDateComplete($now);
$obj->setDateExpire($expiry);
$obj->setCOC($payload['coc_url']);
$this->em->flush();
// send notification
$this->fcmclient->sendEvent($obj->getCustomer(), "insurance_fcm_title_completed", "insurance_fcm_body_completed", [
'cv_id' => $obj->getCustomerVehicle()->getID(),
]);
}
return $this->json([
'success' => true,
]);
}
protected function handleUpdateMade($payload)
{
$obj = $this->getApplication($payload['id']);
if (!empty($obj)) {
$metadata = $obj->getMetadata();
// initialize change list if not present
if (empty($metadata['changes'])) {
$metadata['changes'] = [];
}
$now = new DateTime;
$metadata['changes'][$now->format('Y-m-d H:i:s')] = $payload['data'];
// update metadata to record change
$obj->setMetadata($metadata);
$this->em->flush();
// send notification
$this->fcmclient->sendEvent($obj->getCustomer(), "insurance_fcm_title_updated", "insurance_fcm_body_updated", [
'cv_id' => $obj->getCustomerVehicle()->getID(),
]);
}
return $this->json([
'success' => true,
]);
}
protected function getApplication($transaction_id)
{
$result = $this->em->getRepository(InsuranceApplication::class)->findBy([
'ext_transaction_id' => $transaction_id,
], [], 1);
return !empty($result) ? $result[0] : false;
}
}

View file

@ -1,269 +0,0 @@
<?php
namespace App\Controller;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Catalyst\MenuBundle\Annotation\Menu;
use App\Entity\PriceTier;
use App\Entity\Battery;
use App\Entity\ServiceOffering;
use App\Entity\ItemType;
use App\Entity\ItemPrice;
class ItemPricingController extends Controller
{
/**
* @Menu(selected="item_pricing")
* @IsGranted("item_pricing.update")
*/
public function index (EntityManagerInterface $em)
{
// get all the price tiers
$price_tiers = $em->getRepository(PriceTier::class)->findAll();
// get all item types
$item_types = $em->getRepository(ItemType::class)->findBy([], ['name' => 'asc']);
// get all the items/batteries
// load only batteries upon initial loading
$items = $this->getBatteries($em);
// set the default item type to battery
$default_it = $em->getRepository(ItemType::class)->findOneBy(['code' => 'battery']);
$params = [
'sets' => [
'price_tiers' => $price_tiers,
'item_types' => $item_types,
],
'items' => $items,
'default_item_type_id' => $default_it->getID(),
];
return $this->render('item-pricing/form.html.twig', $params);
}
/**
* @Menu(selected="item_pricing")
* @IsGranted("item_pricing.update")
*/
public function formSubmit(Request $req, EntityManagerInterface $em)
{
$pt_id = $req->request->get('price_tier_id');
$it_id = $req->request->get('item_type_id');
$prices = $req->request->get('price');
// get the item type
$item_type = $em->getRepository(ItemType::class)->find($it_id);
if ($item_type->getCode() == 'battery')
{
// get batteries
$items = $em->getRepository(Battery::class)->findBy(['flag_active' => true], ['id' => 'asc']);
}
else
{
// get service offerings
$items = $em->getRepository(ServiceOffering::class)->findBy([], ['id' => 'asc']);
}
// on default price tier
if ($pt_id == 0)
{
// default price tier, update battery or service offering, depending on item type
// NOTE: battery and service offering prices or fees are stored as decimal.
foreach ($items as $item)
{
$item_id = $item->getID();
if (isset($prices[$item_id]))
{
// check item type
if ($item_type->getCode() == 'battery')
$item->setSellingPrice($prices[$item_id]);
else
$item->setFee($prices[$item_id]);
}
}
}
else
{
// get the price tier
$price_tier = $em->getRepository(PriceTier::class)->find($pt_id);
$item_prices = $price_tier->getItemPrices();
// clear the tier's item prices for the specific item type
foreach ($item_prices as $ip)
{
if ($ip->getItemType() == $item_type)
$em->remove($ip);
}
// update the tier's item prices
foreach ($items as $item)
{
$item_id = $item->getID();
$item_price = new ItemPrice();
$item_price->setItemType($item_type)
->setPriceTier($price_tier)
->setItemID($item_id);
if (isset($prices[$item_id]))
{
$item_price->setPrice($prices[$item_id] * 100);
}
else
{
$item_price->setPrice($item->getPrice() * 100);
}
// save
$em->persist($item_price);
}
}
$em->flush();
return $this->redirectToRoute('item_pricing');
}
/**
* @IsGranted("item_pricing.update")
*/
public function itemPrices(EntityManagerInterface $em, $pt_id, $it_id)
{
$pt_prices = [];
// get the item type
$it = $em->getRepository(ItemType::class)->find($it_id);
// check if default prices are needed
if ($pt_id != 0)
{
// get the price tier
$pt = $em->getRepository(PriceTier::class)->find($pt_id);
// get the items under the price tier
$pt_items = $pt->getItemPrices();
foreach ($pt_items as $pt_item)
{
// make item price hash
$pt_prices[$pt_item->getItemID()] = $pt_item->getPrice();
}
}
// get the prices from battery or service offering, depending on item type
if ($it->getCode() == 'battery')
{
// get batteries
$items = $em->getRepository(Battery::class)->findBy(['flag_active' => true], ['id' => 'asc']);
}
else
{
// get service offerings
$items = $em->getRepository(ServiceOffering::class)->findBy([], ['id' => 'asc']);
}
$data_items = [];
foreach ($items as $item)
{
$item_id = $item->getID();
// get default price
if ($it->getCode() == 'battery')
{
$price = $item->getSellingPrice();
$name = $item->getModel()->getName() . ' ' . $item->getSize()->getName();
}
else
{
$price = $item->getFee();
$name = $item->getName();
}
// check if tier has price for item
if (isset($pt_prices[$item_id]))
{
$pt_price = $pt_prices[$item_id];
// actual price
$price = number_format($pt_price / 100, 2, '.', '');
}
$actual_price = $price;
$data_items[] = [
'id' => $item_id,
'name' => $name,
'item_type_id' => $it->getID(),
'item_type' => $it->getName(),
'price' => $actual_price,
];
}
// response
return new JsonResponse([
'items' => $data_items,
]);
}
protected function getBatteries(EntityManagerInterface $em)
{
// get the item type for battery
$batt_item_type = $em->getRepository(ItemType::class)->findOneBy(['code' => 'battery']);
// get all active batteries
$batts = $em->getRepository(Battery::class)->findBy(['flag_active' => true], ['id' => 'asc']);
foreach ($batts as $batt)
{
$batt_set[$batt->getID()] = [
'name' => $batt->getModel()->getName() . ' ' . $batt->getSize()->getName(),
'item_type_id' => $batt_item_type->getID(),
'item_type' => $batt_item_type->getName(),
'price' => $batt->getSellingPrice(),
];
}
return [
'items' => $batt_set,
];
}
protected function getServiceOfferings(EntityeManagerInterface $em)
{
// get the item type for service offering
$service_item_type = $em->getRepository(ItemType::class)->findOneBy(['code' => 'service_offering']);
// get all service offerings
$services = $em->getRepository(ServiceOffering::class)->findBy([], ['id' => 'asc']);
$service_set = [];
foreach ($services as $service)
{
$service_set[$service->getID()] = [
'name' => $service->getName(),
'item_type_id' => $service_item_type->getID(),
'item_type' => $service_item_type->getName(),
'price' => $service->getFee(),
];
}
return [
'items' => $service_set,
];
}
}

View file

@ -1,251 +0,0 @@
<?php
namespace App\Controller;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
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 Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use App\Entity\ItemType;
use Catalyst\MenuBundle\Annotation\Menu;
class ItemTypeController extends Controller
{
/**
* @Menu(selected="item_type_list")
* @IsGranted("item_type.list")
*/
public function index ()
{
return $this->render('item-type/list.html.twig');
}
/**
* @IsGranted("item_type.list")
*/
public function datatableRows(Request $req)
{
// get query builder
$qb = $this->getDoctrine()
->getRepository(ItemType::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $qb->select('COUNT(q)');
$this->setQueryFilters($datatable, $tquery);
$total = $tquery->getQuery()
->getSingleScalarResult();
// get current page number
$page = $datatable['pagination']['page'] ?? 1;
$perpage = $datatable['pagination']['perpage'];
$offset = ($page - 1) * $perpage;
// add metadata
$meta = [
'page' => $page,
'perpage' => $perpage,
'pages' => ceil($total / $perpage),
'total' => $total,
'sort' => 'asc',
'field' => 'id'
];
// build query
$query = $qb->select('q');
$this->setQueryFilters($datatable, $query);
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
$order = $datatable['sort']['sort'] ?? 'asc';
$query->orderBy('q.' . $datatable['sort']['field'], $order);
} else {
$query->orderBy('q.id', 'asc');
}
// get rows for this page
$obj_rows = $query->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery()
->getResult();
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow->getID();
$row['name'] = $orow->getName();
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// add crud urls
if ($this->isGranted('item_type.update'))
$row['meta']['update_url'] = $this->generateUrl('item_type_update_form', ['id' => $row['id']]);
if ($this->isGranted('item_type.delete'))
$row['meta']['delete_url'] = $this->generateUrl('item_type_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
/**
* @Menu(selected="item_type.list")
* @IsGranted("item_type.add")
*/
public function addForm()
{
$item_type = new ItemType();
$params = [
'obj' => $item_type,
'mode' => 'create',
];
// response
return $this->render('item-type/form.html.twig', $params);
}
/**
* @IsGranted("item_type.add")
*/
public function addSubmit(Request $req, EntityManagerInterface $em, ValidatorInterface $validator)
{
$item_type = new ItemType();
$this->setObject($item_type, $req);
// validate
$errors = $validator->validate($item_type);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->persist($item_type);
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
/**
* @Menu(selected="item_type_list")
* @ParamConverter("item_type", class="App\Entity\ItemType")
* @IsGranted("item_type.update")
*/
public function updateForm($id, EntityManagerInterface $em, ItemType $item_type)
{
$params = [];
$params['obj'] = $item_type;
$params['mode'] = 'update';
// response
return $this->render('item-type/form.html.twig', $params);
}
/**
* @ParamConverter("item_type", class="App\Entity\ItemType")
* @IsGranted("item_type.update")
*/
public function updateSubmit(Request $req, EntityManagerInterface $em, ValidatorInterface $validator, ItemType $item_type)
{
$this->setObject($item_type, $req);
// validate
$errors = $validator->validate($item_type);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
/**
* @ParamConverter("item_type", class="App\Entity\ItemType")
* @IsGranted("item_type.delete")
*/
public function deleteSubmit(EntityManagerInterface $em, ItemType $item_type)
{
// delete this object
$em->remove($item_type);
$em->flush();
// response
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->send();
}
protected function setObject(ItemType $obj, Request $req)
{
// set and save values
$obj->setName($req->request->get('name'))
->setCode($req->request->get('code'));
}
protected function setQueryFilters($datatable, QueryBuilder $query)
{
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->where('q.name LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
}

View file

@ -7,7 +7,6 @@ use App\Ramcar\InvoiceCriteria;
use App\Ramcar\CMBServiceType;
use App\Ramcar\ServiceType;
use App\Ramcar\JOCancelReasons;
use App\Ramcar\TransactionOrigin;
use App\Entity\CustomerVehicle;
use App\Entity\Promo;
@ -30,7 +29,6 @@ use App\Service\HubSelector;
use App\Service\RiderTracker;
use App\Service\MotivConnector;
use App\Service\PriceTierManager;
use App\Service\GeofenceTracker;
use Symfony\Component\HttpFoundation\Request;
@ -43,8 +41,6 @@ use Doctrine\ORM\EntityManagerInterface;
use Catalyst\MenuBundle\Annotation\Menu;
use CrEOF\Spatial\PHP\Types\Geometry\Point;
class JobOrderController extends Controller
{
public function getJobOrders(Request $req, JobOrderHandlerInterface $jo_handler)
@ -303,7 +299,6 @@ class JobOrderController extends Controller
$rows[$key]['meta']['update_url'] = $this->generateUrl($jo_handler->getEditRoute($jo_id, $tier_params['edit_route']), ['id' => $jo_id]);
$rows[$key]['meta']['onestep_edit_url'] = $this->generateUrl('jo_onestep_edit_form', ['id' => $jo_id]);
$rows[$key]['meta']['pdf_url'] = $this->generateUrl('jo_pdf_form', ['id' => $jo_id]);
$rows[$key]['meta']['view_url'] = $this->generateUrl('jo_all_view_form',['id' => $jo_id]);
}
if ($tier_params['unlock_route'] != '')
@ -662,32 +657,6 @@ class JobOrderController extends Controller
// response
return $this->render($template, $params);
}
/**
* @Menu(selected="jo_all")
*/
public function allViewForm($id, JobOrderHandlerInterface $jo_handler,
GISManagerInterface $gis, EntityManagerInterface $em)
{
$this->denyAccessUnlessGranted('jo_all.list', null, 'No access.');
try
{
$params = $jo_handler->initializeAllViewForm($id);
}
catch (NotFoundHttpException $e)
{
throw $this->createNotFoundException($e->getMessage());
}
$params['return_url'] = $this->generateUrl('jo_all');
$params['map_js_file'] = $gis->getJSJOFile();
$template = $params['template'];
// response
return $this->render($template, $params);
}
public function pdfForm(Request $req, $id, JobOrderHandlerInterface $jo_handler)
@ -744,7 +713,7 @@ class JobOrderController extends Controller
}
public function generateInvoice(Request $req, InvoiceGeneratorInterface $ic, PriceTierManager $pt_manager)
public function generateInvoice(Request $req, InvoiceGeneratorInterface $ic)
{
// error_log('generating invoice...');
$error = false;
@ -754,21 +723,6 @@ class JobOrderController extends Controller
$promo_id = $req->request->get('promo');
$cvid = $req->request->get('cvid');
$service_charges = $req->request->get('service_charges', []);
$flag_coolant = $req->request->get('flag_coolant', false);
$flag_sealant = $req->request->get('flag_sealant', false);
// coordinates
// need to check if lng and lat are set
$lng = $req->request->get('coord_lng', 0);
$lat = $req->request->get('coord_lat', 0);
$price_tier = 0;
if (!empty($lng) && !empty($lat))
{
$coordinates = new Point($req->request->get('coord_lng'), $req->request->get('coord_lat'));
$price_tier = $pt_manager->getPriceTier($coordinates);
}
$em = $this->getDoctrine()->getManager();
@ -783,12 +737,8 @@ class JobOrderController extends Controller
// instantiate invoice criteria
$criteria = new InvoiceCriteria();
$criteria->setServiceType($stype)
->setCustomerVehicle($cv)
->setIsTaxable()
->setSource(TransactionOrigin::CALL)
->setPriceTier($price_tier)
->setHasCoolant($flag_coolant)
->setHasSealant($flag_sealant);
->setCustomerVehicle($cv);
/*
// if it's a jumpstart or troubleshoot only, we know what to charge already

View file

@ -1,106 +0,0 @@
<?php
namespace App\Controller;
use App\Entity\GatewayTransaction;
use App\Ramcar\TransactionStatus;
use App\Service\PayMongoConnector;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use DateTime;
class PayMongoController extends Controller
{
protected $pm;
protected $em;
public function __construct(PayMongoConnector $pm, EntityManagerInterface $em)
{
$this->pm = $pm;
$this->em = $em;
}
public function listen(Request $req)
{
$payload = json_decode($req->getContent(), true);
// log this callback
$this->pm->log('CALLBACK', "[]", $req->getContent(), 'callback');
// if no event type given, silently fail
if (empty($payload['data'])) {
error_log("Invalid paymongo callback received: " . print_r($payload, true));
return $this->json([
'success' => true,
]);
}
// get event type and process accordingly
$attr = $payload['data']['attributes'];
$event = $attr['data'];
$event_name = $attr['type'];
switch ($event_name) {
case "payment.paid":
return $this->handlePaymentPaid($event);
case "payment.failed":
return $this->handlePaymentFailed($event);
case "payment.refunded": // TODO: handle refunds
case "payment.refund.updated":
case "checkout_session.payment.paid":
default:
break;
}
return $this->json([
'success' => true,
]);
}
protected function handlePaymentPaid($event)
{
$metadata = $event['attributes']['metadata'];
$obj = $this->getTransaction($metadata['transaction_id']);
if (!empty($obj)) {
// mark as paid
$obj->setStatus(TransactionStatus::PAID);
$obj->setDatePay(new DateTime());
$this->em->flush();
}
return $this->json([
'success' => true,
]);
}
protected function handlePaymentFailed($event)
{
// TODO: do something about failed payments?
return $this->json([
'success' => true,
]);
}
protected function getTransaction($id)
{
//$class_name = 'App\\Entity\\' . $type;
//$instance = new $class_name;
return $this->em->getRepository(GatewayTransaction::class)->find($id);
}
public function paymentSuccess(Request $req)
{
return $this->render('paymongo/success.html.twig');
}
public function paymentCancelled(Request $req)
{
return $this->render('paymongo/cancelled.html.twig');
}
}

View file

@ -1,355 +0,0 @@
<?php
namespace App\Controller;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Catalyst\MenuBundle\Annotation\Menu;
use App\Entity\PriceTier;
use App\Entity\SupportedArea;
class PriceTierController extends Controller
{
/**
* @Menu(selected="price_tier_list")
* @IsGranted("price_tier.list")
*/
public function index()
{
return $this->render('price-tier/list.html.twig');
}
/**
* @IsGranted("price_tier.list")
*/
public function datatableRows(Request $req)
{
// get query builder
$qb = $this->getDoctrine()
->getRepository(PriceTier::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $qb->select('COUNT(q)');
$this->setQueryFilters($datatable, $tquery);
$total = $tquery->getQuery()
->getSingleScalarResult();
// get current page number
$page = $datatable['pagination']['page'] ?? 1;
$perpage = $datatable['pagination']['perpage'];
$offset = ($page - 1) * $perpage;
// add metadata
$meta = [
'page' => $page,
'perpage' => $perpage,
'pages' => ceil($total / $perpage),
'total' => $total,
'sort' => 'asc',
'field' => 'id'
];
// build query
$query = $qb->select('q');
$this->setQueryFilters($datatable, $query);
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
$order = $datatable['sort']['sort'] ?? 'asc';
$query->orderBy('q.' . $datatable['sort']['field'], $order);
} else {
$query->orderBy('q.id', 'asc');
}
// get rows for this page
$obj_rows = $query->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery()
->getResult();
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow->getID();
$row['name'] = $orow->getName();
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// add crud urls
if ($this->isGranted('price_tier.update'))
$row['meta']['update_url'] = $this->generateUrl('price_tier_update_form', ['id' => $row['id']]);
if ($this->isGranted('service_offering.delete'))
$row['meta']['delete_url'] = $this->generateUrl('price_tier_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
/**
* @Menu(selected="price_tier.list")
* @IsGranted("price_tier.add")
*/
public function addForm(EntityManagerInterface $em)
{
$pt = new PriceTier();
// get the supported areas
$sets = $this->generateFormSets($em);
$params = [
'obj' => $pt,
'sets' => $sets,
'mode' => 'create',
];
// response
return $this->render('price-tier/form.html.twig', $params);
}
/**
* @IsGranted("price_tier.add")
*/
public function addSubmit(Request $req, EntityManagerInterface $em, ValidatorInterface $validator)
{
// initialize error list
$error_array = [];
$pt = new PriceTier();
$error_array = $this->validateRequest($em, $req);
$this->setObject($pt, $req);
// validate
$errors = $validator->validate($pt);
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->persist($pt);
// set the price tier id for the selected supported areas
$this->updateSupportedAreas($em, $pt, $req);
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
/**
* @Menu(selected="price_tier_list")
* @ParamConverter("pt", class="App\Entity\PriceTier")
* @IsGranted("price_tier.update")
*/
public function updateForm($id, EntityManagerInterface $em, PriceTier $pt)
{
// get the supported areas
$sets = $this->generateFormSets($em, $pt);
$params = [
'obj' => $pt,
'sets' => $sets,
'mode' => 'update',
];
// response
return $this->render('price-tier/form.html.twig', $params);
}
/**
* @ParamConverter("pt", class="App\Entity\PriceTier")
* @IsGranted("price_tier.update")
*/
public function updateSubmit(Request $req, EntityManagerInterface $em, ValidatorInterface $validator, PriceTier $pt)
{
// initialize error list
$error_array = [];
// clear supported areas of price tier
$this->clearPriceTierSupportedAreas($em, $pt);
$error_array = $this->validateRequest($em, $req);
$this->setObject($pt, $req);
// validate
$errors = $validator->validate($pt);
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// set the price tier id for the selected supported areas
$this->updateSupportedAreas($em, $pt, $req);
// validated! save the entity
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
/**
* @ParamConverter("pt", class="App\Entity\PriceTier")
* @IsGranted("price_tier.delete")
*/
public function deleteSubmit(EntityManagerInterface $em, PriceTier $pt)
{
// clear supported areas of price tier
$this->clearPriceTierSupportedAreas($em, $pt);
// delete this object
$em->remove($pt);
$em->flush();
// response
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->send();
}
protected function validateRequest(EntityManagerInterface $em, Request $req)
{
// get areas
$areas = $req->request->get('areas');
// check if no areas selected aka empty
if (!empty($areas))
{
foreach ($areas as $area_id)
{
$supported_area = $em->getRepository(SupportedArea::class)->find($area_id);
if ($supported_area == null)
return ['areas' => 'Invalid area'];
// check if supported area already belongs to a price tier
if ($supported_area->getPriceTier() != null)
return ['areas' => 'Area already belongs to a price tier.'];
}
}
return null;
}
protected function setObject(PriceTier $obj, Request $req)
{
// clear supported areas first
$obj->clearSupportedAreas();
$obj->setName($req->request->get('name'));
}
protected function clearPriceTierSupportedAreas(EntityManagerInterface $em, PriceTier $obj)
{
// find the supported areas set with the price tier
$areas = $em->getRepository(SupportedArea::class)->findBy(['price_tier' => $obj]);
if (!empty($areas))
{
// set the price tier id for the supported areas to null
foreach ($areas as $area)
{
$area->setPriceTier(null);
}
$em->flush();
}
}
protected function updateSupportedAreas(EntityManagerInterface $em, PriceTier $obj, Request $req)
{
// get the selected areas
$areas = $req->request->get('areas');
// check if no areas selected aka empty
if (!empty($areas))
{
foreach ($areas as $area_id)
{
// get supported area
$supported_area = $em->getRepository(SupportedArea::class)->find($area_id);
if ($supported_area != null)
$supported_area->setPriceTier($obj);
}
}
}
protected function generateFormSets(EntityManagerInterface $em, PriceTier $pt = null)
{
// get the supported areas with no price tier id or price tier id is set to the one that is being updated
$areas = $em->getRepository(SupportedArea::class)->findBy(['price_tier' => array(null, $pt)]);
$areas_set = [];
foreach ($areas as $area)
{
$areas_set[$area->getID()] = $area->getName();
}
return [
'areas' => $areas_set
];
}
protected function setQueryFilters($datatable, QueryBuilder $query)
{
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->where('q.name LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
}

View file

@ -236,10 +236,6 @@ class ReportController extends Controller
$reason = $jor->getReason();
$dispatched_by = 'system';
if ($jor->getUser() != null)
$dispatched_by = $jor->getUser()->getFullName();
$res[] = [
$jo->getID(),
$jo->getDateSchedule()->format('m/d/Y H:i'),
@ -248,7 +244,7 @@ class ReportController extends Controller
JORejectionReason::getName($jor->getReason()),
$jor->getContactPerson(),
$jor->getRemarks(),
!empty($jor->getUser()) ? $jor->getUser()->getFullName() : "",
$jor->getUser()->getFullName(),
ServiceType::getName($jo->getServiceType()),
];
}
@ -540,7 +536,7 @@ class ReportController extends Controller
'Mobile Number',
'Landline Number',
'Office Number',
'Alternative Phone Number',
'Fax Number',
'Plate Number',
'Date Mobile App Downloaded',
'Mobile Number Using Mobile App',
@ -710,7 +706,7 @@ class ReportController extends Controller
'Customer Mobile Phone',
'Customer Landline Phone',
'Customer Office Phone',
'Customer Alternative Phone',
'Customer Fax Phone',
'Customer Email Address',
'Customer Notes',
'Customer Has Third Party Privacy Policy?',
@ -817,7 +813,6 @@ class ReportController extends Controller
'Plate Number',
'SKU',
'Serial Number',
'Inventory',
'Invoice/DR No.',
'Existing Battery',
'Rider Name',
@ -1146,7 +1141,7 @@ class ReportController extends Controller
'Mobile Phone',
'Landline',
'Office Phone',
'Alternative Phone',
'Fax',
'Email Address',
'Vehicle Manufacturer',
'Vehicle Make',
@ -1937,9 +1932,6 @@ class ReportController extends Controller
$fac_hub_coord_lat = $fac_hub->getCoordinates()->getLatitude();
}
// get inventory count
$inventory = $jo->getInventoryCount();
// find date and time when JO was assigned a hub
$datetime_hub_assign_jo = '';
$date_hub_assign_jo = '';
@ -2262,7 +2254,6 @@ class ReportController extends Controller
$plate_number,
$sku,
$serial,
$inventory,
$jo->getORName(),
$existing_batt,
$rider_name,

View file

@ -14,7 +14,6 @@ use Doctrine\ORM\EntityManagerInterface;
use Catalyst\MenuBundle\Annotation\Menu;
use App\Entity\JobOrder;
use App\Entity\Rider;
use App\Service\JobOrderHandlerInterface;
@ -23,9 +22,6 @@ use App\Ramcar\JOStatus;
use App\Ramcar\ServiceType;
use App\Ramcar\WillingToWaitContent;
use App\Ramcar\CustomerClassification;
use App\Ramcar\CustomerNotWaitReason;
use DateTime;
class ResqJobOrderController extends Controller
{
@ -43,7 +39,7 @@ class ResqJobOrderController extends Controller
/**
* @IsGranted("jo_resq_proc.list")
*/
public function datatableRows(EntityManagerInterface $em, Request $req, $tier, JobOrderHandlerInterface $jo_handler)
public function datatableRows(Request $req, JobOrderHandlerInterface $jo_handler)
{
// get query builder
$qb = $this->getDoctrine()
@ -56,14 +52,7 @@ class ResqJobOrderController extends Controller
// count total records
$tquery = $qb->select('COUNT(q)');
// right now, tier is either proc or all
if ($tier == 'proc')
$this->setQueryFilters($datatable, $tquery, $qb, $tier);
else
{
// default to all
$this->setQueryFilters($datatable, $tquery, $qb, $tier);
}
$this->setQueryFilters($datatable, $tquery, $qb, JOStatus::PENDING, TransactionOrigin::MOBILE_APP);
$total = $tquery->getQuery()
->getSingleScalarResult();
@ -85,17 +74,9 @@ class ResqJobOrderController extends Controller
];
// build query
$qb = $em->getRepository(JobOrder::class)
->createQueryBuilder('q');
$query = $qb->select('q');
if ($tier == 'proc')
$this->setQueryFilters($datatable, $query, $qb, $tier);
else
{
// default to all
$this->setQueryFilters($datatable, $query, $qb, $tier);
}
$this->setQueryFilters($datatable, $query, $qb, JOStatus::PENDING, TransactionOrigin::MOBILE_APP);
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
@ -129,13 +110,7 @@ class ResqJobOrderController extends Controller
// check if customer is not willing to wait
$will_not_wait = $orow->getWillWait();
if ($will_not_wait == WillingToWaitContent::NOT_WILLING_TO_WAIT)
{
// check if reason is emergency or rush
$reason = $orow->getReasonNotWait();
if (($reason == CustomerNotWaitReason::EMERGENCY) ||
($reason == CustomerNotWaitReason::RUSH_REQUEST))
$is_emergency = true;
}
$is_emergency = true;
// add row data
$row['id'] = $orow->getID();
@ -150,9 +125,6 @@ class ResqJobOrderController extends Controller
$row['is_mobile'] = $orow->getSource() == TransactionOrigin::MOBILE_APP;
$row['is_vip'] = $is_vip;
$row['is_emergency'] = $is_emergency;
$row['flag_cust_new'] = $orow->isCustNew();
$row['date_assign'] = !empty($orow->getDateAssign()) ? $orow->getDateAssign()->format("c") : null;
$row['date_fulfill'] = !empty($orow->getDateFulfill()) ? $orow->getDateFulfill()->format("c") : null;
$processor = $orow->getProcessedBy();
if ($processor == null)
@ -160,28 +132,11 @@ class ResqJobOrderController extends Controller
else
$row['processor'] = $orow->getProcessedBy()->getFullName();
// get the assigned hub, if any
$assigned_hub = $orow->getHub();
if ($assigned_hub == null)
$row['assigned_hub'] = '';
else
$row['assigned_hub'] = $orow->getHub()->getName();
// add the items for Actions
$jo_id = $orow->getID();
if ($tier == 'proc')
{
$row['meta']['update_url'] = $this->generateUrl('jo_proc_form', ['id' => $jo_id, 'origin' => 'resq']);
$row['meta']['unlock_url'] = $this->generateUrl('jo_proc_unlock', ['id' => $jo_id, 'origin' => 'resq']);
}
else
{
// default to all
$row['meta']['update_url'] = $this->generateUrl('jo_all_form', ['id' => $jo_id, 'origin' => 'resq']);
$row['meta']['pdf_url'] = $this->generateUrl('jo_pdf_form', ['id' => $jo_id, 'origin' => 'resq']);
$row['meta']['view_url'] = $this->generateUrl('jo_all_view_form',['id' => $jo_id, 'origin' => 'resq']);
}
$row['meta']['update_url'] = $this->generateUrl('jo_proc_form', ['id' => $jo_id, 'origin' => 'resq']);
$row['meta']['unlock_url'] = $this->generateUrl('jo_proc_unlock', ['id' => $jo_id, 'origin' => 'resq']);
$rows[] = $row;
}
@ -193,77 +148,11 @@ class ResqJobOrderController extends Controller
]);
}
/**
* @Menu(selected="jo_resq_all")
* @IsGranted("jo_resq_all.list")
*/
public function listAll(EntityManagerInterface $em)
protected function setQueryFilters($datatable, &$query, $qb, $status, $source)
{
$params['table_refresh_rate'] = $this->container->getParameter('job_order_refresh_interval');
// get riders for dropdown
$params['riders'] = $em->getRepository(Rider::class)->findAll();
return $this->render('resq-job-order/list.all.html.twig', $params);
}
protected function setQueryFilters($datatable, &$query, $qb, $tier)
{
switch ($tier)
{
case 'proc':
$query->where('q.status = :status')
->andWhere('q.source = :source')
->setParameter('status', JOStatus::PENDING)
->setParameter('source', TransactionOrigin::MOBILE_APP);
if (isset($datatable['query']['data-rows-search']))
{
$query->andWhere('q.plate_number like :filter')
->orWhere('q.phone_mobile like :filter')
->orWhere('q.first_name like :filter')
->orWhere('q.last_name like :filter')
->setParameter('filter', $datatable['query']['data-rows-search'] . '%');
}
break;
case 'all':
if (isset($datatable['query']['data-rows-search']))
{
$query->andWhere('q.plate_number like :filter')
->orWhere('q.phone_mobile like :filter')
->orWhere('q.first_name like :filter')
->orWhere('q.last_name like :filter')
->setParameter('filter', $datatable['query']['data-rows-search'] . '%');
}
if (isset($datatable['query']['rider']))
{
$query->innerJoin('q.rider', 'r')
->andWhere('r.id = :rider_id')
->setParameter('rider_id', $datatable['query']['rider']);
}
if (isset($datatable['query']['schedule_date']))
{
$start = $datatable['query']['schedule_date'][0] . ' ' . '00:00:00';
$end = $datatable['query']['schedule_date'][1] . ' ' . '23:59:00';
$date_start = DateTime::createFromFormat('m/d/Y H:i:s', $start);
$date_end = DateTime::createFromFormat('m/d/Y H:i:s', $end);
$query->andWhere('q.date_schedule >= :date_start')
->andWhere('q.date_schedule <= :date_end')
->setParameter('date_start', $date_start)
->setParameter('date_end', $date_end);
}
$query->andWhere('q.source = :source')
->setParameter('source', TransactionOrigin::MOBILE_APP);
break;
default:
$query->where('q.source = :source')
->setParameter('source', TransactionOrigin::MOBILE_APP);
break;
}
$query->where('q.status = :status')
->andWhere('q.source = :source')
->setParameter('status', $status)
->setParameter('source', $source);
}
}

View file

@ -1,252 +0,0 @@
<?php
namespace App\Controller;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
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 Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Catalyst\MenuBundle\Annotation\Menu;
use App\Entity\ServiceOffering;
class ServiceOfferingController extends Controller
{
/**
* @Menu(selected="service_offering_list")
* @IsGranted("service_offering.list")
*/
public function index()
{
return $this->render('service-offering/list.html.twig');
}
/**
* @IsGranted("service_offering.list")
*/
public function datatableRows(Request $req)
{
// get query builder
$qb = $this->getDoctrine()
->getRepository(ServiceOffering::class)
->createQueryBuilder('q');
// get datatable params
$datatable = $req->request->get('datatable');
// count total records
$tquery = $qb->select('COUNT(q)');
$this->setQueryFilters($datatable, $tquery);
$total = $tquery->getQuery()
->getSingleScalarResult();
// get current page number
$page = $datatable['pagination']['page'] ?? 1;
$perpage = $datatable['pagination']['perpage'];
$offset = ($page - 1) * $perpage;
// add metadata
$meta = [
'page' => $page,
'perpage' => $perpage,
'pages' => ceil($total / $perpage),
'total' => $total,
'sort' => 'asc',
'field' => 'id'
];
// build query
$query = $qb->select('q');
$this->setQueryFilters($datatable, $query);
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
$order = $datatable['sort']['sort'] ?? 'asc';
$query->orderBy('q.' . $datatable['sort']['field'], $order);
} else {
$query->orderBy('q.id', 'asc');
}
// get rows for this page
$obj_rows = $query->setFirstResult($offset)
->setMaxResults($perpage)
->getQuery()
->getResult();
// process rows
$rows = [];
foreach ($obj_rows as $orow) {
// add row data
$row['id'] = $orow->getID();
$row['name'] = $orow->getName();
$row['fee'] = $orow->getFee();
// add row metadata
$row['meta'] = [
'update_url' => '',
'delete_url' => ''
];
// add crud urls
if ($this->isGranted('service_offering.update'))
$row['meta']['update_url'] = $this->generateUrl('service_offering_update_form', ['id' => $row['id']]);
if ($this->isGranted('service_offering.delete'))
$row['meta']['delete_url'] = $this->generateUrl('service_offering_delete', ['id' => $row['id']]);
$rows[] = $row;
}
// response
return $this->json([
'meta' => $meta,
'data' => $rows
]);
}
/**
* @Menu(selected="service_offering.list")
* @IsGranted("service_offering.add")
*/
public function addForm()
{
$service_offering = new ServiceOffering();
$params = [
'service_offering' => $service_offering,
'mode' => 'create',
];
// response
return $this->render('service-offering/form.html.twig', $params);
}
/**
* @IsGranted("service_offering.add")
*/
public function addSubmit(Request $req, EntityManagerInterface $em, ValidatorInterface $validator)
{
$service_offering = new ServiceOffering();
$this->setObject($service_offering, $req);
// validate
$errors = $validator->validate($service_offering);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->persist($service_offering);
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
/**
* @Menu(selected="service_offering_list")
* @ParamConverter("service_offering", class="App\Entity\ServiceOffering")
* @IsGranted("service_offering.update")
*/
public function updateForm($id, EntityManagerInterface $em, ServiceOffering $service_offering)
{
$params = [];
$params['service_offering'] = $service_offering;
$params['mode'] = 'update';
// response
return $this->render('service-offering/form.html.twig', $params);
}
/**
* @ParamConverter("service_offering", class="App\Entity\ServiceOffering")
* @IsGranted("service_offering.update")
*/
public function updateSubmit(Request $req, EntityManagerInterface $em, ValidatorInterface $validator, ServiceOffering $service_offering)
{
$this->setObject($service_offering, $req);
// validate
$errors = $validator->validate($service_offering);
// initialize error list
$error_array = [];
// add errors to list
foreach ($errors as $error) {
$error_array[$error->getPropertyPath()] = $error->getMessage();
}
// check if any errors were found
if (!empty($error_array)) {
// return validation failure response
return $this->json([
'success' => false,
'errors' => $error_array
], 422);
}
// validated! save the entity
$em->flush();
// return successful response
return $this->json([
'success' => 'Changes have been saved!'
]);
}
/**
* @ParamConverter("service_offering", class="App\Entity\ServiceOffering")
* @IsGranted("service_offering.delete")
*/
public function deleteSubmit(EntityManagerInterface $em, ServiceOffering $service_offering)
{
// delete this object
$em->remove($service_offering);
$em->flush();
// response
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->send();
}
protected function setObject(ServiceOffering $obj, Request $req)
{
// set and save values
$obj->setName($req->request->get('name'))
->setCode($req->request->get('code'))
->setFee($req->request->get('fee'));
}
protected function setQueryFilters($datatable, QueryBuilder $query)
{
if (isset($datatable['query']['data-rows-search']) && !empty($datatable['query']['data-rows-search'])) {
$query->where('q.name LIKE :filter')
->setParameter('filter', '%' . $datatable['query']['data-rows-search'] . '%');
}
}
}

View file

@ -9,19 +9,14 @@ use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Ramcar\APIResult;
use App\Entity\Vehicle;
use App\Entity\ItemType;
use App\Service\PriceTierManager;
use CrEOF\Spatial\PHP\Types\Geometry\Point;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class BatteryController extends ApiController
class BatteryController extends APIController
{
protected $acl_gen;
@ -30,7 +25,7 @@ class BatteryController extends ApiController
$this->acl_gen = $acl_gen;
}
public function getCompatibleBatteries(Request $req, $vid, EntityManagerInterface $em, PriceTierManager $pt_manager)
public function getCompatibleBatteries(Request $req, $vid, EntityManagerInterface $em)
{
$this->denyAccessUnlessGranted('tapi_battery_compatible.list', null, 'No access.');
@ -48,44 +43,12 @@ class BatteryController extends ApiController
return new APIResponse(false, $message);
}
// get location from request
$lng = $req->request->get('longitude', '');
$lat = $req->request->get('latitude', '');
$batts = $vehicle->getActiveBatteries();
$pt_id = 0;
if ((!(empty($lng))) && (!(empty($lat))))
{
// get the price tier
$coordinates = new Point($lng, $lat);
$pt_id = $pt_manager->getPriceTier($coordinates);
}
// batteries
$batt_list = [];
$batts = $vehicle->getBatteries();
foreach ($batts as $batt)
{
// TODO: Add warranty_tnv to battery information
// check if customer location is in a price tier location
if ($pt_id == 0)
$price = $batt->getSellingPrice();
else
{
// get item type for battery
$item_type = $em->getRepository(ItemType::class)->findOneBy(['code' => 'battery']);
if ($item_type == null)
$price = $batt->getSellingPrice();
else
{
$item_type_id = $item_type->getID();
$batt_id = $batt->getID();
// find the item price given price tier id and battery id
$price = $pt_manager->getItemPrice($pt_id, $item_type_id, $batt_id);
}
}
$batt_list[] = [
'id' => $batt->getID(),
'mfg_id' => $batt->getManufacturer()->getID(),
@ -94,7 +57,7 @@ class BatteryController extends ApiController
'model_name' => $batt->getModel()->getName(),
'size_id' => $batt->getSize()->getID(),
'size_name' => $batt->getSize()->getName(),
'price' => $price,
'price' => $batt->getSellingPrice(),
'wty_private' => $batt->getWarrantyPrivate(),
'wty_commercial' => $batt->getWarrantyCommercial(),
'image_url' => $this->getBatteryImageURL($req, $batt),

View file

@ -12,7 +12,7 @@ use Doctrine\ORM\EntityManagerInterface;
use CrEOF\Spatial\PHP\Types\Geometry\Point;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Ramcar\WarrantyClass;
use App\Ramcar\JOStatus;
@ -45,8 +45,6 @@ use App\Service\HubFilteringGeoChecker;
use App\Service\RiderTracker;
use App\Service\PromoLogger;
use App\Service\MapTools;
use App\Service\JobOrderManager;
use App\Service\PriceTierManager;
use App\Entity\JobOrder;
use App\Entity\CustomerVehicle;
@ -65,7 +63,7 @@ use DateInterval;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class JobOrderController extends ApiController
class JobOrderController extends APIController
{
protected $acl_gen;
@ -80,8 +78,7 @@ class JobOrderController extends ApiController
FCMSender $fcmclient,
RiderAssignmentHandlerInterface $rah, PromoLogger $promo_logger,
HubSelector $hub_select, HubDistributor $hub_dist, HubFilterLogger $hub_filter_logger,
HubFilteringGeoChecker $hub_geofence, EntityManagerInterface $em, JobOrderManager $jo_manager,
PriceTierManager $pt_manager)
HubFilteringGeoChecker $hub_geofence, EntityManagerInterface $em)
{
$this->denyAccessUnlessGranted('tapi_jo.request', null, 'No access.');
@ -110,7 +107,7 @@ class JobOrderController extends ApiController
// get data from request
$data = [];
$status = $this->getJobOrderRequestInfo($req, $em, $jo_manager, $data);
$status = $this->getJobOrderRequestInfo($req, $em, $data);
if ($status != null)
return new APIResponse(false, $status);
@ -139,8 +136,7 @@ class JobOrderController extends ApiController
->setModeOfPayment($data['payment_mode'])
->setAdvanceOrder($data['is_advance_order'])
->setStatusAutoAssign(AutoAssignStatus::NOT_ASSIGNED)
->setLandmark($data['landmark'])
->setCustNew($data['flag_cust_new']);
->setLandmark($data['landmark']);
$jo->setCustomer($data['customer']);
$jo->setCustomerVehicle($data['customer_vehicle']);
@ -161,23 +157,7 @@ class JobOrderController extends ApiController
$icrit->setCustomerVehicle($data['customer_vehicle']);
// set taxable
$icrit->setIsTaxable();
// set JO source
$icrit->setSource(TransactionOrigin::THIRD_PARTY);
// set price tier
$pt_id = $pt_manager->getPriceTier($jo->getCoordinates());
$icrit->setPriceTier($pt_id);
// add the actual battery item first
$icrit->addEntry($data['batt'], null, 1);
// if we have a trade in, add it as well, assuming trade in battery == battery purchased
if (!empty($data['trade_in_type'])) {
$icrit->addEntry($data['batt'], $data['trade_in_type'], 1);
}
$icrit->addEntry($data['batt'], $data['trade_in_type'], 1);
// send to invoice generator
$invoice = $ic->generateInvoice($icrit);
@ -239,10 +219,6 @@ class JobOrderController extends ApiController
// find nearest hubs
$nearest_hubs = $hub_select->find($hub_criteria);
// set filter flags for inventory and available riders
$hub_criteria->setInventoryCheck();
$hub_criteria->setRidersCheck();
if (!empty($nearest_hubs))
{
// go through the hub list, find the nearest hub
@ -470,12 +446,6 @@ class JobOrderController extends ApiController
$icrit->addEntry($data['battery'], $data['trade_in_type'], 1);
// set taxable
$icrit->setIsTaxable();
// set JO source
$icrit->setSource('third_party');
// send to invoice generator
$invoice = $ic->generateInvoice($icrit);
@ -1263,7 +1233,7 @@ class JobOrderController extends ApiController
return $file_path;
}
protected function getJobOrderRequestInfo(Request $req, EntityManagerInterface $em, JobOrderManager $jo_manager, &$data)
protected function getJobOrderRequestInfo(Request $req, EntityManagerInterface $em, &$data)
{
$error = $this->validateJORequest($req, $em);
if ($error != null)
@ -1386,7 +1356,7 @@ class JobOrderController extends ApiController
];
// process customer and vehicle information
$cust_data = $this->processCustomerAndVehicleInformation($c_data, $em, $jo_manager);
$cust_data = $this->processCustomerAndVehicleInformation($c_data, $em);
$data = [
'trade_in_type' => $trade_in_type,
@ -1406,7 +1376,6 @@ class JobOrderController extends ApiController
'customer_vehicle' => $cust_data['customer_vehicle'],
'source' => TransactionOrigin::THIRD_PARTY,
'warranty_class' => $warranty_class,
'flag_cust_new' => $cust_data['flag_cust_new'],
];
return null;
@ -1563,7 +1532,7 @@ class JobOrderController extends ApiController
return null;
}
protected function processCustomerAndVehicleInformation($data, EntityManagerInterface $em, JobOrderManager $jo_manager)
protected function processCustomerAndVehicleInformation($data, EntityManagerInterface $em)
{
$c_data = [];
@ -1580,7 +1549,6 @@ class JobOrderController extends ApiController
// find customer + customer vehicle combo
$cust_vehicle = $this->findCustomerAndCustomerVehicle($data, $em);
$flag_cust_new = false;
if ($cust_vehicle == null)
{
// find customer given phone number
@ -1616,8 +1584,7 @@ class JobOrderController extends ApiController
// add customer vehicle
$cust_vehicle = $this->createCustomerVehicle($em, $cust, $data);
$flag_cust_new = true;
}
else
{
@ -1628,18 +1595,9 @@ class JobOrderController extends ApiController
$em->flush();
}
// check if customer has more than one job order already
if ($cust != null)
{
$cust_jo_count = $jo_manager->getCustomerJobOrderCount($cust->getID());
if ($cust_jo_count <= 1)
$flag_cust_new = true;
}
$c_data = [
'customer' => $cust_vehicle->getCustomer(),
'customer_vehicle' => $cust_vehicle,
'flag_cust_new' => $flag_cust_new,
];
return $c_data;

View file

@ -9,13 +9,13 @@ use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Entity\Promo;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class PromoController extends ApiController
class PromoController extends APIController
{
protected $acl_gen;

View file

@ -9,13 +9,13 @@ use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Entity\Service;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class ServiceController extends ApiController
class ServiceController extends APIController
{
protected $acl_gen;

View file

@ -9,14 +9,14 @@ use Doctrine\ORM\Query;
use Doctrine\ORM\EntityManagerInterface;
use Catalyst\ApiBundle\Controller\ApiController;
use Catalyst\ApiBundle\Component\Response as APIResponse;
use Catalyst\ApiBundle\Response\APIResponse;
use App\Entity\VehicleManufacturer;
use App\Entity\Vehicle;
use Catalyst\AuthBundle\Service\ACLGenerator as ACLGenerator;
class VehicleController extends ApiController
class VehicleController extends APIController
{
protected $acl_gen;

View file

@ -105,7 +105,6 @@ class TicketController extends Controller
$row['status'] = TicketStatus::getName($orow->getStatus());
$row['ticket_type'] = $orow->getTicketTypeText();
$row['plate_number'] = $orow->getPlateNumber();
$row['flag_late_doc'] = $orow->isLateDoc();
// add row metadata
$row['meta'] = [
@ -261,12 +260,6 @@ class TicketController extends Controller
// get remarks
$remarks = $req->request->get('remarks', '');
// is this a late documentation
$flag_late_doc = $req->request->get('flag_late_doc', false);
// reason for late documentation
$late_doc_reason = $flag_late_doc ? $req->request->get('late_doc_reason') : null;
// set and save values
$obj->setFirstName($first_name)
->setLastName($last_name)
@ -280,9 +273,7 @@ class TicketController extends Controller
->setCreatedBy($this->getUser())
->setSourceOfAwareness($soa_type)
->setRemarks($remarks)
->setOtherDescription($other_desc)
->setLateDoc($flag_late_doc)
->setLateDocReason($late_doc_reason);
->setOtherDescription($other_desc);
// if assigned to customer, set association
if ($customer_id) {
@ -480,12 +471,6 @@ class TicketController extends Controller
// get remarks
$remarks = $req->request->get('remarks', '');
// is this a late documentation
$flag_late_doc = $req->request->get('flag_late_doc', false);
// reason for late documentation
$late_doc_reason = $flag_late_doc ? $req->request->get('late_doc_reason') : null;
// set and save values
$obj->setFirstName($first_name)
->setLastName($last_name)
@ -497,9 +482,7 @@ class TicketController extends Controller
->setPlateNumber($req->request->get('plate_number'))
->setSourceOfAwareness($soa_type)
->setRemarks($remarks)
->setOtherDescription($other_desc)
->setLateDoc($flag_late_doc)
->setLateDocReason($late_doc_reason);
->setOtherDescription($other_desc);
// initialize error list
$error_array = [];

View file

@ -70,14 +70,11 @@ class VehicleController extends Controller
// build query
$query = $qb->select('q')
->addSelect('mfg.name as mfg_name')
->addSelect('mfg.id as mfg_id');
->addSelect('mfg.name as mfg_name');
// add filters to query
$this->setQueryFilters($datatable, $query);
error_log("test");
// check if sorting is present, otherwise use default
if (isset($datatable['sort']['field']) && !empty($datatable['sort']['field'])) {
$prefix = '';
@ -88,8 +85,7 @@ class VehicleController extends Controller
$order = $datatable['sort']['sort'] ?? 'asc';
$query->orderBy($prefix . $datatable['sort']['field'], $order);
} else {
$query->orderBy('mfg_name', 'asc')
->addOrderBy('q.make', 'asc');
$query->orderBy('mfg_name', 'asc');
}
// get rows for this page
@ -104,7 +100,6 @@ class VehicleController extends Controller
// add row data
$row['id'] = $orow[0]->getID();
$row['mfg_name'] = $orow['mfg_name'];
$row['mfg_id'] = $orow['mfg_id'];
$row['make'] = $orow[0]->getMake();
$row['model_year_from'] = $orow[0]->getModelYearFrom();
$row['model_year_to'] = $orow[0]->getModelYearTo();
@ -490,7 +485,7 @@ class VehicleController extends Controller
// get row data
$em = $this->getDoctrine()->getManager();
$vobj = $em->getRepository(Vehicle::class)->find($req->request->get('vehicle_id'));
$all_batts = $em->getRepository(Battery::class)->findBy(['flag_active' => true]);
$all_batts = $em->getRepository(Battery::class)->findAll();
if (empty($vobj))
throw $this->createNotFoundException('The item does not exist');
@ -500,20 +495,19 @@ class VehicleController extends Controller
$battery_index = [];
// get compatible batteries from selected manufacturer
// foreach ($vobj->getBatteries() as $battery)
foreach ($vobj->getActiveBatteries() as $battery)
foreach ($vobj->getBatteries() as $battery)
{
$batteries[] = [
'id' => $battery->getID(),
'mfg_name' => $battery->getManufacturer()->getName(),
'model_name' => $battery->getModel()->getName(),
'size_name' => $battery->getSize()->getName(),
'prod_code' => $battery->getProductCode(),
'sell_price' => $battery->getSellingPrice(),
'warr_private' => $battery->getWarrantyPrivate(),
'warr_commercial' => $battery->getWarrantyCommercial(),
];
$battery_index[$battery->getID()] = 1;
$batteries[] = [
'id' => $battery->getID(),
'mfg_name' => $battery->getManufacturer()->getName(),
'model_name' => $battery->getModel()->getName(),
'size_name' => $battery->getSize()->getName(),
'prod_code' => $battery->getProductCode(),
'sell_price' => $battery->getSellingPrice(),
'warr_private' => $battery->getWarrantyPrivate(),
'warr_commercial' => $battery->getWarrantyCommercial(),
];
$battery_index[$battery->getID()] = 1;
}
// add all other batteries, because they want options

View file

@ -147,12 +147,6 @@ class Battery
*/
protected $image_file;
// flag if battery is active
/**
* @ORM\Column(type="boolean", options={"default": true})
*/
protected $flag_active;
public function __construct()
{
$this->vehicles = new ArrayCollection();
@ -165,8 +159,6 @@ class Battery
$this->total_height = 0;
$this->date_create = new DateTime();
$this->flag_active = true;
}
public function getID()
@ -390,15 +382,4 @@ class Battery
{
return $this->image_file;
}
public function isActive()
{
return $this->flag_active;
}
public function setActive($flag_active = true)
{
$this->flag_active = $flag_active;
return $this;
}
}

View file

@ -1,209 +0,0 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use DateTime;
/**
* @ORM\Entity
* @ORM\Table(name="customer_delete_request")
*/
class CustomerDeleteRequest
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="string", length=50)
*/
protected $id;
// phone number
/**
* @ORM\Column(type="string", length=12)
*/
protected $phone_number;
// reason for account deletion
/**
* @ORM\Column(type="text", nullable=true)
*/
protected $reason;
// confirm code that we send via SMS
/**
* @ORM\Column(type="string", length=6, nullable=true)
*/
protected $confirm_code;
// if this request has been confirmed via SMS
/**
* @ORM\Column(type="boolean")
*/
protected $flag_confirmed;
// if this request has been completed
/**
* @ORM\Column(type="boolean")
*/
protected $flag_completed;
// date request was created
/**
* @ORM\Column(type="datetime")
*/
protected $date_created;
// date and time that the confirmation code was last sent
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $date_code_sent;
// date request was confirmed
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $date_confirmed;
// date customer was created
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $date_completed;
// link to customer
/**
* @ORM\ManyToOne(targetEntity="Customer")
* @ORM\JoinColumn(name="customer_id", referencedColumnName="id", nullable=true)
*/
protected $customer;
public function __construct()
{
$this->id = $this->generateKeyID();
$this->flag_confirmed = false;
$this->flag_completed = false;
$this->date_created = new DateTime();
$this->date_code_sent = null;
$this->date_confirmed = null;
$this->date_completed = null;
$this->reason = null;
$this->customer = null;
}
public function generateKeyID()
{
// use uniqid with unix timestamp prefix for now
return uniqid(time());
}
public function getID()
{
return $this->id;
}
public function setPhoneNumber($num)
{
$this->phone_number = $num;
return $this;
}
public function getPhoneNumber()
{
return $this->phone_number;
}
public function setReason($reason)
{
$this->reason = $reason;
return $this;
}
public function getReason()
{
return $this->reason;
}
public function setConfirmCode($code)
{
$this->confirm_code = $code;
return $this;
}
public function getConfirmCode()
{
return $this->confirm_code;
}
public function setConfirmed($flag = true)
{
$this->flag_confirmed = $flag;
return $this;
}
public function isConfirmed()
{
return $this->flag_confirmed;
}
public function setCompleted($flag = true)
{
$this->flag_completed = $flag;
return $this;
}
public function isCompleted()
{
return $this->flag_completed;
}
public function getDateCreated()
{
return $this->date_created;
}
public function setDateCodeSent(DateTime $date)
{
$this->date_code_sent = $date;
return $this;
}
public function getDateCodeSent()
{
return $this->date_code_sent;
}
public function setDateConfirmed(DateTime $date)
{
$this->date_confirmed = $date;
return $this;
}
public function getDateConfirmed()
{
return $this->date_confirmed;
}
public function setDateCompleted(DateTime $date)
{
$this->date_completed = $date;
return $this;
}
public function getDateCompleted()
{
return $this->date_completed;
}
public function setCustomer(Customer $cust = null)
{
$this->customer = $cust;
return $this;
}
public function getCustomer()
{
return $this->customer;
}
}

View file

@ -1,63 +0,0 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
* @ORM\Table(name="customer_location", indexes={
* @ORM\Index(name="cust_location_idx", columns={"code"}),
* })
*/
class CustomerLocation
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=25)
* @Assert\NotBlank()
*/
protected $code;
/**
* @ORM\Column(type="string", length=25)
* @Assert\NotBlank()
*/
protected $name;
public function getID()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function setCode($code)
{
$this->code = $code;
return $this;
}
public function getCode()
{
return $this->code;
}
}

View file

@ -20,7 +20,7 @@ class CustomerSession
*/
protected $id;
// link to customer
// link to customer er
/**
* @ORM\ManyToOne(targetEntity="Customer")
* @ORM\JoinColumn(name="customer_id", referencedColumnName="id", nullable=true)

View file

@ -2,13 +2,11 @@
namespace App\Entity;
use App\Ramcar\InsuranceApplicationStatus;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use DateTime;
use Doctrine\Common\Collections\Criteria;
/**
* @ORM\Entity
@ -116,15 +114,10 @@ class CustomerVehicle
*/
protected $flag_active;
// link to insurance
/**
* @ORM\OneToMany(targetEntity="InsuranceApplication", mappedBy="customer_vehicle")
*/
protected $insurance_applications;
public function __construct()
{
$this->flag_active = true;
$this->job_orders = new ArrayCollection();
}
@ -289,21 +282,4 @@ class CustomerVehicle
{
return $this->flag_active;
}
public function getInsuranceApplications()
{
return $this->insurance_applications;
}
public function getLatestInsuranceApplication()
{
$criteria = Criteria::create()
->where(Criteria::expr()->notIn('status', [InsuranceApplicationStatus::CANCELLED]))
->orderBy(['date_submit' => Criteria::DESC])
->setMaxResults(1);
$result = $this->insurance_applications->matching($criteria);
return !empty($result) ? $result[0] : null;
}
}

View file

@ -1,193 +0,0 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Ramcar\TransactionStatus;
use Symfony\Component\Validator\Constraints as Assert;
use DateTime;
/**
* @ORM\Entity
* @ORM\Table(name="gateway_transaction")
*/
class GatewayTransaction
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="Customer", inversedBy="transactions")
* @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
*/
protected $customer;
// date ticket was created
/**
* @ORM\Column(type="datetime")
*/
protected $date_create;
// date ticket was paid
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $date_pay;
// amount
/**
* @ORM\Column(type="bigint")
* @Assert\NotBlank()
*/
protected $amount;
// status of the transaction
/**
* @ORM\Column(type="string", length=50)
* @Assert\NotBlank()
*/
protected $status;
// type of transaction
/**
* @ORM\Column(type="string", length=50)
* @Assert\NotBlank()
*/
protected $type;
// gateway used for transaction
/**
* @ORM\Column(type="string", length=50)
* @Assert\NotBlank()
*/
protected $gateway;
// external transaction id
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
protected $ext_transaction_id;
// other data related to the transaction
/**
* @ORM\Column(type="json")
*/
protected $metadata;
public function __construct()
{
$this->date_create = new DateTime();
$this->status = TransactionStatus::PENDING;
$this->metadata = [];
}
public function getID()
{
return $this->id;
}
public function setCustomer(Customer $customer)
{
$this->customer = $customer;
return $this;
}
public function getCustomer()
{
return $this->customer;
}
public function setDateCreate(DateTime $date)
{
$this->date_create = $date;
return $this;
}
public function getDateCreate()
{
return $this->date_create;
}
public function setDatePay(DateTime $date)
{
$this->date_pay = $date;
return $this;
}
public function getDatePay()
{
return $this->date_pay;
}
public function setAmount($amount)
{
$this->amount = $amount;
return $this;
}
public function getAmount()
{
return $this->amount;
}
public function setStatus($status)
{
$this->status = $status;
return $this;
}
public function getStatus()
{
return $this->status;
}
public function setType($type)
{
$this->type = $type;
return $this;
}
public function getType()
{
return $this->type;
}
public function setGateway($gateway)
{
$this->gateway = $gateway;
return $this;
}
public function getGateway()
{
return $this->gateway;
}
public function setExtTransactionId($transaction_id)
{
$this->ext_transaction_id = $transaction_id;
return $this;
}
public function getExtTransactionId()
{
return $this->ext_transaction_id;
}
public function setMetadata($metadata)
{
$this->metadata = $metadata;
return $this;
}
public function getMetadata()
{
return $this->metadata;
}
}

View file

@ -114,9 +114,7 @@ class Hub
public function getAvailableRiders()
{
$crit = Criteria::create();
$crit->where(Criteria::expr()->eq('flag_available', true))
->where(Criteria::expr()->eq('flag_active', true))
->where(Criteria::expr()->eq('current_job_order', null));
$crit->where(Criteria::expr()->eq('flag_available', true));
return $this->riders->matching($crit);
}

View file

@ -1,226 +0,0 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use DateTime;
/**
* @ORM\Entity
* @ORM\Table(name="insurance_application")
*/
class InsuranceApplication
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// link to customer
/**
* @ORM\ManyToOne(targetEntity="Customer")
* @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
*/
protected $customer;
// link to customer vehicle
/**
* @ORM\ManyToOne(targetEntity="CustomerVehicle", inversedBy="insurance")
* @ORM\JoinColumn(name="customer_vehicle_id", referencedColumnName="id")
* @Assert\NotBlank()
*/
protected $customer_vehicle;
// gateway transaction
/**
* @ORM\OneToOne(targetEntity="GatewayTransaction")
* @ORM\JoinColumn(name="gateway_transaction_id", referencedColumnName="id")
*/
protected $gateway_transaction;
// status
/**
* @ORM\Column(type="string", length=32)
*/
protected $status;
// URL of COC
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
protected $coc_url;
// date the application was submitted
/**
* @ORM\Column(type="datetime")
*/
protected $date_submit;
// date the application was paid
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $date_pay;
// date the application was marked as completed by the insurance api
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $date_complete;
// date the application is set to expire
/**
* @ORM\Column(type="datetime", nullable=true)
*/
protected $date_expire;
// external transaction id
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
protected $ext_transaction_id;
// form data when submitting the application
/**
* @ORM\Column(type="json")
*/
protected $metadata;
public function __construct()
{
$this->date_submit = new DateTime();
$this->date_pay = null;
$this->date_complete = null;
$this->date_expire = null;
$this->metadata = [];
}
public function getID()
{
return $this->id;
}
public function setCustomer(Customer $cust = null)
{
$this->customer = $cust;
return $this;
}
public function getCustomer()
{
return $this->customer;
}
public function setCustomerVehicle(CustomerVehicle $cv = null)
{
$this->customer_vehicle = $cv;
return $this;
}
public function getCustomerVehicle()
{
return $this->customer_vehicle;
}
public function setDateSubmit(DateTime $date)
{
$this->date_submit = $date;
return $this;
}
public function getDateSubmit()
{
return $this->date_submit;
}
public function setGatewayTransaction(GatewayTransaction $transaction)
{
$this->gateway_transaction = $transaction;
return $this;
}
public function getGatewayTransaction()
{
return $this->gateway_transaction;
}
public function setStatus($status)
{
return $this->status = $status;
}
public function getStatus()
{
return $this->status;
}
public function setCOC($url)
{
return $this->coc_url = $url;
}
public function getCOC()
{
return $this->coc_url;
}
public function setDatePay(DateTime $date)
{
$this->date_pay = $date;
return $this;
}
public function getDatePay()
{
return $this->date_pay;
}
public function setDateComplete(DateTime $date)
{
$this->date_complete = $date;
return $this;
}
public function getDateComplete()
{
return $this->date_complete;
}
public function setDateExpire(DateTime $date)
{
$this->date_expire = $date;
return $this;
}
public function getDateExpire()
{
return $this->date_expire;
}
public function setExtTransactionId($transaction_id)
{
$this->ext_transaction_id = $transaction_id;
return $this;
}
public function getExtTransactionId()
{
return $this->ext_transaction_id;
}
public function setMetadata($metadata)
{
return $this->metadata = $metadata;
}
public function getMetadata()
{
return $this->metadata;
}
}

View file

@ -50,24 +50,10 @@ class InvoiceItem
*/
protected $battery;
// battery size for trade in items
/**
* @ORM\ManyToOne(targetEntity="BatterySize")
* @ORM\JoinColumn(name="battery_size_id", referencedColumnName="id")
*/
protected $battery_size;
// trade in type
/**
* @ORM\Column(type="string", length=20)
*/
protected $trade_in_type;
public function __construct()
{
$this->title = '';
$this->price = 0.0;
$this->trade_in_type = '';
}
public function getID()
@ -129,26 +115,4 @@ class InvoiceItem
{
return $this->battery;
}
public function setBatterySize(BatterySize $battery_size)
{
$this->battery_size = $battery_size;
return $this;
}
public function getBatterySize()
{
return $this->battery_size;
}
public function setTradeInType(string $trade_in_type)
{
$this->trade_in_type = $trade_in_type;
return $this;
}
public function getTradeInType()
{
return $this->trade_in_type;
}
}

View file

@ -1,97 +0,0 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="item_price")
*/
class ItemPrice
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\ManyToOne(targetEntity="PriceTier", inversedBy="item_prices")
* @ORM\JoinColumn(name="price_tier_id", referencedColumnName="id")
*/
protected $price_tier;
// item type
/**
* @ORM\ManyToOne(targetEntity="ItemType", inversedBy="items")
* @ORM\JoinColumn(name="item_type_id", referencedColumnName="id")
*/
protected $item_type;
// could be battery id or service offering id, loosely coupled
/**
* @ORM\Column(type="integer")
*/
protected $item_id;
// current price
// NOTE: we need to move the decimal point two places to the left to get actual value
// we want to avoid floating point problems
/**
* @ORM\Column(type="integer")
*/
protected $price;
public function getID()
{
return $this->id;
}
public function setPriceTier(PriceTier $price_tier)
{
$this->price_tier = $price_tier;
return $this;
}
public function getPriceTier()
{
return $this->price_tier;
}
public function setItemType(ItemType $item_type)
{
$this->item_type = $item_type;
return $this;
}
public function getItemType()
{
return $this->item_type;
}
public function setItemID($item_id)
{
$this->item_id = $item_id;
return $this;
}
public function getItemID()
{
return $this->item_id;
}
public function setPrice($price)
{
$this->price = $price;
return $this;
}
public function getPrice()
{
return $this->price;
}
}

View file

@ -1,80 +0,0 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
* @ORM\Table(name="item_type", indexes={
* @ORM\Index(name="item_type_idx", columns={"code"})
* })
*/
class ItemType
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $name;
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $code;
// items under an item type
/**
* @ORM\OneToMany(targetEntity="ItemPrice", mappedBy="item_type")
*/
protected $items;
public function __construct()
{
$this->code = '';
}
public function getID()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function setCode($code)
{
$this->code = $code;
return $this;
}
public function getCode()
{
return $this->code;
}
public function getItems()
{
return $this->items;
}
}

View file

@ -422,31 +422,6 @@ class JobOrder
*/
protected $ownership_type;
// customer location
/**
* @ORM\ManyToOne(targetEntity="CustomerLocation", inversedBy="job_orders")
* @ORM\JoinColumn(name="cust_location_id", referencedColumnName="id", nullable=true)
*/
protected $cust_location;
// inventory count of hub at time of hub assignment
/**
* @ORM\Column(type="smallint")
*/
protected $inventory_count;
// flag to indicate if customer is new aka has one or less job order in system
/**
* @ORM\Column(type="boolean")
*/
protected $flag_cust_new;
// only for tire service, if it requires sealant or not
/**
* @ORM\Column(type="boolean")
*/
protected $flag_sealant;
public function __construct()
{
$this->date_create = new DateTime();
@ -464,7 +439,6 @@ class JobOrder
$this->trade_in_type = null;
$this->flag_rider_rating = false;
$this->flag_coolant = false;
$this->flag_sealant = false;
$this->priority = 0;
$this->meta = [];
@ -472,10 +446,6 @@ class JobOrder
$this->phone_mobile = '';
$this->will_wait = WillingToWaitContent::WILLING_TO_WAIT;
$this->inventory_count = 0;
$this->flag_cust_new = false;
}
public function getID()
@ -1229,49 +1199,4 @@ class JobOrder
{
return $this->ownership_type;
}
public function setCustomerLocation(CustomerLocation $cust_location = null)
{
$this->cust_location = $cust_location;
return $this;
}
public function getCustomerLocation()
{
return $this->cust_location;
}
public function setInventoryCount($inventory_count)
{
$this->inventory_count = $inventory_count;
return $this;
}
public function getInventoryCount()
{
return $this->inventory_count;
}
public function setCustNew($flag_cust_new = true)
{
$this->flag_cust_new = $flag_cust_new;
return $this;
}
public function isCustNew()
{
return $this->flag_cust_new;
}
public function setHasSealant($flag = true)
{
$this->flag_sealant = $flag;
return $this;
}
public function hasSealant()
{
return $this->flag_sealant;
}
}

View file

@ -21,7 +21,7 @@ class MotoliteEvent
protected $id;
/**
* @ORM\Column(type="string", length=255)
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $name;

View file

@ -1,88 +0,0 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* @ORM\Entity
* @ORM\Table(name="price_tier")
*/
class PriceTier
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// name of price tier
/**
* @ORM\Column(type="string", length=80)
*/
protected $name;
// supported areas under price tier
/**
* @ORM\OneToMany(targetEntity="SupportedArea", mappedBy="price_tier");
*/
protected $supported_areas;
// items under a price tier
/**
* @ORM\OneToMany(targetEntity="ItemPrice", mappedBy="price_tier")
*/
protected $item_prices;
public function __construct()
{
$this->supported_areas = new ArrayCollection();
$this->items = new ArrayCollection();
}
public function getID()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function getSupportedAreaObjects()
{
return $this->supported_areas;
}
public function getSupportedAreas()
{
$str_supported_areas = [];
foreach ($this->supported_areas as $supported_area)
$str_supported_areas[] = $supported_area->getID();
return $str_supported_areas;
}
public function clearSupportedAreas()
{
$this->supported_areas->clear();
return $this;
}
public function getItemPrices()
{
return $this->item_prices;
}
}

View file

@ -6,30 +6,16 @@ use Catalyst\AuthBundle\Entity\Role as BaseRole;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* @ORM\Entity
* @ORM\Table(name="role")
* @ORM\Table(name="user_role")
* @UniqueEntity("id")
* @UniqueEntity("name")
*/
class Role extends BaseRole
{
/**
* @ORM\Id
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $id;
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $name;
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="roles", fetch="EXTRA_LAZY")
*/

View file

@ -1,81 +0,0 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* @ORM\Entity
* @ORM\Table(name="service_offering", indexes={
* @ORM\Index(name="service_offering_idx", columns={"code"}),
* })
*/
class ServiceOffering
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $name;
/**
* @ORM\Column(type="string", length=80)
* @Assert\NotBlank()
*/
protected $code;
// service fee
/**
* @ORM\Column(type="decimal", precision=9, scale=2)
*/
protected $fee;
public function getID()
{
return $this->id;
}
public function setName($name)
{
$this->name = $name;
return $this;
}
public function getName()
{
return $this->name;
}
public function setCode($code)
{
$this->code = $code;
return $this;
}
public function getCode()
{
return $this->code;
}
public function setFee($fee)
{
$this->fee = $fee;
return $this;
}
public function getFee()
{
return $this->fee;
}
}

View file

@ -39,24 +39,9 @@ class SupportedArea
*/
protected $coverage_area;
// prevent certain hub filters from being used
/**
* @ORM\Column(type="json", nullable=true)
*/
protected $hub_filter_exceptions;
/**
* @ORM\ManyToOne(targetEntity="PriceTier", inversedBy="supported_areas")
* @ORM\JoinColumn(name="price_tier_id", referencedColumnName="id", nullable=true)
*/
protected $price_tier;
public function __construct()
{
$this->date_create = new DateTime();
$this->price_tier = null;
$this->hub_filter_exceptions = [];
}
public function getID()
@ -72,7 +57,7 @@ class SupportedArea
public function getDateCreate()
{
return $this->date_create;
return $this->date_Create;
}
public function setName($name)
@ -97,27 +82,5 @@ class SupportedArea
{
return $this->coverage_area;
}
public function setPriceTier(PriceTier $price_tier = null)
{
$this->price_tier = $price_tier;
return $this;
}
public function getPriceTier()
{
return $this->price_tier;
}
public function setHubFilterExceptions($exceptions)
{
$this->hub_filter_exceptions = $exceptions;
return $this;
}
public function getHubFilterExceptions()
{
return $this->hub_filter_exceptions;
}
}

View file

@ -139,22 +139,9 @@ class Ticket
*/
protected $other_description;
// is it a late documentation?
/**
* @ORM\Column(type="boolean", nullable=true)
*/
protected $flag_late_doc;
// reason for late documentation
/**
* @ORM\Column(type="text", nullable=true)
*/
protected $late_doc_reason;
public function __construct()
{
$this->date_create = new DateTime();
$this->flag_late_doc = false;
}
public function getID()
@ -367,26 +354,4 @@ class Ticket
{
return $this->other_description;
}
public function setLateDoc($flag_late_doc = true)
{
$this->flag_late_doc = $flag_late_doc;
return $this;
}
public function isLateDoc()
{
return $this->flag_late_doc;
}
public function setLateDocReason($late_doc_reason)
{
$this->late_doc_reason = $late_doc_reason;
return $this;
}
public function getLateDocReason()
{
return $this->late_doc_reason;
}
}

View file

@ -12,7 +12,7 @@ use Serializable;
/**
* @ORM\Entity
* @ORM\Table(name="user")
* @ORM\Table(name="user_user")
* @UniqueEntity("username")
* @UniqueEntity("email")
*/
@ -39,7 +39,7 @@ class User extends BaseUser implements Serializable
/**
* @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
* @ORM\JoinTable(name="user_role")
* @ORM\JoinTable(name="user_user_role")
*/
protected $roles;

View file

@ -4,8 +4,6 @@ namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;
use Symfony\Component\Validator\Constraints as Assert;
/**
@ -179,12 +177,4 @@ class Vehicle
{
return $this->cust_vehicles;
}
public function getActiveBatteries()
{
$crit = Criteria::create();
$crit->where(Criteria::expr()->eq('flag_active', true));
return $this->batteries->matching($crit);
}
}

View file

@ -1,78 +0,0 @@
<?php
namespace App\EntityListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\GatewayTransaction;
use App\Entity\InsuranceApplication;
use App\Service\InsuranceConnector;
use App\Ramcar\InsuranceApplicationStatus;
use App\Ramcar\TransactionStatus;
use DateTime;
class GatewayTransactionListener
{
protected $ic;
protected $em;
public function __construct(EntityManagerInterface $em, InsuranceConnector $ic)
{
$this->em = $em;
$this->ic = $ic;
}
public function postUpdate(GatewayTransaction $gt_obj, LifecycleEventArgs $args)
{
// get transaction changes
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
$changeset = $uow->getEntityChangeSet($gt_obj);
if (array_key_exists('status', $changeset)) {
$field_changes = $changeset['status'];
$prev_value = $field_changes[0] ?? null;
$new_value = $field_changes[1] ?? null;
// only do something if the status has changed to paid
if ($prev_value !== $new_value && $new_value === TransactionStatus::PAID) {
// handle based on type
// TODO: add types here as we go. there's probably a better way to do this.
switch ($gt_obj->getType()) {
case 'insurance_premium':
return $this->handleInsurancePremium($gt_obj);
break;
default:
break;
}
}
}
}
protected function handleInsurancePremium($gt_obj)
{
// get insurance application object
$obj = $this->em->getRepository(InsuranceApplication::class)->findOneBy([
'gateway_transaction' => $gt_obj,
]);
// make sure the object exists and has not been processed yet
if (!empty($obj) && $obj->getStatus() === InsuranceApplicationStatus::CREATED) {
// mark as paid
$obj->setDatePay(new DateTime());
$obj->setStatus(InsuranceApplicationStatus::PAID);
$this->em->flush();
// flag on api as paid
$result = $this->ic->tagApplicationPaid($obj->getExtTransactionId());
// something went wrong with insurance api
if (!$result['success'] || $result['response']['transaction_code'] !== 'GR004') {
error_log("INSURANCE MARK AS PAID FAILED FOR " . $obj->getID() . ": " . $result['error']['message']);
}
}
}
}

View file

@ -1,166 +0,0 @@
<?php
namespace App\InvoiceRule;
use App\InvoiceRuleInterface;
use Doctrine\ORM\EntityManagerInterface;
use App\Ramcar\ServiceType;
use App\Ramcar\TradeInType;
use App\Entity\Battery;
use App\Entity\ServiceOffering;
use App\Entity\ItemType;
use App\Service\PriceTierManager;
class BatteryReplacementWarranty implements InvoiceRuleInterface
{
protected $em;
protected $pt_manager;
public function __construct(EntityManagerInterface $em, PriceTierManager $pt_manager)
{
$this->em = $em;
$this->pt_manager = $pt_manager;
}
public function getID()
{
return 'battery_warranty';
}
public function compute($criteria, &$total)
{
$stype = $criteria->getServiceType();
$pt_id = $criteria->getPriceTier();
$items = [];
if ($stype == $this->getID())
{
// get the entries
$entries = $criteria->getEntries();
foreach($entries as $entry)
{
$batt = $entry['battery'];
$qty = 1;
// check if price tier has item price
$pt_price = $this->getPriceTierItemPrice($pt_id);
if ($pt_price == null)
$price = $this->getServiceTypeFee();
else
$price = $pt_price;
$items[] = [
'service_type' => $this->getID(),
'battery' => $batt,
'qty' => $qty,
'title' => $this->getTitle($batt),
'price' => $price,
];
$qty_price = bcmul($price, $qty, 2);
$total['total_price'] = bcadd($total['total_price'], $qty_price, 2);
}
}
return $items;
}
public function getServiceTypeFee()
{
$code = 'battery_replacement_warranty_fee';
// find the service fee using the code
// if we can't find the fee, return 0
$fee = $this->em->getRepository(ServiceOffering::class)->findOneBy(['code' => $code]);
if ($fee == null)
return 0;
return $fee->getFee();
}
public function validatePromo($criteria, $promo_id)
{
return false;
}
public function validateInvoiceItems($criteria, $invoice_items)
{
// check service type. Only battery sales and battery warranty should have invoice items. Since this is the
// battery replacement warranty rule, we only check for battery replacement warranty.
$stype = $criteria->getServiceType();
if ($stype != ServiceType::BATTERY_REPLACEMENT_WARRANTY)
return null;
// return error if there's a problem, false otherwise
if (!empty($invoice_items))
{
// check if this is a valid battery
foreach ($invoice_items as $item)
{
$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;
if (empty($item['trade_in']))
{
$trade_in = null;
$criteria->addEntry($battery, $trade_in, $qty);
}
}
}
return null;
}
protected function getPriceTierItemPrice($pt_id)
{
// price_tier is default
if ($pt_id == 0)
return null;
// find the item type for service offering
$item_type = $this->em->getRepository(ItemType::class)->findOneBy(['code' => 'service_offering']);
if ($item_type == null)
return null;
// find the service offering
$code = 'battery_replacement_warranty_fee';
$service = $this->em->getRepository(ServiceOffering::class)->findOneBy(['code' => $code]);
// check if service is null. If null, return null
if ($service == null)
return null;
$item_type_id = $item_type->getID();
$item_id = $service->getID();
$price = $this->pt_manager->getItemPrice($pt_id, $item_type_id, $item_id);
return $price;
}
protected function getTitle($battery)
{
$title = $battery->getModel()->getName() . ' ' . $battery->getSize()->getName() . ' - Service Unit';
return $title;
}
}

View file

@ -1,155 +0,0 @@
<?php
namespace App\InvoiceRule;
use Doctrine\ORM\EntityManagerInterface;
use App\InvoiceRuleInterface;
use App\Ramcar\TradeInType;
use App\Ramcar\ServiceType;
use App\Entity\Battery;
use App\Entity\ItemType;
use App\Service\PriceTierManager;
class BatterySales implements InvoiceRuleInterface
{
protected $em;
protected $pt_manager;
public function __construct(EntityManagerInterface $em, PriceTierManager $pt_manager)
{
$this->em = $em;
$this->pt_manager = $pt_manager;
}
public function getID()
{
return 'battery_new';
}
public function compute($criteria, &$total)
{
$stype = $criteria->getServiceType();
$pt = $criteria->getPriceTier();
$items = [];
if ($stype == $this->getID())
{
// get the entries
$entries = $criteria->getEntries();
foreach($entries as $entry)
{
$qty = $entry['qty'];
$trade_in = null;
// check if entry is for trade in
if (isset($entry['trade_in']))
$trade_in = $entry['trade_in'];
// entry is a battery purchase
if ($trade_in == null)
{
// safe to get entry with battery key since CRM and apps
// will set this for a battery purchase and trade_in will
// will not be set
$batt = $entry['battery'];
// check if price tier has item price for battery
$pt_price = $this->getPriceTierItemPrice($pt, $batt);
if ($pt_price == null)
$price = $batt->getSellingPrice();
else
$price = $pt_price;
$items[] = [
'service_type' => $this->getID(),
'battery' => $batt,
'qty' => $qty,
'title' => $this->getTitle($batt),
'price' => $price,
];
$qty_price = bcmul($price, $qty, 2);
$total['sell_price'] = bcadd($total['sell_price'], $qty_price, 2);
$total['total_price'] = bcadd($total['total_price'], $qty_price, 2);
}
}
}
return $items;
}
public function validatePromo($criteria, $promo_id)
{
return false;
}
public function validateInvoiceItems($criteria, $invoice_items)
{
// check service type. Only battery sales and battery warranty should have invoice items. Since this is the battery sales
// rule, we only check for battery sales.
$stype = $criteria->getServiceType();
if ($stype != ServiceType::BATTERY_REPLACEMENT_NEW)
return null;
// return error if there's a problem, false otherwise
if (!empty($invoice_items))
{
// check if this is a valid battery
foreach ($invoice_items as $item)
{
if (isset($item['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;
$trade_in = null;
$criteria->addEntry($battery, $trade_in, $qty);
}
}
}
return null;
}
protected function getPriceTierItemPrice($pt_id, $batt)
{
// price tier is default
if ($pt_id == 0)
return null;
// find the item type battery
$item_type = $this->em->getRepository(ItemType::class)->findOneBy(['code' => 'battery']);
if ($item_type == null)
return null;
$item_type_id = $item_type->getID();
$item_id = $batt->getID();
$price = $this->pt_manager->getItemPrice($pt_id, $item_type_id, $item_id);
return $price;
}
protected function getTitle($battery)
{
$title = $battery->getModel()->getName() . ' ' . $battery->getSize()->getName();
return $title;
}
}

View file

@ -1,116 +0,0 @@
<?php
namespace App\InvoiceRule;
use Doctrine\ORM\EntityManagerInterface;
use App\InvoiceRuleInterface;
use App\Ramcar\ServiceType;
use App\Ramcar\DiscountApply;
use App\Entity\Promo;
class DiscountType implements InvoiceRuleInterface
{
protected $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
public function getID()
{
return 'discount';
}
public function compute($criteria, &$total)
{
$items = [];
$promos = $criteria->getPromos();
if (empty($promos))
return $items;
// 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 = bcmul($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);
$num1 = bcdiv(1.5, 0.7, 9);
$num1_rate = bcmul($num1, $rate, 9);
$multiplier = bcsub(1, $num1_rate, 9);
$discount = bcmul($total['sell_price'], $multiplier, 2);
break;
}
// if discount is higher than 0, add to items
if ($discount > 0)
{
$qty = 1;
$price = bcmul(-1, $discount, 2);
$items[] = [
'promo' => $promo,
'title' => $this->getTitle(),
'qty' => $qty,
'price' => $price,
];
}
$total['discount'] = $discount;
$total['total_price'] = bcsub($total['total_price'], $discount, 2);
return $items;
}
public function validatePromo($criteria, $promo_id)
{
// return error if there's a problem, false otherwise
// check service type
$stype = $criteria->getServiceType();
// discount/promo only applies for battery sales
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 validateInvoiceItems($criteria, $invoice_items)
{
return null;
}
protected function getTitle()
{
$title = 'Promo discount';
return $title;
}
}

View file

@ -1,238 +0,0 @@
<?php
namespace App\InvoiceRule;
use Doctrine\ORM\EntityManagerInterface;
use App\InvoiceRuleInterface;
use App\Ramcar\FuelType;
use App\Ramcar\ServiceType;
use App\Entity\ServiceOffering;
use App\Entity\CustomerVehicle;
use App\Entity\ItemType;
use App\Service\PriceTierManager;
class Fuel implements InvoiceRuleInterface
{
protected $em;
protected $pt_manager;
public function __construct(EntityManagerInterface $em, PriceTierManager $pt_manager)
{
$this->em = $em;
$this->pt_manager = $pt_manager;
}
public function getID()
{
return 'fuel';
}
public function compute($criteria, &$total)
{
$stype = $criteria->getServiceType();
$pt_id = $criteria->getPriceTier();
$items = [];
if ($stype == $this->getID())
{
$cv = $criteria->getCustomerVehicle();
// check if price tier has item price
$pt_price = $this->getPriceTierItemPrice($pt_id, $cv);
if ($pt_price == null)
$service_price = $this->getServiceTypeFee($cv);
else
$service_price = $pt_price;
$ftype = $cv->getFuelType();
// add the service fee to items
$qty = 1;
$items[] = [
'service_type' => $this->getID(),
'qty' => $qty,
'title' => $this->getServiceTitle($ftype),
'price' => $service_price,
];
$qty_fee = bcmul($qty, $service_price, 2);
$total_price = $qty_fee;
switch ($ftype)
{
case FuelType::GAS:
case FuelType::DIESEL:
$qty = 1;
// check if price tier has item price for fuel type
$pt_price = $this->getPriceTierFuelItemPrice($pt_id, $ftype);
if ($pt_price == null)
$price = $this->getFuelFee($ftype);
else
$price = $pt_price;
$items[] = [
'service_type' => $this->getID(),
'qty' => $qty,
'title' => $this->getTitle($ftype),
'price' => $price,
];
$qty_price = bcmul($price, $qty, 2);
$total_price = bcadd($total_price, $qty_price, 2);
break;
default:
$qty = 1;
$price = 0;
$items[] = [
'service_type' => $this->getID(),
'qty' => $qty,
'title' => $this->getTitle('Unknown'),
'price' => $price,
];
$qty_price = bcmul($price, $qty, 2);
$total_price = bcadd($total_price, $qty_price, 2);
break;
}
$total['total_price'] = bcadd($total['total_price'], $total_price, 2);
}
return $items;
}
public function getServiceTypeFee(CustomerVehicle $cv)
{
// check if customer vehicle has a motolite battery
// if yes, set the code to the motolite user service fee
if ($cv->hasMotoliteBattery())
$code = 'motolite_user_service_fee';
else
$code = 'fuel_service_fee';
// find the service fee using the code
// if we can't find the fee, return 0
$fee = $this->em->getRepository(ServiceOffering::class)->findOneBy(['code' => $code]);
if ($fee == null)
return 0;
return $fee->getFee();
}
public function getFuelFee($fuel_type)
{
$code = '';
if ($fuel_type == FuelType::GAS)
$code = 'fuel_gas_fee';
if ($fuel_type == FuelType::DIESEL)
$code = 'fuel_diesel_fee';
// find the fuel fee for the specific fuel type using the code
// if we can't find the fee, return 0
$fee = $this->em->getRepository(ServiceOffering::class)->findOneBy(['code' => $code]);
if ($fee == null)
return 0;
return $fee->getFee();
}
public function validatePromo($criteria, $promo_id)
{
return false;
}
public function validateInvoiceItems($criteria, $invoice_items)
{
return null;
}
protected function getPriceTierItemPrice($pt_id, CustomerVehicle $cv)
{
// price_tier is default
if ($pt_id == 0)
return null;
// find the item type for service offering
$item_type = $this->em->getRepository(ItemType::class)->findOneBy(['code' => 'service_offering']);
if ($item_type == null)
return null;
// find the service offering
// check if customer vehicle has a motolite battery
// if yes, set the code to the motolite user service fee
if ($cv->hasMotoliteBattery())
$code = 'motolite_user_service_fee';
else
$code = 'fuel_service_fee';
$service = $this->em->getRepository(ServiceOffering::class)->findOneBy(['code' => $code]);
// check if service is null. If null, return null
if ($service == null)
return null;
$item_type_id = $item_type->getID();
$item_id = $service->getID();
$price = $this->pt_manager->getItemPrice($pt_id, $item_type_id, $item_id);
return $price;
}
protected function getPriceTierFuelItemPrice($pt_id, $fuel_type)
{
// price_tier is default
if ($pt_id == 0)
return null;
// find the item type for service offering
$item_type = $this->em->getRepository(ItemType::class)->findOneBy(['code' => 'service_offering']);
if ($item_type == null)
return null;
// find the service offering
$code = '';
if ($fuel_type == FuelType::GAS)
$code = 'fuel_gas_fee';
if ($fuel_type == FuelType::DIESEL)
$code = 'fuel_diesel_fee';
$service = $this->em->getRepository(ServiceOffering::class)->findOneBy(['code' => $code]);
// check if service is null. If null, return null
if ($service == null)
return null;
$item_type_id = $item_type->getID();
$item_id = $service->getID();
$price = $this->pt_manager->getItemPrice($pt_id, $item_type_id, $item_id);
return $price;
}
protected function getTitle($fuel_type)
{
$title = '4L - ' . ucfirst($fuel_type);
return $title;
}
protected function getServiceTitle($fuel_type)
{
$title = 'Service - ' . ServiceType::getName(ServiceType::EMERGENCY_REFUEL);
return $title;
}
}

View file

@ -1,156 +0,0 @@
<?php
namespace App\InvoiceRule;
use Doctrine\ORM\EntityManagerInterface;
use App\InvoiceRuleInterface;
use App\Entity\ServiceOffering;
use App\Entity\CustomerVehicle;
use App\Entity\ItemType;
use App\Ramcar\TransactionOrigin;
use App\Service\PriceTierManager;
class Jumpstart implements InvoiceRuleInterface
{
protected $em;
protected $pt_manager;
public function __construct(EntityManagerInterface $em, PriceTierManager $pt_manager)
{
$this->em = $em;
$this->pt_manager = $pt_manager;
}
public function getID()
{
return 'jumpstart_troubleshoot';
}
public function compute($criteria, &$total)
{
$stype = $criteria->getServiceType();
$source = $criteria->getSource();
$pt_id = $criteria->getPriceTier();
$items = [];
if ($stype == $this->getID())
{
$cv = $criteria->getCustomerVehicle();
// check if price tier has item price
$pt_price = $this->getPriceTierItemPrice($pt_id, $source, $cv);
if ($pt_price == null)
$price = $this->getServiceTypeFee($source, $cv);
else
$price = $pt_price;
// add the service fee to items
$qty = 1;
$items[] = [
'service_type' => $this->getID(),
'qty' => $qty,
'title' => $this->getServiceTitle(),
'price' => $price,
];
$qty_price = bcmul($price, $qty, 2);
$total['total_price'] = bcadd($total['total_price'], $qty_price, 2);
}
return $items;
}
public function getServiceTypeFee($source, CustomerVehicle $cv)
{
// get the service fee code, depending on the JO source and if customer vehicle has a motolite battery
$code = $this->getServiceFeeCode($cv, $source);
$fee = $this->em->getRepository(ServiceOffering::class)->findOneBy(['code' => $code]);
if ($fee == null)
return 0;
return $fee->getFee();
}
public function validatePromo($criteria, $promo_id)
{
return false;
}
public function validateInvoiceItems($criteria, $invoice_items)
{
return null;
}
protected function getPriceTierItemPrice($pt_id, $source, $cv)
{
// price_tier is default
if ($pt_id == 0)
return null;
// find the item type for service offering
$item_type = $this->em->getRepository(ItemType::class)->findOneBy(['code' => 'service_offering']);
if ($item_type == null)
return null;
// get the service fee code, depending on the JO source and if customer vehicle has a motolite battery
$code = $this->getServiceFeeCode($cv, $source);
// find the service offering
$service = $this->em->getRepository(ServiceOffering::class)->findOneBy(['code' => $code]);
// check if service is null. If null, return null
if ($service == null)
return null;
$item_type_id = $item_type->getID();
$item_id = $service->getID();
$price = $this->pt_manager->getItemPrice($pt_id, $item_type_id, $item_id);
return $price;
}
protected function getServiceTitle()
{
$title = 'Service - Troubleshooting fee';
return $title;
}
protected function getServiceFeeCode(CustomerVehicle $cv, $source)
{
// check the source of JO
// (1) if from app, service fee is 0 if motolite user. jumpstart fee for app if non-motolite user.
// (2) any other source, jumpstart fees are charged whether motolite user or not. Service fees for non-motolite
// and motolite users are now different (used to be the same)
if ($source == TransactionOrigin::MOBILE_APP)
{
if ($cv->hasMotoliteBattery())
$code = 'motolite_user_service_fee';
else
$code = 'jumpstart_fee_mobile_app';
}
else
{
error_log('hotline');
if ($cv->hasMotoliteBattery())
{
error_log('has motolite battery');
$code = 'motolite_user_jumpstart_fee';
}
else
$code = 'jumpstart_fee';
}
return $code;
}
}

View file

@ -1,134 +0,0 @@
<?php
namespace App\InvoiceRule;
use Doctrine\ORM\EntityManagerInterface;
use App\InvoiceRuleInterface;
use App\Entity\ServiceOffering;
use App\Entity\ItemType;
use App\Entity\CustomerVehicle;
use App\Service\PriceTierManager;
class JumpstartWarranty implements InvoiceRuleInterface
{
protected $em;
protected $pt_manager;
public function __construct(EntityManagerInterface $em, PriceTierManager $pt_manager)
{
$this->em = $em;
$this->pt_manager = $pt_manager;
}
public function getID()
{
return 'jumpstart_warranty';
}
public function compute($criteria, &$total)
{
$stype = $criteria->getServiceType();
$pt_id = $criteria->getPriceTier();
$items = [];
if ($stype == $this->getID())
{
$cv = $criteria->getCustomerVehicle();
// check if price tier has item price
$pt_price = $this->getPriceTierItemPrice($pt_id, $cv);
if ($pt_price == null)
$price = $this->getServiceTypeFee($cv);
else
$price = $pt_price;
// add the service fee to items
$qty = 1;
$items[] = [
'service_type' => $this->getID(),
'qty' => $qty,
'title' => $this->getServiceTitle(),
'price' => $price,
];
$qty_price = bcmul($price, $qty, 2);
$total['total_price'] = bcadd($total['total_price'], $qty_price, 2);
}
return $items;
}
public function getServiceTypeFee(CustomerVehicle $cv)
{
// check if user has motolite battery.
// Motolite users now have a service fee for jumpstart warranty
if ($cv->hasMotoliteBattery())
$code = 'motolite_user_jumpstart_warranty_fee';
else
$code = 'jumpstart_warranty_fee';
// find the service fee using the code
// if we can't find the fee, return 0
$fee = $this->em->getRepository(ServiceOffering::class)->findOneBy(['code' => $code]);
if ($fee == null)
return 0;
return $fee->getFee();
}
public function validatePromo($criteria, $promo_id)
{
return false;
}
public function validateInvoiceItems($criteria, $invoice_items)
{
return null;
}
protected function getPriceTierItemPrice($pt_id, CustomerVehicle $cv)
{
// price_tier is default
if ($pt_id == 0)
return null;
// find the item type for service offering
$item_type = $this->em->getRepository(ItemType::class)->findOneBy(['code' => 'service_offering']);
if ($item_type == null)
return null;
// find the service offering
// check if user has motolite battery.
// Motolite users now have a service fee for jumpstart warranty
if ($cv->hasMotoliteBattery())
$code = 'motolite_user_jumpstart_warranty_fee';
else
$code = 'jumpstart_warranty_fee';
$service = $this->em->getRepository(ServiceOffering::class)->findOneBy(['code' => $code]);
// check if service is null. If null, return null
if ($service == null)
return null;
$item_type_id = $item_type->getID();
$item_id = $service->getID();
$price = $this->pt_manager->getItemPrice($pt_id, $item_type_id, $item_id);
return $price;
}
protected function getServiceTitle()
{
$title = 'Service - Troubleshooting fee';
return $title;
}
}

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