Merge branch '119-rider-api' into 'master'

Resolve "Rider API"

Closes #119

See merge request jankstudio/resq!108
This commit is contained in:
Kendrick Chan 2018-05-23 01:35:42 +00:00
commit a7f5a85e65
7 changed files with 739 additions and 1 deletions

View file

@ -23,6 +23,10 @@ security:
pattern: ^\/api\/ pattern: ^\/api\/
security: false security: false
rider_api:
pattern: ^\/rapi\/
security: false
main: main:
form_login: form_login:
login_path: login login_path: login

View file

@ -0,0 +1,41 @@
# rider app api
rapi_register:
path: /rapi/register
controller: App\Controller\RAPIController::register
methods: [POST]
rapi_login:
path: /rapi/login
controller: App\Controller\RAPIController::login
methods: [POST]
rapi_logout:
path: /rapi/logout
controller: App\Controller\RAPIController::logout
methods: [POST]
rapi_jo_get:
path: /rapi/joborder
controller: App\Controller\RAPIController::getJobOrder
methods: [GET]
rapi_jo_accept:
path: /rapi/accept
controller: App\Controller\RAPIController::acceptJobOrder
methods: [POST]
rapi_jo_cancel:
path: /rapi/cancel
controller: App\Controller\RAPIController::cancelJobOrder
methods: [POST]
rapi_arrive:
path: /rapi/arrive
controller: App\Controller\RAPIController::arrive
methods: [POST]
rapi_payment:
path: /rapi/payment
controller: App\Controller\RAPIController::payment
methods: [POST]

View file

