src/Controller/Admin/DashboardController.php line 97

Open in your IDE?
  1. <?php
  2. namespace App\Controller\Admin;
  3. use App\Entity\Clinic\Appointment;
  4. use App\Entity\Clinic\Appointment\GoogleEvent;
  5. use App\Entity\Clinic\Clinic;
  6. use App\Entity\Clinic\Person\ClinicUser;
  7. use App\Entity\Clinic\Stock\PriceList;
  8. use App\Entity\Clinic\Stock\Product;
  9. use App\Entity\Clinic\Stock\ProductBalanceHistory;
  10. use App\Entity\Clinic\Stock\TreatmentClinic;
  11. use App\Entity\Clinic\TaskBoard;
  12. use App\Entity\Clinic\TaskBoard\TaskItem;
  13. use App\Entity\LeadCapture\LeadCapture;
  14. use App\Entity\Patient\BaseInvoice;
  15. use App\Entity\Patient\CreditNote;
  16. use App\Entity\Patient\GiftVoucher;
  17. use App\Entity\Patient\Invoice;
  18. use App\Entity\Patient\Invoice\Refund;
  19. use App\Entity\Patient\Payment;
  20. use App\Entity\Patient\Payment\Kind;
  21. use App\Entity\Patient\Prepay;
  22. use App\Entity\Person\Patient;
  23. use App\Entity\Person\Setting;
  24. use App\Entity\Person\SuperClinicAdmin;
  25. use App\Form\Model\DashboardFilter;
  26. use App\Form\Model\SearchFilter;
  27. use App\Form\Type\Dashboard\DashboardFilterType;
  28. use App\Form\Type\Model\BoardSearchClinicFilterType;
  29. use App\Form\Type\Person\SettingType;
  30. use App\HighCharts\TransformData;
  31. use App\Services\CreateDefaultTaskBoard;
  32. use App\Services\DashboardService;
  33. use App\Services\Twilio;
  34. use Doctrine\Common\Collections\Criteria;
  35. use Doctrine\Persistence\ManagerRegistry;
  36. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  37. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  38. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  39. use Symfony\Component\HttpFoundation\JsonResponse;
  40. use Symfony\Component\HttpFoundation\Request;
  41. use Symfony\Component\Routing\Annotation\Route;
  42. use Twilio\Rest\Api\V2010\Account\MessageInstance;
  43. use WhiteOctober\BreadcrumbsBundle\Model\Breadcrumbs;
  44. use App\Entity\Person\User;
  45. use App\Entity\SmsSetting;
  46. /**
  47.  * Class DashboardController.
  48.  *
  49.  * @Route("/admin")
  50.  * @Security("is_granted('ROLE_SUB_DASHBOARD')")
  51.  */
  52. class DashboardController extends AbstractController
  53. {
  54.     /**
  55.      * @var Breadcrumbs
  56.      */
  57.     private $breadcrumbs;
  58.     /**
  59.      * @var CreateDefaultTaskBoard
  60.      */
  61.     private $createDefaultTaskBoard;
  62.     /**
  63.      * @var DashboardService
  64.      */
  65.     private $dashboardService;
  66.     public function __construct(
  67.         Breadcrumbs $breadcrumbs,
  68.         CreateDefaultTaskBoard $createDefaultTaskBoard,
  69.         DashboardService $dashboardService
  70.     ) {
  71.         $this->breadcrumbs $breadcrumbs;
  72.         $this->createDefaultTaskBoard $createDefaultTaskBoard;
  73.         $this->dashboardService $dashboardService;
  74.     }
  75.     /**
  76.      * @var ManagerRegistry
  77.      */
  78.     private static $entityManager;
  79.     public static function setEntityManager(ManagerRegistry $entityManager)
  80.     {
  81.         self::$entityManager $entityManager;
  82.     }
  83.     /**
  84.      * @Route("", name="dashboard_index")
  85.      * @Template()
  86.      */
  87.     public function index(Request $request)
  88.     {
  89.         $user $this->getUser();
  90.         // $connection = $this->getDoctrine()->getManager()->getConnection();
  91.         // $sql = "SELECT * FROM user WHERE id = :userId";
  92.         // $statement = $connection->prepare($sql);
  93.         // $statement->bindValue('userId', $user->getId());
  94.         // $statement->execute();
  95.         // $usr = $statement->fetch();
  96.         // $clinic = $this->getDoctrine()->getRepository(User::Class)->find($usr['clinic_id']);
  97.         $filter = new DashboardFilter();
  98.         $filter->addClinic($this->getClinic());
  99.         $filter->setDashboard(true);
  100.         $form $this->createForm(DashboardFilterType::class, $filter, [
  101.             'timezone' => $this->getParameter('google_calendar_default_timezone'),
  102.             'user' => $this->getUser()
  103.         ]);
  104.         $form->handleRequest($request);
  105.         if (== $filter->getClinics()->count() && ($user instanceof SuperClinicAdmin || $user->getRole() == User::ROLE_SUPER_CLINIC_ADMIN)) {
  106.             $user->getOrganisation()->getClinics()->map(function (Clinic $clinic) use (&$filter) {
  107.                 $filter->addClinic($clinic);
  108.             });
  109.         }
  110.         if ($user instanceof ClinicUser && $user->getRole() != User::ROLE_SUPER_CLINIC_ADMIN) {
  111.             $filter->addClinic($user->getClinic());
  112.         }
  113.         $filter->getDateEnd()->setTime(235959);
  114.         if ($filter->getDateEndSecond()) {
  115.             $filter->getDateEndSecond()->setTime(235959);
  116.         }
  117.         $filter->getDateStart()->setTimezone(new \DateTimeZone('UTC'));
  118.         $filter->getDateEnd()->setTimezone(new \DateTimeZone('UTC'));
  119.         $filter->getDateStartSecond()->setTimezone(new \DateTimeZone('UTC'));
  120.         $filter->getDateEndSecond()->setTimezone(new \DateTimeZone('UTC'));
  121.         $setting $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['user' => $user]);
  122.         if (!$setting) {
  123.             $setting = new Setting();
  124.             $setting->setUser($user);
  125.         }
  126.         $settingsForm $this->createForm(SettingType::class, $setting, [
  127.             'action' => $this->generateUrl('setting', ['redirect' => 1]),
  128.             'clinic' => $filter->getClinics()->count() ? $filter->getClinics()->first() : null,
  129.         ]);
  130.         $breadcrumbs $this->breadcrumbs;
  131.         $breadcrumbs->addItem('Dashboard');
  132.         $settingsList $this->getDoctrine()->getRepository(Setting::class)->findOneBy(['user' => $this->getUser()]);
  133.         if ((!$settingsList || !$settingsList->getValue()) && $this->isGranted('ROLE_SUB_REPORTING')) {
  134.             $this->addFlash('warning''Please select Charts from the Dashboard Settings panel below');
  135.         }
  136.         $searchClinicFilter = new SearchFilter();
  137.         $searchClinicFilter->setCurrentUser($user);
  138.         $searchClinicFilter->setForMe((bool) $request->get('forMe'));
  139.         $formSearchClinic $this->createForm(BoardSearchClinicFilterType::class, $searchClinicFilter, ['user' => $user]);
  140.         $formSearchClinic->handleRequest($request);
  141.         if ($user instanceof ClinicUser && $user->getRole() != User::ROLE_SUPER_CLINIC_ADMIN) {
  142.             $this->createDefaultTaskBoard->create($user->getClinic());
  143.             $searchClinicFilter->setClinic($user->getClinic());
  144.         } else {
  145.             if ($searchClinicFilter->getClinic()) {
  146.                 $this->createDefaultTaskBoard->create($searchClinicFilter->getClinic());
  147.             }
  148.         }
  149.         if ($user->getRole() == User::ROLE_CONSENTZ_ADMIN) {
  150.             $clinic '';
  151.         }else{
  152.             $clinic $user->getClinic();
  153.         }
  154.         return [
  155.             'form' => $form->createView(),
  156.         'clinic' => $clinic,
  157.             'filter' => $filter,
  158.             'settingsForm' => $settingsForm->createView(),
  159.             'settingsList' => $settingsList $settingsList->getValue() : null,
  160.             'formTaskBoard' => ($user instanceof SuperClinicAdmin || $user->getRole() == User::ROLE_SUPER_CLINIC_ADMIN) ? $formSearchClinic->createView() : null,
  161.             'boardList' => $this->getDoctrine()->getRepository(TaskBoard::class)
  162.                 ->findBy(['clinic' => $searchClinicFilter->getClinic()], ['position' => Criteria::ASC]),
  163.             'taskList' => $this->getDoctrine()->getRepository(TaskItem::class)
  164.                 ->findTaskByFilter($searchClinicFilter),
  165.             'searchClinicFilter' => $searchClinicFilter,
  166.         ];
  167.     }
  168.     /**
  169.      * @return Clinic|null
  170.      */
  171.     private function getClinic()
  172.     {
  173.         return $this->getUser() instanceof ClinicUser $this->getUser()->getClinic() : null;
  174.     }
  175.     /**
  176.      * @return JsonResponse
  177.      *
  178.      * @Route("/dashboard/transaction", name="dashboard_transaction", options={"expose" = "true"}, methods={"POST"})
  179.      */
  180.     public function transactions(Request $request)
  181.     {
  182.         $filter $this->getFilter($request);
  183.         $filter->setNameReport(Setting::TRANSACTIONS);
  184.         $baseInvoice $this->getDoctrine()->getRepository(BaseInvoice::class)->selectInvoicesDeatilPage($filter)->getResult();
  185.         $originalPaymentType $this->getDoctrine()->getRepository(Kind::class)->findBy(['clinic' => $filter->getClinics()->getValues()]);
  186.         $arrOriginalType = [];
  187.         $criteriaDb Criteria::create()->andWhere(
  188.             Criteria::expr()->andX(
  189.                 Criteria::expr()->gte('createdAt'$filter->getDateStart()),
  190.                 Criteria::expr()->lt('createdAt'$filter->getDateEnd())
  191.             )
  192.         );
  193.         /** @var Kind $type */
  194.         foreach ($originalPaymentType as $type) {
  195.             $arrOriginalType array_merge($arrOriginalTypearray_filter([$type->getType() => $type->getColor()]));
  196.         }
  197.         $data = [];
  198.         $resultData = [];
  199.         $result = [];
  200.         $categories = [];
  201.         $format $this->dashboardService->createFormat($filter);
  202.         $datePayment $this->dashboardService->createDefaultData($filter);
  203.         /* @var BaseInvoice $payment */
  204.         foreach ($baseInvoice as $item) {
  205.             if ($item instanceof Prepay && $item->getKind()) {
  206.                 $dataType[] = $item->getKind()->getType();
  207.             }
  208.             if ($item instanceof Invoice) {
  209.                 /** @var Payment $payment */
  210.                 foreach ($item->getPayments()->matching($criteriaDb) as $payment) {
  211.                     if (!$payment->isPrepay()) {
  212.                         $dataType[] = $payment->getType()->getType();
  213.                     }
  214.                 }
  215.             }
  216.         }
  217.         if (isset($dataType)) {
  218.             $dataType array_unique($dataType);
  219.         } else {
  220.             $dataType array_column($this->getDoctrine()->getRepository(Kind::class)->findNamePaymentType($filter->getClinics()->getValues()), 'type');
  221.         }
  222.         /**
  223.          * @var string
  224.          * @var \DateTime $dateValue
  225.          */
  226.         foreach ($datePayment as $dateItem => $dateValue) {
  227.             $date $dateValue;
  228.             $name null;
  229.             $arrSomeDate = [];
  230.             $defaultKeyValue array_fill_keys($dataType0);
  231.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  232.                 $cloneDate = clone $dateValue;
  233.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  234.             }
  235.             /* @var BaseInvoice $payment */
  236.             foreach ($baseInvoice as $item) {
  237.                 if ($item instanceof Prepay && $item->getKind()) {
  238.                     $type $item->getKind()->getType();
  239.                     if ($dateItem == $item->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  240.                         if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  241.                             $cloneDate = clone $item->getCreatedAt();
  242.                             $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  243.                         }
  244.                         $date $item->getCreatedAt();
  245.                         if (array_key_exists($type$arrSomeDate)) {
  246.                             $value $arrSomeDate[$type];
  247.                             $value += (float) $item->getAmount();
  248.                             $arrSomeDate[$type] = $value;
  249.                         } else {
  250.                             $arrSomeDate[$type] = (float) $item->getAmount();
  251.                         }
  252.                     }
  253.                 }
  254.                 if ($item instanceof Invoice) {
  255.                     /** @var Payment $payment */
  256.                     foreach ($item->getPayments() as $payment) {
  257.                         if (!$payment->isPrepay()) {
  258.                             $type $payment->getType()->getType();
  259.                             if ($dateItem == $payment->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  260.                                 if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  261.                                     $cloneDate = clone $payment->getCreatedAt();
  262.                                     $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  263.                                 }
  264.                                 $date $payment->getCreatedAt();
  265.                                 if (array_key_exists($type$arrSomeDate)) {
  266.                                     $value $arrSomeDate[$type];
  267.                                     $value += (float) $payment->getAmount();
  268.                                     $arrSomeDate[$type] = $value;
  269.                                 } else {
  270.                                     $arrSomeDate[$type] = (float) $payment->getAmount();
  271.                                 }
  272.                             }
  273.                         }
  274.                     }
  275.                 }
  276.             }
  277.             $arrSomeDate array_merge($defaultKeyValue$arrSomeDate);
  278.             if ($arrSomeDate) {
  279.                 $data[] = [
  280.                     'data' => $arrSomeDate,
  281.                     'categories' => $name $name $dateItem,
  282.                     'date' => $date
  283.                 ];
  284.             }
  285.         }
  286.         if ($data) {
  287.             usort($data, function ($a$b) {
  288.                 return ($a['date'] < $b['date']) ? -1;
  289.             });
  290.             $ars = [];
  291.             foreach ($data as $item) {
  292.                 foreach ($item['data'] as $key => $value) {
  293.                     if (array_key_exists($key$ars)) {
  294.                         $ars[$key][] = $value;
  295.                     } else {
  296.                         $ars[$key] = [$value];
  297.                     }
  298.                 }
  299.                 $resultData['data'] = $ars;
  300.             }
  301.             foreach ($resultData['data'] as $key => $value) {
  302.                 $arr['name'] = $key;
  303.                 $arr['data'] = $value;
  304.                 $arr['color'] = isset($arrOriginalType[$key]) ? $arrOriginalType[$key] : null;
  305.                 $result['data'][] = $arr;
  306.             }
  307.             foreach ($data as $item) {
  308.                 $categories[] = $item['categories'];
  309.             }
  310.             $result['categories'] = $categories;
  311.         }
  312.         return $this->json($result);
  313.     }
  314.     /**
  315.      * @return JsonResponse
  316.      *
  317.      * @Route("/dashboard/net-transaction", name="dashboard_net_transaction", options={"expose" = "true"}, methods={"POST"})
  318.      */
  319.     public function netTransactions(Request $request)
  320.     {
  321.         $filter $this->getFilter($request);
  322.         $filter->setNameReport(Setting::TRANSACTIONS);
  323.         $baseInvoice $this->getDoctrine()->getRepository(BaseInvoice::class)->selectInvoicesDeatilPage($filter)->getResult();
  324.         $originalPaymentType $this->getDoctrine()->getRepository(Kind::class)->findBy(['clinic' => $filter->getClinics()->getValues()]);
  325.         $arrOriginalType = [];
  326.         $criteriaDb Criteria::create()->andWhere(
  327.             Criteria::expr()->andX(
  328.                 Criteria::expr()->gte('createdAt'$filter->getDateStart()),
  329.                 Criteria::expr()->lt('createdAt'$filter->getDateEnd())
  330.             )
  331.         );
  332.         /** @var Kind $type */
  333.         foreach ($originalPaymentType as $type) {
  334.             $arrOriginalType array_merge($arrOriginalTypearray_filter([$type->getType() => $type->getColor()]));
  335.             //            $arrOriginalType[$type->getType()] = $type->getColor();
  336.         }
  337.         $data = [];
  338.         $resultData = [];
  339.         $result = [];
  340.         $categories = [];
  341.         $format $this->dashboardService->createFormat($filter);
  342.         $datePayment $this->dashboardService->createDefaultData($filter);
  343.         /* @var BaseInvoice $payment */
  344.         foreach ($baseInvoice as $item) {
  345.             if ($item instanceof Prepay && $item->getKind()) {
  346.                 $dataType[] = $item->getKind()->getType();
  347.             }
  348.             if ($item instanceof Invoice) {
  349.                 /** @var Payment $payment */
  350.                 foreach ($item->getPayments()->matching($criteriaDb) as $payment) {
  351.                     if (!$payment->isPrepay()) {
  352.                         $dataType[] = $payment->getType()->getType();
  353.                     }
  354.                 }
  355.                 /** @var Refund $refund */
  356.                 foreach ($item->getItems()->matching($criteriaDb) as $refund) {
  357.                     if ($refund instanceof Refund && !$refund->isPrepay()) {
  358.                         $dataType[] = $refund->getKind()->getType();
  359.                     }
  360.                 }
  361.             }
  362.         }
  363.         if (isset($dataType)) {
  364.             $dataType array_unique($dataType);
  365.         } else {
  366.             $dataType array_column($this->getDoctrine()->getRepository(Kind::class)->findNamePaymentType($filter->getClinics()->getValues()), 'type');
  367.         }
  368.         /**
  369.          * @var string
  370.          * @var \DateTime $dateValue
  371.          */
  372.         foreach ($datePayment as $dateItem => $dateValue) {
  373.             $date $dateValue;
  374.             $name null;
  375.             $arrSomeDate = [];
  376.             $defaultKeyValue array_fill_keys($dataType0);
  377.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  378.                 $cloneDate = clone $dateValue;
  379.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  380.             }
  381.             /* @var BaseInvoice $payment */
  382.             foreach ($baseInvoice as $item) {
  383.                 if ($item instanceof Prepay && $item->getKind()) {
  384.                     $type $item->getKind()->getType();
  385.                     if ($dateItem == $item->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  386.                         if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  387.                             $cloneDate = clone $item->getCreatedAt();
  388.                             $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  389.                         }
  390.                         $date $item->getCreatedAt();
  391.                         if (array_key_exists($type$arrSomeDate)) {
  392.                             $value $arrSomeDate[$type];
  393.                             $value += (float) $item->getAmount();
  394.                             $arrSomeDate[$type] = $value;
  395.                         } else {
  396.                             $arrSomeDate[$type] = (float) $item->getAmount();
  397.                         }
  398.                     }
  399.                 }
  400.                 if ($item instanceof Invoice) {
  401.                     /** @var Payment $payment */
  402.                     foreach ($item->getPayments() as $payment) {
  403.                         if (!$payment->isPrepay()) {
  404.                             $type $payment->getType()->getType();
  405.                             if ($dateItem == $payment->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  406.                                 if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  407.                                     $cloneDate = clone $payment->getCreatedAt();
  408.                                     $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  409.                                 }
  410.                                 $date $payment->getCreatedAt();
  411.                                 if (array_key_exists($type$arrSomeDate)) {
  412.                                     $value $arrSomeDate[$type];
  413.                                     $value += (float) $payment->getAmount();
  414.                                     $arrSomeDate[$type] = $value;
  415.                                 } else {
  416.                                     $arrSomeDate[$type] = (float) $payment->getAmount();
  417.                                 }
  418.                             }
  419.                         }
  420.                     }
  421.                     /** @var Refund $itemInv */
  422.                     foreach ($item->getItems() as $itemInv) {
  423.                         if ($itemInv instanceof Refund && !$itemInv->isPrepay()) {
  424.                             $type $itemInv->getKind()->getType();
  425.                             if ($dateItem == $itemInv->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  426.                                 if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  427.                                     $cloneDate = clone $itemInv->getCreatedAt();
  428.                                     $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  429.                                 }
  430.                                 $date $itemInv->getCreatedAt();
  431.                                 if (array_key_exists($type$arrSomeDate)) {
  432.                                     $value $arrSomeDate[$type];
  433.                                     $value += (float) $itemInv->getTotal();
  434.                                     $arrSomeDate[$type] = $value;
  435.                                 } else {
  436.                                     $arrSomeDate[$type] = (float) $itemInv->getTotal();
  437.                                 }
  438.                             }
  439.                         }
  440.                     }
  441.                 }
  442.             }
  443.             $arrSomeDate array_merge($defaultKeyValue$arrSomeDate);
  444.             if ($arrSomeDate) {
  445.                 $data[] = [
  446.                     'data' => $arrSomeDate,
  447.                     'categories' => $name $name $dateItem,
  448.                     'date' => $date
  449.                 ];
  450.             }
  451.         }
  452.         if ($data) {
  453.             usort($data, function ($a$b) {
  454.                 return ($a['date'] < $b['date']) ? -1;
  455.             });
  456.             $ars = [];
  457.             foreach ($data as $item) {
  458.                 foreach ($item['data'] as $key => $value) {
  459.                     if (array_key_exists($key$ars)) {
  460.                         $ars[$key][] = $value;
  461.                     } else {
  462.                         $ars[$key] = [$value];
  463.                     }
  464.                 }
  465.                 $resultData['data'] = $ars;
  466.             }
  467.             foreach ($resultData['data'] as $key => $value) {
  468.                 $arr['name'] = $key;
  469.                 $arr['data'] = $value;
  470.                 $arr['color'] = isset($arrOriginalType[$key]) ? $arrOriginalType[$key] : null;
  471.                 $result['data'][] = $arr;
  472.             }
  473.             foreach ($data as $item) {
  474.                 $categories[] = $item['categories'];
  475.             }
  476.             $result['categories'] = $categories;
  477.         }
  478.         return $this->json($result);
  479.     }
  480.     /**
  481.      * @return JsonResponse
  482.      *
  483.      * @Route("/dashboard/cash-transaction", name="dashboard_cash_transaction", options={"expose" = "true"}, methods={"POST"})
  484.      */
  485.     public function cashTrans(Request $request)
  486.     {
  487.         $filter $this->getFilter($request);
  488.         return $this->json(
  489.             TransformData::transform(
  490.                 $this->getDoctrine()->getRepository(Payment::class)->findPaymentCashByFilter($filter)
  491.             )
  492.         );
  493.     }
  494.     /**
  495.      * @return JsonResponse
  496.      *
  497.      * @Route("/dashboard/dashboard_card_transaction", name="dashboard_card_transaction", options={"expose" = "true"}, methods={"POST"})
  498.      */
  499.     public function cardTransactionBySuplier(Request $request)
  500.     {
  501.         $filter $this->getFilter($request);
  502.         return $this->json(
  503.             TransformData::transform(
  504.                 $this->getDoctrine()->getRepository('App:Patient\Payment')->findPaymentCardByFilter($filter)
  505.             )
  506.         );
  507.     }
  508.     /**
  509.      * @return JsonResponse
  510.      *
  511.      * @Route("/dashboard/stock-levels", name="stock-levels", options={"expose" = "true"}, methods={"POST"})
  512.      */
  513.     public function stockLevels(Request $request)
  514.     {
  515.         $filter $this->getFilter($request);
  516.         return $this->json(
  517.             TransformData::transform(
  518.                 $this->getDoctrine()->getRepository(Product::class)->findStockLevelsByFilter($filter)
  519.             )
  520.         );
  521.     }
  522.     /**
  523.      * @return JsonResponse
  524.      *
  525.      * @Route("/dashboard/stock-values", name="stock-values", options={"expose" = "true"}, methods={"POST"})
  526.      */
  527.     public function stockValues(Request $request)
  528.     {
  529.         $filter $this->getFilter($request);
  530.         $currentBalance 0;
  531.         $data = [];
  532.         $dataProduct = [];
  533.         $originalProducts = [];
  534.         $products $this->getDoctrine()->getRepository(Product::class)->selectProductByFilter($filter)->getQuery()->getResult();
  535.         /** @var Product $product */
  536.         foreach ($products as $product) {
  537.             $currentBalance += $product->getTotal();
  538.             $originalProducts['id_' $product->getId()] = $product->getTotal();
  539.         }
  540.         $productsHistory $this->getDoctrine()->getRepository(ProductBalanceHistory::class)->selectProductByFilter($filter)->getQuery()->getResult();
  541.         /** @var ProductBalanceHistory $item */
  542.         foreach ($productsHistory as $item) {
  543.             $itemProduct $item->getProduct();
  544.             if (isset($dataProduct['id_' $itemProduct->getId()])) {
  545.                 $dataProduct['id_' $itemProduct->getId()] = (($item->getBalance() * $itemProduct->getUnitPrice()) > $dataProduct['id_' $itemProduct->getId()]) ? ($item->getBalance() * $itemProduct->getUnitPrice()) : $dataProduct['id_' $itemProduct->getId()];
  546.             } else {
  547.                 $dataProduct['id_' $itemProduct->getId()] = $item->getBalance() * $itemProduct->getUnitPrice();
  548.             }
  549.         }
  550.         $dataProduct array_merge($originalProducts$dataProduct);
  551.         $maxBalance array_sum(array_values($dataProduct));
  552.         $data[] = [
  553.             'name' => '',
  554.             'y' => $currentBalance,
  555.             'maxBalance' => $maxBalance
  556.         ];
  557.         return $this->json($data);
  558.     }
  559.     /**
  560.      * @return JsonResponse
  561.      *
  562.      * @Route("/dashboard/stock-sales", name="stock-sales", options={"expose" = "true"}, methods={"POST"})
  563.      */
  564.     public function stockSales(Request $request)
  565.     {
  566.         $filter $this->getFilter($request);
  567.         $sales $this->getDoctrine()->getRepository(PriceList::class)->findSaleProducts($filter);
  568.         $stock $this->getDoctrine()->getRepository(Product::class)->findStockSalesByFilter($filter);
  569.         return $this->json(
  570.             TransformData::diffArray($sales$stock)
  571.         );
  572.     }
  573.     /**
  574.      * @return JsonResponse
  575.      *
  576.      * @Route("/dashboard/sale-product-per-practitioner", name="sale-product-per-practitioner", options={"expose" = "true"}, methods={"POST"})
  577.      */
  578.     public function saleProductsPerPractitioner(Request $request)
  579.     {
  580.         $filter $this->getFilter($request);
  581.         return $this->json(
  582.             TransformData::transform(
  583.                 $this->getDoctrine()->getRepository(Invoice::class)->findSaleProductsPerPractitioner($filter)
  584.             )
  585.         );
  586.     }
  587.     /**
  588.      * @return JsonResponse
  589.      *
  590.      * @Route("/dashboard/sale-service-per-practitioner", name="sale-service-per-practitioner", options={"expose" = "true"}, methods={"POST"})
  591.      */
  592.     public function saleServicePerPractitioner(Request $request)
  593.     {
  594.         $filter $this->getFilter($request);
  595.         return $this->json(
  596.             TransformData::transform(
  597.                 $this->getDoctrine()->getRepository(Invoice::class)->findSaleServicesPerPractitioner($filter)
  598.             )
  599.         );
  600.     }
  601.     /**
  602.      * @return JsonResponse
  603.      *
  604.      * @Route("/dashboard/revenue-per-practitioner", name="revenue-per-practitioner", options={"expose" = "true"}, methods={"POST"})
  605.      */
  606.     public function revenuePerPractitioner(Request $request)
  607.     {
  608.         $filter $this->getFilter($request);
  609.         $data $this->getDoctrine()->getRepository(Invoice::class)->findRevenuePerPractitioner($filter);
  610.         $defaultData $this->dashboardService->createDefaultDataPerPractitioner($filter);
  611.         $result = [];
  612.         foreach ($defaultData as $item) {
  613.             $sumInv 0;
  614.             /** @var Invoice $baseInvoice */
  615.             foreach ($data as $baseInvoice) {
  616.                 if ($item['id'] === $baseInvoice->getPractitioner()->getId()) {
  617.                     $sumInv += $baseInvoice->getTotalList() + $baseInvoice->getAmountRefund();
  618.                 }
  619.             }
  620.             $result[] = [
  621.                 'y' => $sumInv,
  622.                 'name' => $item['name'],
  623.                 'color' => $item['color'],
  624.             ];
  625.         }
  626.         return $this->json(
  627.             TransformData::transform($result)
  628.         );
  629.     }
  630.     /**
  631.      * @return JsonResponse
  632.      *
  633.      * @Route("/dashboard/revenue-per-period", name="revenue-per-period", options={"expose" = "true"}, methods={"POST"})
  634.      */
  635.     public function revenuePerPeriod(Request $request)
  636.     {
  637.         $filter $this->getFilter($request);
  638.         $invoices $this->getDoctrine()->getRepository(Invoice::class)->findRevenuePerPractitioner($filter);
  639.         $data = [];
  640.         $invoicesDate $this->dashboardService->createDefaultData($filter);
  641.         $format $this->dashboardService->createFormat($filter);
  642.         /**
  643.          * @var string
  644.          * @var \DateTime $itemValue
  645.          */
  646.         foreach ($invoicesDate as $item => $itemValue) {
  647.             $sumInvoices 0;
  648.             $date $itemValue;
  649.             $name null;
  650.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  651.                 $cloneDate = clone $itemValue;
  652.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  653.             }
  654.             /** @var Invoice $invoice */
  655.             foreach ($invoices as $invoice) {
  656.                 if ($item == $invoice->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  657.                     if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  658.                         $cloneDate = clone $invoice->getCreatedAt();
  659.                         $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  660.                     }
  661.                     $sumInvoices += $invoice->getTotalList() + $invoice->getAmountRefund();
  662.                     $date $invoice->getCreatedAt();
  663.                 }
  664.             }
  665.             $data[] = [
  666.                 'name' => $name $name $item,
  667.                 'y' => $sumInvoices,
  668.                 'date' => $date
  669.             ];
  670.         }
  671.         if ($data) {
  672.             usort($data, function ($a$b) {
  673.                 return ($a['date'] < $b['date']) ? -1;
  674.             });
  675.         }
  676.         return $this->json(TransformData::transform($data));
  677.     }
  678.     /**
  679.      * @return JsonResponse
  680.      *
  681.      * @Route("/dashboard/appointments-per-practitioner", name="appointments-per-practitioner", options={"expose" = "true"}, methods={"POST"})
  682.      */
  683.     public function appointmentsPerPractitioner(Request $request)
  684.     {
  685.         $filter $this->getFilter($request);
  686.         return $this->json(
  687.             TransformData::transform(
  688.                 $this->getDoctrine()->getRepository(GoogleEvent::class)->findAppoitmentsPerPractitionerByFilter($filter)
  689.             )
  690.         );
  691.     }
  692.     /**
  693.      * @return JsonResponse
  694.      *
  695.      * @Route("/dashboard/average-per-practitioner", name="average-per-practitioner", options={"expose" = "true"}, methods={"POST"})
  696.      */
  697.     public function averagePerPractitioner(Request $request)
  698.     {
  699.         $filter $this->getFilter($request);
  700.         return $this->json(
  701.             TransformData::transform(
  702.                 $this->getDoctrine()->getRepository('App:Clinic\Appointment')->findAverageAppoitmentsPerPractitionerByFilter($filter)
  703.             )
  704.         );
  705.     }
  706.     /**
  707.      * @return JsonResponse
  708.      *
  709.      * @Route("/dashboard/commission-per-practitioner", name="commission-per-practitioner", options={"expose" = "true"}, methods={"POST"})
  710.      */
  711.     public function commissionPerPractitioner(Request $request)
  712.     {
  713.         $filter $this->getFilter($request);
  714.         return $this->json(
  715.             TransformData::transform(
  716.                 $this->getDoctrine()->getRepository('App:Patient\Invoice')->findRevenuePerPractitioner($filter0.05)
  717.             )
  718.         );
  719.     }
  720.     /**
  721.      * @return JsonResponse
  722.      *
  723.      * @Route("/dashboard/appointments-by-new-patient", name="appointments-by-new-patient", options={"expose" = "true"}, methods={"POST"})
  724.      */
  725.     public function appointmentsByNewPatient(Request $request)
  726.     {
  727.         $filter $this->getFilter($request);
  728.         return $this->json(
  729.             TransformData::transform(
  730.                 $this->getDoctrine()->getRepository(GoogleEvent::class)->findAppoitmentsPatientsByFilter($filter)
  731.             )
  732.         );
  733.     }
  734.     /**
  735.      * @return JsonResponse
  736.      *
  737.      * @Route("/dashboard/appointments-by-existing-patient", name="appointments-by-existing-patient", options={"expose" = "true"}, methods={"POST"})
  738.      */
  739.     public function appointmentsByExistingPatient(Request $request)
  740.     {
  741.         $filter $this->getFilter($request);
  742.         return $this->json(
  743.             TransformData::transform(
  744.                 $this->getDoctrine()->getRepository(GoogleEvent::class)->findAppoitmentsPatientsByFilter($filterfalse)
  745.             )
  746.         );
  747.     }
  748.     /**
  749.      * @return JsonResponse
  750.      *
  751.      * @Route("/dashboard/spend-by-new-patient", name="spend-by-new-patient", options={"expose" = "true"}, methods={"POST"})
  752.      */
  753.     public function spendByNewPatient(Request $request)
  754.     {
  755.         $filter $this->getFilter($request);
  756.         return $this->json(
  757.             TransformData::transform(
  758.                 $this->getDoctrine()->getRepository('App:Clinic\Appointment')->findSpendPatientsByFilter($filter)
  759.             )
  760.         );
  761.     }
  762.     /**
  763.      * @return JsonResponse
  764.      *
  765.      * @Route("/dashboard/spend-by-existing-patient", name="spend-by-existing-patient", options={"expose" = "true"}, methods={"POST"})
  766.      */
  767.     public function spendByExistingPatient(Request $request)
  768.     {
  769.         $filter $this->getFilter($request);
  770.         return $this->json(
  771.             TransformData::transform(
  772.                 $this->getDoctrine()->getRepository('App:Clinic\Appointment')->findSpendPatientsByFilter($filterfalse)
  773.             )
  774.         );
  775.     }
  776.     /**
  777.      * @return JsonResponse
  778.      *
  779.      * @Route("/dashboard/demand-clinic", name="demand-clinic", options={"expose" = "true"}, methods={"POST"})
  780.      */
  781.     public function demandClinic(Request $request)
  782.     {
  783.         $filter $this->getFilter($request);
  784.         $appointments count($this->getDoctrine()->getRepository('App:Clinic\Appointment')->findBy(['clinic' => $filter->getClinic()]));
  785.         $waitings count($this->getDoctrine()->getRepository('App:Waiting\Item')->findBy(['clinic' => $filter->getClinic()]));
  786.         $leadCaptures count($this->getDoctrine()->getRepository('App:LeadCapture\LeadCapture')->findBy(['clinic' => $filter->getClinic()]));
  787.         return $this->json(
  788.             [
  789.                 [
  790.                     'name' => $filter->getClinic()->getName(),
  791.                     'y' => (float) ($appointments $waitings $leadCaptures),
  792.                 ],
  793.             ]
  794.         );
  795.     }
  796.     /**
  797.      * @return JsonResponse
  798.      *
  799.      * @Route("/dashboard/average-spend-patients", name="average-spend-patients", options={"expose" = "true"}, methods={"POST"})
  800.      */
  801.     public function averageSpendPatients(Request $request)
  802.     {
  803.         $filter $this->getFilter($request);
  804.         $start $filter->getDateStart();
  805.         $end $filter->getDateEnd();
  806.         $filter->setNameReport(Setting::AVERAGE_SPEND_PER_PATIENT);
  807.         //        $invoices = $this->getDoctrine()->getRepository(Invoice::class)->findInvoicesAverageSpendPatients($filter);
  808.         $invoices $this->getDoctrine()->getRepository(BaseInvoice::class)->selectInvoicesDeatilPage($filter)->getResult();
  809.         $data = [];
  810.         $format $this->dashboardService->createFormat($filter);
  811.         $dateInvoices $this->dashboardService->createDefaultData($filter);
  812.         /**
  813.          * @var string
  814.          * @var \DateTime $itemValue
  815.          */
  816.         foreach ($dateInvoices as $item => $itemValue) {
  817.             $sumInvoices 0;
  818.             $date $itemValue;
  819.             $startFilter $start;
  820.             $endFilter $end;
  821.             $name null;
  822.             $patients = [];
  823.             $countPatientsAppointment 0;
  824.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  825.                 $cloneDate = clone $itemValue;
  826.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  827.             }
  828.             if ($invoices) {
  829.                 /** @var BaseInvoice $invoice */
  830.                 foreach ($invoices as $invoice) {
  831.                     if ($invoice instanceof Prepay) {
  832.                         if ($item == $invoice->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  833.                             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  834.                                 $cloneDate = clone $invoice->getCreatedAt();
  835.                                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  836.                             }
  837.                             $sumInvoices += $invoice->getAmount();
  838.                             $date $invoice->getCreatedAt();
  839.                             $patients[] = $invoice->getPatient()->getId();
  840.                         }
  841.                     }
  842.                     if ($invoice instanceof Invoice) {
  843.                         if ($item == $invoice->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  844.                             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  845.                                 $cloneDate = clone $invoice->getCreatedAt();
  846.                                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  847.                             }
  848.                             $sumInvoices += $invoice->getTotalList();
  849.                             $date $invoice->getCreatedAt();
  850.                             $patients[] = $invoice->getPatient()->getId();
  851.                         }
  852.                     }
  853.                 }
  854.                 $countPatientsAppointment count(array_unique($patients));
  855.             }
  856.             $data[] = [
  857.                 'name' => $name $name $item,
  858.                 'y' => (isset($countPatientsAppointment) && $countPatientsAppointment) ? $sumInvoices $countPatientsAppointment 0,
  859.                 'date' => $date
  860.             ];
  861.         }
  862.         if ($data) {
  863.             usort($data, function ($a$b) {
  864.                 return ($a['date'] < $b['date']) ? -1;
  865.             });
  866.         }
  867.         return $this->json(TransformData::transform($data));
  868.     }
  869.     /**
  870.      * @param Request $request
  871.      * @return JsonResponse
  872.      *
  873.      * @throws \Exception
  874.      * @Route("/dashboard/birthday-patient", name="birthday-patient", options={"expose" = "true"}, methods={"POST"})
  875.      */
  876.     public function birthdayPatient(Request $request)
  877.     {
  878.         $filter $this->getFilter($request);
  879.         $filter->setDateStart(new \DateTime('first day of this month'));
  880.         $filter->setDateEnd(new \DateTime('last day of this month'));
  881.         return $this->json(
  882.             $this->getDoctrine()->getRepository('App:Person\Patient')->findBirthdayCurrentMonth($filter)
  883.         );
  884.     }
  885.     /**
  886.      * @return JsonResponse
  887.      *
  888.      * @Route("/dashboard/last-appointment", name="last_appointment", options={"expose" = "true"}, methods={"POST"})
  889.      */
  890.     public function lastAppointment(Request $request)
  891.     {
  892.         $filter $this->getFilter($request);
  893.         $events $this->getDoctrine()->getRepository(GoogleEvent::class)->selectLastAppointments($filter);
  894.         return $this->json(TransformData::transformLastAppointmentData($events->getQuery()->getResult()));
  895.     }
  896.     /**
  897.      * @return JsonResponse
  898.      *
  899.      * @Route("/dashboard/top-patient-revenue", name="top-patient-revenue", options={"expose" = "true"}, methods={"POST"})
  900.      */
  901.     public function topPatientsRevenue(Request $request)
  902.     {
  903.         $filter $this->getFilter($request);
  904.         return $this->json(
  905.             $this->getDoctrine()->getRepository('App:Patient\Payment')->findTopPatientsByFilter($filter)
  906.         );
  907.     }
  908.     /**
  909.      * @return JsonResponse
  910.      *
  911.      * @Route("/dashboard/number-appointments", name="number-appointments", options={"expose" = "true"}, methods={"POST"})
  912.      */
  913.     public function numberAppointments(Request $request)
  914.     {
  915.         $filter $this->getFilter($request);
  916.         $events $this->getDoctrine()->getRepository(GoogleEvent::class)->findNumberAppointments($filter);
  917.         $data = [];
  918.         $format $this->dashboardService->createFormat($filter);
  919.         $dataPeriod $this->dashboardService->createDefaultData($filter);
  920.         /**
  921.          * @var string
  922.          * @var \DateTime $dateValue
  923.          */
  924.         foreach ($dataPeriod as $dateItem => $dateValue) {
  925.             $count 0;
  926.             $date $dateValue;
  927.             $name null;
  928.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  929.                 $cloneDate = clone $dateValue;
  930.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  931.             }
  932.             /** @var GoogleEvent $event */
  933.             foreach ($events as $event) {
  934.                 if ($dateItem == $event->getStart()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  935.                     if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  936.                         $cloneDate = clone $event->getStart();
  937.                         $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  938.                     }
  939.                     ++$count;
  940.                     $date $event->getStart();
  941.                 }
  942.             }
  943.             $data[] = [
  944.                 'y' => $count,
  945.                 'name' => $name $name $dateItem,
  946.                 'date' => $date
  947.             ];
  948.         }
  949.         if ($data) {
  950.             usort($data, function ($a$b) {
  951.                 return ($a['date'] < $b['date']) ? -1;
  952.             });
  953.         }
  954.         return $this->json(TransformData::transform($data));
  955.     }
  956.     /**
  957.      * @return JsonResponse
  958.      *
  959.      * @Route("/dashboard/number-paying-appointments", name="number-paying-appointments", options={"expose" = "true"}, methods={"POST"})
  960.      */
  961.     public function numberPayingAppointments(Request $request)
  962.     {
  963.         $filter $this->getFilter($request);
  964.         return $this->json(
  965.             TransformData::transform(
  966.                 $this->getDoctrine()->getRepository(GoogleEvent::class)->findNumberAppointments($filterAppointment::STATUS_CONFIRMED)
  967.             )
  968.         );
  969.     }
  970.     /**
  971.      * @return JsonResponse
  972.      *
  973.      * @Route("/dashboard/number-rebooked-appointments", name="number-rebooked-appointments", options={"expose" = "true"}, methods={"POST"})
  974.      */
  975.     public function numberRebookedAppointments(Request $request)
  976.     {
  977.         $filter $this->getFilter($request);
  978.         return $this->json(
  979.             TransformData::transform(
  980.                 $this->getDoctrine()->getRepository(GoogleEvent::class)->findRebookedAppointmentsByFilter($filter)
  981.             )
  982.         );
  983.     }
  984.     /**
  985.      * @return JsonResponse
  986.      *
  987.      * @Route("/dashboard/number-cancellations-appointments", name="number-cancellations-appointments", options={"expose" = "true"}, methods={"POST"})
  988.      */
  989.     public function numberCancellationsAppointments(Request $request)
  990.     {
  991.         $filter $this->getFilter($request);
  992.         $events $this->getDoctrine()->getRepository(GoogleEvent::class)->findCancelledAppointments($filter);
  993.         $data = [];
  994.         $format $this->dashboardService->createFormat($filter);
  995.         $dataPeriod $this->dashboardService->createDefaultData($filter);
  996.         /**
  997.          * @var string
  998.          * @var \DateTime $dateValue
  999.          */
  1000.         foreach ($dataPeriod as $dateItem => $dateValue) {
  1001.             $count 0;
  1002.             $date $dateValue;
  1003.             $name null;
  1004.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1005.                 $cloneDate = clone $dateValue;
  1006.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1007.             }
  1008.             /** @var GoogleEvent $event */
  1009.             foreach ($events as $event) {
  1010.                 if ($dateItem == $event->getStart()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  1011.                     if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1012.                         $cloneDate = clone $event->getStart();
  1013.                         $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1014.                     }
  1015.                     ++$count;
  1016.                     $date $event->getStart();
  1017.                 }
  1018.             }
  1019.             $data[] = [
  1020.                 'y' => $count,
  1021.                 'name' => $name $name $dateItem,
  1022.                 'date' => $date
  1023.             ];
  1024.         }
  1025.         if ($data) {
  1026.             usort($data, function ($a$b) {
  1027.                 return ($a['date'] < $b['date']) ? -1;
  1028.             });
  1029.         }
  1030.         return $this->json(TransformData::transform($data));
  1031.     }
  1032.     /**
  1033.      * @return JsonResponse
  1034.      *
  1035.      * @Route("/dashboard/conversion-appointments", name="conversion-appointments", options={"expose" = "true"}, methods={"POST"})
  1036.      */
  1037.     public function conversionAppointments(Request $request)
  1038.     {
  1039.         $filter $this->getFilter($request);
  1040.         $filter->setNameReport(Setting::CONVERSION_APPOINTMENTS_NEW_PATIENT);
  1041.         $events $this->getDoctrine()->getRepository(GoogleEvent::class)->selectEventsDetailPage($filter)->getResult();
  1042.         $data = [];
  1043.         $format $this->dashboardService->createFormat($filter);
  1044.         $dataPeriod $this->dashboardService->createDefaultData($filter);
  1045.         /**
  1046.          * @var string
  1047.          * @var \DateTime $value
  1048.          */
  1049.         foreach ($dataPeriod as $item => $value) {
  1050.             $count 0;
  1051.             $countInv 0;
  1052.             $date $value;
  1053.             $name null;
  1054.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1055.                 $cloneDate = clone $value;
  1056.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1057.             }
  1058.             /** @var GoogleEvent $event */
  1059.             foreach ($events as $event) {
  1060.                 if ($item == $event->getStart()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format) && $event->getAppointment()->getPatient()) {
  1061.                     if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1062.                         $cloneDate = clone $event->getStart();
  1063.                         $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1064.                     }
  1065.                     $invoices $this->getDoctrine()->getRepository(Invoice::class)->findInvoicesByEvent($event);
  1066.                     $countInv += count($invoices) >= 0;
  1067.                     ++$count;
  1068.                     $date $event->getStart();
  1069.                 }
  1070.             }
  1071.             $data[] = [
  1072.                 'y' => $count ? ($countInv $count) * 100 0,
  1073.                 'name' => $name $name $value,
  1074.                 'date' => $date
  1075.             ];
  1076.         }
  1077.         if ($data) {
  1078.             usort($data, function ($a$b) {
  1079.                 return ($a['date'] < $b['date']) ? -1;
  1080.             });
  1081.         }
  1082.         return $this->json(TransformData::transform($data));
  1083.     }
  1084.     /**
  1085.      * @return JsonResponse
  1086.      *
  1087.      * @Route("/dashboard/refunds-clinic", name="refunds-clinic", options={"expose" = "true"}, methods={"POST"})
  1088.      */
  1089.     public function refundsClinic(Request $request)
  1090.     {
  1091.         $filter $this->getFilter($request);
  1092.         $refunds $this->getDoctrine()->getRepository(Refund::class)->findRefundsClinicByFilter($filter);
  1093.         $data = [];
  1094.         $result = [];
  1095.         $resultData = [];
  1096.         $categories = [];
  1097.         $format $this->dashboardService->createFormat($filter);
  1098.         $dataPeriod $this->dashboardService->createDefaultData($filter);
  1099.         /**
  1100.          * @var string
  1101.          * @var \DateTime $itemValue
  1102.          */
  1103.         foreach ($dataPeriod as $item => $itemValue) {
  1104.             $date null;
  1105.             $name null;
  1106.             $arrSomeDate = [];
  1107.             $i 1;
  1108.             if (!$refunds) {
  1109.                 if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1110.                     $cloneDate = clone $itemValue;
  1111.                     $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1112.                 }
  1113.                 $arrSomeDate[$item '_Number'] = 0;
  1114.                 $arrSomeDate[$item '_Value'] = 0;
  1115.                 $date $itemValue;
  1116.             }
  1117.             /** @var Refund $refund */
  1118.             foreach ($refunds as $refund) {
  1119.                 if ($item == $refund->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  1120.                     if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1121.                         $cloneDate = clone $refund->getCreatedAt();
  1122.                         $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1123.                     }
  1124.                     if (array_key_exists($item '_Value'$arrSomeDate)) {
  1125.                         $value $arrSomeDate[$item '_Value'];
  1126.                         $value += (float) $refund->getTotal() * (-1);
  1127.                         $arrSomeDate[$item '_Value'] = $value;
  1128.                     } else {
  1129.                         $arrSomeDate[$item '_Value'] = (float) $refund->getTotal() * (-1);
  1130.                     }
  1131.                     if (array_key_exists($item '_Number'$arrSomeDate)) {
  1132.                         $arrSomeDate[$item '_Number'] = $i++;
  1133.                     } else {
  1134.                         $arrSomeDate[$item '_Number'] = $i++;
  1135.                     }
  1136.                     $date $refund->getCreatedAt();
  1137.                 } else {
  1138.                     if (!array_key_exists($item '_Number'$arrSomeDate) && !array_key_exists($item '_Value'$arrSomeDate)) {
  1139.                         if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1140.                             $cloneDate = clone $itemValue;
  1141.                             $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1142.                         }
  1143.                         $arrSomeDate[$item '_Number'] = 0;
  1144.                         $arrSomeDate[$item '_Value'] = 0;
  1145.                         $date $itemValue;
  1146.                     }
  1147.                 }
  1148.             }
  1149.             $data[] = [
  1150.                 'categories' => $name $name $item,
  1151.                 'data' => $arrSomeDate,
  1152.                 'date' => $date
  1153.             ];
  1154.         }
  1155.         if ($data) {
  1156.             usort($data, function ($a$b) {
  1157.                 return ($a['date'] < $b['date']) ? -1;
  1158.             });
  1159.             $ars = [];
  1160.             foreach ($data as $item) {
  1161.                 foreach ($item['data'] as $key => $value) {
  1162.                     if (array_key_exists($key substr(stristr($key'_'), 1), $ars)) {
  1163.                         $ars[$key][] = $value;
  1164.                     } else {
  1165.                         $ars[$key] = [$value];
  1166.                     }
  1167.                 }
  1168.                 $resultData['data'] = $ars;
  1169.             }
  1170.             foreach ($resultData['data'] as $key => $value) {
  1171.                 $arr = [];
  1172.                 $arr['name'] = $key;
  1173.                 $arr['data'] = $value;
  1174.                 if ('Value' == $key) {
  1175.                     $arr['type'] = 'column';
  1176.                     $arr['yAxis'] = 1;
  1177.                 } else {
  1178.                     $arr['type'] = 'spline';
  1179.                 }
  1180.                 $result['data'][] = $arr;
  1181.             }
  1182.             foreach ($data as $item) {
  1183.                 $categories[] = $item['categories'];
  1184.             }
  1185.             $result['categories'] = $categories;
  1186.         }
  1187.         return $this->json($result);
  1188.     }
  1189.     /**
  1190.      * @return JsonResponse
  1191.      *
  1192.      * @Route("/dashboard/retention-clinic", name="retention-clinic", options={"expose" = "true"}, methods={"POST"})
  1193.      */
  1194.     public function retentionClinic(Request $request)
  1195.     {
  1196.         $filter $this->getFilter($request);
  1197.         $allPatients $this->getDoctrine()->getRepository(Patient::class)->findAllPatientsByFilter($filter);
  1198.         $allPatientsAppointments $this->getDoctrine()->getRepository(Patient::class)->findAllPatientsAppointmentsByFilter($filter);
  1199.         $allPatients $allPatients ? (float) $allPatients 0;
  1200.         $allPatientsAppointments $allPatientsAppointments ? (float) $allPatientsAppointments 0;
  1201.         $allPatientsWithoutAppointments $allPatients $allPatientsAppointments;
  1202.         $data = [
  1203.             ["Customers whom existed 12m before period not visiting in selected period - $allPatientsWithoutAppointments patient(s)"$allPatientsWithoutAppointments],
  1204.             ["Customers whom existed 12m before period visiting during selected period - $allPatientsAppointments patient(s)"$allPatientsAppointments]
  1205.         ];
  1206.         return $this->json($data);
  1207.     }
  1208.     /**
  1209.      * @return JsonResponse
  1210.      *
  1211.      * @Route("/dashboard/frequency-of-visit", name="frequency-of-visit", options={"expose" = "true"}, methods={"POST"})
  1212.      */
  1213.     public function frequencyOfVisit(Request $request)
  1214.     {
  1215.         $filter $this->getFilter($request);
  1216.         //        $filter->setViewType(DashboardFilter::VIEW_TYPE_MONTH);
  1217.         $events $this->getDoctrine()->getRepository(GoogleEvent::class)->findFrequencyOfVisitByFilter($filter);
  1218.         $data = [];
  1219.         $dateAppointments $this->dashboardService->createDefaultData($filter);
  1220.         $format $this->dashboardService->createFormat($filter);
  1221.         /**
  1222.          * @var string
  1223.          * @var \DateTime $dateValue
  1224.          */
  1225.         foreach ($dateAppointments as $dateItem => $dateValue) {
  1226.             $patients = [];
  1227.             $sumPatients 0;
  1228.             $countPatients 1;
  1229.             $date $dateValue;
  1230.             $name null;
  1231.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1232.                 $cloneDate = clone $dateValue;
  1233.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1234.             }
  1235.             /** @var GoogleEvent $event */
  1236.             foreach ($events as $event) {
  1237.                 if ($dateItem == $event->getStart()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  1238.                     if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1239.                         $cloneDate = clone $event->getStart();
  1240.                         $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1241.                     }
  1242.                     $patients[] = $event->getAppointment()->getPatient()->getId();
  1243.                     $date $event->getStart();
  1244.                 }
  1245.             }
  1246.             if ($patients) {
  1247.                 $countValuesPatients array_count_values($patients);
  1248.                 $sumPatients array_sum($countValuesPatients);
  1249.                 $countPatients count($countValuesPatients);
  1250.             }
  1251.             $data[] = [
  1252.                 'y' => $sumPatients $countPatients,
  1253.                 'name' => $name $name $dateItem,
  1254.                 'date' => $date
  1255.             ];
  1256.         }
  1257.         if ($data) {
  1258.             usort($data, function ($a$b) {
  1259.                 return ($a['date'] < $b['date']) ? -1;
  1260.             });
  1261.         }
  1262.         return $this->json(TransformData::transform($data));
  1263.     }
  1264.     /**
  1265.      * @return JsonResponse
  1266.      *
  1267.      * @Route("/dashboard/base-of-visit", name="base-of-visit", options={"expose" = "true"}, methods={"POST"})
  1268.      */
  1269.     public function baseOfVisit(Request $request)
  1270.     {
  1271.         $filter $this->getFilter($request);
  1272.         return $this->json(
  1273.             TransformData::transformBasePeriodData(
  1274.                 $this->getDoctrine()->getRepository(Patient::class)->findBaseOfVisitByFilter($filter)
  1275.             )
  1276.         );
  1277.     }
  1278.     /**
  1279.      * @return JsonResponse
  1280.      *
  1281.      * @Route("/dashboard/list-patient-treatment-date", name="list-patient-treatment-date", options={"expose" = "true"}, methods={"POST"})
  1282.      */
  1283.     public function listPatientTreatmentDate(Request $request)
  1284.     {
  1285.         $filter $this->getFilter($request);
  1286.         return $this->json(
  1287.             $this->getDoctrine()->getRepository(GoogleEvent::class)->findPatientTreatmentDate($filter)
  1288.         );
  1289.     }
  1290.     /**
  1291.      * @return JsonResponse
  1292.      *
  1293.      * @Route("/dashboard/list-patient-practitioner-bouncing", name="list-patient-practitioner-bouncing", options={"expose" = "true"}, methods={"POST"})
  1294.      */
  1295.     public function listPatientPractitionerBouncing(Request $request)
  1296.     {
  1297.         $filter $this->getFilter($request);
  1298.         return $this->json(
  1299.             $this->getDoctrine()->getRepository('App:Clinic\Appointment')->findPatientPractitionerBouncing($filter)
  1300.         );
  1301.     }
  1302.     /**
  1303.      * @return JsonResponse
  1304.      *
  1305.      * @Route("/dashboard/recency-of-visit", name="recency-of-visit", options={"expose" = "true"}, methods={"POST"})
  1306.      */
  1307.     public function recency(Request $request)
  1308.     {
  1309.         $filter $this->getFilter($request);
  1310.         $events $this->getDoctrine()->getRepository(GoogleEvent::class)->findEventsByFilter($filter);
  1311.         $data = [];
  1312.         $resultData = [];
  1313.         $patients = [];
  1314.         $arrMonth = [];
  1315.         $defaultDataPeriod $this->dashboardService->createDefaultData($filter);
  1316.         $format $this->dashboardService->createFormat($filter);
  1317.         /** @var GoogleEvent $event */
  1318.         foreach ($events as $event) {
  1319.             $nameWeek null;
  1320.             if (!in_array([$event->getStart()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format) => $event->getAppointment()->getPatient()->getId()], $patients)) {
  1321.                 $patients[] = [$event->getStart()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format) => $event->getAppointment()->getPatient()->getId()];
  1322.                 /** @var GoogleEvent $prevEvent */
  1323.                 $prevEvent $this->getDoctrine()->getRepository(GoogleEvent::class)->findPrevLastVisitByFilter($event);
  1324.                 if ($prevEvent) {
  1325.                     $startLastVisit $event->getStart();
  1326.                     $startPrevVisit $prevEvent->getStart();
  1327.                     $interval $startLastVisit->diff($startPrevVisit)->format('%a');
  1328.                     if (== $interval) {
  1329.                         $dayLast $startLastVisit->format('d');
  1330.                         $dayPrev $startPrevVisit->format('d');
  1331.                         $interval $dayLast $dayPrev;
  1332.                     }
  1333.                     if (!in_array($startLastVisit->format($format), $arrMonth)) {
  1334.                         $arrMonth[] = $startLastVisit->format($format);
  1335.                     }
  1336.                     if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1337.                         /** @var \DateTime $cloneDate */
  1338.                         $cloneDate = clone $startLastVisit;
  1339.                         $cloneDate $cloneDate->modify('monday this week');
  1340.                         $nameWeek $cloneDate->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1341.                     }
  1342.                     $data[] = [
  1343.                         'y' => $interval,
  1344.                         'name' => $startLastVisit->format($format),
  1345.                         'date' => $startLastVisit,
  1346.                         'nameWeek' => $nameWeek
  1347.                     ];
  1348.                 }
  1349.             }
  1350.         }
  1351.         /**
  1352.          * @var string
  1353.          * @var \DateTime $monthDate
  1354.          */
  1355.         foreach ($defaultDataPeriod as $month => $monthDate) {
  1356.             $y 0;
  1357.             $count 0;
  1358.             $name '';
  1359.             $date null;
  1360.             $nameWeek null;
  1361.             if (!$data) {
  1362.                 if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1363.                     $cloneDate = clone $monthDate;
  1364.                     $cloneDate $cloneDate->modify('monday this week');
  1365.                     $nameWeek $cloneDate->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1366.                 }
  1367.                 $y 0;
  1368.                 $count 1;
  1369.                 $name $nameWeek $nameWeek $month;
  1370.                 $date $monthDate;
  1371.             }
  1372.             foreach ($data as $item) {
  1373.                 if ($item['name'] == $month) {
  1374.                     $y += $item['y'];
  1375.                     ++$count;
  1376.                     $name $item['nameWeek'] ? $item['nameWeek'] : $item['name'];
  1377.                     $date $item['date'];
  1378.                 } else {
  1379.                     if (!in_array($month$arrMonth)) {
  1380.                         if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1381.                             $cloneDate = clone $monthDate;
  1382.                             $cloneDate $cloneDate->modify('monday this week');
  1383.                             $nameWeek $cloneDate->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1384.                         }
  1385.                         $y 0;
  1386.                         $count 1;
  1387.                         $name $nameWeek $nameWeek $month;
  1388.                         $date $monthDate;
  1389.                     }
  1390.                 }
  1391.             }
  1392.             $resultData[] = [
  1393.                 'y' => $y $count,
  1394.                 'name' => $name,
  1395.                 'date' => $date
  1396.             ];
  1397.         }
  1398.         if ($resultData) {
  1399.             usort($resultData, function ($a$b) {
  1400.                 return ($a['date'] < $b['date']) ? -1;
  1401.             });
  1402.         }
  1403.         return $this->json(
  1404.             TransformData::transform($resultData)
  1405.         );
  1406.     }
  1407.     /**
  1408.      * @Route("/dashboard/treatments-per-practitioner", name="treatments-per-practitioner", options={"expose" = "true"}, methods={"POST"})
  1409.      */
  1410.     public function treatmentsPerPractitioner(Request $request)
  1411.     {
  1412.         $filter $this->getFilter($request);
  1413.         $data $this->getDoctrine()->getRepository(BaseInvoice::class)->selectInvoicesDeatilPage($filter)->getResult();
  1414.         $defaultData $this->dashboardService->createDefaultDataPerPractitioner($filter);
  1415.         $result = [];
  1416.         foreach ($defaultData as $item) {
  1417.             $sumInv 0;
  1418.             /** @var BaseInvoice $baseInvoice */
  1419.             foreach ($data as $baseInvoice) {
  1420.                 if ($item['id'] === $baseInvoice->getPractitioner()->getId()) {
  1421.                     if ($baseInvoice instanceof Invoice) {
  1422.                         $sumInv += $baseInvoice->getTotalList() - $baseInvoice->getAmountPrepay() + $baseInvoice->getAmountRefund();
  1423.                     }
  1424.                     if ($baseInvoice instanceof Prepay) {
  1425.                         $sumInv += $baseInvoice->getAmount();
  1426.                     }
  1427.                 }
  1428.             }
  1429.             $result[] = [
  1430.                 'y' => $sumInv,
  1431.                 'name' => $item['name'],
  1432.                 'color' => $item['color'],
  1433.             ];
  1434.         }
  1435.         return $this->json(
  1436.             TransformData::transform($result)
  1437.         );
  1438.     }
  1439.     /**
  1440.      * @Route("/dashboard/treatments-per-period", name="treatments-per-period", options={"expose" = "true"}, methods={"POST"})
  1441.      */
  1442.     public function treatmentsPerPeriod(Request $request)
  1443.     {
  1444.         $filter $this->getFilter($request);
  1445.         $invoices $this->getDoctrine()->getRepository(BaseInvoice::class)->selectInvoicesDeatilPage($filter)->getResult();
  1446.         $data = [];
  1447.         $invoicesDate $this->dashboardService->createDefaultData($filter);
  1448.         $format $this->dashboardService->createFormat($filter);
  1449.         /**
  1450.          * @var string
  1451.          * @var \DateTime $itemValue
  1452.          */
  1453.         foreach ($invoicesDate as $item => $itemValue) {
  1454.             $sumInvoices 0;
  1455.             $date $itemValue;
  1456.             $name null;
  1457.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1458.                 $cloneDate = clone $itemValue;
  1459.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1460.             }
  1461.             /** @var BaseInvoice $invoice */
  1462.             foreach ($invoices as $invoice) {
  1463.                 if ($item == $invoice->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  1464.                     if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1465.                         $cloneDate = clone $invoice->getCreatedAt();
  1466.                         $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1467.                     }
  1468.                     if ($invoice instanceof Invoice) {
  1469.                         $sumInvoices += $invoice->getTotalList() - $invoice->getAmountPrepay();
  1470.                     }
  1471.                     if ($invoice instanceof Prepay) {
  1472.                         $sumInvoices += $invoice->getAmount();
  1473.                     }
  1474.                     $date $invoice->getCreatedAt();
  1475.                 }
  1476.             }
  1477.             $data[] = [
  1478.                 'name' => $name $name $item,
  1479.                 'y' => $sumInvoices,
  1480.                 'date' => $date
  1481.             ];
  1482.         }
  1483.         if ($data) {
  1484.             usort($data, function ($a$b) {
  1485.                 return ($a['date'] < $b['date']) ? -1;
  1486.             });
  1487.         }
  1488.         return $this->json(TransformData::transform($data));
  1489.     }
  1490.     /**
  1491.      * @Route("/dashboard/billings-per-coordinator", name="billings-per-coordinator", options={"expose" = "true"}, methods={"POST"})
  1492.      */
  1493.     public function billingsPerCoordinator(Request $request)
  1494.     {
  1495.         $filter $this->getFilter($request);
  1496.         $filter->setNameReport(Setting::BILLINGS_PER_COORDINATOR);
  1497.         $data $this->getDoctrine()->getRepository(Invoice::class)->selectInvoicesDeatilPage($filter)->getResult();
  1498.         $defaultData $this->dashboardService->createDefaultDataPerPractitioner($filter);
  1499.         $result = [];
  1500.         foreach ($defaultData as $item) {
  1501.             $sumInv 0;
  1502.             /** @var Invoice $baseInvoice */
  1503.             foreach ($data as $baseInvoice) {
  1504.                 if ($baseInvoice->getConsultationPractitioner() && $item['id'] === $baseInvoice->getConsultationPractitioner()->getId()) {
  1505.                     $sumInv += $baseInvoice->getTotalList() - $baseInvoice->getAmountPrepay() + $baseInvoice->getAmountRefund();
  1506.                 }
  1507.             }
  1508.             $result[] = [
  1509.                 'y' => $sumInv,
  1510.                 'name' => $item['name'],
  1511.                 'color' => $item['color'],
  1512.             ];
  1513.         }
  1514.         return $this->json(
  1515.             TransformData::transform($result)
  1516.         );
  1517.     }
  1518.     /**
  1519.      * @Route("/dashboard/vouchers", name="vouchers", options={"expose" = "true"}, methods={"POST"})
  1520.      */
  1521.     public function vouchers(Request $request)
  1522.     {
  1523.         $filter $this->getFilter($request);
  1524.         $vouchers $this->getDoctrine()->getRepository(GiftVoucher::class)->selectVouchersDetailPage($filter)->getResult();
  1525.         $data = [];
  1526.         $vouchersDate $this->dashboardService->createDefaultData($filter);
  1527.         $format $this->dashboardService->createFormat($filter);
  1528.         /**
  1529.          * @var string
  1530.          * @var \DateTime $itemValue
  1531.          */
  1532.         foreach ($vouchersDate as $item => $itemValue) {
  1533.             $sumVouchers 0;
  1534.             $date $itemValue;
  1535.             $name null;
  1536.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1537.                 $cloneDate = clone $itemValue;
  1538.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1539.             }
  1540.             /** @var GiftVoucher $voucher */
  1541.             foreach ($vouchers as $voucher) {
  1542.                 if ($item == $voucher->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  1543.                     if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1544.                         $cloneDate = clone $voucher->getCreatedAt();
  1545.                         $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1546.                     }
  1547.                     $sumVouchers += $voucher->getAmount();
  1548.                     $date $voucher->getCreatedAt();
  1549.                 }
  1550.             }
  1551.             $data[] = [
  1552.                 'name' => $name $name $item,
  1553.                 'y' => $sumVouchers,
  1554.                 'date' => $date
  1555.             ];
  1556.         }
  1557.         if ($data) {
  1558.             usort($data, function ($a$b) {
  1559.                 return ($a['date'] < $b['date']) ? -1;
  1560.             });
  1561.         }
  1562.         return $this->json(TransformData::transform($data));
  1563.     }
  1564.     /**
  1565.      * @Route("/dashboard/treatments-interested-in", name="treatments-interested-in", options={"expose" = "true"}, methods={"POST"})
  1566.      */
  1567.     public function treatmentsInterestedIn(Request $request)
  1568.     {
  1569.         $filter $this->getFilter($request);
  1570.         return $this->json(
  1571.             TransformData::transformTreatmentsInterestedIn(
  1572.                 $this->getDoctrine()->getRepository(TreatmentClinic::class)->findPatientsTreatmentsInterestedIn($filter)
  1573.             )
  1574.         );
  1575.     }
  1576.     /**
  1577.      * @Route("/dashboard/conversion-prospects", name="conversion-prospects", options={"expose" = "true"}, methods={"POST"})
  1578.      */
  1579.     public function conversionProspects(Request $request)
  1580.     {
  1581.         $filter $this->getFilter($request);
  1582.         return $this->json(
  1583.             TransformData::transformConvertProspectData(
  1584.                 $this->getDoctrine()->getRepository(LeadCapture::class)->findCoversionProspects($filter)
  1585.             )
  1586.         );
  1587.     }
  1588.     /**
  1589.      * @Route("/dashboard/mailing-list", name="mailing-list", options={"expose" = "true"}, methods={"POST"})
  1590.      */
  1591.     public function mailingList(Request $request)
  1592.     {
  1593.         $filter $this->getFilter($request);
  1594.         return $this->json(
  1595.             $this->getDoctrine()->getRepository(Patient::class)->findMailingListByFilter($filter)
  1596.         );
  1597.     }
  1598.     /**
  1599.      * @Route("/dashboard/prepayments-balance", name="prepayments-balance", options={"expose" = "true"}, methods={"POST"})
  1600.      */
  1601.     public function prepaymentsBalance(Request $request)
  1602.     {
  1603.         $filter $this->getFilter($request);
  1604.         return $this->json(
  1605.             $this->getDoctrine()->getRepository(Prepay::class)->findPrepayDashboard($filter)
  1606.         );
  1607.     }
  1608.     /**
  1609.      * @Route("/dashboard/reconciliation", name="reconciliation", options={"expose" = "true"}, methods={"POST"})
  1610.      */
  1611.     public function reconciliation(Request $request)
  1612.     {
  1613.         $filter $this->getFilter($request);
  1614.         self::setEntityManager($this->getDoctrine());
  1615.         return $this->json(
  1616.             self::getReconciliationData($filter)
  1617.         );
  1618.     }
  1619.     /**
  1620.      * @Route("/dashboard/unpaid-report", name="unpaid-report", options={"expose" = "true"}, methods={"POST"})
  1621.      */
  1622.     public function unpaidReport(Request $request)
  1623.     {
  1624.         $filter $this->getFilter($request);
  1625.         $filter->setNameReport(Setting::UNPAID_REPORT);
  1626.         $invoices $this->getDoctrine()->getRepository(Invoice::class)->selectInvoices($filter)->getQuery()->getResult();
  1627.         $data = [];
  1628.         $invoicesDate $this->dashboardService->createDefaultData($filter);
  1629.         $format $this->dashboardService->createFormat($filter);
  1630.         /**
  1631.          * @var string
  1632.          * @var \DateTime $itemValue
  1633.          */
  1634.         foreach ($invoicesDate as $item => $itemValue) {
  1635.             $sumInvoices 0;
  1636.             $date $itemValue;
  1637.             $name null;
  1638.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1639.                 $cloneDate = clone $itemValue;
  1640.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1641.             }
  1642.             /** @var Invoice $invoice */
  1643.             foreach ($invoices as $invoice) {
  1644.                 if ($item == $invoice->getCreatedAt()->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  1645.                     if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1646.                         $cloneDate = clone $invoice->getCreatedAt();
  1647.                         $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1648.                     }
  1649.                     $sumInvoices += $invoice->getDue();
  1650.                     $date $invoice->getCreatedAt();
  1651.                 }
  1652.             }
  1653.             $data[] = [
  1654.                 'name' => $name $name $item,
  1655.                 'y' => $sumInvoices,
  1656.                 'date' => $date
  1657.             ];
  1658.         }
  1659.         if ($data) {
  1660.             usort($data, function ($a$b) {
  1661.                 return ($a['date'] < $b['date']) ? -1;
  1662.             });
  1663.         }
  1664.         return $this->json(TransformData::transform($data));
  1665.     }
  1666.     /**
  1667.      * @Route("/dashboard/sms-messages", name="sms-messages", options={"expose" = "true"}, methods={"POST"})
  1668.      */
  1669.     public function smsMessages(Request $requestTwilio $twilio)
  1670.     {
  1671.         $filter $this->getFilter($request);
  1672.         $mesDate $this->dashboardService->createDefaultData($filter);
  1673.         $format $this->dashboardService->createFormat($filter);
  1674.         $data = [];
  1675.         $messages $twilio->getStatusesByFilter($filter);
  1676.         /**
  1677.          * @var string
  1678.          * @var \DateTime $itemValue
  1679.          */
  1680.         foreach ($mesDate as $item => $itemValue) {
  1681.             $sumMes 0;
  1682.             $sumTotal 0;
  1683.             $date $itemValue;
  1684.             $name null;
  1685.             if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1686.                 $cloneDate = clone $itemValue;
  1687.                 $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1688.             }
  1689.             foreach ($messages as $itemMes) {
  1690.                 /** @var MessageInstance $message */
  1691.                 foreach ($itemMes as $message) {
  1692.                     if ($item == $message->dateSent->setTimezone(new \DateTimeZone($this->getParameter('google_calendar_default_timezone')))->format($format)) {
  1693.                         if (DashboardFilter::VIEW_TYPE_WEEK == $filter->getViewType()) {
  1694.                             $cloneDate = clone $message->dateSent;
  1695.                             $name $cloneDate->modify('monday this week')->format(DashboardFilter::FORMAT_WEEK_FOR_NAME);
  1696.                         }
  1697.                         if ('delivered' === $message->status) {
  1698.                             ++$sumMes;
  1699.                         }
  1700.                         ++$sumTotal;
  1701.                         $date $message->dateSent;
  1702.                     }
  1703.                 }
  1704.                 $data[] = [
  1705.                     'name' => $name $name $item,
  1706.                     'y' => $sumTotal ? (float) (($sumMes 100) / $sumTotal) : 0,
  1707.                     'date' => $date,
  1708.                     'sumMes' => $sumMes,
  1709.                     'sumTotal' => $sumTotal
  1710.                 ];
  1711.             }
  1712.         }
  1713.         if ($data) {
  1714.             usort($data, function ($a$b) {
  1715.                 return ($a['date'] < $b['date']) ? -1;
  1716.             });
  1717.         }
  1718.         return $this->json(TransformData::transform($data));
  1719.     }
  1720.     /**
  1721.      * @return JsonResponse
  1722.      *
  1723.      * @Route("/dashboard/referred-patients", name="referred-patients", options={"expose" = "true"}, methods={"POST"})
  1724.      */
  1725.     public function referredPatients(Request $request)
  1726.     {
  1727.         $filter $this->getFilter($request);
  1728.         return $this->json(
  1729.             TransformData::transformReferredPatientsData(
  1730.                 $this->getDoctrine()->getRepository(Patient::class)->findReferredPatients($filter)
  1731.             )
  1732.         );
  1733.     }
  1734.     /**
  1735.      * @return DashboardFilter
  1736.      */
  1737.     private function getFilter(Request $request)
  1738.     {
  1739.         $user $this->getUser();
  1740.         $filter = new DashboardFilter();
  1741.         $filter->addClinic($this->getClinic());
  1742.         $filter->setDashboard(true);
  1743.         $form $this->createForm(DashboardFilterType::class, $filter, ['timezone' => $this->getParameter('google_calendar_default_timezone'), 'user' => $this->getUser()]);
  1744.         $form->handleRequest($request);
  1745.         if (== $filter->getClinics()->count() && ($user instanceof SuperClinicAdmin || $user->getRole() == User::ROLE_SUPER_CLINIC_ADMIN)) {
  1746.             $user->getOrganisation()->getClinics()->map(function (Clinic $clinic) use (&$filter) {
  1747.                 $filter->addClinic($clinic);
  1748.             });
  1749.         }
  1750.         if ($user instanceof ClinicUser && $user->getRole() != User::ROLE_SUPER_CLINIC_ADMIN) {
  1751.             $filter->addClinic($user->getClinic());
  1752.         }
  1753.         if($filter->getDateEnd()) {
  1754.           $filter->getDateEnd()->setTime(235959);
  1755.         }
  1756.         if ($filter->getDateEndSecond()) {
  1757.             $filter->getDateEndSecond()->setTime(235959);
  1758.             $filter->getDateEndSecond()->setTimezone(new \DateTimeZone('UTC'));
  1759.         }
  1760.         if ($filter->getDateStartSecond()) {
  1761.             $filter->getDateStartSecond()->setTimezone(new \DateTimeZone('UTC'));
  1762.         }
  1763.         $filter->getDateStart()->setTimezone(new \DateTimeZone('UTC'));
  1764.         $filter->getDateEnd()->setTimezone(new \DateTimeZone('UTC'));
  1765.         return $filter;
  1766.     }
  1767.     public static function getReconciliationData(DashboardFilter $filter)
  1768.     {
  1769.         $filter->setNameReport(Setting::RECONCILIATION);
  1770.         $totals self::$entityManager->getRepository(BaseInvoice::class)->selectInvoicesDeatilPage($filter)->getResult();
  1771.         $sum_amt 0;
  1772.         foreach ($totals as $total) {
  1773.             if ($total instanceof Invoice) {
  1774.                 $sum_amt += $total->getTotalList();
  1775.             }
  1776.             if ($total instanceof Prepay) {
  1777.                 $sum_amt += $total->getAmount();
  1778.             }
  1779.             // if ($total->getType() == '')
  1780.             //     $sum_amt += $total->getTotalList();
  1781.         }
  1782.         $filter->setNameReport(Setting::BILLINGS_PER_PERIOD);
  1783.         $totalBillings self::$entityManager->getRepository(BaseInvoice::class)->selectInvoicesDeatilPage($filter)->getResult();
  1784.         $sumBillings 0;
  1785.         $refundTotal 0;
  1786.         $totalNet 0;
  1787.         $dueAmt 0;
  1788.         /** @var Invoice|Prepay|CreditNote $billing */
  1789.         foreach ($totalBillings as $billing) {
  1790.             if ($billing instanceof Invoice) {
  1791.                 $dueAmt += $billing->getDue();
  1792.                 //echo $sumInvoices;
  1793.                 foreach ($billing->getPayments() as $list) {
  1794.                     $totalNet += $list->getAmount();
  1795.                 }
  1796.                 foreach ($billing->getItems() as $itemInv) {
  1797.                     if ($itemInv instanceof Refund) {
  1798.                         $refundTotal += $itemInv->getTotal();
  1799.                     }
  1800.                 }
  1801.                 $sumBillings += $billing->getTotalList();
  1802.             }
  1803.             if ($billing instanceof Prepay) {
  1804.                 $sumBillings += $billing->getAmount();
  1805.             }
  1806.         }
  1807.         $refundValue = ($dueAmt) - ($refundTotal);
  1808.         //echo "<br>";
  1809.         //echo $refundTotal;
  1810.         $sumBillings $sum_amt;
  1811.         //echo $sum_amt - $totalNet;
  1812.         $filter->setNameReport(Setting::RECONCILIATION);
  1813.         $receiptsPrevPeriod self::$entityManager->getRepository(Payment::class)->findTransactionsPrevPeriodByFilter($filter);
  1814.         $sumReceiptsPrevPeriod 0;
  1815.         $neus 0;
  1816.         /** @var Payment $receipt */
  1817.         foreach ($receiptsPrevPeriod as $receipt) {
  1818.             //echo $neus;
  1819.             if (!$receipt->isPrepay()) {
  1820.                 $testBIlling $receipt->getInvoice();
  1821.                 foreach ($testBIlling->getItems() as $itemInv) {
  1822.                     if ($itemInv instanceof Refund) {
  1823.                         $neus += $itemInv->getTotal();
  1824.                     }
  1825.                 }
  1826.                 $sumReceiptsPrevPeriod += $receipt->getAmount();
  1827.             }
  1828.         }
  1829.         $totalBillingsNotPayment self::$entityManager->getRepository(Invoice::class)->findBillingsNotPayment($filter);
  1830.         $sumBillingsNotPayment 0;
  1831.         /** @var Invoice $item */
  1832.         foreach ($totalBillingsNotPayment as $item) {
  1833.             $sumBillingsNotPayment += $item->getTotalList();
  1834.         }
  1835.         $sumBillingsNotPayment $refundValue;
  1836.         $sumPrepayments 0;
  1837.         /** @var Invoice|Prepay|CreditNote $billing */
  1838.         foreach ($totalBillings as $billing) {
  1839.             if ($billing instanceof Prepay) {
  1840.                 $sumPrepayments += $billing->getAmount();
  1841.             }
  1842.         }
  1843.         $filter->setNameReport(Setting::TRANSACTIONS);
  1844.         $sumReceipts $sumBillings $sumReceiptsPrevPeriod $sumBillingsNotPayment;
  1845.         $totalPrepaidInvoice self::$entityManager->getRepository(Invoice::class)->findRevenuePerPractitioner($filtertrue);
  1846.         $sumPrepaidInvoice 0;
  1847.         /** @var Invoice $item */
  1848.         foreach ($totalPrepaidInvoice as $item) {
  1849.             $sumPrepaidInvoice += $item->getTotalList();
  1850.         }
  1851.         $sumRevenue $sumReceipts $sumPrepayments $sumReceiptsPrevPeriod $sumPrepaidInvoice $sumBillingsNotPayment $refundTotal;
  1852.         $sumBillingsNotPayment $sumBillingsNotPayment;
  1853.         $newValue $sumBillingsNotPayment + ($refundTotal);
  1854.         return
  1855.             [
  1856.                 [
  1857.                     'th1' => 'Total Billings',
  1858.                     'th2' => $sum_amt,
  1859.                 ],
  1860.                 [
  1861.                     'th1' => 'Plus: Net Receipts from Previous Period',
  1862.                     'th2' => $sumReceiptsPrevPeriod + ($neus),
  1863.                 ],
  1864.                 [
  1865.                     'th1' => 'Less: Billings Payment Not Received',
  1866.                     'th2' => $sumBillingsNotPayment * (-1),
  1867.                 ],
  1868.                 [
  1869.                     'th1' => 'Total Net Receipts',
  1870.                     'th2' => $sumReceipts,
  1871.                 ],
  1872.                 [
  1873.                     'th1' => 'Less: Prepayments',
  1874.                     'th2' => $sumPrepayments * (-1),
  1875.                 ],
  1876.                 [
  1877.                     'th1' => 'Less: Net Receipts for Previous Period',
  1878.                     'th2' => $sumReceiptsPrevPeriod * (-1),
  1879.                 ],
  1880.                 [
  1881.                     'th1' => 'Plus: Prepaid Invoices',
  1882.                     'th2' => $sumPrepaidInvoice,
  1883.                 ],
  1884.                 [
  1885.                     'th1' => 'Plus: Invoices Payment Not Received',
  1886.                     'th2' => $newValue,
  1887.                 ],
  1888.                 [
  1889.                     'th1' => 'Total Revenue',
  1890.                     'th2' => $sumRevenue,
  1891.                 ]
  1892.             ];
  1893.     }
  1894. }