src/Parcels/ParcelController.php line 695

Open in your IDE?
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: parcel
  5. * Date: 8/24/18
  6. * Time: 6:28 PM
  7. */
  8. namespace App\Parcels;
  9. use App\Entity\DailyAccount;
  10. use App\Entity\DebitCreditNote;
  11. use App\Entity\DeliveryParcel;
  12. use App\Entity\DeliveryVehicle;
  13. use App\Entity\Etr;
  14. use App\Entity\Mpesa;
  15. use App\Entity\MpesaAuth;
  16. use App\Entity\MpesaPayment;
  17. use App\Entity\MpesaTransaction;
  18. use App\Entity\Organization;
  19. use App\Entity\Parcel;
  20. use App\Entity\Sms;
  21. use App\Entity\Station;
  22. use App\Entity\TimsStation;
  23. use App\Entity\Transaction;
  24. use App\Entity\TransactionExpense;
  25. use App\Entity\UserStation;
  26. use App\Entity\WayBill;
  27. use App\Form\ParcelForm;
  28. use App\Form\WayBillExpense;
  29. use App\Form\WayBillForm;
  30. use App\Service\ActionMatrix;
  31. use App\Service\TremolInitiator;
  32. use App\TimsProcessor\Tremol\core\SException;
  33. use App\TimsProcessor\Tremol\FP;
  34. use DateTime;
  35. use Doctrine\Persistence\ManagerRegistry;
  36. use Doctrine\Persistence\ObjectManager;
  37. use Exception;
  38. use JMS\Serializer\SerializationContext;
  39. use JMS\Serializer\SerializerBuilder;
  40. use Mpdf\QrCode\Output\Png;
  41. use Mpdf\QrCode\Output\Svg;
  42. use Mpdf\QrCode\QrCode;
  43. use PDOException;
  44. use PhpAmqpLib\Connection\AMQPStreamConnection;
  45. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  46. use Symfony\Component\Form\FormError;
  47. use Symfony\Component\HttpFoundation\RedirectResponse;
  48. use Symfony\Component\HttpFoundation\Request;
  49. use Symfony\Component\HttpFoundation\Response;
  50. use Symfony\Component\HttpFoundation\Session\Session;
  51. use Symfony\Component\HttpKernel\KernelInterface;
  52. use Symfony\Component\Messenger\MessageBusInterface;
  53. use Symfony\Component\Routing\Annotation\Route;
  54. use Sasedev\MpdfBundle\Factory\MpdfFactory;
  55. use Symfony\Contracts\HttpClient\HttpClientInterface;
  56. use Twig\Error\Error;
  57. class ParcelController extends AbstractController
  58. {
  59. private $authType = 'PROD';
  60. private ManagerRegistry $doctrine;
  61. // private TremolInitiator $initiator;
  62. /** KernelInterface $appKernel */
  63. private $appKernel;
  64. private fp $fp;
  65. private $client;
  66. private ActionMatrix $actionMatrix;
  67. private ObjectManager $em;
  68. private MessageBusInterface $messageBus;
  69. private $smsStatus = [
  70. 100 => "Processed",
  71. 101 => "Sent",
  72. 102 => "Queued",
  73. 401 => "RiskHold",
  74. 402 => "InvalidSenderId",
  75. 403 => "InvalidPhoneNumber",
  76. 404 => "UnsupportedNumberType",
  77. 405 => "InsufficientBalance",
  78. 406 => "UserInBlacklist",
  79. 407 => "CouldNotRoute",
  80. 409 => "DoNotDisturbRejection",
  81. 500 => "InternalServerError",
  82. 501 => "GatewayError",
  83. 502 => "RejectedByGateway"
  84. ];
  85. public function __construct(ManagerRegistry $doctrine, KernelInterface $appKernel, HttpClientInterface $client,MessageBusInterface $messageBus)
  86. {
  87. $this->doctrine = $doctrine;
  88. $this->appKernel = $appKernel;
  89. $this->em = $this->doctrine->getManager();
  90. $this->client = $client;
  91. $this->messageBus = $messageBus;
  92. }
  93. /**
  94. * @Route("/", name="all_parcels")
  95. */
  96. public function parcelsAction()
  97. {
  98. return $this->render('fos/parcels/all_parcels.html.twig', []);
  99. }
  100. /**
  101. * @Route("/incoming", name="all_incoming_parcels")
  102. */
  103. public function incomingParcelsAction()
  104. {
  105. return $this->render('fos/parcels/incoming_parcel.html.twig', []);
  106. }
  107. /**
  108. *
  109. * @Route("/incoming/parcels-list", name="getAllInComingParcels")
  110. */
  111. public function getInComingParcels(Request $request)
  112. {
  113. $em = $this->getDoctrine()->getManager();
  114. $context = new SerializationContext();
  115. $context->setSerializeNull(true);
  116. $serializer = SerializerBuilder::create()->build();
  117. if (!$request->getSession()->get('STATION')) {
  118. $data = [
  119. 'error' => 'User is not well registered'
  120. ];
  121. $data = $serializer->serialize($data, 'json', $context);
  122. return new Response($data, Response::HTTP_OK);
  123. }
  124. $station_id = $request->getSession()->get('STATION');
  125. $page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
  126. $rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
  127. $offset = ($page - 1) * $rows;
  128. $filterRules = $request->request->get('filterRules');
  129. $parcels = $em->getRepository(DeliveryParcel::class)->findInComingParcels($filterRules, $station_id, $offset, $rows);
  130. $total = $em->getRepository(DeliveryParcel::class)->findTotalInComingParcels($filterRules, $station_id);
  131. /* $parcels = $em->getRepository(Parcel::class)->findBy([
  132. 'fromStation' => $station_id,
  133. 'isEnRoute' => true
  134. ],['id'=>'DESC']);*/
  135. $data = [
  136. 'total' => $total,
  137. 'rows' => $parcels
  138. ];
  139. $data = $serializer->serialize($data, 'json', $context);
  140. return new Response($data, Response::HTTP_OK);
  141. }
  142. /**
  143. * @Route("/collected", name="all_collected_parcels")
  144. */
  145. public function collectedParcelsAction()
  146. {
  147. return $this->render('fos/parcels/collected_parcels.html.twig', []);
  148. }
  149. /**
  150. *
  151. * @Route("/collected/parcels-list", name="getAllCollectedParcels")
  152. */
  153. public function getCollectedParcels(Request $request)
  154. {
  155. $em = $this->getDoctrine()->getManager();
  156. $context = new SerializationContext();
  157. $context->setSerializeNull(true);
  158. $serializer = SerializerBuilder::create()->build();
  159. if (!$request->getSession()->get('STATION')) {
  160. $data = [
  161. 'error' => 'User is not well registered'
  162. ];
  163. $data = $serializer->serialize($data, 'json', $context);
  164. return new Response($data, Response::HTTP_OK);
  165. }
  166. $station_id = $request->getSession()->get('STATION');
  167. $page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
  168. $rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
  169. $offset = ($page - 1) * $rows;
  170. $filterRules = $request->request->get('filterRules');
  171. $results = $em->getRepository(DeliveryParcel::class)->findCollectedParcels($filterRules, $station_id, $offset, $rows);
  172. $parcels = $results['results'];
  173. $count = $results;
  174. /* $parcels = $em->getRepository(Parcel::class)->findBy([
  175. 'fromStation' => $station_id,
  176. 'isEnRoute' => true
  177. ],['id'=>'DESC']);*/
  178. $data = [
  179. 'rows' => $parcels,
  180. 'total' => $count
  181. ];
  182. $readyData = $serializer->serialize($data, 'json', $context);
  183. return new Response($readyData, Response::HTTP_OK);
  184. }
  185. /**
  186. * @Route("/at-office", name="all_at_office_parcels")
  187. */
  188. public function AtOfficeParcelsAction()
  189. {
  190. return $this->render('fos/parcels/at_office.html.twig', []);
  191. }
  192. /**
  193. *
  194. * @Route("/at-office/parcels-list", name="get_all_at_office")
  195. */
  196. public function getAtOfficeParcels(Request $request)
  197. {
  198. $em = $this->getDoctrine()->getManager();
  199. $context = new SerializationContext();
  200. $context->setSerializeNull(true);
  201. $serializer = SerializerBuilder::create()->build();
  202. if (!$request->getSession()->get('STATION')) {
  203. $data = [
  204. 'error' => 'User is not well registered'
  205. ];
  206. $data = $serializer->serialize($data, 'json', $context);
  207. return new Response($data, Response::HTTP_OK);
  208. }
  209. $station_id = $request->getSession()->get('STATION');
  210. $page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
  211. $rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
  212. $offset = ($page - 1) * $rows;
  213. $filterRules = $request->request->get('filterRules');
  214. $parcels = $em->getRepository(Parcel::class)->findAtOfficeParcels($filterRules, $station_id, $offset, $rows);
  215. $total = $em->getRepository(Parcel::class)->findTotalAtOfficeParcels($filterRules, $station_id);
  216. $data = [
  217. 'total' => $total,
  218. 'rows' => $parcels
  219. ];
  220. $data = $serializer->serialize($data, 'json', $context);
  221. return new Response($data, Response::HTTP_OK);
  222. }
  223. /**
  224. * @Route("/received", name="all_received_parcels")
  225. */
  226. public function receivedParcelsAction()
  227. {
  228. return $this->render('fos/parcels/received_parcel.html.twig', []);
  229. }
  230. /**
  231. *
  232. * @Route("/received/parcels-list", name="getAllReceivedParcels")
  233. */
  234. public function getReceivedParcels(Request $request)
  235. {
  236. $em = $this->getDoctrine()->getManager();
  237. $context = new SerializationContext();
  238. $context->setSerializeNull(true);
  239. $serializer = SerializerBuilder::create()->build();
  240. if (!$request->getSession()->get('STATION')) {
  241. $data = [
  242. 'error' => 'User is not well registered'
  243. ];
  244. $data = $serializer->serialize($data, 'json', $context);
  245. return new Response($data, Response::HTTP_OK);
  246. }
  247. $station_id = $request->getSession()->get('STATION');
  248. $page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
  249. $rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
  250. $offset = ($page - 1) * $rows;
  251. $filterRules = $request->request->get('filterRules');
  252. $parcels = $em->getRepository(DeliveryParcel::class)->findReceivedParcels($filterRules, $station_id, $offset, $rows);
  253. $total = $em->getRepository(DeliveryParcel::class)->findTotalReceivedParcels($filterRules, $station_id);
  254. /* $parcels = $em->getRepository(Parcel::class)->findBy([
  255. 'fromStation' => $station_id,
  256. 'isEnRoute' => true
  257. ],['id'=>'DESC']);*/
  258. $data = [
  259. 'total' => $total,
  260. 'rows' => $parcels
  261. ];
  262. $allData = $serializer->serialize($data, 'json', $context);
  263. return new Response($allData, Response::HTTP_OK);
  264. }
  265. /**
  266. * @Route("/out_going", name="all_out_going_parcels")
  267. */
  268. public function outGoingParcelsAction()
  269. {
  270. return $this->render('fos/parcels/en_route_deliveries.html.twig', []);
  271. }
  272. /**
  273. *
  274. * @Route("/en-route/delivery-list", name="getAllEnrouteDeliveries")
  275. */
  276. public function getEnrouteDeliveries(Request $request)
  277. {
  278. $em = $this->getDoctrine()->getManager();
  279. $context = new SerializationContext();
  280. $context->setSerializeNull(true);
  281. $serializer = SerializerBuilder::create()->build();
  282. if (!$request->getSession()->get('STATION')) {
  283. $data = [
  284. 'error' => 'User is not well registered'
  285. ];
  286. $data = $serializer->serialize($data, 'json', $context);
  287. return new Response($data, Response::HTTP_OK);
  288. }
  289. $station_id = $request->getSession()->get('STATION');
  290. $page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
  291. $rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
  292. $offset = ($page - 1) * $rows;
  293. $filterRules = $request->request->get('filterRules');
  294. // $parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteParcels($filterRules, $station_id, $offset,$rows);
  295. $parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteDeliveries($filterRules, $station_id, $offset, $rows);
  296. $total = $em->getRepository(DeliveryParcel::class)->findTotalEnRouteDeliveries($filterRules, $station_id);
  297. $data = [
  298. 'total' => $total,
  299. 'rows' => $parcels
  300. ];
  301. $data = $serializer->serialize($data, 'json', $context);
  302. return new Response($data, Response::HTTP_OK);
  303. }
  304. /**
  305. * @Route("/out_going/delivery/{id}", name="all_delivery_parcels")
  306. */
  307. public function deliveryParcelsAction($id)
  308. {
  309. $em = $this->getDoctrine()->getManager();
  310. $context = new SerializationContext();
  311. $context->setSerializeNull(true);
  312. $serializer = SerializerBuilder::create()->build();
  313. // $parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteParcels($filterRules, $station_id, $offset,$rows);
  314. $parcels = $em->getRepository(DeliveryParcel::class)->findDeliveryParcels($id);
  315. // $total = $em->getRepository(DeliveryParcel::class)->findTotalEnRouteParcels($filterRules, $station_id);
  316. return $this->render('fos/parcels/delivery_parcels.html.twig', [
  317. 'id' => $id,
  318. 'parcels' => $parcels
  319. ]);
  320. }
  321. /**
  322. * @Route("/en-route/delivery-parcels-list/{delivery_id}", methods={"GET"},name="getDeliveryParcels")
  323. */
  324. public function getDeliveryParcels($delivery_id, Request $request)
  325. {
  326. $em = $this->getDoctrine()->getManager();
  327. $context = new SerializationContext();
  328. $context->setSerializeNull(true);
  329. $serializer = SerializerBuilder::create()->build();
  330. // $parcels = $em->getRepository(DeliveryParcel::class)->findEnRouteParcels($filterRules, $station_id, $offset,$rows);
  331. $parcels = $em->getRepository(DeliveryParcel::class)->findDeliveryParcels($delivery_id);
  332. // $total = $em->getRepository(DeliveryParcel::class)->findTotalEnRouteParcels($filterRules, $station_id);
  333. $data = [
  334. 'rows' => $parcels
  335. ];
  336. $data = $serializer->serialize($data, 'json', $context);
  337. return new Response($data, Response::HTTP_OK);
  338. }
  339. /**
  340. * @Route("/all/parcels-list", methods={"POST"}, name="get_all_Parcels")
  341. */
  342. public function getAllParcels(Request $request)
  343. {
  344. $em = $this->getDoctrine()->getManager();
  345. $serializer = SerializerBuilder::create()->build();
  346. $page = empty($request->request->get('page')) ? intval('page') : 1;
  347. $rows = empty($request->request->get('rows')) ? intval('rows') : 10;
  348. $offset = ($page - 1) * $rows;
  349. $session = new Session();
  350. if (!$session->get('town')) {
  351. $data = [
  352. 'error' => 'User is not well registered'
  353. ];
  354. $data = $serializer->serialize($data, 'json');
  355. return new Response($data, Response::HTTP_OK);
  356. }
  357. $page = $request->request->get('page') > 1 ? $request->request->get('page') : 1;
  358. $rows = $request->request->get('rows') > 1 ? $request->request->get('rows') : 20;
  359. $offset = ($page - 1) * $rows;
  360. $filterRules = $request->request->get('filterRules');
  361. $em = $this->getDoctrine()->getManager();
  362. $parcels = $em->getRepository(Parcel::class)->findTownParcels($session->get('town'), $offset, $rows);
  363. // dump($parcels); die;
  364. $parcelsCount = $em->getRepository(Parcel::class)->findTownParcelsCount($session->get('town'));
  365. $data = [
  366. 'rows' => $parcels,
  367. 'total' => $parcelsCount
  368. ];
  369. $data = $serializer->serialize($data, 'json');
  370. return new Response($data, Response::HTTP_OK);
  371. }
  372. /**
  373. * @Route("/new-parcel", name="new-parcel")
  374. */
  375. public function newParcel(Request $request)
  376. {
  377. $waybill = new WayBill();
  378. $em = $this->getDoctrine()->getManager();
  379. $organization = $em->getRepository(Organization::class)->findOneBy([
  380. 'id' => $request->getSession()->get('ORGANIZATION')
  381. ]);
  382. $waybill->setOrganization($organization);
  383. $form = $this->createForm(WayBillForm::class, $waybill, [
  384. 'validation_groups' => [
  385. 'Default'
  386. ]
  387. ]);
  388. $form->handleRequest($request);
  389. /** @var UserStation $userStation */
  390. $userStation = $em->getRepository(UserStation::class)->findOneBy([
  391. 'user' => $this->getUser(),
  392. 'isActive' => true
  393. ], ['id' => 'DESC']);
  394. $date = new \DateTime();
  395. $stringDate = $date->format('Y-m-d');
  396. $dailyAccount = $em->getRepository(DailyAccount::class)->findOneBy([
  397. 'user' => $this->getUser(),
  398. 'isClosed' => false,
  399. 'accountDate' => $date
  400. ], ['id' => 'DESC']);
  401. if (!$dailyAccount) {
  402. $this->addFlash('warning', "Please Open A new Daily account for today ({$stringDate}) to make any transactions");
  403. return $this->render('fos/parcels/new_parcel.html.twig', [
  404. 'form' => $form->createView(),
  405. 'user_station' => $userStation
  406. ]);
  407. }
  408. if ($form->isSubmitted() && $form->isValid()) {
  409. if ($waybill->getToStation()->getId() === $userStation->getStation()->getId()) {
  410. $form->addError(new FormError('Origin Station and Destination Station cannot be the same'));
  411. return $this->render('fos/parcels/new_parcel.html.twig', [
  412. 'form' => $form->createView(),
  413. 'user_station' => $userStation
  414. ]);
  415. }
  416. $waybill->setCreatedAt(new \DateTime());
  417. $waybill->setCreatedBy($this->getUser());
  418. $waybill->setFromStation($userStation->getStation());
  419. $waybill->setIsCollected(false);
  420. $waybill->setPercelCount(count($waybill->getParcels()));
  421. $waybill->setIsCollected(false);
  422. $waybill->setIsReceived(false);
  423. $waybill->addTransaction($dailyAccount);
  424. foreach ($waybill->getParcels() as $key => $item) {
  425. $waybill->getParcels()->get($key)->setNumber($key + 1);
  426. // $waybill->getParcels()->get($key)->setIsCollected(false);
  427. }
  428. $conn = $em->getConnection();
  429. $conn->beginTransaction();
  430. try {
  431. $em->persist($waybill);
  432. $em->flush();
  433. $em->getConnection()->commit();
  434. $this->addFlash('success', 'Parcel Saved Successfully');
  435. return $this->redirectToRoute('one_way_bill', ['id' => $waybill->getId()]);
  436. } catch (PDOException $e) {
  437. $em->getConnection()->rollBack();
  438. $this->addFlash('error', 'An Error Occurred Please check whether every thin is filled');
  439. return $this->render('fos/parcels/new_parcel.html.twig', [
  440. 'form' => $form->createView(),
  441. 'user_station' => $userStation
  442. ]);
  443. }
  444. }
  445. return $this->render('fos/parcels/new_parcel.html.twig', [
  446. 'form' => $form->createView(),
  447. 'user_station' => $userStation
  448. ]);
  449. }
  450. /**
  451. *
  452. * @Route("/details/{id}", name="one_detail_parcel")
  453. */
  454. public function getDetailParcel($id)
  455. {
  456. $em = $this->getDoctrine()->getManager();
  457. $transaction = $em->getRepository(Transaction::class)->findOneBy([
  458. 'wayBill' => $id
  459. ]);
  460. $parcel = $em->getRepository(Parcel::class)->findOneBy([
  461. 'waybill' => $id
  462. ]);
  463. return $this->render('fos/parcels/parcel_detail.html.twig', [
  464. 'transaction' => $transaction,
  465. 'parc' => $parcel
  466. ]);
  467. }
  468. /**
  469. * @Route("/way_bill/{id}", methods={"GET","POST"}, name="one_way_bill")
  470. * @param $id
  471. * @param Request $request
  472. * @return RedirectResponse|Response
  473. */
  474. public function getOneWayBill($id, Request $request, MpdfFactory $mpdfFactory)
  475. {
  476. $em = $this->getDoctrine()->getManager();
  477. $dailyAccount = $em->getRepository(DailyAccount::class)->findOneBy([
  478. 'user' => $this->getUser()
  479. ], ['id' => 'DESC']);
  480. /** @var Transaction $transaction */
  481. $transaction = $em->getRepository(Transaction::class)->findOneBy([
  482. 'wayBill' => $id
  483. ]);
  484. $isMpesaAvailable = false;
  485. /** @var MpesaAuth $credentials */
  486. $credentials = $em->getRepository(MpesaAuth::class)->findOneBy([
  487. 'station' => $request->getSession()->get('STATION'),
  488. 'authType' => $this->authType
  489. ]);
  490. $isCashCanChangeMpesa = false;
  491. if ($credentials && ($transaction->getDailyAccount()->getId() == $dailyAccount->getId())) {
  492. $isMpesaAvailable = true;
  493. }
  494. if ($credentials && ($transaction->getDailyAccount()->getId() == $dailyAccount->getId()) && $transaction->getPaymentMethod() == 'CASH') {
  495. $isCashCanChangeMpesa = true;
  496. }
  497. $isCancellable = true;
  498. // if ($transaction->getisCancelled()){
  499. // $this->addFlash('warning', 'This Transaction is already cancelled');
  500. // }else if($dailyAccount->getId() !== $transaction->getDailyAccount()->getId()){
  501. // $isCancellable = false;
  502. // $this->addFlash('warning', 'You cannot Cancel this transaction');
  503. // }
  504. // if ($this->get('security.authorization_checker')->isGranted('ROLE_BOS_USER')) {
  505. // // the user has the ROLE_BRAND role, so act accordingly
  506. // $isCancellable = true;
  507. // }
  508. /** @var Parcel $parcels */
  509. $parcels = $em->getRepository(Parcel::class)->findBy([
  510. 'waybill' => $id
  511. ]);
  512. /** @var Sms $sms */
  513. $sms = $em->getRepository(Sms::class)->findBy([
  514. 'transaction' => $transaction
  515. ]);
  516. dump($sms);
  517. $timsSupport = $em->getRepository(TimsStation::class)->findOneBy([
  518. 'station' => $request->getSession()->get('STATION'),
  519. 'client' => 'WEB'
  520. ]);
  521. // dump($timsSupport);
  522. $wayBillExpense = new TransactionExpense();
  523. $cancelForm = $this->cancelTransactionForm($id);
  524. $cancelForm->handleRequest($request);
  525. if ($cancelForm->isSubmitted()) {
  526. if (!$transaction->getIsComplete() || $this->get('security.authorization_checker')->isGranted('ROLE_BOS_USER')) {
  527. if (!$transaction->getisCancelled() && ($dailyAccount == $transaction->getDailyAccount() || $this->get('security.authorization_checker')->isGranted('ROLE_BOS_USER'))) {
  528. if($transaction->getIsFinal() && $transaction->getCuInvoiceNumber()){
  529. return $this->makeCreditNote($transaction, $mpdfFactory);
  530. }else{
  531. $transaction->setIsCancelled(true);
  532. // $transaction->getDailyAccount()->setCash($transaction->getDailyAccount()->getCash() - $transaction->getAmount());
  533. $em->flush();
  534. }
  535. $this->addFlash('warning', 'This Transaction has been cancelled successfully');
  536. } else if ($cancelForm->isSubmitted()) {
  537. $this->addFlash('warning', 'This Transaction has not been cancelled');
  538. }
  539. } else {
  540. $this->addFlash('error', 'YOU CANNOT CANCEL A COMPLETE TRANSACTION, CONTACT ADMIN');
  541. }
  542. }
  543. $cashPaymentOptionForm = $this->cashPaymentOptionForm($id);
  544. $cashPaymentOptionForm->handleRequest($request);
  545. if ($cashPaymentOptionForm->isSubmitted()) {
  546. if (!$transaction->getIsPaid()) {
  547. $conn = $em->getConnection();
  548. $conn->beginTransaction();
  549. try {
  550. // $dailyAccount->setCash($transaction->getAmount() + $dailyAccount->getCash());
  551. $transaction->setIsPaid(true);
  552. $transaction->setPaymentMethod('CASH');
  553. $transaction->setPaidBy('sender');
  554. $transaction->setCashAmount($transaction->getAmount());
  555. $em->getConnection()->commit();
  556. $em->flush();
  557. $this->addFlash('success', 'Transaction paid in cash');
  558. return $this->redirectToRoute('one_way_bill', ['id' => $id]);
  559. } catch (\PDOException $e) {
  560. $em->getConnection()->rollBack();
  561. $this->addFlash('error', 'An Error Occurred Please check whether every thing is ok or contact admin');
  562. return $this->redirectToRoute('one_way_bill', ['id' => $id]);
  563. }
  564. }
  565. }
  566. $form = $this->createForm(WayBillExpense::class, $wayBillExpense);
  567. $form->handleRequest($request);
  568. if ($form->isSubmitted() && $form->isValid()) {
  569. $wayBillExpense->setTransaction($transaction);
  570. $wayBillExpense->setCreatedBy($this->getUser());
  571. $wayBillExpense->setCreatedAt(new \DateTime());
  572. $conn = $em->getConnection();
  573. $conn->beginTransaction();
  574. try {
  575. $em->persist($wayBillExpense);
  576. $em->flush();
  577. $em->getConnection()->commit();
  578. $this->addFlash('success', 'Expense Updated Successfully');
  579. return $this->redirectToRoute('one_way_bill', ['id' => $transaction->getWayBill()->getId()]);
  580. } catch (\PDOException $e) {
  581. $em->getConnection()->rollBack();
  582. $this->addFlash('error', 'An Error Occurred Please check whether every thing is filled');
  583. return $this->render('fos/parcels/view_parcel.html.twig', [
  584. 'transaction' => $transaction,
  585. 'daily_account' => $dailyAccount,
  586. 'parcels' => $parcels,
  587. 'form' => $form->createView(),
  588. 'cancelForm' => $cancelForm->createView(),
  589. 'cashPaymentOptionForm' => $cashPaymentOptionForm->createView(),
  590. 'isCancellable' => $isCancellable,
  591. 'isMpesaAvailable' => $isMpesaAvailable,
  592. 'isCashCanChangeMpesa' => $isCashCanChangeMpesa,
  593. 'tims' => $timsSupport
  594. ]);
  595. }
  596. }
  597. return $this->render('fos/parcels/view_parcel.html.twig', [
  598. 'transaction' => $transaction,
  599. 'daily_account' => $dailyAccount,
  600. 'parcels' => $parcels,
  601. 'form' => $form->createView(),
  602. 'cancelForm' => $cancelForm->createView(),
  603. 'cashPaymentOptionForm' => $cashPaymentOptionForm->createView(),
  604. 'isCancellable' => $isCancellable,
  605. 'isMpesaAvailable' => $isMpesaAvailable,
  606. 'isCashCanChangeMpesa' => $isCashCanChangeMpesa,
  607. 'tims' => $timsSupport,
  608. 'sms' => $sms,
  609. 'statusChart' => $this->smsStatus
  610. ]);
  611. }
  612. /**
  613. * @Route("/way_bill/parcel/{parcel_id}", name="one_waybill_parcel")
  614. * @param $parcel_id
  615. * @return Response
  616. */
  617. public function getParcelDeliveryData($parcel_id)
  618. {
  619. $em = $this->getDoctrine()->getManager();
  620. $isEnRoute = false;
  621. $isInDelivery = false;
  622. $deliveryParcel = $em->getRepository(DeliveryParcel::class)->findOneBy([
  623. 'isCancelled' => false,
  624. 'parcel' => $parcel_id
  625. ]);
  626. if ($deliveryParcel) {
  627. $isInDelivery = true;
  628. $deliveryVehicle = $em->getRepository(DeliveryVehicle::class)->findOneBy([
  629. 'isCancelled' => false,
  630. 'delivery' => $deliveryParcel->getDelivery()
  631. ]);
  632. if ($deliveryVehicle) {
  633. $isEnRoute = true;
  634. return $this->render('fos/parcels/parcel_status.html.twig', [
  635. 'isEnRoute' => $isEnRoute,
  636. 'inDelivery' => $isInDelivery,
  637. 'delivery_parcel' => $deliveryParcel,
  638. 'delivery_vehicle' => $deliveryVehicle
  639. ]);
  640. }
  641. return $this->render('fos/parcels/parcel_status.html.twig', [
  642. 'isEnRoute' => $isEnRoute,
  643. 'inDelivery' => $isInDelivery,
  644. 'delivery_parcel' => $deliveryParcel
  645. ]);
  646. }
  647. return $this->render('fos/parcels/parcel_status.html.twig', [
  648. 'isEnRoute' => $isEnRoute,
  649. 'inDelivery' => $isInDelivery,
  650. 'delivery_parcel' => null
  651. ]);
  652. }
  653. /**
  654. * @Route("/form/towns",methods={"GET"}, name="form_towns")
  655. */
  656. public function getTowns(Request $request)
  657. {
  658. $queryTerm = $request->get('q');
  659. $em = $this->getDoctrine()->getManager();
  660. $towns = $em->getRepository(Station::class)->findFormTown($queryTerm);
  661. $serializer = SerializerBuilder::create()->build();
  662. $town = new Station();
  663. $town->setStationName('ALL STATIONS');
  664. $town->setId(-1);
  665. array_push($towns, $town);
  666. $data = $serializer->serialize($towns, 'json');
  667. return new Response($data, Response::HTTP_OK);
  668. }
  669. private function cancelTransactionForm($id)
  670. {
  671. $fb = $this->createFormBuilder();
  672. return $fb
  673. ->setAction($this->generateUrl('one_way_bill', ['id' => $id]))
  674. ->setMethod('POST')
  675. ->getForm();
  676. }
  677. private function cashPaymentOptionForm($id)
  678. {
  679. // $fb = $this->createFormBuilder();
  680. $fb = $this->get('form.factory')->createNamedBuilder('cash_payment_mode');
  681. return $fb
  682. ->setAction($this->generateUrl('one_way_bill', ['id' => $id]))
  683. ->setMethod('POST')
  684. ->getForm();
  685. }
  686. /**
  687. * @Route("/receipt/{waybill_}", methods={"GET"}, name="receipt_action")
  688. */
  689. public function ReceiptAction(Request $request, $waybill_, MpdfFactory $MpdfFactory): Response
  690. {
  691. $em = $this->getDoctrine()->getManager();
  692. /** @var Transaction $transaction */
  693. $transaction = $em->getRepository(Transaction::class)->findOneBy([
  694. 'wayBill' => $waybill_
  695. ]);
  696. $transaction->setIsComplete(true);
  697. $transaction->setIsPaid(true);
  698. $transaction->setIsFinal(true);
  699. $em->flush();
  700. $mpesa = null;
  701. if ($transaction->getPaymentMethod() == 'MPESA' || $transaction->getPaymentMethod() == 'MPESA_CASH' ) {
  702. $mpesa = $em->getRepository(MpesaTransaction::class)->findOneBy([
  703. 'transaction' => $transaction
  704. ]);
  705. }
  706. /** @var WayBill $waybill */
  707. $waybill = $transaction->getWaybill();
  708. $parcels = $em->getRepository(Parcel::class)->findBy([
  709. 'waybill' => $waybill
  710. ]);
  711. $mPdf = $MpdfFactory->createMpdfObject([
  712. 'mode' => 'utf-8',
  713. 'format' => [70, 254],
  714. 'margin_header' => 5,
  715. 'margin_footer' => 5,
  716. 'orientation' => 'P'
  717. ]);
  718. $date = new DateTime();
  719. $time = $date->getTimestamp();
  720. $mPdf->SetTopMargin("50");
  721. // get the logo image and change it to base64
  722. $logoImage = file_get_contents('../public/logo.png');
  723. $logoBase64 = base64_encode($logoImage);
  724. // dump($logoBase64);
  725. // $o = $output->output($qrCode, 100, 'white', 'black');
  726. // $mPdf->SetHTMLHeader($this->renderView('twigfolder/pdf/pdf_header.html.twig', $TwigVars));
  727. // $mPdf->SetFooter($this->renderView('twigfolder/pdf/pdf_footer.html.twig', $TwigVars));
  728. $mPdf->WriteHTML($this->renderView('fos/parcels/receipt/receipt_g03_pdf.html.twig', [
  729. 'waybill' => $waybill,
  730. 'transaction' => $transaction,
  731. 'parcels' => $parcels,
  732. 'mpesa' => $mpesa,
  733. 'logoBase64' => $logoBase64,
  734. 'by' => $waybill->getCreatedBy()->getPerson(),
  735. 'receiptType' => "RECEIPT"
  736. ]));
  737. return $MpdfFactory->createDownloadResponse($mPdf, "receipt_{$waybill_}.pdf", Response::HTTP_OK, ["Set-Cookie", "fileDownload=true; path=/"]);
  738. }
  739. private function makeCreditNote(Transaction $transaction, MpdfFactory $MpdfFactory): Response
  740. {
  741. $em = $this->em;
  742. /** @var Etr $etr */
  743. $etr = $em->getRepository(Etr::class)->findOneBy([
  744. 'isDefault' => 1
  745. ]);
  746. try{
  747. $tremolInitiator = new TremolInitiator($em, $etr);
  748. }catch(Exception $e){
  749. dump($e);
  750. $this->addFlash("warn");
  751. return $this->redirectToRoute("one_way_bill", $transaction->getWayBill()->getId());
  752. }
  753. $mpesa = null;
  754. if ($transaction->getPaymentMethod() == 'MPESA' || $transaction->getPaymentMethod() == 'MPESA_CASH') {
  755. /** @var MpesaTransaction $mpesa */
  756. $mpesa = $em->getRepository(MpesaTransaction::class)->findOneBy([
  757. 'transaction' => $transaction
  758. ]);
  759. }
  760. /** @var WayBill $waybill */
  761. $waybill = $transaction->getWaybill();
  762. $parcels = $em->getRepository(Parcel::class)->findBy([
  763. 'waybill' => $waybill
  764. ]);
  765. $mPdf = $MpdfFactory->createMpdfObject([
  766. 'mode' => 'utf-8',
  767. 'format' => [70, 230],
  768. 'margin_header' => 5,
  769. 'margin_footer' => 5,
  770. 'orientation' => 'P'
  771. ]);
  772. $date = new DateTime();
  773. $time = $date->getTimestamp();
  774. $mPdf->SetTopMargin("1");
  775. try {
  776. $invoiceNumber = $transaction->getCuInvoiceNumber();
  777. $receiptType = 'CREDIT NOTE';
  778. if ($invoiceNumber and $transaction->getIsFinal()) {
  779. /** @var Etr $etr */
  780. $etr = $em->getRepository(Etr::class)->findOneBy([
  781. 'serialNumber' => $transaction->getCuSerialNumber()
  782. ]);
  783. if($etr && !$etr->isDefault()){
  784. $message = "The CU Device {$transaction->getCuSerialNumber()} is not currently the default device on the network Please contact admin";
  785. return new Response($message, Response::HTTP_BAD_REQUEST);
  786. }
  787. if ($transaction->getPinNumber()) {
  788. TremolInitiator::$FP->OpenCreditNoteWithFreeCustomerData(
  789. '',
  790. $transaction->getPinNumber(),
  791. '',
  792. '',
  793. '',
  794. '',
  795. $transaction->getCuInvoiceNumber(),
  796. $waybill->getId()
  797. );
  798. } else {
  799. TremolInitiator::$FP->OpenCreditNoteWithFreeCustomerData(
  800. '',
  801. '',
  802. '',
  803. '',
  804. '',
  805. '',
  806. $transaction->getCuInvoiceNumber(),
  807. $waybill->getId()
  808. );
  809. }
  810. $parcelCount = $waybill->getPercelCount();
  811. foreach ($parcels as $index => $parcel) {
  812. TremolInitiator::$FP->SellPLUfromExtDB($parcel->getDescription(),
  813. 'A',
  814. ($transaction->getAmount() / $parcelCount),
  815. '',
  816. '',
  817. '',
  818. 16.00,
  819. 1
  820. );
  821. }
  822. $rec = TremolInitiator::$FP->CloseReceipt();
  823. $invoiceNumber = $rec->InvoiceNum;
  824. $creditNote = new DebitCreditNote();
  825. $creditNote->setAmount($transaction->getAmount());
  826. $creditNote->setTransaction($transaction);
  827. $creditNote->setCreatedAt(new Datetime());
  828. $creditNote->setCuInvoiceNumber($invoiceNumber);
  829. $creditNote->setTransactionType('CREDITNOTE');
  830. $em->persist($creditNote);
  831. if($mpesa){
  832. $mpesa->getMpesa()->setIsUsed(false);
  833. $em->remove($mpesa);
  834. }
  835. }
  836. $transaction->setIsComplete(true);
  837. $transaction->setMpesaAmount(0);
  838. $transaction->setCashAmount(0);
  839. $transaction->setIsFinal(true);
  840. $transaction->setTaxAmount(0);
  841. $transaction->setIsCancelled(true);
  842. $em->flush();
  843. // get the logo image and change it to base64
  844. $logoImage = file_get_contents('../public/logo.png');
  845. $logoBase64 = base64_encode($logoImage);
  846. // dump($logoBase64);
  847. // create TIMS QRCODE change it to base64;
  848. $timsQRCode = 'https://itax.kra.go.ke/KRA-Portal/invoiceChk.htm?actionCode=loadPage&invoiceNo=' . $invoiceNumber;
  849. $timsqrCode = new QrCode($timsQRCode);
  850. $output = new Png();
  851. $timsQRCodeData = $output->output($timsqrCode, 100, [255, 255, 255], [0, 0, 0]);
  852. $base64 = base64_encode($timsQRCodeData);
  853. $mPdf->WriteHTML($this->renderView('fos/parcels/receipt/receipt_g03_pdf.html.twig', [
  854. 'waybill' => $waybill,
  855. 'transaction' => $transaction,
  856. 'parcels' => $parcels,
  857. 'mpesa' => $mpesa,
  858. 'qrcode' => $base64,
  859. 'logoBase64' => $logoBase64,
  860. 'timsInvoiceNumber' => $invoiceNumber,
  861. 'by' => $waybill->getCreatedBy()->getPerson(),
  862. 'receiptType' => $receiptType
  863. ]));
  864. return $MpdfFactory->createDownloadResponse($mPdf, "receipt_credit_note{$waybill->getId()}.pdf", Response::HTTP_OK, ["Set-Cookie", "fileDownload=true; path=/"]);
  865. } catch (\Exception $e) {
  866. return new Response($e->getMessage(), Response::HTTP_BAD_REQUEST);
  867. }
  868. }
  869. /**
  870. * @Route("/receipt/g03/{waybill_}", methods={"GET"}, name="receipt_action_tremol")
  871. */
  872. public function ReceiptGO3Action(Request $request, $waybill_, MpdfFactory $MpdfFactory): Response
  873. {
  874. $em = $this->getDoctrine()->getManager();
  875. /** @var Transaction $transaction */
  876. $transaction = $em->getRepository(Transaction::class)->findOneBy([
  877. 'wayBill' => $waybill_
  878. ]);
  879. $mpesa = null;
  880. if ($transaction->getPaymentMethod() == 'MPESA' || $transaction->getPaymentMethod() == 'MPESA_CASH') {
  881. $mpesa = $em->getRepository(MpesaTransaction::class)->findOneBy([
  882. 'transaction' => $transaction
  883. ]);
  884. }
  885. /** @var WayBill $waybill */
  886. $waybill = $transaction->getWaybill();
  887. $parcels = $em->getRepository(Parcel::class)->findBy([
  888. 'waybill' => $waybill
  889. ]);
  890. $mPdf = $MpdfFactory->createMpdfObject([
  891. 'mode' => 'utf-8',
  892. 'format' => [70, 230],
  893. 'margin_header' => 0,
  894. 'margin_footer' => 0,
  895. 'orientation' => 'P'
  896. ]);
  897. $date = new DateTime();
  898. $time = $date->getTimestamp();
  899. $mPdf->SetTopMargin("1");
  900. $qrCode = new QrCode($waybill_);
  901. /** @var Etr $etr */
  902. $etr = $em->getRepository(Etr::class)->findOneBy([
  903. 'isDefault' => 1
  904. ]);
  905. try {
  906. //$fp->ServerSetSettings("192.168.13.125", 4444);
  907. // $fp->SetServer_UsedComModule('LAN/WiFi');
  908. // $fp->SetWiFi_Password(10,'mirage2222');
  909. // $fp->SetTCP_Password(10,'mirage2222');
  910. // $fp->SaveNetworkSettings();
  911. // $fp->ApplyClientLibraryDefinitions();
  912. // var_dump($fp->ServerGetDeviceSettings());
  913. // die;
  914. $invoiceNumber = $transaction->getCuInvoiceNumber();
  915. $receiptType = 'FISCAL RECEIPT COPY';
  916. // dump($fp);
  917. // die;
  918. if (!$invoiceNumber and !$transaction->getIsFinal()) {
  919. try{
  920. $tremolInitiator = new TremolInitiator($this->em, $etr);
  921. }catch(\Exception $e){
  922. dump($e);
  923. }
  924. // $this->fp->ServerGetClients();
  925. $receiptType = 'FISCAL RECEIPT';
  926. if ($transaction->getPinNumber()) {
  927. TremolInitiator::$FP->OpenInvoiceWithFreeCustomerData(
  928. '',
  929. $transaction->getPinNumber(),
  930. '',
  931. '',
  932. '',
  933. '',
  934. $waybill->getId()
  935. );
  936. } else {
  937. TremolInitiator::$FP->OpenReceipt(1, $waybill->getId());
  938. }
  939. $parcelCount = $waybill->getPercelCount();
  940. foreach ($parcels as $index => $parcel) {
  941. TremolInitiator::$FP->SellPLUfromExtDB($parcel->getDescription(),
  942. 'A',
  943. ($transaction->getAmount() / $parcelCount),
  944. '',
  945. '',
  946. '',
  947. 16.00,
  948. 1
  949. );
  950. }
  951. $rec = TremolInitiator::$FP->CloseReceipt();
  952. // var_dump($rec);
  953. $invoiceNumber = $rec->InvoiceNum;
  954. $transaction->setCuInvoiceNumber($invoiceNumber);
  955. $transaction->setIsComplete(true);
  956. $transaction->setIsPaid(true);
  957. $transaction->setIsFinal(true);
  958. $transaction->setCuSerialNumber($etr->getSerialNumber());
  959. // $this->actionMatrix = new ActionMatrix($this->messageBus,$this->em,$transaction->getWayBill());
  960. // $this->actionMatrix->payingAction($this->getUser());
  961. $em->flush();
  962. }
  963. // $data = $output->output($qrCode, 100, [255, 255, 255], [0, 0, 0]);
  964. // file_put_contents('../public/qrcode.png', $data);
  965. // file_put_contents('../public/timsQRCode.png', $timsQRCodeData);
  966. // $dataFile = file_get_contents('../public/timsQRCode.png');
  967. /*$image = imagecreatefromstring($dataFile);
  968. $im = '../public/awesome.png';
  969. imagepng($image, $im, 0);*/
  970. // get the logo image and change it to base64
  971. $logoImage = file_get_contents('../public/logo.png');
  972. $logoBase64 = base64_encode($logoImage);
  973. // dump($logoBase64);
  974. // create TIMS QRCODE change it to base64;
  975. $timsQRCode = 'https://itax.kra.go.ke/KRA-Portal/invoiceChk.htm?actionCode=loadPage&invoiceNo=' . $invoiceNumber;
  976. $timsqrCode = new QrCode($timsQRCode);
  977. $output = new Png();
  978. $timsQRCodeData = $output->output($timsqrCode, 100, [255, 255, 255], [0, 0, 0]);
  979. $base64 = base64_encode($timsQRCodeData);
  980. $mPdf->WriteHTML($this->renderView('fos/parcels/receipt/receipt_g03_pdf.html.twig', [
  981. 'waybill' => $waybill,
  982. 'transaction' => $transaction,
  983. 'parcels' => $parcels,
  984. 'mpesa' => $mpesa,
  985. 'qrcode' => $base64,
  986. 'logoBase64' => $logoBase64,
  987. 'timsInvoiceNumber' => $invoiceNumber,
  988. 'by' => $waybill->getCreatedBy()->getPerson(),
  989. 'receiptType' => $receiptType
  990. ]));
  991. return $MpdfFactory->createDownloadResponse($mPdf, "receipt_{$waybill_}.pdf", Response::HTTP_OK, ["Set-Cookie", "fileDownload=true; path=/"]);
  992. } catch (\Exception $e) {
  993. return new Response($e->getMessage(), Response::HTTP_BAD_REQUEST);
  994. }
  995. // return new Response("error occurred");
  996. }
  997. /**
  998. * @Route("/way_bill/{id}/complete", name="register_transaction_as_complete")
  999. */
  1000. public function registerTransactionAsComplete($id)
  1001. {
  1002. $em = $this->getDoctrine()->getManager();
  1003. // $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
  1004. $connection = new AMQPStreamConnection('192.168.13.125', 5672, 'guest', 'guest');
  1005. $channel = $connection->channel();
  1006. /** @var Transaction $transaction */
  1007. $transaction = $em->getRepository(Transaction::class)->findOneBy([
  1008. 'wayBill' => $id
  1009. ]);
  1010. $transaction->setIsComplete(true);
  1011. try {
  1012. if (!$transaction->getIsPaid()) {
  1013. $transaction->setIsPaid(true);
  1014. $transaction->setCashAmount($transaction->getAmount());
  1015. $transaction->setPaymentMethod('CASH');
  1016. $transaction->setIsPaid(true);
  1017. }
  1018. $em->flush();
  1019. $response = [
  1020. 'is_complete' => true
  1021. ];
  1022. return new Response(json_encode($response), Response::HTTP_OK);
  1023. } catch (\Exception $e) {
  1024. $response = [
  1025. 'is_complete' => false,
  1026. 'error' => $e->getMessage()
  1027. ];
  1028. return new Response(json_encode($response), Response::HTTP_NOT_ACCEPTABLE);
  1029. }
  1030. }
  1031. /**
  1032. * @Route("/awesome", name="tims_awesomeness")
  1033. */
  1034. public function getKRASerials(){
  1035. $em = $this->getDoctrine()->getManager();
  1036. for($x =19340;$x > 0; $x--) {
  1037. $k = sprintf('%010d', $x);
  1038. $k = '004079153'.$k;
  1039. dump($k);
  1040. $response = $this->client->request(
  1041. 'POST',
  1042. 'https://itax.kra.go.ke/KRA-Portal/middlewareController.htm?actionCode=fetchInvoiceDtl',
  1043. [
  1044. 'body' => [
  1045. 'invNo' => "{$k}"
  1046. ]
  1047. ]
  1048. );
  1049. $json = json_decode($response->getContent(),true);
  1050. dump($json);
  1051. if($json['traderSystemInvNo']){
  1052. dump($json['traderSystemInvNo']);
  1053. $transaction = $em->getRepository(Transaction::class)->findOneBy([
  1054. 'wayBill' => $json['traderSystemInvNo']
  1055. ]);
  1056. if($transaction){
  1057. $transaction->setCuInvoiceNumber($json['mwInvNo']);
  1058. $em->flush();
  1059. }
  1060. }
  1061. }
  1062. die;
  1063. }
  1064. }