@ -0,0 +1,453 @@
<?php
namespace App\Controller;
use Doctrine\ORM\Query;
use Doctrine\ORM\QueryBuilder;
use Doctrine\DBAL\DBALException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use CrEOF\Spatial\PHP\Types\Geometry\Point;
use App\Ramcar\APIResult;
use App\Ramcar\JOStatus;
use App\Ramcar\InvoiceCriteria;
use App\Ramcar\ServiceType;
use App\Ramcar\WarrantyClass;
use App\Ramcar\APIRiderStatus;
use App\Ramcar\TransactionOrigin;
use App\Ramcar\TradeInType;
use App\Service\InvoiceCreator;
use App\Entity\RiderSession;
use App\Entity\Customer;
use App\Entity\VehicleManufacturer;
use App\Entity\Vehicle;
use App\Entity\CustomerVehicle;
use App\Entity\JobOrder;
use App\Entity\Promo;
use App\Entity\Battery;
use App\Entity\RiderRating;
use App\Entity\Rider;
use App\Entity\User;
use DateTime;
// Rider API controller
class RAPIController extends Controller
{
protected $session;
public function __construct()
{
// one device = one session, since we have control over the devices
// when a rider logs in, we just change the rider assigned to the device
// when a rider logs out, we remove the rider assigned to the device
$this->session = null;
}
protected function checkMissingParameters(Request $req, $params = [])
{
$missing = [];
// check if parameters are there
foreach ($params as $param)
{
if ($req->getMethod() == 'GET')
{
$check = $req->query->get($param);
if (empty($check))
$missing[] = $param;
}
else if ($req->getMethod() == 'POST')
{
$check = $req->request->get($param);
if (empty($check))
$missing[] = $param;
}
else
return $params;
}
return $missing;
}
// TODO: type hint entity manager
protected function checkAPIKey($em, $api_key)
{
// find the api key (session id)
$session = $em->getRepository(RiderSession::class)->find($api_key);
if ($session == null)
return null;
return $session;
}
protected function checkParamsAndKey(Request $req, $em, $params)
{
// returns APIResult object
$res = new APIResult();
// check for api_key in query string
$api_key = $req->query->get('api_key');
if (empty($api_key))
{
$res->setError(true)
->setErrorMessage('Missing API key');
return $res;
}
// check missing parameters
$missing = $this->checkMissingParameters($req, $params);
if (count($missing) > 0)
{
$miss_string = implode(', ', $missing);
$res->setError(true)
->setErrorMessage('Missing parameter(s): ' . $miss_string);
return $res;
}
// check api key
$sess = $this->checkAPIKey($em, $req->query->get('api_key'));
if ($sess == null)
{
$res->setError(true)
->setErrorMessage('Invalid API Key');
return $res;
}
// store session
$this->session = $sess;
return $res;
}
public function register(Request $req)
{
$res = new APIResult();
// confirm parameters
$required_params = [
'phone_number',
'device_push_id'
];
$missing = $this->checkMissingParameters($req, $required_params);
if (count($missing) > 0)
{
$params = implode(', ', $missing);
$res->setError(true)
->setErrorMessage('Missing parameter(s): ' . $params);
return $res->getReturnResponse();
}
$em = $this->getDoctrine()->getManager();
// retry until we get a unique id
while (true)
{
try
{
// instantiate session
$sess = new RiderSession();
$sess->setPhoneNumber($req->request->get('phone_number'))
->setDevicePushID($req->request->get('device_push_id'));
// reopen in case we get an exception
if (!$em->isOpen())
{
$em = $em->create(
$em->getConnection(),
$em->getConfiguration()
);
}
// save
$em->persist($sess);
$em->flush();
}
catch (DBALException $e)
{
error_log($e->getMessage());
// delay one second and try again
sleep(1);
continue;
}
break;
}
// return data
$data = [
'session_id' => $sess->getID()
];
$res->setData($data);
// response
return $res->getReturnResponse();
}
public function login(Request $req, EncoderFactoryInterface $ef)
{
$required_params = [
'user',
'pass',
];
$em = $this->getDoctrine()->getManager();
$res = $this->checkParamsAndKey($req, $em, $required_params);
if ($res->isError())
return $res->getReturnResponse();
// check if session has a rider already
if ($this->session->hasRider())
{
$res->setError(true)
->setErrorMessage('Another rider is already logged in. Please logout first.');
return $res->getReturnResponse();
}
// look for rider with username
$rider = $em->getRepository(Rider::class)->findOneBy(['username' => $req->request->get('user')]);
if ($rider == null)
{
$res->setError(true)
->setErrorMessage('Invalid username or password.');
return $res->getReturnResponse();
}
// check if rider password is correct
$encoder = $ef->getEncoder(new User());
if (!$encoder->isPasswordValid($rider->getPassword(), $req->request->get('pass'), ''))
{
$res->setError(true)
->setErrorMessage('Invalid username or password.');
return $res->getReturnResponse();
}
// assign rider to session
$this->session->setRider($rider);
// TODO: log rider logging in
$em->flush();
return $res->getReturnResponse();
}
public function logout(Request $req)
{
$required_params = [];
$em = $this->getDoctrine()->getManager();
$res = $this->checkParamsAndKey($req, $em, $required_params);
if ($res->isError())
return $res->getReturnResponse();
// remove rider from session
$this->session->setRider(null);
// TODO: log rider logging out
$em->flush();
return $res->getReturnResponse();
}
public function getJobOrder(Request $req)
{
// get the job order of the rider assigned to this session
$required_params = [];
$em = $this->getDoctrine()->getManager();
$res = $this->checkParamsAndKey($req, $em, $required_params);
if ($res->isError())
return $res->getReturnResponse();
// are we logged in?
if (!$this->session->hasRider())
{
$res->setError(true)
->setErrorMessage('No logged in rider.');
return $res->getReturnResponse();
}
$rider = $this->session->getRider();
// do we have a job order?
$jo = $rider->getActiveJobOrder();
if ($jo == null)
{
$data = [
'job_order' => null
];
}
else
{
$coord = $jo->getCoordinates();
$cust = $jo->getCustomer();
$cv = $jo->getCustomerVehicle();
$v = $cv->getVehicle();
$inv = $jo->getInvoice();
// invoice items
$inv_items = [];
foreach ($inv->getItems() as $item)
{
$inv_items[] = [
'id' => $item->getID(),
'title' => $item->getTitle(),
'qty' => $item->getQuantity(),
'price' => $item->getPrice(),
];
}
$data = [
'job_order' => [
'id' => $jo->getID(),
'service_type' => $jo->getServiceType(),
'date_schedule' => $jo->getDateSchedule()->format('Ymd'),
'longitude' => $coord->getLongitude(),
'latitude' => $coord->getLatitude(),
'status' => $jo->getStatus(),
'customer' => [
'title' => $cust->getTitle(),
'first_name' => $cust->getFirstName(),
'last_name' => $cust->getLastName(),
'phone_mobile' => $cust->getPhoneMobile(),
],
'vehicle' => [
'manufacturer' => $v->getManufacturer()->getName(),
'make' => $v->getMake(),
'model' => $cv->getModelYear(),
'plate_number' => $cv->getPlateNumber(),
'color' => $cv->getColor(),
],
'delivery_instructions' => $jo->getDeliveryInstructions(),
'delivery_address' => $jo->getDeliveryAddress(),
'landmark' => $jo->getLandmark(),
'invoice' => [
'discount' => $inv->getDiscount(),
'trade_in' => $inv->getTradeIn(),
'total_price' => $inv->getTotalPrice(),
'vat' => $inv->getVat(),
'items' => $inv_items,
],
'mode_of_payment' => $jo->getModeOfPayment(),
]
];
}
$res->setData($data);
return $res->getReturnResponse();
}
protected function checkJO(Request $req, $required_params)
{
// set jo status to in transit
$em = $this->getDoctrine()->getManager();
$res = $this->checkParamsAndKey($req, $em, $required_params);
if ($res->isError())
return $res;
// are we logged in?
if (!$this->session->hasRider())
{
$res->setError(true)
->setErrorMessage('No logged in rider.');
return $res;
}
$rider = $this->session->getRider();
// check if we have an active JO
$jo = $rider->getActiveJobOrder();
if ($jo == null)
{
$res->setError(true)
->setErrorMessage('No active job order.');
return $res;
}
// check if the jo_id sent is the same as our active jo
if ($req->request->get('jo_id') != $jo->getID())
{
$res->setError(true)
->setErrorMessage('Job order selected is not active job order.');
return $res;
}
return $res;
}
public function acceptJobOrder(Request $req)
{
$required_params = ['jo_id'];
$res = $this->checkJO($req, $required_params);
if ($res->isError())
return $res->getReturnResponse();
// TODO: refactor this into a jo handler class, so we don't have to repeat for control center
// set jo status to in transit
$jo->setStatus(JOStatus::IN_TRANSIT);
// TODO: send mqtt event
// TODO: add event
return $res->getReturnResponse();
}
public function cancelJobOrder(Request $req)
{
$required_params = ['jo_id'];
$res = $this->checkJO($req, $required_params);
if ($res->isError())
return $res->getReturnResponse();
// TODO: refactor this into a jo handler class, so we don't have to repeat for control center
// set jo status to cancelled
$jo->setStatus(JOStatus::CANCELLED);
// TODO: send mqtt event
// TODO: add event
return $res->getReturnResponse();
}
public function arrive(Request $req)
{
$required_params = ['jo_id'];
$res = $this->checkJO($req, $required_params);
if ($res->isError())
return $res->getReturnResponse();
// TODO: refactor this into a jo handler class, so we don't have to repeat for control center
// set jo status to in progress
$jo->setStatus(JOStatus::IN_PROGRESS);
// TODO: send mqtt event
// TODO: add event
return $res->getReturnResponse();
}
public function payment(Request $req)
{
// set invoice to paid
// set jo status to fulfilled
}
}

