src/ApplicationBundle/Modules/Sales/Controller/SalesController.php line 3811

Open in your IDE?
  1. <?php
  2. namespace ApplicationBundle\Modules\Sales\Controller;
  3. use ApplicationBundle\ApplicationBundle;
  4. use ApplicationBundle\Constants\AccountsConstant;
  5. use ApplicationBundle\Constants\AfterSalesServiceConstant;
  6. use ApplicationBundle\Constants\GeneralConstant;
  7. use ApplicationBundle\Constants\ProjectConstant;
  8. use ApplicationBundle\Controller\GenericController;
  9. use ApplicationBundle\Entity\AccClients;
  10. use ApplicationBundle\Entity\AccSettings;
  11. use ApplicationBundle\Entity\AfterSalesServiceIssue;
  12. use ApplicationBundle\Entity\Branch;
  13. use ApplicationBundle\Entity\ClientType;
  14. use ApplicationBundle\Entity\Employee;
  15. use ApplicationBundle\Entity\Region;
  16. use ApplicationBundle\Entity\SalesOrder;
  17. use ApplicationBundle\Entity\Warehouse;
  18. use ApplicationBundle\Entity\WarehouseAction;
  19. use ApplicationBundle\Helper\Generic;
  20. use ApplicationBundle\Helper\ResponseStructure;
  21. use ApplicationBundle\Interfaces\SessionCheckInterface;
  22. use ApplicationBundle\Modules\Accounts\Accounts;
  23. use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
  24. use ApplicationBundle\Modules\Inventory\Inventory;
  25. use ApplicationBundle\Modules\Project\ProjectM;
  26. use ApplicationBundle\Modules\Sales\Client;
  27. use ApplicationBundle\Modules\Sales\Constants\SalesConstant;
  28. use ApplicationBundle\Modules\Sales\Helper\SalesOrderHelper;
  29. use ApplicationBundle\Modules\Sales\Package;
  30. use ApplicationBundle\Modules\Sales\SalesOrderM;
  31. use ApplicationBundle\Modules\System\DeleteDocument;
  32. use ApplicationBundle\Modules\System\DocValidation;
  33. use ApplicationBundle\Modules\System\MiscActions;
  34. use ApplicationBundle\Modules\System\System;
  35. use ApplicationBundle\Modules\User\Company;
  36. use ApplicationBundle\Modules\User\Position;
  37. use ApplicationBundle\Modules\User\Users;
  38. use CompanyGroupBundle\Entity\EntityFile;
  39. use Symfony\Component\HttpFoundation\JsonResponse;
  40. use Symfony\Component\HttpFoundation\Request;
  41. use Symfony\Component\HttpFoundation\Response;
  42. class SalesController extends GenericController implements SessionCheckInterface
  43. {
  44.     public function ParseCustomerCsv(Request $request)
  45.     {
  46.         $customerList = [];
  47.         if ($request->isMethod('POST')) {
  48.             $post $request->request;
  49.             $path "";
  50.             $file_path "";
  51.             foreach ($request->files as $uploadedFile) {
  52.                 //            if($uploadedFile->getImage())
  53.                 //                var_dump($uploadedFile->getFile());
  54.                 //                var_dump($uploadedFile);
  55.                 if ($uploadedFile != null) {
  56.                     $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  57.                     $path $fileName;
  58.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  59.                     if (!file_exists($upl_dir)) {
  60.                         mkdir($upl_dir0777true);
  61.                     }
  62.                     $file $uploadedFile->move($upl_dir$path);
  63.                 }
  64.             }
  65.             //        print_r($file);
  66.             if ($path != "")
  67.                 $file_path 'uploads/FileUploads/' $path;
  68.             $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  69.             $row 1;
  70.             $csv_data = [];
  71.             $rawData "";
  72.             if (($handle fopen($g_path"r")) !== FALSE) {
  73. //                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
  74. //                    $num = count($data);
  75. //                    $csv_data[$row] = $data;
  76. //
  77. //                    $row++;
  78. //
  79. //                }
  80.                 $rawData file_get_contents($g_path);
  81.                 fclose($handle);
  82.                 unlink($g_path);
  83.             }
  84. //            $rawData = "John Doe, 34, johndoe@example.com, Software Engineer, New York
  85. //            Jane Smith, 28, janesmith@example.com, Data Analyst, San Francisco
  86. //            EOD";
  87.             $apiKey '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';
  88.             $expectedStructure 'Please extract the following structured JSON from the input. use null if a property is not found:
  89.             
  90.             [
  91.               {
  92.     "client_name": "",
  93.     "contact_person_name": "",
  94.     "sales_person_id": "",
  95.     "type": "2",
  96.     "region_id": "0",
  97.     "division_id": "0",
  98.     "address_contact": "",
  99.     "contact_number": "",
  100.     "shipping_address": "",
  101.     "billing_address": "",
  102.     "email": "",
  103.     "fax": "",
  104.     "client_order_amount": null,
  105.     "client_invoice_amount": "",
  106.     "client_received": "",
  107.     "client_due": "",
  108.     "client_area_wise_code": "0",
  109.     "temp_client_flag": "0",
  110.     "head_addition_pending_flag": null,
  111.     "geographical_region_id": "0",
  112.     "image": null,
  113.     "geographical_region_name": null,
  114.     "tagged_item_groups": null,
  115.     "credit_limit": "0.000",
  116.     "provision_flag": null,
  117.     "device_id": null,
  118.     "device_id_locked_flag": null,
  119.     "lock_device_id_on_next_login_flag": null,
  120.     "credit_limit_enabled": "0",
  121.     "delivery_locked": "0",
  122.     "client_alternate_code": "2015001",
  123.     "initial_opening_balance": "0",
  124.     "temp_area_str": null,
  125.     "temp_customer_id_hash": null,
  126.     "project_ids": null,
  127.     "doc_booked_flag": null,
  128.     "time_stamp_of_form": null,
  129.     "client_level": "1",
  130.     "parent_id": "0",
  131.     "is_consumer": "0",
  132.     "username": null,
  133.     "password": null,
  134.     "email_verification_hash": null,
  135.     "phone_verification_hash": null,
  136.     "trigger_reset_password": null,
  137.     "is_email_verified": null,
  138.     "is_phone_verified": null,
  139.     "is_banned": null,
  140.     "ban_expires": null,
  141.     "strike_count": null,
  142.     "strike_threshold": null,
  143.     "account_status": null,
  144.     "general_info_tin": "",
  145.     "general_info_bin": "",
  146.     "is_individual": null,
  147.     "allowed_brand_ids": "null",
  148.     "delivery_instruction": null,
  149.     "client_own_balance_amount": null,
  150.     "client_own_due_amount": null,
  151.     "client_own_sales_amount": null,
  152.     "client_own_received_amount": null,
  153.     "client_cash_amount": null,
  154.     "client_bank_amount": null,
  155.     "client_payment_methods_info": null,
  156.     "default_courier_id": "0",
  157.     "freeze_balance": null,
  158.     "otp_action_id": null,
  159.     "otp": null,
  160.     "otp_expire_ts": null,
  161.     "forgot_password_token": null,
  162.     "forgot_password_token_expire_ts": null,
  163.     "last_settings_updated_ts": "1709528898",
  164.     "app_id": null,
  165.     "representative_emails": null,
  166.     "representative_emails_data": null,
  167.     "global_user_id": null
  168. },
  169.             ]
  170.             
  171.              Return only the JSON output. Do not include any extra text or explanation.
  172.             ';
  173.             $messages = [
  174.                 ['role' => 'system''content' => 'You are a data structuring assistant.'],
  175.                 ['role' => 'user''content' => "Raw data:\n$rawData"],
  176.                 ['role' => 'user''content' => "Expected structure:\n$expectedStructure"],
  177.             ];
  178.             $data = [
  179.                 'model' => 'gpt-4.1',
  180.                 'messages' => $messages,
  181.                 'temperature' => 0.2
  182.             ];
  183.             $ch curl_init();
  184.             curl_setopt($chCURLOPT_URL'https://api.openai.com/v1/chat/completions');
  185.             curl_setopt($chCURLOPT_RETURNTRANSFERtrue);
  186.             curl_setopt($chCURLOPT_POSTtrue);
  187.             curl_setopt($chCURLOPT_HTTPHEADER, [
  188.                 "Authorization: Bearer $apiKey",
  189.                 'Content-Type: application/json'
  190.             ]);
  191.             curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  192.             $response curl_exec($ch);
  193.             if (curl_errno($ch)) {
  194.                 echo 'Request Error:' curl_error($ch);
  195.             }
  196.             curl_close($ch);
  197. // Decode response
  198.             $responseData json_decode($responsetrue);
  199.             $customerList json_decode($responseData['choices'][0]['message']['content'] ?? '[]]'true);
  200. //            echo "<pre>$structuredOutput</pre>";
  201.             //now getting the relevant checks
  202. //            $customerList = [];
  203. //            if ($customerList) {
  204. //                foreach ($customerList as $customer) {
  205. //                }
  206. //
  207. //            }
  208.             return new JsonResponse(array(
  209.                 "success" => true,
  210.                 "file_path" => $file_path,
  211. //                "csv_data" => $csv_data,
  212. //                'responseData' => $responseData,
  213.                 "customerList" => $customerList,
  214.                 //                "debug_data"=>System::encryptSignature($r)
  215.             ));
  216.         }
  217.         return new JsonResponse(array(
  218.             "success" => false,
  219.             "customerList" => $customerList,
  220.         ));
  221.     }
  222.     public function RecalculateSalesOrders(Request $request)
  223.     {
  224.         $em $this->getDoctrine()->getManager();
  225.         $debug_data = [];
  226.         $setFlagInitially 0;
  227.         if ($request->request->has('setInitialFlag'))
  228.             $setFlagInitially $request->request->get('setInitialFlag');
  229.         if ($request->isMethod('POST')) {
  230.             //            $Transaction = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  231.             //            $Transaction = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  232.             //                'approved' => 1,
  233.             //                'ledgerHit' => 0
  234.             //            ));
  235.             if ($setFlagInitially == 1) {
  236.                 $get_kids_sql 'UPDATE `sales_order` SET recalculate_flag=1';
  237.                 $stmt $em->getConnection()->prepare($get_kids_sql);
  238.                 $stmt->execute();
  239.                 $stmt->closeCursor();
  240.             }
  241.             $q $this->getDoctrine()
  242.                 ->getRepository('ApplicationBundle:SalesOrder')
  243.                 ->findOneBy(
  244.                     array(
  245.                         'status' => GeneralConstant::ACTIVE,
  246.                         'recalculateFlag' => 1,
  247.                     ),
  248.                     array(
  249.                         'salesOrderDate' => 'ASC'
  250.                     )
  251.                 );
  252.             if ($q) {
  253.                 SalesOrderM::recalculateSalesOrder($em$q->getSalesOrderId());
  254.                 SalesOrderM::checkIfSalesOrderComplete($em$q->getSalesOrderId());
  255.                 return new JsonResponse(array(
  256.                     "success" => true,
  257.                     "debugData" => $debug_data,
  258.                     "last_doc" => $q->getDocumentHash(),
  259.                     "last_doc_id" => $q->getSalesOrderId()
  260.                 ));
  261.             } else {
  262.                 return new JsonResponse(array(
  263.                     "success" => false,
  264.                     "debugData" => $debug_data,
  265.                     "last_doc" => '',
  266.                     "last_doc_id" => ''
  267.                 ));
  268.             }
  269.         }
  270.         return new JsonResponse(array(
  271.             "success" => false,
  272.             "debugData" => $debug_data,
  273.             "last_doc" => '',
  274.             "last_doc_id" => ''
  275.         ));
  276.         //        MiscActions::refreshDatabase($em);
  277.         //        return $this->redirectToRoute('dashboard');
  278.     }
  279.     public function AssignExistingEntitiesToVoucher(Request $request)
  280.     {
  281.         $em $this->getDoctrine()->getManager();
  282.         $debug_data = [];
  283.         $setFlagInitially 0;
  284.         if ($request->request->has('setInitialFlag'))
  285.             $setFlagInitially $request->request->get('setInitialFlag');
  286.         if ($request->isMethod('POST')) {
  287.             //            $Transaction = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
  288.             //                'approved' => 1,
  289.             //                'ledgerHit' => 0
  290.             //            ));
  291.             $currEntity 8;
  292.             $tocheckEntityList = array(
  293.                 => 'Grn',
  294.                 => 'PurchaseInvoice',
  295.                 10 => 'ExpenseInvoice',
  296.                 16 => 'DeliveryReceipt',
  297.                 18 => 'SalesInvoice',
  298.                 20 => 'StockTransfer',
  299.                 21 => 'StockReceivedNote',
  300.                 30 => 'ServiceChallan',
  301.                 41 => 'ItemReceivedAndReplacement',
  302.                 44 => 'StockConsumptionNote',
  303.                 47 => 'FixedAssetConversionNote',
  304.                 48 => 'FixedAssetDisposalNote',
  305.                 53 => 'Production',
  306.             );
  307.             foreach ($tocheckEntityList as $entity => $entityName) {
  308.                 $entityList $em->getRepository('ApplicationBundle:' $entityName)->findBy(
  309.                     array(),
  310.                     array( //                        GeneralConstant::$Entity_id_list[$entity]
  311.                     )
  312.                 );
  313.                 foreach ($entityList as $entry) {
  314.                     $voucherIds method_exists($entry'getVoucherIds') ? json_decode($entry->getVoucherIds(), true) : [];
  315.                     $getMethod GeneralConstant::$Entity_id_get_method_list[$entity];
  316.                     if ($voucherIds == null)
  317.                         $voucherIds = [];
  318.                     if (!empty($voucherIds)) {
  319.                         $transactions $em->getRepository('ApplicationBundle:AccTransactions')->findBy(
  320.                             array(
  321.                                 'transactionId' => $voucherIds
  322.                             )
  323.                         );
  324.                         foreach ($transactions as $transaction) {
  325.                             if ($transaction->getEntityId() == || $transaction->getEntityId() == null) {
  326.                                 $transaction->setEntityId($entry->$getMethod());
  327.                                 $transaction->setEntity($entity);
  328.                                 $transaction->setEntityDocHash($entry->getDocumentHash());
  329.                                 $em->flush();
  330.                             }
  331.                         }
  332.                     }
  333.                 }
  334.             }
  335.             //            if ($q) {
  336.             //
  337.             //                return new JsonResponse(array(
  338.             //                    "success" => true,
  339.             //                    "debugData" => $debug_data,
  340.             //                    "last_doc"=>$q->getDocumentHash(),
  341.             //                    "last_doc_id"=>$q->getSalesOrderId()
  342.             //
  343.             //                ));
  344.             //            } else {
  345.             //
  346.             //                return new JsonResponse(array(
  347.             //                    "success" => false,
  348.             //                    "debugData" => $debug_data,
  349.             //                    "last_doc"=>'',
  350.             //                    "last_doc_id"=>''
  351.             //
  352.             //                ));
  353.             //            }
  354.         }
  355.         return new JsonResponse(array(
  356.             "success" => false,
  357.             "debugData" => $debug_data,
  358.             "last_doc" => '',
  359.             "last_doc_id" => ''
  360.         ));
  361.         //        MiscActions::refreshDatabase($em);
  362.         //        return $this->redirectToRoute('dashboard');
  363.     }
  364.     public function GetClientNumericalCode(Request $request$ct$reg)
  365.     {
  366.         //        return new JsonResponse();
  367.         return new JsonResponse(array("success" => true"content" => Client::GetClientNumCode($this->getDoctrine()
  368.             ->getManager(), $ct$reg$this->getLoggedUserCompanyId($request))));
  369.     }
  370.     public function CreateTradeOffer(Request $request$id 0)
  371.     {
  372.         $em $this->getDoctrine()->getManager();
  373.         if ($request->isMethod('POST')) {
  374.             $em $this->getDoctrine()->getManager();
  375.             $entity_id array_flip(GeneralConstant::$Entity_list)['TradeOffer'];
  376.             //            $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
  377.             //                array(
  378.             //                    'tradeOfferId'=>$id, ///material
  379.             //
  380.             //                ),array('projectDate'=>'desc')
  381.             //            );
  382.             //            $client=$em->getRepository('ApplicationBundle:AccClients')->findOneBy(
  383.             //                array(
  384.             //                    'clientId'=>$projectData->getClientId(), ///material
  385.             //
  386.             //                ),array('projectDate'=>'desc')
  387.             //            );
  388.             $dochash $request->request->get('docHash');
  389.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  390.             $approveRole $request->request->get('approvalRole');
  391.             $approveHash $request->request->get('approvalHash');
  392.             if (!DocValidation::isInsertable(
  393.                 $em,
  394.                 $entity_id,
  395.                 $dochash,
  396.                 $loginId,
  397.                 $approveRole,
  398.                 $approveHash,
  399.                 $id
  400.             )) {
  401.                 $this->addFlash(
  402.                     'error',
  403.                     'Sorry Could not insert Data.'
  404.                 );
  405.             } else {
  406.                 //construct the files
  407.                 $file_list = array(
  408.                     'product_files' => [],
  409.                     'service_files' => [],
  410.                     'ar_files' => [],
  411.                 );
  412.                 //
  413.                 $spId SalesOrderM::CreateNewTradeOffer(
  414.                     $this->getDoctrine()->getManager(),
  415.                     $id,
  416.                     $request->request,
  417.                     $dochash,
  418.                     $file_list,
  419.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  420.                     $this->getLoggedUserCompanyId($request)
  421.                 );
  422.                 //now add Approval info
  423.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  424.                 $approveRole $request->request->get('approvalRole');  //created
  425.                 $options = array(
  426.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  427.                     'notification_server' => $this->container->getParameter('notification_server'),
  428.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  429.                     'url' => $this->generateUrl(
  430.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['TradeOffer']]['entity_view_route_path_name']
  431.                     )
  432.                 );
  433.                 System::setApprovalInfo(
  434.                     $this->getDoctrine()->getManager(),
  435.                     $options,
  436.                     array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
  437.                     $spId,
  438.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  439.                 );
  440.                 System::createEditSignatureHash(
  441.                     $this->getDoctrine()->getManager(),
  442.                     array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
  443.                     $spId,
  444.                     $loginId,
  445.                     $approveRole,
  446.                     $request->request->get('approvalHash')
  447.                 );
  448.                 $this->addFlash(
  449.                     'success',
  450.                     'Trade Offer Created'
  451.                 );
  452.                 $url $this->generateUrl(
  453.                     'view_trade_offer'
  454.                 );
  455.                 System::AddNewNotification(
  456.                     $this->container->getParameter('notification_enabled'),
  457.                     $this->container->getParameter('notification_server'),
  458.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  459.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  460.                     "Trade Offer : " $dochash " Has Been Created And is Under Processing",
  461.                     'pos',
  462.                     System::getPositionIdsByDepartment($emGeneralConstant::SALES_DEPARTMENT),
  463.                     'success',
  464.                     $url "/" $spId,
  465.                     "Trade Offer"
  466.                 );
  467.                 return $this->redirect($url "/" $spId);
  468.             }
  469.         }
  470.         $message "";
  471.         $extData = [];
  472.         $extDetails = [];
  473.         if ($id != 0) {
  474.             $extData $em->getRepository('ApplicationBundle:TradeOffer')->findOneBy(
  475.                 array(
  476.                     'tradeOfferId' => $id///material
  477.                 )
  478.             );
  479.             //now if its not editable, redirect to view
  480.             if ($extData) {
  481.                 $extDetails json_decode($extData->getData(), true);
  482.                 if ($extDetails == null)
  483.                     $extDetails = [];
  484.                 //                if ($proposalData->getEditFlag() != 1) {
  485.                 //                    $url = $this->generateUrl(
  486.                 //                        'view_trade_offer'
  487.                 //                    );
  488.                 //                    $this->addFlash(
  489.                 //                        'error',
  490.                 //                        'Sorry You cant Edit the document Right now.'
  491.                 //                    );
  492.                 //                    return $this->redirect($url . "/" . $id);
  493.                 //                }
  494.             }
  495.         }
  496.         $qry $em->getRepository("ApplicationBundle:InvProducts")->findBy(array(
  497.             "status" => GeneralConstant::ACTIVE,
  498.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  499.             'type' => //trade items
  500.         ));
  501.         $pl = [];
  502.         $pl_array = [];
  503.         foreach ($qry as $product) {
  504.             $pl[$product->getId()] = array(
  505.                 'text' => $product->getName(),
  506.                 'name' => $product->getName(),
  507.                 'id' => $product->getId(),
  508.                 'value' => $product->getId(),
  509.                 'purchase_price' => $product->getPurchasePrice(),
  510.                 'sales_price' => $product->getSalesPrice(),
  511.                 'supplier_id' => $product->getBrandCompany(),
  512.             );
  513.             $pl_array[] = array(
  514.                 'text' => $product->getName(),
  515.                 'value' => $product->getId(),
  516.                 'name' => $product->getName(),
  517.                 'id' => $product->getId(),
  518.                 'purchase_price' => $product->getPurchasePrice(),
  519.                 'sales_price' => $product->getSalesPrice(),
  520.                 'supplier_id' => $product->getBrandCompany(),
  521.             );
  522.         }
  523.         $qry $em->getRepository("ApplicationBundle:AccService")->findBy(array(
  524.             "status" => GeneralConstant::ACTIVE,
  525.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  526.             //            'type'=>1//trade items
  527.         ));
  528.         $sl = [];
  529.         $sl_array = [];
  530.         foreach ($qry as $product) {
  531.             $sl[$product->getServiceId()] = array(
  532.                 'text' => $product->getServiceName(),
  533.                 'value' => $product->getServiceId(),
  534.                 'name' => $product->getServiceName(),
  535.                 'id' => $product->getServiceId(),
  536.             );
  537.             $sl_array[] = array(
  538.                 'text' => $product->getServiceName(),
  539.                 'value' => $product->getServiceId(),
  540.                 'name' => $product->getServiceName(),
  541.                 'id' => $product->getServiceId(),
  542.             );
  543.         }
  544.         $qry $em->getRepository("ApplicationBundle:ProjectWorkStage")->findBy(array(
  545.             "status" => GeneralConstant::ACTIVE,
  546.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  547.             //            'type'=>1//trade items
  548.         ));
  549.         $workStages = [];
  550.         $workStages_array = [];
  551.         foreach ($qry as $product) {
  552.             $workStages[$product->getProjectWorkStageId()] = array(
  553.                 'text' => $product->getStageName(),
  554.                 'value' => $product->getProjectWorkStageId(),
  555.                 'name' => $product->getStageName(),
  556.                 'id' => $product->getProjectWorkStageId(),
  557.             );
  558.             $workStages_array[] = array(
  559.                 'text' => $product->getStageName(),
  560.                 'value' => $product->getProjectWorkStageId(),
  561.                 'name' => $product->getStageName(),
  562.                 'id' => $product->getProjectWorkStageId(),
  563.             );
  564.         }
  565.         $hl Accounts::HeadList($em);
  566.         $debug_data $request->files->get('product_reference_file');
  567.         $companyId $this->getLoggedUserCompanyId($request);
  568.         $productListArray = [];
  569.         $subCategoryListArray = [];
  570.         $categoryListArray = [];
  571.         $igListArray = [];
  572.         $unitListArray = [];
  573.         $productList Inventory::ProductList($em$companyId1);
  574.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  575.         $categoryList Inventory::ProductCategoryList($em$companyId);
  576.         $igList Inventory::ItemGroupList($em$companyId);
  577.         $unitList Inventory::UnitTypeList($em);
  578.         foreach ($productList as $product) {
  579.             $productListArray[] = $product;
  580.         }
  581.         foreach ($categoryList as $product) {
  582.             $categoryListArray[] = $product;
  583.         }
  584.         foreach ($subCategoryList as $product) {
  585.             $subCategoryListArray[] = $product;
  586.         }
  587.         foreach ($igList as $product) {
  588.             $igListArray[] = $product;
  589.         }
  590.         foreach ($unitList as $product) {
  591.             $unitListArray[] = $product;
  592.         }
  593.         $brandList Inventory::GetBrandList($em$companyId);
  594.         $brandListArray = [];
  595.         foreach ($brandList as $product) {
  596.             $brandListArray[] = $product;
  597.         }
  598.         return $this->render(
  599.             '@Sales/pages/input_forms/create_trade_offer.html.twig',
  600.             array(
  601.                 'page_title' => 'Trade Offer',
  602.                 'ExistingClients' => Client::GetExistingClientList($em$companyId),
  603.                 //                'clients'=>SalesOrderM::GetClientList($em),
  604.                 'clients_by_ac_head' => SalesOrderM::GetClientListByAcHead($em),
  605.                 'users' => Users::getUserListById($em),
  606.                 'stages' => ProjectConstant::$projectStages,
  607.                 'productList' => $productList,
  608.                 'subCategoryList' => $subCategoryList,
  609.                 'categoryList' => $categoryList,
  610.                 'igList' => $igList,
  611.                 'unitList' => $unitList,
  612.                 'brandList' => $brandList,
  613.                 'brandListArray' => $brandListArray,
  614.                 'productListArray' => $productListArray,
  615.                 'subCategoryListArray' => $subCategoryListArray,
  616.                 'categoryListArray' => $categoryListArray,
  617.                 'igListArray' => $igListArray,
  618.                 'unitListArray' => $unitListArray,
  619.                 'sl' => $sl,
  620.                 'pl' => $pl,
  621.                 'hl' => $hl,
  622.                 'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  623.                 'extData' => $extData,
  624.                 'extDetails' => $extDetails,
  625.                 'extId' => $id,
  626.                 'message' => $message,
  627.                 'tradeOfferId' => $id,
  628.                 'regionList' => Client::RegionList($em$companyId),
  629.                 'branchList' => Client::BranchList($em$companyId),
  630.                 'pl_array' => $pl_array,
  631.                 'sl_array' => $sl_array,
  632.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  633.                 'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  634.                 'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  635.                 'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  636.                 'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  637.                 'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  638.                 'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  639.                 'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  640.                 'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  641.                 'debug_data' => $debug_data,
  642.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  643.                 //              'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  644.             )
  645.         );
  646.     }
  647.     public function TradeOfferList(Request $request)
  648.     {
  649.         $em $this->getDoctrine()->getManager();
  650.         $q $this->getDoctrine()
  651.             ->getRepository('ApplicationBundle:TradeOffer')
  652.             ->findBy(
  653.                 array(
  654.                     'status' => GeneralConstant::ACTIVE,
  655.                 ),
  656.                 array(
  657.                     'tradeOfferDate' => 'DESC',
  658.                     //                    'salesOrderId'=>'DESC'
  659.                 )
  660.             );
  661.         $stage_list = ['Pending''Pending''Complete''Partial'];
  662.         $d 9;
  663.         $data = [];
  664.         foreach ($q as $entry) {
  665.             //            $clientId=$entry->getClientId();
  666.             //            $client=$em->getRepository('ApplicationBundle:AccClients')
  667.             //                ->findOneBy(
  668.             //                    array(
  669.             //                        'clientId'=>$clientId
  670.             //                    )
  671.             //                );
  672.             $data[] = array(
  673.                 'doc_date' => $entry->getTradeOfferDate(),
  674.                 'start_date' => $entry->getTradeOfferStartDate(),
  675.                 'end_date' => $entry->getTradeOfferEndDate(),
  676.                 'id' => $entry->getTradeOfferId(),
  677.                 'doc_hash' => $entry->getDocumentHash(),
  678.                 'title' => $entry->getTitle(),
  679.                 'code' => $entry->getCode(),
  680.                 'invokeType' => $entry->getInvokeTYpe(),
  681.                 'status' => 'Active',
  682.                 'proposal_accepted' => $entry->getAccepted(),
  683.                 //                'stage'=>$stage_list[$entry->getStage()]
  684.             );
  685.         }
  686.         return $this->render(
  687.             '@Sales/pages/list/trade_offer_list.html.twig',
  688.             array(
  689.                 'page_title' => 'Trade Offers',
  690.                 'data' => $data,
  691.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  692.                 'users' => Users::getUserListById($em)
  693.             )
  694.         );
  695.     }
  696.     public function ViewTradeOffer(Request $request$id)
  697.     {
  698.         $em $this->getDoctrine()->getManager();
  699.         $dt SalesOrderM::GetTradeOfferDetails($em$id);
  700.         ///
  701.         //        $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
  702.         //            array(
  703.         //                'tradeOfferId'=>$id, ///material
  704.         //                'projectStep'=>array_flip(ProjectConstant::$projectSteps)['NEGOTIATION'], ///material
  705.         ////                'stage'=>array_flip(ProjectConstant::$projectStages)['INITIATED'],
  706.         ////                'status'=>array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  707.         //            ),array('projectDate'=>'desc')
  708.         //        );
  709.         //        $offerDataList=$em->getRepository('ApplicationBundle:TradeOffer')->findBy(
  710.         //            array(
  711.         //                'approved'=>1, ///material
  712.         //
  713.         //            )
  714.         //        );
  715.         //        if(!empty($offerDataList)) {
  716.         //            foreach ($offerDataList as $offerData) {
  717.         //                $all_det_data = json_decode($offerData->getData(), true);
  718.         //                $entry = $all_det_data[0];
  719.         //                $store_items = $entry['boqData']['Products'];
  720.         //                SalesOrderM::addProductsByFdm($em, $store_items['product_fdm'], $offerData->getCompanyId());
  721.         //
  722.         //            }
  723.         //        }
  724.         ///////
  725.         if (!$dt) {
  726.             $url $this->generateUrl(
  727.                 'create_trade_offer'
  728.             );
  729.             $this->addFlash(
  730.                 'error',
  731.                 'The Document You asked for was not found.'
  732.             );
  733.             return $this->redirect($url "/" $id);
  734.         }
  735.         $stage_list ProjectConstant::$projectStages;
  736.         $status_list ProjectConstant::$projectStatus;
  737.         $steps_list ProjectConstant::$projectSteps;
  738.         $companyId $dt['companyId'];
  739.         return $this->render(
  740.             '@Sales/pages/views/view_trade_offer.html.twig',
  741.             array(
  742.                 'page_title' => 'Trade Offer',
  743.                 'data' => $dt,
  744.                 //                'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
  745.                 //                'wpData'=>SalesOrderM::GetWpDetails($em,$id),
  746.                 'clientList' => SalesOrderM::GetClientList($em),
  747.                 'stageList' => $stage_list,
  748.                 'statusList' => $status_list,
  749.                 'stepsList' => $steps_list,
  750.                 'auto_created' => $dt['auto_created'],
  751.                 'approval_data' => System::checkIfApprovalExists(
  752.                     $em,
  753.                     array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
  754.                     $id,
  755.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  756.                 ),
  757.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  758.                     $this->getDoctrine()->getManager(),
  759.                     array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
  760.                     $id,
  761.                     $dt['created_by'],
  762.                     $dt['edited_by']
  763.                 ) : [],
  764.                 'users' => Users::getUserListById($em),
  765.                 'ExistingClients' => Client::GetExistingClientList($em$companyId),
  766.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  767.                 'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  768.                 'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  769.                 'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  770.                 'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  771.                 'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  772.                 'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  773.                 'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  774.                 'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  775.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  776.                 'stage_list' => ProjectM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)),
  777.                 'regionList' => Client::RegionList($em$companyId),
  778.                 'branchList' => Client::BranchList($em$companyId),
  779.             )
  780.         );
  781.     }
  782.     public function PrintTradeOffer(Request $request$id)
  783.     {
  784.         $em $this->getDoctrine()->getManager();
  785.         $dt SalesOrderM::GetProposalDetails($em$id);
  786.         if (!$dt) {
  787.             $url $this->generateUrl(
  788.                 'create_trade_offer'
  789.             );
  790.             $this->addFlash(
  791.                 'error',
  792.                 'Please Create Offer for the project 1st.'
  793.             );
  794.             return $this->redirect($url "/" $id);
  795.         }
  796.         $company_data Company::getCompanyData($em1);
  797.         $document_mark = array(
  798.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  799.             'copy' => ''
  800.         );
  801.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  802.             $html $this->renderView(
  803.                 '@Sales/pages/print/print_trade_offer.html.twig',
  804.                 array(
  805.                     //full array here
  806.                     'pdf' => true,
  807.                     'page_title' => 'Offer Letter',
  808.                     'export' => 'pdf,print',
  809.                     'data' => $dt,
  810.                     'stage_list' => SalesOrderM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)),
  811.                     'approval_data' => System::checkIfApprovalExists(
  812.                         $em,
  813.                         array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
  814.                         $id,
  815.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  816.                     ),
  817.                     'document_log' => System::getDocumentLog(
  818.                         $this->getDoctrine()->getManager(),
  819.                         array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
  820.                         $id,
  821.                         $dt['created_by'],
  822.                         $dt['edited_by']
  823.                     ),
  824.                     'document_mark_image' => $document_mark['original'],
  825.                     'document_type' => 'Offer Letter',
  826.                     'company_name' => $company_data->getName(),
  827.                     'company_data' => $company_data,
  828.                     'company_address' => $company_data->getAddress(),
  829.                     'company_image' => $company_data->getImage(),
  830.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  831.                     'red' => 0,
  832.                     'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  833.                 )
  834.             );
  835.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  836.                 //                'orientation' => 'landscape',
  837.                 //                'enable-javascript' => true,
  838.                 //                'javascript-delay' => 1000,
  839.                 'no-stop-slow-scripts' => false,
  840.                 'no-background' => false,
  841.                 'lowquality' => false,
  842.                 'encoding' => 'utf-8',
  843.                 //            'images' => true,
  844.                 //            'cookie' => array(),
  845.                 'dpi' => 300,
  846.                 'image-dpi' => 300,
  847.                 //                'enable-external-links' => true,
  848.                 //                'enable-internal-links' => true
  849.             ));
  850.             return new Response(
  851.                 $pdf_response,
  852.                 200,
  853.                 array(
  854.                     'Content-Type' => 'application/pdf',
  855.                     'Content-Disposition' => 'attachment; filename="offer.pdf"'
  856.                 )
  857.             );
  858.         }
  859.         return $this->render(
  860.             '@Sales/pages/print/print_trade_offer.html.twig',
  861.             array(
  862.                 'page_title' => 'Project Offer Letter',
  863.                 'export' => 'pdf,print',
  864.                 'data' => $dt,
  865.                 'stage_list' => SalesOrderM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)),
  866.                 'approval_data' => System::checkIfApprovalExists(
  867.                     $em,
  868.                     array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
  869.                     $id,
  870.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  871.                 ),
  872.                 'document_log' => System::getDocumentLog(
  873.                     $this->getDoctrine()->getManager(),
  874.                     array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
  875.                     $id,
  876.                     $dt['created_by'],
  877.                     $dt['edited_by']
  878.                 ),
  879.                 'document_mark_image' => $document_mark['original'],
  880.                 'company_name' => $company_data->getName(),
  881.                 'company_data' => $company_data,
  882.                 'company_address' => $company_data->getAddress(),
  883.                 'company_image' => $company_data->getImage(),
  884.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  885.                 'red' => 0,
  886.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  887.             )
  888.         );
  889.     }
  890.     public function ConvertToOrder(Request $request$id 0)
  891.     {
  892.         $em $this->getDoctrine()->getManager();
  893.         $retData = array(
  894.             'success' => false
  895.         );
  896.         if ($request->isMethod('POST')) {
  897.             $docType $request->get('docType''_proposal_');
  898.             $docId $request->get('docId'0);
  899.             if ($docType == '_project_') {
  900.                 $theParentDoc $em->getRepository('ApplicationBundle:Project')->findOneBy(
  901.                     array(
  902.                         'projectId' => $docId,
  903.                         'autoSoEnabled' => [0null],
  904.                     )
  905.                 );
  906.                 if ($theParentDoc) {
  907.                     $theParentDoc->setAutoSoEnabled(1);
  908.                     $em->flush();
  909.                     ProjectM::CreateSoFromBoq($em$docId$auto_created 1);
  910.                     $retData['success'] = true;
  911.                 }
  912.             }
  913.             if ($docType == '_proposal_') {
  914.                 $theParentDoc $em->getRepository('ApplicationBundle:Project')->findOneBy(
  915.                     array(
  916.                         'projectId' => $docId,
  917.                         'autoSoEnabled' => [0null],
  918.                     )
  919.                 );
  920.                 if ($theParentDoc) {
  921.                     $theParentDoc->setAutoSoEnabled(1);
  922.                     $em->flush();
  923.                     ProjectM::CreateSoFromProposal($em$docId$auto_created 1);
  924.                     $retData['success'] = true;
  925.                 }
  926.             }
  927.         }
  928.         return new JsonResponse($retData);
  929.     }
  930.     public function ConvertToProposal(Request $request$id 0)
  931.     {
  932.         $em $this->getDoctrine()->getManager();
  933.         $retData = array(
  934.             'success' => false
  935.         );
  936.         if ($request->isMethod('POST')) {
  937.             $docType $request->get('docType''_lead_');
  938.             $docId $request->get('docId'0);
  939.             if ($docType == '_lead_') {
  940.                 $theParentDoc $em->getRepository('ApplicationBundle:SalesLead')->findOneBy(
  941.                     array(
  942.                         'leadId' => $docId,
  943.                     )
  944.                 );
  945.                 if ($theParentDoc) {
  946.                     SalesOrderM::CreateNewProposalFromLead($em$theParentDoc->getSalesProposalId(), $docId$theParentDoc->getCreatedLoginId());
  947.                     $retData['success'] = true;
  948.                 }
  949.             }
  950.         }
  951.         return new JsonResponse($retData);
  952.     }
  953.     public function CreateSalesProposal(Request $request$id 0)
  954.     {
  955.         $em $this->getDoctrine()->getManager();
  956.         if ($request->isMethod('POST')) {
  957.             $em $this->getDoctrine()->getManager();
  958.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesProposal'];
  959.             //            $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
  960.             //                array(
  961.             //                    'salesProposalId'=>$id, ///material
  962.             //
  963.             //                ),array('projectDate'=>'desc')
  964.             //            );
  965.             //            $client=$em->getRepository('ApplicationBundle:AccClients')->findOneBy(
  966.             //                array(
  967.             //                    'clientId'=>$projectData->getClientId(), ///material
  968.             //
  969.             //                ),array('projectDate'=>'desc')
  970.             //            );
  971.             $dochash $request->request->get('docHash');
  972.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  973.             $approveRole $request->request->get('approvalRole');
  974.             $approveHash $request->request->get('approvalHash');
  975.             if (!DocValidation::isInsertable(
  976.                 $em,
  977.                 $entity_id,
  978.                 $dochash,
  979.                 $loginId,
  980.                 $approveRole,
  981.                 $approveHash,
  982.                 $id
  983.             )) {
  984.                 $this->addFlash(
  985.                     'error',
  986.                     'Sorry Could not insert Data.'
  987.                 );
  988.             } else {
  989.                 //construct the files
  990.                 $file_list = array(
  991.                     'product_files' => [],
  992.                     'service_files' => [],
  993.                     'ar_files' => [],
  994.                 );
  995.                 //                if ($request->request->has('products')) {
  996.                 //
  997.                 //                    if ($request->files->has('product_reference_file')) {
  998.                 //                        foreach ($request->files->get('product_reference_file') as $uploadedFile) {
  999.                 //
  1000.                 //                            $path = "";
  1001.                 //
  1002.                 //                            if ($uploadedFile != null) {
  1003.                 //
  1004.                 //                                $fileName = 'p' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  1005.                 //                                $path = $fileName;
  1006.                 //                                $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
  1007.                 //                                if (!file_exists($upl_dir)) {
  1008.                 //                                    mkdir($upl_dir, 0777, true);
  1009.                 //                                }
  1010.                 //                                $file = $uploadedFile->move($upl_dir, $path);
  1011.                 //
  1012.                 //                            }
  1013.                 //                            $file_list['product_files'][] = $path;
  1014.                 //                        }
  1015.                 //                    }
  1016.                 //
  1017.                 //
  1018.                 //                }
  1019.                 //                if ($request->request->has('services')) {
  1020.                 //                    //construct the ref_files array
  1021.                 //                    $ref_files = [];
  1022.                 //                    $path = "";
  1023.                 //                    $file_path = "";
  1024.                 //                    if ($request->files->has('product_reference_file')) {
  1025.                 //                        foreach ($request->files->get('service_reference_file') as $uploadedFile) {
  1026.                 ////                        $uploadedFile = $request->files['service_reference_file_' . $request->request->get('service_uid')[$key]];
  1027.                 //                            $path = "";
  1028.                 //                            if ($uploadedFile != null) {
  1029.                 //
  1030.                 //                                $fileName = 's' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  1031.                 //                                $path = $fileName;
  1032.                 //                                $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
  1033.                 //                                if (!file_exists($upl_dir)) {
  1034.                 //                                    mkdir($upl_dir, 0777, true);
  1035.                 //                                }
  1036.                 //                                $file = $uploadedFile->move($upl_dir, $path);
  1037.                 //
  1038.                 //                            }
  1039.                 //                            $file_list['service_files'][] = $path;
  1040.                 //                        }
  1041.                 //                    }
  1042.                 //
  1043.                 //                }
  1044.                 //                if ($request->request->has('heads')) {
  1045.                 //                    //construct the ref_files array
  1046.                 //                    $ref_files = [];
  1047.                 //                    $path = "";
  1048.                 //                    $file_path = "";
  1049.                 //                    foreach ($request->files->get('ar_reference_file') as $uploadedFile) {
  1050.                 ////                        $uploadedFile = $request->files['ar_reference_file_' . $request->request->get('ar_uid')[$key]];
  1051.                 //                        $path = "";
  1052.                 //                        if ($uploadedFile != null) {
  1053.                 //
  1054.                 //                            $fileName = 'a' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  1055.                 //                            $path = $fileName;
  1056.                 //                            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
  1057.                 //                            if (!file_exists($upl_dir)) {
  1058.                 //                                mkdir($upl_dir, 0777, true);
  1059.                 //                            }
  1060.                 //                            $file = $uploadedFile->move($upl_dir, $path);
  1061.                 //
  1062.                 //                        }
  1063.                 //                        $file_list['ar_files'][] = $path;
  1064.                 //                    }
  1065.                 //
  1066.                 //                }
  1067.                 $document_data_id SalesOrderM::UpdateDocumentData($this->getDoctrine()->getManager(), $request->request->get('documentDataId'), $request->request$file_list);
  1068.                 $spId SalesOrderM::CreateNewProposal(
  1069.                     $this->getDoctrine()->getManager(),
  1070.                     $id,
  1071.                     $document_data_id,
  1072.                     $request->request,
  1073.                     $dochash,
  1074.                     $file_list,
  1075.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  1076.                     $this->getLoggedUserCompanyId($request)
  1077.                 );
  1078.                 //now add Approval info
  1079.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  1080.                 $approveRole $request->request->get('approvalRole');  //created
  1081.                 $options = array(
  1082.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  1083.                     'notification_server' => $this->container->getParameter('notification_server'),
  1084.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  1085.                     'url' => $this->generateUrl(
  1086.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesProposal']]['entity_view_route_path_name']
  1087.                     )
  1088.                 );
  1089.                 $currentApprovalData System::setApprovalInfo(
  1090.                     $this->getDoctrine()->getManager(),
  1091.                     $options,
  1092.                     array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1093.                     $spId,
  1094.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  1095.                 );
  1096.                 System::createEditSignatureHash(
  1097.                     $this->getDoctrine()->getManager(),
  1098.                     array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1099.                     $spId,
  1100.                     $loginId,
  1101.                     $approveRole,
  1102.                     $request->request->get('approvalHash')
  1103.                 );
  1104.                 $this->addFlash(
  1105.                     'success',
  1106.                     'Sales Proposal Created'
  1107.                 );
  1108.                 $url $this->generateUrl(
  1109.                     'view_sales_proposal'
  1110.                 );
  1111.                 if ($currentApprovalData['inProcess'] == 1) {
  1112.                     System::AddNewNotification(
  1113.                         $this->container->getParameter('notification_enabled'),
  1114.                         $this->container->getParameter('notification_server'),
  1115.                         $request->getSession()->get(UserConstants::USER_APP_ID),
  1116.                         $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  1117.                         "Sales Order : " $dochash " Has Been Created And is Under Processing",
  1118.                         'pos',
  1119.                         System::getPositionIdsByDepartment($emGeneralConstant::SALES_DEPARTMENT),
  1120.                         'success',
  1121.                         $url "/" $spId,
  1122.                         "Sales Order"
  1123.                     );
  1124.                 }
  1125.                 return $this->redirect($url "/" $spId);
  1126.             }
  1127.         }
  1128.         $projectList = [];
  1129.         $projectData = [];
  1130.         $materialData = [];
  1131.         $boqData = [];
  1132.         $wpData = [];
  1133.         $offerData = [];
  1134.         $proposalData = [];
  1135.         $message "";
  1136.         $allDetData = [];
  1137.         $projectList $em->getRepository('ApplicationBundle:Project')->findBy(
  1138.             array(
  1139.                 'projectStep' => array_flip(ProjectConstant::$projectSteps)['PROPOSAL'], ///material
  1140.                 'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
  1141.                 'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  1142.             ),
  1143.             array('projectDate' => 'desc')
  1144.         );
  1145.         if ($id != 0) {
  1146.             $proposalData $em->getRepository('ApplicationBundle:SalesProposal')->findOneBy(
  1147.                 array(
  1148.                     'salesProposalId' => $id///material
  1149.                 )
  1150.             );
  1151.             //now if its not editable, redirect to view
  1152.             if ($proposalData) {
  1153.             }
  1154.         }
  1155.         $qry $em->getRepository("ApplicationBundle:InvProducts")->findBy(array(
  1156.             "status" => GeneralConstant::ACTIVE,
  1157.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  1158.             'type' => //trade items
  1159.         ));
  1160.         $pl = [];
  1161.         $pl_array = [];
  1162.         foreach ($qry as $product) {
  1163.             $pl[$product->getId()] = array(
  1164.                 'text' => $product->getName(),
  1165.                 'name' => $product->getName(),
  1166.                 'id' => $product->getId(),
  1167.                 'value' => $product->getId(),
  1168.                 'purchase_price' => $product->getPurchasePrice(),
  1169.                 'sales_price' => $product->getSalesPrice(),
  1170.                 'supplier_id' => $product->getBrandCompany(),
  1171.             );
  1172.             $pl_array[] = array(
  1173.                 'text' => $product->getName(),
  1174.                 'value' => $product->getId(),
  1175.                 'name' => $product->getName(),
  1176.                 'id' => $product->getId(),
  1177.                 'purchase_price' => $product->getPurchasePrice(),
  1178.                 'sales_price' => $product->getSalesPrice(),
  1179.                 'supplier_id' => $product->getBrandCompany(),
  1180.             );
  1181.         }
  1182.         $qry $em->getRepository("ApplicationBundle:AccService")->findBy(array(
  1183.             "status" => GeneralConstant::ACTIVE,
  1184.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  1185.             //            'type'=>1//trade items
  1186.         ));
  1187.         $sl = [];
  1188.         $sl_array = [];
  1189.         foreach ($qry as $product) {
  1190.             $sl[$product->getServiceId()] = array(
  1191.                 'text' => $product->getServiceName(),
  1192.                 'value' => $product->getServiceId(),
  1193.                 'name' => $product->getServiceName(),
  1194.                 'id' => $product->getServiceId(),
  1195.             );
  1196.             $sl_array[] = array(
  1197.                 'text' => $product->getServiceName(),
  1198.                 'value' => $product->getServiceId(),
  1199.                 'name' => $product->getServiceName(),
  1200.                 'id' => $product->getServiceId(),
  1201.             );
  1202.         }
  1203.         $qry $em->getRepository("ApplicationBundle:ProjectWorkStage")->findBy(array(
  1204.             "status" => GeneralConstant::ACTIVE,
  1205.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  1206.             //            'type'=>1//trade items
  1207.         ));
  1208.         $workStages = [];
  1209.         $workStages_array = [];
  1210.         foreach ($qry as $product) {
  1211.             $workStages[$product->getProjectWorkStageId()] = array(
  1212.                 'text' => $product->getStageName(),
  1213.                 'value' => $product->getProjectWorkStageId(),
  1214.                 'name' => $product->getStageName(),
  1215.                 'id' => $product->getProjectWorkStageId(),
  1216.             );
  1217.             $workStages_array[] = array(
  1218.                 'text' => $product->getStageName(),
  1219.                 'value' => $product->getProjectWorkStageId(),
  1220.                 'name' => $product->getStageName(),
  1221.                 'id' => $product->getProjectWorkStageId(),
  1222.             );
  1223.         }
  1224.         $hl Accounts::HeadList($em);
  1225.         $debug_data $request->files->get('product_reference_file');
  1226.         $companyId $this->getLoggedUserCompanyId($request);
  1227.         $productListArray = [];
  1228.         $subCategoryListArray = [];
  1229.         $categoryListArray = [];
  1230.         $igListArray = [];
  1231.         $unitListArray = [];
  1232.         $brandListArray = [];
  1233.         $productList Inventory::ProductList($em$companyId);
  1234.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  1235.         $categoryList Inventory::ProductCategoryList($em$companyId);
  1236.         $igList Inventory::ItemGroupList($em$companyId);
  1237.         $unitList Inventory::UnitTypeList($em);
  1238.         $brandList Inventory::GetBrandList($em$companyId);
  1239.         foreach ($productList as $product$productListArray[] = $product;
  1240.         foreach ($categoryList as $product$categoryListArray[] = $product;
  1241.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  1242.         foreach ($igList as $product$igListArray[] = $product;
  1243.         foreach ($unitList as $product$unitListArray[] = $product;
  1244.         foreach ($brandList as $product$brandListArray[] = $product;
  1245.         $assignedProjectSiteList = [];
  1246.         //        if($projectId==0)
  1247.         //        {
  1248.         //            $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
  1249.         //        }
  1250.         //        else
  1251.         //        {
  1252.         //
  1253.         //            $extTrans=$em->getRepository('ApplicationBundle:Project')->findOneBy(
  1254.         //                array(
  1255.         //                    'projectId'=>$projectId, ///material
  1256.         //
  1257.         //                )
  1258.         //            );
  1259.         //            $assignedProjectSiteList=ProjectM::ProjectSiteList($em,$projectId,$companyId);
  1260.         //            $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
  1261.         //
  1262.         //
  1263.         //            //now if its not editable, redirect to view
  1264.         //            if($extTrans) {
  1265.         //                if ($extTrans->getEditFlag() != 1 && $request->query->get('forceEdit',0)==0) {
  1266.         //                    $url = $this->generateUrl(
  1267.         //                        'view_project'
  1268.         //                    );
  1269.         //                    return $this->redirect($url . "/" . $projectId);
  1270.         //                }
  1271.         //                else
  1272.         //                {
  1273.         //                    $extDocData=$extTrans;
  1274.         ////                    $extDocDetailsData=Accounts::GetVoucherDataForEdit($em,$projectId);
  1275.         //                }
  1276.         //            }
  1277.         //            else
  1278.         //            {
  1279.         //
  1280.         //            }
  1281.         //
  1282.         //        }
  1283.         return $this->render(
  1284.             '@Sales/pages/input_forms/create_sales_proposal.html.twig',
  1285.             array(
  1286.                 'page_title' => 'Sales Proposal Letter',
  1287.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  1288.                 //                'clients'=>SalesOrderM::GetClientList($em),
  1289.                 'clients_by_ac_head' => SalesOrderM::GetClientListByAcHead($em),
  1290.                 'users' => Users::getUserListById($em),
  1291.                 'stages' => ProjectConstant::$projectStages,
  1292.                 'bankGuaranteeTypes' => AccountsConstant::$BankGuarnteeTypes,
  1293.                 'productList' => $productList,
  1294.                 'subCategoryList' => $subCategoryList,
  1295.                 'categoryList' => $categoryList,
  1296.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  1297.                 'igList' => $igList,
  1298.                 'unitList' => $unitList,
  1299.                 'brandList' => $brandList,
  1300.                 'brandListArray' => $brandListArray,
  1301.                 'productListArray' => $productListArray,
  1302.                 'subCategoryListArray' => $subCategoryListArray,
  1303.                 'categoryListArray' => $categoryListArray,
  1304.                 'igListArray' => $igListArray,
  1305.                 'unitListArray' => $unitListArray,
  1306.                 'currencyList' => Inventory::CurrencyList($em),
  1307.                 'sl' => $sl,
  1308.                 'pl' => $pl,
  1309.                 'hl' => $hl,
  1310.                 'workStages' => $workStages,
  1311.                 'projectList' => $projectList,
  1312.                 'projectData' => $projectData,
  1313.                 'materialData' => $materialData,
  1314.                 'boqData' => $boqData,
  1315.                 'wpData' => $wpData,
  1316.                 'offerData' => $offerData,
  1317.                 'proposalData' => $proposalData,
  1318.                 'extDocData' => $proposalData,
  1319.                 'message' => $message,
  1320.                 'salesProposalId' => $id,
  1321.                 'pl_array' => $pl_array,
  1322.                 'sl_array' => $sl_array,
  1323.                 'workStages_array' => $workStages_array,
  1324.                 'debug_data' => $debug_data,
  1325.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  1326.                 //                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  1327.             )
  1328.         );
  1329.     }
  1330.     #DemoNote create - Sadia
  1331.     //    public function CreateDemoProposal(Request $request, $id = 0)
  1332.     //    {
  1333.     //        $em = $this->getDoctrine()->getManager();
  1334.     //        if ($request->isMethod('POST')) {
  1335.     //            $em = $this->getDoctrine()->getManager();
  1336.     //            $entity_id = array_flip(GeneralConstant::$Entity_list)['SalesProposal'];
  1337.     ////            $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
  1338.     ////                array(
  1339.     ////                    'salesProposalId'=>$id, ///material
  1340.     ////
  1341.     ////                ),array('projectDate'=>'desc')
  1342.     ////            );
  1343.     ////            $client=$em->getRepository('ApplicationBundle:AccClients')->findOneBy(
  1344.     ////                array(
  1345.     ////                    'clientId'=>$projectData->getClientId(), ///material
  1346.     ////
  1347.     ////                ),array('projectDate'=>'desc')
  1348.     ////            );
  1349.     //
  1350.     //
  1351.     //            $dochash = $request->request->get('docHash');
  1352.     //            $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  1353.     //            $approveRole = $request->request->get('approvalRole');
  1354.     //            $approveHash = $request->request->get('approvalHash');
  1355.     //            if (!DocValidation::isInsertable($em, $entity_id, $dochash,
  1356.     //                $loginId, $approveRole, $approveHash, $id)
  1357.     //            ) {
  1358.     //                $this->addFlash(
  1359.     //                    'error',
  1360.     //                    'Sorry Could not insert Data.'
  1361.     //                );
  1362.     //            } else {
  1363.     //                //construct the files
  1364.     //                $file_list = array(
  1365.     //                    'product_files' => [],
  1366.     //                    'service_files' => [],
  1367.     //                    'ar_files' => [],
  1368.     //                );
  1369.     //
  1370.     //                $document_data_id=SalesOrderM::UpdateDocumentData($this->getDoctrine()->getManager(),$request->request->get('documentDataId'), $request->request,$file_list);
  1371.     //
  1372.     //
  1373.     //                $spId = SalesOrderM::CreateNewProposal($this->getDoctrine()->getManager(), $id,$document_data_id, $request->request, $dochash, $file_list,
  1374.     //                    $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  1375.     //                    $this->getLoggedUserCompanyId($request));
  1376.     //
  1377.     //                //now add Approval info
  1378.     //                $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  1379.     //                $approveRole = $request->request->get('approvalRole');  //created
  1380.     //                $options = array(
  1381.     //                    'notification_enabled' => $this->container->getParameter('notification_enabled'),
  1382.     //                    'notification_server' => $this->container->getParameter('notification_server'),
  1383.     //                    'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  1384.     //                    'url' => $this->generateUrl(
  1385.     //                        GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesProposal']]
  1386.     //                        ['entity_view_route_path_name']
  1387.     //                    )
  1388.     //                );
  1389.     //                System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
  1390.     //                    array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1391.     //                    $spId,
  1392.     //                    $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  1393.     //                );
  1394.     //                System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1395.     //                    $spId,
  1396.     //                    $loginId,
  1397.     //                    $approveRole,
  1398.     //                    $request->request->get('approvalHash'));
  1399.     //
  1400.     //                $this->addFlash(
  1401.     //                    'success',
  1402.     //                    'Sales Proposal Created'
  1403.     //                );
  1404.     //
  1405.     //                $url = $this->generateUrl(
  1406.     //                    'view_sales_proposal'
  1407.     //                );
  1408.     //
  1409.     //                System::AddNewNotification(
  1410.     //                    $this->container->getParameter('notification_enabled'),
  1411.     //                    $this->container->getParameter('notification_server'),
  1412.     //                    $request->getSession()->get(UserConstants::USER_APP_ID),
  1413.     //                    $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  1414.     //                    "Sales Order : " . $dochash . " Has Been Created And is Under Processing",
  1415.     //                    'pos',
  1416.     //                    System::getPositionIdsByDepartment($em, GeneralConstant::SALES_DEPARTMENT),
  1417.     //                    'success',
  1418.     //                    $url . "/" . $spId,
  1419.     //                    "Sales Order"
  1420.     //
  1421.     //                );
  1422.     //
  1423.     //                return $this->redirect($url . "/" . $spId);
  1424.     //            }
  1425.     //
  1426.     //        }
  1427.     //        $projectList = [];
  1428.     //        $projectData = [];
  1429.     //        $materialData = [];
  1430.     //        $boqData = [];
  1431.     //        $wpData = [];
  1432.     //        $offerData = [];
  1433.     //        $proposalData = [];
  1434.     //        $message = "";
  1435.     //        $allDetData=[];
  1436.     //        $projectList = $em->getRepository('ApplicationBundle:Project')->findBy(
  1437.     //            array(
  1438.     //                'projectStep' => array_flip(ProjectConstant::$projectSteps)['PROPOSAL'], ///material
  1439.     //                'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
  1440.     //                'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  1441.     //            ), array('projectDate' => 'desc')
  1442.     //        );
  1443.     //
  1444.     //
  1445.     //        if ($id != 0) {
  1446.     //
  1447.     //            $proposalData = $em->getRepository('ApplicationBundle:SalesProposal')->findOneBy(
  1448.     //                array(
  1449.     //                    'salesProposalId' => $id, ///material
  1450.     //
  1451.     //                )
  1452.     //            );
  1453.     //
  1454.     //            //now if its not editable, redirect to view
  1455.     //
  1456.     //            if ($proposalData) {
  1457.     //
  1458.     //
  1459.     //
  1460.     //
  1461.     //
  1462.     //            }
  1463.     //        }
  1464.     //
  1465.     //
  1466.     //        $qry = $em->getRepository("ApplicationBundle:InvProducts")->findBy(array(
  1467.     //            "status" => GeneralConstant::ACTIVE,
  1468.     //            'CompanyId' => $this->getLoggedUserCompanyId($request),
  1469.     //            'type' => 1//trade items
  1470.     //        ));
  1471.     //        $pl = [];
  1472.     //        $pl_array = [];
  1473.     //        foreach ($qry as $product) {
  1474.     //            $pl[$product->getId()] = array(
  1475.     //                'text' => $product->getName(),
  1476.     //                'name' => $product->getName(),
  1477.     //                'id' => $product->getId(),
  1478.     //                'value' => $product->getId(),
  1479.     //                'purchase_price' => $product->getPurchasePrice(),
  1480.     //                'sales_price' => $product->getSalesPrice(),
  1481.     //                'supplier_id' => $product->getBrandCompany(),
  1482.     //            );
  1483.     //            $pl_array[] = array(
  1484.     //                'text' => $product->getName(),
  1485.     //                'value' => $product->getId(),
  1486.     //                'name' => $product->getName(),
  1487.     //                'id' => $product->getId(),
  1488.     //                'purchase_price' => $product->getPurchasePrice(),
  1489.     //                'sales_price' => $product->getSalesPrice(),
  1490.     //                'supplier_id' => $product->getBrandCompany(),
  1491.     //            );
  1492.     //        }
  1493.     //        $qry = $em->getRepository("ApplicationBundle:AccService")->findBy(array(
  1494.     //            "status" => GeneralConstant::ACTIVE,
  1495.     //            'CompanyId' => $this->getLoggedUserCompanyId($request),
  1496.     ////            'type'=>1//trade items
  1497.     //        ));
  1498.     //        $sl = [];
  1499.     //        $sl_array = [];
  1500.     //        foreach ($qry as $product) {
  1501.     //            $sl[$product->getServiceId()] = array(
  1502.     //                'text' => $product->getServiceName(),
  1503.     //                'value' => $product->getServiceId(),
  1504.     //                'name' => $product->getServiceName(),
  1505.     //                'id' => $product->getServiceId(),
  1506.     //            );
  1507.     //            $sl_array[] = array(
  1508.     //                'text' => $product->getServiceName(),
  1509.     //                'value' => $product->getServiceId(),
  1510.     //                'name' => $product->getServiceName(),
  1511.     //                'id' => $product->getServiceId(),
  1512.     //            );
  1513.     //        }
  1514.     //        $qry = $em->getRepository("ApplicationBundle:ProjectWorkStage")->findBy(array(
  1515.     //            "status" => GeneralConstant::ACTIVE,
  1516.     //            'CompanyId' => $this->getLoggedUserCompanyId($request),
  1517.     ////            'type'=>1//trade items
  1518.     //        ));
  1519.     //        $workStages = [];
  1520.     //        $workStages_array = [];
  1521.     //        foreach ($qry as $product) {
  1522.     //            $workStages[$product->getProjectWorkStageId()] = array(
  1523.     //                'text' => $product->getStageName(),
  1524.     //                'value' => $product->getProjectWorkStageId(),
  1525.     //                'name' => $product->getStageName(),
  1526.     //                'id' => $product->getProjectWorkStageId(),
  1527.     //            );
  1528.     //            $workStages_array[] = array(
  1529.     //                'text' => $product->getStageName(),
  1530.     //                'value' => $product->getProjectWorkStageId(),
  1531.     //                'name' => $product->getStageName(),
  1532.     //                'id' => $product->getProjectWorkStageId(),
  1533.     //            );
  1534.     //        }
  1535.     //        $hl = Accounts::HeadList($em);
  1536.     //        $debug_data = $request->files->get('product_reference_file');
  1537.     //        $companyId = $this->getLoggedUserCompanyId($request);
  1538.     //
  1539.     //        $productListArray = [];
  1540.     //        $subCategoryListArray = [];
  1541.     //        $categoryListArray = [];
  1542.     //        $igListArray = [];
  1543.     //        $unitListArray = [];
  1544.     //        $brandListArray = [];
  1545.     //        $productList = Inventory::ProductList($em, $companyId);
  1546.     //        $subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
  1547.     //        $categoryList = Inventory::ProductCategoryList($em, $companyId);
  1548.     //        $igList = Inventory::ItemGroupList($em, $companyId);
  1549.     //        $unitList = Inventory::UnitTypeList($em);
  1550.     //        $brandList = Inventory::GetBrandList($em, $companyId);
  1551.     //        foreach ($productList as $product) $productListArray[] = $product;
  1552.     //        foreach ($categoryList as $product) $categoryListArray[] = $product;
  1553.     //        foreach ($subCategoryList as $product) $subCategoryListArray[] = $product;
  1554.     //        foreach ($igList as $product) $igListArray[] = $product;
  1555.     //        foreach ($unitList as $product) $unitListArray[] = $product;
  1556.     //        foreach ($brandList as $product) $brandListArray[] = $product;
  1557.     //        $assignedProjectSiteList=[];
  1558.     ////        if($projectId==0)
  1559.     ////        {
  1560.     ////            $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
  1561.     ////        }
  1562.     ////        else
  1563.     ////        {
  1564.     ////
  1565.     ////            $extTrans=$em->getRepository('ApplicationBundle:Project')->findOneBy(
  1566.     ////                array(
  1567.     ////                    'projectId'=>$projectId, ///material
  1568.     ////
  1569.     ////                )
  1570.     ////            );
  1571.     ////            $assignedProjectSiteList=ProjectM::ProjectSiteList($em,$projectId,$companyId);
  1572.     ////            $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
  1573.     ////
  1574.     ////
  1575.     ////            //now if its not editable, redirect to view
  1576.     ////            if($extTrans) {
  1577.     ////                if ($extTrans->getEditFlag() != 1 && $request->query->get('forceEdit',0)==0) {
  1578.     ////                    $url = $this->generateUrl(
  1579.     ////                        'view_project'
  1580.     ////                    );
  1581.     ////                    return $this->redirect($url . "/" . $projectId);
  1582.     ////                }
  1583.     ////                else
  1584.     ////                {
  1585.     ////                    $extDocData=$extTrans;
  1586.     //////                    $extDocDetailsData=Accounts::GetVoucherDataForEdit($em,$projectId);
  1587.     ////                }
  1588.     ////            }
  1589.     ////            else
  1590.     ////            {
  1591.     ////
  1592.     ////            }
  1593.     ////
  1594.     ////        }
  1595.     //
  1596.     //
  1597.     //        return $this->render('@Sales/pages/input_forms/demo.html.twig',
  1598.     //            array(
  1599.     //                'page_title' => 'Sales Proposal Letter',
  1600.     //                'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  1601.     ////                'clients'=>SalesOrderM::GetClientList($em),
  1602.     //                'clients_by_ac_head' => SalesOrderM::GetClientListByAcHead($em),
  1603.     //                'users' => Users::getUserListById($em),
  1604.     //                'stages' => ProjectConstant::$projectStages,
  1605.     //                'bankGuaranteeTypes' => AccountsConstant::$BankGuarnteeTypes,
  1606.     //                'productList' => $productList,
  1607.     //                'subCategoryList' => $subCategoryList,
  1608.     //                'categoryList' => $categoryList,
  1609.     //                'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
  1610.     //
  1611.     //                'igList' => $igList,
  1612.     //                'unitList' => $unitList,
  1613.     //                'brandList' => $brandList,
  1614.     //                'brandListArray' => $brandListArray,
  1615.     //                'productListArray' => $productListArray,
  1616.     //                'subCategoryListArray' => $subCategoryListArray,
  1617.     //                'categoryListArray' => $categoryListArray,
  1618.     //                'igListArray' => $igListArray,
  1619.     //                'unitListArray' => $unitListArray,
  1620.     //                'currencyList' => Inventory::CurrencyList($em),
  1621.     //                'sl' => $sl,
  1622.     //                'pl' => $pl,
  1623.     //                'hl' => $hl,
  1624.     //                'workStages' => $workStages,
  1625.     //                'projectList' => $projectList,
  1626.     //                'projectData' => $projectData,
  1627.     //                'materialData' => $materialData,
  1628.     //                'boqData' => $boqData,
  1629.     //                'wpData' => $wpData,
  1630.     //                'offerData' => $offerData,
  1631.     //                'proposalData' => $proposalData,
  1632.     //                'extDocData' => $proposalData,
  1633.     //                'message' => $message,
  1634.     //                'salesProposalId' => $id,
  1635.     //                'pl_array' => $pl_array,
  1636.     //                'sl_array' => $sl_array,
  1637.     //                'workStages_array' => $workStages_array,
  1638.     //                'debug_data' => $debug_data,
  1639.     //                'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  1640.     ////                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  1641.     //
  1642.     //
  1643.     //            )
  1644.     //        );
  1645.     //    }
  1646.     public function SalesProposalList(Request $request)
  1647.     {
  1648.         $em $this->getDoctrine()->getManager();
  1649.         $q $this->getDoctrine()
  1650.             ->getRepository('ApplicationBundle:SalesProposal')
  1651.             ->findBy(
  1652.                 array(
  1653.                     'status' => GeneralConstant::ACTIVE,
  1654.                 ),
  1655.                 array(
  1656.                     'salesProposalDate' => 'DESC',
  1657.                     //                    'salesOrderId'=>'DESC'
  1658.                 )
  1659.             );
  1660.         $stage_list = ['Pending''Pending''Complete''Partial'];
  1661.         $d 9;
  1662.         $data = [];
  1663.         return $this->render(
  1664.             '@Sales/pages/list/sales_proposal_list.html.twig',
  1665.             array(
  1666.                 'page_title' => 'Sales Proposals',
  1667.                 'data' => $data,
  1668.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  1669.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  1670.                 'users' => Users::getUserListById($em)
  1671.             )
  1672.         );
  1673.     }
  1674.     public function ViewSalesProposal(Request $request$id)
  1675.     {
  1676.         $em $this->getDoctrine()->getManager();
  1677.         $themeId $request->get('themeId'1);
  1678.         $defaultColEnabled = array(
  1679.             1,
  1680.             2,
  1681.             3,
  1682.             4,
  1683.             5,
  1684.             6,
  1685.             7,
  1686.             8,
  1687.             9,
  1688.             10,
  1689.             11,
  1690.             12,
  1691.             13,
  1692.             14,
  1693.             15,
  1694.             16,
  1695.             17,
  1696.             18,
  1697.             19,
  1698.             20,
  1699.             21,
  1700.             22,
  1701.             23,
  1702.             24,
  1703.             25,
  1704.             26,
  1705.             27,
  1706.             28,
  1707.             29,
  1708.             30,
  1709.             3132
  1710.         );
  1711.         $columnsEnabled $request->get('columnsEnabled'$defaultColEnabled);
  1712.         $config $request->get('config', []);
  1713.         if (is_string($columnsEnabled)) $columnsEnabled json_decode($columnsEnabledtrue);
  1714.         if (is_string($config)) $config json_decode($configtrue);
  1715.         if ($config == null$config = [];
  1716.         if ($columnsEnabled == null$columnsEnabled = [];
  1717.         $dt SalesOrderM::GetProposalDetails($em$id$columnsEnabled$config);
  1718.         if (!$dt) {
  1719.             $url $this->generateUrl(
  1720.                 'create_sales_proposal'
  1721.             );
  1722.             $this->addFlash(
  1723.                 'error',
  1724.                 'The Document You asked for was not found.'
  1725.             );
  1726.             return $this->redirect($url "/" $id);
  1727.         }
  1728.         $stage_list ProjectConstant::$projectStages;
  1729.         $status_list ProjectConstant::$projectStatus;
  1730.         $steps_list ProjectConstant::$projectSteps;
  1731.         if ($request->get('returnJson'0) == 1) {
  1732.             return new JsonResponse(
  1733.                 array(
  1734.                     'page_title' => 'Proposal Letter',
  1735.                     'data' => $dt,
  1736.                     'config' => $config,
  1737.                     'columnsEnabled' => $columnsEnabled,
  1738.                     'theme_id' => $themeId,
  1739.                     //                'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
  1740.                     //                'wpData'=>SalesOrderM::GetWpDetails($em,$id),
  1741.                     'clientList' => SalesOrderM::GetClientList($em),
  1742.                     'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  1743.                     'stageList' => $stage_list//
  1744.                     'statusList' => $status_list,
  1745.                     'stepsList' => $steps_list,
  1746.                     'stage_list' => ProjectM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)), //
  1747.                     'auto_created' => $dt['auto_created'],
  1748.                     'approval_data' => System::checkIfApprovalExists(
  1749.                         $em,
  1750.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1751.                         $id,
  1752.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  1753.                     ),
  1754.                     'document_log' => $dt['auto_created'] == System::getDocumentLog(
  1755.                         $this->getDoctrine()->getManager(),
  1756.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1757.                         $id,
  1758.                         $dt['created_by'],
  1759.                         $dt['edited_by']
  1760.                     ) : [],
  1761.                     'users' => Users::getUserListById($em),
  1762.                     'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  1763.                 )
  1764.             );
  1765.         } else
  1766.             return $this->render(
  1767.                 '@Sales/pages/views/view_sales_proposal.html.twig',
  1768.                 array(
  1769.                     'page_title' => 'Proposal Letter',
  1770.                     'data' => $dt,
  1771.                     'config' => $config,
  1772.                     'columnsEnabled' => $columnsEnabled,
  1773.                     'theme_id' => $themeId,
  1774.                     //                'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
  1775.                     //                'wpData'=>SalesOrderM::GetWpDetails($em,$id),
  1776.                     'clientList' => SalesOrderM::GetClientList($em),
  1777.                     'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  1778.                     'stageList' => $stage_list,
  1779.                     'statusList' => $status_list,
  1780.                     'stepsList' => $steps_list,
  1781.                     'stage_list' => ProjectM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)),
  1782.                     'auto_created' => $dt['auto_created'],
  1783.                     'approval_data' => System::checkIfApprovalExists(
  1784.                         $em,
  1785.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1786.                         $id,
  1787.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  1788.                     ),
  1789.                     'document_log' => $dt['auto_created'] == System::getDocumentLog(
  1790.                         $this->getDoctrine()->getManager(),
  1791.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1792.                         $id,
  1793.                         $dt['created_by'],
  1794.                         $dt['edited_by']
  1795.                     ) : [],
  1796.                     'users' => Users::getUserListById($em),
  1797.                     'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  1798.                 )
  1799.             );
  1800.     }
  1801.     public function PrintSalesProposal(Request $request$id)
  1802.     {
  1803.         $em $this->getDoctrine()->getManager();
  1804.         $stage_list ProjectConstant::$projectStages;
  1805.         $status_list ProjectConstant::$projectStatus;
  1806.         $steps_list ProjectConstant::$projectSteps;
  1807.         $themeId $request->get('themeId'1);
  1808.         $defaultColEnabled = array(
  1809.             1,
  1810.             2,
  1811.             3,
  1812.             4,
  1813.             5,
  1814.             6,
  1815.             7,
  1816.             8,
  1817.             9,
  1818.             10,
  1819.             11,
  1820.             12,
  1821.             13,
  1822.             14,
  1823.             15,
  1824.             16,
  1825.             17,
  1826.             18,
  1827.             19,
  1828.             20,
  1829.             21,
  1830.             22,
  1831.             23,
  1832.             24,
  1833.             25,
  1834.             26,
  1835.             27,
  1836.             28,
  1837.             29,
  1838.             30,
  1839.             31
  1840.         );
  1841.         $columnsEnabled $request->get('columnsEnabled'$defaultColEnabled);
  1842.         if ($themeId == 2)
  1843.             $columnsEnabled array_diff($columnsEnabled, [13242630311968152021222329]);
  1844.         if ($request->get('printType''technical_proposal') == 'technical_proposal') {
  1845.             $columnsEnabled array_diff($columnsEnabled, [6810121518]);
  1846.         }
  1847.         $config $request->get('config', []);
  1848.         if (is_string($columnsEnabled)) $columnsEnabled json_decode($columnsEnabledtrue);
  1849.         if (is_string($config)) $config json_decode($configtrue);
  1850.         if ($config == null$config = [];
  1851.         if ($columnsEnabled == null$columnsEnabled = [];
  1852.         $dt SalesOrderM::GetProposalDetails($em$id$columnsEnabled$config);
  1853.         if (!$dt) {
  1854.             $url $this->generateUrl(
  1855.                 'create_sales_proposal'
  1856.             );
  1857.             $this->addFlash(
  1858.                 'error',
  1859.                 'Please Create Offer for the project 1st.'
  1860.             );
  1861.             return $this->redirect($url "/" $id);
  1862.         }
  1863.         $company_data Company::getCompanyData($em1);
  1864.         $document_mark = array(
  1865.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  1866.             'copy' => ''
  1867.         );
  1868.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  1869.             $html $this->renderView(
  1870.                 '@Sales/pages/print/print_sales_proposal.html.twig',
  1871.                 array(
  1872.                     //full array here
  1873.                     'pdf' => true,
  1874.                     'config' => $config,
  1875.                     'columnsEnabled' => $columnsEnabled,
  1876.                     'theme_id' => $themeId,
  1877.                     'page_title' => 'Offer ' $dt['doc_hash'] . ' (' $dt['general_data']->getClientname() . ')',
  1878.                     'export' => 'pdf,print',
  1879.                     'data' => $dt,
  1880.                     'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  1881.                     'document_mark_image' => $document_mark['original'],
  1882.                     'company_name' => $company_data->getName(),
  1883.                     'company_data' => $company_data,
  1884.                     'company_address' => $company_data->getAddress(),
  1885.                     'company_image' => $company_data->getImage(),
  1886.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  1887.                     'red' => 0,
  1888.                     //                'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
  1889.                     //                'wpData'=>SalesOrderM::GetWpDetails($em,$id),
  1890.                     'clientList' => SalesOrderM::GetClientList($em),
  1891.                     'stageList' => $stage_list,
  1892.                     'statusList' => $status_list,
  1893.                     'stepsList' => $steps_list,
  1894.                     'stage_list' => ProjectM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)),
  1895.                     'auto_created' => $dt['auto_created'],
  1896.                     'approval_data' => System::checkIfApprovalExists(
  1897.                         $em,
  1898.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1899.                         $id,
  1900.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  1901.                     ),
  1902.                     'document_log' => $dt['auto_created'] == System::getDocumentLog(
  1903.                         $this->getDoctrine()->getManager(),
  1904.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1905.                         $id,
  1906.                         $dt['created_by'],
  1907.                         $dt['edited_by']
  1908.                     ) : [],
  1909.                     'users' => Users::getUserListById($em),
  1910.                     'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  1911.                 )
  1912.             );
  1913.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  1914.                 //                'orientation' => 'landscape',
  1915.                 'enable-javascript' => true,
  1916.                 'javascript-delay' => 2000,
  1917.                 'no-stop-slow-scripts' => false,
  1918.                 'no-background' => false,
  1919.                 'lowquality' => false,
  1920.                 'encoding' => 'utf-8',
  1921.                 //            'images' => true,
  1922.                 //            'cookie' => array(),
  1923.                 'dpi' => 300,
  1924.                 'image-dpi' => 300,
  1925.                 //                'enable-external-links' => true,
  1926.                 //                'enable-internal-links' => true
  1927.             ));
  1928.             return new Response(
  1929.                 $pdf_response,
  1930.                 200,
  1931.                 array(
  1932.                     'Content-Type' => 'application/pdf',
  1933.                     'Content-Disposition' => $themeId == 'attachment; filename="PI_' $dt['doc_hash'] . ' (' $dt['general_data']->getClientname() . ')' '.pdf"' :
  1934.                         'attachment; filename="Offer_' $dt['doc_hash'] . ' (' $dt['general_data']->getClientname() . ')' '.pdf"'
  1935.                 )
  1936.             );
  1937.         }
  1938.         return $this->render(
  1939.             '@Sales/pages/print/print_sales_proposal.html.twig',
  1940.             array(
  1941.                 'export' => 'pdf,print',
  1942.                 'config' => $config,
  1943.                 'columnsEnabled' => $columnsEnabled,
  1944.                 'theme_id' => $themeId,
  1945.                 'document_mark_image' => $document_mark['original'],
  1946.                 'company_name' => $company_data->getName(),
  1947.                 'company_data' => $company_data,
  1948.                 'company_address' => $company_data->getAddress(),
  1949.                 'company_image' => $company_data->getImage(),
  1950.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  1951.                 'red' => 0,
  1952.                 'page_title' => 'Proposal Letter',
  1953.                 'data' => $dt,
  1954.                 //                'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
  1955.                 //                'wpData'=>SalesOrderM::GetWpDetails($em,$id),
  1956.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  1957.                 'clientList' => SalesOrderM::GetClientList($em),
  1958.                 'stageList' => $stage_list,
  1959.                 'statusList' => $status_list,
  1960.                 'stepsList' => $steps_list,
  1961.                 'stage_list' => ProjectM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)),
  1962.                 'auto_created' => $dt['auto_created'],
  1963.                 'approval_data' => System::checkIfApprovalExists(
  1964.                     $em,
  1965.                     array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1966.                     $id,
  1967.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  1968.                 ),
  1969.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  1970.                     $this->getDoctrine()->getManager(),
  1971.                     array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  1972.                     $id,
  1973.                     $dt['created_by'],
  1974.                     $dt['edited_by']
  1975.                 ) : [],
  1976.                 'users' => Users::getUserListById($em),
  1977.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  1978.             )
  1979.         );
  1980.     }
  1981.     public function CreateSoAmendment(Request $request$id 0)
  1982.     {
  1983.         $em $this->getDoctrine()->getManager();
  1984.         if ($request->isMethod('POST')) {
  1985.             $em $this->getDoctrine()->getManager();
  1986.             $entity_id array_flip(GeneralConstant::$Entity_list)['SoAmendment']; //change
  1987.             //            $proj_here = $this->getDoctrine()
  1988.             //                ->getRepository('ApplicationBundle:SoAmendment')
  1989.             //                ->findOneBy(
  1990.             //                    array(
  1991.             //                        'soAmendmentId' => $id
  1992.             //                    )
  1993.             //                );
  1994.             $dochash $request->request->get('docHash');  //change
  1995.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  1996.             $approveRole $request->request->get('approvalRole');
  1997.             $approveHash $request->request->get('approvalHash');
  1998.             if (!DocValidation::isInsertable(
  1999.                 $em,
  2000.                 $entity_id,
  2001.                 $dochash,
  2002.                 $loginId,
  2003.                 $approveRole,
  2004.                 $approveHash,
  2005.                 $id
  2006.             )) {
  2007.                 $this->addFlash(
  2008.                     'error',
  2009.                     'Sorry Could not insert Data.'
  2010.                 );
  2011.             } else {
  2012.                 //construct the files
  2013.                 $file_list = array(
  2014.                     'product_files' => [],
  2015.                     'service_files' => [],
  2016.                     'ar_files' => [],
  2017.                 );
  2018.                 $soAmendmentId SalesOrderM::CreateNewSoAmendment(
  2019.                     $this->getDoctrine()->getManager(),
  2020.                     $id,
  2021.                     $request->request,
  2022.                     $dochash,
  2023.                     $file_list,
  2024.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  2025.                     $this->getLoggedUserCompanyId($request)
  2026.                 );
  2027.                 //now add Approval info
  2028.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  2029.                 $approveRole $request->request->get('approvalRole');  //created
  2030.                 $options = array(
  2031.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2032.                     'notification_server' => $this->container->getParameter('notification_server'),
  2033.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  2034.                     'url' => $this->generateUrl(
  2035.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SoAmendment']]['entity_view_route_path_name']
  2036.                     )
  2037.                 );
  2038.                 System::setApprovalInfo(
  2039.                     $this->getDoctrine()->getManager(),
  2040.                     $options,
  2041.                     array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
  2042.                     $soAmendmentId,
  2043.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  2044.                 );
  2045.                 System::createEditSignatureHash(
  2046.                     $this->getDoctrine()->getManager(),
  2047.                     array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
  2048.                     $soAmendmentId,
  2049.                     $loginId,
  2050.                     $approveRole,
  2051.                     $request->request->get('approvalHash')
  2052.                 );
  2053.                 $this->addFlash(
  2054.                     'success',
  2055.                     'Sales Order Amendment Request Created'
  2056.                 );
  2057.                 $url $this->generateUrl(
  2058.                     'view_so_amendment'
  2059.                 );
  2060.                 return $this->redirect($url "/" $soAmendmentId);
  2061.             }
  2062.         }
  2063.         $projectList = [];
  2064.         $projectData = [];
  2065.         $materialData = [];
  2066.         $boqData = [];
  2067.         $message "";
  2068.         $projectList $em->getRepository('ApplicationBundle:Project')->findBy(
  2069.             array(
  2070.                 'projectStep' => array_flip(ProjectConstant::$projectSteps)['BILL OF QUANTITY PLAN'], ///material
  2071.                 'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
  2072.                 'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  2073.             ),
  2074.             array('projectDate' => 'desc')
  2075.         );
  2076.         $companyId $this->getLoggedUserCompanyId($request);
  2077.         $productListArray = [];
  2078.         $subCategoryListArray = [];
  2079.         $categoryListArray = [];
  2080.         $igListArray = [];
  2081.         $unitListArray = [];
  2082.         $productList Inventory::ProductList($em$companyId1);
  2083.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  2084.         $categoryList Inventory::ProductCategoryList($em$companyId);
  2085.         $igList Inventory::ItemGroupList($em$companyId);
  2086.         $unitList Inventory::UnitTypeList($em);
  2087.         foreach ($productList as $product) {
  2088.             $productListArray[] = $product;
  2089.         }
  2090.         foreach ($categoryList as $product) {
  2091.             $categoryListArray[] = $product;
  2092.         }
  2093.         foreach ($subCategoryList as $product) {
  2094.             $subCategoryListArray[] = $product;
  2095.         }
  2096.         foreach ($igList as $product) {
  2097.             $igListArray[] = $product;
  2098.         }
  2099.         foreach ($unitList as $product) {
  2100.             $unitListArray[] = $product;
  2101.         }
  2102.         $brandList Inventory::GetBrandList($em$companyId);
  2103.         $brandListArray = [];
  2104.         foreach ($brandList as $product) {
  2105.             $brandListArray[] = $product;
  2106.         }
  2107.         $qry $em->getRepository("ApplicationBundle:AccService")->findBy(array(
  2108.             "status" => GeneralConstant::ACTIVE,
  2109.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  2110.             //            'type'=>1//trade items
  2111.         ));
  2112.         $sl = [];
  2113.         $sl_array = [];
  2114.         foreach ($qry as $product) {
  2115.             $sl[$product->getServiceId()] = array(
  2116.                 'text' => $product->getServiceName(),
  2117.                 'value' => $product->getServiceId(),
  2118.                 'name' => $product->getServiceName(),
  2119.                 'id' => $product->getServiceId(),
  2120.             );
  2121.             $sl_array[] = array(
  2122.                 'text' => $product->getServiceName(),
  2123.                 'value' => $product->getServiceId(),
  2124.                 'name' => $product->getServiceName(),
  2125.                 'id' => $product->getServiceId(),
  2126.             );
  2127.         }
  2128.         $hl Accounts::HeadList($em);
  2129.         $debug_data $request->files->get('product_reference_file');
  2130.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2131.         $userBranchIdList $request->getSession()->get('branchIdList');
  2132.         if ($userBranchIdList == null$userBranchIdList = [];
  2133.         $userBranchId $request->getSession()->get('branchId');
  2134.         return $this->render(
  2135.             '@Sales/pages/input_forms/create_so_amendment.html.twig',
  2136.             array(
  2137.                 'page_title' => 'SO Amendment',
  2138.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  2139.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  2140.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  2141.                 //                'clients'=>SalesOrderM::GetClientList($em),
  2142.                 //                'clients_by_ac_head'=>SalesOrderM::GetClientListByAcHead($em),
  2143.                 'users' => Users::getUserListById($em),
  2144.                 'stages' => ProjectConstant::$projectStages,
  2145.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  2146.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  2147.                 'sl' => $sl,
  2148.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  2149.                 'productList' => $productList,
  2150.                 'subCategoryList' => $subCategoryList,
  2151.                 'categoryList' => $categoryList,
  2152.                 'igList' => $igList,
  2153.                 'unitList' => $unitList,
  2154.                 'brandList' => $brandList,
  2155.                 'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  2156.                 'brandListArray' => $brandListArray,
  2157.                 'productListArray' => $productListArray,
  2158.                 'subCategoryListArray' => $subCategoryListArray,
  2159.                 'categoryListArray' => $categoryListArray,
  2160.                 'igListArray' => $igListArray,
  2161.                 'unitListArray' => $unitListArray,
  2162.                 'hl' => $hl,
  2163.                 'projectList' => $projectList,
  2164.                 'projectData' => $projectData,
  2165.                 'materialData' => $materialData,
  2166.                 'boqData' => $boqData,
  2167.                 'message' => $message,
  2168.                 'projectId' => $id,
  2169.                 'sl_array' => $sl_array,
  2170.                 'debug_data' => $debug_data,
  2171.                 'canUseOwnPrice' => 0,
  2172.                 'canSkipProductId' => 0,
  2173.                 'canUseZeroPrice' => 0,
  2174.                 'canSetDiscount' => 0,
  2175.                 'maxIndividualDiscountAllowed' => 0,
  2176.                 'maxGrossDiscountAllowed' => 0,
  2177.                 //                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  2178.             )
  2179.         );
  2180.     }
  2181.     public function CheckCreditLimitValidityForSalesOrder(Request $request$id 0)
  2182.     {
  2183.         $em $this->getDoctrine()->getManager();
  2184.         $repeatCount 1;
  2185.         $spec_item_id 0;
  2186.         $skip_ids = [];
  2187.         $so_ids = [];
  2188.         $succeeded_so_ids = [];
  2189.         $fail_reasons = [];
  2190.         $clearUnnecessaryOnly 0;
  2191.         $creditLimitEnabled 0;
  2192.         if ($request->query->has('soIds'))
  2193.             $so_ids $request->query->get('soIds');
  2194.         if ($request->request->has('soIds'))
  2195.             $so_ids $request->request->get('soIds');
  2196.         $docs $em->getRepository('ApplicationBundle:SalesOrder')->findBy(
  2197.             array(
  2198.                 'salesOrderId' => $so_ids,
  2199.                 'orderConfirmationPendingFlag' => 1,
  2200.                 'draftFlag' => [0null],
  2201.                 //                        'approved'=>GeneralConstant::APPROVAL_STATUS_PENDING
  2202.                 //                        'id' => $item_id
  2203.             )
  2204.         );
  2205.         foreach ($docs as $doc) {
  2206.             $client $em
  2207.                 ->getRepository('ApplicationBundle:AccClients')
  2208.                 ->findOneby(array(
  2209.                     'clientId' => $doc->getClientId()
  2210.                 ));
  2211.             $creditLimitEnabled $client->getCreditLimitEnabled() == 0;
  2212.             //check if credit limit is ok
  2213.             $order_confirmation_pending_flag $doc->getOrderConfirmationPendingFlag();
  2214.             $freezeBalance $client->getFreezeBalance();
  2215.             $client_credit_limit_effective = ($client->getCreditLimit() - $freezeBalance) - round($doc->getSoAmount()) - $client->getClientDue();
  2216.             if ($client_credit_limit_effective && $client->getCreditLimitEnabled() == 1) {
  2217.                 $fail_reasons[] = "Credit Limit Exceeded";
  2218.                 $em->flush();
  2219.                 //                continue;
  2220.             } else {
  2221.             }
  2222.             //confirm if not approved
  2223.             if ($doc->getApproved() != GeneralConstant::APPROVED) {
  2224.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  2225.                 $approveRole 1;  //created
  2226.                 $options = array(
  2227.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2228.                     'notification_server' => $this->container->getParameter('notification_server'),
  2229.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  2230.                     'url' => $this->generateUrl(
  2231.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
  2232.                     )
  2233.                 );
  2234.                 System::setApprovalInfo(
  2235.                     $this->getDoctrine()->getManager(),
  2236.                     $options,
  2237.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  2238.                     $doc->getSalesOrderId(),
  2239.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  2240.                 );
  2241.                 System::createEditSignatureHash(
  2242.                     $this->getDoctrine()->getManager(),
  2243.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  2244.                     $doc->getSalesOrderId(),
  2245.                     $loginId,
  2246.                     $approveRole,
  2247.                     $request->request->get('approvalHash')
  2248.                 );
  2249.                 //                $doc->setClientCreatedFlag($post->get('clientCreatedFlag', null));
  2250.                 //                $doc->setDraftFlag($post->get('draftFlag', null));
  2251.                 $doc->setOrderConfirmationPendingFlag(0);
  2252.                 $doc->setStage(GeneralConstant::STAGE_INITIATED);
  2253.                 $em->flush();
  2254.                 $succeeded_so_ids[] = $doc->getSalesOrderId();
  2255.             } else
  2256.                 $fail_reasons[] = "Document is already Approved";
  2257.         }
  2258.         return new JsonResponse(array(
  2259.             'success' => (!empty($succeeded_so_ids)) ? true false,
  2260.             'skipIds' => [],
  2261.             'reasons' => $fail_reasons,
  2262.             'creditLimitEnabled' => $creditLimitEnabled,
  2263.             'succeeded_so_ids' => $succeeded_so_ids
  2264.         ));
  2265.     }
  2266.     public function ConfirmClientSalesOrder(Request $request$id 0)
  2267.     {
  2268.         $em $this->getDoctrine()->getManager();
  2269.         $repeatCount 1;
  2270.         $spec_item_id 0;
  2271.         $skip_ids = [];
  2272.         $so_ids = [];
  2273.         $succeeded_so_ids = [];
  2274.         $fail_reasons = [];
  2275.         $clearUnnecessaryOnly 0;
  2276.         $creditLimitEnabled 0;
  2277.         if ($request->query->has('soIds'))
  2278.             $so_ids $request->query->get('soIds');
  2279.         if ($request->request->has('soIds'))
  2280.             $so_ids $request->request->get('soIds');
  2281.         $docs $em->getRepository('ApplicationBundle:SalesOrder')->findBy(
  2282.             array(
  2283.                 'salesOrderId' => $so_ids,
  2284.                 'orderConfirmationPendingFlag' => 1,
  2285.                 'draftFlag' => [0null],
  2286.                 //                        'approved'=>GeneralConstant::APPROVAL_STATUS_PENDING
  2287.                 //                        'id' => $item_id
  2288.             )
  2289.         );
  2290.         if (empty($docs))
  2291.             $fail_reasons[] = "Document Not Found in Pending List.";
  2292.         foreach ($docs as $doc) {
  2293.             $client $em
  2294.                 ->getRepository('ApplicationBundle:AccClients')
  2295.                 ->findOneby(array(
  2296.                     'clientId' => $doc->getClientId()
  2297.                 ));
  2298.             $creditLimitEnabled $client->getCreditLimitEnabled() == 0;
  2299.             //check if credit limit is ok
  2300.             $order_confirmation_pending_flag $doc->getOrderConfirmationPendingFlag();
  2301.             $freezeBalance $client->getFreezeBalance();
  2302.             $client_credit_limit_effective = ($client->getCreditLimit() - $freezeBalance) - round($doc->getSoAmount()) - $client->getClientDue();
  2303.             if ($client_credit_limit_effective && $client->getCreditLimitEnabled() == 1) {
  2304.                 $doc->setCreditLimitExceededFlag(1);
  2305.                 $order_confirmation_pending_flag 1;
  2306.                 $doc->setOrderConfirmationPendingFlag($order_confirmation_pending_flag);
  2307.                 $fail_reasons[] = "Credit Limit Exceeded";
  2308.                 $em->flush();
  2309.                 continue;
  2310.             } else {
  2311.                 $doc->setCreditLimitExceededFlag(0);
  2312.                 $em->flush();
  2313.             }
  2314.             //confirm if not approved
  2315.             if ($doc->getApproved() != GeneralConstant::APPROVED) {
  2316.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  2317.                 $approveRole 1;  //created
  2318.                 $options = array(
  2319.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2320.                     'notification_server' => $this->container->getParameter('notification_server'),
  2321.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  2322.                     'url' => $this->generateUrl(
  2323.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
  2324.                     )
  2325.                 );
  2326.                 System::setApprovalInfo(
  2327.                     $this->getDoctrine()->getManager(),
  2328.                     $options,
  2329.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  2330.                     $doc->getSalesOrderId(),
  2331.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  2332.                 );
  2333.                 System::createEditSignatureHash(
  2334.                     $this->getDoctrine()->getManager(),
  2335.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  2336.                     $doc->getSalesOrderId(),
  2337.                     $loginId,
  2338.                     $approveRole,
  2339.                     $request->request->get('approvalHash')
  2340.                 );
  2341.                 //                $doc->setClientCreatedFlag($post->get('clientCreatedFlag', null));
  2342.                 //                $doc->setDraftFlag($post->get('draftFlag', null));
  2343.                 $doc->setOrderConfirmationPendingFlag(0);
  2344.                 $doc->setStage(GeneralConstant::STAGE_INITIATED);
  2345.                 $em->flush();
  2346.                 $succeeded_so_ids[] = $doc->getSalesOrderId();
  2347.             } else
  2348.                 $fail_reasons[] = "Document is already Approved";
  2349.         }
  2350.         return new JsonResponse(array(
  2351.             'success' => (!empty($succeeded_so_ids)) ? true false,
  2352.             'skipIds' => [],
  2353.             'reasons' => $fail_reasons,
  2354.             'creditLimitEnabled' => $creditLimitEnabled,
  2355.             'succeeded_so_ids' => $succeeded_so_ids
  2356.         ));
  2357.     }
  2358.     public function SubmitClientSalesOrder(Request $request$id 0)
  2359.     {
  2360.         $em $this->getDoctrine()->getManager();
  2361.         $repeatCount 1;
  2362.         $spec_item_id 0;
  2363.         $skip_ids = [];
  2364.         $so_ids = [];
  2365.         $succeeded_so_ids = [];
  2366.         $clearUnnecessaryOnly 0;
  2367.         if ($request->query->has('soIds'))
  2368.             $so_ids $request->query->get('soIds');
  2369.         if ($request->request->has('soIds'))
  2370.             $so_ids $request->request->get('soIds');
  2371.         $docs $em->getRepository('ApplicationBundle:SalesOrder')->findBy(
  2372.             array(
  2373.                 'salesOrderId' => $so_ids,
  2374.                 'draftFlag' => 1,
  2375.                 //                        'approved'=>GeneralConstant::APPROVAL_STATUS_PENDING
  2376.                 //                        'id' => $item_id
  2377.             )
  2378.         );
  2379.         foreach ($docs as $doc) {
  2380.             //confirm if not approved
  2381.             if ($doc->getApproved() != GeneralConstant::APPROVED) {
  2382.                 //                $doc->setClientCreatedFlag($post->get('clientCreatedFlag', null));
  2383.                 $doc->setDraftFlag(0);
  2384.                 $doc->setOrderConfirmationPendingFlag(1);
  2385.                 $doc->setStage(GeneralConstant::STAGE_PENDING_CONFIRMATION);
  2386.                 $em->flush();
  2387.                 $succeeded_so_ids[] = $doc->getSalesOrderId();
  2388.             }
  2389.         }
  2390.         return new JsonResponse(array(
  2391.             'success' => (!empty($succeeded_so_ids)) ? true false,
  2392.             'skipIds' => [],
  2393.             'succeeded_so_ids' => $succeeded_so_ids
  2394.         ));
  2395.     }
  2396.     public function ProcessDeliveryOnDirectOrder(Request $request$id 0)
  2397.     {
  2398.         $em $this->getDoctrine()->getManager();
  2399.         $hasProject 0;
  2400.         $extId $id;
  2401.         $projectId 0;
  2402.         if ($request->query->has('soId'))
  2403.             $id $request->query->get('soId');
  2404.         if ($request->request->has('soId'))
  2405.             $id $request->request->get('soId');
  2406.         if ($id == 0)
  2407.             return new JsonResponse(array(
  2408.                 'success' => false
  2409.             ));
  2410.         $companyId $this->getLoggedUserCompanyId($request);
  2411.         $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  2412.             array(
  2413.                 'salesOrderId' => $id
  2414.             )
  2415.         );
  2416.         $drId 0;
  2417.         $pvId 0;
  2418.         //        if($so->getPaymentProcessType()==1) //with order auto
  2419.         //        {
  2420.         //           $pvId =SalesOrderM::addPaymentAutomaticallyForSO($em,$so);
  2421.         //        }
  2422.         if ($so->getDeliveryProcessType() == 1//with order auto
  2423.         {
  2424.             $drId SalesOrderM::CreateNewDeliveryReceiptFromScheduleForSo($em$so, [], $so->getCreatedLoginId(), $so->getCompanyId(), 1);
  2425.         }
  2426.         if ($drId != 0)
  2427.             return new JsonResponse(array(
  2428.                 'success' => true,
  2429.                 'billIds' => [],
  2430.                 'drIds' => [$drId],
  2431.                 'pmntTransIds' => [$pvId],
  2432.                 'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  2433.                 'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  2434.                 'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  2435.                 'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  2436.             ));
  2437.         return new JsonResponse(array(
  2438.             'success' => false
  2439.         ));
  2440.     }
  2441.     public function ProcessPaymentOnDirectOrder(Request $request$id 0)
  2442.     {
  2443.         $em $this->getDoctrine()->getManager();
  2444.         $hasProject 0;
  2445.         $extId $id;
  2446.         $projectId 0;
  2447.         if ($request->query->has('soId'))
  2448.             $id $request->query->get('soId');
  2449.         if ($request->request->has('soId'))
  2450.             $id $request->request->get('soId');
  2451.         if ($id == 0)
  2452.             return new JsonResponse(array(
  2453.                 'success' => false
  2454.             ));
  2455.         $companyId $this->getLoggedUserCompanyId($request);
  2456.         $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  2457.             array(
  2458.                 'salesOrderId' => $id
  2459.             )
  2460.         );
  2461.         $drId 0;
  2462.         $pvId 0;
  2463.         if ($so->getPaymentProcessType() == 1//with order auto
  2464.         {
  2465.             $pvId SalesOrderM::addPaymentAutomaticallyForSO($em$so);
  2466.         }
  2467.         //        if($so->getDeliveryProcessType()==1) //with order auto
  2468.         //        {
  2469.         //            $drId= SalesOrderM::CreateNewDeliveryReceiptFromScheduleForSo($em, $so, [], $so->getCreatedLoginId(), $so->getCompanyId(), 1);
  2470.         //        }
  2471.         if ($pvId != 0)
  2472.             return new JsonResponse(array(
  2473.                 'success' => true,
  2474.                 'billIds' => [],
  2475.                 'drIds' => [$drId],
  2476.                 'pmntTransIds' => [$pvId],
  2477.                 'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  2478.                 'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  2479.                 'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  2480.                 'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  2481.             ));
  2482.         return new JsonResponse(array(
  2483.             'success' => false
  2484.         ));
  2485.     }
  2486.     public function BackgroundApproveOrder(Request $request$id 0)
  2487.     {
  2488.         $em $this->getDoctrine()->getManager();
  2489.         $hasProject 0;
  2490.         $extId $id;
  2491.         $projectId 0;
  2492.         $companyId $this->getLoggedUserCompanyId($request);
  2493.         $orderId $id;
  2494.         //testing direct sale
  2495.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  2496.             //            if($request->request->has('getInitialData'))
  2497.             $em $this->getDoctrine()->getManager();
  2498.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  2499.             $approveRole 1;  //created
  2500.             $options = array(
  2501.                 'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2502.                 'notification_server' => $this->container->getParameter('notification_server'),
  2503.                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  2504.                 'url' => $this->generateUrl(
  2505.                     GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
  2506.                 )
  2507.             );
  2508.             System::takeFullApproveActions(
  2509.                 $em,
  2510.                 array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  2511.                 $orderId
  2512.             );
  2513.             $url $this->generateUrl(
  2514.                 'view_sales_order'
  2515.             );
  2516.             if ($request->request->has('returnJson')) {
  2517.                 $order $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  2518.                     array(
  2519.                         'salesOrderId' => $orderId///material
  2520.                     )
  2521.                 );
  2522.                 $clnt $em->getRepository('ApplicationBundle:AccClients')->findOneBy(
  2523.                     array(
  2524.                         'clientId' => $order->getClientId(), ///material
  2525.                     )
  2526.                 );
  2527.                 $drs $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  2528.                     array(
  2529.                         'salesOrderId' => $orderId///material
  2530.                     )
  2531.                 );
  2532.                 $bills $em->getRepository('ApplicationBundle:SalesInvoice')->findBy(
  2533.                     array(
  2534.                         'salesOrderId' => $orderId///material
  2535.                     )
  2536.                 );
  2537.                 $billIds = [];
  2538.                 $drIds = [];
  2539.                 $pmntTransIds = [];
  2540.                 foreach ($bills as $bill)
  2541.                     $billIds[] = $bill->getSalesInvoiceId();
  2542.                 foreach ($drs as $dr)
  2543.                     $drIds[] = $dr->getDeliveryReceiptId();
  2544.                 $pmntTransIds json_decode($order->getOrderPaymentReceiptVoucherIds(), true);
  2545.                 if ($pmntTransIds == null)
  2546.                     $pmntTransIds = [];
  2547.                 return new JsonResponse(array(
  2548.                     'success' => true,
  2549.                     'documentHash' => $order->getDocumentHash(),
  2550.                     'documentId' => $orderId,
  2551.                     'documentIdPadded' => str_pad($orderId8'0'STR_PAD_LEFT),
  2552.                     'documentDate' => $order->getSalesOrderDate()->format('Y-m-d'),
  2553.                     'deliveryProcessType' => $order->getDeliveryProcessType(),
  2554.                     'paymentProcessType' => $order->getPaymentProcessType(),
  2555.                     'clientId' => $order->getClientId(),
  2556.                     'clientMail' => $clnt->getEmail() == null '' $clnt->getEmail(),
  2557.                     'billIds' => $billIds,
  2558.                     'drIds' => $drIds,
  2559.                     'pmntTransIds' => $pmntTransIds,
  2560.                     'viewUrl' => $url "/" $orderId,
  2561.                     'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  2562.                     'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  2563.                     'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  2564.                     'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  2565.                 ));
  2566.             } else {
  2567.                 $this->addFlash(
  2568.                     'success',
  2569.                     'New Sales order Created'
  2570.                 );
  2571.                 return $this->redirect($url "/" $id);
  2572.             }
  2573.         }
  2574.         return new JsonResponse(array(
  2575.             'success' => true,
  2576.         ));
  2577.     }
  2578.     public function CreateNewOrder(Request $request$id 0)
  2579.     {
  2580.         $em $this->getDoctrine()->getManager();
  2581.         $hasProject 0;
  2582.         $extId $id;
  2583.         $projectId 0;
  2584.         $companyId $this->getLoggedUserCompanyId($request);
  2585.         if ($request->query->has('projectId'))
  2586.             if ($request->query->get('projectId') != 0) {
  2587.                 $hasProject 1;
  2588.                 $projectId $request->query->get('projectId');
  2589.             }
  2590.         //testing direct sale
  2591.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  2592.             //            if($request->request->has('getInitialData'))
  2593.             $em $this->getDoctrine()->getManager();
  2594.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesOrder']; //change
  2595.             $dochash $request->request->get('docHash'); //change
  2596.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  2597.             $approveRole $request->request->get('approvalRole');
  2598.             $approveHash $request->request->get('approvalHash');
  2599.             if (!DocValidation::isInsertable(
  2600.                 $em,
  2601.                 $entity_id,
  2602.                 $dochash,
  2603.                 $loginId,
  2604.                 $approveRole,
  2605.                 $approveHash,
  2606.                 $id,
  2607.                 $request->request->has('skipApprovalFlag') ? $request->request->get('skipApprovalFlag') : 0,
  2608.                 $companyId
  2609.             )) {
  2610.                 if ($request->request->has('returnJson')) {
  2611.                     return new JsonResponse(array(
  2612.                         'success' => false,
  2613.                         'documentHash' => 0,
  2614.                         'documentId' => 0,
  2615.                         'documentIdPadded' => str_pad(08'0'STR_PAD_LEFT),
  2616.                         'documentDate' => '',
  2617.                         'billIds' => [],
  2618.                         'drIds' => [],
  2619.                         'pmntTransIds' => [],
  2620.                         'viewUrl' => '',
  2621.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  2622.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  2623.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  2624.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  2625.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  2626.                     ));
  2627.                 } else
  2628.                     $this->addFlash(
  2629.                         'error',
  2630.                         'Sorry Could not insert Data.'
  2631.                     );
  2632.             } else {
  2633.                 $funcname 'SalesOrder';
  2634.                 $doc_id $extId;
  2635.                 DeleteDocument::$funcname($em$doc_id00);
  2636.                 Client::ProcessTempClients($em$companyId$clientIds = [$request->request->get('client_id'null)]);
  2637.                 $orderHere SalesOrderM::CreateNew(
  2638.                     $this->getDoctrine()->getManager(),
  2639.                     $doc_id,
  2640.                     $request->request,
  2641.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  2642.                     $this->getLoggedUserCompanyId($request)
  2643.                 );
  2644.                 $orderId $orderHere->getSalesOrderId();
  2645.                 $orderConfirmationPendingFlag $orderHere->getOrderConfirmationPendingFlag();
  2646.                 $draftFlag $orderHere->getDraftFlag();
  2647.                 $inhouseShortageFlag $orderHere->getInhouseShortageFlag();
  2648.                 $clientCreatedFlag $orderHere->getClientCreatedFlag();
  2649.                 $creditLimitExceededFlag $orderHere->getCreditLimitExceededFlag();
  2650.                 if ($draftFlag == && $orderConfirmationPendingFlag == 0) {
  2651.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  2652.                     $approveRole 1;  //created
  2653.                     $options = array(
  2654.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  2655.                         'notification_server' => $this->container->getParameter('notification_server'),
  2656.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  2657.                         'url' => $this->generateUrl(
  2658.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
  2659.                         )
  2660.                     );
  2661.                     System::setApprovalInfo(
  2662.                         $this->getDoctrine()->getManager(),
  2663.                         $options,
  2664.                         array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  2665.                         $orderId,
  2666.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  2667.                         $request->request->get('salesMethod'1),
  2668.                         $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0
  2669.                     );
  2670.                     System::createEditSignatureHash(
  2671.                         $this->getDoctrine()->getManager(),
  2672.                         array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  2673.                         $orderId,
  2674.                         $loginId,
  2675.                         $approveRole,
  2676.                         $request->request->get('approvalHash')
  2677.                     );
  2678.                 }
  2679.                 $url $this->generateUrl(
  2680.                     'view_sales_order'
  2681.                 );
  2682.                 System::AddNewNotification(
  2683.                     $this->container->getParameter('notification_enabled'),
  2684.                     $this->container->getParameter('notification_server'),
  2685.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  2686.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  2687.                     "Sales Order : " $dochash " Has Been Created And is Under Processing",
  2688.                     'pos',
  2689.                     System::getPositionIdsByDepartment($emGeneralConstant::SALES_DEPARTMENT),
  2690.                     'success',
  2691.                     $url "/" $orderId,
  2692.                     "Sales Order"
  2693.                 );
  2694.                 if ($request->request->has('returnJson')) {
  2695.                     $order $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  2696.                         array(
  2697.                             'salesOrderId' => $orderId,
  2698.                         )
  2699.                     );
  2700.                     $clnt $em->getRepository('ApplicationBundle:AccClients')->findOneBy(
  2701.                         array(
  2702.                             'clientId' => $order->getClientId(),
  2703.                         )
  2704.                     );
  2705.                     $drs $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  2706.                         array(
  2707.                             'salesOrderId' => $orderId,
  2708.                         )
  2709.                     );
  2710.                     $bills $em->getRepository('ApplicationBundle:SalesInvoice')->findBy(
  2711.                         array(
  2712.                             'salesOrderId' => $orderId,
  2713.                         )
  2714.                     );
  2715.                     $billIds = [];
  2716.                     $drIds = [];
  2717.                     $pmntTransIds = [];
  2718.                     foreach ($bills as $bill)
  2719.                         $billIds[] = $bill->getSalesInvoiceId();
  2720.                     foreach ($drs as $dr)
  2721.                         $drIds[] = $dr->getDeliveryReceiptId();
  2722.                     $pmntTransIds json_decode($order->getOrderPaymentReceiptVoucherIds(), true);
  2723.                     if ($pmntTransIds == null)
  2724.                         $pmntTransIds = [];
  2725.                     return new JsonResponse(array(
  2726.                         'success' => true,
  2727.                         'documentHash' => $order->getDocumentHash(),
  2728.                         'documentId' => $orderId,
  2729.                         'orderConfirmationPendingFlag' => $orderConfirmationPendingFlag,
  2730.                         'draftFlag' => $draftFlag,
  2731.                         'clientCreatedFlag' => $clientCreatedFlag,
  2732.                         'inhouseShortageFlag' => $inhouseShortageFlag,
  2733.                         'creditLimitExceededFlag' => $creditLimitExceededFlag,
  2734.                         'documentIdPadded' => str_pad($orderId8'0'STR_PAD_LEFT),
  2735.                         'documentDate' => $order->getSalesOrderDate()->format('Y-m-d'),
  2736.                         'deliveryProcessType' => $order->getDeliveryProcessType(),
  2737.                         'paymentProcessType' => $order->getPaymentProcessType(),
  2738.                         'clientId' => $order->getClientId(),
  2739.                         'clientMail' => $clnt->getEmail() == null '' $clnt->getEmail(),
  2740.                         'billIds' => $billIds,
  2741.                         'drIds' => $drIds,
  2742.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  2743.                         'pmntTransIds' => $pmntTransIds,
  2744.                         'viewUrl' => $url "/" $orderId,
  2745.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  2746.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  2747.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  2748.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  2749.                     ));
  2750.                 } else {
  2751.                     $this->addFlash(
  2752.                         'success',
  2753.                         'New Sales order Created'
  2754.                     );
  2755.                     return $this->redirect($url "/" $orderId);
  2756.                 }
  2757.             }
  2758.         }
  2759.         $projectList = [];
  2760.         $projectListArray = [];
  2761.         $dt $em->getRepository('ApplicationBundle:Project')->findBy(
  2762.             array(
  2763.                 'projectStep' => array_flip(ProjectConstant::$projectSteps)['SALES ORDER'], ///material
  2764.                 'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
  2765.                 'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  2766.             ),
  2767.             array('projectDate' => 'desc')
  2768.         );
  2769.         foreach ($dt as $entry) {
  2770.             $projectListArray[] = array(
  2771.                 'id' => $entry->getProjectId(),
  2772.                 'value' => $entry->getProjectId(),
  2773.                 'name' => $entry->getProjectName(),
  2774.                 'text' => $entry->getProjectName(),
  2775.                 'clientId' => $entry->getClientId(),
  2776.             );
  2777.             $projectList[$entry->getProjectId()] = array(
  2778.                 'id' => $entry->getProjectId(),
  2779.                 'value' => $entry->getProjectId(),
  2780.                 'name' => $entry->getProjectName(),
  2781.                 'text' => $entry->getProjectName(),
  2782.                 'clientId' => $entry->getClientId(),
  2783.             );
  2784.         }
  2785.         $productListArray = [];
  2786.         $subCategoryListArray = [];
  2787.         $categoryListArray = [];
  2788.         $igListArray = [];
  2789.         $unitListArray = [];
  2790.         $brandListArray = [];
  2791.         $clientLevelListArray = [];
  2792.         //        $productList = Inventory::ProductList($em, $companyId, 1);
  2793.         $productList = [];
  2794.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  2795.         $categoryList Inventory::ProductCategoryList($em$companyId);
  2796.         $igList Inventory::ItemGroupList($em$companyId);
  2797.         $unitList Inventory::UnitTypeList($em);
  2798.         $brandList Inventory::GetBrandList($em$companyId);
  2799.         $clientLevelList Inventory::GetClientLevelList($em$companyId);
  2800.         $salesLevelList Inventory::GetSalesLevelList($em$companyId);
  2801.         $salesLevelListArray = [];
  2802.         foreach ($productList as $product$productListArray[] = $product;
  2803.         foreach ($categoryList as $product$categoryListArray[] = $product;
  2804.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  2805.         foreach ($igList as $product$igListArray[] = $product;
  2806.         foreach ($unitList as $product$unitListArray[] = $product;
  2807.         foreach ($brandList as $product$brandListArray[] = $product;
  2808.         foreach ($salesLevelList as $product$salesLevelListArray[] = $product;
  2809.         foreach ($clientLevelList as $product) {
  2810.             $clientLevelListArray[] = $product;
  2811.         }
  2812.         $extDocData = [];
  2813.         $extDocDataDetails = [];
  2814.         $extDocData = [];
  2815.         $extDocDetailsData = [];
  2816.         $itemSegmentData = [];
  2817.         $segmentData = [];
  2818.         if ($extId == 0) {
  2819.         } else {
  2820.             $extDoc $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  2821.                 array(
  2822.                     'salesOrderId' => $extId,
  2823.                 )
  2824.             );
  2825.             //now if its not editable, redirect to view
  2826.             if ($extDoc) {
  2827.                 if ($extDoc->getEditFlag() != && $extDoc->getCanBeEditedGenerallyFlag() != 1) {
  2828.                     $url $this->generateUrl(
  2829.                         'view_sales_order'
  2830.                     );
  2831.                     return $this->redirect($url "/" $extId);
  2832.                 } else {
  2833.                     $extDocData $extDoc;
  2834.                     $itemSegmentData json_decode($extDocData->getItemSegmentData(), true);
  2835.                     $segmentData json_decode($extDocData->getSegmentData(), true);
  2836.                     if ($segmentData == null$segmentData = [];
  2837.                     if ($itemSegmentData == null$itemSegmentData = [
  2838.                         [
  2839.                             'currCust' => "",
  2840.                             'descCust' => "",
  2841.                             'index' => 0,
  2842.                             'priceCust' => "1",
  2843.                             'scfc' => 0,
  2844.                             'scopeDescription' => "",
  2845.                             'show' => 1,
  2846.                             'title' => "Product & Services",
  2847.                             'unitCust' => "1",
  2848.                             'uomCust' => "Lot",
  2849.                         ]
  2850.                     ];
  2851.                     $extDocDetailsDataQry $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy(
  2852.                         array(
  2853.                             'salesOrderId' => $id///material
  2854.                         )
  2855.                     );
  2856.                     foreach ($extDocDetailsDataQry as $dt) {
  2857.                         $detailsIds = [];
  2858.                         $specificUnit = [];
  2859.                         $docIds = [];
  2860. //                        $tagDetails = json_decode($dt->getTagData(), true);
  2861. //                        if ($tagDetails == null) $tagDetails = [];
  2862. //                        foreach ($tagDetails as $k => $tagDetail) {
  2863. //
  2864. //
  2865. //                            $detailsIds[] = isset($tagDetail['details_id']) ? $tagDetail['details_id'] : 0;
  2866. //                            $specificUnit[] = isset($tagDetail['specificUnit']) ? $tagDetail['specificUnit'] : 0;
  2867. //                            $docIds[] = isset($tagDetail['docId']) ? $tagDetail['docId'] : 0;
  2868. //
  2869. //
  2870. //                        }
  2871.                         $ggObj = [
  2872.                             'alias' => $dt->getAlias(),
  2873.                             'billingSchedule' => "",
  2874.                             'currency' => $extDoc->getCurrency(),
  2875.                             'currencyMultiplyRate' => $extDoc->getCurrencyMultiplyRate(),
  2876.                             'deliveryPorts' => "",
  2877.                             'deliverySchedule' => "",
  2878.                             'dependencyOnIndex' => "0",
  2879.                             'dependencyOnPid' => "0",
  2880.                             'dependencyOnSegment' => "0",
  2881.                             'dependencyOnSid' => "0",
  2882.                             'discountAmount' => $dt->getDiscountAmount(),
  2883.                             'discountRate' => $dt->getDiscountRate(),
  2884.                             'discountedAmount' => $dt->getDiscountedAmount(),
  2885.                             'fdm' => $dt->getProductFdm(),
  2886.                             'finalPrice' => $dt->getFinalPrice(),
  2887.                             'finalAmount' => $dt->getFinalAmount(),
  2888.                             'id' => $dt->getType() == $dt->getServiceId() : $dt->getProductId(),
  2889.                             'incoterm' => "",
  2890. //                            'index' => "1753779068784",
  2891. //                            'isForeign' => 0,
  2892. //                            'marginAmount' => "0.000",
  2893. //                            'marginRate' => "0.000",
  2894. //                            'markupRate' => "0.000",
  2895.                             'name' => $dt->getProductNameFdm(),
  2896.                             'note' => $dt->getDesc(),
  2897.                             'origin' => $dt->getOrigin(),
  2898.                             'origins' => [$dt->getOrigin()],
  2899. //                            'recurring' => "1753779068784",
  2900. //                            'referenceFiles' => "",
  2901. //                            'referenceNo' => "",
  2902. //                            'rfqSuppIds' => [],
  2903. //                            'rowCostTriggerPercentage' => "0",
  2904. //                            'rowCostTriggerType' => "",
  2905. //                            'rowId' => '',
  2906. //                            'scope' => "",
  2907. //                            'scopeDescription' => "",
  2908. //                            'scopeId' => 0,
  2909. //                            'scopeName' => "",
  2910.                             'segmentIndex' => $dt->getSegmentIndex() == null $dt->getSegmentIndex(),
  2911. //                            'sequence' => "0",
  2912.                             'soItemDelivered' => $dt->getReceived(),
  2913.                             'soItemFound' => 1,
  2914.                             'soItemId' => $dt->getId(),
  2915.                             'taxAmount' => $dt->getIndividualTaxAmount(),
  2916.                             'taxId' => $dt->getTaxConfigId(),
  2917.                             'taxName' => $dt->getTaxConfigName(),
  2918. //                            'taxAsExpense' => $dt->getTaxAsExpense(),
  2919. //                            'taxAsExpense' => $dt->getTaxAsExpense(),
  2920.                             'taxRate' => $dt->getIndividualTaxPercentage(),
  2921.                             'totalPrice' => $dt->getAmount(),
  2922.                             'totalSalesPrice' => $dt->getAmount(),
  2923.                             'type' => $dt->getType(),
  2924.                             'unit' => $dt->getQty(),
  2925.                             'unitPrice' => $dt->getPrice(),
  2926.                             'unitSalesPrice' => $dt->getPrice(),
  2927.                             'unitTypeId' => $dt->getUnitTypeId(),
  2928.                             'warranty' => "0",
  2929.                             'specificUnit' => $specificUnit,
  2930.                             'detailsIds' => $detailsIds,
  2931.                             'docIds' => $docIds,
  2932.                         ];
  2933.                         $extDocDetailsData[] = $ggObj;
  2934.                     }
  2935.                 }
  2936.             } else {
  2937.             }
  2938.         }
  2939.         //        $clientListById = Client::GetExistingClientList($em, $companyId,['status'=>GeneralConstant::ACTIVE]);
  2940.         $clientListById = [];
  2941.         $userId $request->getSession()->get(UserConstants::USER_ID);
  2942.         $ownerId 0;
  2943.         $ownerLevel 0;
  2944.         $salesLevel 0;
  2945.         if ($request->getSession()->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_CLIENT) {
  2946.             $thisClientLevel 0;
  2947.             $ownerId $request->getSession()->get(UserConstants::CLIENT_ID);
  2948.             if ($request->getSession()->has(UserConstants::USER_CLIENT_LEVEL))
  2949.                 $thisClientLevel $request->getSession()->has(UserConstants::USER_CLIENT_LEVEL);
  2950.             else {
  2951.                 $thisClient $em->getRepository('ApplicationBundle:AccClients')->findOneBy(
  2952.                     array(
  2953.                         'clientId' => $ownerId///material
  2954.                     )
  2955.                 );
  2956.                 if ($thisClient) {
  2957.                     $thisClientLevel $thisClient->getClientLevel();
  2958.                 }
  2959.             }
  2960.             if ($thisClientLevel == || $thisClientLevel == null || $thisClientLevel == '') {
  2961.                 $thisClientLevel 0;
  2962.             }
  2963.             $ownerLevel $thisClientLevel;
  2964.             $salesLevel $ownerLevel;
  2965.         }
  2966.         $warehouse_action_list GeneralConstant::$warehouse_action_list;
  2967.         $warehouse_action_list_array GeneralConstant::$warehouse_action_list_array;
  2968.         //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  2969.         $userBranchIdList json_decode($request->getSession()->get('branchIdList'), true);
  2970.         if ($userBranchIdList == null$userBranchIdList = [];
  2971.         $userBranchId $request->getSession()->get('branchId');
  2972.         $dataArray = array(
  2973.             'page_title' => 'New Sales Order',
  2974.             //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  2975.             'ExistingClients' => [],
  2976.             'ClientDetails' => [],
  2977.             'allowedSalesPersonIds' => Client::AllowedSalesPersonIds($em$userId$companyId, []),
  2978.             //            'ClientDetails' => Client::ClientDetailsAgainstID($em, $companyId, []),
  2979.             'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager(), [], ['status' => GeneralConstant::ACTIVE]),
  2980.             'ClientListById' => $clientListById,
  2981.             'users' => Users::getUserListById($em),
  2982.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  2983.             'hasProject' => $hasProject,
  2984.             'warehouseList' => Inventory::WarehouseList($em),
  2985.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  2986.             'warehouseActionList' => $warehouse_action_list,
  2987.             'warehouseActionListArray' => $warehouse_action_list_array,
  2988.             'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  2989.             'projectId' => $projectId,
  2990.             'projectList' => $projectList,
  2991.             'productList' => $productList,
  2992.             'productListArray' => $productListArray,
  2993.             'projectListArray' => $projectListArray,
  2994.             'subCategoryList' => $subCategoryList,
  2995.             'categoryList' => $categoryList,
  2996.             'igList' => $igList,
  2997.             'unitList' => $unitList,
  2998.             'unitListArray' => $unitListArray,
  2999.             'brandList' => $brandList,
  3000.             'extDocDataDetails' => $extDocDataDetails,
  3001.             'extDocData' => $extDocData,
  3002.             'currencyList' => Inventory::CurrencyList($em),
  3003.             'colorList' => Inventory::GetColorList($em),
  3004.             'extData' => $extDocData,
  3005.             'extDocDetailsData' => $extDocDetailsData,
  3006.             'itemSegmentData' => $itemSegmentData,
  3007.             'segmentData' => $segmentData,
  3008.             //            'ExistingClients' => $clientListById,
  3009.             'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  3010.             'clientTypeList' => Client::ClientTypeList($em$companyId),
  3011.             'ownerId' => $ownerId,
  3012.             'ownerLevel' => $ownerLevel,
  3013.             'salesLevel' => $salesLevel,
  3014.             'clientLevelList' => $clientLevelList,
  3015.             'salesLevelList' => $salesLevelList,
  3016.             'clientLevelListArray' => $clientLevelListArray,
  3017.             'salesLevelListArray' => $salesLevelListArray,
  3018.             'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  3019.             'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  3020.             'salesMethodList' => SalesConstant::$salesMethod,
  3021.             'deliveryProcessTypes' => SalesConstant::$deliveryProcessType,
  3022.             'paymentProcessTypes' => SalesConstant::$paymentProcessType,
  3023.             'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  3024.             'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  3025.             'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  3026.             'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  3027.             'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  3028.             'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  3029.             //            'sales_person_list' => Client::SalesPersonList($em),
  3030.             'sales_person_list' => [],
  3031.             'stage_list' => ProjectM::GetWorkStageList($em$companyId),
  3032.             'regionList' => Client::RegionList($em$companyId),
  3033.             'regionListForClient' => Client::RegionListForClientEntry($em$companyId),
  3034.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  3035.             'userBranchIdList' => $userBranchIdList,
  3036.             'userBranchId' => $userBranchId,
  3037.             'headList' => Accounts::HeadList($em),
  3038.         );
  3039.         //json
  3040.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  3041.         {
  3042.             $dataArray['success'] = true;
  3043.             return new JsonResponse(
  3044.                 $dataArray
  3045.             );
  3046.         }
  3047.         if ($request->query->has('showPos'))
  3048.             return $this->render(
  3049.                 '@Sales/pages/input_forms/new_sales_order_pos.html.twig',
  3050.                 $dataArray
  3051.             );
  3052.         else
  3053.             return $this->render(
  3054.                 '@Sales/pages/input_forms/new_sales_order.html.twig',
  3055.                 $dataArray
  3056.             );
  3057.     }
  3058.     public function CreateOrder(Request $request)
  3059.     {
  3060.         if ($request->isMethod('POST')) {
  3061.             try {
  3062.                 $em $this->getDoctrine()->getManager();
  3063.                 $authToken $request->headers->get('auth-token');
  3064.                 if (!$authToken) {
  3065.                     return new JsonResponse(['error' => 'Invalid or missing auth-token'], 401);
  3066.                 }
  3067.                 $LoginId 1;
  3068.                 $companyId $this->getLoggedUserCompanyId($request);
  3069.                 $typeHash $request->request->get('type_hash''SO');
  3070.                 $prefixHash $request->request->get('prefix_hash''11');
  3071.                 $approvalRole $request->request->get('approvalRole''3');
  3072.                 $timestamp $request->request->get('timeStampOfForm'time());
  3073.                 $numberHash MiscActions::GetNumberHash($em$typeHash$prefixHash$approvalRole$timestamp0$companyId);
  3074.                 $docHash "{$typeHash}/{$prefixHash}/{$approvalRole}/{$numberHash}";
  3075.                 $options = array(
  3076.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3077.                     'notification_server' => $this->container->getParameter('notification_server'),
  3078.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3079.                     'url' => $this->generateUrl(
  3080.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
  3081.                     )
  3082.                 );
  3083.                 $request->request->set('number_hash'$numberHash);
  3084.                 $request->request->set('docHash'$docHash);
  3085. //                Client::ProcessTempClients($em, $companyId, $clientIds = [$request->request->get('client_id', null)]);
  3086.                 $salesOrder SalesOrderM::CreateNewForApi($em0$request->request$LoginId$companyId0);
  3087.                 $orderId $salesOrder->getSalesOrderId();
  3088.                 System::setApprovalInfo(
  3089.                     $this->getDoctrine()->getManager(),
  3090.                     $options,
  3091.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  3092.                     $orderId,
  3093.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  3094.                     $request->request->get('salesMethod'1),
  3095.                     $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0
  3096.                 );
  3097.                 return new JsonResponse([
  3098.                     'status' => 'success',
  3099.                     'salesOrderId' => $salesOrder->getSalesOrderId(),
  3100.                     'salesOrderNumber' => $salesOrder->getSalesOrderNumber(),
  3101.                     'message' => 'Sales order created successfully'
  3102.                 ], 201);
  3103.             } catch (\Exception $e) {
  3104.                 return new JsonResponse([
  3105.                     'status' => 'error',
  3106.                     'message' => 'Failed to create sales order',
  3107.                     'details' => $e->getMessage()
  3108.                 ], 500);
  3109.             }
  3110.         } else {
  3111.             return new JsonResponse("It should be post");
  3112.         }
  3113.     }
  3114.     public function getAllSalesOrderByUser(Request $request)
  3115.     {
  3116.         $session $request->getSession();
  3117.         $userId $session->get('userId');
  3118.         if (!$userId) {
  3119.             return ResponseStructure::error('User not authenticated'401);
  3120.         }
  3121.         $em $this->getDoctrine()->getManager();
  3122.         try {
  3123.             $salesOrders SalesOrderHelper::getSalesOrdersByUser($session$em);
  3124.             return ResponseStructure::success($salesOrders'Sales orders fetched successfully');
  3125.         } catch (\Exception $e) {
  3126.             return ResponseStructure::error($e->getMessage(), 500);
  3127.         }
  3128.     }
  3129.     public function CreateNewPointOfSales(Request $request$id 0)
  3130.     {
  3131.         $em $this->getDoctrine()->getManager();
  3132.         $hasProject 0;
  3133.         $extId $id;
  3134.         $projectId 0;
  3135.         if ($request->query->has('projectId'))
  3136.             if ($request->query->get('projectId') != 0) {
  3137.                 $hasProject 1;
  3138.                 $projectId $request->query->get('projectId');
  3139.             }
  3140.         if ($request->isMethod('POST')) {
  3141.             $em $this->getDoctrine()->getManager();
  3142.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesOrder']; //change
  3143.             $dochash $request->request->get('sales_order_number'); //change
  3144.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3145.             $approveRole $request->request->get('approvalRole');
  3146.             $approveHash $request->request->get('approvalHash');
  3147.             if (!DocValidation::isInsertable(
  3148.                 $em,
  3149.                 $entity_id,
  3150.                 $dochash,
  3151.                 $loginId,
  3152.                 $approveRole,
  3153.                 $approveHash,
  3154.                 $id
  3155.             )) {
  3156.                 $this->addFlash(
  3157.                     'error',
  3158.                     'Sorry Could not insert Data.'
  3159.                 );
  3160.             } else {
  3161.                 $funcname 'SalesOrder';
  3162.                 $doc_id $extId;
  3163.                 DeleteDocument::$funcname($em$doc_id0);
  3164.                 $orderId SalesOrderM::CreateNew(
  3165.                     $this->getDoctrine()->getManager(),
  3166.                     $doc_id,
  3167.                     $request->request,
  3168.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  3169.                     $this->getLoggedUserCompanyId($request)
  3170.                 );
  3171.                 //now add Approval info
  3172.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  3173.                 $approveRole 1;  //created
  3174.                 $options = array(
  3175.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  3176.                     'notification_server' => $this->container->getParameter('notification_server'),
  3177.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  3178.                     'url' => $this->generateUrl(
  3179.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
  3180.                     )
  3181.                 );
  3182.                 System::setApprovalInfo(
  3183.                     $this->getDoctrine()->getManager(),
  3184.                     $options,
  3185.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  3186.                     $orderId,
  3187.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3188.                 );
  3189.                 System::createEditSignatureHash(
  3190.                     $this->getDoctrine()->getManager(),
  3191.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  3192.                     $orderId,
  3193.                     $loginId,
  3194.                     $approveRole,
  3195.                     $request->request->get('approvalHash')
  3196.                 );
  3197.                 $this->addFlash(
  3198.                     'success',
  3199.                     'New Sales order Created'
  3200.                 );
  3201.                 $url $this->generateUrl(
  3202.                     'view_sales_order'
  3203.                 );
  3204.                 System::AddNewNotification(
  3205.                     $this->container->getParameter('notification_enabled'),
  3206.                     $this->container->getParameter('notification_server'),
  3207.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  3208.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  3209.                     "Sales Order : " $dochash " Has Been Created And is Under Processing",
  3210.                     'pos',
  3211.                     System::getPositionIdsByDepartment($emGeneralConstant::SALES_DEPARTMENT),
  3212.                     'success',
  3213.                     $url "/" $orderId,
  3214.                     "Sales Order"
  3215.                 );
  3216.                 return $this->redirect($url "/" $orderId);
  3217.             }
  3218.         }
  3219.         $projectList = [];
  3220.         $projectListArray = [];
  3221.         //        $dt=ProjectM::GetProjectListById($em);
  3222.         $dt $em->getRepository('ApplicationBundle:Project')->findBy(
  3223.             array(
  3224.                 'projectStep' => array_flip(ProjectConstant::$projectSteps)['SALES ORDER'], ///material
  3225.                 'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
  3226.                 'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  3227.             ),
  3228.             array('projectDate' => 'desc')
  3229.         );
  3230.         //        $projectList=$dt;
  3231.         foreach ($dt as $entry) {
  3232.             $projectListArray[] = array(
  3233.                 'id' => $entry->getProjectId(),
  3234.                 'value' => $entry->getProjectId(),
  3235.                 'name' => $entry->getProjectName(),
  3236.                 'text' => $entry->getProjectName(),
  3237.                 'clientId' => $entry->getClientId(),
  3238.             );
  3239.             $projectList[$entry->getProjectId()] = array(
  3240.                 'id' => $entry->getProjectId(),
  3241.                 'value' => $entry->getProjectId(),
  3242.                 'name' => $entry->getProjectName(),
  3243.                 'text' => $entry->getProjectName(),
  3244.                 'clientId' => $entry->getClientId(),
  3245.             );
  3246.             //            $projectList[]=array(
  3247.             //                'id'=>$entry['id'],
  3248.             //                'value'=>$entry['id'],
  3249.             //                'name'=>$entry['projectName'],
  3250.             //                'text'=>$entry['projectName'],
  3251.             //                'clientId'=>$entry['clientId'],
  3252.             //            );
  3253.             //
  3254.         }
  3255.         $productListArray = [];
  3256.         $subCategoryListArray = [];
  3257.         $categoryListArray = [];
  3258.         $igListArray = [];
  3259.         $unitListArray = [];
  3260.         $brandListArray = [];
  3261.         $companyId $this->getLoggedUserCompanyId($request);
  3262.         $productList Inventory::ProductList($em$companyId1);
  3263.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  3264.         $categoryList Inventory::ProductCategoryList($em$companyId);
  3265.         $igList Inventory::ItemGroupList($em$companyId);
  3266.         $unitList Inventory::UnitTypeList($em);
  3267.         $brandList Inventory::GetBrandList($em$companyId);
  3268.         foreach ($productList as $product$productListArray[] = $product;
  3269.         foreach ($categoryList as $product$categoryListArray[] = $product;
  3270.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  3271.         foreach ($igList as $product$igListArray[] = $product;
  3272.         foreach ($unitList as $product$unitListArray[] = $product;
  3273.         foreach ($brandList as $product$brandListArray[] = $product;
  3274.         $extDocData = [];
  3275.         $extDocDataDetails = [];
  3276.         if ($extId == 0) {
  3277.         } else {
  3278.             $extDoc $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  3279.                 array(
  3280.                     'salesOrderId' => $extId///material
  3281.                 )
  3282.             );
  3283.             //now if its not editable, redirect to view
  3284.             if ($extDoc) {
  3285.                 if ($extDoc->getEditFlag() != 1) {
  3286.                     $url $this->generateUrl(
  3287.                         'view_sales_order'
  3288.                     );
  3289.                     return $this->redirect($url "/" $extId);
  3290.                 } else {
  3291.                     $extDocData $extDoc;
  3292.                     $extDocDataDetails $em->getRepository('ApplicationBundle:SalesOrderItem')->findOneBy(
  3293.                         array(
  3294.                             'salesOrderId' => $extId///material
  3295.                         )
  3296.                     );
  3297.                 }
  3298.             } else {
  3299.             }
  3300.         }
  3301.         return $this->render(
  3302.             '@Sales/pages/input_forms/new_point_of_sales.html.twig',
  3303.             array(
  3304.                 'page_title' => 'New Sales Order',
  3305.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  3306.                 'ClientList' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  3307.                 'ClientListById' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  3308.                 'users' => Users::getUserListById($em),
  3309.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  3310.                 'hasProject' => $hasProject,
  3311.                 'projectId' => $projectId,
  3312.                 'projectList' => $projectList,
  3313.                 'productList' => $productList,
  3314.                 'productListArray' => $productListArray,
  3315.                 'projectListArray' => $projectListArray,
  3316.                 'subCategoryList' => $subCategoryList,
  3317.                 'categoryList' => $categoryList,
  3318.                 'igList' => $igList,
  3319.                 'unitList' => $unitList,
  3320.                 'unitListArray' => $unitListArray,
  3321.                 'brandList' => $brandList,
  3322.                 'extDocDataDetails' => $extDocDataDetails,
  3323.                 'extDocData' => $extDocData,
  3324.             )
  3325.         );
  3326.     }
  3327.     public function GetExtDataForSo(Request $request$id 0)
  3328.     {
  3329.         $em $this->getDoctrine()->getManager();
  3330.         $Content = [];
  3331.         $itemList = [];
  3332.         $serviceList = [];
  3333.         $extData $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy(
  3334.             array(
  3335.                 'salesOrderId' => $id///material
  3336.             )
  3337.         );
  3338.         if (!empty($extData)) {
  3339.             foreach ($extData as $dt) {
  3340.                 if ($dt->getType() == 1) {
  3341.                     $itemList[] = array(
  3342.                         'id' => $dt->getProductId(),
  3343.                         'unit' => $dt->getQty(),
  3344.                         'balance' => $dt->getBalance(),
  3345.                         'transitQty' => $dt->getTransitQty(),
  3346.                         'delivered' => $dt->getDelivered(),
  3347.                         'prohibitProductChange' => ($dt->getDelivered() + $dt->getTransitQty()) > 0,
  3348.                         'unitTypeId' => $dt->getUnitTypeId(),
  3349.                         'colorId' => $dt->getColorId(),
  3350.                         'sizeId' => $dt->getSizeId(),
  3351.                         'origin' => $dt->getOrigin(),
  3352.                         'unit_price' => $dt->getPrice(),
  3353.                         'total_price' => $dt->getProductAmount(),
  3354.                         'discount_rate' => $dt->getDiscountRate(),
  3355.                         'discount_amount' => $dt->getDiscountAmount(),
  3356.                         'discounted_amount' => $dt->getDiscountedAmount(),
  3357.                         'free_product_ids' => json_decode($dt->getFreeProductIds()),
  3358.                         'so_item_id' => $dt->getId(),
  3359.                         'free_products_so_item_ids' => json_decode($dt->getFreeProductSoItemIds()),
  3360.                         'free_products_so_item_ids_str' => $dt->getFreeProductSoItemIds(),
  3361.                         'freeProductUnit' => json_decode($dt->getFreeProductUnits()),
  3362.                         'warranty' => $dt->getWarranty(),
  3363.                         'alias' => $dt->getAlias(),
  3364.                         'note' => $dt->getDesc(),
  3365.                         'incoTerm' => $dt->getIncoTerm(),
  3366.                         'taxConfigId' => $dt->getTaxConfigId(),
  3367.                         'taxConfigName' => $dt->getTaxConfigName(),
  3368.                         'tax_amount' => $dt->getIndividualTaxAmount(),
  3369.                         'tax_percentage' => $dt->getIndividualTaxPercentage(),
  3370.                         'ret_data' => [],
  3371.                         'fdm' => $dt->getProductFdm(),
  3372.                         'product_name' => $dt->getProductNameFdm(),
  3373.                         'detailsIds' => [],
  3374.                         'docIds' => [],
  3375.                     );
  3376.                 }
  3377.                 if ($dt->getType() == 2) {
  3378.                     $serviceList[] = array(
  3379.                         'id' => $dt->getServiceId(),
  3380.                         'unit' => $dt->getQty(),
  3381.                         'transitQty' => $dt->getTransitQty(),
  3382.                         'delivered' => $dt->getDelivered(),
  3383.                         'prohibitProductChange' => ($dt->getDelivered() + $dt->getTransitQty()) > 0,
  3384.                         'unit_price' => $dt->getPrice(),
  3385.                         'total_price' => $dt->getProductAmount(),
  3386.                         'alias' => $dt->getAlias(),
  3387.                         'note' => $dt->getDesc(),
  3388.                         'detailsIds' => [],
  3389.                         'so_item_id' => $dt->getId(),
  3390.                         'incoTerm' => $dt->getIncoTerm(),
  3391.                         'taxConfigId' => $dt->getTaxConfigId(),
  3392.                         'taxConfigName' => $dt->getTaxConfigName(),
  3393.                         'tax_amount' => $dt->getIndividualTaxAmount(),
  3394.                         'tax_percentage' => $dt->getIndividualTaxPercentage(),
  3395.                     );
  3396.                 }
  3397.             }
  3398.         }
  3399.         if (empty($extData))
  3400.             return new JsonResponse(array("success" => false"content" => $Content));
  3401.         else {
  3402.             //            $Content=$engine->render('@Sales/pages/report/selected_client_details_for_so.html.twig', array("cd"=>$CD));
  3403.             return new JsonResponse(array("success" => true"content" => array(
  3404.                 'Products' => $itemList,
  3405.                 'Services' => $serviceList
  3406.             )));
  3407.         }
  3408.     }
  3409.     public function GetAvailableProductQtyForSo(Request $request$id 0)
  3410.     {
  3411.         $em $this->getDoctrine()->getManager();
  3412.         $productId $request->request->has('productId') ? $request->request->get('productId') : 0;
  3413.         $colorId $request->request->has('colorId') ? $request->request->get('colorId') : 0;
  3414.         $qty SalesOrderM::getNonBookedProductQtyForSales($em$productId$colorId);
  3415.         return new JsonResponse(array("success" => true"qty" => $qty));
  3416.     }
  3417.     public function AfterSalesServiceProductStatusList(Request $request)
  3418.     {
  3419.         $em $this->getDoctrine()->getManager();
  3420.         $routeName $request->attributes->get('_route');
  3421.         $filterCondition "mainTable.CompanyId=1";
  3422.         //        $filterCondition = " mainTable.CompanyId=1 and mainTable.status=1 ";
  3423.         //        if ($routeName != 'client_pending_sales_orders') {
  3424.         //            $filterCondition .= " and ( mainTable.orderConfirmationPendingFlag =0 or mainTable.orderConfirmationPendingFlag is null)";
  3425.         //        }
  3426.         return $this->render(
  3427.             '@Sales/pages/list/after_sales_service_status.html.twig',
  3428.             array(
  3429.                 'page_title' => 'After Sales Service Status',
  3430.                 'data' => [],
  3431.                 'filterCondition' => $filterCondition,
  3432.             )
  3433.         );
  3434.     }
  3435.     public function SalesOrderList(Request $request)
  3436.     {
  3437.         $em $this->getDoctrine()->getManager();
  3438.         $routeName $request->attributes->get('_route');
  3439.         $filterCondition " mainTable.CompanyId=1 and mainTable.status=1 ";
  3440.         $filterCondition .= " and ( mainTable.orderConfirmationPendingFlag =0 or mainTable.orderConfirmationPendingFlag is null)";
  3441.         return $this->render(
  3442.             '@Sales/pages/list/sales_order_list.html.twig',
  3443.             array(
  3444.                 'page_title' => $routeName == 'client_pending_sales_orders' 'Confirmation Pending Orders' 'Sales Orders',
  3445.                 'data' => [],
  3446.                 'orderConfirmationPendingFlag' => 0,
  3447.                 'filterCondition' => $filterCondition,
  3448.             )
  3449.         );
  3450.     }
  3451.     public function ClientPendingSalesOrderList(Request $request)
  3452.     {
  3453.         $em $this->getDoctrine()->getManager();
  3454.         $routeName $request->attributes->get('_route');
  3455.         $filterCondition " mainTable.CompanyId=1 and mainTable.status=1 ";
  3456.         $filterCondition .= " and mainTable.orderConfirmationPendingFlag =1 ";
  3457.         return $this->render(
  3458.             '@Sales/pages/list/sales_order_list.html.twig',
  3459.             array(
  3460.                 'page_title' => 'Confirmation Pending Orders',
  3461.                 'data' => [],
  3462.                 'filterCondition' => $filterCondition,
  3463.                 'orderConfirmationPendingFlag' => 1,
  3464.             )
  3465.         );
  3466.     }
  3467.     public function ViewSalesOrder(Request $request$id)
  3468.     {
  3469.         $em $this->getDoctrine()->getManager();
  3470.         $mis_data_flag 0;
  3471.         if ($request->query->has('mis_print'))
  3472.             $mis_data_flag 1;
  3473.         $dt SalesOrderM::GetSalesOrderDetails($em$id$mis_data_flag);
  3474.         //        $companyId = $this->getLoggedUserCompanyId($request);
  3475.         $companyId $dt['so_data']->getCompanyId();
  3476.         $company_data Company::getCompanyData($em$companyId);
  3477.         $forwardToMailAddress '';
  3478.         if ($request->query->has('forwardToMailAddress'))
  3479.             $forwardToMailAddress $request->query->get('forwardToMailAddress');
  3480.         if ($forwardToMailAddress == '')
  3481.             $forwardToMailAddress $dt['client_data']->getEmail();
  3482.         $currentRoute $request->attributes->get('_route');
  3483.         if ($currentRoute === 'app_view_sales_order_api') {
  3484.             if ($id) {
  3485.                 $salesOrderData $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy([
  3486.                     'salesOrderId' => (int)$id
  3487.                 ]);
  3488.                 if (!$salesOrderData) {
  3489.                     return new JsonResponse([
  3490.                         'status' => 'false',
  3491.                         'message' => 'Sales order not found.',
  3492.                         'data' => null
  3493.                     ], 404);
  3494.                 }
  3495.                 $salesOrderItems $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy([
  3496.                     'salesOrderId' => (int)$id
  3497.                 ]);
  3498.                 $clientId $salesOrderData->getClientId();
  3499.                 $clientData $em->getRepository('ApplicationBundle:AccClients')->find($clientId);
  3500.                 if (!$clientData) {
  3501.                     $clientResponse null;
  3502.                 } else {
  3503.                     $clientResponse = [
  3504.                         "client_id" => (string)$clientData->getClientId(),
  3505.                         "client_name" => $clientData->getClientName(),
  3506.                         "contact_person_name" => $clientData->getContactPersonName(),
  3507.                         "address_contact" => $clientData->getAddressContact(),
  3508.                         "contact_number" => $clientData->getContactNumber() ?? "",
  3509.                         "image" => $clientData->getImage(),
  3510.                         "email" => $clientData->getEmail() ?? "",
  3511.                         "credit_limit" => number_format($clientData->getCreditLimit() ?? 03'.'''),
  3512.                         "shipping_address" => $clientData->getShippingAddress() ?? "",
  3513.                         "billing_address" => $clientData->getBillingAddress() ?? "",
  3514.                         "client_due" => $clientData->getClientDue() ?? "0",
  3515.                         "client_level" => (string)($clientData->getClientLevel() ?? 0),
  3516.                         "parent_id" => (string)($clientData->getParentId() ?? 0),
  3517.                         "client_type" => (int)($clientData->getType() ?? 0),
  3518.                         "region_id" => (int)($clientData->getRegionId() ?? 0),
  3519.                         "sales_person_id" => (string)($clientData->getSalesPersonId() ?? 0),
  3520.                         "client_own_balance" => $clientData->getClientOwnBalanceAmount(),
  3521.                         "client_own_due" => $clientData->getClientOwnDueAmount(),
  3522.                         "client_own_sales" => $clientData->getClientOwnSalesAmount(),
  3523.                         "client_own_received" => $clientData->getClientOwnReceivedAmount(),
  3524.                         "status" => (string)$clientData->getStatus(),
  3525.                         "created_at" => $clientData->getCreatedAt() ? [
  3526.                             "date" => $clientData->getCreatedAt()->format('Y-m-d H:i:s.u'),
  3527.                             "timezone_type" => 3,
  3528.                             "timezone" => strtolower($clientData->getCreatedAt()->getTimezone()->getName())
  3529.                         ] : null,
  3530.                         "company_id" => (int)$clientData->getCompanyId(),
  3531.                     ];
  3532.                 }
  3533.                 $productList = [];
  3534.                 foreach ($salesOrderItems as $index => $item) {
  3535.                     $product $em->getRepository('ApplicationBundle:InvProducts')->findOneBy([
  3536.                         'id' => $item->getProductId()
  3537.                     ]);
  3538.                     if (!$product) {
  3539.                         continue;
  3540.                     }
  3541.                     $productList[] = [
  3542.                         'name' => $product->getName(),
  3543.                         'id' => (string)$product->getId(),
  3544.                         'default_image' => $product->getDefaultImage(),
  3545.                         'colors' => $product->getColors() ?? json_encode([""]),
  3546.                         'sizes' => $product->getSizes() ?? json_encode([""]),
  3547.                         'brand_company' => (string)$product->getBrandCompany(),
  3548.                         'product_code' => $product->getProductCode() ?? '',
  3549.                         'curr_sales_price' => $product->getSalesPrice() ?? '',
  3550.                         'curr_purchase_price' => $product->getPurchasePrice() ?? '0',
  3551.                         'qty' => (string)$item->getQty(),
  3552.                         'value' => (string)$item->getQty(),
  3553.                         'rendered_text' => '#' . ($index 1) . ' ' $product->getName(),
  3554.                         'text' => $product->getName(),
  3555.                         'currentTs' => (string)time()
  3556.                     ];
  3557.                 }
  3558.                 $data = [
  3559.                     'salesOrderId' => $salesOrderData->getSalesOrderId(),
  3560.                     'salesOrderNumber' => $salesOrderData->getSalesOrderNumber(),
  3561.                     'salesOrderDate' => $salesOrderData->getSalesOrderDate() ? $salesOrderData->getSalesOrderDate()->format('Y-m-d H:i:s') : null,
  3562.                     'soAmount' => $salesOrderData->getSoAmount(),
  3563.                     'invoiceAmount' => $salesOrderData->getInvoiceAmount(),
  3564.                     'clientReceivableAmount' => $salesOrderData->getClientReceivableAmount(),
  3565.                     'discountAmount' => $salesOrderData->getDiscountAmount(),
  3566.                     'vatAmount' => $salesOrderData->getVatAmount(),
  3567.                     'paymentTerms' => $salesOrderData->getPaymentTerms(),
  3568.                     'deliveryInstruction' => $salesOrderData->getDeliveryInstruction(),
  3569.                     'documentHash' => $salesOrderData->getDocumentHash(),
  3570.                     'typeHash' => $salesOrderData->getTypeHash(),
  3571.                     'prefixHash' => $salesOrderData->getPrefixHash(),
  3572.                     'assocHash' => $salesOrderData->getAssocHash(),
  3573.                     'numberHash' => $salesOrderData->getNumberHash(),
  3574.                     'refPoNumber' => $salesOrderData->getRefPoNumber(),
  3575.                     'currency' => $salesOrderData->getCurrency(),
  3576.                     'currencyMultiply' => $salesOrderData->getCurrencyMultiply(),
  3577.                     'currencyMultiplyRate' => $salesOrderData->getCurrencyMultiplyRate(),
  3578.                     'status' => $salesOrderData->getStatus(),
  3579.                     'createdAt' => $salesOrderData->getCreatedAt() ? $salesOrderData->getCreatedAt()->format('Y-m-d H:i:s') : null,
  3580.                     'updatedAt' => $salesOrderData->getUpdatedAt() ? $salesOrderData->getUpdatedAt()->format('Y-m-d H:i:s') : null,
  3581.                     'client' => $clientResponse,
  3582.                     'products' => $productList,
  3583.                 ];
  3584.                 return new JsonResponse([
  3585.                     'status' => 'success',
  3586.                     'message' => 'Sales order data retrieved successfully.',
  3587.                     'data' => $data
  3588.                 ]);
  3589.             } else {
  3590.                 return new JsonResponse([
  3591.                     'status' => 'false',
  3592.                     'message' => 'Sales order ID is missing!',
  3593.                     'data' => null
  3594.                 ], 400);
  3595.             }
  3596.         }
  3597.         return $this->render(
  3598.             '@Sales/pages/views/sales_order_view.html.twig',
  3599.             array(
  3600.                 'page_title' => 'View',
  3601.                 'data' => $dt,
  3602.                 'forwardToMailAddress' => $forwardToMailAddress,
  3603.                 'company_name' => $company_data->getName(),
  3604.                 'company_data' => $company_data,
  3605.                 'company_address' => $company_data->getAddress(),
  3606.                 'company_image' => $company_data->getImage(),
  3607.                 //                'invoice_footer' => $company_data->getInvoiceFooter(),
  3608.                 'projectList' => ProjectM::GetProjectListById($em),
  3609.                 'auto_created' => $dt['auto_created'],
  3610.                 'approval_data' => System::checkIfApprovalExists(
  3611.                     $em,
  3612.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  3613.                     $id,
  3614.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3615.                 ),
  3616.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  3617.                     $this->getDoctrine()->getManager(),
  3618.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  3619.                     $id,
  3620.                     $dt['created_by'],
  3621.                     $dt['edited_by']
  3622.                 ) : [],
  3623.                 'users' => Users::getUserListById($em),
  3624.                 'ExistingClients' => Client::GetExistingClientList($em$companyId),
  3625.                 'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  3626.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  3627.                 'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  3628.                 'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  3629.                 'salesMethodList' => SalesConstant::$salesMethod,
  3630.                 'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  3631.                 'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  3632.                 'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  3633.                 'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  3634.                 'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  3635.                 'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  3636.                 'sales_person_list' => Client::SalesPersonList($em),
  3637.                 'stage_list' => ProjectM::GetWorkStageList($em$companyId),
  3638.                 'regionList' => Client::RegionList($em$companyId),
  3639.                 'regionListForClient' => Client::RegionListForClientEntry($em$companyId),
  3640.                 'branchList' => Client::BranchList($em$companyId),
  3641.                 'headList' => Accounts::HeadList($em),
  3642.                 'positionList' => Position::getPositionList($em)
  3643.             )
  3644.         );
  3645.     }
  3646.     public function PrintSalesOrder(Request $request$id)
  3647.     {
  3648.         $em $this->getDoctrine()->getManager();
  3649.         $companyId $this->getLoggedUserCompanyId($request);
  3650.         //mis options flag
  3651.         $mis_data_flag 0;
  3652.         if ($request->query->has('mis_print') || $request->query->has('includeMisFlag'))
  3653.             $mis_data_flag 1;
  3654.         $data SalesOrderM::GetSalesOrderDetails($em$id$mis_data_flag);
  3655.         //print common options starts
  3656.         $printTypesEnabled = ['office_copy']; //default
  3657.         $sendAsPdf 0;
  3658.         $printType 'office_copy';
  3659.         if ($request->query->has('printType'))
  3660.             $printType $request->query->get('printType');
  3661.         if ($request->query->has('forwardToEmail')) {
  3662.             $printType 'forwardToEmail';
  3663.             //            $sendAsPdf=1;
  3664.         }
  3665.         if ($request->query->has('attachPdf')) {
  3666.             $printType 'forwardToEmail';
  3667.             $sendAsPdf $request->query->get('attachPdf');
  3668.         }
  3669.         if ($printType == 'all_copy') {
  3670.             $printTypesEnabled = ['office_copy''party_copy'];
  3671.         }
  3672.         if ($printType == 'forwardToEmail') {
  3673.             $printTypesEnabled = ['party_copy'];
  3674.         }
  3675.         $forwardToMailAddress '';
  3676.         if ($request->query->has('forwardToMailAddress'))
  3677.             $forwardToMailAddress $request->query->get('forwardToMailAddress');
  3678.         if ($forwardToMailAddress == '')
  3679.             $forwardToMailAddress $data['client_data']->getEmail();
  3680.         //print spec options end
  3681.         $company_data Company::getCompanyData($em$companyId);
  3682.         $document_mark = array(
  3683.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  3684.             'copy' => ''
  3685.         );
  3686.         if (($request->query->has('pdf') || $printType == 'forwardToEmail') && $this->get('knp_snappy.pdf')) {
  3687.             $html '';
  3688.             $pdf_response '';
  3689.             $dataForRender = array(
  3690.                 //full array here
  3691.                 'page_title' => 'Sales Order ' $data['doc_hash'],
  3692.                 'pdf' => true,
  3693.                 'forwardToMailAddress' => $forwardToMailAddress,
  3694.                 'data' => $data,
  3695.                 'printTypesEnabled' => $printTypesEnabled,
  3696.                 'sendAsPdf' => $sendAsPdf,
  3697.                 'export' => 'pdf,print,sendForward',
  3698.                 'document_mark_image' => $document_mark['original'],
  3699.                 'company_name' => $company_data->getName(),
  3700.                 'company_data' => $company_data,
  3701.                 'company_address' => $company_data->getAddress(),
  3702.                 'company_image' => $company_data->getImage(),
  3703.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  3704.                 'page_header' => 'New Product',
  3705.                 'document_type' => 'Sales Order',
  3706.                 'page_header_sub' => 'Add',
  3707.                 'projectList' => ProjectM::GetProjectListById($em),
  3708.                 'ExistingClients' => Client::GetExistingClientList($em$companyId),
  3709.                 'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  3710.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  3711.                 'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  3712.                 'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  3713.                 'salesMethodList' => SalesConstant::$salesMethod,
  3714.                 'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  3715.                 'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  3716.                 'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  3717.                 'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  3718.                 'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  3719.                 'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  3720.                 'sales_person_list' => Client::SalesPersonList($em),
  3721.                 'stage_list' => ProjectM::GetWorkStageList($em$companyId),
  3722.                 'regionList' => Client::RegionList($em$companyId),
  3723.                 'regionListForClient' => Client::RegionListForClientEntry($em$companyId),
  3724.                 'branchList' => Client::BranchList($em$companyId),
  3725.                 'headList' => Accounts::HeadList($em),
  3726.                 'positionList' => Position::getPositionList($em),
  3727.                 'item_data' => [],
  3728.                 'received' => 2,
  3729.                 'return' => 1,
  3730.                 'total_w_vat' => 1,
  3731.                 'total_vat' => 1,
  3732.                 'total_wo_vat' => 1,
  3733.                 'invoice_id' => 'abcd1234',
  3734.                 'created_by' => 'created by',
  3735.                 'created_at' => '',
  3736.                 'red' => 0,
  3737.                 'users' => Users::getUserListById($em)
  3738.             );
  3739.             if ($request->query->has('pdf') || $sendAsPdf == 1) {
  3740.                 //genertae the html only if pdf is returned or attached
  3741.                 $html $this->renderView(
  3742.                     '@Sales/pages/print/sales_order_print.html.twig',
  3743.                     array(
  3744.                         //full array here
  3745.                         'page_title' => 'Sales Order ' $data['doc_hash'],
  3746.                         'pdf' => true,
  3747.                         'forwardToMailAddress' => $forwardToMailAddress,
  3748.                         //                    'convertImageToBase64'=>true,
  3749.                         'data' => $data,
  3750.                         'printTypesEnabled' => $printTypesEnabled,
  3751.                         'sendAsPdf' => $sendAsPdf,
  3752.                         'export' => 'pdf,print',
  3753.                         'document_mark_image' => $document_mark['original'],
  3754.                         'company_name' => $company_data->getName(),
  3755.                         'company_data' => $company_data,
  3756.                         'company_address' => $company_data->getAddress(),
  3757.                         'company_image' => $company_data->getImage(),
  3758.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  3759.                         'page_header' => 'New Product',
  3760.                         'document_type' => 'Sales Order',
  3761.                         'page_header_sub' => 'Add',
  3762.                         'projectList' => ProjectM::GetProjectListById($em),
  3763.                         'ExistingClients' => Client::GetExistingClientList($em$companyId),
  3764.                         'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  3765.                         'clientTypeList' => Client::ClientTypeList($em$companyId),
  3766.                         'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  3767.                         'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  3768.                         'salesMethodList' => SalesConstant::$salesMethod,
  3769.                         'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  3770.                         'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  3771.                         'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  3772.                         'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  3773.                         'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  3774.                         'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  3775.                         'sales_person_list' => Client::SalesPersonList($em),
  3776.                         'stage_list' => ProjectM::GetWorkStageList($em$companyId),
  3777.                         'regionList' => Client::RegionList($em$companyId),
  3778.                         'regionListForClient' => Client::RegionListForClientEntry($em$companyId),
  3779.                         'branchList' => Client::BranchList($em$companyId),
  3780.                         'headList' => Accounts::HeadList($em),
  3781.                         'positionList' => Position::getPositionList($em),
  3782.                         //                'type_list'=>$type_list,
  3783.                         //                'mis_data'=>$mis_data,
  3784.                         //                'mis_print'=>$mis_print,
  3785.                         'item_data' => [],
  3786.                         'received' => 2,
  3787.                         'return' => 1,
  3788.                         'total_w_vat' => 1,
  3789.                         'total_vat' => 1,
  3790.                         'total_wo_vat' => 1,
  3791.                         'invoice_id' => 'abcd1234',
  3792.                         'created_by' => 'created by',
  3793.                         'created_at' => '',
  3794.                         'red' => 0,
  3795.                         'users' => Users::getUserListById($em)
  3796.                     )
  3797.                 );
  3798.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  3799.                     //                'orientation' => 'landscape',
  3800.                     //                'enable-javascript' => true,
  3801.                     //                'javascript-delay' => 1000,
  3802.                     'no-stop-slow-scripts' => false,
  3803.                     'no-background' => false,
  3804.                     'lowquality' => false,
  3805.                     'encoding' => 'utf-8',
  3806.                     //            'images' => true,
  3807.                     //            'cookie' => array(),
  3808.                     'dpi' => 300,
  3809.                     'image-dpi' => 300,
  3810.                     //                'enable-external-links' => true,
  3811.                     //                'enable-internal-links' => true
  3812.                 ));
  3813.             }
  3814.             if ($printType == 'forwardToEmail') {
  3815.                 $bodyHtml '';
  3816.                 $bodyTemplate '@Sales/pages/print/sales_order_print.html.twig';
  3817.                 $bodyData $dataForRender;
  3818.                 $attachments = [];
  3819.                 if ($sendAsPdf == 1) {
  3820.                     $attachments[] = array(
  3821.                         'file' => $pdf_response,
  3822.                         'fileName' => 'Order#' str_pad($id8'0'STR_PAD_LEFT) . '.pdf',
  3823.                         'fileType' => 'application/pdf'
  3824.                     );
  3825.                 }
  3826.                 //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  3827.                 $new_mail $this->get('mail_module');
  3828.                 $new_mail->sendMyMail(array(
  3829.                     'senderHash' => '_SALES_ORDERS_',
  3830.                     //                        'senderHash'=>'_CUSTOM_',
  3831.                     'forwardToMailAddress' => $forwardToMailAddress,
  3832.                     'subject' => $company_data->getName() . ' New Order#' str_pad($id8'0'STR_PAD_LEFT),
  3833.                     'fileName' => 'Order#' str_pad($id8'0'STR_PAD_LEFT) . '.pdf',
  3834.                     'attachments' => $attachments,
  3835.                     'toAddress' => $forwardToMailAddress,
  3836.                     //                        'fromAddress'=>'sales@entity.innobd.com',
  3837.                     //                        'userName'=>'sales@entity.innobd.com',
  3838.                     //                        'password'=>'Y41dh8g0112',
  3839.                     //                        'smtpServer'=>'smtp.hostinger.com',
  3840.                     //                        'smtpPort'=>587,
  3841.                     //                        'emailBody'=>$bodyHtml,
  3842.                     'mailTemplate' => $bodyTemplate,
  3843.                     'templateData' => $bodyData,
  3844.                     'embedCompanyImage' => 1,
  3845.                     'companyId' => $companyId,
  3846.                     'companyImagePath' => $company_data->getImage()
  3847.                 ));
  3848.                 return new JsonResponse(
  3849.                     array(
  3850.                         'success' => true
  3851.                     )
  3852.                 );
  3853.             } else {
  3854.                 return new Response(
  3855.                     $pdf_response,
  3856.                     200,
  3857.                     array(
  3858.                         'Content-Type' => 'application/pdf',
  3859.                         'Content-Disposition' => 'attachment; filename="sales_order_' $id '.pdf"'
  3860.                     )
  3861.                 );
  3862.             }
  3863.         }
  3864.         return $this->render(
  3865.             '@Sales/pages/print/sales_order_print.html.twig',
  3866.             array(
  3867.                 'page_title' => 'Sales Order ' $data['doc_hash'],
  3868.                 'data' => $data,
  3869.                 //                'convertImageToBase64'=>true,
  3870.                 'printTypesEnabled' => $printTypesEnabled,
  3871.                 'sendAsPdf' => $sendAsPdf,
  3872.                 'forwardToMailAddress' => $forwardToMailAddress,
  3873.                 'export' => 'pdf,print,sendForward',
  3874.                 'document_mark_image' => $document_mark['original'],
  3875.                 'company_name' => $company_data->getName(),
  3876.                 'company_data' => $company_data,
  3877.                 'company_address' => $company_data->getAddress(),
  3878.                 'company_image' => $company_data->getImage(),
  3879.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  3880.                 'page_header' => 'Sales Order',
  3881.                 'document_type' => 'Sales Order',
  3882.                 'page_header_sub' => 'Add',
  3883.                 'projectList' => ProjectM::GetProjectListById($em),
  3884.                 'ExistingClients' => Client::GetExistingClientList($em$companyId),
  3885.                 'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  3886.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  3887.                 'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  3888.                 'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  3889.                 'salesMethodList' => SalesConstant::$salesMethod,
  3890.                 'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  3891.                 'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  3892.                 'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  3893.                 'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  3894.                 'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  3895.                 'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  3896.                 'sales_person_list' => Client::SalesPersonList($em),
  3897.                 'stage_list' => ProjectM::GetWorkStageList($em$companyId),
  3898.                 'regionList' => Client::RegionList($em$companyId),
  3899.                 'regionListForClient' => Client::RegionListForClientEntry($em$companyId),
  3900.                 'branchList' => Client::BranchList($em$companyId),
  3901.                 'headList' => Accounts::HeadList($em),
  3902.                 'positionList' => Position::getPositionList($em),
  3903.                 //                'type_list'=>$type_list,
  3904.                 //                'mis_data'=>$mis_data,
  3905.                 //                'mis_print'=>$mis_print,
  3906.                 'item_data' => [],
  3907.                 'received' => 2,
  3908.                 'return' => 1,
  3909.                 'total_w_vat' => 1,
  3910.                 'total_vat' => 1,
  3911.                 'total_wo_vat' => 1,
  3912.                 'invoice_id' => 'abcd1234',
  3913.                 'created_by' => 'created by',
  3914.                 'created_at' => '',
  3915.                 'red' => 0,
  3916.                 'users' => Users::getUserListById($em)
  3917.             )
  3918.         );
  3919.     }
  3920.     //delivery order
  3921.     public function DeliveryOrderList(Request $request)
  3922.     {
  3923.         $q $this->getDoctrine()
  3924.             ->getRepository('ApplicationBundle:DeliveryOrder')
  3925.             ->findBy(
  3926.                 array(
  3927.                     'status' => GeneralConstant::ACTIVE,
  3928.                 ),
  3929.                 array(
  3930.                     'deliveryOrderDate' => 'DESC'
  3931.                 )
  3932.             );
  3933.         $stage_list = array(
  3934.             => 'Pending',
  3935.             => 'Pending',
  3936.             => 'Complete',
  3937.             => 'Partial',
  3938.         );
  3939.         $data = [];
  3940.         foreach ($q as $entry) {
  3941.             $data[] = array(
  3942.                 'doc_date' => $entry->getDeliveryOrderDate(),
  3943.                 'id' => $entry->getDeliveryOrderId(),
  3944.                 'doc_hash' => $entry->getDocumentHash(),
  3945.                 //                'so_amount'=>$entry->getSoAmount(),
  3946.                 'stage' => $stage_list[$entry->getStage()]
  3947.             );
  3948.         }
  3949.         return $this->render(
  3950.             '@Sales/pages/list/delivery_orders.html.twig',
  3951.             array(
  3952.                 'page_title' => 'Delivery Orders',
  3953.                 'data' => $data
  3954.             )
  3955.         );
  3956.     }
  3957.     public function ViewDeliveryOrder(Request $request$id)
  3958.     {
  3959.         $em $this->getDoctrine()->getManager();
  3960.         $dt SalesOrderM::GetDeliveryOrderDetails($em$id);
  3961.         return $this->render(
  3962.             '@Sales/pages/views/delivery_order_view.html.twig',
  3963.             array(
  3964.                 'page_title' => 'View',
  3965.                 'data' => $dt,
  3966.                 'auto_created' => $dt['auto_created'],
  3967.                 'approval_data' => System::checkIfApprovalExists(
  3968.                     $em,
  3969.                     array_flip(GeneralConstant::$Entity_list)['DeliveryOrder'],
  3970.                     $id,
  3971.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  3972.                 ),
  3973.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  3974.                     $this->getDoctrine()->getManager(),
  3975.                     array_flip(GeneralConstant::$Entity_list)['DeliveryOrder'],
  3976.                     $id,
  3977.                     $dt['created_by'],
  3978.                     $dt['edited_by']
  3979.                 ) : []
  3980.             )
  3981.         );
  3982.     }
  3983.     public function PrintDeliveryOrder(Request $request$id)
  3984.     {
  3985.         $em $this->getDoctrine()->getManager();
  3986.         $data SalesOrderM::GetDeliveryOrderDetails($em$id);
  3987.         $company_data Company::getCompanyData($em1);
  3988.         $document_mark = array(
  3989.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  3990.             'copy' => ''
  3991.         );
  3992.         return $this->render(
  3993.             '@Sales/pages/print/delivery_order_print.html.twig',
  3994.             array(
  3995.                 'page_title' => 'Delivery Order ' $data['doc_hash'],
  3996.                 'data' => $data,
  3997.                 'document_mark_image' => $document_mark['original'],
  3998.                 'company_name' => $company_data->getName(),
  3999.                 'company_data' => $company_data,
  4000.                 'company_address' => $company_data->getAddress(),
  4001.                 'company_image' => $company_data->getImage(),
  4002.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4003.                 'page_header' => 'New Product',
  4004.                 'document_type' => 'Delivery Order',
  4005.                 'page_header_sub' => 'Add',
  4006.                 //                'type_list'=>$type_list,
  4007.                 //                'mis_data'=>$mis_data,
  4008.                 //                'mis_print'=>$mis_print,
  4009.                 'item_data' => [],
  4010.                 'received' => 2,
  4011.                 'return' => 1,
  4012.                 'total_w_vat' => 1,
  4013.                 'total_vat' => 1,
  4014.                 'total_wo_vat' => 1,
  4015.                 'invoice_id' => 'abcd1234',
  4016.                 'created_by' => 'created by',
  4017.                 'created_at' => '',
  4018.                 'red' => 0,
  4019.             )
  4020.         );
  4021.     }
  4022.     //SalesReturn
  4023.     public function CreateSalesReturn(Request $request)
  4024.     {
  4025.         $em $this->getDoctrine()->getManager();
  4026.         $companyId $this->getLoggedUserCompanyId($request);
  4027.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4028.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4029.         if ($request->isMethod('POST')) {
  4030.             $em $this->getDoctrine()->getManager();
  4031.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesReturn']; //change
  4032.             $dochash $request->request->get('voucherNumber'); //change
  4033.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4034.             $approveRole $request->request->get('approvalRole');
  4035.             $approveHash $request->request->get('approvalHash');
  4036.             if (!DocValidation::isInsertable(
  4037.                 $em,
  4038.                 $entity_id,
  4039.                 $dochash,
  4040.                 $loginId,
  4041.                 $approveRole,
  4042.                 $approveHash
  4043.             )) {
  4044.                 $this->addFlash(
  4045.                     'error',
  4046.                     'Sorry Couldnot insert Data.'
  4047.                 );
  4048.             } else {
  4049.                 if ($request->request->has('check_allowed'))
  4050.                     $check_allowed 1;
  4051.                 $StID SalesOrderM::CreateNewSalesReturn(
  4052.                     $this->getDoctrine()->getManager(),
  4053.                     $request->request,
  4054.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4055.                     $this->getLoggedUserCompanyId($request)
  4056.                 );
  4057.                 //now add Approval info
  4058.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4059.                 $approveRole 1;  //created
  4060.                 $options = array(
  4061.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4062.                     'notification_server' => $this->container->getParameter('notification_server'),
  4063.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4064.                     'url' => $this->generateUrl(
  4065.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReturn']]['entity_view_route_path_name']
  4066.                     )
  4067.                 );
  4068.                 System::setApprovalInfo(
  4069.                     $this->getDoctrine()->getManager(),
  4070.                     $options,
  4071.                     array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
  4072.                     $StID,
  4073.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4074.                 );
  4075.                 System::createEditSignatureHash(
  4076.                     $this->getDoctrine()->getManager(),
  4077.                     array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
  4078.                     $StID,
  4079.                     $loginId,
  4080.                     $approveRole,
  4081.                     $request->request->get('approvalHash')
  4082.                 );
  4083.                 $this->addFlash(
  4084.                     'success',
  4085.                     'Sales return Added.'
  4086.                 );
  4087.                 $url $this->generateUrl(
  4088.                     'view_sales_return'
  4089.                 );
  4090.                 return $this->redirect($url "/" $StID);
  4091.             }
  4092.         }
  4093.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  4094.             array(
  4095.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  4096.             )
  4097.         );
  4098.         $INVLIST = [];
  4099.         foreach ($slotList as $slot) {
  4100.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  4101.         }
  4102.         return $this->render(
  4103.             '@Sales/pages/input_forms/sales_return.html.twig',
  4104.             array(
  4105.                 'page_title' => 'Sales Return',
  4106.                 'warehouseList' => Inventory::WarehouseList($em),
  4107.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  4108.                 'warehouseActionList' => $warehouse_action_list,
  4109.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4110.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  4111.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  4112.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  4113.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  4114.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  4115.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  4116.                 'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  4117.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  4118.                 'deliveryReceipts' => SalesOrderM::DeliveryReceiptList($this->getDoctrine()->getManager()),
  4119.                 'deliveryReceiptsArray' => SalesOrderM::DeliveryReceiptListArray($this->getDoctrine()->getManager()),
  4120.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  4121.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  4122.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  4123.                 'productList' => $productList Inventory::ProductList($em$companyId1),
  4124.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  4125.                 'unit_list' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  4126.                 'prefix_list' => array(
  4127.                     [
  4128.                         'id' => 1,
  4129.                         'value' => 'GN',
  4130.                         'text' => 'GN'
  4131.                     ]
  4132.                 ),
  4133.                 'assoc_list' => array(
  4134.                     [
  4135.                         'id' => 1,
  4136.                         'value' => 1,
  4137.                         'text' => 'GN'
  4138.                     ]
  4139.                 ),
  4140.                 'INVLIST' => $INVLIST
  4141.             )
  4142.         );
  4143.     }
  4144.     public function RefreshMrp(Request $request)
  4145.     {
  4146.         $em $this->getDoctrine()->getManager();
  4147.         $res Package::refreshMrp($em);
  4148.         return new JsonResponse(
  4149.             array(
  4150.                 'success' => true,
  4151.                 'data' => $res
  4152.             )
  4153.         );
  4154.     }
  4155.     public function SalesReturnList(Request $request)
  4156.     {
  4157.         $em $this->getDoctrine()->getManager();
  4158.         $companyId $this->getLoggedUserCompanyId($request);
  4159.         $q $this->getDoctrine()
  4160.             ->getRepository('ApplicationBundle:SalesReturn')
  4161.             ->findBy(
  4162.                 array(
  4163.                     'status' => GeneralConstant::ACTIVE,
  4164.                     'CompanyId' => $companyId
  4165.                     //                    'approved' =>  GeneralConstant::APPROVED,
  4166.                 )
  4167.             );
  4168.         $stage_list = array(
  4169.             => 'Pending',
  4170.             => 'Pending',
  4171.             => 'Complete',
  4172.             => 'Partial',
  4173.         );
  4174.         $data = [];
  4175.         $clientList SalesOrderM::GetClientList($em, [], $companyId);
  4176.         foreach ($q as $entry) {
  4177.             $clientId $entry->getClientId();
  4178.             $data[] = array(
  4179.                 'doc_date' => $entry->getSalesReturnDate(),
  4180.                 'id' => $entry->getSalesReturnId(),
  4181.                 'doc_hash' => $entry->getDocumentHash(),
  4182.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  4183.                 'stage' => $stage_list[$entry->getStage()],
  4184.                 'client_id' => $clientId,
  4185.                 'client_name' => $clientList[$clientId]['client_name'],
  4186.                 'client_code' => $clientList[$clientId]['client_code'],
  4187.                 'client_alternate_code' => $clientList[$clientId]['client_alternate_code'],
  4188.             );
  4189.         }
  4190.         return $this->render(
  4191.             '@Sales/pages/list/sales_return_list.html.twig',
  4192.             array(
  4193.                 'page_title' => 'Sales Return List',
  4194.                 'data' => $data
  4195.             )
  4196.         );
  4197.     }
  4198.     public function ViewSalesReturn(Request $request$id)
  4199.     {
  4200.         $em $this->getDoctrine()->getManager();
  4201.         $dt SalesOrderM::GetSalesReturnDetails($em$id);
  4202.         return $this->render(
  4203.             '@Sales/pages/views/view_sales_return.html.twig',
  4204.             array(
  4205.                 'page_title' => 'Sales Return',
  4206.                 'data' => $dt,
  4207.                 'approval_data' => System::checkIfApprovalExists(
  4208.                     $em,
  4209.                     array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
  4210.                     $id,
  4211.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4212.                 ),
  4213.                 'document_log' => System::getDocumentLog(
  4214.                     $this->getDoctrine()->getManager(),
  4215.                     array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
  4216.                     $id,
  4217.                     $dt['created_by'],
  4218.                     $dt['edited_by']
  4219.                 )
  4220.             )
  4221.         );
  4222.     }
  4223.     public function PrintSalesReturn(Request $request$id)
  4224.     {
  4225.         $em $this->getDoctrine()->getManager();
  4226.         $dt SalesOrderM::GetSalesReturnDetails($em$id);
  4227.         $company_data Company::getCompanyData($em1);
  4228.         $document_mark = array(
  4229.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4230.             'copy' => ''
  4231.         );
  4232.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  4233.             $html $this->renderView(
  4234.                 '@Sales/pages/print/print_sales_return.html.twig',
  4235.                 array(
  4236.                     //full array here
  4237.                     'pdf' => true,
  4238.                     'page_title' => 'Sales return',
  4239.                     'export' => 'pdf,print',
  4240.                     'data' => $dt,
  4241.                     'approval_data' => System::checkIfApprovalExists(
  4242.                         $em,
  4243.                         array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
  4244.                         $id,
  4245.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4246.                     ),
  4247.                     'document_log' => System::getDocumentLog(
  4248.                         $this->getDoctrine()->getManager(),
  4249.                         array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
  4250.                         $id,
  4251.                         $dt['created_by'],
  4252.                         $dt['edited_by']
  4253.                     ),
  4254.                     'document_mark_image' => $document_mark['original'],
  4255.                     'company_name' => $company_data->getName(),
  4256.                     'company_data' => $company_data,
  4257.                     'company_address' => $company_data->getAddress(),
  4258.                     'company_image' => $company_data->getImage(),
  4259.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  4260.                     'red' => 0
  4261.                 )
  4262.             );
  4263.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  4264.                 //                'orientation' => 'landscape',
  4265.                 //                'enable-javascript' => true,
  4266.                 //                'javascript-delay' => 1000,
  4267.                 'no-stop-slow-scripts' => false,
  4268.                 'no-background' => false,
  4269.                 'lowquality' => false,
  4270.                 'encoding' => 'utf-8',
  4271.                 //            'images' => true,
  4272.                 //            'cookie' => array(),
  4273.                 'dpi' => 300,
  4274.                 'image-dpi' => 300,
  4275.                 //                'enable-external-links' => true,
  4276.                 //                'enable-internal-links' => true
  4277.             ));
  4278.             return new Response(
  4279.                 $pdf_response,
  4280.                 200,
  4281.                 array(
  4282.                     'Content-Type' => 'application/pdf',
  4283.                     'Content-Disposition' => 'attachment; filename="sales_return_' $id '.pdf"'
  4284.                 )
  4285.             );
  4286.         }
  4287.         return $this->render(
  4288.             '@Sales/pages/print/print_sales_return.html.twig',
  4289.             array(
  4290.                 'page_title' => 'Sales Return',
  4291.                 'export' => 'pdf,print',
  4292.                 'data' => $dt,
  4293.                 'approval_data' => System::checkIfApprovalExists(
  4294.                     $em,
  4295.                     array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
  4296.                     $id,
  4297.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4298.                 ),
  4299.                 'document_log' => System::getDocumentLog(
  4300.                     $this->getDoctrine()->getManager(),
  4301.                     array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
  4302.                     $id,
  4303.                     $dt['created_by'],
  4304.                     $dt['edited_by']
  4305.                 ),
  4306.                 'document_mark_image' => $document_mark['original'],
  4307.                 'company_name' => $company_data->getName(),
  4308.                 'company_data' => $company_data,
  4309.                 'company_address' => $company_data->getAddress(),
  4310.                 'company_image' => $company_data->getImage(),
  4311.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4312.                 'red' => 0
  4313.             )
  4314.         );
  4315.     }
  4316.     //after Sales Service order
  4317.     public function CreateAfterSalesServiceOrder(Request $request$stage 0$id 0)
  4318.     {
  4319.         $em $this->getDoctrine()->getManager();
  4320.         $companyId $this->getLoggedUserCompanyId($request);
  4321.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4322.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4323.         $service Inventory::ServiceList($em$companyId);
  4324.         $issueQuery $em->getRepository('ApplicationBundle:AfterSalesServiceIssue')->findAll();
  4325.         $issue = [];
  4326.         foreach ($issueQuery as $d) {
  4327.             $issue[$d->getId()] = array(
  4328.                 'id' => $d->getId(),
  4329.                 'documentName' => $d->getCoreIssue(),
  4330.                 'text' => $d->getCoreIssue(),
  4331.                 'isParent' => $d->getIsParent(),
  4332.             );
  4333.         }
  4334.         if ($request->isMethod('POST')) {
  4335.             $em $this->getDoctrine()->getManager();
  4336.             $entity_id array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder']; //change
  4337.             $dochash $request->request->get('voucherNumber'); //change
  4338.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4339.             $approveRole $request->request->get('approvalRole');
  4340.             $approveHash $request->request->get('approvalHash');
  4341.             if (!DocValidation::isInsertable(
  4342.                 $em,
  4343.                 $entity_id,
  4344.                 $dochash,
  4345.                 $loginId,
  4346.                 $approveRole,
  4347.                 $approveHash
  4348.             )) {
  4349.                 $this->addFlash(
  4350.                     'error',
  4351.                     'Sorry Couldnot insert Data.'
  4352.                 );
  4353.             } else {
  4354.                 if ($request->request->has('check_allowed'))
  4355.                     $check_allowed 1;
  4356.                 Client::ProcessTempClients($em$companyId$clientIds = [$request->request->get('returning_client_id'null)]);
  4357.                 $StID SalesOrderM::CreateNewAfterSalesServiceOrder(
  4358.                     $this->getDoctrine()->getManager(),
  4359.                     0,
  4360.                     $request->request,
  4361.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4362.                     $this->getLoggedUserCompanyId($request)
  4363.                 );
  4364.                 //now add Approval info
  4365.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4366.                 $approveRole 1;  //created
  4367.                 $options = array(
  4368.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4369.                     'notification_server' => $this->container->getParameter('notification_server'),
  4370.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4371.                     'url' => $this->generateUrl(
  4372.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder']]['entity_view_route_path_name']
  4373.                     )
  4374.                 );
  4375.                 System::setApprovalInfo(
  4376.                     $this->getDoctrine()->getManager(),
  4377.                     $options,
  4378.                     array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
  4379.                     $StID,
  4380.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4381.                 );
  4382.                 System::createEditSignatureHash(
  4383.                     $this->getDoctrine()->getManager(),
  4384.                     array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
  4385.                     $StID,
  4386.                     $loginId,
  4387.                     $approveRole,
  4388.                     $request->request->get('approvalHash')
  4389.                 );
  4390.                 $this->addFlash(
  4391.                     'success',
  4392.                     'Preliminary Info Added.'
  4393.                 );
  4394.                 $url $this->generateUrl(
  4395.                     'view_after_sales_service_order'
  4396.                 );
  4397.                 return $this->redirect($url "/" $StID);
  4398.             }
  4399.         }
  4400.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  4401.             array(
  4402.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  4403.             )
  4404.         );
  4405.         $INVLIST = [];
  4406.         foreach ($slotList as $slot) {
  4407.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  4408.         }
  4409.         return $this->render(
  4410.             '@Sales/pages/input_forms/after_sales_service_order.html.twig',
  4411.             array(
  4412.                 'page_title' => 'After Sales Service Order',
  4413.                 'warehouseList' => Inventory::WarehouseList($em),
  4414.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  4415.                 'warehouseActionList' => $warehouse_action_list,
  4416.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  4417.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4418.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  4419.                 'ClientListByAcHead' => [],
  4420.                 //                'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  4421.                 'ClientList' => [],
  4422.                 //                'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  4423.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  4424.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  4425.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  4426.                 'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  4427.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  4428.                 'deliveryReceipts' => SalesOrderM::DeliveryReceiptList($this->getDoctrine()->getManager()),
  4429.                 'deliveryReceiptsArray' => SalesOrderM::DeliveryReceiptListArray($this->getDoctrine()->getManager()),
  4430.                 'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  4431.                 'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
  4432.                 'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
  4433.                 'productList' => $productList Inventory::ProductList($em$companyId1),
  4434.                 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
  4435.                 'unit_list' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  4436.                 'service' => $service,
  4437.                 'issue' => $issue,
  4438.                 'accessories' => AfterSalesServiceConstant::$accessories,
  4439.                 'prefix_list' => array(
  4440.                     [
  4441.                         'id' => 1,
  4442.                         'value' => 'GN',
  4443.                         'text' => 'GN'
  4444.                     ]
  4445.                 ),
  4446.                 'assoc_list' => array(
  4447.                     [
  4448.                         'id' => 1,
  4449.                         'value' => 1,
  4450.                         'text' => 'GN'
  4451.                     ]
  4452.                 ),
  4453.                 'INVLIST' => $INVLIST
  4454.             )
  4455.         );
  4456.     }
  4457.     public function getIndividualIssue(Request $request$id)
  4458.     {
  4459.         $em $this->getDoctrine()->getManager();
  4460.         if ($id == 0) {
  4461.             if ($request->request->has('documentId'))
  4462.                 $id $request->request->get('documentId');
  4463.         }
  4464.         $document $em->getRepository('ApplicationBundle:AfterSalesServiceIssue')->find($id);
  4465.         return new JsonResponse(
  4466.             array(
  4467.                 'success' => true,
  4468.                 'rowId' => $request->request->get('rowId'),
  4469.                 'detailedIssue' => json_decode($document->getDetailedissues()),
  4470.                 'checklist' => json_decode($document->getPreliminaryCheckList()),
  4471.             )
  4472.         );
  4473.     }
  4474.     public function AfterSalesServiceOrderList(Request $request)
  4475.     {
  4476.         $em $this->getDoctrine()->getManager();
  4477.         $companyId $this->getLoggedUserCompanyId($request);
  4478.         $q $this->getDoctrine()
  4479.             ->getRepository('ApplicationBundle:AfterSalesServiceOrder')
  4480.             ->findBy(
  4481.                 array(
  4482.                     'status' => GeneralConstant::ACTIVE,
  4483.                     'CompanyId' => $companyId
  4484.                     //                    'approved' =>  GeneralConstant::APPROVED,
  4485.                 )
  4486.             );
  4487.         $stage_list = array(
  4488.             => 'Pending',
  4489.             => 'Pending',
  4490.             => 'Complete',
  4491.             => 'Partial',
  4492.         );
  4493.         $data = [];
  4494.         $clientList SalesOrderM::GetClientList($em, [], $companyId);
  4495.         foreach ($q as $entry) {
  4496.             $clientId $entry->getClientId();
  4497.             $data[] = array(
  4498.                 'doc_date' => $entry->getAfterSalesServiceOrderDate(),
  4499.                 'id' => $entry->getAfterSalesServiceOrderId(),
  4500.                 'doc_hash' => $entry->getDocumentHash(),
  4501.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  4502.                 'stage' => $stage_list[$entry->getStage()],
  4503.                 'client_id' => $clientId,
  4504.                 'client_name' => $clientList[$clientId]['client_name'],
  4505.                 'client_code' => $clientList[$clientId]['client_code'],
  4506.                 'client_alternate_code' => $clientList[$clientId]['client_alternate_code'],
  4507.             );
  4508.         }
  4509.         return $this->render(
  4510.             '@Sales/pages/list/after_sales_service_order_list.html.twig',
  4511.             array(
  4512.                 'page_title' => 'After Sales Service Order List',
  4513.                 'data' => $data
  4514.             )
  4515.         );
  4516.     }
  4517.     public function ViewAfterSalesServiceOrder(Request $request$id 0)
  4518.     {
  4519.         $em $this->getDoctrine()->getManager();
  4520.         $companyId $this->getLoggedUserCompanyId($request);
  4521.         $afterSalesServiceOrderDetails $em->getRepository('ApplicationBundle:AfterSalesServiceOrder')->find($id);
  4522.         $wareHouseActionList $em->getRepository('ApplicationBundle:WarehouseAction')->findAll();
  4523.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4524.         $branchList Client::BranchList($em$companyId, []);
  4525.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4526.         //        $producByCodelist = Inventory::productByCodeList($em, $this->getLoggedUserCompanyId($request), 'object');;
  4527.         $productByCodeData $em->getRepository('ApplicationBundle:ProductByCode')->findOneBy(
  4528.             array(
  4529.                 'productByCodeId' => $afterSalesServiceOrderDetails->getProductByCodeId()
  4530.             )
  4531.         );
  4532.         //        $producByCodelistArray = Inventory::productByCodeList($em, $this->getLoggedUserCompanyId($request), 'array');;
  4533.         $issueQuery $em->getRepository('ApplicationBundle:AfterSalesServiceIssue')->findAll();
  4534.         $issue = [];
  4535.         foreach ($issueQuery as $d) {
  4536.             $issue[$d->getId()] = array(
  4537.                 'id' => $d->getId(),
  4538.                 'documentName' => $d->getCoreIssue(),
  4539.                 'text' => $d->getCoreIssue(),
  4540.                 'isParent' => $d->getIsParent(),
  4541.             );
  4542.         }
  4543.         //$dt = SalesOrderM::GetAfterSalesServiceOrderDetails($em, $id);
  4544.         return $this->render(
  4545.             '@Sales/pages/views/view_after_sales_service_order.html.twig',
  4546.             array(
  4547.                 'page_title' => 'View Preliminary Registration',
  4548.                 'afterSalesServiceOrderDetails' => $afterSalesServiceOrderDetails,
  4549.                 'warehouseActionList' => $warehouse_action_list,
  4550.                 'branchList' => $branchList,
  4551.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4552.                 'productByCodeData' => $productByCodeData,
  4553.                 //                'producByCodelistArray' => $producByCodelistArray,
  4554.                 'issue' => $issue,
  4555.                 'accessories' => AfterSalesServiceConstant::$accessories,
  4556.                 'accessoriesFromDb' => json_decode($afterSalesServiceOrderDetails->getAccessories(), true),
  4557.             )
  4558.         );
  4559.     }
  4560.     public function PrintAfterSalesServiceOrder(Request $request$id)
  4561.     {
  4562.         $em $this->getDoctrine()->getManager();
  4563.         $dt SalesOrderM::GetAfterSalesServiceOrderDetails($em$id);
  4564.         $company_data Company::getCompanyData($em1);
  4565.         $document_mark = array(
  4566.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4567.             'copy' => ''
  4568.         );
  4569.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  4570.             $html $this->renderView(
  4571.                 '@Sales/pages/print/print_after_sales_service_order.html.twig',
  4572.                 array(
  4573.                     //full array here
  4574.                     'pdf' => true,
  4575.                     'page_title' => 'Sales return',
  4576.                     'export' => 'pdf,print',
  4577.                     'data' => $dt,
  4578.                     'approval_data' => System::checkIfApprovalExists(
  4579.                         $em,
  4580.                         array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
  4581.                         $id,
  4582.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4583.                     ),
  4584.                     'document_log' => System::getDocumentLog(
  4585.                         $this->getDoctrine()->getManager(),
  4586.                         array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
  4587.                         $id,
  4588.                         $dt['created_by'],
  4589.                         $dt['edited_by']
  4590.                     ),
  4591.                     'document_mark_image' => $document_mark['original'],
  4592.                     'company_name' => $company_data->getName(),
  4593.                     'company_data' => $company_data,
  4594.                     'company_address' => $company_data->getAddress(),
  4595.                     'company_image' => $company_data->getImage(),
  4596.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  4597.                     'red' => 0
  4598.                 )
  4599.             );
  4600.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  4601.                 //                'orientation' => 'landscape',
  4602.                 //                'enable-javascript' => true,
  4603.                 //                'javascript-delay' => 1000,
  4604.                 'no-stop-slow-scripts' => false,
  4605.                 'no-background' => false,
  4606.                 'lowquality' => false,
  4607.                 'encoding' => 'utf-8',
  4608.                 //            'images' => true,
  4609.                 //            'cookie' => array(),
  4610.                 'dpi' => 300,
  4611.                 'image-dpi' => 300,
  4612.                 //                'enable-external-links' => true,
  4613.                 //                'enable-internal-links' => true
  4614.             ));
  4615.             return new Response(
  4616.                 $pdf_response,
  4617.                 200,
  4618.                 array(
  4619.                     'Content-Type' => 'application/pdf',
  4620.                     'Content-Disposition' => 'attachment; filename="after_sales_service_order_' $id '.pdf"'
  4621.                 )
  4622.             );
  4623.         }
  4624.         return $this->render(
  4625.             '@Sales/pages/print/print_after_sales_service_order.html.twig',
  4626.             array(
  4627.                 'page_title' => 'After Sales Service Order',
  4628.                 'export' => 'pdf,print',
  4629.                 'data' => $dt,
  4630.                 'approval_data' => System::checkIfApprovalExists(
  4631.                     $em,
  4632.                     array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
  4633.                     $id,
  4634.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4635.                 ),
  4636.                 'document_log' => System::getDocumentLog(
  4637.                     $this->getDoctrine()->getManager(),
  4638.                     array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
  4639.                     $id,
  4640.                     $dt['created_by'],
  4641.                     $dt['edited_by']
  4642.                 ),
  4643.                 'document_mark_image' => $document_mark['original'],
  4644.                 'company_name' => $company_data->getName(),
  4645.                 'company_data' => $company_data,
  4646.                 'company_address' => $company_data->getAddress(),
  4647.                 'company_image' => $company_data->getImage(),
  4648.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4649.                 'red' => 0
  4650.             )
  4651.         );
  4652.     }
  4653.     public function SoAmendmentList(Request $request)
  4654.     {
  4655.         $q $this->getDoctrine()
  4656.             ->getRepository('ApplicationBundle:SoAmendment')
  4657.             ->findBy(
  4658.                 array(
  4659.                     'status' => GeneralConstant::ACTIVE,
  4660.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  4661.                     //                    'approved' =>  GeneralConstant::APPROVED,
  4662.                 )
  4663.             );
  4664.         $stage_list = array(
  4665.             => 'Pending',
  4666.             => 'Pending',
  4667.             => 'Complete',
  4668.             => 'Partial',
  4669.         );
  4670.         $data = [];
  4671.         foreach ($q as $entry) {
  4672.             $data[] = array(
  4673.                 'doc_date' => $entry->getSoAmendmentDate(),
  4674.                 'id' => $entry->getSoAmendmentId(),
  4675.                 'doc_hash' => $entry->getDocumentHash(),
  4676.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  4677.                 //            'stage'=>$stage_list[$entry->getStage()]
  4678.             );
  4679.         }
  4680.         return $this->render(
  4681.             '@Sales/pages/list/so_amendment_list.html.twig',
  4682.             array(
  4683.                 'page_title' => 'Sales Order Amendment List',
  4684.                 'data' => $data
  4685.             )
  4686.         );
  4687.     }
  4688.     public function ViewSoAmendment(Request $request$id)
  4689.     {
  4690.         $em $this->getDoctrine()->getManager();
  4691.         $dt SalesOrderM::GetSoAmendmentDetails($em$id);
  4692.         return $this->render(
  4693.             '@Sales/pages/views/view_so_amendment.html.twig',
  4694.             array(
  4695.                 'page_title' => 'Sales Order Amendment',
  4696.                 'data' => $dt,
  4697.                 'approval_data' => System::checkIfApprovalExists(
  4698.                     $em,
  4699.                     array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
  4700.                     $id,
  4701.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4702.                 ),
  4703.                 'document_log' => System::getDocumentLog(
  4704.                     $this->getDoctrine()->getManager(),
  4705.                     array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
  4706.                     $id,
  4707.                     $dt['created_by'],
  4708.                     $dt['edited_by']
  4709.                 )
  4710.             )
  4711.         );
  4712.     }
  4713.     public function PrintSoAmendment(Request $request$id)
  4714.     {
  4715.         $em $this->getDoctrine()->getManager();
  4716.         $dt SalesOrderM::GetSoAmendmentDetails($em$id);
  4717.         $company_data Company::getCompanyData($em1);
  4718.         $document_mark = array(
  4719.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  4720.             'copy' => ''
  4721.         );
  4722.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  4723.             $html $this->renderView(
  4724.                 '@Sales/pages/print/print_so_amendment.html.twig',
  4725.                 array(
  4726.                     //full array here
  4727.                     'pdf' => true,
  4728.                     'page_title' => 'Sales Order Amendment',
  4729.                     'export' => 'pdf,print',
  4730.                     'data' => $dt,
  4731.                     'approval_data' => System::checkIfApprovalExists(
  4732.                         $em,
  4733.                         array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
  4734.                         $id,
  4735.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4736.                     ),
  4737.                     'document_log' => System::getDocumentLog(
  4738.                         $this->getDoctrine()->getManager(),
  4739.                         array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
  4740.                         $id,
  4741.                         $dt['created_by'],
  4742.                         $dt['edited_by']
  4743.                     ),
  4744.                     'document_mark_image' => $document_mark['original'],
  4745.                     'company_name' => $company_data->getName(),
  4746.                     'company_data' => $company_data,
  4747.                     'company_address' => $company_data->getAddress(),
  4748.                     'company_image' => $company_data->getImage(),
  4749.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  4750.                     'red' => 0
  4751.                 )
  4752.             );
  4753.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  4754.                 //                'orientation' => 'landscape',
  4755.                 //                'enable-javascript' => true,
  4756.                 //                'javascript-delay' => 1000,
  4757.                 'no-stop-slow-scripts' => false,
  4758.                 'no-background' => false,
  4759.                 'lowquality' => false,
  4760.                 'encoding' => 'utf-8',
  4761.                 //            'images' => true,
  4762.                 //            'cookie' => array(),
  4763.                 'dpi' => 300,
  4764.                 'image-dpi' => 300,
  4765.                 //                'enable-external-links' => true,
  4766.                 //                'enable-internal-links' => true
  4767.             ));
  4768.             return new Response(
  4769.                 $pdf_response,
  4770.                 200,
  4771.                 array(
  4772.                     'Content-Type' => 'application/pdf',
  4773.                     'Content-Disposition' => 'attachment; filename="so_amendment_' $id '.pdf"'
  4774.                 )
  4775.             );
  4776.         }
  4777.         return $this->render(
  4778.             '@Sales/pages/print/print_so_amendment.html.twig',
  4779.             array(
  4780.                 'page_title' => 'Sales Order Amendment',
  4781.                 'export' => 'pdf,print',
  4782.                 'data' => $dt,
  4783.                 'approval_data' => System::checkIfApprovalExists(
  4784.                     $em,
  4785.                     array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
  4786.                     $id,
  4787.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  4788.                 ),
  4789.                 'document_log' => System::getDocumentLog(
  4790.                     $this->getDoctrine()->getManager(),
  4791.                     array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
  4792.                     $id,
  4793.                     $dt['created_by'],
  4794.                     $dt['edited_by']
  4795.                 ),
  4796.                 'document_mark_image' => $document_mark['original'],
  4797.                 'company_name' => $company_data->getName(),
  4798.                 'company_data' => $company_data,
  4799.                 'company_address' => $company_data->getAddress(),
  4800.                 'company_image' => $company_data->getImage(),
  4801.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  4802.                 'red' => 0
  4803.             )
  4804.         );
  4805.     }
  4806.     //ItemReceivedAndReplacement
  4807.     public function CreateItemReceivedAndReplacement(Request $request)
  4808.     {
  4809.         $em $this->getDoctrine()->getManager();
  4810.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  4811.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  4812.         if ($request->isMethod('POST')) {
  4813.             $em $this->getDoctrine()->getManager();
  4814.             $entity_id array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement']; //change
  4815.             $dochash $request->request->get('voucherNumber'); //change
  4816.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4817.             $approveRole $request->request->get('approvalRole');
  4818.             $approveHash $request->request->get('approvalHash');
  4819.             if (!DocValidation::isInsertable(
  4820.                 $em,
  4821.                 $entity_id,
  4822.                 $dochash,
  4823.                 $loginId,
  4824.                 $approveRole,
  4825.                 $approveHash
  4826.             )) {
  4827.                 $this->addFlash(
  4828.                     'error',
  4829.                     'Sorry Couldnot insert Data.'
  4830.                 );
  4831.             } else {
  4832.                 if ($request->request->has('check_allowed'))
  4833.                     $check_allowed 1;
  4834.                 $StID SalesOrderM::CreateNewItemReceivedAndReplacement(
  4835.                     $this->getDoctrine()->getManager(),
  4836.                     $request->request,
  4837.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  4838.                     $this->getLoggedUserCompanyId($request)
  4839.                 );
  4840.                 //now add Approval info
  4841.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  4842.                 $approveRole 1;  //created
  4843.                 $options = array(
  4844.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  4845.                     'notification_server' => $this->container->getParameter('notification_server'),
  4846.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  4847.                     'url' => $this->generateUrl(
  4848.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement']]['entity_view_route_path_name']
  4849.                     )
  4850.                 );
  4851.                 System::setApprovalInfo(
  4852.                     $this->getDoctrine()->getManager(),
  4853.                     $options,
  4854.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  4855.                     $StID,
  4856.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  4857.                 );
  4858.                 System::createEditSignatureHash(
  4859.                     $this->getDoctrine()->getManager(),
  4860.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  4861.                     $StID,
  4862.                     $loginId,
  4863.                     $approveRole,
  4864.                     $request->request->get('approvalHash')
  4865.                 );
  4866.                 $this->addFlash(
  4867.                     'success',
  4868.                     'Item Return & Replacement Added.'
  4869.                 );
  4870.                 $url $this->generateUrl(
  4871.                     'view_irr'
  4872.                 );
  4873.                 return $this->redirect($url "/" $StID);
  4874.             }
  4875.         }
  4876.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  4877.             array(
  4878.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  4879.             )
  4880.         );
  4881.         $INVLIST = [];
  4882.         foreach ($slotList as $slot) {
  4883.             $INVLIST[$slot->getWarehouseId() . '_' $slot->getActionTagId() . '_' $slot->getproductId()] = $slot->getQty();
  4884.         }
  4885.         $companyId $this->getLoggedUserCompanyId($request);
  4886.         $productListArray = [];
  4887.         $subCategoryListArray = [];
  4888.         $categoryListArray = [];
  4889.         $igListArray = [];
  4890.         $unitListArray = [];
  4891.         $brandListArray = [];
  4892.         $productList Inventory::ProductList($em$companyId1);
  4893.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  4894.         $categoryList Inventory::ProductCategoryList($em$companyId);
  4895.         $igList Inventory::ItemGroupList($em$companyId);
  4896.         $unitList Inventory::UnitTypeList($em);
  4897.         $brandList Inventory::GetBrandList($em$companyId);
  4898.         foreach ($productList as $product$productListArray[] = $product;
  4899.         foreach ($categoryList as $product$categoryListArray[] = $product;
  4900.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  4901.         foreach ($igList as $product$igListArray[] = $product;
  4902.         foreach ($unitList as $product$unitListArray[] = $product;
  4903.         foreach ($brandList as $product$brandListArray[] = $product;
  4904.         $salesReturnList = [];
  4905.         $salesReturnListArray = [];
  4906.         $QD $this->getDoctrine()
  4907.             ->getRepository('ApplicationBundle:SalesReturn')
  4908.             ->findBy(
  4909.                 array(
  4910.                     'stage' => GeneralConstant::STAGE_INITIATED,
  4911.                     'approved' => 1,
  4912.                     'status' => GeneralConstant::ACTIVE
  4913.                 )
  4914.             );
  4915.         foreach ($QD as $dt) {
  4916.             $salesReturnList[$dt->getSalesReturnId()] = array(
  4917.                 'id' => $dt->getSalesReturnId(),
  4918.                 'name' => $dt->getDocumentHash(),
  4919.                 'soId' => $dt->getSalesOrderId(),
  4920.                 'text' => $dt->getDocumentHash(),
  4921.             );
  4922.             $salesReturnListArray[] = array(
  4923.                 'id' => $dt->getSalesReturnId(),
  4924.                 'name' => $dt->getDocumentHash(),
  4925.                 'soId' => $dt->getSalesOrderId(),
  4926.                 'text' => $dt->getDocumentHash(),
  4927.             );
  4928.         }
  4929.         return $this->render(
  4930.             '@Sales/pages/input_forms/irr.html.twig',
  4931.             array(
  4932.                 'page_title' => 'Item Return & Replacement',
  4933.                 'warehouseList' => Inventory::WarehouseList($em),
  4934.                 'warehouseListArray' => Inventory::WarehouseListArray($em),
  4935.                 'warehouseActionList' => $warehouse_action_list,
  4936.                 'warehouseActionListArray' => $warehouse_action_list_array,
  4937.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  4938.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  4939.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  4940.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  4941.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
  4942.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
  4943.                 //                'deliveryOrders'=>SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
  4944.                 //                'deliveryOrdersArray'=>SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
  4945.                 //                'deliveryReceipts'=>SalesOrderM::DeliveryReceiptList($this->getDoctrine()->getManager()),
  4946.                 //                'deliveryReceiptsArray'=>SalesOrderM::DeliveryReceiptListArray($this->getDoctrine()->getManager()),
  4947.                 'salesReturnList' => $salesReturnList,
  4948.                 'salesReturnListArray' => $salesReturnListArray,
  4949.                 'productList' => $productList,
  4950.                 'subCategoryList' => $subCategoryList,
  4951.                 'categoryList' => $categoryList,
  4952.                 'igList' => $igList,
  4953.                 'unitList' => $unitList,
  4954.                 'brandList' => $brandList,
  4955.                 'brandListArray' => $brandListArray,
  4956.                 'productListArray' => $productListArray,
  4957.                 'subCategoryListArray' => $subCategoryListArray,
  4958.                 'categoryListArray' => $categoryListArray,
  4959.                 'igListArray' => $igListArray,
  4960.                 'unitListArray' => $unitListArray,
  4961.                 'prefix_list' => array(
  4962.                     [
  4963.                         'id' => 1,
  4964.                         'value' => 'GN',
  4965.                         'text' => 'GN'
  4966.                     ]
  4967.                 ),
  4968.                 'assoc_list' => array(
  4969.                     [
  4970.                         'id' => 1,
  4971.                         'value' => 1,
  4972.                         'text' => 'GN'
  4973.                     ]
  4974.                 ),
  4975.                 'INVLIST' => $INVLIST
  4976.             )
  4977.         );
  4978.     }
  4979.     public function ItemReceivedAndReplacementList(Request $request)
  4980.     {
  4981.         $q $this->getDoctrine()
  4982.             ->getRepository('ApplicationBundle:ItemReceivedAndReplacement')
  4983.             ->findBy(
  4984.                 array(
  4985.                     'status' => GeneralConstant::ACTIVE,
  4986.                     'CompanyId' => $this->getLoggedUserCompanyId($request)
  4987.                     //                    'approved' =>  GeneralConstant::APPROVED,
  4988.                 )
  4989.             );
  4990.         $stage_list = array(
  4991.             => 'Pending',
  4992.             => 'Pending',
  4993.             => 'Complete',
  4994.             => 'Partial',
  4995.         );
  4996.         $data = [];
  4997.         foreach ($q as $entry) {
  4998.             $data[] = array(
  4999.                 'doc_date' => $entry->getItemReceivedAndReplacementDate(),
  5000.                 'id' => $entry->getItemReceivedAndReplacementId(),
  5001.                 'doc_hash' => $entry->getDocumentHash(),
  5002.                 'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
  5003.                 'stage' => $stage_list[$entry->getStage()]
  5004.             );
  5005.         }
  5006.         return $this->render(
  5007.             '@Sales/pages/list/irr_list.html.twig',
  5008.             array(
  5009.                 'page_title' => 'Item Return & Replacement List',
  5010.                 'data' => $data
  5011.             )
  5012.         );
  5013.     }
  5014.     public function ViewItemReceivedAndReplacement(Request $request$id)
  5015.     {
  5016.         $em $this->getDoctrine()->getManager();
  5017.         $dt SalesOrderM::GetItemReceivedAndReplacementDetails($em$id);
  5018.         return $this->render(
  5019.             '@Sales/pages/views/view_irr.html.twig',
  5020.             array(
  5021.                 'page_title' => 'Item Received And Replacement',
  5022.                 'data' => $dt,
  5023.                 'approval_data' => System::checkIfApprovalExists(
  5024.                     $em,
  5025.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  5026.                     $id,
  5027.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5028.                 ),
  5029.                 'document_log' => System::getDocumentLog(
  5030.                     $this->getDoctrine()->getManager(),
  5031.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  5032.                     $id,
  5033.                     $dt['created_by'],
  5034.                     $dt['edited_by']
  5035.                 )
  5036.             )
  5037.         );
  5038.     }
  5039.     public function PrintItemReceivedAndReplacement(Request $request$id)
  5040.     {
  5041.         $em $this->getDoctrine()->getManager();
  5042.         $dt SalesOrderM::GetItemReceivedAndReplacementDetails($em$id);
  5043.         $company_data Company::getCompanyData($em1);
  5044.         $document_mark = array(
  5045.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5046.             'copy' => ''
  5047.         );
  5048.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5049.             $html $this->renderView(
  5050.                 '@Sales/pages/print/print_irr.html.twig',
  5051.                 array(
  5052.                     //full array here
  5053.                     'pdf' => true,
  5054.                     'page_title' => 'Item Received And Replacement',
  5055.                     'export' => 'pdf,print',
  5056.                     'data' => $dt,
  5057.                     'approval_data' => System::checkIfApprovalExists(
  5058.                         $em,
  5059.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  5060.                         $id,
  5061.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5062.                     ),
  5063.                     'document_log' => System::getDocumentLog(
  5064.                         $this->getDoctrine()->getManager(),
  5065.                         array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  5066.                         $id,
  5067.                         $dt['created_by'],
  5068.                         $dt['edited_by']
  5069.                     ),
  5070.                     'document_mark_image' => $document_mark['original'],
  5071.                     'company_name' => $company_data->getName(),
  5072.                     'company_data' => $company_data,
  5073.                     'company_address' => $company_data->getAddress(),
  5074.                     'company_image' => $company_data->getImage(),
  5075.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5076.                     'red' => 0
  5077.                 )
  5078.             );
  5079.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5080.                 //                'orientation' => 'landscape',
  5081.                 //                'enable-javascript' => true,
  5082.                 //                'javascript-delay' => 1000,
  5083.                 'no-stop-slow-scripts' => false,
  5084.                 'no-background' => false,
  5085.                 'lowquality' => false,
  5086.                 'encoding' => 'utf-8',
  5087.                 //            'images' => true,
  5088.                 //            'cookie' => array(),
  5089.                 'dpi' => 300,
  5090.                 'image-dpi' => 300,
  5091.                 //                'enable-external-links' => true,
  5092.                 //                'enable-internal-links' => true
  5093.             ));
  5094.             return new Response(
  5095.                 $pdf_response,
  5096.                 200,
  5097.                 array(
  5098.                     'Content-Type' => 'application/pdf',
  5099.                     'Content-Disposition' => 'attachment; filename="irr_' $id '.pdf"'
  5100.                 )
  5101.             );
  5102.         }
  5103.         return $this->render(
  5104.             '@Sales/pages/print/print_irr.html.twig',
  5105.             array(
  5106.                 'page_title' => 'Item Return & Replacement',
  5107.                 'export' => 'pdf,print',
  5108.                 'data' => $dt,
  5109.                 'approval_data' => System::checkIfApprovalExists(
  5110.                     $em,
  5111.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  5112.                     $id,
  5113.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5114.                 ),
  5115.                 'document_log' => System::getDocumentLog(
  5116.                     $this->getDoctrine()->getManager(),
  5117.                     array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
  5118.                     $id,
  5119.                     $dt['created_by'],
  5120.                     $dt['edited_by']
  5121.                 ),
  5122.                 'document_mark_image' => $document_mark['original'],
  5123.                 'company_name' => $company_data->getName(),
  5124.                 'company_data' => $company_data,
  5125.                 'company_address' => $company_data->getAddress(),
  5126.                 'company_image' => $company_data->getImage(),
  5127.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5128.                 'red' => 0
  5129.             )
  5130.         );
  5131.     }
  5132.     public function getAllowedSalesPersonIds(Request $request)
  5133.     {
  5134.         $em $this->getDoctrine()->getManager();
  5135.         $companyId $this->getLoggedUserCompanyId($request);
  5136.         $userId $request->getSession()->get(UserConstants::USER_ID);
  5137.         if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  5138.             return new JsonResponse(
  5139.                 array(
  5140.                     'success' => true,
  5141.                     'allowedSalesPersonIds' => Client::AllowedSalesPersonIds($em$userId$companyId, [])
  5142.                 )
  5143.             );
  5144.         }
  5145.         $data = [];
  5146.         return new JsonResponse(
  5147.             array(
  5148.                 'success' => true,
  5149.                 'allowedSalesPersonIds' => []
  5150.             )
  5151.         );
  5152.         //        return $this->render('@Inventory/pages/views/delivery_receipts.html.twig',
  5153.         //            array(
  5154.         //                'page_title' => 'Delivery Receipts',
  5155.         //                'data' => $data,
  5156.         //
  5157.         //            )
  5158.         //        );
  5159.     }
  5160.     //delivery Receipts
  5161.     public function DeliveryReceiptList(Request $request)
  5162.     {
  5163.         $em $this->getDoctrine()->getManager();
  5164.         $data = [];
  5165.         return $this->render(
  5166.             '@Inventory/pages/views/delivery_receipts.html.twig',
  5167.             array(
  5168.                 'page_title' => 'Delivery Receipts',
  5169.                 'data' => $data,
  5170.             )
  5171.         );
  5172.     }
  5173.     public function CreateDeliveryReceipt(Request $request$id 0)
  5174.     {
  5175.         $em $this->getDoctrine()->getManager();
  5176.         $companyId $this->getLoggedUserCompanyId($request);
  5177.         $userBranchIdList $request->getSession()->get('branchIdList');
  5178.         if ($userBranchIdList == null$userBranchIdList = [];
  5179.         $userBranchId $request->getSession()->get('branchId');
  5180.         $extId $id;
  5181.         $skipInventoryHit null;
  5182.         if ($request->query->has('skipInventoryHit'))
  5183.             $skipInventoryHit $request->query->get('skipInventoryHit');
  5184.         if ($request->isMethod('POST')) {
  5185.             $entity_id array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
  5186.             $dochash $request->request->get('docHash'); //change
  5187.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5188.             $approveRole 1;  //created
  5189.             $approveHash $request->request->get('approvalHash');
  5190.             if (!DocValidation::isInsertable(
  5191.                 $em,
  5192.                 $entity_id,
  5193.                 $dochash,
  5194.                 $loginId,
  5195.                 $approveRole,
  5196.                 $approveHash,
  5197.                 $request->request->get('drId')
  5198.             )) {
  5199.                 if ($request->request->has('returnJson')) {
  5200.                     return new JsonResponse(array(
  5201.                         'success' => false,
  5202.                         //                        'documentHash' => 0,
  5203.                         'documentId' => 0,
  5204.                         'documentIdPadded' => str_pad(08'0'STR_PAD_LEFT),
  5205.                         //                        'documentDate' => '',
  5206.                         //                        'billIds' => [],
  5207.                         //                        'drIds' => [],
  5208.                         //                        'pmntTransIds' => [],
  5209.                         'viewUrl' => '',
  5210.                         //                        'skipApprovalAction' => $request->request->has('skipApprovalAction')?$request->request->get('skipApprovalAction'):0,
  5211.                         //                        'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  5212.                         //                        'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  5213.                         //                        'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  5214.                         //                        'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  5215.                     ));
  5216.                 } else
  5217.                     $this->addFlash(
  5218.                         'error',
  5219.                         'Sorry Could not insert Data.'
  5220.                     );
  5221.             } else {
  5222.                 $receiptId SalesOrderM::CreateNewDeliveryReceipt(
  5223.                     $this->getDoctrine()->getManager(),
  5224.                     $request->request,
  5225.                     $skipInventoryHit,
  5226.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  5227.                     $this->getLoggedUserCompanyId($request)
  5228.                 );
  5229.                 $draftFlag $request->request->has('draftFlag') ? $request->request->get('draftFlag') : 0;
  5230.                 if ($draftFlag == 0) {
  5231.                     //now add Approval info
  5232.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  5233.                     $approveRole 1;  //created
  5234.                     System::createEditSignatureHash(
  5235.                         $this->getDoctrine()->getManager(),
  5236.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  5237.                         $receiptId,
  5238.                         $loginId,
  5239.                         $approveRole,
  5240.                         $request->request->get('approvalHash')
  5241.                     );
  5242.                     $options = array(
  5243.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  5244.                         'notification_server' => $this->container->getParameter('notification_server'),
  5245.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  5246.                         'url' => $this->generateUrl(
  5247.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]['entity_view_route_path_name']
  5248.                         )
  5249.                     );
  5250.                     System::setApprovalInfo(
  5251.                         $this->getDoctrine()->getManager(),
  5252.                         $options,
  5253.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  5254.                         $receiptId,
  5255.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5256.                     );
  5257.                 }
  5258.                 $url $this->generateUrl(
  5259.                     'view_delivery_receipt'
  5260.                 );
  5261.                 if ($request->request->has('returnJson')) {
  5262.                     //                    $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  5263.                     //                        array(
  5264.                     //                            'salesOrderId' => $orderId, ///material
  5265.                     //
  5266.                     //                        )
  5267.                     //                    );
  5268.                     return new JsonResponse(array(
  5269.                         'success' => true,
  5270.                         //                        'documentHash' => $order->getDocumentHash(),
  5271.                         'documentId' => $receiptId,
  5272.                         'documentIdPadded' => str_pad($receiptId8'0'STR_PAD_LEFT),
  5273.                         'viewUrl' => $url "/" $receiptId,
  5274.                     ));
  5275.                 } else {
  5276.                     $this->addFlash(
  5277.                         'success',
  5278.                         'New Delivery Receipt Created'
  5279.                     );
  5280.                     return $this->redirect($url "/" $receiptId);
  5281.                 }
  5282.             }
  5283.         }
  5284.         $debugData = [];
  5285.         //        $dr_data=$em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
  5286.         //            array(
  5287.         //                'deliveryReceiptId'=>$dr_id
  5288.         //            )
  5289.         //        );
  5290.         $new_swld = new \DateTime('2017-07-09');
  5291.         //        if ($entry->getWarranty() > 0)
  5292.         //            $new_swld->modify('+' . $entry->getWarranty() . ' month');
  5293.         $debugData[] = $new_swld->format('Y-m-d');
  5294.         $debugData[] = $new_swld;
  5295.         //        $debugData[]=$dr_data->getDeliveryReceiptDate();
  5296.         $debugData[] = '+' '1' ' month';
  5297.         $branchList Client::BranchList($em$companyId, [], $userBranchIdList);
  5298.         $warehouseIds = [];
  5299.         foreach ($branchList as $br) {
  5300.             $warehouseIds[] = $br['warehouseId'];
  5301.         }
  5302.         $extDocData = [];
  5303.         $extDocDataDetails = [];
  5304.         if ($extId == 0) {
  5305.         } else {
  5306.             $extDoc $em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
  5307.                 array(
  5308.                     'deliveryReceiptId' => $extId///material
  5309.                 )
  5310.             );
  5311.             //now if its not editable, redirect to view
  5312.             if ($extDoc) {
  5313.                 if ($extDoc->getEditFlag() != && $extDoc->getDraftFlag() != 1) {
  5314.                     $url $this->generateUrl(
  5315.                         'view_delivery_receipt'
  5316.                     );
  5317.                     return $this->redirect($url "/" $extId);
  5318.                 } else {
  5319.                     $extDocData $extDoc;
  5320.                     $extDocDataDetails $em->getRepository('ApplicationBundle:DeliveryReceiptItem')->findOneBy(
  5321.                         array(
  5322.                             'deliveryReceiptId' => $extId///material
  5323.                         )
  5324.                     );
  5325.                 }
  5326.             } else {
  5327.             }
  5328.         }
  5329.         return $this->render(
  5330.             '@Sales/pages/input_forms/deliveryReceipt.html.twig',
  5331.             array(
  5332.                 'page_title' => 'New Delivery Receipt',
  5333.                 'extDocDataDetails' => $extDocDataDetails,
  5334.                 'extDocData' => $extDocData,
  5335.                 'extData' => $extDocData,
  5336.                 'ExistingClients' => Accounts::getClientLedgerHeads($em),
  5337.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($em),
  5338.                 'ClientList' => SalesOrderM::GetClientList($em),
  5339.                 'warehouse' => Inventory::WarehouseList($em$companyId$warehouseIds),
  5340.                 'salesOrders' => SalesOrderM::SalesOrderListPendingDelivery($em$warehouseIds),
  5341.                 'salesOrdersArray' => SalesOrderM::SalesOrderListPendingDeliveryArray($em$warehouseIds),
  5342.                 'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
  5343.                 'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
  5344.                 'debugData' => $debugData,
  5345.             )
  5346.         );
  5347.     }
  5348.     public function ViewDeliveryReceipt(Request $request$id)
  5349.     {
  5350.         $em $this->getDoctrine()->getManager();
  5351.         $dt SalesOrderM::GetDeliveryReceiptDetails($em$id);
  5352.         return $this->render(
  5353.             '@Sales/pages/views/delivery_receipt_view.html.twig',
  5354.             array(
  5355.                 'page_title' => 'View',
  5356.                 'data' => $dt,
  5357.                 'warehouseList' => Inventory::WarehouseList($em),
  5358.                 'warehouseActionList' => Inventory::warehouse_action_list($em$dt['rel_data']->getCompanyId(), 'object'),
  5359.                 'auto_created' => $dt['auto_created'],
  5360.                 'approval_data' => System::checkIfApprovalExists(
  5361.                     $em,
  5362.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  5363.                     $id,
  5364.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5365.                 ),
  5366.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  5367.                     $this->getDoctrine()->getManager(),
  5368.                     array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  5369.                     $id,
  5370.                     $dt['created_by'],
  5371.                     $dt['edited_by']
  5372.                 ) : []
  5373.             )
  5374.         );
  5375.     }
  5376.     public function PrintDeliveryReceipt(Request $request$id)
  5377.     {
  5378.         $em $this->getDoctrine()->getManager();
  5379.         $data SalesOrderM::GetDeliveryReceiptDetails($em$id);
  5380.         $print_bar_code_flag 0;
  5381.         if ($request->query->has('print_bar_code_flag'))
  5382.             $print_bar_code_flag $request->query->get('print_bar_code_flag');
  5383.         $company_data Company::getCompanyData($em1);
  5384.         $document_mark = array(
  5385.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5386.             'copy' => ''
  5387.         );
  5388.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  5389.             $html $this->renderView(
  5390.                 '@Sales/pages/print/delivery_receipt_print.html.twig',
  5391.                 array(
  5392.                     //full array here
  5393.                     'pdf' => true,
  5394.                     'page_title' => 'Delivery Receipt ' $data['doc_hash'],
  5395.                     'data' => $data,
  5396.                     'document_mark_image' => $document_mark['original'],
  5397.                     'company_name' => $company_data->getName(),
  5398.                     'company_data' => $company_data,
  5399.                     'company_address' => $company_data->getAddress(),
  5400.                     'company_image' => $company_data->getImage(),
  5401.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  5402.                     'page_header' => 'New Product',
  5403.                     'document_type' => 'Delivery Receipt (Challan)',
  5404.                     'page_header_sub' => 'Add',
  5405.                     'print_bar_code_flag' => $print_bar_code_flag,
  5406.                     //                'type_list'=>$type_list,
  5407.                     //                'mis_data'=>$mis_data,
  5408.                     //                'mis_print'=>$mis_print,
  5409.                     'item_data' => [],
  5410.                     'received' => 2,
  5411.                     'return' => 1,
  5412.                     'total_w_vat' => 1,
  5413.                     'total_vat' => 1,
  5414.                     'total_wo_vat' => 1,
  5415.                     'invoice_id' => 'abcd1234',
  5416.                     'created_by' => 'created by',
  5417.                     'created_at' => '',
  5418.                     'red' => 0,
  5419.                     'approval_data' => System::checkIfApprovalExists(
  5420.                         $em,
  5421.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  5422.                         $id,
  5423.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5424.                     ),
  5425.                     'document_log' => System::getDocumentLog(
  5426.                         $this->getDoctrine()->getManager(),
  5427.                         array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
  5428.                         $id,
  5429.                         $data['created_by'],
  5430.                         $data['edited_by']
  5431.                     ),
  5432.                 )
  5433.             );
  5434.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  5435.                 //                'orientation' => 'landscape',
  5436.                 //                'enable-javascript' => true,
  5437.                 //                'javascript-delay' => 1000,
  5438.                 'no-stop-slow-scripts' => false,
  5439.                 'no-background' => false,
  5440.                 'lowquality' => false,
  5441.                 'encoding' => 'utf-8',
  5442.                 //            'images' => true,
  5443.                 //            'cookie' => array(),
  5444.                 'dpi' => 300,
  5445.                 'image-dpi' => 300,
  5446.                 //                'enable-external-links' => true,
  5447.                 //                'enable-internal-links' => true
  5448.             ));
  5449.             return new Response(
  5450.                 $pdf_response,
  5451.                 200,
  5452.                 array(
  5453.                     'Content-Type' => 'application/pdf',
  5454.                     'Content-Disposition' => 'attachment; filename="delivery_challan_' $id '.pdf"'
  5455.                 )
  5456.             );
  5457.         }
  5458.         return $this->render(
  5459.             '@Sales/pages/print/delivery_receipt_print.html.twig',
  5460.             array(
  5461.                 'page_title' => 'Delivery Receipt ' $data['doc_hash'],
  5462.                 'data' => $data,
  5463.                 'export' => 'pdf,print',
  5464.                 'document_mark_image' => $document_mark['original'],
  5465.                 'company_name' => $company_data->getName(),
  5466.                 'company_data' => $company_data,
  5467.                 'company_address' => $company_data->getAddress(),
  5468.                 'company_image' => $company_data->getImage(),
  5469.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5470.                 'page_header' => 'New Product',
  5471.                 'document_type' => 'Delivery Receipt (Challan)',
  5472.                 'page_header_sub' => 'Add',
  5473.                 'print_bar_code_flag' => $print_bar_code_flag,
  5474.                 //                'type_list'=>$type_list,
  5475.                 //                'mis_data'=>$mis_data,
  5476.                 //                'mis_print'=>$mis_print,
  5477.                 'item_data' => [],
  5478.                 'received' => 2,
  5479.                 'return' => 1,
  5480.                 'total_w_vat' => 1,
  5481.                 'total_vat' => 1,
  5482.                 'total_wo_vat' => 1,
  5483.                 'invoice_id' => 'abcd1234',
  5484.                 'created_by' => 'created by',
  5485.                 'created_at' => '',
  5486.                 'red' => 0,
  5487.             )
  5488.         );
  5489.     }
  5490.     public function ServiceChallanList(Request $request)
  5491.     {
  5492.         $q $this->getDoctrine()
  5493.             ->getRepository('ApplicationBundle:ServiceChallan')
  5494.             ->findBy(
  5495.                 array(
  5496.                     'status' => GeneralConstant::ACTIVE,
  5497.                 ),
  5498.                 array(
  5499.                     'serviceChallanDate' => 'DESC'
  5500.                 )
  5501.             );
  5502.         $stage_list = array(
  5503.             => 'Pending',
  5504.             => 'Pending',
  5505.             => 'Complete',
  5506.             => 'Partial',
  5507.         );
  5508.         $data = [];
  5509.         foreach ($q as $entry) {
  5510.             $data[] = array(
  5511.                 'doc_date' => $entry->getServiceChallanDate(),
  5512.                 'id' => $entry->getServiceChallanId(),
  5513.                 'doc_hash' => $entry->getDocumentHash(),
  5514.                 //                'so_amount'=>$entry->getSoAmount(),
  5515.                 'stage' => $stage_list[$entry->getStage()]
  5516.             );
  5517.         }
  5518.         return $this->render(
  5519.             '@Inventory/pages/views/sc_list.html.twig',
  5520.             array(
  5521.                 'page_title' => 'Service Challan List',
  5522.                 'data' => $data
  5523.             )
  5524.         );
  5525.     }
  5526.     public function ViewServiceChallan(Request $request$id)
  5527.     {
  5528.         $em $this->getDoctrine()->getManager();
  5529.         $dt SalesOrderM::GetServiceChallanDetails($em$id);
  5530.         return $this->render(
  5531.             '@Inventory/pages/views/view_service_challan.html.twig',
  5532.             array(
  5533.                 'page_title' => 'View',
  5534.                 'data' => $dt,
  5535.                 'auto_created' => $dt['auto_created'],
  5536.                 'approval_data' => System::checkIfApprovalExists(
  5537.                     $em,
  5538.                     array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  5539.                     $id,
  5540.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5541.                 ),
  5542.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  5543.                     $this->getDoctrine()->getManager(),
  5544.                     array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
  5545.                     $id,
  5546.                     $dt['created_by'],
  5547.                     $dt['edited_by']
  5548.                 ) : []
  5549.             )
  5550.         );
  5551.     }
  5552.     public function PrintServiceChallan(Request $request$id)
  5553.     {
  5554.         $em $this->getDoctrine()->getManager();
  5555.         $data SalesOrderM::GetServiceChallanDetails($em$id);
  5556.         $company_data Company::getCompanyData($em1);
  5557.         $document_mark = array(
  5558.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5559.             'copy' => ''
  5560.         );
  5561.         return $this->render(
  5562.             '@Inventory/pages/print/print_service_challan.html.twig',
  5563.             array(
  5564.                 'page_title' => 'Service Challan ' $data['doc_hash'],
  5565.                 'data' => $data,
  5566.                 'document_mark_image' => $document_mark['original'],
  5567.                 'company_name' => $company_data->getName(),
  5568.                 'company_data' => $company_data,
  5569.                 'company_address' => $company_data->getAddress(),
  5570.                 'company_image' => $company_data->getImage(),
  5571.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5572.                 'page_header' => 'New Product',
  5573.                 'document_type' => 'Service Challan',
  5574.                 'page_header_sub' => 'Add',
  5575.                 //                'type_list'=>$type_list,
  5576.                 //                'mis_data'=>$mis_data,
  5577.                 //                'mis_print'=>$mis_print,
  5578.                 'item_data' => [],
  5579.                 'received' => 2,
  5580.                 'return' => 1,
  5581.                 'total_w_vat' => 1,
  5582.                 'total_vat' => 1,
  5583.                 'total_wo_vat' => 1,
  5584.                 'invoice_id' => 'abcd1234',
  5585.                 'created_by' => 'created by',
  5586.                 'created_at' => '',
  5587.                 'red' => 0,
  5588.             )
  5589.         );
  5590.     }
  5591.     //delivery confirmation
  5592.     //delivery Receipts
  5593.     public function DeliveryConfirmationList(Request $request)
  5594.     {
  5595.         $q $this->getDoctrine()
  5596.             ->getRepository('ApplicationBundle:DeliveryConfirmation')
  5597.             ->findBy(
  5598.                 array(
  5599.                     'status' => GeneralConstant::ACTIVE,
  5600.                 ),
  5601.                 array(
  5602.                     'deliveryConfirmationDate' => 'DESC'
  5603.                 )
  5604.             );
  5605.         $stage_list = array(
  5606.             => 'Pending',
  5607.             => 'Pending',
  5608.             => 'Complete',
  5609.             => 'Partial',
  5610.         );
  5611.         $data = [];
  5612.         foreach ($q as $entry) {
  5613.             $data[] = array(
  5614.                 'doc_date' => $entry->getDeliveryConfirmationDate(),
  5615.                 'id' => $entry->getDeliveryConfirmationId(),
  5616.                 'doc_hash' => $entry->getDocumentHash(),
  5617.                 //                'so_amount'=>$entry->getSoAmount(),
  5618.                 'stage' => $stage_list[$entry->getStage()]
  5619.             );
  5620.         }
  5621.         return $this->render(
  5622.             '@Sales/pages/list/delivery_confirmations.html.twig',
  5623.             array(
  5624.                 'page_title' => 'Delivery Confirmations',
  5625.                 'data' => $data
  5626.             )
  5627.         );
  5628.     }
  5629.     public function ViewDeliveryConfirmation(Request $request$id)
  5630.     {
  5631.         $em $this->getDoctrine()->getManager();
  5632.         $dcon $this->getDoctrine()
  5633.             ->getRepository('ApplicationBundle:DeliveryConfirmation')
  5634.             ->findOneBy(
  5635.                 array(
  5636.                     'status' => GeneralConstant::ACTIVE,
  5637.                     'deliveryConfirmationId' => $id
  5638.                 )
  5639.             );
  5640.         $dt SalesOrderM::GetDeliveryConfirmationDetails($em$id$dcon->getDeliveryReceiptId());
  5641.         return $this->render(
  5642.             '@Sales/pages/views/delivery_confirmation_view.html.twig',
  5643.             array(
  5644.                 'page_title' => 'View',
  5645.                 'delConData' => $dcon,
  5646.                 'data' => $dt,
  5647.                 'auto_created' => $dt['auto_created'],
  5648.                 'approval_data' => System::checkIfApprovalExists(
  5649.                     $em,
  5650.                     array_flip(GeneralConstant::$Entity_list)['DeliveryConfirmation'],
  5651.                     $id,
  5652.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  5653.                 ),
  5654.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  5655.                     $this->getDoctrine()->getManager(),
  5656.                     array_flip(GeneralConstant::$Entity_list)['DeliveryConfirmation'],
  5657.                     $id,
  5658.                     $dt['created_by'],
  5659.                     $dt['edited_by']
  5660.                 ) : []
  5661.             )
  5662.         );
  5663.     }
  5664.     public function PrintDeliveryConfirmation(Request $request$id)
  5665.     {
  5666.         $em $this->getDoctrine()->getManager();
  5667.         $data SalesOrderM::GetSalesOrderDetails($em$id);
  5668.         $company_data Company::getCompanyData($em1);
  5669.         $document_mark = array(
  5670.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  5671.             'copy' => ''
  5672.         );
  5673.         return $this->render(
  5674.             '@Sales/pages/print/sales_order_print.html.twig',
  5675.             array(
  5676.                 'page_title' => 'Sales Order ' $data['doc_hash'],
  5677.                 'data' => $data,
  5678.                 'document_mark_image' => $document_mark['original'],
  5679.                 'company_name' => $company_data->getName(),
  5680.                 'company_data' => $company_data,
  5681.                 'company_address' => $company_data->getAddress(),
  5682.                 'company_image' => $company_data->getImage(),
  5683.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  5684.                 'page_header' => 'New Product',
  5685.                 'document_type' => 'Sales Order',
  5686.                 'page_header_sub' => 'Add',
  5687.                 //                'type_list'=>$type_list,
  5688.                 //                'mis_data'=>$mis_data,
  5689.                 //                'mis_print'=>$mis_print,
  5690.                 'item_data' => [],
  5691.                 'received' => 2,
  5692.                 'return' => 1,
  5693.                 'total_w_vat' => 1,
  5694.                 'total_vat' => 1,
  5695.                 'total_wo_vat' => 1,
  5696.                 'invoice_id' => 'abcd1234',
  5697.                 'created_by' => 'created by',
  5698.                 'created_at' => '',
  5699.                 'red' => 0,
  5700.             )
  5701.         );
  5702.     }
  5703.     public function GetClientLatestDetails(Request $request$id)
  5704.     {
  5705.         $em $this->getDoctrine()->getManager();
  5706.         $client_id $id;
  5707.         $engine $this->container->get("templating");
  5708.         $CD Client::GetClientDetails($em$client_id);
  5709.         if ($CD) {
  5710.             $Content $engine->render('@Sales/pages/report/selected_client_details.html.twig', array("cd" => $CD));
  5711.             return new JsonResponse(array("success" => $client_id"content" => $Content));
  5712.         }
  5713.         return new JsonResponse(array("success" => false));
  5714.     }
  5715.     public function GetClientLatestDetailsForSo(Request $request$id)
  5716.     {
  5717.         $em $this->getDoctrine()->getManager();
  5718.         $client_id $id;
  5719.         $engine $this->container->get("templating");
  5720.         $CD Client::GetClientDetailsForSoHistory($em$client_id);
  5721.         if ($CD) {
  5722.             $Content $engine->render('@Sales/pages/report/selected_client_details_for_so.html.twig', array("cd" => $CD));
  5723.             return new JsonResponse(array("success" => true"content" => $Content'cd' => $CD));
  5724.         }
  5725.         return new JsonResponse(array("success" => false'cd' => $CD));
  5726.     }
  5727.     public function GetSoItemLatestDetails(Request $request)
  5728.     {
  5729.         $em $this->getDoctrine()->getManager();
  5730.         $search_query = [];
  5731.         $res_data_by_so_item_id = [];
  5732.         if ($request->query->has('projectId'))
  5733.             $search_query['projectId'] = $request->query->get('projectId');
  5734.         $SO $this->getDoctrine()
  5735.             ->getRepository('ApplicationBundle:SalesOrder')
  5736.             ->findOneBy(
  5737.                 $search_query
  5738.             );
  5739.         if ($SO) {
  5740.             $SO_ITEMS $this->getDoctrine()
  5741.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  5742.                 ->findBy(
  5743.                     array(
  5744.                         'salesOrderId' => $SO->getSalesOrderId()
  5745.                     )
  5746.                 );
  5747.             foreach ($SO_ITEMS as $SO_ITEM) {
  5748.                 $res_data_by_so_item_id[$SO_ITEM->getId()] = array(
  5749.                     'soItemId' => $SO_ITEM->getId(),
  5750.                     'units' => $SO_ITEM->getQty(),
  5751.                     'unitTypeId' => $SO_ITEM->getUnitTypeId(),
  5752.                     'balance' => $SO_ITEM->getBalance(),
  5753.                     'delivered' => ($SO_ITEM->getDelivered()) + ($SO_ITEM->getTransitQty()),
  5754.                     'price' => $SO_ITEM->getPrice(),
  5755.                     'productFdm' => $SO_ITEM->getProductFdm(),
  5756.                 );
  5757.             }
  5758.         }
  5759.         if (!empty($res_data_by_so_item_id)) {
  5760.             return new JsonResponse(array("success" => true"content" => $res_data_by_so_item_id));
  5761.         } else {
  5762.             return new JsonResponse(array("success" => false"content" => $res_data_by_so_item_id));
  5763.         }
  5764.         return new JsonResponse(array("success" => true"content" => $res_data_by_so_item_id));
  5765.     }
  5766.     public function GetTradeOffersForSo(Request $request)
  5767.     {
  5768.         $em $this->getDoctrine()->getManager();
  5769.         $Content = [];
  5770.         $Content_by_id = [];
  5771.         if ($request->isMethod('POST')) {
  5772.             $now_time = new \DateTime($request->request->get('qDate'));
  5773.             $now_time_str $now_time->format('Y-m-d');
  5774.             //            $now_time_str.= " 00:00:00";
  5775.             //            $now_time_str.= " 00:00:00";
  5776.             $get_kids_sql "SELECT trade_offer.* FROM trade_offer WHERE trade_offer.approved=" GeneralConstant::APPROVED .
  5777.                 " AND trade_offer.status=" GeneralConstant::ACTIVE;
  5778.             $get_kids_sql .= " AND ((trade_offer.trade_offer_end_date>= '" $now_time_str " 23:59:59'";
  5779.             $get_kids_sql .= " AND trade_offer.trade_offer_start_date<= '" $now_time_str " 00:00:00') or perpetual_flag=1)";
  5780.             $get_kids_sql .= " order by invoke_type desc;";
  5781.             $stmt $em->getConnection()->prepare($get_kids_sql);
  5782.             $stmt->execute();
  5783.             $pl $stmt->fetchAll();
  5784.             foreach ($pl as $d) {
  5785.                 $tmp $d;
  5786.                 $tmp['payment_sub_types'] = json_decode($tmp['payment_sub_types'], true) ? json_decode($tmp['payment_sub_types'], true) : [];
  5787.                 $tmp['payment_types'] = json_decode($tmp['payment_types'], true) ? json_decode($tmp['payment_types'], true) : [];
  5788.                 $tmp['payment_methods'] = json_decode($tmp['payment_methods'], true) ? json_decode($tmp['payment_methods'], true) : [];
  5789.                 $tmp['client_types'] = json_decode($tmp['client_types'], true) ? json_decode($tmp['client_types'], true) : [];
  5790.                 $tmp['client_ids'] = json_decode($tmp['client_ids'], true) ? json_decode($tmp['client_ids'], true) : [];
  5791.                 $tmp['branch_ids'] = json_decode($tmp['branch_ids'], true) ? json_decode($tmp['branch_ids'], true) : [];
  5792.                 $tmp['region_ids'] = json_decode($tmp['region_ids'], true) ? json_decode($tmp['region_ids'], true) : [];
  5793.                 $tmp['sales_person_ids'] = json_decode($tmp['sales_person_ids'], true) ? json_decode($tmp['sales_person_ids'], true) : [];
  5794.                 $tmp['data'] = json_decode($tmp['data'], true) ? json_decode($tmp['data'], true) : [];;
  5795.                 $Content[] = $tmp;
  5796.                 $Content_by_id[$d['trade_offer_id']] = $tmp;
  5797.             }
  5798.         }
  5799.         if (!empty($Content)) {
  5800.             return new JsonResponse(array("success" => 1"content" => $Content"content_by_id" => $Content_by_id));
  5801.         }
  5802.         return new JsonResponse(array("success" => false"content" => $Content));
  5803.     }
  5804.     public function GetPaymentReceiptHeadsForBranch(Request $request)
  5805.     {
  5806.         $em $this->getDoctrine()->getManager();
  5807.         $Content = [];
  5808.         $Content_by_id = [];
  5809.         $Content_by_id['cashHeadIds'] = [];
  5810.         $Content_by_id['bankHeadIds'] = [];
  5811.         if ($request->isMethod('POST')) {
  5812.             $qryArray = [];
  5813.             if ($request->request->get('branchId') != '')
  5814.                 $qryArray['branchId'] = $request->request->get('branchId');
  5815.             $QDLIST $this->getDoctrine()
  5816.                 ->getRepository('ApplicationBundle:Branch')
  5817.                 ->findBy(
  5818.                     $qryArray
  5819.                 );
  5820.             foreach ($QDLIST as $QD) {
  5821.                 $cashHeadIds json_decode($QD->getCashHeadIds(), true);
  5822.                 if ($cashHeadIds == null$cashHeadIds = [];
  5823.                 $bankHeadIds json_decode($QD->getbankHeadIds(), true);
  5824.                 if ($bankHeadIds == null$bankHeadIds = [];
  5825.                 $Content_by_id['cashHeadIds'] = array_merge($Content_by_id['cashHeadIds'], array_diff($cashHeadIds$Content_by_id['cashHeadIds']));
  5826.                 $Content_by_id['bankHeadIds'] = array_merge($Content_by_id['bankHeadIds'], array_diff($bankHeadIds$Content_by_id['bankHeadIds']));
  5827.                 //                    $Content_by_id['cashHeadIds'] = $cashHeadIds;
  5828.                 //                    $Content_by_id['bankHeadIds'] = $bankHeadIds;
  5829.             }
  5830.         }
  5831.         if (!empty($Content)) {
  5832.             return new JsonResponse(array("success" => true"content" => $Content"content_by_id" => $Content_by_id));
  5833.         }
  5834.         return new JsonResponse(array("success" => true"content" => $Content"content_by_id" => $Content_by_id));
  5835.     }
  5836.     public function GetPaymentReceiptHeadsForBranchApp(Request $request): JsonResponse
  5837.     {
  5838.         $em $this->getDoctrine()->getManager();
  5839.         $result = [];
  5840.         if ($request->isMethod('POST')) {
  5841.             $qryArray = [];
  5842.             if ($branchId $request->request->get('branchId')) {
  5843.                 $qryArray['branchId'] = $branchId;
  5844.             }
  5845.             $branches $this->getDoctrine()
  5846.                 ->getRepository('ApplicationBundle:Branch')
  5847.                 ->findBy($qryArray);
  5848.             $allHeadIds = [];
  5849.             foreach ($branches as $branch) {
  5850.                 $cashHeadIds json_decode($branch->getCashHeadIds(), true) ?? [];
  5851.                 $bankHeadIds json_decode($branch->getBankHeadIds(), true) ?? [];
  5852.                 $allHeadIds array_merge($allHeadIds$cashHeadIds$bankHeadIds);
  5853.             }
  5854.             $allHeadIds array_unique($allHeadIds);
  5855.             if (!empty($allHeadIds)) {
  5856.                 $accountHeadRepo $this->getDoctrine()->getRepository('ApplicationBundle:AccAccountsHead');
  5857.                 $heads $accountHeadRepo->findBy(['accountsHeadId' => $allHeadIds]);
  5858.                 foreach ($heads as $head) {
  5859.                     $result[] = [
  5860.                         'id' => (string)$head->getAccountsHeadId(),
  5861.                         'name' => $head->getName()
  5862.                     ];
  5863.                 }
  5864.             }
  5865.         }
  5866.         $paymentMethods = [
  5867.             [
  5868.                 'id' => 1,
  5869.                 'name' => 'Cash'
  5870.             ],
  5871.             [
  5872.                 'id' => 2,
  5873.                 'name' => 'Credit'
  5874.             ]
  5875.         ];
  5876.         $basedOn = [
  5877.             [
  5878.                 'id' => 1,
  5879.                 'name' => 'Price'
  5880.             ],
  5881.             [
  5882.                 'id' => 2,
  5883.                 'name' => 'Quantity'
  5884.             ],
  5885.             [
  5886.                 'id' => 3,
  5887.                 'name' => 'Days'
  5888.             ],
  5889.         ];
  5890.         $billStructure = [
  5891.             [
  5892.                 'id' => 1,
  5893.                 'name' => 'Completion Of Delivery'
  5894.             ],
  5895.             [
  5896.                 'id' => 1,
  5897.                 'name' => 'Completion Of Days'
  5898.             ]
  5899.         ];
  5900.         return new JsonResponse([
  5901.             "success" => true,
  5902.             "content" => $result,
  5903.             'paymentMethod' => $paymentMethods,
  5904.             'billingStructure' => $billStructure,
  5905.             'basedOn' => $basedOn
  5906.         ]);
  5907.     }
  5908.     public function GetSelectedProductsHistory(Request $request)
  5909.     {
  5910.         $em $this->getDoctrine()->getManager();
  5911.         $engine $this->container->get("templating");
  5912.         $pids array_unique(explode("::"$_POST["pids"]));
  5913.         $Products $em->getRepository('ApplicationBundle:InvProducts')->findBy(array(
  5914.             'id' => $pids
  5915.         ));
  5916.         $ProductSales = array();
  5917.         foreach ($Products as $Product) {
  5918.             $ProductSales[] = array(
  5919.                 "name" => $Product->getName(),
  5920.                 "unit_price" => "100",
  5921.                 "quantity" => "15"
  5922.             );
  5923.         }
  5924.         $Content $engine->render('@Sales/pages/report/selected_products_details.html.twig', array('pSalesDetails' => $ProductSales));
  5925.         $stockPosition $engine->render('@Sales/pages/report/selected_products_stock_position.html.twig', array('pSalesDetails' => $ProductSales));
  5926.         return new JsonResponse(array("success" => false"content" => $Content"stockPosition" => $stockPosition));
  5927.     }
  5928.     public function GetModalForTradeOffer(Request $request)
  5929.     {
  5930.         $em $this->getDoctrine()->getManager();
  5931.         $engine $this->container->get("templating");
  5932.         $discount_type 1;
  5933.         $itemSelectionType 1;
  5934.         if ($request->request->has('discountType'))
  5935.             $discount_type $request->request->get('discountType');
  5936.         if ($request->request->has('itemSelectionType'))
  5937.             $discount_type $request->request->get('itemSelectionType');
  5938.         $Content '';
  5939.         if ($discount_type == 1)
  5940.             $Content $engine->render('ApplicationBundle:modals/input_forms:trade_offer_modal_1_1.html.twig', array());
  5941.         else if ($discount_type == 2)
  5942.             $Content $engine->render('ApplicationBundle:modals/input_forms:add_product_to_product_list.html.twig', array());
  5943.         else if ($discount_type == 3)
  5944.             $Content $engine->render('ApplicationBundle:modals/input_forms:add_product_to_product_list.html.twig', array());
  5945.         else
  5946.             $Content $engine->render('ApplicationBundle:modals/input_forms:add_product_to_product_list.html.twig', array());
  5947.         //        $stockPosition=$engine->render('@Sales/pages/report/selected_products_stock_position.html.twig', array('pSalesDetails'=>$ProductSales));
  5948.         return new JsonResponse(array("success" => false"content" => $Content,));
  5949.     }
  5950.     public function CreateServiceOrder(Request $request)
  5951.     {
  5952.         return $this->render(
  5953.             '@Sales/pages/input_forms/new_service_order.html.twig',
  5954.             array(
  5955.                 'page_title' => 'New Service Order',
  5956.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager())
  5957.             )
  5958.         );
  5959.     }
  5960.     public function GetSelectedServiceHistory(Request $request)
  5961.     {
  5962.         $em $this->getDoctrine()->getManager();
  5963.         $engine $this->container->get("templating");
  5964.         $pids array_unique(explode("::"$_POST["pids"]));
  5965.         $services $em->getRepository('ApplicationBundle:AccService')->findBy(array(
  5966.             'id' => $pids
  5967.         ));
  5968.         $ProductSales = array();
  5969.         foreach ($services as &$service) {
  5970.             $ProductSales[] = array(
  5971.                 "name" => $service->getServiceName(),
  5972.                 "unit_price" => "100",
  5973.                 "quantity" => "15"
  5974.             );
  5975.         }
  5976.         $Content $engine->render('@Sales/pages/report/selected_products_details.html.twig', array('pSalesDetails' => $ProductSales));
  5977.         return new JsonResponse(array("success" => false"content" => $Content));
  5978.     }
  5979.     public function CreateTransportBill(Request $request)
  5980.     {
  5981.         return $this->render(
  5982.             '@Sales/pages/input_forms/transport_bill.html.twig',
  5983.             array(
  5984.                 'page_title' => 'New Transport Bill'
  5985.             )
  5986.         );
  5987.     }
  5988.     public function CreateSalesBill(Request $request)
  5989.     {
  5990.         return $this->render(
  5991.             '@Sales/pages/input_forms/sales_bill.html.twig',
  5992.             array(
  5993.                 'page_title' => 'New Sales Bill'
  5994.             )
  5995.         );
  5996.     }
  5997.     public function CreateServiceBill(Request $request)
  5998.     {
  5999.         return $this->render(
  6000.             '@Sales/pages/input_forms/service_bill.html.twig',
  6001.             array(
  6002.                 'page_title' => 'New Service Bill'
  6003.             )
  6004.         );
  6005.     }
  6006.     public function CreateClient(Request $request$id 0)
  6007.     {
  6008.         $exClientId $id;
  6009.         if ($exClientId == 0)
  6010.             $exClientId $request->query->has("ex_c_id") ? $request->query->get("ex_c_id") : null;
  6011.         $em $this->getDoctrine()->getManager();
  6012.         $companyId $this->getLoggedUserCompanyId($request);
  6013.         $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6014.         if ($request->isMethod('POST')) {
  6015.             if ($request->request->get('exClientID'false)) {
  6016.                 $IFUpdated Client::UpdateClient(
  6017.                     $em,
  6018.                     $this->getLoggedUserCompanyId($request),
  6019.                     $request->request->get('exClientID'),
  6020.                     $request->request->get('clientName'),
  6021.                     $request->request->get('contactPersonName'),
  6022.                     $request->request->get('clientDue') == '' $request->request->get('clientDue'),
  6023.                     $request->request->get('initialOpeningBalance') == '' $request->request->get('initialOpeningBalance'),
  6024.                     $request->request->get('salesPersonID'),
  6025.                     $request->request->get('type'),
  6026.                     $request->request->get('regionId'),
  6027.                     $request->request->get('countryId'),
  6028.                     $request->request->get('geographicalRegionId'),
  6029.                     $request->request->get('clientNumericalCode'),
  6030.                     $request->request->get('clientAreaWiseCode'),
  6031.                     $request->request->get('clientShortCode'),
  6032.                     $request->request->get('clientAlternateCode'),
  6033.                     0,
  6034.                     //                    $request->request->get('divisionId'),
  6035.                     $request->request->get('addressContact'),
  6036.                     $request->request->get('contactNumber'),
  6037.                     $request->request->get('shippingAddress'),
  6038.                     $request->request->get('billingAddress'),
  6039.                     $request->request->get('email'),
  6040.                     $request->request->get('fax'),
  6041.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6042.                     0,
  6043.                     $request->request->get('accountsHeadId''_UNSET_'),
  6044.                     $request->request->get('advanceHeadId''_UNSET_'),
  6045.                     $request->request->get('allowedBrandIds'null),
  6046.                     $request->request->get('creditLimitEnabled'0),
  6047.                     $request->request->get('creditLimit'null),
  6048.                     $request->request->get('generalInfoTin'null),
  6049.                     $request->request->get('generalInfoBin'null),
  6050.                     $request->request->get('isIndividual'null),
  6051.                     $request->request->get('defaultCourierId'0)
  6052.                 );
  6053.                 if ($IFUpdated) {
  6054.                     $this->addFlash(
  6055.                         'success',
  6056.                         'Client Updated'
  6057.                     );
  6058.                 } else {
  6059.                     $this->addFlash(
  6060.                         'error',
  6061.                         'Client have not been updated'
  6062.                     );
  6063.                 }
  6064.                 //                return $this->redirectToRoute("create_client");
  6065.             } else {
  6066.                 Client::CreateNewClient(
  6067.                     $em,
  6068.                     $this->getLoggedUserCompanyId($request),
  6069.                     $request->request->get('clientName'),
  6070.                     $request->request->get('clientDue') == '' $request->request->get('clientDue'),
  6071.                     $request->request->get('initialOpeningBalance') == '' $request->request->get('initialOpeningBalance'),
  6072.                     $request->request->get('contactPersonName'),
  6073.                     $request->request->get('salesPersonID'),
  6074.                     $request->request->get('type'),
  6075.                     $request->request->get('regionId'),
  6076.                     $request->request->get('countryId'),
  6077.                     $request->request->get('geographicalRegionId'),
  6078.                     $request->request->get('clientNumericalCode'),
  6079.                     $request->request->get('clientAreaWiseCode'),
  6080.                     $request->request->get('clientShortCode'),
  6081.                     $request->request->get('clientAlternateCode'),
  6082.                     //                    $request->request->get('divisionId'),
  6083.                     0,
  6084.                     $request->request->get('addressContact'),
  6085.                     $request->request->get('contactNumber'),
  6086.                     $request->request->get('shippingAddress'),
  6087.                     $request->request->get('billingAddress'),
  6088.                     $request->request->get('email'),
  6089.                     $request->request->get('fax'),
  6090.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6091.                     $request->request->get('accountsHeadId''_UNSET_'),
  6092.                     $request->request->get('advanceHeadId''_UNSET_'),
  6093.                     $request->request->get('allowedBrandIds'null),
  6094.                     $request->request->get('creditLimitEnabled'0),
  6095.                     $request->request->get('creditLimit'null),
  6096.                     $request->request->get('generalInfoTin'null),
  6097.                     $request->request->get('generalInfoBin'null),
  6098.                     $request->request->get('isIndividual'null),
  6099.                     $request->request->get('defaultCourierId'0)
  6100.                 );
  6101.             }
  6102.             Client::ProcessTempClients($em$companyId);
  6103.         }
  6104.         return $this->render(
  6105.             '@Sales/pages/input_forms/create_client.html.twig',
  6106.             array(
  6107.                 'page_title' => 'New Client',
  6108.                 'existingClientID' => $exClientId,
  6109.                 'brand_list' => Inventory::GetBrandList($em$this->getLoggedUserCompanyId($request)),
  6110.                 'client_types' => Client::ClientTypeList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6111.                 'region_data' => Client::RegionListForClientEntry($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  6112.                 'geographical_region_data' => Client::GeographicalRegionListForClientEntry($this->getDoctrine()->getManager(), 19$this->getLoggedUserCompanyId($request)),
  6113.                 'division_list' => Client::DivisionList($this->getDoctrine()->getManager()),
  6114.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  6115.                 'sales_person_list_array' => Client::SalesPersonListArray($this->getDoctrine()->getManager()),
  6116.                 'heads' => Accounts::getLedgerHeadsWithParents($em)
  6117.             )
  6118.         );
  6119.     }
  6120.     public function CreateClientForApp(Request $request$id 0)
  6121.     {
  6122.         $exClientId $id;
  6123.         if ($exClientId == 0)
  6124.             $exClientId $request->query->has("ex_c_id") ? $request->query->get("ex_c_id") : null;
  6125.         $em $this->getDoctrine()->getManager();
  6126.         $companyId $this->getLoggedUserCompanyId($request);
  6127.         $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6128.         if ($request->isMethod('POST')) {
  6129.             if ($request->request->get('exClientID'false)) {
  6130.                 $IFUpdated Client::UpdateClient(
  6131.                     $em,
  6132.                     $this->getLoggedUserCompanyId($request),
  6133.                     $request->request->get('exClientID'),
  6134.                     $request->request->get('clientName'),
  6135.                     $request->request->get('contactPersonName'),
  6136.                     $request->request->get('clientDue') == '' $request->request->get('clientDue'),
  6137.                     $request->request->get('initialOpeningBalance') == '' $request->request->get('initialOpeningBalance'),
  6138.                     $request->request->get('salesPersonID'),
  6139.                     $request->request->get('type'),
  6140.                     $request->request->get('regionId'),
  6141.                     $request->request->get('countryId'),
  6142.                     $request->request->get('geographicalRegionId'),
  6143.                     $request->request->get('clientNumericalCode'),
  6144.                     $request->request->get('clientAreaWiseCode'),
  6145.                     $request->request->get('clientShortCode'),
  6146.                     $request->request->get('clientAlternateCode'),
  6147.                     0,
  6148.                     //                    $request->request->get('divisionId'),
  6149.                     $request->request->get('addressContact'),
  6150.                     $request->request->get('contactNumber'),
  6151.                     $request->request->get('shippingAddress'),
  6152.                     $request->request->get('billingAddress'),
  6153.                     $request->request->get('email'),
  6154.                     $request->request->get('fax'),
  6155.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6156.                     0,
  6157.                     $request->request->get('accountsHeadId''_UNSET_'),
  6158.                     $request->request->get('advanceHeadId''_UNSET_'),
  6159.                     $request->request->get('allowedBrandIds'null),
  6160.                     $request->request->get('creditLimitEnabled'0),
  6161.                     $request->request->get('creditLimit'null),
  6162.                     $request->request->get('generalInfoTin'null),
  6163.                     $request->request->get('generalInfoBin'null),
  6164.                     $request->request->get('isIndividual'null),
  6165.                     $request->request->get('defaultCourierId'0)
  6166.                 );
  6167.                 if ($IFUpdated) {
  6168.                     $this->addFlash(
  6169.                         'success',
  6170.                         'Client Updated'
  6171.                     );
  6172.                 } else {
  6173.                     $this->addFlash(
  6174.                         'error',
  6175.                         'Client have not been updated'
  6176.                     );
  6177.                 }
  6178.                 //                return $this->redirectToRoute("create_client");
  6179.             } else {
  6180.                 Client::CreateNewClient(
  6181.                     $em,
  6182.                     $this->getLoggedUserCompanyId($request),
  6183.                     $request->request->get('clientName'),
  6184.                     $request->request->get('clientDue') == '' $request->request->get('clientDue'),
  6185.                     $request->request->get('initialOpeningBalance') == '' $request->request->get('initialOpeningBalance'),
  6186.                     $request->request->get('contactPersonName'),
  6187.                     $request->request->get('salesPersonID'),
  6188.                     $request->request->get('type'),
  6189.                     $request->request->get('regionId'),
  6190.                     $request->request->get('countryId'),
  6191.                     $request->request->get('geographicalRegionId'),
  6192.                     $request->request->get('clientNumericalCode'),
  6193.                     $request->request->get('clientAreaWiseCode'),
  6194.                     $request->request->get('clientShortCode'),
  6195.                     $request->request->get('clientAlternateCode'),
  6196.                     //                    $request->request->get('divisionId'),
  6197.                     0,
  6198.                     $request->request->get('addressContact'),
  6199.                     $request->request->get('contactNumber'),
  6200.                     $request->request->get('shippingAddress'),
  6201.                     $request->request->get('billingAddress'),
  6202.                     $request->request->get('email'),
  6203.                     $request->request->get('fax'),
  6204.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6205.                     $request->request->get('accountsHeadId''_UNSET_'),
  6206.                     $request->request->get('advanceHeadId''_UNSET_'),
  6207.                     $request->request->get('allowedBrandIds'null),
  6208.                     $request->request->get('creditLimitEnabled'0),
  6209.                     $request->request->get('creditLimit'null),
  6210.                     $request->request->get('generalInfoTin'null),
  6211.                     $request->request->get('generalInfoBin'null),
  6212.                     $request->request->get('isIndividual'null),
  6213.                     $request->request->get('defaultCourierId'0)
  6214.                 );
  6215.             }
  6216.             Client::ProcessTempClients($em$companyId);
  6217.         }
  6218.         return new JsonResponse(
  6219.             array(
  6220.                 'success' => true,
  6221.             )
  6222.         );
  6223.     }
  6224.     public function UpdateClientOnTheFly(Request $request$id 0)
  6225.     {
  6226.         $exClientId $id;
  6227.         if ($exClientId == 0)
  6228.             $exClientId $request->request->has("clientId") ? $request->request->get("clientId") : null;
  6229.         $returnTableData $request->request->has("returnTableData") ? $request->request->get("returnTableData") : 0;
  6230.         $em $this->getDoctrine()->getManager();
  6231.         $companyId $this->getLoggedUserCompanyId($request);
  6232.         $data = [];
  6233.         if ($request->isMethod('POST')) {
  6234.             if ($request->request->has('clientId')) {
  6235.                 $entry Client::UpdateClientOnTheFly(
  6236.                     $em,
  6237.                     $this->getLoggedUserCompanyId($request),
  6238.                     $request->request->get('clientId'),
  6239.                     $request->request->get('clientName'),
  6240.                     $request->request->get('contactPersonName'),
  6241.                     $request->request->get('clientDue') == '' $request->request->get('clientDue'),
  6242.                     $request->request->has('initialOpeningBalance') ? $request->request->get('initialOpeningBalance') : 0,
  6243.                     $request->request->get('salesPersonID'),
  6244.                     $request->request->get('type'),
  6245.                     $request->request->get('regionId'),
  6246.                     $request->request->get('countryId'),
  6247.                     $request->request->get('geographicalRegionId'null),
  6248.                     $request->request->get('clientNumericalCode'''),
  6249.                     $request->request->get('clientAreaWiseCode'''),
  6250.                     $request->request->get('clientShortCode'''),
  6251.                     $request->request->get('clientAlternateCode'''),
  6252.                     0,
  6253.                     //                    $request->request->get('divisionId'),
  6254.                     $request->request->get('addressContact'$request->request->get('billingAddress''')),
  6255.                     $request->request->get('contactNumber'),
  6256.                     $request->request->get('shippingAddress'),
  6257.                     $request->request->get('billingAddress'),
  6258.                     $request->request->get('email'),
  6259.                     $request->request->get('fax'''),
  6260.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6261.                     $request->request->get('tempFlag'0)
  6262.                 );
  6263.                 if ($entry) {
  6264.                     if ($returnTableData == 1) {
  6265.                         $get_kids_sql "SELECT * FROM acc_clients
  6266.                                 WHERE client_id=" $entry->getClientId();
  6267.                         //                $get_kids_sql .=' ORDER BY name ASC';
  6268.                         $stmt $em->getConnection()->prepare($get_kids_sql);
  6269.                         $stmt->execute();
  6270.                         $em->flush();
  6271.                         $check_here $stmt->fetchAll();
  6272.                         $data $check_here[0];
  6273.                         $data['id'] = $entry->getClientId();
  6274.                         $data['value'] = $entry->getClientId();
  6275.                         $data['text'] = $entry->getClientName();
  6276.                     } else {
  6277.                         $data = array(
  6278.                             'id' => $entry->getClientId(),
  6279.                             'value' => $entry->getClientId(),
  6280.                             'name' => $entry->getClientName(),
  6281.                             'contactNumber' => $entry->getContactNumber(),
  6282.                             'email' => $entry->getEmail(),
  6283.                             'numericalCode' => $entry->getClientNumericalCode(),
  6284.                             'invoiced' => $entry->getClientInvoiceAmount(),
  6285.                             'received' => $entry->getClientReceived(),
  6286.                             'due' => $entry->getClientDue(),
  6287.                             'clientType' => $entry->getType(),
  6288.                             'regionId' => $entry->getRegionId(),
  6289.                             'accHeadId' => $entry->getAccountsHeadId(),
  6290.                             'salesPersonId' => $entry->getSalesPersonId(),
  6291.                             'advanceHeadId' => $entry->getAdvanceHeadId(),
  6292.                             'tempFlag' => $entry->getTempClientFlag(),
  6293.                         );
  6294.                     }
  6295.                     return new JsonResponse(
  6296.                         array(
  6297.                             'success' => true,
  6298.                             'data' => $data
  6299.                         )
  6300.                     );
  6301.                 } else {
  6302.                     return new JsonResponse(
  6303.                         array(
  6304.                             'success' => false,
  6305.                             'data' => $data
  6306.                         )
  6307.                     );
  6308.                 }
  6309.                 //                return $this->redirectToRoute("create_client");
  6310.             } else {
  6311.                 return new JsonResponse(
  6312.                     array(
  6313.                         'success' => false,
  6314.                         'data' => $data
  6315.                     )
  6316.                 );
  6317.             }
  6318.         }
  6319.         return new JsonResponse(
  6320.             array(
  6321.                 'success' => false,
  6322.                 'data' => $data
  6323.             )
  6324.         );
  6325.     }
  6326.     public function UpdateSecondaryClientOnTheFly(Request $request$id 0)
  6327.     {
  6328.         $exClientId $id;
  6329.         if ($exClientId == 0)
  6330.             $exClientId $request->request->has("clientId") ? $request->request->get("clientId") : null;
  6331.         $em $this->getDoctrine()->getManager();
  6332.         $companyId $this->getLoggedUserCompanyId($request);
  6333.         $data = [];
  6334.         if ($request->isMethod('POST')) {
  6335.             if ($request->request->has('clientId')) {
  6336.                 $entry Client::UpdateSecondaryClientOnTheFly(
  6337.                     $em,
  6338.                     $this->getLoggedUserCompanyId($request),
  6339.                     $request->request->get('clientId'),
  6340.                     $request->request->get('clientName'),
  6341.                     $request->request->get('contactPersonName'),
  6342.                     $request->request->get('clientDue') == '' $request->request->get('clientDue'),
  6343.                     $request->request->has('initialOpeningBalance') ? $request->request->get('initialOpeningBalance') : 0,
  6344.                     $request->request->get('salesPersonID'),
  6345.                     $request->request->get('type'),
  6346.                     $request->request->get('regionId'),
  6347.                     $request->request->get('countryId'),
  6348.                     $request->request->get('geographicalRegionId'null),
  6349.                     $request->request->get('clientNumericalCode'''),
  6350.                     $request->request->get('clientAreaWiseCode'''),
  6351.                     $request->request->get('clientShortCode'''),
  6352.                     $request->request->get('clientAlternateCode'''),
  6353.                     0,
  6354.                     //                    $request->request->get('divisionId'),
  6355.                     $request->request->get('addressContact'$request->request->get('billingAddress''')),
  6356.                     $request->request->get('contactNumber'),
  6357.                     $request->request->get('shippingAddress'),
  6358.                     $request->request->get('billingAddress'),
  6359.                     $request->request->get('email'),
  6360.                     $request->request->get('fax'''),
  6361.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  6362.                     $request->request->get('tempFlag'0)
  6363.                 );
  6364.                 if ($entry) {
  6365.                     $data = array(
  6366.                         'id' => $entry->getClientId(),
  6367.                         'value' => $entry->getClientId(),
  6368.                         'name' => $entry->getClientName(),
  6369.                         'contactNumber' => $entry->getContactNumber(),
  6370.                         'email' => $entry->getEmail(),
  6371.                         'numericalCode' => $entry->getClientNumericalCode(),
  6372.                         'invoiced' => $entry->getClientInvoiceAmount(),
  6373.                         'received' => $entry->getClientReceived(),
  6374.                         'due' => $entry->getClientDue(),
  6375.                         'clientType' => $entry->getType(),
  6376.                         'regionId' => $entry->getRegionId(),
  6377.                         'accHeadId' => $entry->getAccountsHeadId(),
  6378.                         'salesPersonId' => $entry->getSalesPersonId(),
  6379.                         'advanceHeadId' => $entry->getAdvanceHeadId(),
  6380.                         'tempFlag' => $entry->getTempClientFlag(),
  6381.                     );
  6382.                     return new JsonResponse(
  6383.                         array(
  6384.                             'success' => true,
  6385.                             'data' => $data
  6386.                         )
  6387.                     );
  6388.                 } else {
  6389.                     return new JsonResponse(
  6390.                         array(
  6391.                             'success' => false,
  6392.                             'data' => $data
  6393.                         )
  6394.                     );
  6395.                 }
  6396.                 //                return $this->redirectToRoute("create_client");
  6397.             } else {
  6398.                 return new JsonResponse(
  6399.                     array(
  6400.                         'success' => false,
  6401.                         'data' => $data
  6402.                     )
  6403.                 );
  6404.             }
  6405.         }
  6406.         return new JsonResponse(
  6407.             array(
  6408.                 'success' => false,
  6409.                 'data' => $data
  6410.             )
  6411.         );
  6412.     }
  6413.     public function ProcessTempClient(Request $request$id 0)
  6414.     {
  6415.         $em $this->getDoctrine()->getManager();
  6416.         $head_id $id;
  6417.         $companyId $this->getLoggedUserCompanyId($request);
  6418.         $loginId $this->getLoggedUserCompanyId($request);
  6419.         $latestCID Client::ProcessTempClients($em$companyId, [], true);
  6420.         if ($latestCID != 0) {
  6421.             return new JsonResponse(array(
  6422.                 "success" => true,
  6423.                 "last_id" => $latestCID,
  6424.                 //                "r"=>$r,
  6425.                 //                "debug_data"=>System::encryptSignature($r)
  6426.             ));
  6427.         } else {
  6428.             return new JsonResponse(array(
  6429.                 "success" => false,
  6430.                 "last_id" => $latestCID,
  6431.                 //                "r"=>$r,
  6432.                 //                "debug_data"=>System::encryptSignature($r)
  6433.             ));
  6434.         }
  6435.         //        return $this->redirectToRoute('dashboard');
  6436.     }
  6437.     public function SalesRegion(Request $request$id)
  6438.     {
  6439.         $cc_id '';
  6440.         $cc_name '';
  6441.         $companyId $this->getLoggedUserCompanyId($request);
  6442.         if ($request->isMethod('POST')) {
  6443.             $regionId 0;
  6444.             $em $this->getDoctrine()->getManager();
  6445.             if ($request->request->get('regionId') != '' && $request->request->get('regionId') != 0) {
  6446.                 $em $this->getDoctrine()->getManager();
  6447.                 $new_cc $this->getDoctrine()
  6448.                     ->getRepository('ApplicationBundle:Region')
  6449.                     ->findOneBy(
  6450.                         array(
  6451.                             'id' => $request->request->get('regionId'),
  6452.                         )
  6453.                     );
  6454.                 $new_cc->setName($request->request->get('name'));
  6455.                 $new_cc->setCode($request->request->get('code'));
  6456.                 $new_cc->setCountryId($request->request->get('countryId'));
  6457.                 $new_cc->setCompanyId($companyId);
  6458.                 $new_cc->setParentRegionId($request->request->get('parentRegionId'));
  6459.                 $new_cc->setSalesPersonId($request->request->get('salesPersonId'));
  6460.                 $new_cc->setRegionHeadId($request->request->get('regionHeadId'));
  6461.                 $new_cc->setSalesPersonIds(json_encode($request->request->get('salesPersonIds')));
  6462.                 $new_cc->setRegionLevelId($request->request->get('regionLevelId'));
  6463.                 $em->flush();
  6464.                 $regionId $id;
  6465.             } else {
  6466.                 $new_cc = new Region();
  6467.                 $new_cc->setName($request->request->get('name'));
  6468.                 $new_cc->setCode($request->request->get('code'));
  6469.                 $new_cc->setCountryId($request->request->get('countryId'));
  6470.                 $new_cc->setCompanyId($companyId);
  6471.                 $new_cc->setParentRegionId($request->request->get('parentRegionId'));
  6472.                 $new_cc->setSalesPersonId($request->request->get('salesPersonId'));
  6473.                 $new_cc->setRegionHeadId($request->request->get('regionHeadId'));
  6474.                 $new_cc->setSalesPersonIds(json_encode($request->request->get('salesPersonIds')));
  6475.                 $new_cc->setRegionLevelId($request->request->get('regionLevelId'));
  6476.                 $em->persist($new_cc);
  6477.                 $em->flush();
  6478.                 $regionId $new_cc->getId();
  6479.             }
  6480.             $related_head_for_path_tree explode('/'$request->request->get('pathTree'));
  6481.             $related_head_for_path_tree[] = $regionId;
  6482.             Client::UpdateRegionPath($em$related_head_for_path_tree$companyId);
  6483.             //now update salesperson on any client if available
  6484.             if ($request->request->has('imposeSalesPersonChange')) {
  6485.                 $clients_for_region $this->getDoctrine()
  6486.                     ->getRepository('ApplicationBundle:AccClients')
  6487.                     ->findBy(
  6488.                         array(
  6489.                             'regionId' => $regionId,
  6490.                         )
  6491.                     );
  6492.                 foreach ($clients_for_region as $client) {
  6493.                     $client->setSalesPersonId($request->request->get('salesPersonId'));
  6494.                 }
  6495.                 $em->flush();
  6496.             }
  6497.         }
  6498.         $extRegionData = [];
  6499.         if ($id != 0) {
  6500.             $extRegionData $this->getDoctrine()
  6501.                 ->getRepository('ApplicationBundle:Region')
  6502.                 ->findOneBy(
  6503.                     array(
  6504.                         'id' => $id
  6505.                     )
  6506.                 );
  6507.             //            $cc_data_list = [];
  6508.             //            foreach ($cc_data as $value) {
  6509.             //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  6510.             //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  6511.             //
  6512.             //                if ($value->getSupplierCategoryId() == $id) {
  6513.             //                    $cc_id = $value->getSupplierCategoryId();
  6514.             //                    $cc_name = $value->getName();
  6515.             //                }
  6516.             //            }
  6517.         }
  6518.         return $this->render(
  6519.             '@Sales/pages/input_forms/sales_region.html.twig',
  6520.             array(
  6521.                 'page_title' => 'Sales Region',
  6522.                 'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $companyId),
  6523.                 'extRegionData' => $extRegionData,
  6524.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  6525.                 //                'countryList'=>SalesOrderM::Co
  6526.             )
  6527.         );
  6528.     }
  6529.     public function Branch(Request $request$id)
  6530.     {
  6531.         $cc_id '';
  6532.         $cc_name '';
  6533.         $em $this->getDoctrine()->getManager();
  6534.         $companyId $this->getLoggedUserCompanyId($request);
  6535.         if ($request->isMethod('POST')) {
  6536.             $new_cc = [];
  6537.             $regionId 0;
  6538.             $warehouseId $request->request->get('warehouseId');
  6539.             if ($request->request->get('branchId') != '' && $request->request->get('branchId') != 0) {
  6540.                 $em $this->getDoctrine()->getManager();
  6541.                 $new_cc $this->getDoctrine()
  6542.                     ->getRepository('ApplicationBundle:Branch')
  6543.                     ->findOneBy(
  6544.                         array(
  6545.                             'branchId' => $request->request->get('branchId'),
  6546.                         )
  6547.                     );
  6548.                 $new_cc->setName($request->request->get('name'));
  6549.                 $new_cc->setAddress($request->request->get('address'));
  6550.                 $new_cc->setDeliveryAddress($request->request->get('deliveryAddress'));
  6551.                 $new_cc->setBillingAddress($request->request->get('billingAddress'));
  6552.                 $new_cc->setWarehouseId($request->request->get('warehouseId'));
  6553.                 $new_cc->setCashHeadIds(json_encode($request->request->get('cashHeadIds')));
  6554.                 $new_cc->setBankHeadIds(json_encode($request->request->get('bankHeadIds')));
  6555.                 $new_cc->setCompanyId($companyId);
  6556.                 $new_cc->setType($request->request->get('type'));
  6557.                 $new_cc->setReplacementAllowed($request->request->get('replacementAllowed'0));
  6558.                 $new_cc->setDeliveryAllowed($request->request->get('deliveryAllowed'0));
  6559.                 $new_cc->setSellAllowed($request->request->get('sellAllowed'0));
  6560.                 $new_cc->setSalesMethod($request->request->get('salesMethod'));
  6561.                 $new_cc->setDeliveryProcessType($request->request->get('deliveryProcessType'));
  6562.                 $new_cc->setPaymentProcessType($request->request->get('paymentProcessType'));
  6563.                 $em->flush();
  6564.                 $branchId $new_cc->getBranchId();
  6565.                 $this->addFlash(
  6566.                     'success',
  6567.                     'Branch Information Updated'
  6568.                 );
  6569.             } else {
  6570.                 $new_cc = new Branch();
  6571.                 $new_cc->setName($request->request->get('name'));
  6572.                 $new_cc->setWarehouseId($request->request->get('warehouseId'));
  6573.                 $new_cc->setCashHeadIds(json_encode($request->request->get('cashHeadIds')));
  6574.                 $new_cc->setBankHeadIds(json_encode($request->request->get('bankHeadIds')));
  6575.                 $new_cc->setCompanyId($companyId);
  6576.                 $new_cc->setType($request->request->get('type'));
  6577.                 $new_cc->setSalesMethod($request->request->get('salesMethod'));
  6578.                 $new_cc->setDeliveryProcessType($request->request->get('deliveryProcessType'));
  6579.                 $new_cc->setPaymentProcessType($request->request->get('paymentProcessType'));
  6580.                 $new_cc->setReplacementAllowed($request->request->get('replacementAllowed'0));
  6581.                 $new_cc->setDeliveryAllowed($request->request->get('deliveryAllowed'0));
  6582.                 $new_cc->setSellAllowed($request->request->get('sellAllowed'0));
  6583.                 $em->persist($new_cc);
  6584.                 $em->flush();
  6585.                 $branchId $new_cc->getBranchId();
  6586.                 $em->flush();
  6587.                 $this->addFlash(
  6588.                     'success',
  6589.                     'New Branch Added'
  6590.                 );
  6591.             }
  6592.             //now update salesperson on any client if available
  6593.             $warehouse null;
  6594.             if ($request->request->has('addWarehouseToSystem')) {
  6595.                 if ($warehouseId == || $warehouseId == '') {
  6596.                     $warehouse = new Warehouse();
  6597.                     $warehouse->setCompanyId($companyId);
  6598.                     $warehouse->setName($request->request->get('name'));
  6599.                     $warehouse->setStatus(GeneralConstant::ACTIVE);
  6600.                     $warehouse->setReplacementAllowed($request->request->get('replacementAllowed'0));
  6601.                     $warehouse->setDeliveryAllowed($request->request->get('deliveryAllowed'0));
  6602.                     $warehouse->setSellAllowed($request->request->get('sellAllowed'0));
  6603.                     $em->persist($warehouse);
  6604.                     $em->flush();
  6605.                     $new_cc->setWarehouseId($warehouse->getId());
  6606.                     $em->flush();
  6607.                 } else {
  6608.                     $warehouse $this->getDoctrine()
  6609.                         ->getRepository('ApplicationBundle:Warehouse')
  6610.                         ->findOneBy(
  6611.                             array(
  6612.                                 'id' => $new_cc->getWarehouseId(),
  6613.                             )
  6614.                         );;
  6615.                     //                    $warehouse->setCompanyId($companyId);
  6616.                     //                    $warehouse->setName($request->request->get('name'));
  6617.                     //                    $warehouse->setStatus(GeneralConstant::ACTIVE);
  6618.                     //                    $warehouse->setReplacementAllowed($request->request->get('replacementAllowed',0));
  6619.                     //                    $warehouse->setDeliveryAllowed($request->request->get('deliveryAllowed',0));
  6620.                     //                    $warehouse->setSellAllowed($request->request->get('sellAllowed',0));
  6621.                     //                    $em->persist($warehouse);
  6622.                     //                    $em->flush();
  6623.                     //                    $new_cc->setWarehouseId($warehouse->getId());
  6624.                     //                    $em->flush();
  6625.                 }
  6626.             }
  6627.             if ($warehouse) {
  6628.             } else
  6629.                 $warehouse $this->getDoctrine()
  6630.                     ->getRepository('ApplicationBundle:Warehouse')
  6631.                     ->findOneBy(
  6632.                         array(
  6633.                             'id' => $new_cc->getWarehouseId(),
  6634.                         )
  6635.                     );;
  6636.             if ($warehouse) {
  6637.                 $warehouse->setReplacementAllowed($request->request->get('replacementAllowed'0));
  6638.                 $warehouse->setDeliveryAllowed($request->request->get('deliveryAllowed'0));
  6639.                 $warehouse->setSellAllowed($request->request->get('sellAllowed'0));
  6640.                 //                    $em->persist($warehouse);
  6641.                 //                    $em->flush();
  6642.                 //                    $new_cc->setWarehouseId($warehouse->getId());
  6643.                 $em->flush();
  6644.             }
  6645.             if ($request->request->has('addCashHeadToSystem')) {
  6646.                 $id_list json_decode($new_cc->getCashHeadIds(), true);
  6647.                 if ($id_list == [] || $id_list == null) {
  6648.                     if ($id_list == null)
  6649.                         $id_list = [];
  6650.                     //now get the cash parent for branch head
  6651.                     $par_set $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  6652.                         'name' => 'branch_cash_parent'
  6653.                     ));
  6654.                     $par_head '';
  6655.                     if ($par_set)
  6656.                         $par_head $par_set->getData();
  6657.                     if ($par_head == '') {
  6658.                         $this->addFlash(
  6659.                             'error',
  6660.                             'Could not add cash head. Parent not found in settings'
  6661.                         );
  6662.                     } else {
  6663.                         //create The head
  6664.                         $accHead Accounts::CreateNewHead($emGeneralConstant::OPENING_YEAR$par_head'Cash at ' $new_cc->getName(), ''00'dr'$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6665.                         $id_list Accounts::addNumberToArrayIfNotExists($accHead$id_list);
  6666.                         $new_cc->setCashHeadIds(json_encode($id_list));
  6667.                         $em->flush();
  6668.                     }
  6669.                 }
  6670.             }
  6671.             if ($request->request->has('addBankHeadToSystem')) {
  6672.                 $id_list json_decode($new_cc->getBankHeadIds(), true);
  6673.                 if ($id_list == [] || $id_list == null) {
  6674.                     if ($id_list == null)
  6675.                         $id_list = [];
  6676.                     //now get the bank parent for branch head
  6677.                     $par_set $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  6678.                         'name' => 'branch_bank_parent'
  6679.                     ));
  6680.                     $par_head '';
  6681.                     if ($par_set)
  6682.                         $par_head $par_set->getData();
  6683.                     if ($par_head == '') {
  6684.                         $this->addFlash(
  6685.                             'error',
  6686.                             'Could not add bank head. Parent not found in settings'
  6687.                         );
  6688.                     } else {
  6689.                         //create The head
  6690.                         $accHead Accounts::CreateNewHead($emGeneralConstant::OPENING_YEAR$par_head'Bank at ' $new_cc->getName(), ''00'dr'$request->getSession()->get(UserConstants::USER_LOGIN_ID));
  6691.                         $id_list Accounts::addNumberToArrayIfNotExists($accHead$id_list);
  6692.                         $new_cc->setBankHeadIds(json_encode($id_list));
  6693.                         $em->flush();
  6694.                     }
  6695.                 }
  6696.             }
  6697.         }
  6698.         $extData = [];
  6699.         if ($id != 0) {
  6700.             $extData $this->getDoctrine()
  6701.                 ->getRepository('ApplicationBundle:Branch')
  6702.                 ->findOneBy(
  6703.                     array(
  6704.                         'branchId' => $id
  6705.                     )
  6706.                 );
  6707.             //            $cc_data_list = [];
  6708.             //            foreach ($cc_data as $value) {
  6709.             //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  6710.             //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  6711.             //
  6712.             //                if ($value->getSupplierCategoryId() == $id) {
  6713.             //                    $cc_id = $value->getSupplierCategoryId();
  6714.             //                    $cc_name = $value->getName();
  6715.             //                }
  6716.             //            }
  6717.         }
  6718.         return $this->render(
  6719.             '@Sales/pages/input_forms/branch.html.twig',
  6720.             array(
  6721.                 'page_title' => 'Company Branch',
  6722.                 'branchList' => $this->getDoctrine()
  6723.                     ->getRepository('ApplicationBundle:Branch')
  6724.                     ->findBy(
  6725.                         array(
  6726.                             'CompanyId' => $companyId
  6727.                         )
  6728.                     ),
  6729.                 'extData' => $extData,
  6730.                 'headList' => Accounts::getParentLedgerHeads($em),
  6731.                 'branchTypes' => SalesConstant::$branchTypes,
  6732.                 'branchTypeDetails' => SalesConstant::$branchTypeDetails,
  6733.                 'salesMethodList' => SalesConstant::$salesMethod,
  6734.                 'deliveryProcessTypes' => SalesConstant::$deliveryProcessType,
  6735.                 'paymentProcessTypes' => SalesConstant::$paymentProcessType,
  6736.                 'warehouseList' => Inventory::WarehouseList($em),
  6737.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  6738.                 //                'countryList'=>SalesOrderM::Co
  6739.             )
  6740.         );
  6741.     }
  6742.     public function SalesPerson(Request $request$id)
  6743.     {
  6744.         $cc_id '';
  6745.         $cc_name '';
  6746.         $em $this->getDoctrine()->getManager();
  6747.         $companyId $this->getLoggedUserCompanyId($request);
  6748.         if ($request->isMethod('POST')) {
  6749.             $regionIds = [];
  6750.             $regionLeaderFlags = [];
  6751.             $employeeId 0;
  6752.             $file_path null;
  6753.             foreach ($request->files as $uploadedFile) {
  6754.                 if ($uploadedFile != null) {
  6755.                     $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  6756.                     $path $fileName;
  6757.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $request->request->get('userId') . '/';
  6758.                     if (!file_exists($upl_dir)) {
  6759.                         mkdir($upl_dir0777true);
  6760.                     }
  6761.                     $file $uploadedFile->move($upl_dir$path);
  6762.                     if ($path != "")
  6763.                         $file_path 'uploads/FileUploads/' $request->request->get('userId') . '/' $path;
  6764.                 }
  6765.             }
  6766.             $name $request->request->get('name');
  6767.             $LoginID $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  6768.             if ($request->request->get('employeeId') != '' && $request->request->get('employeeId') != 0) {
  6769.                 $em $this->getDoctrine()->getManager();
  6770.                 $new_cc $this->getDoctrine()
  6771.                     ->getRepository('ApplicationBundle:Employee')
  6772.                     ->findOneBy(
  6773.                         array(
  6774.                             'employeeId' => $request->request->get('employeeId'),
  6775.                         )
  6776.                     );
  6777.                 $AccHeadId $new_cc->getAccountsHeadId();
  6778.                 if ($AccHeadId == || $AccHeadId == null || $AccHeadId == '') {
  6779.                     $general_parent 0;
  6780.                     $general_parent_head $em->getRepository('ApplicationBundle:AccAccountsHead')
  6781.                         ->findOneBy(array(
  6782.                             'markerHash' => AccountsConstant::GENERAL_EMPLOYEE_PARENT
  6783.                         ));
  6784.                     if ($general_parent)
  6785.                         $AccHeadId Accounts::CreateNewHead($emGeneralConstant::OPENING_YEAR$general_parent_head->getAccountsHeadId(), $name''00'cr'$LoginID);
  6786.                     else
  6787.                         $AccHeadId null;
  6788.                 }
  6789.                 $new_cc->setAccountsHeadId($AccHeadId);
  6790.                 $new_cc->setName($request->request->get('name'));
  6791.                 $new_cc->setAllowedBrandIds(json_encode($request->request->get('allowedBrandIds')));
  6792.                 $new_cc->setCountryId($request->request->get('countryId'));
  6793.                 $new_cc->setCompanyId($companyId);
  6794.                 $new_cc->setBranchId($request->request->get('branchId'));
  6795.                 $new_cc->setEmployeeCode($request->request->get('employeeCode'));
  6796.                 $new_cc->setAddressContact($request->request->get('addressContact'));
  6797.                 $new_cc->setContactNumber($request->request->get('contactNumber'));
  6798.                 $new_cc->setPositionId($request->request->get('positionId'));
  6799.                 $new_cc->setUserId($request->request->get('userId'));
  6800.                 $new_cc->setSupervisorId($request->request->get('supervisorId'));
  6801.                 $new_cc->setImage($file_path);
  6802.                 $new_cc->setSalesPersonFlag($request->request->has('salesPersonFlag') ? 0);
  6803.                 $regionIds = [];
  6804.                 $regionLeaderFlags = [];
  6805.                 if ($request->request->has('regionId')) {
  6806.                     foreach ($request->request->get('regionId') as $key => $val) {
  6807.                         if ($val != '' && $val != 0) {
  6808.                             $regionIds[] = $request->request->get('regionId')[$key];
  6809.                             $regionLeaderFlags[] = $request->request->get('regionLeaderFlag')[$key];
  6810.                         }
  6811.                     }
  6812.                 }
  6813.                 $new_cc->setRegionIds(json_encode($regionIds));
  6814.                 $new_cc->setRegionLeaderFlags(json_encode($regionLeaderFlags));
  6815.                 $em->flush();
  6816.                 $employeeId $new_cc->getEmployeeId();
  6817.             } else {
  6818.                 $new_cc = new Employee();
  6819.                 $general_parent 0;
  6820.                 $general_parent_head $em->getRepository('ApplicationBundle:AccAccountsHead')
  6821.                     ->findOneBy(array(
  6822.                         'markerHash' => AccountsConstant::GENERAL_EMPLOYEE_PARENT
  6823.                     ));
  6824.                 if ($general_parent)
  6825.                     $AccHeadId Accounts::CreateNewHead($emGeneralConstant::OPENING_YEAR$general_parent_head->getAccountsHeadId(), $name''00'cr'$LoginID);
  6826.                 else
  6827.                     $AccHeadId null;
  6828.                 $new_cc->setAccountsHeadId($AccHeadId);
  6829.                 $new_cc->setName($request->request->get('name'));
  6830.                 $new_cc->setCountryId($request->request->get('countryId'));
  6831.                 $new_cc->setCompanyId($companyId);
  6832.                 $new_cc->setBranchId($request->request->get('branchId'));
  6833.                 $new_cc->setAllowedBrandIds(json_encode($request->request->get('allowedBrandIds')));
  6834.                 $new_cc->setEmployeeCode($request->request->get('employeeCode'));
  6835.                 $new_cc->setAddressContact($request->request->get('addressContact'));
  6836.                 $new_cc->setContactNumber($request->request->get('contactNumber'));
  6837.                 $new_cc->setPositionId($request->request->get('positionId'));
  6838.                 $new_cc->setUserId($request->request->get('userId'));
  6839.                 $new_cc->setSupervisorId($request->request->get('supervisorId'));
  6840.                 $new_cc->setImage($file_path);
  6841.                 $new_cc->setSalesPersonFlag($request->request->has('salesPersonFlag') ? 0);
  6842.                 $regionIds = [];
  6843.                 $regionLeaderFlags = [];
  6844.                 if ($request->request->has('regionId')) {
  6845.                     foreach ($request->request->get('regionId') as $key => $val) {
  6846.                         if ($val != '' && $val != 0) {
  6847.                             $regionIds[] = $request->request->get('regionId')[$key];
  6848.                             $regionLeaderFlags[] = $request->request->get('regionLeaderFlag')[$key];
  6849.                         }
  6850.                     }
  6851.                 }
  6852.                 $new_cc->setRegionIds(json_encode($regionIds));
  6853.                 $new_cc->setRegionLeaderFlags(json_encode($regionLeaderFlags));
  6854.                 $em->persist($new_cc);
  6855.                 $em->flush();
  6856.                 $employeeId $new_cc->getEmployeeId();
  6857.             }
  6858.             foreach ($regionIds as $k => $regionId) {
  6859.                 $reg $this->getDoctrine()
  6860.                     ->getRepository('ApplicationBundle:Region')
  6861.                     ->findOneBy(
  6862.                         array(
  6863.                             'id' => $regionId,
  6864.                         )
  6865.                     );
  6866.                 if ($reg) {
  6867.                     if ($reg->getSalesPersonIds() == null)
  6868.                         $ext_sp_id_list = [];
  6869.                     else
  6870.                         $ext_sp_id_list json_decode($reg->getSalesPersonIds(), true);
  6871.                     if ($ext_sp_id_list == null)
  6872.                         $ext_sp_id_list = [];
  6873.                     $ext_sp_id_list Accounts::addNumberToArrayIfNotExists($employeeId$ext_sp_id_list);
  6874.                     $reg->setSalesPersonIds(json_encode($ext_sp_id_list));
  6875.                     if ($regionLeaderFlags[$k] == 1) {
  6876.                         $reg->setRegionHeadId($employeeId);
  6877.                     }
  6878.                     $em->flush();
  6879.                 }
  6880.             }
  6881.             //            Client::UpdateRegionPath($em,$related_head_for_path_tree,$companyId);
  6882.             //now update salesperson on any client if available
  6883.             //            if($request->request->has('imposeSalesPersonChange'))
  6884.             //            {
  6885.             //                $clients_for_region = $this->getDoctrine()
  6886.             //                    ->getRepository('ApplicationBundle:AccClients')
  6887.             //                    ->findBy(
  6888.             //                        array(
  6889.             //                            'regionId' => $regionId,
  6890.             //                        )
  6891.             //                    );
  6892.             //                foreach($clients_for_region as $client)
  6893.             //                {
  6894.             //                    $client->setSalesPersonId($request->request->get('salesPersonId'));
  6895.             //
  6896.             //                }
  6897.             //                $em->flush();
  6898.             //            }
  6899.         }
  6900.         $extEmployeeData = [];
  6901.         if ($id != 0) {
  6902.             $extEmployeeData $this->getDoctrine()
  6903.                 ->getRepository('ApplicationBundle:Employee')
  6904.                 ->findOneBy(
  6905.                     array(
  6906.                         'employeeId' => $id
  6907.                     )
  6908.                 );
  6909.             //            $cc_data_list = [];
  6910.             //            foreach ($cc_data as $value) {
  6911.             //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  6912.             //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  6913.             //
  6914.             //                if ($value->getSupplierCategoryId() == $id) {
  6915.             //                    $cc_id = $value->getSupplierCategoryId();
  6916.             //                    $cc_name = $value->getName();
  6917.             //                }
  6918.             //            }
  6919.         }
  6920.         return $this->render(
  6921.             '@Sales/pages/input_forms/create_sales_person.html.twig',
  6922.             array(
  6923.                 'page_title' => 'Sales Person',
  6924.                 'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $companyId),
  6925.                 'extData' => $extEmployeeData,
  6926.                 'brand_list' => Inventory::GetBrandList($em$this->getLoggedUserCompanyId($request)),
  6927.                 'users' => Users::getUserListById($em),
  6928.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  6929.                 'branch_list' => Client::BranchList($this->getDoctrine()->getManager(), $companyId),
  6930.                 //                'countryList'=>SalesOrderM::Co
  6931.             )
  6932.         );
  6933.     }
  6934.     public function ConvertUserToSalesPerson(Request $request)
  6935.     {
  6936.         $qryArray = [];
  6937.         $userIdList = [];
  6938.         $em $this->getDoctrine()->getManager();
  6939.         //        if($request->request->has('department'))
  6940.         //        {
  6941.         //
  6942.         //                $positions=$em->getRepository('ApplicationBundle:SysDepartmentPosition')->findBy(
  6943.         //                    array(
  6944.         //                        'departmentId'=>$positionId
  6945.         //                    )
  6946.         //                );
  6947.         //        }
  6948.         $companyId $this->getLoggedUserCompanyId($request);
  6949.         //        $qryArray['CompanyId']=$companyId;
  6950.         $dt Client::ConvertUserToSalesPerson($em$qryArray);
  6951.         return new JsonResponse(array("success" => true"content" => $dt));
  6952.     }
  6953.     public function CreatePackage(Request $request)
  6954.     {
  6955.         if ($request->isMethod('POST')) {
  6956.             $em $this->getDoctrine()->getManager();
  6957.             if (isset($_POST['products'])) {
  6958.                 $Products = array(
  6959.                     'products' => $_POST['products'],
  6960.                     'product_units' => $_POST['product_units'],
  6961.                     'product_unit_price' => $_POST['product_unit_price'],
  6962.                     'product_total_price' => $_POST['product_total_price'],
  6963.                     'product_reference_price' => $_POST['product_reference_price']
  6964.                 );
  6965.             } else {
  6966.                 $Products = array();
  6967.             }
  6968.             if (isset($_POST['services'])) {
  6969.                 $Services = array(
  6970.                     'services' => $_POST['services'],
  6971.                     'services_units' => $_POST['services_units'],
  6972.                     'services_unit_price' => $_POST['services_unit_price'],
  6973.                     'services_total_price' => $_POST['services_total_price'],
  6974.                     'services_reference_price' => $_POST['services_reference_price']
  6975.                 );
  6976.             } else {
  6977.                 $Services = array();
  6978.             }
  6979.             if (isset($_POST['heads'])) {
  6980.                 $ArCosts = array(
  6981.                     'heads' => $_POST['heads'],
  6982.                     'ar_units' => $_POST['ar_units'],
  6983.                     'ar_unit_price' => $_POST['ar_unit_price'],
  6984.                     'ar_total_price' => $_POST['ar_total_price'],
  6985.                     'ar_reference_price' => $_POST['ar_reference_price']
  6986.                 );
  6987.             } else {
  6988.                 $ArCosts = array();
  6989.             }
  6990.             $pckgId Package::CreatePackage(
  6991.                 $em,
  6992.                 $request->request->get('packageName'),
  6993.                 $request->request->get('categoryID'),
  6994.                 $request->request->get('subCategory'),
  6995.                 $request->request->get('salesWarrenty'),
  6996.                 $request->request->get('note'),
  6997.                 json_encode(
  6998.                     $Products
  6999.                 ),
  7000.                 json_encode(
  7001.                     $Services
  7002.                 ),
  7003.                 json_encode(
  7004.                     $ArCosts
  7005.                 ),
  7006.                 $request->request->get('markupPercentage'),
  7007.                 $request->request->get('totalCost'),
  7008.                 $request->request->get('totalStoreCost'),
  7009.                 $request->request->get('totalNonStoreCost'),
  7010.                 $request->request->get('salesValue'),
  7011.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7012.                 $this->getLoggedUserCompanyId($request)
  7013.             );
  7014.             //now add Approval info
  7015.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7016.             $approveRole 1;  //created
  7017.             $options = array(
  7018.                 'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7019.                 'notification_server' => $this->container->getParameter('notification_server'),
  7020.                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7021.                 'url' => $this->generateUrl(
  7022.                     GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ProductPackage']]['entity_view_route_path_name']
  7023.                 )
  7024.             );
  7025.             System::setApprovalInfo(
  7026.                 $this->getDoctrine()->getManager(),
  7027.                 $options,
  7028.                 array_flip(GeneralConstant::$Entity_list)['ProductPackage'],
  7029.                 $pckgId,
  7030.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  7031.             );
  7032.             System::createEditSignatureHash(
  7033.                 $this->getDoctrine()->getManager(),
  7034.                 array_flip(GeneralConstant::$Entity_list)['ProductPackage'],
  7035.                 $pckgId,
  7036.                 $loginId,
  7037.                 $approveRole,
  7038.                 $request->request->get('approvalHash')
  7039.             );
  7040.             $this->addFlash(
  7041.                 'success',
  7042.                 'New Package Added.'
  7043.             );
  7044.         }
  7045.         return $this->render(
  7046.             '@Sales/pages/input_forms/create_package.html.twig',
  7047.             array(
  7048.                 'page_title' => 'Add Package',
  7049.                 'product_list' => Inventory::ProductListArray($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  7050.                 'product_list_obj' => Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request))
  7051.             )
  7052.         );
  7053.     }
  7054.     public function mrpOld(Request $request$id 0)
  7055.     {
  7056.         if ($request->isMethod('POST')) {
  7057.             $em $this->getDoctrine()->getManager();
  7058.             if (isset($_POST['products'])) {
  7059.                 $Products = array(
  7060.                     'products' => $_POST['products'],
  7061.                     'product_units' => $_POST['product_units'],
  7062.                     'product_unit_price' => $_POST['product_unit_price'],
  7063.                     'product_total_price' => $_POST['product_total_price'],
  7064.                     'product_reference_price' => $_POST['product_reference_price']
  7065.                 );
  7066.             } else {
  7067.                 $Products = array();
  7068.             }
  7069.             if (isset($_POST['services'])) {
  7070.                 $Services = array(
  7071.                     'services' => $_POST['services'],
  7072.                     'services_units' => $_POST['services_units'],
  7073.                     'services_unit_price' => $_POST['services_unit_price'],
  7074.                     'services_total_price' => $_POST['services_total_price'],
  7075.                     'services_reference_price' => $_POST['services_reference_price']
  7076.                 );
  7077.             } else {
  7078.                 $Services = array();
  7079.             }
  7080.             if (isset($_POST['heads'])) {
  7081.                 $ArCosts = array(
  7082.                     'heads' => $_POST['heads'],
  7083.                     'ar_units' => $_POST['ar_units'],
  7084.                     'ar_unit_price' => $_POST['ar_unit_price'],
  7085.                     'ar_total_price' => $_POST['ar_total_price'],
  7086.                     'ar_reference_price' => $_POST['ar_reference_price']
  7087.                 );
  7088.             } else {
  7089.                 $ArCosts = array();
  7090.             }
  7091.             $mrpId Package::CreateProductMrpDocument(
  7092.                 $em,
  7093.                 $id,
  7094.                 $request->request->get('product'),
  7095.                 $request->request->get('salesWarrenty'),
  7096.                 $request->request->get('note'),
  7097.                 $request->request->get('product_total_price'),
  7098.                 json_encode(
  7099.                     $Services
  7100.                 ),
  7101.                 json_encode(
  7102.                     $ArCosts
  7103.                 ),
  7104.                 $request->request->get('markupPercentage'),
  7105.                 $request->request->get('totalCost'),
  7106.                 $request->request->get('totalStoreCost'),
  7107.                 $request->request->get('totalNonStoreCost'),
  7108.                 $request->request->get('salesValue'),
  7109.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7110.                 $this->getLoggedUserCompanyId($request)
  7111.             );
  7112.             //now add Approval info
  7113.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7114.             $approveRole 1;  //created
  7115.             $options = array(
  7116.                 'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7117.                 'notification_server' => $this->container->getParameter('notification_server'),
  7118.                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7119.                 'url' => $this->generateUrl(
  7120.                     GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument']]['entity_view_route_path_name']
  7121.                 )
  7122.             );
  7123.             System::setApprovalInfo(
  7124.                 $this->getDoctrine()->getManager(),
  7125.                 $options,
  7126.                 array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
  7127.                 $mrpId,
  7128.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  7129.             );
  7130.             System::createEditSignatureHash(
  7131.                 $this->getDoctrine()->getManager(),
  7132.                 array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
  7133.                 $mrpId,
  7134.                 $loginId,
  7135.                 $approveRole,
  7136.                 $request->request->get('approvalHash')
  7137.             );
  7138.             $this->addFlash(
  7139.                 'success',
  7140.                 'New Package Added.'
  7141.             );
  7142.         }
  7143.         return $this->render(
  7144.             '@Sales/pages/input_forms/create_product_mrp.html.twig',
  7145.             array(
  7146.                 'page_title' => 'Product Mrp',
  7147.                 'product_list' => Inventory::ProductListArray($this->getDoctrine()->getManager()),
  7148.                 'product_list_obj' => Inventory::ProductList($this->getDoctrine()->getManager())
  7149.             )
  7150.         );
  7151.         //        return $this->render('@Sales/pages/input_forms/create_product_mrp.html.twig',
  7152.         //            array(
  7153.         //                'page_title'=>'Product Mrp',
  7154.         //                'product_list'=>Inventory::ProductListArray($this->getDoctrine()->getManager()),
  7155.         //                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager())
  7156.         //
  7157.         //            )
  7158.         //        );
  7159.     }
  7160.     public function GetPackageDetails(Request $request$id)
  7161.     {
  7162.         $em $this->getDoctrine()->getManager();
  7163.         $package_id $id;
  7164.         $details $em->getRepository('ApplicationBundle:ProductPackage')->findOneBy(array(
  7165.             'packageId' => $package_id
  7166.         ));
  7167.         $products json_decode($details->getProducts(), true);
  7168.         $cnt = array();
  7169.         for ($x 0$x count($products["products"]); $x++) {
  7170.             $cnt[] = array(
  7171.                 "id" => ($x 1),
  7172.                 "productID" => $products["products"][$x],
  7173.                 "product_units" => $products["product_units"][$x],
  7174.                 "product_unit_price" => $products["product_unit_price"][$x],
  7175.                 "product_sales_multiplier" => $details->getSalesMultiplier(),
  7176.                 "package_unit_price" => $details->getTotalPrice(),
  7177.                 "warranty" => $details->getSalesWarrantyMonths()
  7178.             );
  7179.         }
  7180.         return new JsonResponse(
  7181.             array(
  7182.                 "success" => true,
  7183.                 "content" => $cnt,
  7184.                 "package_data" => array(
  7185.                     "package_unit_price" => $details->getTotalPrice(),
  7186.                     "package_warranty" => $details->getSalesWarrantyMonths()
  7187.                 )
  7188.             )
  7189.         );
  7190.     }
  7191.     public function ClientList(Request $request)
  7192.     {
  7193.         $em $this->getDoctrine()->getManager();
  7194.         $allowed_ids = [];
  7195.         $companyId $this->getLoggedUserCompanyId($request);
  7196.         $listData SalesOrderM::GetClientListForClientList($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  7197.         if ($request->isMethod('POST')) {
  7198.             if ($request->query->has('dataTableQry')) {
  7199.                 return new JsonResponse(
  7200.                     $listData
  7201.                 );
  7202.             }
  7203.         }
  7204.         return $this->render(
  7205.             '@Sales/pages/list/client_list.html.twig',
  7206.             //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  7207.             array(
  7208.                 'page_title' => 'Client List',
  7209.                 'data' => SalesOrderM::GetClientList($em, [], $companyId),
  7210.                 'client_types' => Client::GetClientType($em$companyId),
  7211.                 'region_list' => Client::RegionList($em$companyId),
  7212.                 'geographical_region_list' => Client::GeographicalRegionList($em$companyId)
  7213.             )
  7214.         );
  7215.     }
  7216.     public function GetAllBranch()
  7217.     {
  7218.         $em $this->getDoctrine()->getManager();
  7219.         $query $em->createQuery('SELECT 
  7220.             b.branchId,b.name,b.address,b.warehouseId, b.type
  7221.             FROM ApplicationBundle:Branch b');
  7222.         $result $query->getArrayResult();
  7223.         return new JsonResponse([
  7224.             "branchList" => $result,
  7225.         ]);
  7226.     }
  7227.     public function ValidateCartForSalesOrder(Request $request)
  7228.     {
  7229.         $data json_decode($request->getContent(), true);
  7230.         $em $this->getDoctrine()->getManager();
  7231.         $cartItems $data['data'];
  7232.         $invalidItems = [];
  7233.         foreach ($cartItems as $item) {
  7234.             $productId $item['id'] ?? null;
  7235.             $inputPrice $item['curr_purchase_price'] ?? null;
  7236.             $inputQty $item['qty'] ?? null;
  7237.             if (!$productId) {
  7238.                 $invalidItems[] = ['error' => 'Missing product ID''item' => $item];
  7239.                 continue;
  7240.             }
  7241.             $product $em->getRepository('ApplicationBundle:InvProducts')->find($productId);
  7242.             if (!$product) {
  7243.                 $invalidItems[] = ['error' => 'Product not found''id' => $productId];
  7244.                 continue;
  7245.             }
  7246.             $dbPrice $product->getPurchasePrice();
  7247.             if ($inputPrice !== null && (float)$inputPrice != (float)$dbPrice) {
  7248.                 $invalidItems[] = [
  7249.                     'error' => 'Price mismatch',
  7250.                     'id' => $productId,
  7251.                     'input_price' => $inputPrice,
  7252.                     'current_price' => $dbPrice
  7253.                 ];
  7254.             }
  7255.             $dbQty $product->getQty();
  7256.             if ($inputQty !== null && $dbQty < (int)$inputQty) {
  7257.                 $invalidItems[] = [
  7258.                     'error' => 'Insufficient quantity',
  7259.                     'id' => $productId,
  7260.                     'requested_qty' => $inputQty,
  7261.                     'available_qty' => $dbQty
  7262.                 ];
  7263.             }
  7264.         }
  7265.         if (!empty($invalidItems)) {
  7266.             return new JsonResponse([
  7267.                 'success' => false,
  7268.                 'message' => 'Validation failed',
  7269.                 'issues' => $invalidItems
  7270.             ], 422);
  7271.         }
  7272.         return new JsonResponse(['success' => true'message' => 'Cart is valid']);
  7273.     }
  7274.     public function CreateSalesOrder(Request $request)
  7275.     {
  7276.     }
  7277.     public function ClientListData(Request $request)
  7278.     {
  7279.         $em $this->getDoctrine()->getManager();
  7280.         $query $em->createQuery('
  7281.         SELECT 
  7282.             c.clientId AS client_id,
  7283.             c.clientName AS client_name,
  7284.             c.contactPersonName AS contact_person_name,
  7285.             c.addressContact AS address_contact,
  7286.             c.contactNumber AS contact_number,
  7287.             c.image,
  7288.             c.email,
  7289.             c.creditLimit As credit_limit,
  7290.             c.shippingAddress AS shipping_address,
  7291.             c.billingAddress AS billing_address,
  7292.             c.clientDue AS client_due,
  7293.             c.clientLevel AS client_level,
  7294.             c.parentId AS parent_id,
  7295.             c.type AS client_type,
  7296.             c.regionId AS region_id,
  7297.             c.salesPersonId AS sales_person_id,
  7298.             c.clientOwnBalanceAmount AS client_own_balance,
  7299.             c.clientOwnDueAmount AS client_own_due,
  7300.             c.clientOwnSalesAmount AS client_own_sales,
  7301.             c.clientOwnReceivedAmount AS client_own_received,
  7302.             c.status,
  7303.             c.createdAt AS created_at,
  7304.             c.CompanyId AS company_id
  7305.         FROM ApplicationBundle:AccClients c
  7306.     ');
  7307.         $result $query->getArrayResult();
  7308.         return new JsonResponse([
  7309.             "client_list" => $result,
  7310.         ]);
  7311.     }
  7312.     public function PrintClientProfile(Request $request$id$idtype)
  7313.     {
  7314.         $em $this->getDoctrine()->getManager();
  7315.         if ($id == 0) {
  7316.             $id $idtype;
  7317.             $idtype "CI";
  7318.         }
  7319.         $companyId $this->getLoggedUserCompanyId($request);
  7320.         $balance_view_method 0;
  7321.         $onlyLedgerFlag 0;
  7322.         if ($request->query->has('onlyLedgerFlag'))
  7323.             $onlyLedgerFlag $request->query->get('onlyLedgerFlag');
  7324.         $bal_set $em
  7325.             ->getRepository('ApplicationBundle:AccSettings')
  7326.             ->findOneBy(
  7327.                 array(
  7328.                     'name' => 'ledger_balance_display_method',
  7329.                 )
  7330.             );
  7331.         if ($bal_set) {
  7332.             $balance_view_method $bal_set->getdata();
  7333.         }
  7334.         $start_date '';
  7335.         $end_date '';
  7336.         if ($request->query->has('start_date'))
  7337.             $start_date $request->query->get('start_date');
  7338.         if ($request->query->has('end_date'))
  7339.             $end_date $request->query->get('end_date');
  7340.         $CD Client::GetClientProfileDetails($em$id$idtype$start_date$end_date);
  7341.         $company_data Company::getCompanyData($em$companyId);
  7342.         $document_mark = array(
  7343.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7344.             'copy' => ''
  7345.         );
  7346.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  7347.             $html $this->renderView(
  7348.                 '@Sales/pages/print/client_profile_print.html.twig',
  7349.                 array(
  7350.                     //full array here
  7351.                     'pdf' => true,
  7352.                     'page_title' => $CD['info']['client_name'],
  7353.                     'export' => 'pdf,print',
  7354.                     'data' => $CD,
  7355.                     'start_date' => $start_date,
  7356.                     'end_date' => $end_date,
  7357.                     'provisional' => 1,
  7358.                     'entityList' => GeneralConstant::$Entity_list_details,
  7359.                     'onlyLedgerFlag' => $onlyLedgerFlag,
  7360.                     'balance_view_method' => $balance_view_method,
  7361.                     'document_mark_image' => $document_mark['original'],
  7362.                     'document_type' => 'Client Ledger',
  7363.                     'company_name' => $company_data->getName(),
  7364.                     'company_data' => $company_data,
  7365.                     'company_address' => $company_data->getAddress(),
  7366.                     'company_image' => $company_data->getImage(),
  7367.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  7368.                     'red' => 0,
  7369.                     //                    'sales_person_list'=>Client::SalesPersonList($this->getDoctrine()->getManager()),
  7370.                 )
  7371.             );
  7372.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  7373.                 //                'orientation' => 'landscape',
  7374.                 //                'enable-javascript' => true,
  7375.                 //                'javascript-delay' => 1000,
  7376.                 'no-stop-slow-scripts' => false,
  7377.                 'no-background' => false,
  7378.                 'lowquality' => false,
  7379.                 'encoding' => 'utf-8',
  7380.                 //            'images' => true,
  7381.                 //            'cookie' => array(),
  7382.                 'dpi' => 300,
  7383.                 'image-dpi' => 300,
  7384.                 //                'enable-external-links' => true,
  7385.                 //                'enable-internal-links' => true
  7386.             ));
  7387.             return new Response(
  7388.                 $pdf_response,
  7389.                 200,
  7390.                 array(
  7391.                     'Content-Type' => 'application/pdf',
  7392.                     'Content-Disposition' => 'attachment; filename="' $CD['info']['client_name'] . '_' 'ledger.pdf"'
  7393.                 )
  7394.             );
  7395.         }
  7396.         return $this->render(
  7397.             '@Sales/pages/print/client_profile_print.html.twig',
  7398.             array(
  7399.                 'page_title' => 'Client Profile',
  7400.                 'data' => $CD,
  7401.                 'export' => 'pdf,print',
  7402.                 'entityList' => GeneralConstant::$Entity_list_details,
  7403.                 'onlyLedgerFlag' => $onlyLedgerFlag,
  7404.                 'start_date' => $start_date,
  7405.                 'end_date' => $end_date,
  7406.                 'provisional' => 1,
  7407.                 'balance_view_method' => $balance_view_method,
  7408.             )
  7409.         );
  7410.     }
  7411.     public function ClientProfile(Request $request$id$idtype)
  7412.     {
  7413.         $em $this->getDoctrine()->getManager();
  7414.         if ($id == 0) {
  7415.             $id $idtype;
  7416.             $idtype "CI";
  7417.         }
  7418.         $companyId $this->getLoggedUserCompanyId($request);
  7419.         $balance_view_method 0;
  7420.         $bal_set $em
  7421.             ->getRepository('ApplicationBundle:AccSettings')
  7422.             ->findOneBy(
  7423.                 array(
  7424.                     'name' => 'ledger_balance_display_method',
  7425.                 )
  7426.             );
  7427.         if ($bal_set) {
  7428.             $balance_view_method $bal_set->getdata();
  7429.         }
  7430.         $start_date '';
  7431.         $end_date '';
  7432.         if ($request->query->has('start_date'))
  7433.             $start_date $request->query->get('start_date');
  7434.         if ($request->query->has('end_date'))
  7435.             $end_date $request->query->get('end_date');
  7436.         $CD Client::GetClientProfileDetails($em$id$idtype$start_date$end_date);
  7437.         $company_data Company::getCompanyData($em$companyId);
  7438.         $document_mark = array(
  7439.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7440.             'copy' => ''
  7441.         );
  7442.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  7443.             $html $this->renderView(
  7444.                 '@Sales/pages/print/client_profile_print.html.twig',
  7445.                 array(
  7446.                     //full array here
  7447.                     'pdf' => true,
  7448.                     'page_title' => $CD['info']['client_name'],
  7449.                     'export' => 'pdf,print',
  7450.                     'data' => $CD,
  7451.                     'entityList' => GeneralConstant::$Entity_list_details,
  7452.                     'start_date' => $start_date,
  7453.                     'end_date' => $end_date,
  7454.                     'provisional' => 1,
  7455.                     'balance_view_method' => $balance_view_method,
  7456.                     'document_mark_image' => $document_mark['original'],
  7457.                     'document_type' => 'Client Ledger',
  7458.                     'company_name' => $company_data->getName(),
  7459.                     'company_data' => $company_data,
  7460.                     'company_address' => $company_data->getAddress(),
  7461.                     'company_image' => $company_data->getImage(),
  7462.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  7463.                     'red' => 0,
  7464.                     //                    'sales_person_list'=>Client::SalesPersonList($this->getDoctrine()->getManager()),
  7465.                 )
  7466.             );
  7467.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  7468.                 //                'orientation' => 'landscape',
  7469.                 //                'enable-javascript' => true,
  7470.                 //                'javascript-delay' => 1000,
  7471.                 'no-stop-slow-scripts' => false,
  7472.                 'no-background' => false,
  7473.                 'lowquality' => false,
  7474.                 'encoding' => 'utf-8',
  7475.                 //            'images' => true,
  7476.                 //            'cookie' => array(),
  7477.                 'dpi' => 300,
  7478.                 'image-dpi' => 300,
  7479.                 //                'enable-external-links' => true,
  7480.                 //                'enable-internal-links' => true
  7481.             ));
  7482.             return new Response(
  7483.                 $pdf_response,
  7484.                 200,
  7485.                 array(
  7486.                     'Content-Type' => 'application/pdf',
  7487.                     'Content-Disposition' => 'attachment; filename="' $CD['info']['client_name'] . '_' 'ledger.pdf"'
  7488.                 )
  7489.             );
  7490.         }
  7491.         return $this->render(
  7492.             '@Sales/pages/report/client_profile.html.twig',
  7493.             array(
  7494.                 'page_title' => 'Client Profile',
  7495.                 'data' => $CD,
  7496.                 'entityList' => GeneralConstant::$Entity_list_details,
  7497.                 'start_date' => $start_date,
  7498.                 'end_date' => $end_date,
  7499.                 'provisional' => 1,
  7500.                 'balance_view_method' => $balance_view_method,
  7501.             )
  7502.         );
  7503.     }
  7504.     public function ViewClientLedger(Request $request$id$idtype)
  7505.     {
  7506.         $em $this->getDoctrine()->getManager();
  7507.         $companyId $this->getLoggedUserCompanyId($request);
  7508.         if ($id == 0) {
  7509.             $id $idtype;
  7510.             $idtype "CI";
  7511.         }
  7512.         if ($id == 'CI') {
  7513.             $idtype "CI";
  7514.             $id 0;
  7515.         }
  7516.         $clientIdList = [];
  7517.         $clientTypeIdList = [];
  7518.         $reportTypeId 'by_client';
  7519.         $outputType 'view';
  7520.         if ($request->query->has('reportTypeId'))
  7521.             $reportTypeId $request->query->get('reportTypeId');
  7522.         if ($request->query->has('outputType'))
  7523.             $outputType $request->query->get('outputType');
  7524.         if ($request->query->has('pdf'))
  7525.             $outputType 'pdf';
  7526.         if ($reportTypeId == 'by_client') {
  7527.             if ($request->query->has('clientId'))
  7528.                 $clientIdList $request->query->get('clientId');
  7529.         } else if ($reportTypeId == 'by_client_type') {
  7530.             if ($request->query->has('clientTypeId'))
  7531.                 $clientTypeIdList $request->query->get('clientTypeId');
  7532.             $clients $em
  7533.                 ->getRepository('ApplicationBundle:AccClients')
  7534.                 ->findBy(
  7535.                     array(
  7536.                         'type' => $clientTypeIdList,
  7537.                         'CompanyId' => $companyId,
  7538.                     )
  7539.                 );
  7540.             foreach ($clients as $client) {
  7541.                 $clientIdList[] = $client->getClientId();
  7542.             }
  7543.         }
  7544.         $balance_view_method 0;
  7545.         $bal_set $em
  7546.             ->getRepository('ApplicationBundle:AccSettings')
  7547.             ->findOneBy(
  7548.                 array(
  7549.                     'name' => 'ledger_balance_display_method',
  7550.                 )
  7551.             );
  7552.         if ($bal_set) {
  7553.             $balance_view_method $bal_set->getdata();
  7554.         }
  7555.         $start_date '';
  7556.         $end_date '';
  7557.         if ($request->query->has('start_date'))
  7558.             $start_date $request->query->get('start_date');
  7559.         if ($request->query->has('end_date'))
  7560.             $end_date $request->query->get('end_date');
  7561.         $CD = [];
  7562.         $clientDataArray = [];
  7563.         //        if($id!=0)
  7564.         foreach ($clientIdList as $clientId) {
  7565.             $CD Client::GetClientProfileDetails($em$clientId$idtype$start_date$end_date);
  7566.             $clientDataArray[] = $CD;
  7567.         }
  7568.         $company_data Company::getCompanyData($em$companyId);
  7569.         $document_mark = array(
  7570.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  7571.             'copy' => ''
  7572.         );
  7573.         if ($outputType == 'pdf') {
  7574.             $html $this->renderView(
  7575.                 '@Sales/pages/print/client_ledger_print.html.twig',
  7576.                 array(
  7577.                     //full array here
  7578.                     'pdf' => true,
  7579.                     'page_title' => 'Customer Ledger',
  7580.                     'export' => 'pdf,print',
  7581.                     'data' => $CD,
  7582.                     'entityList' => GeneralConstant::$Entity_list_details,
  7583.                     'start_date' => $start_date,
  7584.                     'end_date' => $end_date,
  7585.                     'provisional' => 1,
  7586.                     'outputType' => $outputType,
  7587.                     'clientIdList' => $clientIdList,
  7588.                     'clientTypeIdList' => $clientTypeIdList,
  7589.                     'reportTypeId' => $reportTypeId,
  7590.                     'clientDataArray' => $clientDataArray,
  7591.                     'balance_view_method' => $balance_view_method,
  7592.                     'document_mark_image' => $document_mark['original'],
  7593.                     'document_type' => 'Client Ledger',
  7594.                     'company_name' => $company_data->getName(),
  7595.                     'company_data' => $company_data,
  7596.                     'company_address' => $company_data->getAddress(),
  7597.                     'company_image' => $company_data->getImage(),
  7598.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  7599.                     'red' => 0,
  7600.                     //                    'sales_person_list'=>Client::SalesPersonList($this->getDoctrine()->getManager()),
  7601.                 )
  7602.             );
  7603.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  7604.                 //                'orientation' => 'landscape',
  7605.                 //                'enable-javascript' => true,
  7606.                 //                'javascript-delay' => 1000,
  7607.                 'no-stop-slow-scripts' => false,
  7608.                 'no-background' => false,
  7609.                 'lowquality' => false,
  7610.                 'encoding' => 'utf-8',
  7611.                 //            'images' => true,
  7612.                 //            'cookie' => array(),
  7613.                 'dpi' => 300,
  7614.                 'image-dpi' => 300,
  7615.                 //                'enable-external-links' => true,
  7616.                 //                'enable-internal-links' => true
  7617.             ));
  7618.             return new Response(
  7619.                 $pdf_response,
  7620.                 200,
  7621.                 array(
  7622.                     'Content-Type' => 'application/pdf',
  7623.                     'Content-Disposition' => 'attachment; filename="' $CD['info']['client_name'] . '_' 'ledger.pdf"'
  7624.                 )
  7625.             );
  7626.         }
  7627.         if ($outputType == 'print') {
  7628.             return $this->render(
  7629.                 '@Sales/pages/print/client_ledger_print.html.twig',
  7630.                 array(
  7631.                     //full array here
  7632.                     'pdf' => true,
  7633.                     'page_title' => 'Customer Ledger',
  7634.                     'export' => 'pdf,print',
  7635.                     'data' => $CD,
  7636.                     'entityList' => GeneralConstant::$Entity_list_details,
  7637.                     'start_date' => $start_date,
  7638.                     'end_date' => $end_date,
  7639.                     'provisional' => 1,
  7640.                     'clientIdList' => $clientIdList,
  7641.                     'clientTypeIdList' => $clientTypeIdList,
  7642.                     'reportTypeId' => $reportTypeId,
  7643.                     'outputType' => $outputType,
  7644.                     'clientDataArray' => $clientDataArray,
  7645.                     'balance_view_method' => $balance_view_method,
  7646.                     'document_mark_image' => $document_mark['original'],
  7647.                     'document_type' => 'Client Ledger',
  7648.                     'company_name' => $company_data->getName(),
  7649.                     'company_data' => $company_data,
  7650.                     'company_address' => $company_data->getAddress(),
  7651.                     'company_image' => $company_data->getImage(),
  7652.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  7653.                     'red' => 0,
  7654.                     //                    'sales_person_list'=>Client::SalesPersonList($this->getDoctrine()->getManager()),
  7655.                 )
  7656.             );
  7657.         }
  7658.         return $this->render(
  7659.             '@Sales/pages/report/client_ledger.html.twig',
  7660.             array(
  7661.                 'page_title' => 'Customer ledger',
  7662.                 //                'data'=>$CD,
  7663.                 'clientId' => $id,
  7664.                 'entityList' => GeneralConstant::$Entity_list_details,
  7665.                 'clientIdList' => $clientIdList,
  7666.                 'clientTypeIdList' => $clientTypeIdList,
  7667.                 'reportTypeId' => $reportTypeId,
  7668.                 'outputType' => $outputType,
  7669.                 'clientDataArray' => $clientDataArray,
  7670.                 'clientList' => Client::GetExistingClientList($em$companyId, []),
  7671.                 'clientTypeList' => Client::GetClientType($em$companyId),
  7672.                 'start_date' => $start_date,
  7673.                 'end_date' => $end_date,
  7674.                 'provisional' => 1,
  7675.                 'balance_view_method' => $balance_view_method,
  7676.             )
  7677.         );
  7678.     }
  7679.     public function CreateDeliveryConfirmation(Request $request)
  7680.     {
  7681.         if ($request->isMethod('POST')) {
  7682.             $post $request->request;
  7683.             $path "";
  7684.             $file_path "";
  7685.             foreach ($request->files as $uploadedFile) {
  7686.                 //            if($uploadedFile->getImage())
  7687.                 //                var_dump($uploadedFile->getFile());
  7688.                 //                var_dump($uploadedFile);
  7689.                 if ($uploadedFile != null) {
  7690.                     $fileName md5(uniqid()) . '.' $uploadedFile->guessExtension();
  7691.                     $path $fileName;
  7692.                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
  7693.                     if (!file_exists($upl_dir)) {
  7694.                         mkdir($upl_dir0777true);
  7695.                     }
  7696.                     $file $uploadedFile->move($upl_dir$path);
  7697.                 }
  7698.             }
  7699.             if ($path != "")
  7700.                 $file_path 'uploads/FileUploads/' $path;
  7701.             $g_path $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' $path;
  7702.             //            $img_file = file_get_contents($g_path);
  7703.             //            $r=base64_encode($img_file);
  7704.             $confirmId SalesOrderM::CreateNewDeliveryConfirmation(
  7705.                 $this->getDoctrine()->getManager(),
  7706.                 $request->request,
  7707.                 $file_path,
  7708.                 Generic::simpleRandString(),
  7709.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7710.                 $this->getLoggedUserCompanyId($request)
  7711.             );
  7712.             //now add Approval info
  7713.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7714.             $approveRole 1;  //created
  7715.             $options = array(
  7716.                 'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7717.                 'notification_server' => $this->container->getParameter('notification_server'),
  7718.                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7719.                 'url' => $this->generateUrl(
  7720.                     GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryConfirmation']]['entity_view_route_path_name']
  7721.                 )
  7722.             );
  7723.             System::setApprovalInfo(
  7724.                 $this->getDoctrine()->getManager(),
  7725.                 $options,
  7726.                 array_flip(GeneralConstant::$Entity_list)['DeliveryConfirmation'],
  7727.                 $confirmId,
  7728.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  7729.             );
  7730.             System::createEditSignatureHash(
  7731.                 $this->getDoctrine()->getManager(),
  7732.                 array_flip(GeneralConstant::$Entity_list)['DeliveryConfirmation'],
  7733.                 $confirmId,
  7734.                 $loginId,
  7735.                 $approveRole,
  7736.                 $request->request->get('approvalHash')
  7737.             );
  7738.             $this->addFlash(
  7739.                 'success',
  7740.                 'New Delivery Confrmation Created'
  7741.             );
  7742.             $url $this->generateUrl(
  7743.                 'view_delivery_confirmation'
  7744.             );
  7745.             return $this->redirect($url "/" $confirmId);
  7746.         }
  7747.         return $this->render(
  7748.             '@Sales/pages/input_forms/delivery_confirmation.html.twig',
  7749.             array(
  7750.                 'page_title' => 'Delivery Confirmation',
  7751.                 'deliveryReceipts' => $this->getDoctrine()->getManager()->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(array(
  7752.                     'approved' => GeneralConstant::APPROVED,
  7753.                     'deliveryStatus' => GeneralConstant::APPROVAL_STATUS_PENDING
  7754.                 ))
  7755.             )
  7756.         );
  7757.     }
  7758.     public function CreateDeliveryOrder(Request $request)
  7759.     {
  7760.         $companyId $this->getLoggedUserCompanyId($request);
  7761.         if ($request->isMethod('POST')) {
  7762.             $orderId SalesOrderM::CreateNewDeliveryOrder(
  7763.                 $this->getDoctrine()->getManager(),
  7764.                 $request->request,
  7765.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  7766.                 $this->getLoggedUserCompanyId($request)
  7767.             );
  7768.             //now add Approval info
  7769.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  7770.             $approveRole 1;  //created
  7771.             $options = array(
  7772.                 'notification_enabled' => $this->container->getParameter('notification_enabled'),
  7773.                 'notification_server' => $this->container->getParameter('notification_server'),
  7774.                 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  7775.                 'url' => $this->generateUrl(
  7776.                     GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryOrder']]['entity_view_route_path_name']
  7777.                 )
  7778.             );
  7779.             System::setApprovalInfo(
  7780.                 $this->getDoctrine()->getManager(),
  7781.                 $options,
  7782.                 array_flip(GeneralConstant::$Entity_list)['DeliveryOrder'],
  7783.                 $orderId,
  7784.                 $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  7785.             );
  7786.             System::createEditSignatureHash(
  7787.                 $this->getDoctrine()->getManager(),
  7788.                 array_flip(GeneralConstant::$Entity_list)['DeliveryOrder'],
  7789.                 $orderId,
  7790.                 $loginId,
  7791.                 $approveRole,
  7792.                 $request->request->get('approvalHash')
  7793.             );
  7794.             $this->addFlash(
  7795.                 'success',
  7796.                 'New Delivery order Created'
  7797.             );
  7798.             $url $this->generateUrl(
  7799.                 'view_delivery_order'
  7800.             );
  7801.             return $this->redirect($url "/" $orderId);
  7802.         }
  7803.         return $this->render(
  7804.             '@Sales/pages/input_forms/delivery_order.html.twig',
  7805.             array(
  7806.                 'page_title' => 'New Delivery Order',
  7807.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  7808.                 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
  7809.                 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
  7810.                 'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  7811.                 'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager(), $companyId, ['deliveryOrderSkipFlag' => [0null]]),
  7812.                 'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager(), $companyId, ['deliveryOrderSkipFlag' => [0null]]),
  7813.             )
  7814.         );
  7815.     }
  7816.     public function GetItemListForDo(Request $request)
  7817.     {
  7818.         if ($request->isMethod('POST')) {
  7819.             $em $this->getDoctrine();
  7820.             $find_array = array( //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  7821.             );
  7822.             $Content = [];
  7823.             $Transport_data = [];
  7824.             $Lul_data = [];
  7825.             if ($request->request->get('soId') != '')
  7826.                 $find_array['salesOrderId'] = $request->request->get('soId');
  7827.             //            if($request->request->get('warehouseId')!='')
  7828.             //                $find_array['warehouseId']=$request->request->get('warehouseId');
  7829.             $QD $this->getDoctrine()
  7830.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  7831.                 ->findBy(
  7832.                     $find_array,
  7833.                     array()
  7834.                 );
  7835.             $SO $this->getDoctrine()
  7836.                 ->getRepository('ApplicationBundle:SalesOrder')
  7837.                 ->findOneBy(
  7838.                     $find_array,
  7839.                     array()
  7840.                 );
  7841.             $sendData = array(
  7842.                 'salesType' => $SO->getSalesType(),
  7843.                 'packageData' => [],
  7844.                 'productList' => [],
  7845.                 'productListByPackage' => [],
  7846.             );
  7847.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  7848.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  7849.             $pckg_item_cross_match_data = [];
  7850.             if ($SO->getSalesType() == 1//package
  7851.             {
  7852.                 //now package data
  7853.                 $package_data json_decode($SO->getPackageData(), true);
  7854.                 foreach ($package_data as $pkg) {
  7855.                     $pckg $pkg['info'];
  7856.                     $pckg_nec_data = array(
  7857.                         'packageId' => $pckg['packageId'],
  7858.                         'packageName' => $pckg['packageName'],
  7859.                         'packageUnits' => $pckg['packageUnits'],
  7860.                         'packageDelivered' => (isset($pckg['packageDelivered'])) ? $pckg['packageDelivered'] : 0,
  7861.                         'packageBalance' => (isset($pckg['packageBalance'])) ? $pckg['packageBalance'] : $pckg['packageUnits'],
  7862.                         'defaultUnit' => 1
  7863.                     );
  7864.                     $sendData['packageData'][] = $pckg_nec_data;
  7865.                     $details $em->getRepository('ApplicationBundle:ProductPackage')->findOneBy(array(
  7866.                         'packageId' => $pckg['packageId']
  7867.                     ));
  7868.                     $pck_prods json_decode($details->getProducts(), true);
  7869.                     $cnt = array();
  7870.                     for ($x 0$x count($pck_prods["products"]); $x++) {
  7871.                         $pckg_item_cross_match_data[$pckg['packageId']][$pck_prods["products"][$x]] = array(
  7872.                             "product_units" => $pck_prods["product_units"][$x],
  7873.                         );
  7874.                     }
  7875.                 }
  7876.                 foreach ($QD as $product) {
  7877.                     $p_data = array(
  7878.                         'details_id' => $product->getId(),
  7879.                         'productId' => $product->getProductId(),
  7880.                         'productFdm' => $product->getProductFdm(),
  7881.                         'product_name' => $productList[$product->getProductId()]['name'],
  7882.                         'package_id' => $product->getPackageId(),
  7883.                         'qty' => $product->getQty(),
  7884.                         'delivered' => $product->getDelivered(),
  7885.                         'balance' => $product->getBalance(),
  7886.                         //                        'unit_package_multiplier'=>1,
  7887.                         'unit_package_multiplier' => $pckg_item_cross_match_data[$product->getPackageId()][$product->getProductId()]['product_units'],
  7888.                         //                        'delivered'=>$product->getDelivered(),
  7889.                     );
  7890.                     $sendData['productList'][] = $p_data;
  7891.                     $sendData['productListByPackage'][$product->getPackageId()][] = $p_data;
  7892.                 }
  7893.             }
  7894.             if ($SO->getSalesType() == || $SO->getSalesType() == 3//Spare
  7895.             {
  7896.                 foreach ($QD as $product) {
  7897.                     $soBalance $product->getQty();
  7898.                     //                $doBalance=$product->getBalance() - $product->getTransitQty();
  7899.                     //                $doBalance = $product->getBalance();
  7900.                     //                $doBalance = 0;
  7901.                     //now check if any so ir do item id there that is at
  7902.                     //least pending
  7903.                     $approvalPendingDos $this->getDoctrine()
  7904.                         ->getRepository('ApplicationBundle:DeliveryOrder')
  7905.                         ->findBy(
  7906.                             array(
  7907.                                 'salesOrderId' => $SO->getSalesOrderId(),
  7908.                                 'approved' => [GeneralConstant::APPROVAL_STATUS_PENDINGGeneralConstant::APPROVED]
  7909.                             )
  7910.                         );
  7911.                     foreach ($approvalPendingDos as $appPendDo) {
  7912.                         $appPendDrItem $this->getDoctrine()
  7913.                             ->getRepository('ApplicationBundle:DeliveryOrderItem')
  7914.                             ->findOneBy(
  7915.                                 array(
  7916.                                     'deliveryOrderId' => $appPendDo->getDeliveryOrderId(),
  7917.                                     'salesorderItemId' => $product->getId()
  7918.                                 )
  7919.                             );
  7920.                         if ($appPendDrItem) {
  7921.                             $soBalance $soBalance $appPendDrItem->getQty();
  7922.                             //                        $doBalance=$doBalance-$appPendDrItem->getQty();
  7923.                         }
  7924.                     }
  7925.                     $p_data = array(
  7926.                         'details_id' => $product->getId(),
  7927.                         'productId' => $product->getProductId(),
  7928.                         'productFdm' => $product->getProductFdm(),
  7929.                         'service_id' => $product->getServiceId(),
  7930.                         'type' => $product->getType(),
  7931.                         //                        'product_name'=>$product->getType()==1?$productList[$product->getProductId()]['name']:'',
  7932.                         'product_name' => ($product->getType() == 1) ?
  7933.                             (isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : $product->getProductNameFdm()) : '',
  7934.                         'service_name' => $product->getType() == $serviceList[$product->getServiceId()]['name'] : '',
  7935.                         'package_id' => $product->getPackageId(),
  7936.                         'qty' => $product->getQty(),
  7937.                         //                        'delivered' => $product->getDelivered(),
  7938.                         'delivered' => $soBalance,
  7939.                         'balance' => $soBalance,
  7940.                         //                        'delivered'=>$product->getDelivered(),
  7941.                     );
  7942.                     $sendData['productList'][] = $p_data;
  7943.                 }
  7944.                 //now package data
  7945.             }
  7946.             if ($sendData) {
  7947.                 return new JsonResponse(array("success" => true"content" => $sendData));
  7948.             }
  7949.             return new JsonResponse(array("success" => false));
  7950.         }
  7951.         return new JsonResponse(array("success" => false));
  7952.     }
  7953.     public function CheckCreditLimitValidityForDr(Request $request)
  7954.     {
  7955.         $allowed 0;
  7956.         if ($request->isMethod('POST')) {
  7957.             $id $request->request->has('soId') ? $request->request->get('soId') : 0;
  7958.             $drData $request->request->has('drData') ? $request->request->get('drData') : [];
  7959.             //            $drData=[
  7960.             //                ['soItemId'=>9,'qty'=>9],
  7961.             //                ['soItemId'=>9,'qty'=>9],
  7962.             //                ['soItemId'=>9,'qty'=>9],
  7963.             //            ];
  7964.             //data will be by soItemId
  7965.             $em $this->getDoctrine();
  7966.             $toGetSoItemsId = [];
  7967.             $toGetDoItemsId = [];
  7968.             $drDataBySoItemId = [];
  7969.             $drDataByDoItemId = [];
  7970.             $so $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(array(
  7971.                 'salesOrderId' => $id   //$id is soId
  7972.             ));
  7973.             if ($so->getDeliveryOrderSkipFlag() == 1) {
  7974.                 foreach ($drData as $pp) {
  7975.                     $toGetSoItemsId[] = $pp['soItemId'];
  7976.                     $drDataBySoItemId[$pp['soItemId']] = $pp;
  7977.                 }
  7978.             } else {
  7979.                 foreach ($drData as $pp) {
  7980.                     $toGetDoItemsId[] = $pp['soItemId'];
  7981.                     $drDataByDoItemId[$pp['soItemId']] = $pp;
  7982.                 }
  7983.                 $do_item_data $em->getRepository('ApplicationBundle:DeliveryOrderItem')->findBy(
  7984.                     array(
  7985.                         'salesorderId' => $id,
  7986.                         'id' => $toGetDoItemsId
  7987.                     )
  7988.                 );
  7989.                 foreach ($do_item_data as $dd) {
  7990.                     $toGetSoItemsId[] = $dd->getSalesorderItemId();
  7991.                     $drDataBySoItemId[$dd->getSalesorderItemId()] = $drDataByDoItemId[$dd->getId()];
  7992.                 }
  7993.                 //                $do_item_data = $em->getRepository('ApplicationBundle:SalesOrderItem')->findOneBy(
  7994.                 //                    array(
  7995.                 ////                'salesOrderId'=>$post_data->get('soId', null),
  7996.                 //                        'id' => $post_data->get('do_details_id')[$key]
  7997.                 //                    )
  7998.                 //                );
  7999.             }
  8000.             $so_item_data $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy(
  8001.                 array(
  8002.                     'salesOrderId' => $id,
  8003.                     'id' => $toGetSoItemsId
  8004.                 )
  8005.             );
  8006.             $prev_so_amount $so->getSoAmount();
  8007.             $total_discounted_amount 0;
  8008.             $total_product_amount 0;
  8009.             $total_discount 0;
  8010.             $total_special_discount $so->getSpecialDiscountAmount();
  8011.             $total_special_discount_rate $so->getSpecialDiscountRate();
  8012.             foreach ($so_item_data as $item) {
  8013.                 $qty $drDataBySoItemId[$item->getId()]['qty'];
  8014.                 $price $item->getPrice();
  8015.                 $amount $qty $price;
  8016.                 $discountAmount $amount * ($item->getDiscountRate() / 100);
  8017.                 $discountedAmount $amount $discountAmount;
  8018.                 $total_discounted_amount += $discountedAmount;
  8019.                 $total_discount += $discountAmount;
  8020.                 $total_product_amount += $amount;
  8021.             }
  8022.             $aitRate $so->getAitRate();
  8023.             $vatRate $so->getVatRate();
  8024.             if ($aitRate == '' || $aitRate == null$aitRate 0;
  8025.             if ($vatRate == '' || $vatRate == null$vatRate 0;
  8026.             //        $so->setVatRate($post->get('vat_rate', null));
  8027.             $vatAmount $total_discounted_amount * ($vatRate 100);
  8028.             $aitAmount $total_discounted_amount * ($aitRate 100);
  8029.             $total_sales_amount $total_discounted_amount $vatAmount $aitAmount $total_special_discount;
  8030.             //now get client
  8031.             $client $em->getRepository('ApplicationBundle:AccClients')->findOneBy(array(
  8032.                 'clientId' => $so->getClientId(),
  8033.             ));
  8034.             if ($client->getCreditLimitEnabled() != 1) {
  8035.                 $allowed 1;
  8036.             } else {
  8037.                 $creditLimit $client->getCreditLimit();
  8038.                 $freezeBalance $client->getFreezeBalance();
  8039.                 $due $client->getClientDue();
  8040.                 if (($creditLimit $freezeBalance) >= ($due $total_sales_amount))
  8041.                     $allowed 1;
  8042.             }
  8043.             //now package data
  8044.             return new JsonResponse(array("allowed" => $allowed));
  8045.         }
  8046.         return new JsonResponse(array("allowed" => $allowed));
  8047.     }
  8048.     public function GetSoDataForSoAmendment(Request $request)
  8049.     {
  8050.         if ($request->isMethod('POST')) {
  8051.             $em $this->getDoctrine();
  8052.             $find_array = array( //                'stage' =>  GeneralConstant::STAGE_PENDING_TAG
  8053.             );
  8054.             $Content = [];
  8055.             $Transport_data = [];
  8056.             $Lul_data = [];
  8057.             if ($request->request->get('soId') != '')
  8058.                 $find_array['salesOrderId'] = $request->request->get('soId');
  8059.             //            if($request->request->get('warehouseId')!='')
  8060.             //                $find_array['warehouseId']=$request->request->get('warehouseId');
  8061.             $QD $this->getDoctrine()
  8062.                 ->getRepository('ApplicationBundle:SalesOrderItem')
  8063.                 ->findBy(
  8064.                     $find_array,
  8065.                     array()
  8066.                 );
  8067.             $SO $this->getDoctrine()
  8068.                 ->getRepository('ApplicationBundle:SalesOrder')
  8069.                 ->findOneBy(
  8070.                     $find_array,
  8071.                     array()
  8072.                 );
  8073.             $sendData = array(
  8074.                 'salesType' => $SO->getSalesType(),
  8075.                 'packageData' => [],
  8076.                 'productList' => [],
  8077.                 'productListByPackage' => [],
  8078.                 'otherData' => [],
  8079.             );
  8080.             $productList Inventory::ProductList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  8081.             $serviceList Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
  8082.             $pckg_item_cross_match_data = [];
  8083.             if ($SO->getSalesType() == 1//package
  8084.             {
  8085.                 //now package data
  8086.                 $package_data json_decode($SO->getPackageData(), true);
  8087.                 foreach ($package_data as $pkg) {
  8088.                     $pckg $pkg['info'];
  8089.                     $pckg_nec_data = array(
  8090.                         'packageId' => $pckg['packageId'],
  8091.                         'packageName' => $pckg['packageName'],
  8092.                         'packageUnits' => $pckg['packageUnits'],
  8093.                         'packageDelivered' => (isset($pckg['packageDelivered'])) ? $pckg['packageDelivered'] : 0,
  8094.                         'packageBalance' => (isset($pckg['packageBalance'])) ? $pckg['packageBalance'] : $pckg['packageUnits'],
  8095.                         'defaultUnit' => 1
  8096.                     );
  8097.                     $sendData['packageData'][] = $pckg_nec_data;
  8098.                     $details $em->getRepository('ApplicationBundle:ProductPackage')->findOneBy(array(
  8099.                         'packageId' => $pckg['packageId']
  8100.                     ));
  8101.                     $pck_prods json_decode($details->getProducts(), true);
  8102.                     $cnt = array();
  8103.                     for ($x 0$x count($pck_prods["products"]); $x++) {
  8104.                         $pckg_item_cross_match_data[$pckg['packageId']][$pck_prods["products"][$x]] = array(
  8105.                             "product_units" => $pck_prods["product_units"][$x],
  8106.                         );
  8107.                     }
  8108.                 }
  8109.                 foreach ($QD as $product) {
  8110.                     $p_data = array(
  8111.                         'details_id' => $product->getId(),
  8112.                         'productId' => $product->getProductId(),
  8113.                         'productFdm' => $product->getProductFdm(),
  8114.                         'product_name' => $productList[$product->getProductId()]['name'],
  8115.                         'package_id' => $product->getPackageId(),
  8116.                         'qty' => $product->getQty(),
  8117.                         'delivered' => $product->getDelivered(),
  8118.                         'balance' => $product->getBalance(),
  8119.                         //                        'unit_package_multiplier'=>1,
  8120.                         'unit_package_multiplier' => $pckg_item_cross_match_data[$product->getPackageId()][$product->getProductId()]['product_units'],
  8121.                         //                        'delivered'=>$product->getDelivered(),
  8122.                     );
  8123.                     $sendData['productList'][] = $p_data;
  8124.                     $sendData['productListByPackage'][$product->getPackageId()][] = $p_data;
  8125.                 }
  8126.             }
  8127.             if ($SO->getSalesType() == || $SO->getSalesType() == 3//Spare
  8128.             {
  8129.                 foreach ($QD as $product) {
  8130.                     $dt $product;
  8131.                     $p_data = array(
  8132.                         'details_id' => $product->getId(),
  8133.                         'productId' => $product->getProductId(),
  8134.                         'serviceId' => $product->getServiceId(),
  8135.                         'productFdm' => $product->getProductFdm(),
  8136.                         'service_id' => $product->getServiceId(),
  8137.                         'type' => $product->getType(),
  8138.                         'desc' => $product->getDesc(),
  8139.                         'origin' => $product->getOrigin(),
  8140.                         'price' => $product->getPrice(),
  8141.                         'warranty' => $product->getWarranty(),
  8142.                         'unitTypeId' => $product->getUnitTypeId(),
  8143.                         //                        'product_name'=>$product->getType()==1?$productList[$product->getProductId()]['name']:'',
  8144.                         'product_name' => ($product->getType() == 1) ?
  8145.                             (isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : $product->getProductNameFdm()) : '',
  8146.                         'service_name' => $product->getType() == $serviceList[$product->getServiceId()]['name'] : '',
  8147.                         'package_id' => $product->getPackageId(),
  8148.                         'qty' => $product->getQty(),
  8149.                         'delivered' => $product->getDelivered(),
  8150.                         'balance' => $product->getBalance(),
  8151.                         'id' => $dt->getProductId(),
  8152.                         'alias' => $dt->getDesc(),
  8153.                         'unit' => $dt->getQty(),
  8154.                         'unit_price' => $dt->getPrice(),
  8155.                         'total_price' => $dt->getProductAmount(),
  8156.                         'discount_rate' => $dt->getDiscountRate(),
  8157.                         'discount_amount' => $dt->getDiscountAmount(),
  8158.                         'discounted_amount' => $dt->getDiscountedAmount(),
  8159.                         'free_product_ids' => json_decode($dt->getFreeProductIds()),
  8160.                         'so_item_id' => $dt->getId(),
  8161.                         'free_products_so_item_ids' => json_decode($dt->getFreeProductSoItemIds()),
  8162.                         'free_products_so_item_ids_str' => $dt->getFreeProductSoItemIds(),
  8163.                         'freeProductUnit' => json_decode($dt->getFreeProductUnits()),
  8164.                         'ret_data' => [],
  8165.                         'fdm' => $dt->getProductFdm(),
  8166.                         'detailsIds' => [],
  8167.                         'docIds' => [],
  8168.                         //                        'delivered'=>$product->getDelivered(),
  8169.                     );
  8170.                     $sendData['productList'][] = $p_data;
  8171.                 }
  8172.                 //now package data
  8173.             }
  8174.             $sendData['otherData']['vatRate'] = $SO->getVatRate();
  8175.             $sendData['otherData']['vatAmount'] = $SO->getVatAmount();
  8176.             $sendData['otherData']['invoiceAmount'] = $SO->getInvoiceAmount();
  8177.             $sendData['otherData']['aitRate'] = $SO->getAitRate();
  8178.             $sendData['otherData']['aitAmount'] = $SO->getAitAmount();
  8179.             $sendData['otherData']['sdRate'] = $SO->getSpecialDiscountRate();
  8180.             $sendData['otherData']['sdAmount'] = $SO->getSpecialDiscountAmount();
  8181.             if ($sendData) {
  8182.                 return new JsonResponse(array("success" => true"content" => $sendData));
  8183.             }
  8184.             return new JsonResponse(array("success" => false));
  8185.         }
  8186.         return new JsonResponse(array("success" => false));
  8187.     }
  8188.     public function CreateDebitNote(Request $request)
  8189.     {
  8190.         return $this->render(
  8191.             '@Sales/pages/input_forms/new_debit_note.html.twig',
  8192.             array(
  8193.                 'page_title' => 'New Debit Note'
  8194.             )
  8195.         );
  8196.     }
  8197.     //package
  8198.     public function ProductPackageList(Request $request)
  8199.     {
  8200.         $q $this->getDoctrine()
  8201.             ->getRepository('ApplicationBundle:ProductPackage')
  8202.             ->findBy(
  8203.                 array(
  8204.                     'status' => GeneralConstant::ACTIVE,
  8205.                 )
  8206.             );
  8207.         $stage_list = array(
  8208.             => 'Pending',
  8209.             => 'Pending',
  8210.             => 'Complete',
  8211.             => 'Partial',
  8212.         );
  8213.         $data = [];
  8214.         foreach ($q as $entry) {
  8215.             $data[] = array(
  8216.                 //                'doc_date'=>$entry->getDeliveryReceiptDate(),
  8217.                 'id' => $entry->getPackageId(),
  8218.                 'doc_hash' => $entry->getDocumentHash(),
  8219.                 'package_amount' => $entry->getTotalPrice(),
  8220.                 'stage' => $stage_list[$entry->getStage()]
  8221.             );
  8222.         }
  8223.         return $this->render(
  8224.             '@Sales/pages/list/product_package_list.html.twig',
  8225.             array(
  8226.                 'page_title' => 'Packages',
  8227.                 'data' => $data
  8228.             )
  8229.         );
  8230.     }
  8231.     public function ViewProductPackage(Request $request$id)
  8232.     {
  8233.         $em $this->getDoctrine()->getManager();
  8234.         $dt Package::GetProductPackageDetails($em$id);
  8235.         return $this->render(
  8236.             '@Sales/pages/views/view_product_package.html.twig',
  8237.             array(
  8238.                 'page_title' => 'View',
  8239.                 'data' => $dt,
  8240.                 'auto_created' => $dt['auto_created'],
  8241.                 'approval_data' => System::checkIfApprovalExists(
  8242.                     $em,
  8243.                     array_flip(GeneralConstant::$Entity_list)['ProductPackage'],
  8244.                     $id,
  8245.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  8246.                 ),
  8247.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  8248.                     $this->getDoctrine()->getManager(),
  8249.                     array_flip(GeneralConstant::$Entity_list)['ProductPackage'],
  8250.                     $id,
  8251.                     $dt['created_by'],
  8252.                     $dt['edited_by']
  8253.                 ) : []
  8254.             )
  8255.         );
  8256.     }
  8257.     public function PrintProductPackage(Request $request$id)
  8258.     {
  8259.         $em $this->getDoctrine()->getManager();
  8260.         $data Package::GetProductPackageDetails($em$id);
  8261.         $company_data Company::getCompanyData($em1);
  8262.         $document_mark = array(
  8263.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  8264.             'copy' => ''
  8265.         );
  8266.         return $this->render(
  8267.             '@Sales/pages/print/product_package_print.html.twig',
  8268.             array(
  8269.                 'page_title' => 'Package ' $data['doc_hash'],
  8270.                 'data' => $data,
  8271.                 'document_mark_image' => $document_mark['original'],
  8272.                 'company_name' => $company_data->getName(),
  8273.                 'company_data' => $company_data,
  8274.                 'company_address' => $company_data->getAddress(),
  8275.                 'company_image' => $company_data->getImage(),
  8276.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  8277.                 'page_header' => 'New Product',
  8278.                 'document_type' => 'Sales Package',
  8279.                 'page_header_sub' => 'Add',
  8280.                 //                'type_list'=>$type_list,
  8281.                 //                'mis_data'=>$mis_data,
  8282.                 //                'mis_print'=>$mis_print,
  8283.                 'item_data' => [],
  8284.                 'received' => 2,
  8285.                 'return' => 1,
  8286.                 'total_w_vat' => 1,
  8287.                 'total_vat' => 1,
  8288.                 'total_wo_vat' => 1,
  8289.                 'invoice_id' => 'abcd1234',
  8290.                 'created_by' => 'created by',
  8291.                 'created_at' => '',
  8292.                 'red' => 0,
  8293.             )
  8294.         );
  8295.     }
  8296.     public function CreateProductMrpDocument(Request $request$id 0)
  8297.     {
  8298.         $em $this->getDoctrine()->getManager();
  8299.         $em_goc $this->getDoctrine()->getManager('company_group');
  8300.         if ($request->isMethod('POST')) {
  8301.             $em $this->getDoctrine()->getManager();
  8302.             MiscActions::RemoveExpiredDocs($em);
  8303.             $entity_id array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'];
  8304.             //            $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
  8305.             //                array(
  8306.             //                    'tradeOfferId'=>$id, ///material
  8307.             //
  8308.             //                ),array('projectDate'=>'desc')
  8309.             //            );
  8310.             //            $client=$em->getRepository('ApplicationBundle:AccClients')->findOneBy(
  8311.             //                array(
  8312.             //                    'clientId'=>$projectData->getClientId(), ///material
  8313.             //
  8314.             //                ),array('projectDate'=>'desc')
  8315.             //            );
  8316.             $dochash $request->request->get('docHash');
  8317.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8318.             $approveRole $request->request->get('approvalRole');
  8319.             $approveHash $request->request->get('approvalHash');
  8320.             if (!DocValidation::isInsertable(
  8321.                 $em,
  8322.                 $entity_id,
  8323.                 $dochash,
  8324.                 $loginId,
  8325.                 $approveRole,
  8326.                 $approveHash,
  8327.                 $id
  8328.             )) {
  8329.                 $this->addFlash(
  8330.                     'error',
  8331.                     'Sorry Could not insert Data.'
  8332.                 );
  8333.             } else {
  8334.                 //construct the files
  8335.                 $file_list = array(
  8336.                     'product_files' => [],
  8337.                     'service_files' => [],
  8338.                     'ar_files' => [],
  8339.                 );
  8340.                 $file_path null;
  8341.                 //                foreach ($request->files as $uploadedFile) {
  8342.                 //                    if ($uploadedFile != null) {
  8343.                 //
  8344.                 //                        $fileName = md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  8345.                 //                        $path = $fileName;
  8346.                 //                        $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' . $request->request->get('userId') . '/';
  8347.                 //                        if (!file_exists($upl_dir)) {
  8348.                 //                            mkdir($upl_dir, 0777, true);
  8349.                 //                        }
  8350.                 //                        $file = $uploadedFile->move($upl_dir, $path);
  8351.                 //                        if ($path != "")
  8352.                 //                            $file_path = 'uploads/FileUploads/' . $request->request->get('userId') . '/' . $path;
  8353.                 //                    }
  8354.                 //
  8355.                 //
  8356.                 //                }
  8357.                 //
  8358.                 $spId SalesOrderM::CreateNewProductPriceList(
  8359.                     $this->getDoctrine()->getManager(),
  8360.                     $id,
  8361.                     $request->request,
  8362.                     $dochash,
  8363.                     $file_path,
  8364.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  8365.                     $this->getLoggedUserCompanyId($request)
  8366.                 );
  8367.                 $file_path_list = [];
  8368.                 if ($spId != 0)
  8369.                     if (!empty($request->files)) {
  8370.                         MiscActions::RemoveFilesForEntityDoc($em_goc'AccTransactions'$spId);
  8371.                         $storePath 'uploads/PriceDoc/';
  8372.                         $path "";
  8373.                         $file_path "";
  8374.                         $session $request->getSession();
  8375.                         MiscActions::RemoveExpiredFiles($em_goc);
  8376.                         foreach ($request->files as $uploadedFileGG) {
  8377.                             //            if($uploadedFile->getImage())
  8378.                             //                var_dump($uploadedFile->getFile());
  8379.                             //                var_dump($uploadedFile);
  8380.                             $tempD $uploadedFileGG;
  8381.                             if (!is_array($uploadedFileGG)) {
  8382.                                 $uploadedFileGG = array();
  8383.                                 $uploadedFileGG[] = $tempD;
  8384.                             }
  8385.                             foreach ($uploadedFileGG as $uploadedFile) {
  8386.                                 if ($uploadedFile != null) {
  8387.                                     $extension $uploadedFile->guessExtension();
  8388.                                     $size $uploadedFile->getSize();
  8389.                                     $fileName 'PRCDOC_' $spId '_' . (md5(uniqid())) . '.' $uploadedFile->guessExtension();
  8390.                                     $path $fileName;
  8391.                                     $upl_dir $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath;
  8392.                                     if (!file_exists($upl_dir)) {
  8393.                                         mkdir($upl_dir0777true);
  8394.                                     }
  8395.                                     if (file_exists($upl_dir '' $path)) {
  8396.                                         chmod($upl_dir '' $path0755);
  8397.                                         unlink($upl_dir '' $path);
  8398.                                     }
  8399.                                     $file $uploadedFile->move($upl_dir$path);
  8400.                                     $expireNever 1;
  8401.                                     $expireTs 0;
  8402.                                     $EntityFile = new EntityFile();
  8403.                                     $EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path);
  8404.                                     $EntityFile->setMarker('_GEN_');
  8405.                                     $EntityFile->setExtension($extension);
  8406.                                     $EntityFile->setExpireTs($expireTs);
  8407.                                     $EntityFile->setSize($size);
  8408.                                     $EntityFile->setRelativePath($storePath $path);
  8409.                                     $EntityFile->setEntityName('ProductMrpDocument');
  8410.                                     $EntityFile->setEntityBundle('ApplicationBundle');
  8411.                                     $EntityFile->setEntityId($spId);
  8412.                                     $EntityFile->setEntityIdField('productMrpDocumentId');
  8413.                                     $EntityFile->setModifyFieldSetter('setFiles');
  8414.                                     $EntityFile->setDocIdForApplicant(0);
  8415.                                     $EntityFile->setUserId($session->get(UserConstants::USER_ID0));
  8416.                                     $EntityFile->setAppId($session->get(UserConstants::USER_APP_ID0));
  8417.                                     $EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID0));
  8418.                                     $EntityFile->setUserType($session->get(UserConstants::USER_TYPE0));
  8419.                                     $em_goc->persist($EntityFile);
  8420.                                     $em_goc->flush();
  8421.                                     $EntityFileId $EntityFile->getId();
  8422.                                 }
  8423.                                 if ($path != "")
  8424.                                     $file_path_list[] = ($storePath $path);
  8425.                             }
  8426.                         }
  8427.                         $g_path $this->container->getParameter('kernel.root_dir') . '/../web/' $storePath $path;
  8428.                         $v $em->getRepository('ApplicationBundle:ProductMrpDocument')->findOneBy(array(
  8429.                             'productMrpDocumentId' => $spId,
  8430.                         ));
  8431.                         if ($v) {
  8432.                             $v->setFiles(implode(','$file_path_list));
  8433.                             $em->flush();
  8434.                         } else {
  8435.                         }
  8436.                     }
  8437.                 //now add Approval info
  8438.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  8439.                 $approveRole $request->request->get('approvalRole');  //created
  8440.                 $options = array(
  8441.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  8442.                     'notification_server' => $this->container->getParameter('notification_server'),
  8443.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  8444.                     'url' => $this->generateUrl(
  8445.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument']]['entity_view_route_path_name']
  8446.                     )
  8447.                 );
  8448.                 System::setApprovalInfo(
  8449.                     $this->getDoctrine()->getManager(),
  8450.                     $options,
  8451.                     array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
  8452.                     $spId,
  8453.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  8454.                 );
  8455.                 System::createEditSignatureHash(
  8456.                     $this->getDoctrine()->getManager(),
  8457.                     array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
  8458.                     $spId,
  8459.                     $loginId,
  8460.                     $approveRole,
  8461.                     $request->request->get('approvalHash')
  8462.                 );
  8463.                 $this->addFlash(
  8464.                     'success',
  8465.                     'Price Settings Created'
  8466.                 );
  8467.                 $url $this->generateUrl(
  8468.                     'view_product_mrp_document'
  8469.                 );
  8470.                 $doc_here $this->getDoctrine()
  8471.                     ->getRepository('ApplicationBundle:ProductMrpDocument')
  8472.                     ->findOneBy(
  8473.                         array(
  8474.                             'productMrpDocumentId' => $spId
  8475.                         )
  8476.                     );
  8477.                 System::AddNewNotification(
  8478.                     $this->container->getParameter('notification_enabled'),
  8479.                     $this->container->getParameter('notification_server'),
  8480.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  8481.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  8482.                     "Price List : " $dochash " Has Been Created And is Under Processing",
  8483.                     'pos',
  8484.                     System::getPositionIdsByDepartment($emGeneralConstant::SALES_DEPARTMENT),
  8485.                     'success',
  8486.                     $url "/" $spId,
  8487.                     "Price Settings"
  8488.                 );
  8489.                 if ($request->request->has('returnJson')) {
  8490.                     $doc $doc_here;
  8491.                     return new JsonResponse(array(
  8492.                         'success' => true,
  8493.                         'documentHash' => $doc_here->getDocumentHash(),
  8494.                         'documentId' => $spId,
  8495.                         'documentIdPadded' => str_pad($spId8'0'STR_PAD_LEFT),
  8496.                         'documentDate' => $doc_here->getProductMrpDocumentDate()->format('Y-m-d'),
  8497.                         'documentAmount' => '',
  8498.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  8499.                         'viewUrl' => $url "/" $spId,
  8500.                         'docPrintMainUrl' => $this->generateUrl('view_product_mrp_document'),
  8501.                     ));
  8502.                 } else {
  8503.                     $this->addFlash(
  8504.                         'success',
  8505.                         'New Document Created'
  8506.                     );
  8507.                     return $this->redirect($url "/" $spId);
  8508.                 }
  8509.             }
  8510.         }
  8511.         $message "";
  8512.         $extData = [];
  8513.         if ($id != 0) {
  8514.             $extData $em->getRepository('ApplicationBundle:ProductMrpDocument')->findOneBy(
  8515.                 array(
  8516.                     'productMrpDocumentId' => $id///material
  8517.                 )
  8518.             );
  8519.             //now if its not editable, redirect to view
  8520.             if ($extData) {
  8521.                 //                if ($proposalData->getEditFlag() != 1) {
  8522.                 //                    $url = $this->generateUrl(
  8523.                 //                        'view_trade_offer'
  8524.                 //                    );
  8525.                 //                    $this->addFlash(
  8526.                 //                        'error',
  8527.                 //                        'Sorry You cant Edit the document Right now.'
  8528.                 //                    );
  8529.                 //                    return $this->redirect($url . "/" . $id);
  8530.                 //                }
  8531.             }
  8532.         }
  8533.         $qry $em->getRepository("ApplicationBundle:InvProducts")->findBy(array(
  8534.             "status" => GeneralConstant::ACTIVE,
  8535.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  8536.             'sellable' => //sellable
  8537.         ));
  8538.         $pl = [];
  8539.         $pl_array = [];
  8540.         foreach ($qry as $product) {
  8541.             $pl[$product->getId()] = array(
  8542.                 'text' => $product->getName(),
  8543.                 'name' => $product->getName(),
  8544.                 'id' => $product->getId(),
  8545.                 'value' => $product->getId(),
  8546.                 'purchase_price' => $product->getPurchasePrice(),
  8547.                 'sales_price' => $product->getSalesPrice(),
  8548.                 'supplier_id' => $product->getBrandCompany(),
  8549.             );
  8550.             $pl_array[] = array(
  8551.                 'text' => $product->getName(),
  8552.                 'value' => $product->getId(),
  8553.                 'name' => $product->getName(),
  8554.                 'id' => $product->getId(),
  8555.                 'purchase_price' => $product->getPurchasePrice(),
  8556.                 'sales_price' => $product->getSalesPrice(),
  8557.                 'supplier_id' => $product->getBrandCompany(),
  8558.             );
  8559.         }
  8560.         $qry $em->getRepository("ApplicationBundle:AccService")->findBy(array(
  8561.             "status" => GeneralConstant::ACTIVE,
  8562.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  8563.             //            'type'=>1//trade items
  8564.         ));
  8565.         $sl = [];
  8566.         $sl_array = [];
  8567.         foreach ($qry as $product) {
  8568.             $sl[$product->getServiceId()] = array(
  8569.                 'text' => $product->getServiceName(),
  8570.                 'value' => $product->getServiceId(),
  8571.                 'name' => $product->getServiceName(),
  8572.                 'id' => $product->getServiceId(),
  8573.             );
  8574.             $sl_array[] = array(
  8575.                 'text' => $product->getServiceName(),
  8576.                 'value' => $product->getServiceId(),
  8577.                 'name' => $product->getServiceName(),
  8578.                 'id' => $product->getServiceId(),
  8579.             );
  8580.         }
  8581.         $qry $em->getRepository("ApplicationBundle:ProjectWorkStage")->findBy(array(
  8582.             "status" => GeneralConstant::ACTIVE,
  8583.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  8584.             //            'type'=>1//trade items
  8585.         ));
  8586.         $workStages = [];
  8587.         $workStages_array = [];
  8588.         foreach ($qry as $product) {
  8589.             $workStages[$product->getProjectWorkStageId()] = array(
  8590.                 'text' => $product->getStageName(),
  8591.                 'value' => $product->getProjectWorkStageId(),
  8592.                 'name' => $product->getStageName(),
  8593.                 'id' => $product->getProjectWorkStageId(),
  8594.             );
  8595.             $workStages_array[] = array(
  8596.                 'text' => $product->getStageName(),
  8597.                 'value' => $product->getProjectWorkStageId(),
  8598.                 'name' => $product->getStageName(),
  8599.                 'id' => $product->getProjectWorkStageId(),
  8600.             );
  8601.         }
  8602.         $hl Accounts::HeadList($em);
  8603.         $debug_data $request->files->get('product_reference_file');
  8604.         $companyId $this->getLoggedUserCompanyId($request);
  8605.         $productListArray = [];
  8606.         $subCategoryListArray = [];
  8607.         $categoryListArray = [];
  8608.         $igListArray = [];
  8609.         $unitListArray = [];
  8610.         $productList Inventory::ProductList($em$companyId00'', [], 1);
  8611.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  8612.         $categoryList Inventory::ProductCategoryList($em$companyId);
  8613.         $igList Inventory::ItemGroupList($em$companyId);
  8614.         $unitList Inventory::UnitTypeList($em);
  8615.         foreach ($productList as $product) {
  8616.             $productListArray[] = $product;
  8617.         }
  8618.         foreach ($categoryList as $product) {
  8619.             $categoryListArray[] = $product;
  8620.         }
  8621.         foreach ($subCategoryList as $product) {
  8622.             $subCategoryListArray[] = $product;
  8623.         }
  8624.         foreach ($igList as $product) {
  8625.             $igListArray[] = $product;
  8626.         }
  8627.         foreach ($unitList as $product) {
  8628.             $unitListArray[] = $product;
  8629.         }
  8630.         $brandList Inventory::GetBrandList($em$companyId);
  8631.         $brandListArray = [];
  8632.         foreach ($brandList as $product) {
  8633.             $brandListArray[] = $product;
  8634.         }
  8635.         //        $colorList=Inventory::GetBrandList($em,$companyId);
  8636.         //        $colorListArray=[];
  8637.         //        foreach ($colorList as $product) {
  8638.         //
  8639.         //            $colorListArray[] = $product;
  8640.         //        }
  8641.         return $this->render(
  8642.             '@Sales/pages/input_forms/create_product_mrp_document.html.twig',
  8643.             array(
  8644.                 'page_title' => 'Price Settings',
  8645.                 'ExistingClients' => Client::GetExistingClientList($em$companyId),
  8646.                 //                'clients'=>SalesOrderM::GetClientList($em),
  8647.                 'clients_by_ac_head' => SalesOrderM::GetClientListByAcHead($em),
  8648.                 'users' => Users::getUserListById($em),
  8649.                 'stages' => ProjectConstant::$projectStages,
  8650.                 'productList' => $productList,
  8651.                 'subCategoryList' => $subCategoryList,
  8652.                 'categoryList' => $categoryList,
  8653.                 'igList' => $igList,
  8654.                 'unitList' => $unitList,
  8655.                 'brandList' => $brandList,
  8656.                 'brandListArray' => $brandListArray,
  8657.                 //                'colorList'=>$colorList,
  8658.                 //                'colorListArray'=>$colorListArray,
  8659.                 'productListArray' => $productListArray,
  8660.                 'subCategoryListArray' => $subCategoryListArray,
  8661.                 'categoryListArray' => $categoryListArray,
  8662.                 'igListArray' => $igListArray,
  8663.                 'unitListArray' => $unitListArray,
  8664.                 'sl' => $sl,
  8665.                 'pl' => $pl,
  8666.                 'hl' => $hl,
  8667.                 'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  8668.                 'extData' => $extData,
  8669.                 'message' => $message,
  8670.                 'tradeOfferId' => $id,
  8671.                 'regionList' => Client::RegionList($em$companyId),
  8672.                 'branchList' => Client::BranchList($em$companyId),
  8673.                 'pl_array' => $pl_array,
  8674.                 'sl_array' => $sl_array,
  8675.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  8676.                 'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  8677.                 'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  8678.                 'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  8679.                 'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  8680.                 'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  8681.                 'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  8682.                 'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  8683.                 'debug_data' => $debug_data,
  8684.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  8685.                 //              'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  8686.             )
  8687.         );
  8688.     }
  8689.     public function ProductMrpDocumentList(Request $request)
  8690.     {
  8691.         $q $this->getDoctrine()
  8692.             ->getRepository('ApplicationBundle:ProductMrpDocument')
  8693.             ->findBy(
  8694.                 array(
  8695.                     'status' => GeneralConstant::ACTIVE,
  8696.                 )
  8697.             );
  8698.         $stage_list = array(
  8699.             => 'Pending',
  8700.             => 'Pending',
  8701.             => 'Complete',
  8702.             => 'Partial',
  8703.         );
  8704.         $data = [];
  8705.         foreach ($q as $entry) {
  8706.             $data[] = array(
  8707.                 'doc_date' => $entry->getProductMrpDocumentDate(),
  8708.                 'id' => $entry->getProductMrpDocumentId(),
  8709.                 'doc_hash' => $entry->getDocumentHash(),
  8710.                 'assigned_amount' => 0,
  8711.                 'stage' => 1
  8712.             );
  8713.         }
  8714.         return $this->render(
  8715.             '@Sales/pages/list/product_mrp_document_list.html.twig',
  8716.             array(
  8717.                 'page_title' => 'Mrp Settings',
  8718.                 'data' => $data
  8719.             )
  8720.         );
  8721.     }
  8722.     public function ProductPriceList(Request $request)
  8723.     {
  8724.         $companyId $this->getLoggedUserCompanyId($request);
  8725.         $em $this->getDoctrine()
  8726.             ->getManager();
  8727.         $q $this->getDoctrine()
  8728.             ->getRepository('ApplicationBundle:ProductMrp')
  8729.             ->findBy(
  8730.                 array(
  8731.                     'status' => GeneralConstant::ACTIVE,
  8732.                     //                    'CompanyId' => $companyId
  8733.                 )
  8734.             );
  8735.         $stage_list = array(
  8736.             => 'Pending',
  8737.             => 'Pending',
  8738.             => 'Complete',
  8739.             => 'Partial',
  8740.         );
  8741.         $data = [];
  8742.         foreach ($q as $entry) {
  8743.             $data[] = array(
  8744.                 //                'doc_date'=>$entry->getProductMrpDocumentDate(),
  8745.                 //                'id'=>$entry->getProductMrpDocumentId(),
  8746.                 'productId' => $entry->getProductId(),
  8747.                 'doc_id' => $entry->getProductMrpDocumentId(),
  8748.                 'doc_hash' => $entry->getDocumentHash(),
  8749.                 'price_data' => json_decode($entry->getPriceByCustomerTypes(), true),
  8750.             );
  8751.         }
  8752.         return $this->render(
  8753.             '@Sales/pages/list/product_mrp_list.html.twig',
  8754.             array(
  8755.                 'page_title' => 'Price Settings',
  8756.                 'data' => $data,
  8757.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  8758.                 'productList' => Inventory::ProductList($em$companyId1)
  8759.             )
  8760.         );
  8761.     }
  8762.     //For Product Catalogue
  8763.     public function ViewProductCatalogueAction(Request $request)
  8764.     {
  8765.         $companyId $this->getLoggedUserCompanyId($request);
  8766.         $em $this->getDoctrine()->getManager();
  8767.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  8768.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  8769.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  8770.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  8771.         $data_searched = [];
  8772.         if ($request->isMethod('POST'))
  8773.             $method 'POST';
  8774.         else
  8775.             $method 'GET';
  8776.         $post_data $method == 'POST' $request->request $request->query;
  8777. //        return new JsonResponse($data_searched);
  8778.         // Fetch flat product data
  8779.         $filterQry $em->getRepository('ApplicationBundle:ProductMrp')->createQueryBuilder('Pr')
  8780.             ->select('Pr.productMrpId''Pr.priceByCustomerTypes''Pr.currency''Pr.minOrderQty')
  8781.             ->addSelect('P.id as pid''P.igId''P.categoryId''P.name''P.defaultImage''P.unitTypeId''P.subCategoryId''P.productCode''P.note''P.productFdm')
  8782.             ->addSelect('IG.id as igId''IG.name as itemGroupName')
  8783.             ->addSelect('PC.name as productCategory')
  8784.             //        ->addSelect('PSc.name as subCategoryName')
  8785.             ->addSelect('B.id as brandId''B.name as brandCompanyName''B.image as brandCompanyImage')
  8786.             ->leftJoin('ApplicationBundle:InvProducts''P''WITH''Pr.productId = P.id')
  8787.             ->leftJoin('ApplicationBundle:InvItemGroup''IG''WITH''P.igId = IG.id')
  8788.             ->leftJoin('ApplicationBundle:InvProductCategories''PC''WITH''P.categoryId = PC.id')
  8789. //        ->leftJoin('ApplicationBundle:InvProductSubCategories', 'PSc', 'WITH', 'P.subCategoryId = PSc.id')
  8790.             ->leftJoin('ApplicationBundle:BrandCompany''B''WITH''P.brandCompany = B.id')
  8791.             ->leftJoin('ApplicationBundle:ClientType''C''WITH''Pr.priceByCustomerTypes = C.clientTypeId');
  8792.         if (!empty($post_data->get('productId'))) {
  8793.             $filterQry->andWhere(' P.id in (' implode(','$post_data->get('productId')) . ') ');
  8794.         }
  8795.         if (!empty($post_data->get('igId'))) {
  8796.             $filterQry->andWhere(' P.igId in (' implode(','$post_data->get('igId')) . ') ');
  8797.         }
  8798.         if (!empty($post_data->get('categoryId'))) {
  8799.             $filterQry->andWhere(' P.categoryId in (' implode(','$post_data->get('categoryId')) . ') ');
  8800.         }
  8801.         if (!empty($post_data->get('brandId'))) {
  8802.             $filterQry->andWhere(' P.brandCompany in (' implode(','$post_data->get('brandId')) . ') ');
  8803.         }
  8804. //        if(!empty($post_data->get('priceByCustomerTypes'))){
  8805. //            $filterQry -> andWhere('Pr.priceByCustomerTypes in ('. implode(',', $post_data->get('priceByCustomerTypes')) .') ');
  8806. //        }
  8807.         if (!empty($post_data->get('currency'))) {
  8808.             $filterQry->andWhere(' Pr.currency in (' implode(','$post_data->get('currency')) . ') ');
  8809.         }
  8810.         $productMrp $filterQry
  8811.             ->getQuery()
  8812.             ->getResult();
  8813.         //ClientType name
  8814.         $clientTypes $em->getRepository('ApplicationBundle:ClientType')
  8815.             ->createQueryBuilder('ct')
  8816.             ->select('ct.clientTypeId, ct.name')
  8817.             ->getQuery()
  8818.             ->getArrayResult();
  8819.         $clientTypeList = [];
  8820.         foreach ($clientTypes as $ct) {
  8821.             $clientTypeList[$ct['clientTypeId']] = $ct['name'];
  8822.         }
  8823.         //UOM name
  8824.         $unitTypes $em->getRepository('ApplicationBundle:UnitType')
  8825.             ->createQueryBuilder('ut')
  8826.             ->select('ut.id, ut.name')
  8827.             ->getQuery()
  8828.             ->getArrayResult();
  8829.         $unitTypeList = [];
  8830.         foreach ($unitTypes as $ut) {
  8831.             $unitTypeList[$ut['id']] = $ut['name'];
  8832.         }
  8833.         //Item group
  8834.         $itemGroups $em->getRepository('ApplicationBundle:InvItemGroup')
  8835.             ->createQueryBuilder('ig')
  8836.             ->select('ig.id, ig.name, ig.categorizationData')
  8837.             ->getQuery()
  8838.             ->getArrayResult();
  8839.         $itemGroupList = [];
  8840.         foreach ($itemGroups as $igData) {
  8841.             $itemGroupList[$igData['id']] = array(
  8842.                 'name' => $igData['name'],
  8843.                 'categorizationData' => json_decode($igData['categorizationData'], true) ??
  8844.                     [
  8845.                         ["alias" => "Category""en" => 1"inc" => "1"],
  8846.                         ["alias" => "Sub Category""en" => 1"inc" => "1"],
  8847.                     ]
  8848.             );
  8849.         }
  8850.         //Currency name
  8851.         $currencyTypes $em->getRepository('ApplicationBundle:Currencies')
  8852.             ->createQueryBuilder('cu')
  8853.             ->select('cu.currencyId, cu.name')
  8854.             ->getQuery()
  8855.             ->getArrayResult();
  8856.         $currencyTypeList = [];
  8857.         foreach ($currencyTypes as $cu) {
  8858.             $currencyTypeList[$cu['currencyId']] = $cu['name'];
  8859.         }
  8860.         //Sub-Category
  8861.         $subCategoryTypes $em->getRepository('ApplicationBundle:InvProductSubCategories')
  8862.             ->createQueryBuilder('sc')
  8863.             ->select('sc.id, sc.name')
  8864.             ->getQuery()
  8865.             ->getArrayResult();
  8866.         $subCategoryTypeList = [];
  8867.         foreach ($subCategoryTypes as $sc) {
  8868.             $subCategoryTypeList[$sc['id']] = $sc['name'];
  8869.         }
  8870. //        dump($subCategoryTypeList);
  8871.         // Restructure: Item Group â†’ Brand â†’ Products
  8872.         $structuredData = [];
  8873.         foreach ($productMrp as $row) {
  8874.             $igId $row['igId'];
  8875.             $brandId $row['brandId'];
  8876.             if (!isset($structuredData[$igId])) {
  8877.                 $structuredData[$igId] = [
  8878.                     'name' => $row['itemGroupName'],
  8879.                     //                    'categorizationData' => json_decode($row['categorizationData'], true) ??
  8880.                     //
  8881.                     //
  8882.                     //                        [
  8883.                     //                            ["alias" => "Category", "en" => 1, "inc" => "1"],
  8884.                     //                            ["alias" => "Sub Category", "en" => 1, "inc" => "1"],
  8885.                     //
  8886.                     //
  8887.                     //                        ]
  8888.                     //                    ,
  8889.                     'brands' => []
  8890.                 ];
  8891.             }
  8892.             if (!isset($structuredData[$igId]['brands'][$brandId])) {
  8893.                 $structuredData[$igId]['brands'][$brandId] = [
  8894.                     'name' => $row['brandCompanyName'],
  8895.                     'image' => $row['brandCompanyImage'],
  8896.                     'products' => []
  8897.                 ];
  8898.             }
  8899.             $unitTypeName = isset($unitTypeList[$row['unitTypeId']]) ? $unitTypeList[$row['unitTypeId']] : 'N/A';
  8900.             $currencyName = isset($currencyTypeList[$row['currency']]) ? $currencyTypeList[$row['currency']] : 'N/A';
  8901.             // Parse productFdm string for SZ, SO, ST, SH values
  8902.             preg_match('/SZ(\d+)/'$row['productFdm'], $szMatch);
  8903.             preg_match('/SO(\d+)/'$row['productFdm'], $soMatch);
  8904.             preg_match('/ST(\d+)/'$row['productFdm'], $stMatch);
  8905.             preg_match('/SH(\d+)/'$row['productFdm'], $shMatch);
  8906.             $subCategoryZeroId $szMatch[1] ?? null;
  8907.             $subCategoryOneId $soMatch[1] ?? null;
  8908.             $subCategoryTwoId $stMatch[1] ?? null;
  8909.             $subCategoryThreeId $shMatch[1] ?? null;
  8910.             $structuredData[$igId]['brands'][$brandId]['products'][] = [
  8911.                 'pid' => $row['pid'],
  8912.                 'name' => $row['name'],
  8913.                 'category' => $row['productCategory'],
  8914.                 'minOrderQty' => $row['minOrderQty'],
  8915.                 'productCode' => $row['productCode'],
  8916.                 'unitTypeId' => $row['unitTypeId'],
  8917.                 'unitTypeName' => $unitTypeName,
  8918.                 'currency' => $row['currency'],
  8919.                 'currencyName' => $currencyName,
  8920.                 'productFdm' => $row['productFdm'],
  8921.                 'note' => $row['note'],
  8922.                 //                'categorizationData' => $row['categorizationData'],
  8923.                 //                'price' => $row['priceByCustomerTypes'],
  8924.                 'priceByCustomerTypes' => json_decode($row['priceByCustomerTypes'], true), // decode JSON
  8925.                 'defaultImage' => $row['defaultImage'], // include image
  8926.                 // Sub-category types extracted
  8927.                 'subCategoryZero' => [
  8928.                     'id' => $subCategoryZeroId,
  8929.                     'name' => $subCategoryTypeList[$subCategoryZeroId] ?? 'N/A'
  8930.                 ],
  8931.                 'subCategoryOne' => [
  8932.                     'id' => $subCategoryOneId,
  8933.                     'name' => $subCategoryTypeList[$subCategoryOneId] ?? 'N/A'
  8934.                 ],
  8935.                 'subCategoryTwo' => [
  8936.                     'id' => $subCategoryTwoId,
  8937.                     'name' => $subCategoryTypeList[$subCategoryTwoId] ?? 'N/A'
  8938.                 ],
  8939.                 'subCategoryThree' => [
  8940.                     'id' => $subCategoryThreeId,
  8941.                     'name' => $subCategoryTypeList[$subCategoryThreeId] ?? 'N/A'
  8942.                 ],
  8943.             ];
  8944.         }
  8945.         $find_by_query = [];
  8946.         $query_add '';
  8947. //        if($method=='POST')
  8948.         if (!empty($post_data->get('productId'))) {
  8949.             $find_by_query['productId'] = $post_data->get('productId');
  8950.         }
  8951.         if (!empty($post_data->get('currency'))) {
  8952.             $find_by_query['currency'] = $post_data->get('currency');
  8953.         }
  8954.         if (!empty($post_data->get('igId'))) {
  8955.             $find_by_query['igId'] = $post_data->get('igId');
  8956.         }
  8957.         if (!empty($post_data->get('categoryId'))) {
  8958.             $find_by_query['categoryId'] = $post_data->get('categoryId');
  8959.         }
  8960.         if (!empty($post_data->get('brandId'))) {
  8961.             $find_by_query['brandId'] = $post_data->get('brandId');
  8962.         }
  8963.         if (!empty($post_data->get('actionTagId'))) {
  8964.             $find_by_query['actionTagId'] = $post_data->get('actionTagId');
  8965.         }
  8966.         if (!empty($post_data->get('customerTypes'))) {
  8967.             $find_by_query['customerTypes'] = $post_data->get('customerTypes');
  8968.         }
  8969.         return $this->render('@Sales/pages/views/view_product_catalogue.html.twig', [
  8970.             'page_title' => 'Product Catalogue View',
  8971.             'start_date' => $start_date,
  8972.             'end_date' => $end_date,
  8973.             'openFilter' => empty($post_data->keys()) ? 0,
  8974.             'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  8975.             'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  8976.             'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  8977.             'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  8978.             'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  8979.             'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  8980.             'customer' => Client::ClientTypeList($this->getDoctrine()->getManager()),
  8981. //            'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  8982.             'action_tag' => $warehouse_action_list,
  8983.             'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  8984.             'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  8985.             'qry' => $find_by_query,
  8986.             'data_searched' => $data_searched,
  8987.             'currencyTypeList' => $currencyTypeList,
  8988.             'clientTypeList' => $clientTypeList,
  8989.             'data' => [
  8990.                 'structuredData' => $structuredData,
  8991.                 'itemGroupList' => $itemGroupList,
  8992.                 'clientTypeList' => $clientTypeList,
  8993.                 'subCategoryTypeList' => $subCategoryTypeList,
  8994.                 //            'categorizationData' => $categorizationData
  8995.             ]
  8996.         ]);
  8997.     }
  8998.     public function PrintProductCatalogueAction(Request $request)
  8999.     {
  9000.         $companyId $this->getLoggedUserCompanyId($request);
  9001.         $em $this->getDoctrine()->getManager();
  9002.         //From
  9003.         $mis_data_flag 0;
  9004.         if ($request->query->has('mis_print'))
  9005.             $mis_data_flag 1;
  9006.         $company_data Company::getCompanyData($em1);
  9007.         $document_mark = array(
  9008.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  9009.             'copy' => ''
  9010.         );
  9011.         //upto
  9012.         $start_date $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
  9013.         $end_date $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' ' 23:59:59.999')) : new \DateTime();
  9014.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), '');;
  9015.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  9016.         $data_searched = [];
  9017.         if ($request->isMethod('POST'))
  9018.             $method 'POST';
  9019.         else
  9020.             $method 'GET';
  9021.         $post_data $method == 'POST' $request->request $request->query;
  9022.         $data_searched = [];
  9023. //        return new JsonResponse($data_searched);
  9024.         // Fetch flat product data
  9025.         $filterQry $em->getRepository('ApplicationBundle:ProductMrp')->createQueryBuilder('Pr')
  9026.             ->select('Pr.productMrpId''Pr.priceByCustomerTypes''Pr.currency''Pr.minOrderQty')
  9027.             ->addSelect('P.id as pid''P.igId''P.categoryId''P.name''P.defaultImage''P.unitTypeId''P.subCategoryId''P.productCode''P.note''P.productFdm')
  9028.             ->addSelect('IG.id as igId''IG.name as itemGroupName')
  9029.             ->addSelect('PC.name as productCategory')
  9030.             //        ->addSelect('PSc.name as subCategoryName')
  9031.             ->addSelect('B.id as brandId''B.name as brandCompanyName''B.image as brandCompanyImage')
  9032.             ->leftJoin('ApplicationBundle:InvProducts''P''WITH''Pr.productId = P.id')
  9033.             ->leftJoin('ApplicationBundle:InvItemGroup''IG''WITH''P.igId = IG.id')
  9034.             ->leftJoin('ApplicationBundle:InvProductCategories''PC''WITH''P.categoryId = PC.id')
  9035.             //        ->leftJoin('ApplicationBundle:InvProductSubCategories', 'PSc', 'WITH', 'P.subCategoryId = PSc.id')
  9036.             ->leftJoin('ApplicationBundle:BrandCompany''B''WITH''P.brandCompany = B.id')
  9037.             ->leftJoin('ApplicationBundle:ClientType''C''WITH''Pr.priceByCustomerTypes = C.clientTypeId');
  9038.         if (!empty($post_data->get('productId'))) {
  9039.             $filterQry->andWhere(' P.id in (' implode(','$post_data->get('productId')) . ') ');
  9040.         }
  9041.         if (!empty($post_data->get('igId'))) {
  9042.             $filterQry->andWhere(' P.igId in (' implode(','$post_data->get('igId')) . ') ');
  9043.         }
  9044.         if (!empty($post_data->get('categoryId'))) {
  9045.             $filterQry->andWhere(' P.categoryId in (' implode(','$post_data->get('categoryId')) . ') ');
  9046.         }
  9047.         if (!empty($post_data->get('brandId'))) {
  9048.             $filterQry->andWhere(' P.brandCompany in (' implode(','$post_data->get('brandId')) . ') ');
  9049.         }
  9050. //        if(!empty($post_data->get('priceByCustomerTypes'))){
  9051. //            $filterQry -> andWhere('Pr.priceByCustomerTypes in ('. implode(',', $post_data->get('priceByCustomerTypes')) .') ');
  9052. //        }
  9053.         if (!empty($post_data->get('currency'))) {
  9054.             $filterQry->andWhere(' Pr.currency in (' implode(','$post_data->get('currency')) . ') ');
  9055.         }
  9056.         $productMrp $filterQry
  9057.             ->getQuery()
  9058.             ->getResult();
  9059.         //ClientType name
  9060.         $clientTypes $em->getRepository('ApplicationBundle:ClientType')
  9061.             ->createQueryBuilder('ct')
  9062.             ->select('ct.clientTypeId, ct.name')
  9063.             ->getQuery()
  9064.             ->getArrayResult();
  9065.         $clientTypeList = [];
  9066.         foreach ($clientTypes as $ct) {
  9067.             $clientTypeList[$ct['clientTypeId']] = $ct['name'];
  9068.         }
  9069.         //UOM name
  9070.         $unitTypes $em->getRepository('ApplicationBundle:UnitType')
  9071.             ->createQueryBuilder('ut')
  9072.             ->select('ut.id, ut.name')
  9073.             ->getQuery()
  9074.             ->getArrayResult();
  9075.         $unitTypeList = [];
  9076.         foreach ($unitTypes as $ut) {
  9077.             $unitTypeList[$ut['id']] = $ut['name'];
  9078.         }
  9079.         //Item group
  9080.         $itemGroups $em->getRepository('ApplicationBundle:InvItemGroup')
  9081.             ->createQueryBuilder('ig')
  9082.             ->select('ig.id, ig.name, ig.categorizationData')
  9083.             ->getQuery()
  9084.             ->getArrayResult();
  9085.         $itemGroupList = [];
  9086.         foreach ($itemGroups as $igData) {
  9087.             $itemGroupList[$igData['id']] = array(
  9088.                 'name' => $igData['name'],
  9089.                 'categorizationData' => json_decode($igData['categorizationData'], true) ??
  9090.                     [
  9091.                         ["alias" => "Category""en" => 1"inc" => "1"],
  9092.                         ["alias" => "Sub Category""en" => 1"inc" => "1"],
  9093.                     ]
  9094.             );
  9095.         }
  9096.         //Currency name
  9097.         $currencyTypes $em->getRepository('ApplicationBundle:Currencies')
  9098.             ->createQueryBuilder('cu')
  9099.             ->select('cu.currencyId, cu.name')
  9100.             ->getQuery()
  9101.             ->getArrayResult();
  9102.         $currencyTypeList = [];
  9103.         foreach ($currencyTypes as $cu) {
  9104.             $currencyTypeList[$cu['currencyId']] = $cu['name'];
  9105.         }
  9106.         //Sub-Category
  9107.         $subCategoryTypes $em->getRepository('ApplicationBundle:InvProductSubCategories')
  9108.             ->createQueryBuilder('sc')
  9109.             ->select('sc.id, sc.name')
  9110.             ->getQuery()
  9111.             ->getArrayResult();
  9112.         $subCategoryTypeList = [];
  9113.         foreach ($subCategoryTypes as $sc) {
  9114.             $subCategoryTypeList[$sc['id']] = $sc['name'];
  9115.         }
  9116.         // Restructure: Item Group â†’ Brand â†’ Products
  9117.         $structuredData = [];
  9118.         foreach ($productMrp as $row) {
  9119.             $igId $row['igId'];
  9120.             $brandId $row['brandId'];
  9121.             if (!isset($structuredData[$igId])) {
  9122.                 $structuredData[$igId] = [
  9123.                     'name' => $row['itemGroupName'],
  9124.                     //                    'categorizationData' => json_decode($row['categorizationData'], true) ??
  9125.                     //
  9126.                     //
  9127.                     //                        [
  9128.                     //                            ["alias" => "Category", "en" => 1, "inc" => "1"],
  9129.                     //                            ["alias" => "Sub Category", "en" => 1, "inc" => "1"],
  9130.                     //
  9131.                     //
  9132.                     //                        ]
  9133.                     //                    ,
  9134.                     'brands' => []
  9135.                 ];
  9136.             }
  9137.             if (!isset($structuredData[$igId]['brands'][$brandId])) {
  9138.                 $structuredData[$igId]['brands'][$brandId] = [
  9139.                     'name' => $row['brandCompanyName'],
  9140.                     'image' => $row['brandCompanyImage'],
  9141.                     'products' => []
  9142.                 ];
  9143.             }
  9144.             $unitTypeName = isset($unitTypeList[$row['unitTypeId']]) ? $unitTypeList[$row['unitTypeId']] : 'N/A';
  9145.             $currencyName = isset($currencyTypeList[$row['currency']]) ? $currencyTypeList[$row['currency']] : 'N/A';
  9146.             // Parse productFdm string for SZ, SO, ST, SH values
  9147.             preg_match('/SZ(\d+)/'$row['productFdm'], $szMatch);
  9148.             preg_match('/SO(\d+)/'$row['productFdm'], $soMatch);
  9149.             preg_match('/ST(\d+)/'$row['productFdm'], $stMatch);
  9150.             preg_match('/SH(\d+)/'$row['productFdm'], $shMatch);
  9151.             $subCategoryZeroId $szMatch[1] ?? null;
  9152.             $subCategoryOneId $soMatch[1] ?? null;
  9153.             $subCategoryTwoId $stMatch[1] ?? null;
  9154.             $subCategoryThreeId $shMatch[1] ?? null;
  9155.             $structuredData[$igId]['brands'][$brandId]['products'][] = [
  9156.                 'pid' => $row['pid'],
  9157.                 'name' => $row['name'],
  9158.                 'category' => $row['productCategory'],
  9159.                 'minOrderQty' => $row['minOrderQty'],
  9160.                 'note' => $row['note'],
  9161.                 'productCode' => $row['productCode'],
  9162.                 'unitTypeId' => $row['unitTypeId'],
  9163.                 'unitTypeName' => $unitTypeName,
  9164.                 'currency' => $row['currency'],
  9165.                 'currencyName' => $currencyName,
  9166.                 'productFdm' => $row['productFdm'],
  9167.                 //                'categorizationData' => $row['categorizationData'],
  9168.                 //                'price' => $row['priceByCustomerTypes'],
  9169.                 'priceByCustomerTypes' => json_decode($row['priceByCustomerTypes'], true), // decode JSON
  9170.                 'defaultImage' => $row['defaultImage'], // include image
  9171.                 // Sub-category types extracted
  9172.                 'subCategoryZero' => [
  9173.                     'id' => $subCategoryZeroId,
  9174.                     'name' => $subCategoryTypeList[$subCategoryZeroId] ?? 'N/A'
  9175.                 ],
  9176.                 'subCategoryOne' => [
  9177.                     'id' => $subCategoryOneId,
  9178.                     'name' => $subCategoryTypeList[$subCategoryOneId] ?? 'N/A'
  9179.                 ],
  9180.                 'subCategoryTwo' => [
  9181.                     'id' => $subCategoryTwoId,
  9182.                     'name' => $subCategoryTypeList[$subCategoryTwoId] ?? 'N/A'
  9183.                 ],
  9184.                 'subCategoryThree' => [
  9185.                     'id' => $subCategoryThreeId,
  9186.                     'name' => $subCategoryTypeList[$subCategoryThreeId] ?? 'N/A'
  9187.                 ],
  9188.             ];
  9189.         }
  9190.         $find_by_query = [];
  9191.         $query_add '';
  9192. //        if($method=='POST')
  9193.         if (!empty($post_data->get('productId'))) {
  9194.             $find_by_query['productId'] = $post_data->get('productId');
  9195.         }
  9196.         if (!empty($post_data->get('currency'))) {
  9197.             $find_by_query['currency'] = $post_data->get('currency');
  9198.         }
  9199.         if (!empty($post_data->get('igId'))) {
  9200.             $find_by_query['igId'] = $post_data->get('igId');
  9201.         }
  9202.         if (!empty($post_data->get('categoryId'))) {
  9203.             $find_by_query['categoryId'] = $post_data->get('categoryId');
  9204.         }
  9205.         if (!empty($post_data->get('brandId'))) {
  9206.             $find_by_query['brandId'] = $post_data->get('brandId');
  9207.         }
  9208.         if (!empty($post_data->get('actionTagId'))) {
  9209.             $find_by_query['actionTagId'] = $post_data->get('actionTagId');
  9210.         }
  9211.         if (!empty($post_data->get('customerTypes'))) {
  9212.             $find_by_query['customerTypes'] = $post_data->get('customerTypes');
  9213.         }
  9214.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  9215.             $html $this->renderView(
  9216.                 '@Sales/pages/views/print_product_catalogue.html.twig',
  9217.                 array(
  9218.                     //full array here
  9219.                     'pdf' => true,
  9220.                     'page_title' => 'Product Catalogue Print',
  9221.                     'export' => 'pdf,print',
  9222.                     //            'doc_name' => Product Cata
  9223.                     'start_date' => $start_date,
  9224.                     'end_date' => $end_date,
  9225.                     'openFilter' => empty($post_data->keys()) ? 0,
  9226.                     'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  9227.                     'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  9228.                     'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  9229.                     'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  9230.                     'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  9231.                     'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  9232.                     //            'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  9233.                     'action_tag' => $warehouse_action_list,
  9234.                     'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  9235.                     'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  9236.                     'qry' => $find_by_query,
  9237.                     'data_searched' => $data_searched,
  9238.                     'document_mark_image' => $document_mark['original'],
  9239.                     'company_name' => $company_data->getName(),
  9240.                     'company_data' => $company_data,
  9241.                     'company_address' => $company_data->getAddress(),
  9242.                     'company_image' => $company_data->getImage(),
  9243.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  9244.                     'currencyTypeList' => $currencyTypeList,
  9245.                     'clientTypeList' => $clientTypeList,
  9246.                     'data' => [
  9247.                         'structuredData' => $structuredData,
  9248.                         'itemGroupList' => $itemGroupList,
  9249.                         'clientTypeList' => $clientTypeList,
  9250.                         'subCategoryTypeList' => $subCategoryTypeList,
  9251.                         //            'categorizationData' => $categorizationData
  9252.                     ],
  9253.                     'red' => 0
  9254.                 )
  9255.             );
  9256.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  9257.                 //                'orientation' => 'landscape',
  9258.                 //                'enable-javascript' => true,
  9259.                 //                'javascript-delay' => 1000,
  9260.                 'no-stop-slow-scripts' => false,
  9261.                 'no-background' => false,
  9262.                 'lowquality' => false,
  9263.                 'encoding' => 'utf-8',
  9264.                 //            'images' => true,
  9265.                 //            'cookie' => array(),
  9266.                 'dpi' => 300,
  9267.                 'image-dpi' => 300,
  9268.                 //                'enable-external-links' => true,
  9269.                 //                'enable-internal-links' => true
  9270.             ));
  9271.             return new Response(
  9272.                 $pdf_response,
  9273.                 200,
  9274.                 array(
  9275.                     'Content-Type' => 'application/pdf',
  9276.                     'Content-Disposition' => 'attachment; filename="Product_catalogue.pdf"'
  9277.                 )
  9278.             );
  9279.         }
  9280.         return $this->render('@Sales/pages/views/print_product_catalogue.html.twig', [
  9281.             'page_title' => 'Product Catalogue Print',
  9282.             'export' => 'pdf,print',
  9283.             //            'doc_name' => Product Cata
  9284.             'start_date' => $start_date,
  9285.             'end_date' => $end_date,
  9286.             'openFilter' => empty($post_data->keys()) ? 0,
  9287.             'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
  9288.             'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
  9289.             'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
  9290.             'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  9291.             'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
  9292.             'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
  9293.             //            'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
  9294.             'action_tag' => $warehouse_action_list,
  9295.             'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
  9296.             'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
  9297.             'qry' => $find_by_query,
  9298.             'data_searched' => $data_searched,
  9299.             'document_mark_image' => $document_mark['original'],
  9300.             'company_name' => $company_data->getName(),
  9301.             'company_data' => $company_data,
  9302.             'company_address' => $company_data->getAddress(),
  9303.             'company_image' => $company_data->getImage(),
  9304.             'invoice_footer' => $company_data->getInvoiceFooter(),
  9305.             'currencyTypeList' => $currencyTypeList,
  9306.             'data' => [
  9307.                 'structuredData' => $structuredData,
  9308.                 'itemGroupList' => $itemGroupList,
  9309.                 'clientTypeList' => $clientTypeList,
  9310.                 'subCategoryTypeList' => $subCategoryTypeList,
  9311.                 //            'categorizationData' => $categorizationData
  9312.             ]
  9313.         ]);
  9314.     }
  9315.     //    public function ViewProductCatalogueAction(Request $request)
  9316.     //    {
  9317.     //        $companyId = $this->getLoggedUserCompanyId($request);
  9318.     //        $em = $this->getDoctrine()->getManager();
  9319.     //
  9320.     //        // Fetch flat product data using Doctrine
  9321.     //        $productMrp = $em->getRepository('ApplicationBundle:ProductMrp')->createQueryBuilder('Pr')
  9322.     //            ->select('Pr.productMrpId', 'Pr.priceByCustomerTypes')
  9323.     //            ->addSelect('P.id as pid', 'P.igId', 'P.categoryId', 'P.name')
  9324.     //            ->addSelect('IG.id as igId', 'IG.name as itemGroupName')
  9325.     //            ->addSelect('PC.name as productCategory')
  9326.     //            ->addSelect('PSc.name as subCategoryName')
  9327.     //            ->addSelect('B.id as brandId', 'B.name as brandCompanyName')
  9328.     //            ->leftJoin('ApplicationBundle:InvProducts', 'P', 'WITH', 'Pr.productId = P.id')
  9329.     //            ->leftJoin('ApplicationBundle:InvItemGroup', 'IG', 'WITH', 'P.igId = IG.id')
  9330.     //            ->leftJoin('ApplicationBundle:InvProductCategories', 'PC', 'WITH', 'P.categoryId = PC.id')
  9331.     //            ->leftJoin('ApplicationBundle:InvProductSubCategories', 'PSc', 'WITH', 'P.subCategoryId = PSc.id')
  9332.     //            ->leftJoin('ApplicationBundle:BrandCompany', 'B', 'WITH', 'P.brandCompany = B.id')
  9333.     //            ->getQuery()
  9334.     //            ->getResult();
  9335.     //
  9336.     //        // Restructure flat product list into nested structure
  9337.     //        $structuredData = [];
  9338.     //
  9339.     //        foreach ($productMrp as $row) {
  9340.     //            $igId = $row['igId'];
  9341.     //            $brandId = $row['brandId'];
  9342.     //
  9343.     //            if (!isset($structuredData[$igId])) {
  9344.     //                $structuredData[$igId] = [
  9345.     //                    'name' => $row['itemGroupName'],
  9346.     //                    'childDataList' => [],
  9347.     //                ];
  9348.     //            }
  9349.     //
  9350.     //            if (!isset($structuredData[$igId]['childDataList'][$brandId])) {
  9351.     //                $structuredData[$igId]['childDataList'][$brandId] = [
  9352.     //                    'name' => $row['brandCompanyName'],
  9353.     //                    'childDataList' => [],
  9354.     //                ];
  9355.     //            }
  9356.     //
  9357.     //            $structuredData[$igId]['childDataList'][$brandId]['childDataList'][] = [
  9358.     //                'pid' => $row['pid'],
  9359.     //                'igId' => $row['igId'],
  9360.     //                'brandId' => $row['brandId'],
  9361.     //                'categoryId' => $row['categoryId'],
  9362.     //                'name' => $row['name'],
  9363.     //            ];
  9364.     //        }
  9365.     //
  9366.     //        return new JsonResponse([
  9367.     //            'structuredData' => $structuredData
  9368.     //        ]);
  9369.     //
  9370.     //        // ---- Optional: Theme/columns setup if needed later in rendering ----
  9371.     //        $themeId = $request->get('themeId', 1);
  9372.     //        $defaultColEnabled = range(1, 31);
  9373.     //        $columnsEnabled = $request->get('columnsEnabled', $defaultColEnabled);
  9374.     //        $config = $request->get('config', []);
  9375.     //
  9376.     //        if (is_string($columnsEnabled)) $columnsEnabled = json_decode($columnsEnabled, true);
  9377.     //        if (is_string($config)) $config = json_decode($config, true);
  9378.     //        if ($config == null) $config = [];
  9379.     //        if ($columnsEnabled == null) $columnsEnabled = [];
  9380.     //    }
  9381.     //    public function ViewProductCatalogueAction(Request $request)
  9382.     //    {
  9383.     //
  9384.     ////        $companyId = $this->getLoggedUserCompanyId($request);
  9385.     ////        $em = $this->getDoctrine()->getManager();
  9386.     ////
  9387.     ////        $q = $this->getDoctrine()
  9388.     ////            ->getRepository('ApplicationBundle:ProductMrp')
  9389.     ////            ->findBy(
  9390.     ////                array(
  9391.     ////                    'status' => GeneralConstant::ACTIVE,
  9392.     //////                    'CompanyId' => $companyId
  9393.     ////                )
  9394.     ////            );
  9395.     ////        $stage_list = array(
  9396.     ////            0 => 'Pending',
  9397.     ////            1 => 'Pending',
  9398.     ////            2 => 'Complete',
  9399.     ////            4 => 'Partial',
  9400.     ////        );
  9401.     ////        $data = [];
  9402.     ////        foreach ($q as $entry) {
  9403.     ////            $data[] = array(
  9404.     //////                'doc_date'=>$entry->getProductMrpDocumentDate(),
  9405.     //////                'id'=>$entry->getProductMrpDocumentId(),
  9406.     ////                'productId' => $entry->getProductId(),
  9407.     ////                'doc_id' => $entry->getProductMrpDocumentId(),
  9408.     ////                'doc_hash' => $entry->getDocumentHash(),
  9409.     ////                'price_data' => json_decode($entry->getPriceByCustomerTypes(), true),
  9410.     ////
  9411.     ////
  9412.     ////            );
  9413.     ////        }
  9414.     ////
  9415.     ////        return $this->render('@Sales/pages/views/view_product_catalogue_list.html.twig',
  9416.     ////            array(
  9417.     ////                'page_title' => 'Product Catalogue List',
  9418.     ////                'data' => $data,
  9419.     //////                'clientTypeList' => Client::ClientTypeList($em, $companyId),
  9420.     ////                'productList' => Inventory::ProductList($em, $companyId, 1)
  9421.     ////
  9422.     ////            )
  9423.     ////        );
  9424.     //
  9425.     //
  9426.     //        //Alternate
  9427.     //        $companyId = $this->getLoggedUserCompanyId($request);
  9428.     //        $em = $this->getDoctrine()->getManager();
  9429.     //
  9430.     //
  9431.     //        $productMrp = $em->getRepository('ApplicationBundle:ProductMrp')->createQueryBuilder('Pr')
  9432.     //            ->select('Pr.productMrpId', 'Pr.priceByCustomerTypes')// all write together
  9433.     //            ->addSelect('IG.name as itemGroupName', 'PSc.name as subCategoryName', 'PC.name as productCategory', 'B.name as brandCompanyName')// separate wise
  9434.     //            ->leftJoin('ApplicationBundle:InvProducts', 'P', 'WITH', 'Pr.productId = P.id')
  9435.     //            ->leftJoin('ApplicationBundle:InvItemGroup', 'IG', 'WITH', 'P.igId = IG.id')
  9436.     //            ->leftJoin('ApplicationBundle:InvProductCategories', 'PC', 'WITH', 'P.categoryId = PC.id')
  9437.     //            ->leftJoin('ApplicationBundle:InvProductSubCategories', 'PSc', 'WITH', 'P.subCategoryId = PSc.id')
  9438.     //            ->leftJoin('ApplicationBundle:BrandCompany', 'B', 'WITH', 'P.brandCompany = B.id')
  9439.     ////            ->where('E.id = :employeeId')
  9440.     ////            ->setParameter('employeeId', $employeeId)
  9441.     //            ->getQuery()//upper query
  9442.     //            ->getResult();//execute
  9443.     //
  9444.     //        // If image is null or empty, assign empty string
  9445.     ////        if (empty($employeeDetails['image'])) {
  9446.     ////            $employeeDetails['image'] = '';
  9447.     ////        }
  9448.     //
  9449.     //        return new JsonResponse($productMrp);
  9450.     //
  9451.     //        //Sample
  9452.     ////        $em = $this->getDoctrine()->getManager();
  9453.     ////        $session = $request->getSession();
  9454.     ////        $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
  9455.     ////
  9456.     ////        $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
  9457.     ////            ->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin', 'E.image', 'P.positionName')
  9458.     ////            ->addSelect('A.current_balance')
  9459.     ////            ->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
  9460.     ////            ->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
  9461.     ////            ->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
  9462.     ////            ->where('E.id = :employeeId')
  9463.     ////            ->setParameter('employeeId', $employeeId)
  9464.     ////            ->getQuery()
  9465.     ////            ->getOneOrNullResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
  9466.     ////
  9467.     ////        // If image is null or empty, assign empty string
  9468.     ////        if (empty($employeeDetails['image'])) {
  9469.     ////            $employeeDetails['image'] = '';
  9470.     ////        }
  9471.     ////
  9472.     ////        return new JsonResponse($employeeDetails);
  9473.     //
  9474.     //
  9475.     //
  9476.     //        //
  9477.     //
  9478.     //        $em = $this->getDoctrine()->getManager();
  9479.     //
  9480.     //        $companyId = $this->getLoggedUserCompanyId($request);
  9481.     //        $listData = Inventory::GetProductListForProductListAjaxAction($em, $request->isMethod('POST') ? 'POST' : 'GET', $request->request, $companyId);
  9482.     //        if ($request->isMethod('POST') && $request->request->has('returnJson')) {
  9483.     //            if ($request->query->has('dataTableQry')) {
  9484.     //                return new JsonResponse(
  9485.     //                    $listData
  9486.     //                );
  9487.     //            }
  9488.     //        }
  9489.     //
  9490.     //
  9491.     //
  9492.     //        // For theme if change later on
  9493.     //        $themeId=$request->get('themeId',1);
  9494.     //        $defaultColEnabled= array(
  9495.     //            1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,30,31
  9496.     //
  9497.     //        );
  9498.     //        $columnsEnabled=$request->get('columnsEnabled',$defaultColEnabled);
  9499.     //        $config=$request->get('config',[]);
  9500.     //        if(is_string($columnsEnabled))$columnsEnabled=json_decode($columnsEnabled,true);
  9501.     //        if(is_string($config))$config=json_decode($config,true);
  9502.     //        if($config==null)$config=[];
  9503.     //        if($columnsEnabled==null)$columnsEnabled=[];
  9504.     //        //till this
  9505.     //
  9506.     ////        return $this->render('@Inventory/pages/views/product_catalogue_list.html.twig',
  9507.     ////            array(
  9508.     ////                'page_title' => 'Product Catalogue List',
  9509.     ////                'products' => [],
  9510.     ////                //sample
  9511.     ////                'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
  9512.     ////                'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
  9513.     ////
  9514.     ////
  9515.     ////            )
  9516.     ////        );
  9517.     //
  9518.     //    }
  9519.     public function ViewProductMrpDocument(Request $request$id)
  9520.     {
  9521.         $em $this->getDoctrine()->getManager();
  9522.         $dt Package::GetProductMrpDocumentDetails($em$id);
  9523.         return $this->render(
  9524.             '@Sales/pages/views/view_product_mrp_document.html.twig',
  9525.             array(
  9526.                 'page_title' => 'View',
  9527.                 'data' => $dt,
  9528.                 'auto_created' => $dt['auto_created'],
  9529.                 'approval_data' => System::checkIfApprovalExists(
  9530.                     $em,
  9531.                     array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
  9532.                     $id,
  9533.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  9534.                 ),
  9535.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  9536.                     $this->getDoctrine()->getManager(),
  9537.                     array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
  9538.                     $id,
  9539.                     $dt['created_by'],
  9540.                     $dt['edited_by']
  9541.                 ) : []
  9542.             )
  9543.         );
  9544.     }
  9545.     public function PrintProductMrpDocument(Request $request$id)
  9546.     {
  9547.         $em $this->getDoctrine()->getManager();
  9548.         $data Package::GetProductMrpDocumentDetails($em$id);
  9549.         $company_data Company::getCompanyData($em1);
  9550.         $document_mark = array(
  9551.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  9552.             'copy' => ''
  9553.         );
  9554.         return $this->render(
  9555.             '@Sales/pages/print/product_mrp_print.html.twig',
  9556.             array(
  9557.                 'page_title' => 'Product ' $data['doc_hash'],
  9558.                 'data' => $data,
  9559.                 'document_mark_image' => $document_mark['original'],
  9560.                 'company_name' => $company_data->getName(),
  9561.                 'company_data' => $company_data,
  9562.                 'company_address' => $company_data->getAddress(),
  9563.                 'company_image' => $company_data->getImage(),
  9564.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  9565.                 'page_header' => 'New Product',
  9566.                 'document_type' => 'MRP settings',
  9567.                 'page_header_sub' => 'Add',
  9568.                 //                'type_list'=>$type_list,
  9569.                 //                'mis_data'=>$mis_data,
  9570.                 //                'mis_print'=>$mis_print,
  9571.                 'item_data' => [],
  9572.                 'received' => 2,
  9573.                 'return' => 1,
  9574.                 'total_w_vat' => 1,
  9575.                 'total_vat' => 1,
  9576.                 'total_wo_vat' => 1,
  9577.                 'invoice_id' => 'abcd1234',
  9578.                 'created_by' => 'created by',
  9579.                 'created_at' => '',
  9580.                 'red' => 0,
  9581.             )
  9582.         );
  9583.     }
  9584.     public function CreateClientType(Request $request$id 0)
  9585.     {
  9586.         $cc_id '';
  9587.         $cc_name '';
  9588.         $em $this->getDoctrine()->getManager();
  9589.         $companyId $this->getLoggedUserCompanyId($request);
  9590.         if ($request->isMethod('POST')) {
  9591.             $new_cc = [];
  9592.             $regionId 0;
  9593.             //            $warehouseId = $request->request->get('warehouseId');
  9594.             if ($request->request->get('clientTypeId') != '' && $request->request->get('clientTypeId') != 0) {
  9595.                 $em $this->getDoctrine()->getManager();
  9596.                 $new_cc $this->getDoctrine()
  9597.                     ->getRepository('ApplicationBundle:ClientType')
  9598.                     ->findOneBy(
  9599.                         array(
  9600.                             'clientTypeId' => $request->request->get('clientTypeId'),
  9601.                         )
  9602.                     );
  9603.                 $new_cc->setName($request->request->get('name'));
  9604.                 //                $new_cc->setSupplierShortCode($request->request->get('supplierShortCode'));
  9605.                 $new_cc->setCompanyId($companyId);
  9606.                 //                $new_cc->setStatus(GeneralConstant::ACTIVE);
  9607.                 $em->flush();
  9608.                 $brandId $new_cc->getClientTypeId();
  9609.                 $this->addFlash(
  9610.                     'success',
  9611.                     'Type Information Updated'
  9612.                 );
  9613.             } else {
  9614.                 $new_cc = new ClientType();
  9615.                 $new_cc->setName($request->request->get('name'));
  9616.                 //                $new_cc->setSupplierShortCode($request->request->get('supplierShortCode'));
  9617.                 $new_cc->setCompanyId($companyId);
  9618.                 //                $new_cc->setStatus(GeneralConstant::ACTIVE);
  9619.                 $em->persist($new_cc);
  9620.                 $em->flush();
  9621.                 $brandId $new_cc->getClientTypeId();
  9622.                 $this->addFlash(
  9623.                     'success',
  9624.                     'Type Added'
  9625.                 );
  9626.             }
  9627.         }
  9628.         $extData = [];
  9629.         if ($id != 0) {
  9630.             $extData $this->getDoctrine()
  9631.                 ->getRepository('ApplicationBundle:ClientType')
  9632.                 ->findOneBy(
  9633.                     array(
  9634.                         'clientTypeId' => $id
  9635.                     )
  9636.                 );
  9637.             //            $cc_data_list = [];
  9638.             //            foreach ($cc_data as $value) {
  9639.             //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  9640.             //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  9641.             //
  9642.             //                if ($value->getSupplierCategoryId() == $id) {
  9643.             //                    $cc_id = $value->getSupplierCategoryId();
  9644.             //                    $cc_name = $value->getName();
  9645.             //                }
  9646.             //            }
  9647.         }
  9648.         return $this->render(
  9649.             '@Sales/pages/input_forms/client_type.html.twig',
  9650.             array(
  9651.                 'page_title' => 'Client Type',
  9652.                 'typeList' => $this->getDoctrine()
  9653.                     ->getRepository('ApplicationBundle:ClientType')
  9654.                     ->findBy(
  9655.                         array(
  9656.                             'CompanyId' => $companyId
  9657.                         )
  9658.                     ),
  9659.                 'extData' => $extData,
  9660.                 //                'headList'=>Accounts::getParentLedgerHeads($em),
  9661.                 //                'warehouseList'=>Inventory::WarehouseList($em),
  9662.                 //                'sales_person_list'=>Client::SalesPersonList($this->getDoctrine()->getManager()),
  9663.                 //                'countryList'=>SalesOrderM::Co
  9664.             )
  9665.         );
  9666.     }
  9667.     public function CreateNewSecondarySaleOrder(Request $request$id 0)
  9668.     {
  9669.         $em $this->getDoctrine()->getManager();
  9670.         $hasProject 0;
  9671.         $extId $id;
  9672.         $projectId 0;
  9673.         $companyId $this->getLoggedUserCompanyId($request);
  9674.         if ($request->query->has('projectId'))
  9675.             if ($request->query->get('projectId') != 0) {
  9676.                 $hasProject 1;
  9677.                 $projectId $request->query->get('projectId');
  9678.             }
  9679.         //testing direct sale
  9680.         if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
  9681.             //            if($request->request->has('getInitialData'))
  9682.             $em $this->getDoctrine()->getManager();
  9683.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesOrder']; //change
  9684.             $dochash $request->request->get('docHash'); //change
  9685.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  9686.             $approveRole $request->request->get('approvalRole');
  9687.             $approveHash $request->request->get('approvalHash');
  9688.             if (!DocValidation::isInsertable(
  9689.                 $em,
  9690.                 $entity_id,
  9691.                 $dochash,
  9692.                 $loginId,
  9693.                 $approveRole,
  9694.                 $approveHash,
  9695.                 $id,
  9696.                 $request->request->has('skipApprovalFlag') ? $request->request->get('skipApprovalFlag') : 0,
  9697.                 $companyId
  9698.             )) {
  9699.                 if ($request->request->has('returnJson')) {
  9700.                     return new JsonResponse(array(
  9701.                         'success' => false,
  9702.                         'documentHash' => 0,
  9703.                         'documentId' => 0,
  9704.                         'documentIdPadded' => str_pad(08'0'STR_PAD_LEFT),
  9705.                         'documentDate' => '',
  9706.                         'billIds' => [],
  9707.                         'drIds' => [],
  9708.                         'pmntTransIds' => [],
  9709.                         'viewUrl' => '',
  9710.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  9711.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  9712.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  9713.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  9714.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  9715.                     ));
  9716.                 } else
  9717.                     $this->addFlash(
  9718.                         'error',
  9719.                         'Sorry Could not insert Data.'
  9720.                     );
  9721.             } else {
  9722.                 $funcname 'SalesOrder';
  9723.                 $doc_id $extId;
  9724.                 DeleteDocument::$funcname($em$doc_id00);
  9725.                 Client::ProcessTempClients($em$companyId$clientIds = [$request->request->get('client_id'null)]);
  9726.                 $orderId SalesOrderM::CreateNewSecondarySales(
  9727.                     $this->getDoctrine()->getManager(),
  9728.                     $doc_id,
  9729.                     $request->request,
  9730.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9731.                     $this->getLoggedUserCompanyId($request)
  9732.                 );
  9733.                 //now add Approval info if not pending confirmation
  9734.                 $draftFlag $request->request->has('draftFlag') ? $request->request->has('draftFlag') : 0;
  9735.                 $clientCreatedFlag $request->request->has('clientCreatedFlag') ? $request->request->has('clientCreatedFlag') : 0;
  9736.                 $orderConfirmationPendingFlag $request->request->has('clientCreatedFlag') ? 0;
  9737.                 if ($draftFlag == && $orderConfirmationPendingFlag == 0) {
  9738.                     $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  9739.                     $approveRole 1;  //created
  9740.                     $options = array(
  9741.                         'notification_enabled' => $this->container->getParameter('notification_enabled'),
  9742.                         'notification_server' => $this->container->getParameter('notification_server'),
  9743.                         'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  9744.                         'url' => $this->generateUrl(
  9745.                             GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
  9746.                         )
  9747.                     );
  9748.                     System::setApprovalInfo(
  9749.                         $this->getDoctrine()->getManager(),
  9750.                         $options,
  9751.                         array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  9752.                         $orderId,
  9753.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  9754.                         $request->request->get('salesMethod'1),
  9755.                         $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0
  9756.                     );
  9757.                     System::createEditSignatureHash(
  9758.                         $this->getDoctrine()->getManager(),
  9759.                         array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  9760.                         $orderId,
  9761.                         $loginId,
  9762.                         $approveRole,
  9763.                         $request->request->get('approvalHash')
  9764.                     );
  9765.                 }
  9766.                 $url $this->generateUrl(
  9767.                     'view_sales_order'
  9768.                 );
  9769.                 System::AddNewNotification(
  9770.                     $this->container->getParameter('notification_enabled'),
  9771.                     $this->container->getParameter('notification_server'),
  9772.                     $request->getSession()->get(UserConstants::USER_APP_ID),
  9773.                     $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  9774.                     "Sales Order : " $dochash " Has Been Created And is Under Processing",
  9775.                     'pos',
  9776.                     System::getPositionIdsByDepartment($emGeneralConstant::SALES_DEPARTMENT),
  9777.                     'success',
  9778.                     $url "/" $orderId,
  9779.                     "Sales Order"
  9780.                 );
  9781.                 if ($request->request->has('returnJson')) {
  9782.                     $order $em->getRepository('ApplicationBundle:SecondarySalesOrder')->findOneBy(
  9783.                         array(
  9784.                             'salesOrderId' => $orderId///material
  9785.                         )
  9786.                     );
  9787.                     $clnt $em->getRepository('ApplicationBundle:AccClients')->findOneBy(
  9788.                         array(
  9789.                             'clientId' => $order->getClientId(), ///material
  9790.                         )
  9791.                     );
  9792.                     $drs $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  9793.                         array(
  9794.                             'salesOrderId' => $orderId///material
  9795.                         )
  9796.                     );
  9797.                     $bills $em->getRepository('ApplicationBundle:SecondarySalesInvoice')->findBy(
  9798.                         array(
  9799.                             'salesOrderId' => $orderId///material
  9800.                         )
  9801.                     );
  9802.                     $billIds = [];
  9803.                     $drIds = [];
  9804.                     $pmntTransIds = [];
  9805.                     foreach ($bills as $bill)
  9806.                         $billIds[] = $bill->getSalesInvoiceId();
  9807.                     foreach ($drs as $dr)
  9808.                         $drIds[] = $dr->getDeliveryReceiptId();
  9809.                     $pmntTransIds json_decode($order->getOrderPaymentReceiptVoucherIds(), true);
  9810.                     if ($pmntTransIds == null)
  9811.                         $pmntTransIds = [];
  9812.                     return new JsonResponse(array(
  9813.                         'success' => true,
  9814.                         'documentHash' => $order->getDocumentHash(),
  9815.                         'documentId' => $orderId,
  9816.                         'documentIdPadded' => str_pad($orderId8'0'STR_PAD_LEFT),
  9817.                         'documentDate' => $order->getSalesOrderDate()->format('Y-m-d'),
  9818.                         'deliveryProcessType' => $order->getDeliveryProcessType(),
  9819.                         'paymentProcessType' => $order->getPaymentProcessType(),
  9820.                         'clientId' => $order->getClientId(),
  9821.                         'clientMail' => $clnt->getEmail() == null '' $clnt->getEmail(),
  9822.                         'billIds' => $billIds,
  9823.                         'drIds' => $drIds,
  9824.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  9825.                         'pmntTransIds' => $pmntTransIds,
  9826.                         'viewUrl' => $url "/" $orderId,
  9827.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  9828.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  9829.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  9830.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  9831.                     ));
  9832.                 } else {
  9833.                     $this->addFlash(
  9834.                         'success',
  9835.                         'New Sales order Created'
  9836.                     );
  9837.                     return $this->redirect($url "/" $orderId);
  9838.                 }
  9839.             }
  9840.         }
  9841.         $projectList = [];
  9842.         $projectListArray = [];
  9843.         //        $dt=ProjectM::GetProjectListById($em);
  9844.         $dt $em->getRepository('ApplicationBundle:Project')->findBy(
  9845.             array(
  9846.                 'projectStep' => array_flip(ProjectConstant::$projectSteps)['SALES ORDER'], ///material
  9847.                 'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
  9848.                 'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  9849.             ),
  9850.             array('projectDate' => 'desc')
  9851.         );
  9852.         //        $projectList=$dt;
  9853.         foreach ($dt as $entry) {
  9854.             $projectListArray[] = array(
  9855.                 'id' => $entry->getProjectId(),
  9856.                 'value' => $entry->getProjectId(),
  9857.                 'name' => $entry->getProjectName(),
  9858.                 'text' => $entry->getProjectName(),
  9859.                 'clientId' => $entry->getClientId(),
  9860.             );
  9861.             $projectList[$entry->getProjectId()] = array(
  9862.                 'id' => $entry->getProjectId(),
  9863.                 'value' => $entry->getProjectId(),
  9864.                 'name' => $entry->getProjectName(),
  9865.                 'text' => $entry->getProjectName(),
  9866.                 'clientId' => $entry->getClientId(),
  9867.             );
  9868.             //            $projectList[]=array(
  9869.             //                'id'=>$entry['id'],
  9870.             //                'value'=>$entry['id'],
  9871.             //                'name'=>$entry['projectName'],
  9872.             //                'text'=>$entry['projectName'],
  9873.             //                'clientId'=>$entry['clientId'],
  9874.             //            );
  9875.             //
  9876.         }
  9877.         $productListArray = [];
  9878.         $subCategoryListArray = [];
  9879.         $categoryListArray = [];
  9880.         $igListArray = [];
  9881.         $unitListArray = [];
  9882.         $brandListArray = [];
  9883.         $productList Inventory::ProductList($em$companyId1);
  9884.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  9885.         $categoryList Inventory::ProductCategoryList($em$companyId);
  9886.         $igList Inventory::ItemGroupList($em$companyId);
  9887.         $unitList Inventory::UnitTypeList($em);
  9888.         $brandList Inventory::GetBrandList($em$companyId);
  9889.         foreach ($productList as $product$productListArray[] = $product;
  9890.         foreach ($categoryList as $product$categoryListArray[] = $product;
  9891.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  9892.         foreach ($igList as $product$igListArray[] = $product;
  9893.         foreach ($unitList as $product$unitListArray[] = $product;
  9894.         foreach ($brandList as $product$brandListArray[] = $product;
  9895.         $extDocData = [];
  9896.         $extDocDataDetails = [];
  9897.         if ($extId == 0) {
  9898.         } else {
  9899.             $extDoc $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  9900.                 array(
  9901.                     'salesOrderId' => $extId///material
  9902.                 )
  9903.             );
  9904.             //now if its not editable, redirect to view
  9905.             if ($extDoc) {
  9906.                 if ($extDoc->getEditFlag() != 1) {
  9907.                     $url $this->generateUrl(
  9908.                         'view_sales_order'
  9909.                     );
  9910.                     return $this->redirect($url "/" $extId);
  9911.                 } else {
  9912.                     $extDocData $extDoc;
  9913.                     $extDocDataDetails $em->getRepository('ApplicationBundle:SalesOrderItem')->findOneBy(
  9914.                         array(
  9915.                             'salesOrderId' => $extId///material
  9916.                         )
  9917.                     );
  9918.                 }
  9919.             } else {
  9920.             }
  9921.         }
  9922.         $clientListById Client::GetExistingSecondaryClientList($em$companyId);
  9923.         $userId $request->getSession()->get(UserConstants::USER_ID);
  9924.         $warehouse_action_list GeneralConstant::$warehouse_action_list;
  9925.         $warehouse_action_list_array GeneralConstant::$warehouse_action_list_array;
  9926.         //        $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
  9927.         $userBranchIdList $request->getSession()->get('branchIdList');
  9928.         if ($userBranchIdList == null$userBranchIdList = [];
  9929.         $userBranchId $request->getSession()->get('branchId');
  9930.         $dataArray = array(
  9931.             'page_title' => 'New Sales Order',
  9932.             //                'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  9933.             'ClientDetails' => Client::SecondaryClientDetailsAgainstID($em$companyId, []),
  9934.             'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($this->getDoctrine()->getManager()),
  9935.             'ClientListById' => $clientListById,
  9936.             'users' => Users::getUserListById($em),
  9937.             'userRestrictions' => Users::getUserApplicationAccessSettings($em$userId)['options'],
  9938.             'hasProject' => $hasProject,
  9939.             'warehouseList' => Inventory::WarehouseList($em),
  9940.             'warehouseListArray' => Inventory::WarehouseListArray($em),
  9941.             'warehouseActionList' => $warehouse_action_list,
  9942.             'warehouseActionListArray' => $warehouse_action_list_array,
  9943.             'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  9944.             //now restrictions
  9945.             //                'canUseOwnPrice'=>0,
  9946.             //                'canSkipProductId'=>0,
  9947.             //                'canUseZeroPrice'=>0,
  9948.             //                'canSetDiscount'=>0,
  9949.             //                'maxIndividualDiscountAllowed'=>0,
  9950.             //                'maxGrossDiscountAllowed'=>0,
  9951.             'projectId' => $projectId,
  9952.             'projectList' => $projectList,
  9953.             'productList' => $productList,
  9954.             'productListArray' => $productListArray,
  9955.             'projectListArray' => $projectListArray,
  9956.             'subCategoryList' => $subCategoryList,
  9957.             'categoryList' => $categoryList,
  9958.             'igList' => $igList,
  9959.             'unitList' => $unitList,
  9960.             'unitListArray' => $unitListArray,
  9961.             'brandList' => $brandList,
  9962.             'extDocDataDetails' => $extDocDataDetails,
  9963.             'extDocData' => $extDocData,
  9964.             'currencyList' => Inventory::CurrencyList($em),
  9965.             'extData' => $extDocData,
  9966.             'ExistingClients' => $clientListById,
  9967.             'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  9968.             'clientTypeList' => Client::ClientTypeList($em$companyId),
  9969.             'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  9970.             'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  9971.             'salesMethodList' => SalesConstant::$salesMethod,
  9972.             'deliveryProcessTypes' => SalesConstant::$deliveryProcessType,
  9973.             'paymentProcessTypes' => SalesConstant::$paymentProcessType,
  9974.             'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  9975.             'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  9976.             'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  9977.             'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  9978.             'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  9979.             'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  9980.             'sales_person_list' => Client::SalesPersonList($em),
  9981.             'stage_list' => ProjectM::GetWorkStageList($em$companyId),
  9982.             'regionList' => Client::RegionList($em$companyId),
  9983.             'regionListForClient' => Client::RegionListForClientEntry($em$companyId),
  9984.             'branchList' => Client::BranchList($em$companyId, [], $userBranchIdList),
  9985.             'userBranchIdList' => $userBranchIdList,
  9986.             'userBranchId' => $userBranchId,
  9987.             'headList' => Accounts::HeadList($em),
  9988.         );
  9989.         //json
  9990.         if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) //        if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
  9991.         {
  9992.             $dataArray['success'] = true;
  9993.             return new JsonResponse(
  9994.                 $dataArray
  9995.             );
  9996.         }
  9997.         if ($request->query->has('showPos'))
  9998.             return $this->render(
  9999.                 '@Sales/pages/input_forms/new_sales_order_pos.html.twig',
  10000.                 $dataArray
  10001.             );
  10002.         else
  10003.             return $this->render(
  10004.                 '@Sales/pages/input_forms/new_secondary_sales.html.twig',
  10005.                 $dataArray
  10006.             );
  10007.     }
  10008.     public function SecondarySalesOrderList(Request $request)
  10009.     {
  10010.         $em $this->getDoctrine()->getManager();
  10011.         $session $request->getSession();
  10012.         $companyId $this->getLoggedUserCompanyId($request);
  10013.         $userRestrictions = [];
  10014.         $selectiveDocumentsFlag 0;
  10015.         $allowedLoginIds = [];
  10016.         $salesPersonList Client::SalesPersonList($this->getDoctrine()->getManager());
  10017.         $clientList SalesOrderM::GetClientList($em, [], $companyId);
  10018.         $userType $session->get(UserConstants::USER_TYPE);
  10019.         $userId $session->get(UserConstants::USER_ID);
  10020.         $orderQryArray = array('status' => GeneralConstant::ACTIVE);
  10021.         if ($userType == UserConstants::USER_TYPE_CLIENT) {
  10022.             $orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
  10023.         }
  10024.         if ($userType == UserConstants::USER_TYPE_GENERAL) {
  10025.             $userRestrictions Users::getUserApplicationAccessSettings($em$userId)['options'];
  10026.             $selectiveDocumentsFlag 1//by default will show only selective
  10027.             if (isset($userRestrictions['canSeeAllSo'])) {
  10028.                 if ($userRestrictions['canSeeAllSo'] == 1) {
  10029.                     $selectiveDocumentsFlag 0;
  10030.                 }
  10031.             }
  10032.             if ($selectiveDocumentsFlag == 1) {
  10033.                 $allowedLoginIds MiscActions::getLoginIdsByUserId($em$session->get(UserConstants::USER_ID));
  10034.             }
  10035.         }
  10036.         if (!$request->request->has('returnJson')) {
  10037.             //if not for mobile skip the pending orders
  10038.             $orderQryArray['orderConfirmationPendingFlag'] = [0null];
  10039.             $orderQryArray['draftFlag'] = [0null];
  10040.         }
  10041.         $q $this->getDoctrine()
  10042.             ->getRepository('ApplicationBundle:SecondarySalesOrder')
  10043.             ->findBy(
  10044.                 $orderQryArray,
  10045.                 array(
  10046.                     'salesOrderDate' => 'DESC',
  10047.                     //                    'salesOrderId'=>'DESC'
  10048.                 )
  10049.             );
  10050.         $stage_list = ['Initiated''Pending''Complete''Partial''Pending Tag''Pending Confirm.'];
  10051.         $d 9;
  10052.         $data = [];
  10053.         foreach ($q as $entry) {
  10054.             $clientId $entry->getClientId();
  10055.             //            $client=$em->getRepository('ApplicationBundle:AccClients')
  10056.             //                ->findOneBy(
  10057.             //                    array(
  10058.             //                        'clientId'=>$clientId
  10059.             //                    )
  10060.             //                );
  10061.             if ($selectiveDocumentsFlag == 1) {
  10062.                 //1st check by sales person
  10063.                 $spCheckFailed 1;
  10064.                 if (isset($salesPersonList[$entry->getSalesPersonId()])) {
  10065.                     if ($salesPersonList[$entry->getSalesPersonId()]['userId'] == $userId) {
  10066.                         $spCheckFailed 0;
  10067.                     }
  10068.                 }
  10069.                 if ($spCheckFailed == 0) {
  10070.                 } else if (in_array($entry->getCreatedLoginId(), $allowedLoginIds) || in_array($entry->getEditedLoginId(), $allowedLoginIds)) {
  10071.                 } else {
  10072.                     continue;
  10073.                 }
  10074.             }
  10075.             $data[] = array(
  10076.                 'doc_date' => $entry->getSalesOrderDate(),
  10077.                 'doc_date_str' => $entry->getSalesOrderDate()->format('F d, Y'),
  10078.                 'id' => $entry->getSalesOrderId(),
  10079.                 'doc_hash' => $entry->getDocumentHash(),
  10080.                 'sales_person_id' => $entry->getSalesPersonId(),
  10081.                 'sales_person_name' => isset($salesPersonList[$entry->getSalesPersonId()]) ? $salesPersonList[$entry->getSalesPersonId()]['name'] : '',
  10082.                 'so_amount' => $entry->getSoAmount(),
  10083.                 'orderConfirmationPendingFlag' => $entry->getOrderConfirmationPendingFlag(),
  10084.                 'draftFlag' => $entry->getDraftFlag(),
  10085.                 'client_id' => $clientId,
  10086.                 'client_name' => $clientList[$clientId]['client_name'],
  10087.                 'client_code' => $clientList[$clientId]['client_code'],
  10088.                 'client_contact_number' => $clientList[$clientId]['contact_number'],
  10089.                 'client_alternate_code' => $clientList[$clientId]['client_alternate_code'],
  10090.                 'stage' => $stage_list[$entry->getStage()]
  10091.             );
  10092.         }
  10093.         if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
  10094.             return new JsonResponse(
  10095.                 array(
  10096.                     'page_title' => 'Sales Orders ',
  10097.                     'data' => $data,
  10098.                     'userType' => $userType,
  10099.                     'orderConfirmationPendingFlag' => 0,
  10100.                     'users' => Users::getUserListById($em),
  10101.                     'sales_person_list' => $salesPersonList,
  10102.                     'success' => empty($data) ? false true
  10103.                 )
  10104.             );
  10105.         }
  10106.         return $this->render(
  10107.             '@Sales/pages/list/secondary_sales_list.html.twig',
  10108.             array(
  10109.                 'page_title' => 'Sales Orders',
  10110.                 'data' => $data,
  10111.                 'orderConfirmationPendingFlag' => 0,
  10112.                 'users' => Users::getUserListById($em),
  10113.                 'sales_person_list' => $salesPersonList,
  10114.             )
  10115.         );
  10116.     }
  10117.     public function ViewSecondarySalesOrder(Request $request$id)
  10118.     {
  10119.         $em $this->getDoctrine()->getManager();
  10120.         $mis_data_flag 0;
  10121.         if ($request->query->has('mis_print'))
  10122.             $mis_data_flag 1;
  10123.         $dt SalesOrderM::GetSecondarySalesOrderDetails($em$id$mis_data_flag);
  10124.         //        $companyId = $this->getLoggedUserCompanyId($request);
  10125.         $companyId $dt['so_data']->getCompanyId();
  10126.         $company_data Company::getCompanyData($em$companyId);
  10127.         $forwardToMailAddress '';
  10128.         if ($request->query->has('forwardToMailAddress'))
  10129.             $forwardToMailAddress $request->query->get('forwardToMailAddress');
  10130.         if ($forwardToMailAddress == '')
  10131.             $forwardToMailAddress $dt['client_data']->getEmail();
  10132.         return $this->render(
  10133.             '@Sales/pages/views/secondary_sales_order_view.html.twig',
  10134.             array(
  10135.                 'page_title' => 'View',
  10136.                 'data' => $dt,
  10137.                 'forwardToMailAddress' => $forwardToMailAddress,
  10138.                 'company_name' => $company_data->getName(),
  10139.                 'company_data' => $company_data,
  10140.                 'company_address' => $company_data->getAddress(),
  10141.                 'company_image' => $company_data->getImage(),
  10142.                 //                'invoice_footer' => $company_data->getInvoiceFooter(),
  10143.                 'projectList' => ProjectM::GetProjectListById($em),
  10144.                 'auto_created' => $dt['auto_created'],
  10145.                 'approval_data' => System::checkIfApprovalExists(
  10146.                     $em,
  10147.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  10148.                     $id,
  10149.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  10150.                 ),
  10151.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  10152.                     $this->getDoctrine()->getManager(),
  10153.                     array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
  10154.                     $id,
  10155.                     $dt['created_by'],
  10156.                     $dt['edited_by']
  10157.                 ) : [],
  10158.                 'users' => Users::getUserListById($em),
  10159.                 'ExistingClients' => Client::GetExistingClientList($em$companyId),
  10160.                 'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  10161.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  10162.                 'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  10163.                 'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  10164.                 'salesMethodList' => SalesConstant::$salesMethod,
  10165.                 'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  10166.                 'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  10167.                 'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  10168.                 'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  10169.                 'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  10170.                 'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  10171.                 'sales_person_list' => Client::SalesPersonList($em),
  10172.                 'stage_list' => ProjectM::GetWorkStageList($em$companyId),
  10173.                 'regionList' => Client::RegionList($em$companyId),
  10174.                 'regionListForClient' => Client::RegionListForClientEntry($em$companyId),
  10175.                 'branchList' => Client::BranchList($em$companyId),
  10176.                 'headList' => Accounts::HeadList($em),
  10177.                 'positionList' => Position::getPositionList($em)
  10178.             )
  10179.         );
  10180.     }
  10181.     public function PrintSecondarySalesOrder(Request $request$id)
  10182.     {
  10183.         $em $this->getDoctrine()->getManager();
  10184.         $companyId $this->getLoggedUserCompanyId($request);
  10185.         //mis options flag
  10186.         $mis_data_flag 0;
  10187.         if ($request->query->has('mis_print') || $request->query->has('includeMisFlag'))
  10188.             $mis_data_flag 1;
  10189.         $data SalesOrderM::GetSecondarySalesOrderDetails($em$id$mis_data_flag);
  10190.         //print common options starts
  10191.         $printTypesEnabled = ['office_copy']; //default
  10192.         $sendAsPdf 0;
  10193.         $printType 'office_copy';
  10194.         if ($request->query->has('printType'))
  10195.             $printType $request->query->get('printType');
  10196.         if ($request->query->has('forwardToEmail')) {
  10197.             $printType 'forwardToEmail';
  10198.             //            $sendAsPdf=1;
  10199.         }
  10200.         if ($request->query->has('attachPdf')) {
  10201.             $printType 'forwardToEmail';
  10202.             $sendAsPdf $request->query->get('attachPdf');
  10203.         }
  10204.         if ($printType == 'all_copy') {
  10205.             $printTypesEnabled = ['office_copy''party_copy'];
  10206.         }
  10207.         if ($printType == 'forwardToEmail') {
  10208.             $printTypesEnabled = ['party_copy'];
  10209.         }
  10210.         $forwardToMailAddress '';
  10211.         if ($request->query->has('forwardToMailAddress'))
  10212.             $forwardToMailAddress $request->query->get('forwardToMailAddress');
  10213.         if ($forwardToMailAddress == '')
  10214.             $forwardToMailAddress $data['client_data']->getEmail();
  10215.         //print spec options end
  10216.         $company_data Company::getCompanyData($em$companyId);
  10217.         $document_mark = array(
  10218.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  10219.             'copy' => ''
  10220.         );
  10221.         if (($request->query->has('pdf') || $printType == 'forwardToEmail') && $this->get('knp_snappy.pdf')) {
  10222.             $html '';
  10223.             $pdf_response '';
  10224.             $dataForRender = array(
  10225.                 //full array here
  10226.                 'page_title' => 'Sales Order ' $data['doc_hash'],
  10227.                 'pdf' => true,
  10228.                 'forwardToMailAddress' => $forwardToMailAddress,
  10229.                 'data' => $data,
  10230.                 'printTypesEnabled' => $printTypesEnabled,
  10231.                 'sendAsPdf' => $sendAsPdf,
  10232.                 'export' => 'pdf,print,sendForward',
  10233.                 'document_mark_image' => $document_mark['original'],
  10234.                 'company_name' => $company_data->getName(),
  10235.                 'company_data' => $company_data,
  10236.                 'company_address' => $company_data->getAddress(),
  10237.                 'company_image' => $company_data->getImage(),
  10238.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10239.                 'page_header' => 'New Product',
  10240.                 'document_type' => 'Sales Order',
  10241.                 'page_header_sub' => 'Add',
  10242.                 'projectList' => ProjectM::GetProjectListById($em),
  10243.                 'ExistingClients' => Client::GetExistingClientList($em$companyId),
  10244.                 'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  10245.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  10246.                 'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  10247.                 'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  10248.                 'salesMethodList' => SalesConstant::$salesMethod,
  10249.                 'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  10250.                 'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  10251.                 'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  10252.                 'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  10253.                 'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  10254.                 'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  10255.                 'sales_person_list' => Client::SalesPersonList($em),
  10256.                 'stage_list' => ProjectM::GetWorkStageList($em$companyId),
  10257.                 'regionList' => Client::RegionList($em$companyId),
  10258.                 'regionListForClient' => Client::RegionListForClientEntry($em$companyId),
  10259.                 'branchList' => Client::BranchList($em$companyId),
  10260.                 'headList' => Accounts::HeadList($em),
  10261.                 'positionList' => Position::getPositionList($em),
  10262.                 'item_data' => [],
  10263.                 'received' => 2,
  10264.                 'return' => 1,
  10265.                 'total_w_vat' => 1,
  10266.                 'total_vat' => 1,
  10267.                 'total_wo_vat' => 1,
  10268.                 'invoice_id' => 'abcd1234',
  10269.                 'created_by' => 'created by',
  10270.                 'created_at' => '',
  10271.                 'red' => 0,
  10272.                 'users' => Users::getUserListById($em)
  10273.             );
  10274.             if ($request->query->has('pdf') || $sendAsPdf == 1) {
  10275.                 //genertae the html only if pdf is returned or attached
  10276.                 $html $this->renderView(
  10277.                     '@Sales/pages/print/secondary_sales_order_print.html.twig',
  10278.                     array(
  10279.                         //full array here
  10280.                         'page_title' => 'Sales Order ' $data['doc_hash'],
  10281.                         'pdf' => true,
  10282.                         'forwardToMailAddress' => $forwardToMailAddress,
  10283.                         //                    'convertImageToBase64'=>true,
  10284.                         'data' => $data,
  10285.                         'printTypesEnabled' => $printTypesEnabled,
  10286.                         'sendAsPdf' => $sendAsPdf,
  10287.                         'export' => 'pdf,print',
  10288.                         'document_mark_image' => $document_mark['original'],
  10289.                         'company_name' => $company_data->getName(),
  10290.                         'company_data' => $company_data,
  10291.                         'company_address' => $company_data->getAddress(),
  10292.                         'company_image' => $company_data->getImage(),
  10293.                         'invoice_footer' => $company_data->getInvoiceFooter(),
  10294.                         'page_header' => 'New Product',
  10295.                         'document_type' => 'Sales Order',
  10296.                         'page_header_sub' => 'Add',
  10297.                         'projectList' => ProjectM::GetProjectListById($em),
  10298.                         'ExistingClients' => Client::GetExistingClientList($em$companyId),
  10299.                         'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  10300.                         'clientTypeList' => Client::ClientTypeList($em$companyId),
  10301.                         'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  10302.                         'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  10303.                         'salesMethodList' => SalesConstant::$salesMethod,
  10304.                         'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  10305.                         'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  10306.                         'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  10307.                         'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  10308.                         'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  10309.                         'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  10310.                         'sales_person_list' => Client::SalesPersonList($em),
  10311.                         'stage_list' => ProjectM::GetWorkStageList($em$companyId),
  10312.                         'regionList' => Client::RegionList($em$companyId),
  10313.                         'regionListForClient' => Client::RegionListForClientEntry($em$companyId),
  10314.                         'branchList' => Client::BranchList($em$companyId),
  10315.                         'headList' => Accounts::HeadList($em),
  10316.                         'positionList' => Position::getPositionList($em),
  10317.                         //                'type_list'=>$type_list,
  10318.                         //                'mis_data'=>$mis_data,
  10319.                         //                'mis_print'=>$mis_print,
  10320.                         'item_data' => [],
  10321.                         'received' => 2,
  10322.                         'return' => 1,
  10323.                         'total_w_vat' => 1,
  10324.                         'total_vat' => 1,
  10325.                         'total_wo_vat' => 1,
  10326.                         'invoice_id' => 'abcd1234',
  10327.                         'created_by' => 'created by',
  10328.                         'created_at' => '',
  10329.                         'red' => 0,
  10330.                         'users' => Users::getUserListById($em)
  10331.                     )
  10332.                 );
  10333.                 $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  10334.                     //                'orientation' => 'landscape',
  10335.                     //                'enable-javascript' => true,
  10336.                     //                'javascript-delay' => 1000,
  10337.                     'no-stop-slow-scripts' => false,
  10338.                     'no-background' => false,
  10339.                     'lowquality' => false,
  10340.                     'encoding' => 'utf-8',
  10341.                     //            'images' => true,
  10342.                     //            'cookie' => array(),
  10343.                     'dpi' => 300,
  10344.                     'image-dpi' => 300,
  10345.                     //                'enable-external-links' => true,
  10346.                     //                'enable-internal-links' => true
  10347.                 ));
  10348.             }
  10349.             if ($printType == 'forwardToEmail') {
  10350.                 $bodyHtml '';
  10351.                 $bodyTemplate '@Sales/pages/print/secondary_sales_order_print.html.twig';
  10352.                 $bodyData $dataForRender;
  10353.                 $attachments = [];
  10354.                 if ($sendAsPdf == 1) {
  10355.                     $attachments[] = array(
  10356.                         'file' => $pdf_response,
  10357.                         'fileName' => 'Order#' str_pad($id8'0'STR_PAD_LEFT) . '.pdf',
  10358.                         'fileType' => 'application/pdf'
  10359.                     );
  10360.                 }
  10361.                 //                    $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
  10362.                 $new_mail $this->get('mail_module');
  10363.                 $new_mail->sendMyMail(array(
  10364.                     'senderHash' => '_SALES_ORDERS_',
  10365.                     //                        'senderHash'=>'_CUSTOM_',
  10366.                     'forwardToMailAddress' => $forwardToMailAddress,
  10367.                     'subject' => $company_data->getName() . ' New Order#' str_pad($id8'0'STR_PAD_LEFT),
  10368.                     'fileName' => 'Order#' str_pad($id8'0'STR_PAD_LEFT) . '.pdf',
  10369.                     'attachments' => $attachments,
  10370.                     'toAddress' => $forwardToMailAddress,
  10371.                     //                        'fromAddress'=>'sales@entity.innobd.com',
  10372.                     //                        'userName'=>'sales@entity.innobd.com',
  10373.                     //                        'password'=>'Y41dh8g0112',
  10374.                     //                        'smtpServer'=>'smtp.hostinger.com',
  10375.                     //                        'smtpPort'=>587,
  10376.                     //                        'emailBody'=>$bodyHtml,
  10377.                     'mailTemplate' => $bodyTemplate,
  10378.                     'templateData' => $bodyData,
  10379.                     'embedCompanyImage' => 1,
  10380.                     'companyId' => $companyId,
  10381.                     'companyImagePath' => $company_data->getImage()
  10382.                 ));
  10383.                 return new JsonResponse(
  10384.                     array(
  10385.                         'success' => true
  10386.                     )
  10387.                 );
  10388.             } else {
  10389.                 return new Response(
  10390.                     $pdf_response,
  10391.                     200,
  10392.                     array(
  10393.                         'Content-Type' => 'application/pdf',
  10394.                         'Content-Disposition' => 'attachment; filename="sales_order_' $id '.pdf"'
  10395.                     )
  10396.                 );
  10397.             }
  10398.         }
  10399.         return $this->render(
  10400.             '@Sales/pages/print/secondary_sales_order_print.html.twig',
  10401.             array(
  10402.                 'page_title' => 'Sales Order ' $data['doc_hash'],
  10403.                 'data' => $data,
  10404.                 //                'convertImageToBase64'=>true,
  10405.                 'printTypesEnabled' => $printTypesEnabled,
  10406.                 'sendAsPdf' => $sendAsPdf,
  10407.                 'forwardToMailAddress' => $forwardToMailAddress,
  10408.                 'export' => 'pdf,print,sendForward',
  10409.                 'document_mark_image' => $document_mark['original'],
  10410.                 'company_name' => $company_data->getName(),
  10411.                 'company_data' => $company_data,
  10412.                 'company_address' => $company_data->getAddress(),
  10413.                 'company_image' => $company_data->getImage(),
  10414.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  10415.                 'page_header' => 'Sales Order',
  10416.                 'document_type' => 'Sales Order',
  10417.                 'page_header_sub' => 'Add',
  10418.                 'projectList' => ProjectM::GetProjectListById($em),
  10419.                 'ExistingClients' => Client::GetExistingClientList($em$companyId),
  10420.                 'priceList' => Inventory::ProductPriceListByProductId($em$companyId),
  10421.                 'clientTypeList' => Client::ClientTypeList($em$companyId),
  10422.                 'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
  10423.                 'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
  10424.                 'salesMethodList' => SalesConstant::$salesMethod,
  10425.                 'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
  10426.                 'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
  10427.                 'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
  10428.                 'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
  10429.                 'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
  10430.                 'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
  10431.                 'sales_person_list' => Client::SalesPersonList($em),
  10432.                 'stage_list' => ProjectM::GetWorkStageList($em$companyId),
  10433.                 'regionList' => Client::RegionList($em$companyId),
  10434.                 'regionListForClient' => Client::RegionListForClientEntry($em$companyId),
  10435.                 'branchList' => Client::BranchList($em$companyId),
  10436.                 'headList' => Accounts::HeadList($em),
  10437.                 'positionList' => Position::getPositionList($em),
  10438.                 //                'type_list'=>$type_list,
  10439.                 //                'mis_data'=>$mis_data,
  10440.                 //                'mis_print'=>$mis_print,
  10441.                 'item_data' => [],
  10442.                 'received' => 2,
  10443.                 'return' => 1,
  10444.                 'total_w_vat' => 1,
  10445.                 'total_vat' => 1,
  10446.                 'total_wo_vat' => 1,
  10447.                 'invoice_id' => 'abcd1234',
  10448.                 'created_by' => 'created by',
  10449.                 'created_at' => '',
  10450.                 'red' => 0,
  10451.                 'users' => Users::getUserListById($em)
  10452.             )
  10453.         );
  10454.     }
  10455.     public function CreateSecondaryClient(Request $request$id 0)
  10456.     {
  10457.         $exClientId $id;
  10458.         if ($exClientId == 0)
  10459.             $exClientId $request->query->has("ex_c_id") ? $request->query->get("ex_c_id") : null;
  10460.         $em $this->getDoctrine()->getManager();
  10461.         $companyId $this->getLoggedUserCompanyId($request);
  10462.         $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10463.         if ($request->isMethod('POST')) {
  10464.             if ($request->request->get('exClientID'false)) {
  10465.                 $IFUpdated Client::UpdateSecondaryClient(
  10466.                     $em,
  10467.                     $this->getLoggedUserCompanyId($request),
  10468.                     $request->request->get('exClientID'),
  10469.                     $request->request->get('clientName'),
  10470.                     $request->request->get('contactPersonName'),
  10471.                     $request->request->get('clientDue') == '' $request->request->get('clientDue'),
  10472.                     $request->request->get('initialOpeningBalance') == '' $request->request->get('initialOpeningBalance'),
  10473.                     $request->request->get('salesPersonID'),
  10474.                     $request->request->get('type'),
  10475.                     $request->request->get('regionId'),
  10476.                     $request->request->get('countryId'),
  10477.                     $request->request->get('geographicalRegionId'),
  10478.                     $request->request->get('clientNumericalCode'),
  10479.                     $request->request->get('clientAreaWiseCode'),
  10480.                     $request->request->get('clientShortCode'),
  10481.                     $request->request->get('clientAlternateCode'),
  10482.                     0,
  10483.                     //                    $request->request->get('divisionId'),
  10484.                     $request->request->get('addressContact'),
  10485.                     $request->request->get('contactNumber'),
  10486.                     $request->request->get('shippingAddress'),
  10487.                     $request->request->get('billingAddress'),
  10488.                     $request->request->get('email'),
  10489.                     $request->request->get('fax'),
  10490.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  10491.                 );
  10492.                 if ($IFUpdated) {
  10493.                     $this->addFlash(
  10494.                         'success',
  10495.                         'Client Updated'
  10496.                     );
  10497.                 } else {
  10498.                     $this->addFlash(
  10499.                         'error',
  10500.                         'Client have not been updated'
  10501.                     );
  10502.                 }
  10503.                 //                return $this->redirectToRoute("create_client");
  10504.             } else {
  10505.                 Client::CreateNewSecondaryClient(
  10506.                     $em,
  10507.                     $this->getLoggedUserCompanyId($request),
  10508.                     $request->request->get('clientName'),
  10509.                     $request->request->get('clientDue') == '' $request->request->get('clientDue'),
  10510.                     $request->request->get('initialOpeningBalance') == '' $request->request->get('initialOpeningBalance'),
  10511.                     $request->request->get('contactPersonName'),
  10512.                     $request->request->get('salesPersonID'),
  10513.                     $request->request->get('type'),
  10514.                     $request->request->get('regionId'),
  10515.                     $request->request->get('countryId'),
  10516.                     $request->request->get('geographicalRegionId'),
  10517.                     $request->request->get('clientNumericalCode'),
  10518.                     $request->request->get('clientAreaWiseCode'),
  10519.                     $request->request->get('clientShortCode'),
  10520.                     $request->request->get('clientAlternateCode'),
  10521.                     //                    $request->request->get('divisionId'),
  10522.                     0,
  10523.                     $request->request->get('addressContact'),
  10524.                     $request->request->get('contactNumber'),
  10525.                     $request->request->get('shippingAddress'),
  10526.                     $request->request->get('billingAddress'),
  10527.                     $request->request->get('email'),
  10528.                     $request->request->get('fax'),
  10529.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  10530.                 );
  10531.             }
  10532.             Client::ProcessTempClients($em$companyId);
  10533.         }
  10534.         return $this->render(
  10535.             '@Sales/pages/input_forms/ceate_secondary_client.html.twig',
  10536.             array(
  10537.                 'page_title' => 'New Client',
  10538.                 'existingClientID' => $exClientId,
  10539.                 'client_types' => Client::ClientTypeList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10540.                 'region_data' => Client::RegionListForClientEntry($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
  10541.                 'geographical_region_data' => Client::GeographicalRegionListForClientEntry($this->getDoctrine()->getManager(), 19$this->getLoggedUserCompanyId($request)),
  10542.                 'division_list' => Client::DivisionList($this->getDoctrine()->getManager()),
  10543.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  10544.                 'sales_person_list_array' => Client::SalesPersonListArray($this->getDoctrine()->getManager()),
  10545.             )
  10546.         );
  10547.     }
  10548.     public function SecondaryClientList(Request $request)
  10549.     {
  10550.         $em $this->getDoctrine()->getManager();
  10551.         $allowed_ids = [];
  10552.         $companyId $this->getLoggedUserCompanyId($request);
  10553.         $listData SalesOrderM::GetClientListForSecondaryClientList($em$request->isMethod('POST') ? 'POST' 'GET'$request->request$companyId);
  10554.         if ($request->isMethod('POST')) {
  10555.             if ($request->query->has('dataTableQry')) {
  10556.                 return new JsonResponse(
  10557.                     $listData
  10558.                 );
  10559.             }
  10560.         }
  10561.         return $this->render(
  10562.             '@Sales/pages/list/secondary_client_list.html.twig',
  10563.             //         return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
  10564.             array(
  10565.                 'page_title' => 'Client List',
  10566.                 'data' => SalesOrderM::GetSecondaryClientList($em, [], $companyId),
  10567.                 'client_types' => Client::GetClientType($em$companyId),
  10568.                 'region_list' => Client::RegionList($em$companyId),
  10569.                 'geographical_region_list' => Client::GeographicalRegionList($em$companyId)
  10570.             )
  10571.         );
  10572.     }
  10573.     public function AddSubWarehouse(Request $request$id 0)
  10574.     {
  10575.         $em $this->getDoctrine()->getManager();
  10576.         $companyId $this->getLoggedUserCompanyId($request);
  10577.         $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10578.         if ($request->isMethod('POST')) {
  10579.             $new_cc = [];
  10580.             $regionId 0;
  10581.             $warehouseId $request->request->get('warehouseId');
  10582.             $createAutomatically $request->request->has('createAutomatically') ? $request->request->get('createAutomatically') : 0;
  10583.             $invParentHead 0;
  10584.             $inv_parent_data $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  10585.                 'name' => 'inventory_parent'
  10586.             ));
  10587.             if ($inv_parent_data)
  10588.                 $invParentHead $inv_parent_data->getData();
  10589.             if ($request->request->get('warehouseActionId') != '' && $request->request->get('warehouseActionId') != 0) {
  10590.                 $em $this->getDoctrine()->getManager();
  10591.                 $subwarehouse $this->getDoctrine()
  10592.                     ->getRepository('ApplicationBundle:WarehouseAction')
  10593.                     ->findOneBy(
  10594.                         array(
  10595.                             'id' => $request->request->get('warehouseActionId'),
  10596.                         )
  10597.                     );
  10598.                 $AccHeadID $request->request->get('accountsHeadId''_UNCHANGED_');
  10599.                 if ($AccHeadID == '_UNCHANGED_')
  10600.                     $AccHeadID $subwarehouse->getAccountsHeadId();
  10601.                 else {
  10602.                     if ($createAutomatically == && $invParentHead != 0) {
  10603.                         $AccHeadID Accounts::CreateNewHead($emGeneralConstant::OPENING_YEAR$invParentHead'Stock of ' $request->request->get('name'), ''00'dr'$loginId);
  10604.                     }
  10605.                 }
  10606.                 $subwarehouse->setName($request->request->get('name'));
  10607.                 $subwarehouse->setCompanyId($companyId);
  10608.                 $subwarehouse->setStatus(1);
  10609.                 $subwarehouse->setAccountsHeadId($AccHeadID);
  10610.                 $subwarehouse->setReplacementAllowed($request->request->get('replacementAllowed'0));
  10611.                 $subwarehouse->setDeliveryAllowed($request->request->get('deliveryAllowed'0));
  10612.                 $subwarehouse->setSellAllowed($request->request->get('sellAllowed'0));
  10613.                 $subwarehouse->setCreatedLoginId($loginId);
  10614.                 $em->persist($subwarehouse);
  10615.                 $em->flush();
  10616.                 $inv_head_data $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  10617.                     'name' => 'warehouse_action_' $subwarehouse->getId()
  10618.                 ));
  10619.                 if (!empty($inv_head_data)) {
  10620.                     $inv_head_data->setData($AccHeadID);
  10621.                     $em->flush();
  10622.                 } else {
  10623.                     $inv_head_data = new AccSettings();
  10624.                     $inv_head_data->setName('warehouse_action_' $subwarehouse->getId());
  10625.                     $inv_head_data->setData($AccHeadID);
  10626.                     $em->persist($inv_head_data);
  10627.                     $em->flush();
  10628.                 }
  10629.                 $this->addFlash(
  10630.                     'success',
  10631.                     'Sub Warehouse Information Updated'
  10632.                 );
  10633.             } else {
  10634.                 $subwarehouse = new Warehouse();
  10635.                 $AccHeadID $request->request->get('accountsHeadId''_UNCHANGED_');
  10636.                 if ($createAutomatically == && $invParentHead != 0) {
  10637.                     $AccHeadID Accounts::CreateNewHead($emGeneralConstant::OPENING_YEAR$invParentHead'Stock of ' $request->request->get('name'), ''00'dr'$loginId);
  10638.                 }
  10639.                 $subwarehouse->setName($request->request->get('name'));
  10640.                 $subwarehouse->setCompanyId($companyId);
  10641.                 $subwarehouse->setStatus(1);
  10642.                 $subwarehouse->setAccountsHeadId($AccHeadID);
  10643.                 $subwarehouse->setReplacementAllowed($request->request->get('replacementAllowed'0));
  10644.                 $subwarehouse->setDeliveryAllowed($request->request->get('deliveryAllowed'0));
  10645.                 $subwarehouse->setSellAllowed($request->request->get('sellAllowed'0));
  10646.                 $subwarehouse->setCreatedLoginId($loginId);
  10647.                 $em->persist($subwarehouse);
  10648.                 $em->flush();
  10649.                 $inv_head_data $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
  10650.                     'name' => 'warehouse_action_' $subwarehouse->getId()
  10651.                 ));
  10652.                 if (!empty($inv_head_data)) {
  10653.                     $inv_head_data->setData($AccHeadID);
  10654.                     $em->flush();
  10655.                 } else {
  10656.                     $inv_head_data = new AccSettings();
  10657.                     $inv_head_data->setName('warehouse_action_' $subwarehouse->getId());
  10658.                     $inv_head_data->setData($AccHeadID);
  10659.                     $em->persist($inv_head_data);
  10660.                     $em->flush();
  10661.                 }
  10662.                 $this->addFlash(
  10663.                     'success',
  10664.                     'Sub Warehouse Added'
  10665.                 );
  10666.             }
  10667.         }
  10668.         $extData = [];
  10669.         if ($id != 0) {
  10670.             $extData $this->getDoctrine()
  10671.                 ->getRepository('ApplicationBundle:WarehouseAction')
  10672.                 ->findOneBy(
  10673.                     array(
  10674.                         'id' => $id
  10675.                     )
  10676.                 );
  10677.             //            $cc_data_list = [];
  10678.             //            foreach ($cc_data as $value) {
  10679.             //                $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
  10680.             //                $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
  10681.             //
  10682.             //                if ($value->getSupplierCategoryId() == $id) {
  10683.             //                    $cc_id = $value->getSupplierCategoryId();
  10684.             //                    $cc_name = $value->getName();
  10685.             //                }
  10686.             //            }
  10687.         }
  10688.         $subWarehouseDetails $em->getRepository(WarehouseAction::class)->findAll();
  10689.         return $this->render(
  10690.             '@Sales/pages/input_forms/addSubWarehouse.html.twig',
  10691.             array(
  10692.                 'page_title' => 'Add Sub Warehouse',
  10693.                 'subWarehouseDetails' => $subWarehouseDetails,
  10694.                 'extData' => $extData,
  10695.             )
  10696.         );
  10697.     }
  10698.     public function AfterSalesServiceIssues(Request $request$id 0)
  10699.     {
  10700.         $em $this->getDoctrine()->getManager();
  10701.         $companyId $this->getLoggedUserCompanyId($request);
  10702.         $afterSalesServiceIssue = [];
  10703.         if ($id != 0)
  10704.             $afterSalesServiceIssue $em->getRepository('ApplicationBundle:AfterSalesServiceIssue')->findOneBy(
  10705.                 array(
  10706.                     'id' => $id
  10707.                 )
  10708.             );
  10709.         if ($request->isMethod('POST')) {
  10710.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10711.             if ($id != 0) {
  10712.             } else
  10713.                 $afterSalesServiceIssue = new AfterSalesServiceIssue();
  10714.             $afterSalesServiceIssue->setCoreIssue($request->request->get('coreIssue'));
  10715.             $afterSalesServiceIssue->setIsParent($request->request->get('isParent'));
  10716.             $afterSalesServiceIssue->setParentIssueId($request->request->get('parentIssueId'));
  10717.             $afterSalesServiceIssue->setItemGroupIds(json_encode($request->request->get('itemGroupIds')));
  10718.             //            $detailedIssue = [
  10719.             //                'detailedIssue' => $request->request->get('detailedIssue'),
  10720.             //            ];
  10721.             $preliminaryCheckList = [
  10722.                 'preliminaryCheckList' => $request->request->get('preliminaryCheckList'),
  10723.             ];
  10724.             $services = [
  10725.                 'services' => $request->request->get('services'),
  10726.                 'serviceName' => $request->request->get('serviceName'),
  10727.                 'serviceCost' => $request->request->get('serviceCost'),
  10728.                 'servicePrice' => $request->request->get('servicePrice')
  10729.             ];
  10730.             //$afterSalaesServiceIssue->setDetailedissues(json_encode($detailedIssue));
  10731.             $afterSalesServiceIssue->setPreliminaryCheckList(json_encode($preliminaryCheckList));
  10732.             $afterSalesServiceIssue->setServices(json_encode($services));
  10733.             $afterSalesServiceIssue->setMargin($request->request->get('margin'));
  10734.             $afterSalesServiceIssue->setCreatedLoginId($loginId);
  10735.             $em->persist($afterSalesServiceIssue);
  10736.             $em->flush();
  10737.             $this->addFlash(
  10738.                 'success',
  10739.                 'Issue Added'
  10740.             );
  10741.         }
  10742.         $issueDetails $em->getRepository(AfterSalesServiceIssue::class)->findAll();
  10743.         return $this->render(
  10744.             '@Sales/pages/input_forms/create_after_sales_service_issues.html.twig',
  10745.             array(
  10746.                 'page_title' => 'Create issues',
  10747.                 'issueDetails' => $issueDetails,
  10748.                 'afterSalesServiceIssue' => $afterSalesServiceIssue,
  10749.             )
  10750.         );
  10751.     }
  10752.     //    public function viewPreliminaryRegistration(){
  10753.     //        return $this->render('@Sales/pages/views/view_after_sales_service_order.html.twig',
  10754.     //            array(
  10755.     //                'page_title' => 'View Preliminary Registration',
  10756.     //            )
  10757.     //        );
  10758.     //    }
  10759.     public function AssessmentAndConfirmation(Request $request$id 0)
  10760.     {
  10761.         $em $this->getDoctrine()->getManager();
  10762.         $companyId $this->getLoggedUserCompanyId($request);
  10763.         $warehouse_action_list Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'object');;
  10764.         $warehouse_action_list_array Inventory::warehouse_action_list($em$this->getLoggedUserCompanyId($request), 'array');;
  10765.         $service Inventory::ServiceList($em$companyId);
  10766.         if ($request->isMethod('POST')) {
  10767.             $em $this->getDoctrine()->getManager();
  10768.             $entity_id array_flip(GeneralConstant::$Entity_list)['AssessmentAndConfirmation']; //change
  10769.             $dochash $request->request->get('voucherNumber'); //change
  10770.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10771.             $approveRole $request->request->get('approvalRole');
  10772.             $approveHash $request->request->get('approvalHash');
  10773.             if (!DocValidation::isInsertable(
  10774.                 $em,
  10775.                 $entity_id,
  10776.                 $dochash,
  10777.                 $loginId,
  10778.                 $approveRole,
  10779.                 $approveHash
  10780.             )) {
  10781.                 $this->addFlash(
  10782.                     'error',
  10783.                     'Sorry Couldnot insert Data.'
  10784.                 );
  10785.             } else {
  10786.                 if ($request->request->has('check_allowed'))
  10787.                     $check_allowed 1;
  10788.                 Client::ProcessTempClients($em$companyId$clientIds = [$request->request->get('returning_client_id'null)]);
  10789.                 $StID SalesOrderM::createNewAssessmentAndConfirmation(
  10790.                     $this->getDoctrine()->getManager(),
  10791.                     0,
  10792.                     $request->request,
  10793.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10794.                     $this->getLoggedUserCompanyId($request)
  10795.                 );
  10796.                 //now add Approval info
  10797.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10798.                 $approveRole 1;  //created
  10799.                 $options = array(
  10800.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  10801.                     'notification_server' => $this->container->getParameter('notification_server'),
  10802.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  10803.                     'url' => $this->generateUrl(
  10804.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AssessmentAndConfirmation']]['entity_view_route_path_name']
  10805.                     )
  10806.                 );
  10807.                 if ($request->request->get('isConfirm'0) == 1) {
  10808.                     System::setApprovalInfo(
  10809.                         $this->getDoctrine()->getManager(),
  10810.                         $options,
  10811.                         array_flip(GeneralConstant::$Entity_list)['AssessmentAndConfirmation'],
  10812.                         $StID,
  10813.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)    //journal voucher
  10814.                     );
  10815.                 }
  10816.                 System::createEditSignatureHash(
  10817.                     $this->getDoctrine()->getManager(),
  10818.                     array_flip(GeneralConstant::$Entity_list)['AssessmentAndConfirmation'],
  10819.                     $StID,
  10820.                     $loginId,
  10821.                     $approveRole,
  10822.                     $request->request->get('approvalHash')
  10823.                 );
  10824.                 $this->addFlash(
  10825.                     'success',
  10826.                     'Assessment Modified.'
  10827.                 );
  10828.                 //                $url = $this->generateUrl(
  10829.                 //                    'view_assessment_and_confirmation_info'
  10830.                 //                );
  10831.                 //                return $this->redirect($url . "/" . $StID);
  10832.             }
  10833.         }
  10834.         $slotList $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
  10835.             array(
  10836.                 'CompanyId' => $this->getLoggedUserCompanyId($request),
  10837.             )
  10838.         );
  10839.         return $this->render(
  10840.             '@Sales/pages/input_forms/assessment_and_confirmation.html.twig',
  10841.             array(
  10842.                 'page_title' => 'Assessment And Confirmation',
  10843.             )
  10844.         );
  10845.     }
  10846.     public function AssessmentAndConfirmationList(Request $request)
  10847.     {
  10848.         //        return new JsonResponse(
  10849.         //           array(
  10850.         //               'msg' => "hello"
  10851.         //           )
  10852.         //        );
  10853.         $em $this->getDoctrine()->getManager();
  10854.         $data = [];
  10855.         return $this->render(
  10856.             '@Sales/pages/list/assessment_and-confirmation_list.html.twig',
  10857.             array(
  10858.                 'page_title' => 'Assessment And Confirmation List',
  10859.                 'data' => $data,
  10860.             )
  10861.         );
  10862.     }
  10863.     public function ViewAssessmentAndConfirmation(Request $request$id 0)
  10864.     {
  10865.         return $this->render(
  10866.             '@Sales/pages/views/view_assessment_and_confirmation.html.twig',
  10867.             array(
  10868.                 'page_title' => 'View Assessment And Confirmation',
  10869.             )
  10870.         );
  10871.     }
  10872.     public function ServiceOperation(Request $request$id 0)
  10873.     {
  10874.         $em $this->getDoctrine()->getManager();
  10875.         $companyId $this->getLoggedUserCompanyId($request);
  10876.         $routeName $request->attributes->get('_route');
  10877.         if ($request->isMethod('POST')) {
  10878.             $em $this->getDoctrine()->getManager();
  10879.             $entity_id array_flip(GeneralConstant::$Entity_list)['ServiceOperation']; //change
  10880.             $dochash $request->request->get('voucherNumber'); //change
  10881.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10882.             $approveRole $request->request->get('approvalRole');
  10883.             $approveHash $request->request->get('approvalHash');
  10884.             if (!DocValidation::isInsertable(
  10885.                 $em,
  10886.                 $entity_id,
  10887.                 $dochash,
  10888.                 $loginId,
  10889.                 $approveRole,
  10890.                 $approveHash
  10891.             )) {
  10892.                 $this->addFlash(
  10893.                     'error',
  10894.                     'Sorry Couldnot insert Data.'
  10895.                 );
  10896.             } else {
  10897.                 if ($request->request->has('check_allowed'))
  10898.                     $check_allowed 1;
  10899.                 Client::ProcessTempClients($em$companyId$clientIds = [$request->request->get('returning_client_id'null)]);
  10900.                 $StID SalesOrderM::createNewServiceOperation(
  10901.                     $this->getDoctrine()->getManager(),
  10902.                     0,
  10903.                     $request->request,
  10904.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10905.                     $this->getLoggedUserCompanyId($request)
  10906.                 );
  10907.                 //now add Approval info
  10908.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10909.                 $approveRole 1;  //created
  10910.                 $options = array(
  10911.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  10912.                     'notification_server' => $this->container->getParameter('notification_server'),
  10913.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  10914.                     'url' => $this->generateUrl(
  10915.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ServiceOperation']]['entity_view_route_path_name']
  10916.                     )
  10917.                 );
  10918.                 System::setApprovalInfo(
  10919.                     $this->getDoctrine()->getManager(),
  10920.                     $options,
  10921.                     array_flip(GeneralConstant::$Entity_list)['ServiceOperation'],
  10922.                     $StID,
  10923.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  10924.                     $request->request->get('assessmentAction'1)
  10925.                 );
  10926.                 System::createEditSignatureHash(
  10927.                     $this->getDoctrine()->getManager(),
  10928.                     array_flip(GeneralConstant::$Entity_list)['ServiceOperation'],
  10929.                     $StID,
  10930.                     $loginId,
  10931.                     $approveRole,
  10932.                     $request->request->get('approvalHash')
  10933.                 );
  10934.                 $this->addFlash(
  10935.                     'success',
  10936.                     'Service Action Added.'
  10937.                 );
  10938.                 //                $url = $this->generateUrl(
  10939.                 //                    'view_service_operation'
  10940.                 //                );
  10941.                 //                return $this->redirect($url . "/" . $StID);
  10942.             }
  10943.         }
  10944.         return $this->render(
  10945.             '@Sales/pages/input_forms/service_operation.html.twig',
  10946.             array(
  10947.                 'page_title' => $routeName == 'service_operation' 'Service Operation' 'Replacement Authorization',
  10948.                 'assessmentActionType' => $routeName == 'service_operation' 2,
  10949.             )
  10950.         );
  10951.     }
  10952.     public function ServiceOperationList(Request $request)
  10953.     {
  10954.         $em $this->getDoctrine()->getManager();
  10955.         $data = [];
  10956.         return $this->render(
  10957.             '@Sales/pages/list/service_operation_list.html.twig',
  10958.             array(
  10959.                 'page_title' => 'Service Operation List',
  10960.                 'data' => $data,
  10961.             )
  10962.         );
  10963.     }
  10964.     public function ViewServiceOperation(Request $request$id 0)
  10965.     {
  10966.         return $this->render(
  10967.             '@Sales/pages/views/view_service_operation.html.twig',
  10968.             array(
  10969.                 'page_title' => 'View Service Operation',
  10970.             )
  10971.         );
  10972.     }
  10973.     public function AfterSalesServiceDelivery(Request $request$id 0)
  10974.     {
  10975.         $em $this->getDoctrine()->getManager();
  10976.         $companyId $this->getLoggedUserCompanyId($request);
  10977.         $routeName $request->attributes->get('_route');
  10978.         if ($request->isMethod('POST')) {
  10979.             $em $this->getDoctrine()->getManager();
  10980.             $entity_id array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceDelivery']; //change
  10981.             $dochash $request->request->get('voucherNumber'); //change
  10982.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  10983.             $approveRole $request->request->get('approvalRole');
  10984.             $approveHash $request->request->get('approvalHash');
  10985.             if (!DocValidation::isInsertable(
  10986.                 $em,
  10987.                 $entity_id,
  10988.                 $dochash,
  10989.                 $loginId,
  10990.                 $approveRole,
  10991.                 $approveHash
  10992.             )) {
  10993.                 $this->addFlash(
  10994.                     'error',
  10995.                     'Sorry Couldnot insert Data.'
  10996.                 );
  10997.             } else {
  10998.                 if ($request->request->has('check_allowed'))
  10999.                     $check_allowed 1;
  11000.                 Client::ProcessTempClients($em$companyId$clientIds = [$request->request->get('returning_client_id'null)]);
  11001.                 $afterSalesDeliveryObj SalesOrderM::createNewAfterSalesServiceDelivery(
  11002.                     $this->getDoctrine()->getManager(),
  11003.                     0,
  11004.                     $request->request,
  11005.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11006.                     $this->getLoggedUserCompanyId($request)
  11007.                 );
  11008.                 $StID $afterSalesDeliveryObj->getId();
  11009.                 //now add Approval info
  11010.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  11011.                 $approveRole 1;  //created
  11012.                 $options = array(
  11013.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  11014.                     'notification_server' => $this->container->getParameter('notification_server'),
  11015.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  11016.                     'url' => $this->generateUrl(
  11017.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceDelivery']]['entity_view_route_path_name']
  11018.                     )
  11019.                 );
  11020.                 $url $this->generateUrl(
  11021.                     'view_after_sales_service_delivery'
  11022.                 );
  11023.                 System::setApprovalInfo(
  11024.                     $this->getDoctrine()->getManager(),
  11025.                     $options,
  11026.                     array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceDelivery'],
  11027.                     $StID,
  11028.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11029.                     $request->request->get('assessmentAction'1)
  11030.                 );
  11031.                 System::createEditSignatureHash(
  11032.                     $this->getDoctrine()->getManager(),
  11033.                     array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceDelivery'],
  11034.                     $StID,
  11035.                     $loginId,
  11036.                     $approveRole,
  11037.                     $request->request->get('approvalHash')
  11038.                 );
  11039.                 $soId $afterSalesDeliveryObj->getSalesOrderId();
  11040.                 $afterSalesServiceOrderId $afterSalesDeliveryObj->getAfterSalesServiceOrderId();
  11041.                 if ($request->request->has('returnJson')) {
  11042.                     $order $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
  11043.                         array(
  11044.                             'salesOrderId' => $soId///material
  11045.                         )
  11046.                     );
  11047.                     $clnt $em->getRepository('ApplicationBundle:AccClients')->findOneBy(
  11048.                         array(
  11049.                             'clientId' => $order->getClientId(), ///material
  11050.                         )
  11051.                     );
  11052.                     $drs $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
  11053.                         array(
  11054.                             'salesOrderId' => $soId///material
  11055.                         )
  11056.                     );
  11057.                     $bills $em->getRepository('ApplicationBundle:SalesInvoice')->findBy(
  11058.                         array(
  11059.                             'salesOrderId' => $soId///material
  11060.                         )
  11061.                     );
  11062.                     $billIds = [];
  11063.                     $drIds = [];
  11064.                     $pmntTransIds = [];
  11065.                     foreach ($bills as $bill)
  11066.                         $billIds[] = $bill->getSalesInvoiceId();
  11067.                     foreach ($drs as $dr)
  11068.                         $drIds[] = $dr->getDeliveryReceiptId();
  11069.                     $pmntTransIds json_decode($order->getOrderPaymentReceiptVoucherIds(), true);
  11070.                     if ($pmntTransIds == null)
  11071.                         $pmntTransIds = [];
  11072.                     return new JsonResponse(array(
  11073.                         'success' => true,
  11074.                         'documentHash' => $order->getDocumentHash(),
  11075.                         'documentId' => $soId,
  11076.                         'documentIdPadded' => str_pad($soId8'0'STR_PAD_LEFT),
  11077.                         'documentDate' => $order->getSalesOrderDate()->format('Y-m-d'),
  11078.                         'deliveryProcessType' => $order->getDeliveryProcessType(),
  11079.                         'paymentProcessType' => $order->getPaymentProcessType(),
  11080.                         'clientId' => $order->getClientId(),
  11081.                         'clientMail' => $clnt->getEmail() == null '' $clnt->getEmail(),
  11082.                         'billIds' => $billIds,
  11083.                         'drIds' => $drIds,
  11084.                         'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
  11085.                         'pmntTransIds' => $pmntTransIds,
  11086.                         'viewUrl' => $url "/" $soId,
  11087.                         'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
  11088.                         'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
  11089.                         'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
  11090.                         'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
  11091.                     ));
  11092.                 } else {
  11093.                     $this->addFlash(
  11094.                         'success',
  11095.                         'Service Action Added.'
  11096.                     );
  11097.                     return $this->redirect($url "/" $soId);
  11098.                 }
  11099.                 //                $url = $this->generateUrl(
  11100.                 //                    'view_service_operation'
  11101.                 //                );
  11102.                 //                return $this->redirect($url . "/" . $StID);
  11103.             }
  11104.         }
  11105.         return $this->render(
  11106.             '@Sales/pages/input_forms/after_sales_service_delivery.html.twig',
  11107.             array(
  11108.                 'page_title' => $routeName == 'service_operation' 'After Sales Delivery' 'After Sales Delivery',
  11109.                 'assessmentActionType' => $routeName == 'after_sales_service_delivery' 2,
  11110.                 'extDocData' => [],
  11111.             )
  11112.         );
  11113.     }
  11114.     public function AfterSalesServiceDeliveryList(Request $request)
  11115.     {
  11116.         $em $this->getDoctrine()->getManager();
  11117.         $data = [];
  11118.         return $this->render(
  11119.             '@Sales/pages/list/after_sales_service_delivery_list.html.twig',
  11120.             array(
  11121.                 'page_title' => 'After Sales Delivery List',
  11122.                 'data' => $data,
  11123.             )
  11124.         );
  11125.     }
  11126.     public function ViewAfterSalesServiceDelivery(Request $request$id 0)
  11127.     {
  11128.         return $this->render(
  11129.             '@Sales/pages/views/view_after_sales_service_delivery.html.twig',
  11130.             array(
  11131.                 'page_title' => 'View After Sales Delivery',
  11132.             )
  11133.         );
  11134.     }
  11135.     public function PrintAfterSalesServiceDelivery(Request $request$id 0)
  11136.     {
  11137.         return $this->render(
  11138.             '@Sales/pages/views/print_after_sales_service_delivery.html.twig',
  11139.             array(
  11140.                 'page_title' => 'View After Sales Delivery',
  11141.             )
  11142.         );
  11143.     }
  11144.     public function CreateSalesLead(Request $request$id 0)
  11145.     {
  11146.         $em $this->getDoctrine()->getManager();
  11147.         if ($request->isMethod('POST')) {
  11148.             $em $this->getDoctrine()->getManager();
  11149.             $entity_id array_flip(GeneralConstant::$Entity_list)['SalesLead'];
  11150.             //            $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
  11151.             //                array(
  11152.             //                    'salesProposalId'=>$id, ///material
  11153.             //
  11154.             //                ),array('projectDate'=>'desc')
  11155.             //            );
  11156.             //            $client=$em->getRepository('ApplicationBundle:AccClients')->findOneBy(
  11157.             //                array(
  11158.             //                    'clientId'=>$projectData->getClientId(), ///material
  11159.             //
  11160.             //                ),array('projectDate'=>'desc')
  11161.             //            );
  11162.             $dochash $request->request->get('docHash');
  11163.             $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  11164.             $approveRole $request->request->get('approvalRole');
  11165.             $approveHash $request->request->get('approvalHash');
  11166.             if (!DocValidation::isInsertable(
  11167.                 $em,
  11168.                 $entity_id,
  11169.                 $dochash,
  11170.                 $loginId,
  11171.                 $approveRole,
  11172.                 $approveHash,
  11173.                 $id
  11174.             )) {
  11175.                 $this->addFlash(
  11176.                     'error',
  11177.                     'Sorry Could not insert Data.'
  11178.                 );
  11179.             } else {
  11180.                 //construct the files
  11181.                 $file_list = array(
  11182.                     'product_files' => [],
  11183.                     'service_files' => [],
  11184.                     'ar_files' => [],
  11185.                 );
  11186.                 //                if ($request->request->has('products')) {
  11187.                 //
  11188.                 //                    if ($request->files->has('product_reference_file')) {
  11189.                 //                        foreach ($request->files->get('product_reference_file') as $uploadedFile) {
  11190.                 //
  11191.                 //                            $path = "";
  11192.                 //
  11193.                 //                            if ($uploadedFile != null) {
  11194.                 //
  11195.                 //                                $fileName = 'p' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  11196.                 //                                $path = $fileName;
  11197.                 //                                $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
  11198.                 //                                if (!file_exists($upl_dir)) {
  11199.                 //                                    mkdir($upl_dir, 0777, true);
  11200.                 //                                }
  11201.                 //                                $file = $uploadedFile->move($upl_dir, $path);
  11202.                 //
  11203.                 //                            }
  11204.                 //                            $file_list['product_files'][] = $path;
  11205.                 //                        }
  11206.                 //                    }
  11207.                 //
  11208.                 //
  11209.                 //                }
  11210.                 //                if ($request->request->has('services')) {
  11211.                 //                    //construct the ref_files array
  11212.                 //                    $ref_files = [];
  11213.                 //                    $path = "";
  11214.                 //                    $file_path = "";
  11215.                 //                    if ($request->files->has('product_reference_file')) {
  11216.                 //                        foreach ($request->files->get('service_reference_file') as $uploadedFile) {
  11217.                 ////                        $uploadedFile = $request->files['service_reference_file_' . $request->request->get('service_uid')[$key]];
  11218.                 //                            $path = "";
  11219.                 //                            if ($uploadedFile != null) {
  11220.                 //
  11221.                 //                                $fileName = 's' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  11222.                 //                                $path = $fileName;
  11223.                 //                                $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
  11224.                 //                                if (!file_exists($upl_dir)) {
  11225.                 //                                    mkdir($upl_dir, 0777, true);
  11226.                 //                                }
  11227.                 //                                $file = $uploadedFile->move($upl_dir, $path);
  11228.                 //
  11229.                 //                            }
  11230.                 //                            $file_list['service_files'][] = $path;
  11231.                 //                        }
  11232.                 //                    }
  11233.                 //
  11234.                 //                }
  11235.                 //                if ($request->request->has('heads')) {
  11236.                 //                    //construct the ref_files array
  11237.                 //                    $ref_files = [];
  11238.                 //                    $path = "";
  11239.                 //                    $file_path = "";
  11240.                 //                    foreach ($request->files->get('ar_reference_file') as $uploadedFile) {
  11241.                 ////                        $uploadedFile = $request->files['ar_reference_file_' . $request->request->get('ar_uid')[$key]];
  11242.                 //                        $path = "";
  11243.                 //                        if ($uploadedFile != null) {
  11244.                 //
  11245.                 //                            $fileName = 'a' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
  11246.                 //                            $path = $fileName;
  11247.                 //                            $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
  11248.                 //                            if (!file_exists($upl_dir)) {
  11249.                 //                                mkdir($upl_dir, 0777, true);
  11250.                 //                            }
  11251.                 //                            $file = $uploadedFile->move($upl_dir, $path);
  11252.                 //
  11253.                 //                        }
  11254.                 //                        $file_list['ar_files'][] = $path;
  11255.                 //                    }
  11256.                 //
  11257.                 //                }
  11258. //                $document_data_id = SalesOrderM::UpdateDocumentData($this->getDoctrine()->getManager(), $request->request->get('documentDataId'), $request->request, $file_list);
  11259.                 $document_data_id 0;
  11260.                 $spId SalesOrderM::CreateNewLead(
  11261.                     $this->getDoctrine()->getManager(),
  11262.                     $id,
  11263.                     $document_data_id,
  11264.                     $request->request,
  11265.                     $dochash,
  11266.                     $file_list,
  11267.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID),
  11268.                     $this->getLoggedUserCompanyId($request)
  11269.                 );
  11270.                 //now add Approval info
  11271.                 $loginId $request->getSession()->get(UserConstants::USER_LOGIN_ID);
  11272.                 $approveRole $request->request->get('approvalRole');  //created
  11273.                 $options = array(
  11274.                     'notification_enabled' => $this->container->getParameter('notification_enabled'),
  11275.                     'notification_server' => $this->container->getParameter('notification_server'),
  11276.                     'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
  11277.                     'url' => $this->generateUrl(
  11278.                         GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesLead']]['entity_view_route_path_name']
  11279.                     )
  11280.                 );
  11281.                 $currentApprovalData System::setApprovalInfo(
  11282.                     $this->getDoctrine()->getManager(),
  11283.                     $options,
  11284.                     array_flip(GeneralConstant::$Entity_list)['SalesLead'],
  11285.                     $spId,
  11286.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  11287.                 );
  11288.                 System::createEditSignatureHash(
  11289.                     $this->getDoctrine()->getManager(),
  11290.                     array_flip(GeneralConstant::$Entity_list)['SalesLead'],
  11291.                     $spId,
  11292.                     $loginId,
  11293.                     $approveRole,
  11294.                     $request->request->get('approvalHash')
  11295.                 );
  11296.                 $this->addFlash(
  11297.                     'success',
  11298.                     'Sales Proposal Created'
  11299.                 );
  11300.                 $url $this->generateUrl(
  11301.                     'view_sales_lead'
  11302.                 );
  11303.                 if ($currentApprovalData['inProcess'] == 1) {
  11304.                     System::AddNewNotification(
  11305.                         $this->container->getParameter('notification_enabled'),
  11306.                         $this->container->getParameter('notification_server'),
  11307.                         $request->getSession()->get(UserConstants::USER_APP_ID),
  11308.                         $request->getSession()->get(UserConstants::USER_COMPANY_ID),
  11309.                         "Sales Order : " $dochash " Has Been Created And is Under Processing",
  11310.                         'pos',
  11311.                         System::getPositionIdsByDepartment($emGeneralConstant::SALES_DEPARTMENT),
  11312.                         'success',
  11313.                         $url "/" $spId,
  11314.                         "Sales Lead"
  11315.                     );
  11316.                 }
  11317.                 return $this->redirect($url "/" $spId);
  11318.             }
  11319.         }
  11320.         $projectList = [];
  11321.         $projectData = [];
  11322.         $materialData = [];
  11323.         $boqData = [];
  11324.         $wpData = [];
  11325.         $offerData = [];
  11326.         $proposalData = [];
  11327.         $leadData = [];
  11328.         $message "";
  11329.         $allDetData = [];
  11330.         $projectList $em->getRepository('ApplicationBundle:Project')->findBy(
  11331.             array(
  11332.                 'projectStep' => array_flip(ProjectConstant::$projectSteps)['PROPOSAL'], ///material
  11333.                 'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
  11334.                 'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
  11335.             ),
  11336.             array('projectDate' => 'desc')
  11337.         );
  11338.         $bgDataListByBgType = [];
  11339.         $bgDataList = [];
  11340.         if ($id != 0) {
  11341.             $leadData $em->getRepository('ApplicationBundle:SalesLead')->findOneBy(
  11342.                 array(
  11343.                     'leadId' => $id///material
  11344.                 )
  11345.             );
  11346.             //now if its not editable, redirect to view
  11347.             if ($leadData) {
  11348.                 $bgDataList json_decode($leadData->getBankGuaranteeData(), true);
  11349.                 if ($bgDataList == null)
  11350.                     $bgDataList = [];
  11351.             }
  11352.         }
  11353.         foreach ($bgDataList as $bgData) {
  11354.             $bgData['number'] = '';
  11355.             if ($bgData['id'] != 0) {
  11356.                 $bg $em->getRepository('ApplicationBundle:AccCheck')->findOneBy(
  11357.                     array(
  11358.                         'CheckId' => $bgData['id'], ///material
  11359.                     )
  11360.                 );
  11361.                 if ($bg) {
  11362.                     $bgData['amount'] = $bg->getCheckAmount();
  11363.                     $bgData['number'] = $bg->getCheckNumber();
  11364.                     $bgData['returnDateTs'] = $bg->getReturnableAfterTs();
  11365.                     $bgData['expireDateTs'] = $bg->getValidUptoTs();
  11366.                     $bgData['dateTs'] = $bg->getCheckDate()->format('U');
  11367.                 }
  11368.             }
  11369.             $bgDataListByBgType[$bgData['bankGuaranteeType']] = $bgData;
  11370.         }
  11371. //        $bgDataListByBgType=$bgDataList;
  11372. //        dump($bgDataList);
  11373. //        dump($leadData->getBankGuaranteeData());
  11374.         $qry $em->getRepository("ApplicationBundle:InvProducts")->findBy(array(
  11375.             "status" => GeneralConstant::ACTIVE,
  11376.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  11377.             'type' => //trade items
  11378.         ));
  11379.         $pl = [];
  11380.         $pl_array = [];
  11381.         foreach ($qry as $product) {
  11382.             $pl[$product->getId()] = array(
  11383.                 'text' => $product->getName(),
  11384.                 'name' => $product->getName(),
  11385.                 'id' => $product->getId(),
  11386.                 'value' => $product->getId(),
  11387.                 'purchase_price' => $product->getPurchasePrice(),
  11388.                 'sales_price' => $product->getSalesPrice(),
  11389.                 'supplier_id' => $product->getBrandCompany(),
  11390.             );
  11391.             $pl_array[] = array(
  11392.                 'text' => $product->getName(),
  11393.                 'value' => $product->getId(),
  11394.                 'name' => $product->getName(),
  11395.                 'id' => $product->getId(),
  11396.                 'purchase_price' => $product->getPurchasePrice(),
  11397.                 'sales_price' => $product->getSalesPrice(),
  11398.                 'supplier_id' => $product->getBrandCompany(),
  11399.             );
  11400.         }
  11401.         $qry $em->getRepository("ApplicationBundle:AccService")->findBy(array(
  11402.             "status" => GeneralConstant::ACTIVE,
  11403.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  11404.             //            'type'=>1//trade items
  11405.         ));
  11406.         $sl = [];
  11407.         $sl_array = [];
  11408.         foreach ($qry as $product) {
  11409.             $sl[$product->getServiceId()] = array(
  11410.                 'text' => $product->getServiceName(),
  11411.                 'value' => $product->getServiceId(),
  11412.                 'name' => $product->getServiceName(),
  11413.                 'id' => $product->getServiceId(),
  11414.             );
  11415.             $sl_array[] = array(
  11416.                 'text' => $product->getServiceName(),
  11417.                 'value' => $product->getServiceId(),
  11418.                 'name' => $product->getServiceName(),
  11419.                 'id' => $product->getServiceId(),
  11420.             );
  11421.         }
  11422.         $qry $em->getRepository("ApplicationBundle:ProjectWorkStage")->findBy(array(
  11423.             "status" => GeneralConstant::ACTIVE,
  11424.             'CompanyId' => $this->getLoggedUserCompanyId($request),
  11425.             //            'type'=>1//trade items
  11426.         ));
  11427.         $workStages = [];
  11428.         $workStages_array = [];
  11429.         foreach ($qry as $product) {
  11430.             $workStages[$product->getProjectWorkStageId()] = array(
  11431.                 'text' => $product->getStageName(),
  11432.                 'value' => $product->getProjectWorkStageId(),
  11433.                 'name' => $product->getStageName(),
  11434.                 'id' => $product->getProjectWorkStageId(),
  11435.             );
  11436.             $workStages_array[] = array(
  11437.                 'text' => $product->getStageName(),
  11438.                 'value' => $product->getProjectWorkStageId(),
  11439.                 'name' => $product->getStageName(),
  11440.                 'id' => $product->getProjectWorkStageId(),
  11441.             );
  11442.         }
  11443.         $hl Accounts::HeadList($em);
  11444.         $debug_data $request->files->get('product_reference_file');
  11445.         $companyId $this->getLoggedUserCompanyId($request);
  11446.         $productListArray = [];
  11447.         $subCategoryListArray = [];
  11448.         $categoryListArray = [];
  11449.         $igListArray = [];
  11450.         $unitListArray = [];
  11451.         $brandListArray = [];
  11452.         $productList Inventory::ProductList($em$companyId);
  11453.         $subCategoryList Inventory::ProductSubCategoryList($em$companyId);
  11454.         $categoryList Inventory::ProductCategoryList($em$companyId);
  11455.         $igList Inventory::ItemGroupList($em$companyId);
  11456.         $unitList Inventory::UnitTypeList($em);
  11457.         $brandList Inventory::GetBrandList($em$companyId);
  11458.         foreach ($productList as $product$productListArray[] = $product;
  11459.         foreach ($categoryList as $product$categoryListArray[] = $product;
  11460.         foreach ($subCategoryList as $product$subCategoryListArray[] = $product;
  11461.         foreach ($igList as $product$igListArray[] = $product;
  11462.         foreach ($unitList as $product$unitListArray[] = $product;
  11463.         foreach ($brandList as $product$brandListArray[] = $product;
  11464.         $assignedProjectSiteList = [];
  11465.         //        if($projectId==0)
  11466.         //        {
  11467.         //            $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
  11468.         //        }
  11469.         //        else
  11470.         //        {
  11471.         //
  11472.         //            $extTrans=$em->getRepository('ApplicationBundle:Project')->findOneBy(
  11473.         //                array(
  11474.         //                    'projectId'=>$projectId, ///material
  11475.         //
  11476.         //                )
  11477.         //            );
  11478.         //            $assignedProjectSiteList=ProjectM::ProjectSiteList($em,$projectId,$companyId);
  11479.         //            $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
  11480.         //
  11481.         //
  11482.         //            //now if its not editable, redirect to view
  11483.         //            if($extTrans) {
  11484.         //                if ($extTrans->getEditFlag() != 1 && $request->query->get('forceEdit',0)==0) {
  11485.         //                    $url = $this->generateUrl(
  11486.         //                        'view_project'
  11487.         //                    );
  11488.         //                    return $this->redirect($url . "/" . $projectId);
  11489.         //                }
  11490.         //                else
  11491.         //                {
  11492.         //                    $extDocData=$extTrans;
  11493.         ////                    $extDocDetailsData=Accounts::GetVoucherDataForEdit($em,$projectId);
  11494.         //                }
  11495.         //            }
  11496.         //            else
  11497.         //            {
  11498.         //
  11499.         //            }
  11500.         //
  11501.         //        }
  11502.         return $this->render(
  11503.             '@Sales/pages/input_forms/create_sales_lead.html.twig',
  11504.             array(
  11505.                 'page_title' => 'Sales Lead',
  11506.                 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
  11507.                 //                'clients'=>SalesOrderM::GetClientList($em),
  11508.                 'clients_by_ac_head' => SalesOrderM::GetClientListByAcHead($em),
  11509.                 'users' => Users::getUserListById($em),
  11510.                 'stages' => ProjectConstant::$projectStages,
  11511.                 'bankGuaranteeTypes' => AccountsConstant::$BankGuarnteeTypes,
  11512.                 'productList' => $productList,
  11513.                 'subCategoryList' => $subCategoryList,
  11514.                 'categoryList' => $categoryList,
  11515.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  11516.                 'igList' => $igList,
  11517.                 'bidDataList' => SalesConstant::$bidDataList,
  11518.                 'unitList' => $unitList,
  11519.                 'brandList' => $brandList,
  11520.                 'brandListArray' => $brandListArray,
  11521.                 'productListArray' => $productListArray,
  11522.                 'subCategoryListArray' => $subCategoryListArray,
  11523.                 'categoryListArray' => $categoryListArray,
  11524.                 'igListArray' => $igListArray,
  11525.                 'unitListArray' => $unitListArray,
  11526.                 'currencyList' => Inventory::CurrencyList($em),
  11527.                 'sl' => $sl,
  11528.                 'pl' => $pl,
  11529.                 'hl' => $hl,
  11530.                 'workStages' => $workStages,
  11531.                 'bgData' => $bgDataListByBgType,
  11532.                 'projectList' => $projectList,
  11533.                 'projectData' => $projectData,
  11534.                 'materialData' => $materialData,
  11535.                 'boqData' => $boqData,
  11536.                 'wpData' => $wpData,
  11537.                 'offerData' => $offerData,
  11538.                 'proposalData' => $proposalData,
  11539.                 'extDocData' => $leadData,
  11540.                 'message' => $message,
  11541.                 'salesProposalId' => $id,
  11542.                 'pl_array' => $pl_array,
  11543.                 'sl_array' => $sl_array,
  11544.                 'workStages_array' => $workStages_array,
  11545.                 'debug_data' => $debug_data,
  11546.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  11547.                 //                'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
  11548.             )
  11549.         );
  11550.     }
  11551.     public function SalesLeadList(Request $request)
  11552.     {
  11553.         $em $this->getDoctrine()->getManager();
  11554.         $q $this->getDoctrine()
  11555.             ->getRepository('ApplicationBundle:SalesProposal')
  11556.             ->findBy(
  11557.                 array(
  11558.                     'status' => GeneralConstant::ACTIVE,
  11559.                 ),
  11560.                 array(
  11561.                     'salesProposalDate' => 'DESC',
  11562.                     //                    'salesOrderId'=>'DESC'
  11563.                 )
  11564.             );
  11565.         $stage_list = ['Pending''Pending''Complete''Partial'];
  11566.         $d 9;
  11567.         $data = [];
  11568.         return $this->render(
  11569.             '@Sales/pages/list/sales_lead_list.html.twig',
  11570.             array(
  11571.                 'page_title' => 'Sales Lead',
  11572.                 'data' => $data,
  11573.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  11574.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  11575.                 'users' => Users::getUserListById($em)
  11576.             )
  11577.         );
  11578.     }
  11579.     public function ViewSalesLead(Request $request$id)
  11580.     {
  11581.         $em $this->getDoctrine()->getManager();
  11582.         $themeId $request->get('themeId'1);
  11583.         $defaultColEnabled = array(
  11584.             1,
  11585.             2,
  11586.             3,
  11587.             4,
  11588.             5,
  11589.             6,
  11590.             7,
  11591.             8,
  11592.             9,
  11593.             10,
  11594.             11,
  11595.             12,
  11596.             13,
  11597.             14,
  11598.             15,
  11599.             16,
  11600.             17,
  11601.             18,
  11602.             19,
  11603.             20,
  11604.             21,
  11605.             22,
  11606.             23,
  11607.             24,
  11608.             25,
  11609.             26,
  11610.             27,
  11611.             28,
  11612.             29,
  11613.             30,
  11614.             3132
  11615.         );
  11616.         $columnsEnabled $request->get('columnsEnabled'$defaultColEnabled);
  11617.         $config $request->get('config', []);
  11618.         if (is_string($columnsEnabled)) $columnsEnabled json_decode($columnsEnabledtrue);
  11619.         if (is_string($config)) $config json_decode($configtrue);
  11620.         if ($config == null$config = [];
  11621.         if ($columnsEnabled == null$columnsEnabled = [];
  11622.         $dt SalesOrderM::GetLeadDetails($em$id$columnsEnabled$config);
  11623.         if (!$dt) {
  11624.             $url $this->generateUrl(
  11625.                 'create_sales_lead'
  11626.             );
  11627.             $this->addFlash(
  11628.                 'error',
  11629.                 'The Document You asked for was not found.'
  11630.             );
  11631.             return $this->redirect($url "/" $id);
  11632.         }
  11633.         $stage_list ProjectConstant::$projectStages;
  11634.         $status_list ProjectConstant::$projectStatus;
  11635.         $steps_list ProjectConstant::$projectSteps;
  11636.         //now if its not editable, redirect to view
  11637.         $bgDataListByBgType = [];
  11638.         $bgDataList json_decode($dt['general_data']->getBankGuaranteeData(), true);
  11639.         if ($bgDataList == null)
  11640.             $bgDataList = [];
  11641.         foreach ($bgDataList as $bgData) {
  11642.             $bgData['number'] = '';
  11643.             if ($bgData['id'] != 0) {
  11644.                 $bg $em->getRepository('ApplicationBundle:AccCheck')->findOneBy(
  11645.                     array(
  11646.                         'CheckId' => $bgData['id'], ///material
  11647.                     )
  11648.                 );
  11649.                 if ($bg) {
  11650.                     $bgData['amount'] = $bg->getCheckAmount();
  11651.                     $bgData['number'] = $bg->getCheckNumber();
  11652.                     $bgData['returnDateTs'] = $bg->getReturnableAfterTs();
  11653.                     $bgData['expireDateTs'] = $bg->getValidUptoTs();
  11654.                     $bgData['dateTs'] = $bg->getCheckDate()->format('U');
  11655.                 }
  11656.             }
  11657.             $bgDataListByBgType[$bgData['bankGuaranteeType']] = $bgData;
  11658.         }
  11659.         if ($request->get('returnJson'0) == 1) {
  11660.             return new JsonResponse(
  11661.                 array(
  11662.                     'page_title' => 'Proposal Letter',
  11663.                     'data' => $dt,
  11664.                     'config' => $config,
  11665.                     'columnsEnabled' => $columnsEnabled,
  11666.                     'theme_id' => $themeId,
  11667.                     //                'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
  11668.                     //                'wpData'=>SalesOrderM::GetWpDetails($em,$id),
  11669.                     'clientList' => SalesOrderM::GetClientList($em),
  11670.                     'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  11671.                     'stageList' => $stage_list//
  11672.                     'statusList' => $status_list,
  11673.                     'stepsList' => $steps_list,
  11674.                     'stage_list' => ProjectM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)), //
  11675.                     'auto_created' => $dt['auto_created'],
  11676.                     'approval_data' => System::checkIfApprovalExists(
  11677.                         $em,
  11678.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  11679.                         $id,
  11680.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  11681.                     ),
  11682.                     'document_log' => $dt['auto_created'] == System::getDocumentLog(
  11683.                         $this->getDoctrine()->getManager(),
  11684.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  11685.                         $id,
  11686.                         $dt['created_by'],
  11687.                         $dt['edited_by']
  11688.                     ) : [],
  11689.                     'users' => Users::getUserListById($em),
  11690.                     'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  11691.                 )
  11692.             );
  11693.         } else
  11694.             return $this->render(
  11695.                 '@Sales/pages/views/view_sales_lead.html.twig',
  11696.                 array(
  11697.                     'page_title' => 'Sales Lead',
  11698.                     'data' => $dt,
  11699.                     'config' => $config,
  11700.                     'columnsEnabled' => $columnsEnabled,
  11701.                     'theme_id' => $themeId,
  11702.                     'bgData' => $bgDataListByBgType,
  11703.                     'bankGuaranteeTypes' => AccountsConstant::$BankGuarnteeTypes,
  11704.                     'bidDataList' => SalesConstant::$bidDataList,
  11705.                     //                'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
  11706.                     //                'wpData'=>SalesOrderM::GetWpDetails($em,$id),
  11707.                     'clientList' => SalesOrderM::GetClientList($em),
  11708.                     'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  11709.                     'stageList' => $stage_list,
  11710.                     'statusList' => $status_list,
  11711.                     'stepsList' => $steps_list,
  11712.                     'stage_list' => ProjectM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)),
  11713.                     'auto_created' => $dt['auto_created'],
  11714.                     'approval_data' => System::checkIfApprovalExists(
  11715.                         $em,
  11716.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  11717.                         $id,
  11718.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  11719.                     ),
  11720.                     'document_log' => $dt['auto_created'] == System::getDocumentLog(
  11721.                         $this->getDoctrine()->getManager(),
  11722.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  11723.                         $id,
  11724.                         $dt['created_by'],
  11725.                         $dt['edited_by']
  11726.                     ) : [],
  11727.                     'users' => Users::getUserListById($em),
  11728.                     'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  11729.                 )
  11730.             );
  11731.     }
  11732.     public function PrintSalesLead(Request $request$id)
  11733.     {
  11734.         $em $this->getDoctrine()->getManager();
  11735.         $stage_list ProjectConstant::$projectStages;
  11736.         $status_list ProjectConstant::$projectStatus;
  11737.         $steps_list ProjectConstant::$projectSteps;
  11738.         $themeId $request->get('themeId'1);
  11739.         $defaultColEnabled = array(
  11740.             1,
  11741.             2,
  11742.             3,
  11743.             4,
  11744.             5,
  11745.             6,
  11746.             7,
  11747.             8,
  11748.             9,
  11749.             10,
  11750.             11,
  11751.             12,
  11752.             13,
  11753.             14,
  11754.             15,
  11755.             16,
  11756.             17,
  11757.             18,
  11758.             19,
  11759.             20,
  11760.             21,
  11761.             22,
  11762.             23,
  11763.             24,
  11764.             25,
  11765.             26,
  11766.             27,
  11767.             28,
  11768.             29,
  11769.             30,
  11770.             31
  11771.         );
  11772.         $columnsEnabled $request->get('columnsEnabled'$defaultColEnabled);
  11773.         if ($themeId == 2)
  11774.             $columnsEnabled array_diff($columnsEnabled, [13242630311968152021222329]);
  11775.         if ($request->get('printType''technical_proposal') == 'technical_proposal') {
  11776.             $columnsEnabled array_diff($columnsEnabled, [6810121518]);
  11777.         }
  11778.         $config $request->get('config', []);
  11779.         if (is_string($columnsEnabled)) $columnsEnabled json_decode($columnsEnabledtrue);
  11780.         if (is_string($config)) $config json_decode($configtrue);
  11781.         if ($config == null$config = [];
  11782.         if ($columnsEnabled == null$columnsEnabled = [];
  11783.         $dt SalesOrderM::GetProposalDetails($em$id$columnsEnabled$config);
  11784.         if (!$dt) {
  11785.             $url $this->generateUrl(
  11786.                 'create_sales_lead'
  11787.             );
  11788.             $this->addFlash(
  11789.                 'error',
  11790.                 'Please Create Offer for the project 1st.'
  11791.             );
  11792.             return $this->redirect($url "/" $id);
  11793.         }
  11794.         $company_data Company::getCompanyData($em1);
  11795.         $document_mark = array(
  11796.             'original' => '/images/Original-Stamp-PNG-Picture.png',
  11797.             'copy' => ''
  11798.         );
  11799.         if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
  11800.             $html $this->renderView(
  11801.                 '@Sales/pages/print/print_sales_lead.html.twig',
  11802.                 array(
  11803.                     //full array here
  11804.                     'pdf' => true,
  11805.                     'config' => $config,
  11806.                     'columnsEnabled' => $columnsEnabled,
  11807.                     'theme_id' => $themeId,
  11808.                     'page_title' => 'Offer ' $dt['doc_hash'] . ' (' $dt['general_data']->getClientname() . ')',
  11809.                     'export' => 'pdf,print',
  11810.                     'data' => $dt,
  11811.                     'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  11812.                     'document_mark_image' => $document_mark['original'],
  11813.                     'company_name' => $company_data->getName(),
  11814.                     'company_data' => $company_data,
  11815.                     'company_address' => $company_data->getAddress(),
  11816.                     'company_image' => $company_data->getImage(),
  11817.                     'invoice_footer' => $company_data->getInvoiceFooter(),
  11818.                     'red' => 0,
  11819.                     //                'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
  11820.                     //                'wpData'=>SalesOrderM::GetWpDetails($em,$id),
  11821.                     'clientList' => SalesOrderM::GetClientList($em),
  11822.                     'stageList' => $stage_list,
  11823.                     'statusList' => $status_list,
  11824.                     'stepsList' => $steps_list,
  11825.                     'stage_list' => ProjectM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)),
  11826.                     'auto_created' => $dt['auto_created'],
  11827.                     'approval_data' => System::checkIfApprovalExists(
  11828.                         $em,
  11829.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  11830.                         $id,
  11831.                         $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  11832.                     ),
  11833.                     'document_log' => $dt['auto_created'] == System::getDocumentLog(
  11834.                         $this->getDoctrine()->getManager(),
  11835.                         array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  11836.                         $id,
  11837.                         $dt['created_by'],
  11838.                         $dt['edited_by']
  11839.                     ) : [],
  11840.                     'users' => Users::getUserListById($em),
  11841.                     'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  11842.                 )
  11843.             );
  11844.             $pdf_response $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
  11845.                 //                'orientation' => 'landscape',
  11846.                 //                'enable-javascript' => true,
  11847.                 //                'javascript-delay' => 1000,
  11848.                 'no-stop-slow-scripts' => false,
  11849.                 'no-background' => false,
  11850.                 'lowquality' => false,
  11851.                 'encoding' => 'utf-8',
  11852.                 //            'images' => true,
  11853.                 //            'cookie' => array(),
  11854.                 'dpi' => 300,
  11855.                 'image-dpi' => 300,
  11856.                 //                'enable-external-links' => true,
  11857.                 //                'enable-internal-links' => true
  11858.             ));
  11859.             return new Response(
  11860.                 $pdf_response,
  11861.                 200,
  11862.                 array(
  11863.                     'Content-Type' => 'application/pdf',
  11864.                     'Content-Disposition' => 'attachment; filename="Offer ' $dt['doc_hash'] . ' (' $dt['general_data']->getClientname() . ')' '.pdf"'
  11865.                 )
  11866.             );
  11867.         }
  11868.         return $this->render(
  11869.             '@Sales/pages/print/print_sales_proposal.html.twig',
  11870.             array(
  11871.                 'export' => 'pdf,print',
  11872.                 'config' => $config,
  11873.                 'columnsEnabled' => $columnsEnabled,
  11874.                 'theme_id' => $themeId,
  11875.                 'document_mark_image' => $document_mark['original'],
  11876.                 'company_name' => $company_data->getName(),
  11877.                 'company_data' => $company_data,
  11878.                 'company_address' => $company_data->getAddress(),
  11879.                 'company_image' => $company_data->getImage(),
  11880.                 'invoice_footer' => $company_data->getInvoiceFooter(),
  11881.                 'red' => 0,
  11882.                 'page_title' => 'Proposal Letter',
  11883.                 'data' => $dt,
  11884.                 //                'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
  11885.                 //                'wpData'=>SalesOrderM::GetWpDetails($em,$id),
  11886.                 'userRestrictions' => Users::getUserApplicationAccessSettings($em$request->getSession()->get(UserConstants::USER_ID))['options'],
  11887.                 'clientList' => SalesOrderM::GetClientList($em),
  11888.                 'stageList' => $stage_list,
  11889.                 'statusList' => $status_list,
  11890.                 'stepsList' => $steps_list,
  11891.                 'stage_list' => ProjectM::GetWorkStageList($em$this->getLoggedUserCompanyId($request)),
  11892.                 'auto_created' => $dt['auto_created'],
  11893.                 'approval_data' => System::checkIfApprovalExists(
  11894.                     $em,
  11895.                     array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  11896.                     $id,
  11897.                     $request->getSession()->get(UserConstants::USER_LOGIN_ID)
  11898.                 ),
  11899.                 'document_log' => $dt['auto_created'] == System::getDocumentLog(
  11900.                     $this->getDoctrine()->getManager(),
  11901.                     array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
  11902.                     $id,
  11903.                     $dt['created_by'],
  11904.                     $dt['edited_by']
  11905.                 ) : [],
  11906.                 'users' => Users::getUserListById($em),
  11907.                 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
  11908.             )
  11909.         );
  11910.     }
  11911.     public function helperDataForClient(Request $request)
  11912.     {
  11913.         $entityManager $this->getDoctrine()->getManager();
  11914.         $companyId $this->getLoggedUserCompanyId($request);
  11915.         $clientTypes Client::ClientTypeListForApp($entityManager$companyId);
  11916.         $regionData Client::RegionListForClientEntryForApp($entityManager$companyId);
  11917.         $geographicalRegionData Client::GeographicalRegionListForClientEntry($entityManager19$companyId);
  11918.         $divisionList Client::DivisionList($entityManager);
  11919.         $salesPersonList Client::SalesPersonListForApp($entityManager);
  11920.         $data = [
  11921.             'client_types' => $clientTypes,
  11922.             'region_data' => $regionData,
  11923.             'geographical_region_data' => $geographicalRegionData,
  11924.             'division_list' => $divisionList,
  11925.             'sales_person_list' => $salesPersonList
  11926.         ];
  11927.         return new JsonResponse($data);
  11928.     }
  11929.     public function getSalesInvoiceListForApp()
  11930.     {
  11931.         $em $this->getDoctrine()->getManager();
  11932.         $salesInvoiceDetails $em->getRepository('ApplicationBundle:SalesInvoice')
  11933.             ->createQueryBuilder('S')
  11934.             ->select('S.salesInvoiceNumber, S.salesInvoiceDate, S.invoiceAmount, S.receivedAmount, C.clientName')
  11935.             ->leftJoin('ApplicationBundle:AccClients''C''WITH''S.clientId = C.clientId')
  11936.             ->getQuery()
  11937.             ->getArrayResult();
  11938.         $formatted array_map(function ($item) {
  11939.             $hasAllData = isset($item['salesInvoiceNumber'], $item['salesInvoiceDate'], $item['invoiceAmount'], $item['clientName'], $item['receivedAmount']);
  11940.             if ($hasAllData && $item['salesInvoiceNumber'] && $item['salesInvoiceDate'] && $item['invoiceAmount'] && $item['clientName']) {
  11941.                 return [
  11942.                     'salesInvoiceNumber' => $item['salesInvoiceNumber'],
  11943.                     'salesInvoiceDate' => ($item['salesInvoiceDate'] instanceof \DateTimeInterface) ? $item['salesInvoiceDate']->format('Y-m-d') : "",
  11944.                     'invoiceAmount' => $item['invoiceAmount'],
  11945.                     'clientName' => $item['clientName'],
  11946.                     'paidBalance' => $item['receivedAmount'] ?? "0"
  11947.                 ];
  11948.             }
  11949.             return [
  11950.                 'salesInvoiceNumber' => '',
  11951.                 'salesInvoiceDate' => '',
  11952.                 'invoiceAmount' => '',
  11953.                 'clientName' => '',
  11954.                 'paidBalance' => ''
  11955.             ];
  11956.         }, $salesInvoiceDetails);
  11957.         return new JsonResponse([
  11958.             'message' => 'success',
  11959.             'data' => $formatted
  11960.         ]);
  11961.     }
  11962. }