src/Controller/Parcels/StationDailyAccountController.php line 42

Open in your IDE?
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: parcel
  5. * Date: 11/29/18
  6. * Time: 11:22 AM
  7. */
  8. namespace App\Controller\Parcels;
  9. use App\Entity\DailyAccount;
  10. use App\Entity\MpesaTransaction;
  11. use App\Entity\Parcel;
  12. use App\Entity\Person;
  13. use App\Entity\Station;
  14. use App\Entity\StationDailyAccount;
  15. use App\Entity\StationExpense;
  16. use App\Entity\Transaction;
  17. use App\Entity\User;
  18. use FOS\RestBundle\Controller\Annotations as Rest;
  19. use FOS\RestBundle\View\View;
  20. use JMS\Serializer\SerializationContext;
  21. use JMS\Serializer\SerializerBuilder;
  22. use PhpOffice\PhpSpreadsheet\Exception;
  23. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  24. use PhpOffice\PhpSpreadsheet\Style\Fill;
  25. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  26. use Psr\Log\LoggerInterface;
  27. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  28. use Symfony\Component\HttpFoundation\Request;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\Routing\Annotation\Route;
  31. use Symfony\Component\VarDumper\Dumper\HtmlDumper;
  32. class StationDailyAccountController extends AbstractController {
  33. /**
  34. * @Route("/daily_accounts", name="daily_accounts")
  35. */
  36. public function transactionAction() {
  37. // replace this example code with whatever you need
  38. return $this->render('parcels/daily_accounts.html.twig',[]);
  39. }
  40. /**
  41. * @Route("/daily_accounts/expenses", name="daily_accounts_expenses")
  42. */
  43. public function expensesAction(Request $request) {
  44. if($request->getMethod() == "POST") {
  45. $em = $this->getDoctrine()->getManager();
  46. $context = new SerializationContext();
  47. $context->setSerializeNull(true);
  48. $serializer = SerializerBuilder::create()->build();
  49. $page = $request->request->get('page') > 1 ? $request->request->get('page'): 1;
  50. $rows = $request->request->get('rows') > 1 ? $request->request->get('rows'): 20;
  51. $offset = ($page - 1)*$rows;
  52. $filterRules = $request->request->get('filterRules');
  53. $fromDate = $request->request->get("from_date");
  54. $toDate = $request->request->get("to_date");
  55. $fDate = null;
  56. $date = new \DateTime('+1 day');
  57. $tDate = null;
  58. // dump($fDate);
  59. // dump($tDate); die;
  60. $fromDate = empty($fromDate) ? $fDate: $fromDate;
  61. $toDate = empty($toDate) ? $tDate: $toDate;
  62. if($fromDate && $toDate){
  63. $filterRules = json_decode($filterRules, true);
  64. $dates = [
  65. 'field'=> 'e.createdAt',
  66. 'op'=> 'between',
  67. 'value' => [
  68. 'from' => str_replace(" ","", $fromDate),
  69. 'to' => str_replace(" ","", $toDate)
  70. ],
  71. ];
  72. array_push($filterRules, $dates);
  73. $filterRules = json_encode($filterRules);
  74. }
  75. $expenses = $em->getRepository(StationExpense::class)->findExpenses($filterRules, $offset, $rows);
  76. // dump($expenses);
  77. $data = [
  78. 'rows' => $expenses['rows'],
  79. 'total' => $expenses['total']
  80. ];
  81. $data = $serializer->serialize($data,'json', $context);
  82. return new Response($data, Response::HTTP_OK);
  83. }
  84. // replace this example code with whatever you need
  85. return $this->render('parcels/expenses.html.twig',[]);
  86. }
  87. /**
  88. * @Route("/daily_accounts/expenses/{fromDate}/{toDate}", name="expense_export_excel")
  89. */
  90. public function findExpensesForExport(Request $request, $fromDate, $toDate, LoggerInterface $logger): Response
  91. {
  92. @ini_set("memory_limit",-1);
  93. set_time_limit(0);
  94. $em = $this->getDoctrine()->getManager();
  95. $context = new SerializationContext();
  96. $context->setSerializeNull(true);
  97. $fDate = null;
  98. $date = new \DateTime('+1 day');
  99. $tDate = null;
  100. // dump($fromDate);
  101. // dump($toDate); die;
  102. $fromDate = $fromDate == 0 ? $fDate: $fromDate;
  103. $toDate = $toDate == 0 ? $tDate: $toDate;
  104. $serializer = SerializerBuilder::create()->build();
  105. $filterRules = $request->request->get('filterRules');
  106. // dump($request->request); die;
  107. if(!$filterRules) {
  108. $filterRules = "[]";
  109. }
  110. if($fromDate && $toDate){
  111. $filterRules = json_decode($filterRules, true);
  112. $dates = [
  113. 'field'=> 'e.createdAt',
  114. 'op'=> 'between',
  115. 'value' => [
  116. 'from' => str_replace(" ","", $fromDate),
  117. 'to' => str_replace(" ","", $toDate)
  118. ],
  119. ];
  120. array_push($filterRules, $dates);
  121. $filterRules = json_encode($filterRules);
  122. }
  123. // dump($filterRules);
  124. $expenses = $em->getRepository(StationExpense::class)->findExpensesExport($filterRules);
  125. $phpExcelObject = new Spreadsheet();
  126. $columns = str_split('ABCDEFGHIJKLMNOPUVWXYZ');
  127. $logger->debug("creating file awesome vv");
  128. // dump("creating a file"); die;
  129. $cancelStyleArray = [
  130. 'fill' => [
  131. 'fillType' => Fill::FILL_SOLID,
  132. 'color' => [
  133. 'rgb' => 'FF0000'
  134. ]
  135. ],
  136. 'font' => [
  137. 'bold' => true,
  138. 'color' => ['rgb' => 'FFFFFFFF'],
  139. 'name' => 'Calibri'
  140. ]
  141. ];
  142. $headerStyleArray = [
  143. 'font' => [
  144. 'bold' => true,
  145. 'color' => ['rgb' => '000000'],
  146. 'size' => 12,
  147. 'name' => 'Cambria'
  148. ]
  149. ];
  150. $phpExcelObject->getActiveSheet()
  151. ->setCellValue('A1', '#')
  152. ->setCellValue('B1', 'DATE')
  153. ->setCellValue('C1', 'STATION')
  154. ->setCellValue('D1', 'USER')
  155. ->setCellValue('E1', 'EXPENSE_TYPE')
  156. ->setCellValue('F1', 'DESCRIPTION')
  157. ->setCellValue('G1', 'AMOUNT')
  158. ->getStyle("A1:G1")
  159. ->applyFromArray($headerStyleArray);
  160. foreach ($expenses as $count => $expense) {
  161. $index = $count + 2;
  162. if($expense->isCancelled()) {
  163. // $parcel['expenses'] = -3;
  164. // $parcel['amount'] = -$parcel['amount'];
  165. $parcel['expenses'] = 0;
  166. $parcel['amount'] = -0;
  167. $phpExcelObject->getActiveSheet()
  168. ->setCellValue('A'.$index, "$index,{$expense->getId()}")
  169. ->setCellValue('B'.$index, $expense->getDailyAccount()->getAccountDate()->format('Y-m-d'))
  170. ->setCellValue('C'.$index, $expense->getStation())
  171. ->setCellValue('D'.$index, $expense->getCreatedBy()->getPerson())
  172. ->setCellValue('E'.$index, $expense->getExpenseType())
  173. ->setCellValue('F'.$index, $expense->getDescription())
  174. ->setCellValue('G'.$index, $expense->getAmount())
  175. ->getStyle("A{$index}:G{$index}")
  176. ->applyFromArray($cancelStyleArray);
  177. // $phpExcelObject->getActiveSheet()
  178. // ->getStyle("A{$index}:G{$index}")
  179. // ->applyFromArray($cancelStyleArray);
  180. }else {
  181. $phpExcelObject->getActiveSheet()
  182. ->setCellValue('A'.$index, "$index,{$expense->getId()}")
  183. ->setCellValue('B'.$index, $expense->getDailyAccount()->getAccountDate()->format('Y-m-d'))
  184. ->setCellValue('C'.$index, $expense->getStation())
  185. ->setCellValue('D'.$index, $expense->getCreatedBy()->getPerson())
  186. ->setCellValue('E'.$index, $expense->getExpenseType())
  187. ->setCellValue('F'.$index, $expense->getDescription())
  188. ->setCellValue('G'.$index, $expense->getAmount())
  189. ->getStyle("A{$index}:G{$index}")
  190. ->applyFromArray([
  191. 'font' => [
  192. 'bold' => false,
  193. 'color' => ['rgb' => '000000'],
  194. 'name' => 'Calibri'
  195. ],
  196. ]);
  197. }
  198. // dump("Entering data");
  199. }
  200. // $phpExcelObject->getActiveSheet()->setTitle("Transactions");
  201. // $phpExcelObject->setActiveSheetIndex(0)->setTitle('Transactions');
  202. $phpExcelObject->getActiveSheet()->setTitle('Expenses');
  203. $logger->debug("saving file awesome vv");
  204. // $writer = $this->get('phpexcel')->createWriter($phpExcelObject,'Excel2007');
  205. $phpExcelObject->getActiveSheet()->setAutoFilter(
  206. $phpExcelObject->getActiveSheet()
  207. ->calculateWorksheetDimension()
  208. );
  209. $writer = new Xlsx($phpExcelObject);
  210. $md5 = md5("{$fromDate}{$toDate}");
  211. $fileName = "transaction_report_{$md5}.xlsx";
  212. try {
  213. $logger->debug("saving file awesome");
  214. $writer->save("reports/{$fileName}");
  215. } catch (Exception $e) {
  216. $logger->debug($e->getMessage());
  217. }
  218. $response = new Response();
  219. $response->headers->set('Content-type', 'text');
  220. $response->setContent($fileName);
  221. return $response;
  222. $fileName = "report_".rand(1,20).".csv";
  223. $fp = fopen($fileName, 'w');
  224. // $fp = fopen('php://output', 'w');
  225. $response = new Response();
  226. $response->headers->set('Content-type', 'text');
  227. $response->setContent($fileName);
  228. return $response;
  229. }
  230. /**
  231. * @Route("/daily_accounts/reports/excel/{fromDate}/{toDate}", name="daily_account_export_excel")
  232. */
  233. public function periodicDailyAccountsExport(Request $request, $fromDate, $toDate, LoggerInterface $logger): Response
  234. {
  235. @ini_set("memory_limit",-1);
  236. set_time_limit(0);
  237. $em = $this->getDoctrine()->getManager();
  238. $context = new SerializationContext();
  239. $context->setSerializeNull(true);
  240. $fDate = null;
  241. $date = new \DateTime('+1 day');
  242. $tDate = null;
  243. // dump($fromDate);
  244. // dump($toDate); die;
  245. $fromDate = $fromDate == 0 ? $fDate: $fromDate;
  246. $toDate = $toDate == 0 ? $tDate: $toDate;
  247. $serializer = SerializerBuilder::create()->build();
  248. $filterRules = $request->request->get('filterRules');
  249. // dump($request->request); die;
  250. if(!$filterRules) {
  251. $filterRules = "[]";
  252. }
  253. if($fromDate && $toDate){
  254. $filterRules = json_decode($filterRules, true);
  255. $dates = [
  256. 'field'=> 'b.created_at',
  257. 'op'=> 'between',
  258. 'value' => [
  259. 'from' => str_replace(" ","", $fromDate),
  260. 'to' => str_replace(" ","", $toDate)
  261. ],
  262. ];
  263. array_push($filterRules, $dates);
  264. $filterRules = json_encode($filterRules);
  265. }
  266. $accounts = $em->getRepository(DailyAccount::class)->findReportDailyAccounts($filterRules);
  267. // dd($accounts);
  268. $phpExcelObject = new Spreadsheet();
  269. $columns = str_split('ABCDEFGHIJKLMNOPUVWXYZ');
  270. $logger->debug("creating file awesome vv");
  271. // dump("creating a file"); die;
  272. $cancelStyleArray = [
  273. 'fill' => [
  274. 'fillType' => Fill::FILL_SOLID,
  275. 'color' => [
  276. 'rgb' => 'FF0000'
  277. ]
  278. ],
  279. 'font' => [
  280. 'bold' => true,
  281. 'color' => ['rgb' => 'FFFFFFFF'],
  282. 'name' => 'Calibri'
  283. ]
  284. ];
  285. $headerStyleArray = [
  286. 'font' => [
  287. 'bold' => true,
  288. 'color' => ['rgb' => '000000'],
  289. 'size' => 12,
  290. 'name' => 'Cambria'
  291. ]
  292. ];
  293. // | id | account_date | station_id | station_name | amount | transactions | expenses |
  294. $phpExcelObject->getActiveSheet()
  295. ->setCellValue('A1', '#')
  296. ->setCellValue('B1', '#')
  297. ->setCellValue('C1', 'DATE')
  298. ->setCellValue('D1', 'STATION')
  299. ->setCellValue('E1', 'TRANSACTIONS')
  300. ->setCellValue('F1', 'AMOUNT')
  301. ->setCellValue('G1', 'EXPENSES')
  302. ->getStyle("A1:G1")
  303. ->applyFromArray($headerStyleArray);
  304. foreach ($accounts as $count => $account) {
  305. $index = $count + 2;
  306. /* if($account->isCancelled()) {
  307. // $parcel['expenses'] = -3;
  308. // $parcel['amount'] = -$parcel['amount'];
  309. $parcel['expenses'] = 0;
  310. $parcel['amount'] = -0;
  311. $phpExcelObject->getActiveSheet()
  312. ->setCellValue('A'.$index, "$index,{$account['id']}")
  313. ->setCellValue('B'.$index, $account['account_date'])
  314. ->setCellValue('C'.$index, $account['station_name'])
  315. ->setCellValue('D'.$index, $account['transactions'])
  316. ->setCellValue('E'.$index, $account['amount'])
  317. ->setCellValue('F'.$index, $account['expenses'])
  318. ->getStyle("A{$index}:F{$index}")
  319. ->applyFromArray($cancelStyleArray);
  320. // $phpExcelObject->getActiveSheet()
  321. // ->getStyle("A{$index}:G{$index}")
  322. // ->applyFromArray($cancelStyleArray);
  323. }else {*/
  324. $phpExcelObject->getActiveSheet()
  325. ->setCellValue('A'.$index, $index)
  326. ->setCellValue('B'.$index, $account['id'])
  327. ->setCellValue('C'.$index, $account['account_date'])
  328. ->setCellValue('D'.$index, $account['station_name'])
  329. ->setCellValue('E'.$index, $account['transactions'])
  330. ->setCellValue('F'.$index, $account['amount'])
  331. ->setCellValue('G'.$index, $account['expenses'])
  332. ->getStyle("A{$index}:G{$index}")
  333. ->applyFromArray([
  334. 'font' => [
  335. 'bold' => false,
  336. 'color' => ['rgb' => '000000'],
  337. 'name' => 'Calibri'
  338. ],
  339. ]);
  340. // dump("Entering data");
  341. }
  342. // $phpExcelObject->getActiveSheet()->setTitle("Transactions");
  343. // $phpExcelObject->setActiveSheetIndex(0)->setTitle('Transactions');
  344. $phpExcelObject->getActiveSheet()->setTitle('DAILY ACCOUNTS');
  345. $logger->debug("saving file awesome vv");
  346. // $writer = $this->get('phpexcel')->createWriter($phpExcelObject,'Excel2007');
  347. $phpExcelObject->getActiveSheet()->setAutoFilter(
  348. $phpExcelObject->getActiveSheet()
  349. ->calculateWorksheetDimension()
  350. );
  351. $writer = new Xlsx($phpExcelObject);
  352. $md5 = md5("{$fromDate}{$toDate}");
  353. $fileName = "transaction_daily_account_report_{$md5}.xlsx";
  354. try {
  355. $logger->debug("saving file awesome");
  356. $writer->save("reports/{$fileName}");
  357. } catch (Exception $e) {
  358. $logger->debug($e->getMessage());
  359. }
  360. $response = new Response();
  361. $response->headers->set('Content-type', 'text');
  362. $response->setContent($fileName);
  363. return $response;
  364. $fileName = "report_".rand(1,20).".csv";
  365. $fp = fopen($fileName, 'w');
  366. // $fp = fopen('php://output', 'w');
  367. $response = new Response();
  368. $response->headers->set('Content-type', 'text');
  369. $response->setContent($fileName);
  370. return $response;
  371. }
  372. /**
  373. *
  374. * @Route("/daily_accounts/{id}", name="daily_station_account")
  375. */
  376. public function indexAction($id){
  377. $em = $this->getDoctrine()->getManager();
  378. $stationDailyAccount = $em->getRepository(StationDailyAccount::class)->findOneBy([
  379. 'id' => $id
  380. ]);
  381. if(!$stationDailyAccount) {
  382. return $this->render('', [
  383. ]);
  384. }
  385. //
  386. // /** @var DailyAccount[] $dailyAccounts */
  387. // $dailyAccounts = $em->getRepository(DailyAccount::class)->findBy([
  388. // 'stationDailyAccount' => $stationDailyAccount
  389. // ]);
  390. $dailyAccount = $em->getRepository(DailyAccount::class)->findOneAccount($stationDailyAccount->getId());
  391. $expenses = $em->getRepository(DailyAccount::class)->findDailyExpenses($stationDailyAccount->getId());
  392. // dump($expenses);
  393. // dump($dailyAccount); die;
  394. return $this->render('bos/daily_accounts/account_detail.html.twig', [
  395. 'station_daily' => $dailyAccount,
  396. 'expenses' => $expenses
  397. ]);
  398. }
  399. /**
  400. *
  401. * @Route("/daily_accounts/view/{id}", name="daily_station_view_account")
  402. */
  403. public function dailyAccountIndex($id){
  404. $em = $this->getDoctrine()->getManager();
  405. $stationDailyAccount = $em->getRepository(StationDailyAccount::class)->findOneBy([
  406. 'id' => $id
  407. ]);
  408. if(!$stationDailyAccount) {
  409. return $this->render('', [
  410. ]);
  411. }
  412. /** @var DailyAccount[] $dailyAccounts */
  413. $dailyAccounts = $em->getRepository(DailyAccount::class)->findBy([
  414. 'stationDailyAccount' => $stationDailyAccount
  415. ]);
  416. $dailyAccount = $em->getRepository(DailyAccount::class)->findOneStationAccount($stationDailyAccount->getId());
  417. return $this->render('bos/daily_accounts/view_daily_account.html.twig', [
  418. 'station_daily' => $dailyAccount
  419. ]);
  420. }
  421. /**
  422. * @Route("/daily_accounts/view/user/{id}", name="daily_station_view_user_daily_account")
  423. */
  424. public function userDailyAccount($id){
  425. $em = $this->getDoctrine()->getManager();
  426. /** @var Transaction[] $transactions */
  427. $transactions = $em->getRepository(Transaction::class)->findUserDailyTransaction($id);
  428. $transactionCount = count($transactions);
  429. // dump($transactions); die;
  430. $total = 0;
  431. $mpesaTotal = 0;
  432. $cashTotal = 0;
  433. foreach ($transactions as $index => $transaction) {
  434. if(!$transaction['is_cancelled']){
  435. $total += $transaction['amount'];
  436. $mpesaTotal += $transaction['mpesaAmount'];
  437. $cashTotal += $transaction['cashAmount'];
  438. }
  439. }
  440. return $this->render('bos/daily_accounts/view_user_daily_account.html.twig', [
  441. 'transactions' => $transactions,
  442. 'total' => $total,
  443. 'cashTotal' => $cashTotal,
  444. 'mpesaTotal' => $mpesaTotal,
  445. 'transactionCount' => $transactionCount,
  446. 'transactions_json' => json_encode($transactions),
  447. 'user_id' => $id
  448. ]);
  449. }
  450. /**
  451. * @Route("/daily_accounts/view/user/{id}/mpesa/{transaction_id}", name="daily_station_view_user_daily_account_mpesa")
  452. */
  453. public function userDailyAccountMpesa($id,$transaction_id){
  454. $em = $em = $this->getDoctrine()->getManager();
  455. $transaction = $em->getRepository(Transaction::class)->findOneBy([
  456. 'id' => $transaction_id
  457. ]);
  458. $mpesa = null;
  459. if($transaction->getPaymentMethod() == 'MPESA' || $transaction->getPaymentMethod() == 'MPESA_CASH'){
  460. $mpesa = $em->getRepository(MpesaTransaction::class)->findOneBy([
  461. 'transaction' => $transaction_id
  462. ]);
  463. }
  464. return $this->render('bos/daily_accounts/mpesa/mpesa_transaction.html.twig', [
  465. 'mpesa' => $mpesa,
  466. 'transaction' => $transaction
  467. ]);
  468. }
  469. /**
  470. *
  471. * @Route("/daily_accounts/view/{id}/expenses", name="daily_station_view_account_expenses")
  472. */
  473. public function dailyAccountExpenses($id){
  474. $em = $this->getDoctrine()->getManager();
  475. /** @var DailyAccount $dailyAccount */
  476. $dailyAccount = $em->getRepository(DailyAccount::class)->findOneBy([
  477. 'id' => $id
  478. ]);
  479. /** @var StationExpense[] $expenses */
  480. $expenses = $em->getRepository(StationExpense::class)->findBy([
  481. 'dailyAccount' => $dailyAccount,
  482. 'isCancelled' => false
  483. ]);
  484. $total = 0;
  485. foreach ($expenses as $index => $expense) {
  486. $total = $total + $expense->getAmount();
  487. }
  488. return $this->render('bos/daily_accounts/expenses/account_expense.html.twig', [
  489. 'expenses' => $expenses,
  490. 'expensesCount' => count($expenses),
  491. 'total' => $total
  492. ]);
  493. }
  494. /**
  495. * @Route("/daily_accounts/view/json/{id}", methods={"POST"}, name="daily_station_view_account_json")
  496. */
  497. public function daily($id) {
  498. $em = $this->getDoctrine()->getManager();
  499. $context = new SerializationContext();
  500. $context->setSerializeNull(true);
  501. $serializer = SerializerBuilder::create()->build();
  502. $stationDailyAccount = $em->getRepository(StationDailyAccount::class)->findOneBy([
  503. 'id' => $id
  504. ]);
  505. if(!$stationDailyAccount) {
  506. return $this->render('', [
  507. ]);
  508. }
  509. $stationAccount = $em->getRepository(DailyAccount::class)->findOneStationAccount($stationDailyAccount->getId());
  510. /** @var DailyAccount[] $dailyAccounts */
  511. $dailyAccounts = $em->getRepository(DailyAccount::class)->findEveryDailyAccounts($stationDailyAccount->getId());
  512. // dump($dailyAccounts);die;
  513. // $dailyAccount = $em->getRepository(DailyAccount::class)->findOneAccount($stationDailyAccount->getId());
  514. $data = [
  515. 'total' => count($dailyAccounts),
  516. 'rows' => $dailyAccounts,
  517. 'footer' => $stationAccount
  518. ];
  519. $data = $serializer->serialize($data,'json', $context);
  520. return new Response($data, Response::HTTP_OK);
  521. }
  522. /**
  523. * @Route("/json/daily_accounts", methods={"POST"}, name="daily_accounts_json")
  524. */
  525. public function dailyTransactions(Request $request) {
  526. $em = $this->getDoctrine()->getManager();
  527. $context = new SerializationContext();
  528. $context->setSerializeNull(true);
  529. $serializer = SerializerBuilder::create()->build();
  530. $page = $request->request->get('page') > 1 ? $request->request->get('page'): 1;
  531. $rows = $request->request->get('rows') > 1 ? $request->request->get('rows'): 20;
  532. $offset = ($page - 1)*$rows;
  533. $filterRules = $request->request->get('filterRules');
  534. $fromDate = $request->request->get("from_date");
  535. $toDate = $request->request->get("to_date");
  536. $fDate = null;
  537. $date = new \DateTime('+1 day');
  538. $tDate = null;
  539. // dump($fDate);
  540. // dump($tDate); die;
  541. $fromDate = empty($fromDate) ? $fDate: $fromDate;
  542. $toDate = empty($toDate) ? $tDate: $toDate;
  543. if($fromDate && $toDate){
  544. $filterRules = json_decode($filterRules, true);
  545. $dates = [
  546. 'field'=> 'a.account_date',
  547. 'op'=> 'between',
  548. 'value' => [
  549. 'from' => str_replace(" ","", $fromDate),
  550. 'to' => str_replace(" ","", $toDate)
  551. ],
  552. ];
  553. array_push($filterRules, $dates);
  554. $filterRules = json_encode($filterRules);
  555. }
  556. $accounts = $em->getRepository(DailyAccount::class)->findAllDailyAccounts($filterRules, $offset, $rows);
  557. $totals = $em->getRepository(DailyAccount::class)->findAllTotals($filterRules);
  558. // $dailyAccount =
  559. // dump($totals);die;
  560. /*$dailyAccount = new DailyAccount();
  561. $stationAccount = new StationDailyAccount();
  562. $station = new Station();
  563. $user = new User();
  564. $person = new Person();
  565. $person->setFirstName('');
  566. $person->setSecondName('');
  567. $person->setSirName('');
  568. $user->setPerson($person);
  569. $station->setStationName('');
  570. $stationAccount->setStation($station);
  571. $dailyAccount->setStationDailyAccount($stationAccount);
  572. $dailyAccount->setUser($user);
  573. $dailyAccount->setTransactionsNo(number_format($totals[0]['transactions']));
  574. $dailyAccount->setAmount(number_format($totals[0]['amount']));
  575. $dailyAccount->setExpenses(number_format($totals[0]['expenses']));*/
  576. // $total = $totals[0]['total'];
  577. // $footerTotals = array();
  578. // array_push($footerTotals, $dailyAccount);
  579. $data = [
  580. 'total' => $totals['total_accounts'],
  581. 'rows' => $accounts,
  582. ];
  583. $data = $serializer->serialize($data,'json', $context);
  584. return new Response($data, Response::HTTP_OK);
  585. }
  586. /**
  587. * @Route("/daily_", name="daily_")
  588. * @param Request $request
  589. * @throws \Mpdf\MpdfException
  590. */
  591. public function dailyAccountReport(Request $request){
  592. $post = $request->request;
  593. $dates = $request->request->get('date_times');
  594. if(!$dates){
  595. return $this->redirectToRoute('daily_accounts');
  596. }
  597. $dates = explode('-', $dates);
  598. $date_1 = trim($dates[0]);
  599. $date_2 = trim($dates[1]);
  600. $days = date_diff(date_create($date_1), date_create($date_2))->format("%R%a")+1;
  601. $data = [
  602. 'message' => 'the date difference must be at least a week',
  603. 'date_1' => $date_1,
  604. 'date_2' => $date_2,
  605. 'dif' => $days
  606. ];
  607. $data = json_encode($data);
  608. if((int)$days < 7){
  609. return new Response(
  610. $data, Response::HTTP_EXPECTATION_FAILED);
  611. }
  612. $starting = date('Y-m-d', strtotime($date_1));
  613. $ending = date('Y-m-d',strtotime($date_2));
  614. $em = $this->getDoctrine()->getManager();
  615. $sqlSet = "SET SESSION group_concat_max_len = 1000000; ";
  616. $stmt = $em->getConnection()->prepare($sqlSet);
  617. $stmt->execute();
  618. $sql = " SELECT c.id, a.station_daily_account, c.station_name, ANY_VALUE(a.user_id) as parcel_no,
  619. ANY_VALUE(a.parcel_no) as parcel_no,
  620. ANY_VALUE(a.account_date) as account_date, sum(a.amount) as amount, sum(a.expenses) AS expenses,
  621. (sum(a.amount) - sum(a.expenses)) as net_income,
  622. (SELECT CONCAT('[',
  623. GROUP_CONCAT(
  624. JSON_OBJECT(
  625. 'user', concat(p.first_name,' ',p.second_name,' ',p.sir_name),
  626. 'account_id', da.id,
  627. 'gross_income', da.amount,
  628. 'total_expenses', da.expenses,
  629. 'net_income', (da.amount - da.expenses)
  630. )
  631. ),']') FROM daily_account da
  632. JOIN user u on da.user_id = u.id
  633. JOIN person p on u.person_id = p.id
  634. WHERE da.station_daily_account = a.station_daily_account) AS user_accounts,
  635. (SELECT CONCAT(
  636. '[', GROUP_CONCAT(
  637. JSON_OBJECT(
  638. 'user_id', daa.user_id,
  639. 'user', concat(paa.first_name,' ',paa.second_name,' ',paa.sir_name),
  640. 'details', (SELECT CONCAT('[',
  641. GROUP_CONCAT(
  642. JSON_OBJECT(
  643. 'expense', et.id,
  644. 'expense_type', et.expense_name,
  645. 'description', se0.description,
  646. 'amount', se0.amount,
  647. 'daily_account', daa.id
  648. )
  649. ),']'
  650. ) FROM station_expense se0
  651. JOIN daily_account da0 ON da0.id = se0.daily_account_id
  652. JOIN expense_type et on se0.expense_type_id = et.id
  653. WHERE se0.daily_account_id = daa.id and se0.created_by = da0.user_id)
  654. )
  655. ), ']') FROM daily_account daa
  656. JOIN user uaa ON uaa.id = daa.user_id
  657. JOIN person paa on uaa.person_id = paa.id
  658. WHERE daa.station_daily_account = a.station_daily_account AND daa.expenses > 0) AS detail_expenses
  659. FROM station_daily_account b
  660. JOIN daily_account a ON b.id = a.station_daily_account
  661. JOIN station c ON c.id = b.station_id
  662. WHERE b.account_date BETWEEN CAST('{$starting}' AS DATE) AND CAST('{$ending}' AS DATE) GROUP BY a.station_daily_account
  663. ORDER BY c.id";
  664. $stmt = $em->getConnection()->prepare($sql);
  665. $stmt->execute();
  666. $stations = $stmt->fetchAll();
  667. /** @var User $user */
  668. $user = $this->getUser();
  669. $person = $user->getPerson();
  670. $user = $person->getFirstName().' '.$person->getSecondName().' '.$person->getSirName();
  671. $fromDate = strtotime($starting);
  672. $toDate = strtotime($ending);
  673. $dates = [
  674. 'from' =>[
  675. 's' => strtolower(date('S', $fromDate)),
  676. 'm' => date('M', $fromDate),
  677. 'day' => date('d', $fromDate),
  678. 'year' => date('Y', $fromDate)
  679. ],
  680. 'to' => [
  681. 's' => date('S', $toDate),
  682. 'm' => date('M', $toDate),
  683. 'day' => date('d', $toDate),
  684. 'year' => date('Y', $toDate)
  685. ]
  686. ];
  687. $footer = '<table width="100%">
  688. <tr>
  689. <td align="left" style="text-transform: uppercase; font-size: 8px; font-family: "Amaranth", sans-serif">
  690. Printed by: <b style="color: gray;"><b>'.strtoupper($user).'</b></b>
  691. '.date('l F d Y').'
  692. </td>
  693. <td align="right" style="color: #000; text-decoration:italic; font-size:8px;">
  694. <span style=" font-size: 8px; color: green; font-family: "Amaranth", sans-serif">
  695. powered by ohau technologies
  696. </span>
  697. <b style="color: #000;font-size:10px;">&nbsp; {PAGENO}/{nb}</b>
  698. </td>
  699. </tr>
  700. </table>';
  701. $header = '
  702. <table width="100%"
  703. style=" border-bottom: 2px solid red;
  704. vertical-align: top;
  705. height:200px;
  706. font-family: serif;
  707. font-size: 9pt;
  708. color: blue;">
  709. <tr>
  710. <td style="width: 20%;">
  711. <img src="assets/img/courier.jpg" width="120px" height="100px" />
  712. </td>
  713. <td align="center">
  714. <div style="font-size:16pt;">
  715. <h4>NENO COURIER SERVICES LTD</h4>
  716. </div>
  717. <div style="font-size:12pt; ">
  718. P.O BOX 660-60100
  719. </div>
  720. <div style="font-size:14pt; ">
  721. EMBU
  722. </div>
  723. <div style="font-size:12pt; text-transform: lowercase;">
  724. nenocourier@gmail.com
  725. </div>
  726. </td>
  727. <td style="width:20%;">
  728. </td>
  729. </tr>
  730. </table>
  731. ';
  732. // dump($stations); die;
  733. /*$context = new SerializationContext();
  734. $context->setSerializeNull(true);
  735. //
  736. ////
  737. ////
  738. $serializer = SerializerBuilder::create()->build();
  739. ////
  740. $data = $serializer->serialize($stations,'json', $context);*/
  741. // $JSONStations = json_encode($stations, JSON_UNESCAPED_SLASHES);
  742. // return new Response($data);
  743. // dump($stations);
  744. // die;
  745. // dump($stations); die;
  746. // $new_date = date('S j F Y', strtotime('2018-11-22'));
  747. // dump($new_date); die;
  748. // return $this->render('report.html.twig', [
  749. // 'stations' => $stations
  750. // ]);
  751. $html = $this->render('report.html.twig', array(
  752. 'stations' => $stations,
  753. 'dates' => $dates
  754. ))->getContent();
  755. $mpdf = new Mpdf([
  756. 'mode' => 'utf-8',
  757. 'orientation' => 'P',
  758. 'margin_top' => 50,
  759. 'margin_footer' => 20,
  760. 'tempDir' => $this->getParameter('kernel.project_dir').'/var/mpdf_temp'
  761. ]);
  762. // epos300
  763. $mpdf->SetHeader($header);
  764. $mpdf->SetFooter($footer);
  765. $mpdf->WriteHTML($html);
  766. $mpdf->Output('daily_account_report.pdf', 'D');
  767. // return $this->render('report.html.twig', [
  768. // 'stations' => $stations
  769. // ]);
  770. }
  771. /**
  772. * @Route("/daily_accounts/update_daily_account/{id}", methods={"GET"}, name="update_payment_method_daily_account")
  773. */
  774. public function updateDailyAccounts($id){
  775. $em = $this->getDoctrine()->getManager();
  776. // $dailyAccount = $em->getRepository(DailyAccount::class)->findBy([
  777. // 'id' => $id,
  778. // ]);
  779. $accountTransactions = $em->getRepository(Transaction::class)->findBy([
  780. 'dailyAccount' => $id,
  781. 'paymentMethod' => 'MPESA'
  782. ]);
  783. foreach($accountTransactions as $accountTransaction) {
  784. $accountTransaction->setPaymentMethod('MPESA');
  785. $accountTransaction->setMpesaAmount($accountTransaction->getAmount());
  786. }
  787. $em->flush();
  788. return new Response("UPDATED SUCCESSFULLY", Response::HTTP_OK);
  789. }
  790. }