View file

@ -7,6 +7,7 @@ use App\Ramcar\DayOfWeek;
use App\Entity\Rider; use App\Entity\Rider;
use App\Entity\RiderSchedule; use App\Entity\RiderSchedule;
use App\Entity\Hub; use App\Entity\Hub;
use App\Entity\User;
use App\Service\FileUploader; use App\Service\FileUploader;
use Doctrine\ORM\Query; use Doctrine\ORM\Query;
@ -14,6 +15,7 @@ use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface; use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface; use Symfony\Component\Validator\Validator\ValidatorInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use DateTime; use DateTime;
@ -154,7 +156,8 @@ class RiderController extends BaseController
->setContactNumber($req->request->get('contact_no')) ->setContactNumber($req->request->get('contact_no'))
->setPlateNumber($req->request->get('plate_number')) ->setPlateNumber($req->request->get('plate_number'))
->setImageFile($req->request->get('image_file')) ->setImageFile($req->request->get('image_file'))
->setActive($req->request->get('flag_active') ? true : false); ->setActive($req->request->get('flag_active') ? true : false)
->setUsername($req->request->get('username'));
} }
public function addSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator) public function addSubmit(Request $req, EncoderFactoryInterface $ef, ValidatorInterface $validator)
@ -176,6 +179,24 @@ class RiderController extends BaseController
// initialize error list // initialize error list
$error_array = []; $error_array = [];
// get password inputs
$password = $req->request->get('password');
$confirm_password = $req->request->get('confirm_password');
// custom validation for password fields
if (!$password) {
$error_array['password'] = 'This value should not be blank.';
} else if ($password != $confirm_password) {
$error_array['confirm_password'] = 'Passwords do not match.';
} else {
// encode password
$enc = $ef->getEncoder(new User());
$encoded_password = $enc->encodePassword($req->request->get('password'), '');
// set password
$obj->setPassword($encoded_password);
}
// custom validation for associations // custom validation for associations
$hub_id = $req->request->get('hub'); $hub_id = $req->request->get('hub');
@ -303,6 +324,24 @@ class RiderController extends BaseController
// initialize error list // initialize error list
$error_array = []; $error_array = [];
// get password inputs
$password = $req->request->get('password');
$confirm_password = $req->request->get('confirm_password');
// custom validation for password fields
if ($password || $confirm_password) {
if ($password != $confirm_password) {
$error_array['confirm_password'] = 'Passwords do not match.';
} else {
// encode password
$enc = $ef->getEncoder(new User());
$encoded_password = $enc->encodePassword($req->request->get('password'), '');
// set password
$obj->setPassword($encoded_password);
}
}
// custom validation for associations // custom validation for associations
$hub_id = $req->request->get('hub'); $hub_id = $req->request->get('hub');

