src/Parcels/ParcelController.php line 870

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