View file

@ -8,6 +8,8 @@ use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria; use Doctrine\Common\Collections\Criteria;
use App\Ramcar\JOStatus;
/** /**
* @ORM\Entity * @ORM\Entity
* @ORM\Table(name="rider") * @ORM\Table(name="rider")
@ -92,6 +94,18 @@ class Rider
*/ */
protected $flag_active; protected $flag_active;
// username for rider api
/**
* @ORM\Column(type="string", length=80, unique=true, nullable=true)
*/
protected $username;
// password for rider api
/**
* @ORM\Column(type="string", length=64)
*/
protected $password;
public function __construct() public function __construct()
{ {
$this->job_orders = new ArrayCollection(); $this->job_orders = new ArrayCollection();
@ -99,6 +113,8 @@ class Rider
$this->curr_rating = 0; $this->curr_rating = 0;
$this->flag_available = true; $this->flag_available = true;
$this->flag_active = true; $this->flag_active = true;
$this->username = null;
$this->password = '';
} }
public function getID() public function getID()
@ -253,4 +269,42 @@ class Rider
{ {
return $this->flag_active; return $this->flag_active;
} }
public function setUsername($username)
{
$this->username = $username;
return $this;
}
public function getUsername()
{
return $this->username;
}
public function setPassword($pass)
{
// they have to pass the encoded password
$this->password = $pass;
return $this;
}
public function getPassword()
{
return $this->password;
}
public function getActiveJobOrder()
{
$active_status = [
JOStatus::ASSIGNED,
JOStatus::IN_TRANSIT,
JOStatus::IN_PROGRESS,
];
$criteria = Criteria::create();
$criteria->where(Criteria::expr()->in('status', $active_status))
->getFirstResult(1);
return $this->job_orders->matching($criteria)[0];
}
} }

117
src/Entity/RiderSession.php Normal file
View file

@ -0,0 +1,117 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use DateTime;
/**
* @ORM\Entity
* @ORM\Table(name="rider_session")
*/
class RiderSession
{
// unique id
/**
* @ORM\Id
* @ORM\Column(type="string", length=13)
*/
protected $id;
// device id or push id used by device
/**
* @ORM\Column(type="string", length=50)
*/
protected $device_push_id;
// link to customer
/**
* @ORM\ManyToOne(targetEntity="Rider", inversedBy="sessions")
* @ORM\JoinColumn(name="rider_id", referencedColumnName="id", nullable=true)
*/
protected $rider;
// phone number
/**
* @ORM\Column(type="string", length=12, nullable=true)
*/
protected $phone_number;
// is this device active
/**
* @ORM\Column(type="boolean")
*/
protected $is_active;
public function __construct()
{
// default date generated to now
$this->id = $this->generateKeyID();
$this->rider = null;
$this->is_active = false;
}
public function generateKeyID()
{
// use uniqid for now, since primary key dupes will trigger exceptions
return uniqid();
}
public function getID()
{
return $this->id;
}
public function setDevicePushID($id)
{
$this->device_push_id = $id;
return $this;
}
public function getDevicePushID()
{
return $this->device_push_id;
}
public function setRider(Rider $rider = null)
{
$this->rider = $rider;
return $this;
}
public function getRider()
{
return $this->rider;
}
public function setPhoneNumber($num)
{
$this->phone_number = $num;
return $this;
}
public function getPhoneNumber()
{
return $this->phone_number;
}
public function setActive($flag = true)
{
$this->is_active = $flag;
return $this;
}
public function isActive()
{
return $this->is_active;
}
public function hasRider()
{
if ($this->rider == null)
return false;
return true;
}
}

View file

@ -35,6 +35,36 @@
<form id="row-form" class="m-form m-form--fit m-form--label-align-right" method="post" action="{{ mode == 'update' ? url('rider_update_submit', {'id': obj.getId()}) : url('rider_create_submit') }}"> <form id="row-form" class="m-form m-form--fit m-form--label-align-right" method="post" action="{{ mode == 'update' ? url('rider_update_submit', {'id': obj.getId()}) : url('rider_create_submit') }}">
<div class="m-portlet__body"> <div class="m-portlet__body">
<div class="m-form__section m-form__section--first"> <div class="m-form__section m-form__section--first">
<div class="m-form__heading">
<h3 class="m-form__heading-title">
Rider App User
</h3>
</div>
<div class="form-group m-form__group row">
<div class="col-lg-6">
<label data-field="username">Username</label>
<input type="text" name="username" class="form-control m-input" value="{{ obj.getUsername() }}">
<div class="form-control-feedback hide" data-field="username"></div>
</div>
</div>
<div class="form-group m-form__group row">
<div class="col-lg-6">
<label data-field="password">Password</label>
<input type="password" name="password" class="form-control m-input">
<div class="form-control-feedback hide" data-field="password"></div>
</div>
</div>
<div class="form-group m-form__group row">
<div class="col-lg-6">
<label data-field="confirm_password">Confirm Password</label>
<input type="password" name="confirm_password" class="form-control m-input">
<div class="form-control-feedback hide" data-field="confirm_password"></div>
</div>
</div>
</div>
<div class="m-form__seperator m-form__seperator--dashed"></div>
<div class="m-form__section m-form__section">
<div class="m-form__heading"> <div class="m-form__heading">
<h3 class="m-form__heading-title"> <h3 class="m-form__heading-title">
Rider Details Rider Details