<?php
namespace ApplicationBundle\Modules\Sales\Controller;
use ApplicationBundle\ApplicationBundle;
use ApplicationBundle\Constants\AccountsConstant;
use ApplicationBundle\Constants\AfterSalesServiceConstant;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Constants\ProjectConstant;
use ApplicationBundle\Controller\GenericController;
use ApplicationBundle\Entity\AccClients;
use ApplicationBundle\Entity\AccSettings;
use ApplicationBundle\Entity\AfterSalesServiceIssue;
use ApplicationBundle\Entity\Branch;
use ApplicationBundle\Entity\ClientType;
use ApplicationBundle\Entity\Employee;
use ApplicationBundle\Entity\Region;
use ApplicationBundle\Entity\SalesOrder;
use ApplicationBundle\Entity\Warehouse;
use ApplicationBundle\Entity\WarehouseAction;
use ApplicationBundle\Helper\Generic;
use ApplicationBundle\Helper\ResponseStructure;
use ApplicationBundle\Interfaces\SessionCheckInterface;
use ApplicationBundle\Modules\Accounts\Accounts;
use ApplicationBundle\Modules\Authentication\Constants\UserConstants;
use ApplicationBundle\Modules\Inventory\Inventory;
use ApplicationBundle\Modules\Project\ProjectM;
use ApplicationBundle\Modules\Sales\Client;
use ApplicationBundle\Modules\Sales\Constants\SalesConstant;
use ApplicationBundle\Modules\Sales\Helper\SalesOrderHelper;
use ApplicationBundle\Modules\Sales\Package;
use ApplicationBundle\Modules\Sales\SalesOrderM;
use ApplicationBundle\Modules\System\DeleteDocument;
use ApplicationBundle\Modules\System\DocValidation;
use ApplicationBundle\Modules\System\MiscActions;
use ApplicationBundle\Modules\System\System;
use ApplicationBundle\Modules\User\Company;
use ApplicationBundle\Modules\User\Position;
use ApplicationBundle\Modules\User\Users;
use CompanyGroupBundle\Entity\EntityFile;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class SalesController extends GenericController implements SessionCheckInterface
{
public function ParseCustomerCsv(Request $request)
{
$customerList = [];
if ($request->isMethod('POST')) {
$post = $request->request;
$path = "";
$file_path = "";
foreach ($request->files as $uploadedFile) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
if ($uploadedFile != null) {
$fileName = md5(uniqid()) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
}
}
// print_r($file);
if ($path != "")
$file_path = 'uploads/FileUploads/' . $path;
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' . $path;
$row = 1;
$csv_data = [];
$rawData = "";
if (($handle = fopen($g_path, "r")) !== FALSE) {
// while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// $num = count($data);
// $csv_data[$row] = $data;
//
// $row++;
//
// }
$rawData = file_get_contents($g_path);
fclose($handle);
unlink($g_path);
}
// $rawData = "John Doe, 34, johndoe@example.com, Software Engineer, New York
// Jane Smith, 28, janesmith@example.com, Data Analyst, San Francisco
// EOD";
$apiKey = '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';
$expectedStructure = 'Please extract the following structured JSON from the input. use null if a property is not found:
[
{
"client_name": "",
"contact_person_name": "",
"sales_person_id": "",
"type": "2",
"region_id": "0",
"division_id": "0",
"address_contact": "",
"contact_number": "",
"shipping_address": "",
"billing_address": "",
"email": "",
"fax": "",
"client_order_amount": null,
"client_invoice_amount": "",
"client_received": "",
"client_due": "",
"client_area_wise_code": "0",
"temp_client_flag": "0",
"head_addition_pending_flag": null,
"geographical_region_id": "0",
"image": null,
"geographical_region_name": null,
"tagged_item_groups": null,
"credit_limit": "0.000",
"provision_flag": null,
"device_id": null,
"device_id_locked_flag": null,
"lock_device_id_on_next_login_flag": null,
"credit_limit_enabled": "0",
"delivery_locked": "0",
"client_alternate_code": "2015001",
"initial_opening_balance": "0",
"temp_area_str": null,
"temp_customer_id_hash": null,
"project_ids": null,
"doc_booked_flag": null,
"time_stamp_of_form": null,
"client_level": "1",
"parent_id": "0",
"is_consumer": "0",
"username": null,
"password": null,
"email_verification_hash": null,
"phone_verification_hash": null,
"trigger_reset_password": null,
"is_email_verified": null,
"is_phone_verified": null,
"is_banned": null,
"ban_expires": null,
"strike_count": null,
"strike_threshold": null,
"account_status": null,
"general_info_tin": "",
"general_info_bin": "",
"is_individual": null,
"allowed_brand_ids": "null",
"delivery_instruction": null,
"client_own_balance_amount": null,
"client_own_due_amount": null,
"client_own_sales_amount": null,
"client_own_received_amount": null,
"client_cash_amount": null,
"client_bank_amount": null,
"client_payment_methods_info": null,
"default_courier_id": "0",
"freeze_balance": null,
"otp_action_id": null,
"otp": null,
"otp_expire_ts": null,
"forgot_password_token": null,
"forgot_password_token_expire_ts": null,
"last_settings_updated_ts": "1709528898",
"app_id": null,
"representative_emails": null,
"representative_emails_data": null,
"global_user_id": null
},
]
Return only the JSON output. Do not include any extra text or explanation.
';
$messages = [
['role' => 'system', 'content' => 'You are a data structuring assistant.'],
['role' => 'user', 'content' => "Raw data:\n$rawData"],
['role' => 'user', 'content' => "Expected structure:\n$expectedStructure"],
];
$data = [
'model' => 'gpt-4.1',
'messages' => $messages,
'temperature' => 0.2
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/chat/completions');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $apiKey",
'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Request Error:' . curl_error($ch);
}
curl_close($ch);
// Decode response
$responseData = json_decode($response, true);
$customerList = json_decode($responseData['choices'][0]['message']['content'] ?? '[]]', true);
// echo "<pre>$structuredOutput</pre>";
//now getting the relevant checks
// $customerList = [];
// if ($customerList) {
// foreach ($customerList as $customer) {
// }
//
// }
return new JsonResponse(array(
"success" => true,
"file_path" => $file_path,
// "csv_data" => $csv_data,
// 'responseData' => $responseData,
"customerList" => $customerList,
// "debug_data"=>System::encryptSignature($r)
));
}
return new JsonResponse(array(
"success" => false,
"customerList" => $customerList,
));
}
public function RecalculateSalesOrders(Request $request)
{
$em = $this->getDoctrine()->getManager();
$debug_data = [];
$setFlagInitially = 0;
if ($request->request->has('setInitialFlag'))
$setFlagInitially = $request->request->get('setInitialFlag');
if ($request->isMethod('POST')) {
// $Transaction = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
// $Transaction = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
// 'approved' => 1,
// 'ledgerHit' => 0
// ));
if ($setFlagInitially == 1) {
$get_kids_sql = 'UPDATE `sales_order` SET recalculate_flag=1';
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
}
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrder')
->findOneBy(
array(
'status' => GeneralConstant::ACTIVE,
'recalculateFlag' => 1,
),
array(
'salesOrderDate' => 'ASC'
)
);
if ($q) {
SalesOrderM::recalculateSalesOrder($em, $q->getSalesOrderId());
SalesOrderM::checkIfSalesOrderComplete($em, $q->getSalesOrderId());
return new JsonResponse(array(
"success" => true,
"debugData" => $debug_data,
"last_doc" => $q->getDocumentHash(),
"last_doc_id" => $q->getSalesOrderId()
));
} else {
return new JsonResponse(array(
"success" => false,
"debugData" => $debug_data,
"last_doc" => '',
"last_doc_id" => ''
));
}
}
return new JsonResponse(array(
"success" => false,
"debugData" => $debug_data,
"last_doc" => '',
"last_doc_id" => ''
));
// MiscActions::refreshDatabase($em);
// return $this->redirectToRoute('dashboard');
}
public function AssignExistingEntitiesToVoucher(Request $request)
{
$em = $this->getDoctrine()->getManager();
$debug_data = [];
$setFlagInitially = 0;
if ($request->request->has('setInitialFlag'))
$setFlagInitially = $request->request->get('setInitialFlag');
if ($request->isMethod('POST')) {
// $Transaction = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
// 'approved' => 1,
// 'ledgerHit' => 0
// ));
$currEntity = 8;
$tocheckEntityList = array(
8 => 'Grn',
9 => 'PurchaseInvoice',
10 => 'ExpenseInvoice',
16 => 'DeliveryReceipt',
18 => 'SalesInvoice',
20 => 'StockTransfer',
21 => 'StockReceivedNote',
30 => 'ServiceChallan',
41 => 'ItemReceivedAndReplacement',
44 => 'StockConsumptionNote',
47 => 'FixedAssetConversionNote',
48 => 'FixedAssetDisposalNote',
53 => 'Production',
);
foreach ($tocheckEntityList as $entity => $entityName) {
$entityList = $em->getRepository('ApplicationBundle:' . $entityName)->findBy(
array(),
array( // GeneralConstant::$Entity_id_list[$entity]
)
);
foreach ($entityList as $entry) {
$voucherIds = method_exists($entry, 'getVoucherIds') ? json_decode($entry->getVoucherIds(), true) : [];
$getMethod = GeneralConstant::$Entity_id_get_method_list[$entity];
if ($voucherIds == null)
$voucherIds = [];
if (!empty($voucherIds)) {
$transactions = $em->getRepository('ApplicationBundle:AccTransactions')->findBy(
array(
'transactionId' => $voucherIds
)
);
foreach ($transactions as $transaction) {
if ($transaction->getEntityId() == 0 || $transaction->getEntityId() == null) {
$transaction->setEntityId($entry->$getMethod());
$transaction->setEntity($entity);
$transaction->setEntityDocHash($entry->getDocumentHash());
$em->flush();
}
}
}
}
}
// if ($q) {
//
// return new JsonResponse(array(
// "success" => true,
// "debugData" => $debug_data,
// "last_doc"=>$q->getDocumentHash(),
// "last_doc_id"=>$q->getSalesOrderId()
//
// ));
// } else {
//
// return new JsonResponse(array(
// "success" => false,
// "debugData" => $debug_data,
// "last_doc"=>'',
// "last_doc_id"=>''
//
// ));
// }
}
return new JsonResponse(array(
"success" => false,
"debugData" => $debug_data,
"last_doc" => '',
"last_doc_id" => ''
));
// MiscActions::refreshDatabase($em);
// return $this->redirectToRoute('dashboard');
}
public function GetClientNumericalCode(Request $request, $ct, $reg)
{
// return new JsonResponse();
return new JsonResponse(array("success" => true, "content" => Client::GetClientNumCode($this->getDoctrine()
->getManager(), $ct, $reg, $this->getLoggedUserCompanyId($request))));
}
public function CreateTradeOffer(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['TradeOffer'];
// $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
// array(
// 'tradeOfferId'=>$id, ///material
//
// ),array('projectDate'=>'desc')
// );
// $client=$em->getRepository('ApplicationBundle:AccClients')->findOneBy(
// array(
// 'clientId'=>$projectData->getClientId(), ///material
//
// ),array('projectDate'=>'desc')
// );
$dochash = $request->request->get('docHash');
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
//construct the files
$file_list = array(
'product_files' => [],
'service_files' => [],
'ar_files' => [],
);
//
$spId = SalesOrderM::CreateNewTradeOffer(
$this->getDoctrine()->getManager(),
$id,
$request->request,
$dochash,
$file_list,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole'); //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['TradeOffer']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
$spId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
$spId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Trade Offer Created'
);
$url = $this->generateUrl(
'view_trade_offer'
);
System::AddNewNotification(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
$request->getSession()->get(UserConstants::USER_APP_ID),
$request->getSession()->get(UserConstants::USER_COMPANY_ID),
"Trade Offer : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::SALES_DEPARTMENT),
'success',
$url . "/" . $spId,
"Trade Offer"
);
return $this->redirect($url . "/" . $spId);
}
}
$message = "";
$extData = [];
$extDetails = [];
if ($id != 0) {
$extData = $em->getRepository('ApplicationBundle:TradeOffer')->findOneBy(
array(
'tradeOfferId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extData) {
$extDetails = json_decode($extData->getData(), true);
if ($extDetails == null)
$extDetails = [];
// if ($proposalData->getEditFlag() != 1) {
// $url = $this->generateUrl(
// 'view_trade_offer'
// );
// $this->addFlash(
// 'error',
// 'Sorry You cant Edit the document Right now.'
// );
// return $this->redirect($url . "/" . $id);
// }
}
}
$qry = $em->getRepository("ApplicationBundle:InvProducts")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
'type' => 1 //trade items
));
$pl = [];
$pl_array = [];
foreach ($qry as $product) {
$pl[$product->getId()] = array(
'text' => $product->getName(),
'name' => $product->getName(),
'id' => $product->getId(),
'value' => $product->getId(),
'purchase_price' => $product->getPurchasePrice(),
'sales_price' => $product->getSalesPrice(),
'supplier_id' => $product->getBrandCompany(),
);
$pl_array[] = array(
'text' => $product->getName(),
'value' => $product->getId(),
'name' => $product->getName(),
'id' => $product->getId(),
'purchase_price' => $product->getPurchasePrice(),
'sales_price' => $product->getSalesPrice(),
'supplier_id' => $product->getBrandCompany(),
);
}
$qry = $em->getRepository("ApplicationBundle:AccService")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
// 'type'=>1//trade items
));
$sl = [];
$sl_array = [];
foreach ($qry as $product) {
$sl[$product->getServiceId()] = array(
'text' => $product->getServiceName(),
'value' => $product->getServiceId(),
'name' => $product->getServiceName(),
'id' => $product->getServiceId(),
);
$sl_array[] = array(
'text' => $product->getServiceName(),
'value' => $product->getServiceId(),
'name' => $product->getServiceName(),
'id' => $product->getServiceId(),
);
}
$qry = $em->getRepository("ApplicationBundle:ProjectWorkStage")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
// 'type'=>1//trade items
));
$workStages = [];
$workStages_array = [];
foreach ($qry as $product) {
$workStages[$product->getProjectWorkStageId()] = array(
'text' => $product->getStageName(),
'value' => $product->getProjectWorkStageId(),
'name' => $product->getStageName(),
'id' => $product->getProjectWorkStageId(),
);
$workStages_array[] = array(
'text' => $product->getStageName(),
'value' => $product->getProjectWorkStageId(),
'name' => $product->getStageName(),
'id' => $product->getProjectWorkStageId(),
);
}
$hl = Accounts::HeadList($em);
$debug_data = $request->files->get('product_reference_file');
$companyId = $this->getLoggedUserCompanyId($request);
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$productList = Inventory::ProductList($em, $companyId, 1);
$subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
$categoryList = Inventory::ProductCategoryList($em, $companyId);
$igList = Inventory::ItemGroupList($em, $companyId);
$unitList = Inventory::UnitTypeList($em);
foreach ($productList as $product) {
$productListArray[] = $product;
}
foreach ($categoryList as $product) {
$categoryListArray[] = $product;
}
foreach ($subCategoryList as $product) {
$subCategoryListArray[] = $product;
}
foreach ($igList as $product) {
$igListArray[] = $product;
}
foreach ($unitList as $product) {
$unitListArray[] = $product;
}
$brandList = Inventory::GetBrandList($em, $companyId);
$brandListArray = [];
foreach ($brandList as $product) {
$brandListArray[] = $product;
}
return $this->render(
'@Sales/pages/input_forms/create_trade_offer.html.twig',
array(
'page_title' => 'Trade Offer',
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
// 'clients'=>SalesOrderM::GetClientList($em),
'clients_by_ac_head' => SalesOrderM::GetClientListByAcHead($em),
'users' => Users::getUserListById($em),
'stages' => ProjectConstant::$projectStages,
'productList' => $productList,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'unitList' => $unitList,
'brandList' => $brandList,
'brandListArray' => $brandListArray,
'productListArray' => $productListArray,
'subCategoryListArray' => $subCategoryListArray,
'categoryListArray' => $categoryListArray,
'igListArray' => $igListArray,
'unitListArray' => $unitListArray,
'sl' => $sl,
'pl' => $pl,
'hl' => $hl,
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'extData' => $extData,
'extDetails' => $extDetails,
'extId' => $id,
'message' => $message,
'tradeOfferId' => $id,
'regionList' => Client::RegionList($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
'pl_array' => $pl_array,
'sl_array' => $sl_array,
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'debug_data' => $debug_data,
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
// 'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
)
);
}
public function TradeOfferList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:TradeOffer')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
),
array(
'tradeOfferDate' => 'DESC',
// 'salesOrderId'=>'DESC'
)
);
$stage_list = ['Pending', 'Pending', 'Complete', 'Partial'];
$d = 9;
$data = [];
foreach ($q as $entry) {
// $clientId=$entry->getClientId();
// $client=$em->getRepository('ApplicationBundle:AccClients')
// ->findOneBy(
// array(
// 'clientId'=>$clientId
// )
// );
$data[] = array(
'doc_date' => $entry->getTradeOfferDate(),
'start_date' => $entry->getTradeOfferStartDate(),
'end_date' => $entry->getTradeOfferEndDate(),
'id' => $entry->getTradeOfferId(),
'doc_hash' => $entry->getDocumentHash(),
'title' => $entry->getTitle(),
'code' => $entry->getCode(),
'invokeType' => $entry->getInvokeTYpe(),
'status' => 'Active',
'proposal_accepted' => $entry->getAccepted(),
// 'stage'=>$stage_list[$entry->getStage()]
);
}
return $this->render(
'@Sales/pages/list/trade_offer_list.html.twig',
array(
'page_title' => 'Trade Offers',
'data' => $data,
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
'users' => Users::getUserListById($em)
)
);
}
public function ViewTradeOffer(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetTradeOfferDetails($em, $id);
///
// $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
// array(
// 'tradeOfferId'=>$id, ///material
// 'projectStep'=>array_flip(ProjectConstant::$projectSteps)['NEGOTIATION'], ///material
//// 'stage'=>array_flip(ProjectConstant::$projectStages)['INITIATED'],
//// 'status'=>array_flip(ProjectConstant::$projectStatus)['PROCESSING']
// ),array('projectDate'=>'desc')
// );
// $offerDataList=$em->getRepository('ApplicationBundle:TradeOffer')->findBy(
// array(
// 'approved'=>1, ///material
//
// )
// );
// if(!empty($offerDataList)) {
// foreach ($offerDataList as $offerData) {
// $all_det_data = json_decode($offerData->getData(), true);
// $entry = $all_det_data[0];
// $store_items = $entry['boqData']['Products'];
// SalesOrderM::addProductsByFdm($em, $store_items['product_fdm'], $offerData->getCompanyId());
//
// }
// }
///////
if (!$dt) {
$url = $this->generateUrl(
'create_trade_offer'
);
$this->addFlash(
'error',
'The Document You asked for was not found.'
);
return $this->redirect($url . "/" . $id);
}
$stage_list = ProjectConstant::$projectStages;
$status_list = ProjectConstant::$projectStatus;
$steps_list = ProjectConstant::$projectSteps;
$companyId = $dt['companyId'];
return $this->render(
'@Sales/pages/views/view_trade_offer.html.twig',
array(
'page_title' => 'Trade Offer',
'data' => $dt,
// 'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
// 'wpData'=>SalesOrderM::GetWpDetails($em,$id),
'clientList' => SalesOrderM::GetClientList($em),
'stageList' => $stage_list,
'statusList' => $status_list,
'stepsList' => $steps_list,
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
'stage_list' => ProjectM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)),
'regionList' => Client::RegionList($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
)
);
}
public function PrintTradeOffer(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetProposalDetails($em, $id);
if (!$dt) {
$url = $this->generateUrl(
'create_trade_offer'
);
$this->addFlash(
'error',
'Please Create Offer for the project 1st.'
);
return $this->redirect($url . "/" . $id);
}
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/print/print_trade_offer.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Offer Letter',
'export' => 'pdf,print',
'data' => $dt,
'stage_list' => SalesOrderM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)),
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
$id,
$dt['created_by'],
$dt['edited_by']
),
'document_mark_image' => $document_mark['original'],
'document_type' => 'Offer Letter',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0,
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="offer.pdf"'
)
);
}
return $this->render(
'@Sales/pages/print/print_trade_offer.html.twig',
array(
'page_title' => 'Project Offer Letter',
'export' => 'pdf,print',
'data' => $dt,
'stage_list' => SalesOrderM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)),
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['TradeOffer'],
$id,
$dt['created_by'],
$dt['edited_by']
),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0,
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
}
public function ConvertToOrder(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$retData = array(
'success' => false
);
if ($request->isMethod('POST')) {
$docType = $request->get('docType', '_proposal_');
$docId = $request->get('docId', 0);
if ($docType == '_project_') {
$theParentDoc = $em->getRepository('ApplicationBundle:Project')->findOneBy(
array(
'projectId' => $docId,
'autoSoEnabled' => [0, null],
)
);
if ($theParentDoc) {
$theParentDoc->setAutoSoEnabled(1);
$em->flush();
ProjectM::CreateSoFromBoq($em, $docId, $auto_created = 1);
$retData['success'] = true;
}
}
if ($docType == '_proposal_') {
$theParentDoc = $em->getRepository('ApplicationBundle:Project')->findOneBy(
array(
'projectId' => $docId,
'autoSoEnabled' => [0, null],
)
);
if ($theParentDoc) {
$theParentDoc->setAutoSoEnabled(1);
$em->flush();
ProjectM::CreateSoFromProposal($em, $docId, $auto_created = 1);
$retData['success'] = true;
}
}
}
return new JsonResponse($retData);
}
public function ConvertToProposal(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$retData = array(
'success' => false
);
if ($request->isMethod('POST')) {
$docType = $request->get('docType', '_lead_');
$docId = $request->get('docId', 0);
if ($docType == '_lead_') {
$theParentDoc = $em->getRepository('ApplicationBundle:SalesLead')->findOneBy(
array(
'leadId' => $docId,
)
);
if ($theParentDoc) {
SalesOrderM::CreateNewProposalFromLead($em, $theParentDoc->getSalesProposalId(), $docId, $theParentDoc->getCreatedLoginId());
$retData['success'] = true;
}
}
}
return new JsonResponse($retData);
}
public function CreateSalesProposal(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['SalesProposal'];
// $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
// array(
// 'salesProposalId'=>$id, ///material
//
// ),array('projectDate'=>'desc')
// );
// $client=$em->getRepository('ApplicationBundle:AccClients')->findOneBy(
// array(
// 'clientId'=>$projectData->getClientId(), ///material
//
// ),array('projectDate'=>'desc')
// );
$dochash = $request->request->get('docHash');
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
//construct the files
$file_list = array(
'product_files' => [],
'service_files' => [],
'ar_files' => [],
);
// if ($request->request->has('products')) {
//
// if ($request->files->has('product_reference_file')) {
// foreach ($request->files->get('product_reference_file') as $uploadedFile) {
//
// $path = "";
//
// if ($uploadedFile != null) {
//
// $fileName = 'p' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
// $path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
// if (!file_exists($upl_dir)) {
// mkdir($upl_dir, 0777, true);
// }
// $file = $uploadedFile->move($upl_dir, $path);
//
// }
// $file_list['product_files'][] = $path;
// }
// }
//
//
// }
// if ($request->request->has('services')) {
// //construct the ref_files array
// $ref_files = [];
// $path = "";
// $file_path = "";
// if ($request->files->has('product_reference_file')) {
// foreach ($request->files->get('service_reference_file') as $uploadedFile) {
//// $uploadedFile = $request->files['service_reference_file_' . $request->request->get('service_uid')[$key]];
// $path = "";
// if ($uploadedFile != null) {
//
// $fileName = 's' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
// $path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
// if (!file_exists($upl_dir)) {
// mkdir($upl_dir, 0777, true);
// }
// $file = $uploadedFile->move($upl_dir, $path);
//
// }
// $file_list['service_files'][] = $path;
// }
// }
//
// }
// if ($request->request->has('heads')) {
// //construct the ref_files array
// $ref_files = [];
// $path = "";
// $file_path = "";
// foreach ($request->files->get('ar_reference_file') as $uploadedFile) {
//// $uploadedFile = $request->files['ar_reference_file_' . $request->request->get('ar_uid')[$key]];
// $path = "";
// if ($uploadedFile != null) {
//
// $fileName = 'a' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
// $path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
// if (!file_exists($upl_dir)) {
// mkdir($upl_dir, 0777, true);
// }
// $file = $uploadedFile->move($upl_dir, $path);
//
// }
// $file_list['ar_files'][] = $path;
// }
//
// }
$document_data_id = SalesOrderM::UpdateDocumentData($this->getDoctrine()->getManager(), $request->request->get('documentDataId'), $request->request, $file_list);
$spId = SalesOrderM::CreateNewProposal(
$this->getDoctrine()->getManager(),
$id,
$document_data_id,
$request->request,
$dochash,
$file_list,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole'); //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesProposal']]['entity_view_route_path_name']
)
);
$currentApprovalData = System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$spId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$spId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Sales Proposal Created'
);
$url = $this->generateUrl(
'view_sales_proposal'
);
if ($currentApprovalData['inProcess'] == 1) {
System::AddNewNotification(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
$request->getSession()->get(UserConstants::USER_APP_ID),
$request->getSession()->get(UserConstants::USER_COMPANY_ID),
"Sales Order : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::SALES_DEPARTMENT),
'success',
$url . "/" . $spId,
"Sales Order"
);
}
return $this->redirect($url . "/" . $spId);
}
}
$projectList = [];
$projectData = [];
$materialData = [];
$boqData = [];
$wpData = [];
$offerData = [];
$proposalData = [];
$message = "";
$allDetData = [];
$projectList = $em->getRepository('ApplicationBundle:Project')->findBy(
array(
'projectStep' => array_flip(ProjectConstant::$projectSteps)['PROPOSAL'], ///material
'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
),
array('projectDate' => 'desc')
);
if ($id != 0) {
$proposalData = $em->getRepository('ApplicationBundle:SalesProposal')->findOneBy(
array(
'salesProposalId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($proposalData) {
}
}
$qry = $em->getRepository("ApplicationBundle:InvProducts")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
'type' => 1 //trade items
));
$pl = [];
$pl_array = [];
foreach ($qry as $product) {
$pl[$product->getId()] = array(
'text' => $product->getName(),
'name' => $product->getName(),
'id' => $product->getId(),
'value' => $product->getId(),
'purchase_price' => $product->getPurchasePrice(),
'sales_price' => $product->getSalesPrice(),
'supplier_id' => $product->getBrandCompany(),
);
$pl_array[] = array(
'text' => $product->getName(),
'value' => $product->getId(),
'name' => $product->getName(),
'id' => $product->getId(),
'purchase_price' => $product->getPurchasePrice(),
'sales_price' => $product->getSalesPrice(),
'supplier_id' => $product->getBrandCompany(),
);
}
$qry = $em->getRepository("ApplicationBundle:AccService")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
// 'type'=>1//trade items
));
$sl = [];
$sl_array = [];
foreach ($qry as $product) {
$sl[$product->getServiceId()] = array(
'text' => $product->getServiceName(),
'value' => $product->getServiceId(),
'name' => $product->getServiceName(),
'id' => $product->getServiceId(),
);
$sl_array[] = array(
'text' => $product->getServiceName(),
'value' => $product->getServiceId(),
'name' => $product->getServiceName(),
'id' => $product->getServiceId(),
);
}
$qry = $em->getRepository("ApplicationBundle:ProjectWorkStage")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
// 'type'=>1//trade items
));
$workStages = [];
$workStages_array = [];
foreach ($qry as $product) {
$workStages[$product->getProjectWorkStageId()] = array(
'text' => $product->getStageName(),
'value' => $product->getProjectWorkStageId(),
'name' => $product->getStageName(),
'id' => $product->getProjectWorkStageId(),
);
$workStages_array[] = array(
'text' => $product->getStageName(),
'value' => $product->getProjectWorkStageId(),
'name' => $product->getStageName(),
'id' => $product->getProjectWorkStageId(),
);
}
$hl = Accounts::HeadList($em);
$debug_data = $request->files->get('product_reference_file');
$companyId = $this->getLoggedUserCompanyId($request);
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$brandListArray = [];
$productList = Inventory::ProductList($em, $companyId);
$subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
$categoryList = Inventory::ProductCategoryList($em, $companyId);
$igList = Inventory::ItemGroupList($em, $companyId);
$unitList = Inventory::UnitTypeList($em);
$brandList = Inventory::GetBrandList($em, $companyId);
foreach ($productList as $product) $productListArray[] = $product;
foreach ($categoryList as $product) $categoryListArray[] = $product;
foreach ($subCategoryList as $product) $subCategoryListArray[] = $product;
foreach ($igList as $product) $igListArray[] = $product;
foreach ($unitList as $product) $unitListArray[] = $product;
foreach ($brandList as $product) $brandListArray[] = $product;
$assignedProjectSiteList = [];
// if($projectId==0)
// {
// $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
// }
// else
// {
//
// $extTrans=$em->getRepository('ApplicationBundle:Project')->findOneBy(
// array(
// 'projectId'=>$projectId, ///material
//
// )
// );
// $assignedProjectSiteList=ProjectM::ProjectSiteList($em,$projectId,$companyId);
// $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
//
//
// //now if its not editable, redirect to view
// if($extTrans) {
// if ($extTrans->getEditFlag() != 1 && $request->query->get('forceEdit',0)==0) {
// $url = $this->generateUrl(
// 'view_project'
// );
// return $this->redirect($url . "/" . $projectId);
// }
// else
// {
// $extDocData=$extTrans;
//// $extDocDetailsData=Accounts::GetVoucherDataForEdit($em,$projectId);
// }
// }
// else
// {
//
// }
//
// }
return $this->render(
'@Sales/pages/input_forms/create_sales_proposal.html.twig',
array(
'page_title' => 'Sales Proposal Letter',
'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
// 'clients'=>SalesOrderM::GetClientList($em),
'clients_by_ac_head' => SalesOrderM::GetClientListByAcHead($em),
'users' => Users::getUserListById($em),
'stages' => ProjectConstant::$projectStages,
'bankGuaranteeTypes' => AccountsConstant::$BankGuarnteeTypes,
'productList' => $productList,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'igList' => $igList,
'unitList' => $unitList,
'brandList' => $brandList,
'brandListArray' => $brandListArray,
'productListArray' => $productListArray,
'subCategoryListArray' => $subCategoryListArray,
'categoryListArray' => $categoryListArray,
'igListArray' => $igListArray,
'unitListArray' => $unitListArray,
'currencyList' => Inventory::CurrencyList($em),
'sl' => $sl,
'pl' => $pl,
'hl' => $hl,
'workStages' => $workStages,
'projectList' => $projectList,
'projectData' => $projectData,
'materialData' => $materialData,
'boqData' => $boqData,
'wpData' => $wpData,
'offerData' => $offerData,
'proposalData' => $proposalData,
'extDocData' => $proposalData,
'message' => $message,
'salesProposalId' => $id,
'pl_array' => $pl_array,
'sl_array' => $sl_array,
'workStages_array' => $workStages_array,
'debug_data' => $debug_data,
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
// 'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
)
);
}
#DemoNote create - Sadia
// public function CreateDemoProposal(Request $request, $id = 0)
// {
// $em = $this->getDoctrine()->getManager();
// if ($request->isMethod('POST')) {
// $em = $this->getDoctrine()->getManager();
// $entity_id = array_flip(GeneralConstant::$Entity_list)['SalesProposal'];
//// $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
//// array(
//// 'salesProposalId'=>$id, ///material
////
//// ),array('projectDate'=>'desc')
//// );
//// $client=$em->getRepository('ApplicationBundle:AccClients')->findOneBy(
//// array(
//// 'clientId'=>$projectData->getClientId(), ///material
////
//// ),array('projectDate'=>'desc')
//// );
//
//
// $dochash = $request->request->get('docHash');
// $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
// $approveRole = $request->request->get('approvalRole');
// $approveHash = $request->request->get('approvalHash');
// if (!DocValidation::isInsertable($em, $entity_id, $dochash,
// $loginId, $approveRole, $approveHash, $id)
// ) {
// $this->addFlash(
// 'error',
// 'Sorry Could not insert Data.'
// );
// } else {
// //construct the files
// $file_list = array(
// 'product_files' => [],
// 'service_files' => [],
// 'ar_files' => [],
// );
//
// $document_data_id=SalesOrderM::UpdateDocumentData($this->getDoctrine()->getManager(),$request->request->get('documentDataId'), $request->request,$file_list);
//
//
// $spId = SalesOrderM::CreateNewProposal($this->getDoctrine()->getManager(), $id,$document_data_id, $request->request, $dochash, $file_list,
// $request->getSession()->get(UserConstants::USER_LOGIN_ID),
// $this->getLoggedUserCompanyId($request));
//
// //now add Approval info
// $loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
// $approveRole = $request->request->get('approvalRole'); //created
// $options = array(
// 'notification_enabled' => $this->container->getParameter('notification_enabled'),
// 'notification_server' => $this->container->getParameter('notification_server'),
// 'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
// 'url' => $this->generateUrl(
// GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesProposal']]
// ['entity_view_route_path_name']
// )
// );
// System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
// array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
// $spId,
// $request->getSession()->get(UserConstants::USER_LOGIN_ID)
// );
// System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
// $spId,
// $loginId,
// $approveRole,
// $request->request->get('approvalHash'));
//
// $this->addFlash(
// 'success',
// 'Sales Proposal Created'
// );
//
// $url = $this->generateUrl(
// 'view_sales_proposal'
// );
//
// System::AddNewNotification(
// $this->container->getParameter('notification_enabled'),
// $this->container->getParameter('notification_server'),
// $request->getSession()->get(UserConstants::USER_APP_ID),
// $request->getSession()->get(UserConstants::USER_COMPANY_ID),
// "Sales Order : " . $dochash . " Has Been Created And is Under Processing",
// 'pos',
// System::getPositionIdsByDepartment($em, GeneralConstant::SALES_DEPARTMENT),
// 'success',
// $url . "/" . $spId,
// "Sales Order"
//
// );
//
// return $this->redirect($url . "/" . $spId);
// }
//
// }
// $projectList = [];
// $projectData = [];
// $materialData = [];
// $boqData = [];
// $wpData = [];
// $offerData = [];
// $proposalData = [];
// $message = "";
// $allDetData=[];
// $projectList = $em->getRepository('ApplicationBundle:Project')->findBy(
// array(
// 'projectStep' => array_flip(ProjectConstant::$projectSteps)['PROPOSAL'], ///material
// 'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
// 'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
// ), array('projectDate' => 'desc')
// );
//
//
// if ($id != 0) {
//
// $proposalData = $em->getRepository('ApplicationBundle:SalesProposal')->findOneBy(
// array(
// 'salesProposalId' => $id, ///material
//
// )
// );
//
// //now if its not editable, redirect to view
//
// if ($proposalData) {
//
//
//
//
//
// }
// }
//
//
// $qry = $em->getRepository("ApplicationBundle:InvProducts")->findBy(array(
// "status" => GeneralConstant::ACTIVE,
// 'CompanyId' => $this->getLoggedUserCompanyId($request),
// 'type' => 1//trade items
// ));
// $pl = [];
// $pl_array = [];
// foreach ($qry as $product) {
// $pl[$product->getId()] = array(
// 'text' => $product->getName(),
// 'name' => $product->getName(),
// 'id' => $product->getId(),
// 'value' => $product->getId(),
// 'purchase_price' => $product->getPurchasePrice(),
// 'sales_price' => $product->getSalesPrice(),
// 'supplier_id' => $product->getBrandCompany(),
// );
// $pl_array[] = array(
// 'text' => $product->getName(),
// 'value' => $product->getId(),
// 'name' => $product->getName(),
// 'id' => $product->getId(),
// 'purchase_price' => $product->getPurchasePrice(),
// 'sales_price' => $product->getSalesPrice(),
// 'supplier_id' => $product->getBrandCompany(),
// );
// }
// $qry = $em->getRepository("ApplicationBundle:AccService")->findBy(array(
// "status" => GeneralConstant::ACTIVE,
// 'CompanyId' => $this->getLoggedUserCompanyId($request),
//// 'type'=>1//trade items
// ));
// $sl = [];
// $sl_array = [];
// foreach ($qry as $product) {
// $sl[$product->getServiceId()] = array(
// 'text' => $product->getServiceName(),
// 'value' => $product->getServiceId(),
// 'name' => $product->getServiceName(),
// 'id' => $product->getServiceId(),
// );
// $sl_array[] = array(
// 'text' => $product->getServiceName(),
// 'value' => $product->getServiceId(),
// 'name' => $product->getServiceName(),
// 'id' => $product->getServiceId(),
// );
// }
// $qry = $em->getRepository("ApplicationBundle:ProjectWorkStage")->findBy(array(
// "status" => GeneralConstant::ACTIVE,
// 'CompanyId' => $this->getLoggedUserCompanyId($request),
//// 'type'=>1//trade items
// ));
// $workStages = [];
// $workStages_array = [];
// foreach ($qry as $product) {
// $workStages[$product->getProjectWorkStageId()] = array(
// 'text' => $product->getStageName(),
// 'value' => $product->getProjectWorkStageId(),
// 'name' => $product->getStageName(),
// 'id' => $product->getProjectWorkStageId(),
// );
// $workStages_array[] = array(
// 'text' => $product->getStageName(),
// 'value' => $product->getProjectWorkStageId(),
// 'name' => $product->getStageName(),
// 'id' => $product->getProjectWorkStageId(),
// );
// }
// $hl = Accounts::HeadList($em);
// $debug_data = $request->files->get('product_reference_file');
// $companyId = $this->getLoggedUserCompanyId($request);
//
// $productListArray = [];
// $subCategoryListArray = [];
// $categoryListArray = [];
// $igListArray = [];
// $unitListArray = [];
// $brandListArray = [];
// $productList = Inventory::ProductList($em, $companyId);
// $subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
// $categoryList = Inventory::ProductCategoryList($em, $companyId);
// $igList = Inventory::ItemGroupList($em, $companyId);
// $unitList = Inventory::UnitTypeList($em);
// $brandList = Inventory::GetBrandList($em, $companyId);
// foreach ($productList as $product) $productListArray[] = $product;
// foreach ($categoryList as $product) $categoryListArray[] = $product;
// foreach ($subCategoryList as $product) $subCategoryListArray[] = $product;
// foreach ($igList as $product) $igListArray[] = $product;
// foreach ($unitList as $product) $unitListArray[] = $product;
// foreach ($brandList as $product) $brandListArray[] = $product;
// $assignedProjectSiteList=[];
//// if($projectId==0)
//// {
//// $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
//// }
//// else
//// {
////
//// $extTrans=$em->getRepository('ApplicationBundle:Project')->findOneBy(
//// array(
//// 'projectId'=>$projectId, ///material
////
//// )
//// );
//// $assignedProjectSiteList=ProjectM::ProjectSiteList($em,$projectId,$companyId);
//// $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
////
////
//// //now if its not editable, redirect to view
//// if($extTrans) {
//// if ($extTrans->getEditFlag() != 1 && $request->query->get('forceEdit',0)==0) {
//// $url = $this->generateUrl(
//// 'view_project'
//// );
//// return $this->redirect($url . "/" . $projectId);
//// }
//// else
//// {
//// $extDocData=$extTrans;
////// $extDocDetailsData=Accounts::GetVoucherDataForEdit($em,$projectId);
//// }
//// }
//// else
//// {
////
//// }
////
//// }
//
//
// return $this->render('@Sales/pages/input_forms/demo.html.twig',
// array(
// 'page_title' => 'Sales Proposal Letter',
// 'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
//// 'clients'=>SalesOrderM::GetClientList($em),
// 'clients_by_ac_head' => SalesOrderM::GetClientListByAcHead($em),
// 'users' => Users::getUserListById($em),
// 'stages' => ProjectConstant::$projectStages,
// 'bankGuaranteeTypes' => AccountsConstant::$BankGuarnteeTypes,
// 'productList' => $productList,
// 'subCategoryList' => $subCategoryList,
// 'categoryList' => $categoryList,
// 'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
//
// 'igList' => $igList,
// 'unitList' => $unitList,
// 'brandList' => $brandList,
// 'brandListArray' => $brandListArray,
// 'productListArray' => $productListArray,
// 'subCategoryListArray' => $subCategoryListArray,
// 'categoryListArray' => $categoryListArray,
// 'igListArray' => $igListArray,
// 'unitListArray' => $unitListArray,
// 'currencyList' => Inventory::CurrencyList($em),
// 'sl' => $sl,
// 'pl' => $pl,
// 'hl' => $hl,
// 'workStages' => $workStages,
// 'projectList' => $projectList,
// 'projectData' => $projectData,
// 'materialData' => $materialData,
// 'boqData' => $boqData,
// 'wpData' => $wpData,
// 'offerData' => $offerData,
// 'proposalData' => $proposalData,
// 'extDocData' => $proposalData,
// 'message' => $message,
// 'salesProposalId' => $id,
// 'pl_array' => $pl_array,
// 'sl_array' => $sl_array,
// 'workStages_array' => $workStages_array,
// 'debug_data' => $debug_data,
// 'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
//// 'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
//
//
// )
// );
// }
public function SalesProposalList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesProposal')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
),
array(
'salesProposalDate' => 'DESC',
// 'salesOrderId'=>'DESC'
)
);
$stage_list = ['Pending', 'Pending', 'Complete', 'Partial'];
$d = 9;
$data = [];
return $this->render(
'@Sales/pages/list/sales_proposal_list.html.twig',
array(
'page_title' => 'Sales Proposals',
'data' => $data,
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
'users' => Users::getUserListById($em)
)
);
}
public function ViewSalesProposal(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$themeId = $request->get('themeId', 1);
$defaultColEnabled = array(
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, 32
);
$columnsEnabled = $request->get('columnsEnabled', $defaultColEnabled);
$config = $request->get('config', []);
if (is_string($columnsEnabled)) $columnsEnabled = json_decode($columnsEnabled, true);
if (is_string($config)) $config = json_decode($config, true);
if ($config == null) $config = [];
if ($columnsEnabled == null) $columnsEnabled = [];
$dt = SalesOrderM::GetProposalDetails($em, $id, $columnsEnabled, $config);
if (!$dt) {
$url = $this->generateUrl(
'create_sales_proposal'
);
$this->addFlash(
'error',
'The Document You asked for was not found.'
);
return $this->redirect($url . "/" . $id);
}
$stage_list = ProjectConstant::$projectStages;
$status_list = ProjectConstant::$projectStatus;
$steps_list = ProjectConstant::$projectSteps;
if ($request->get('returnJson', 0) == 1) {
return new JsonResponse(
array(
'page_title' => 'Proposal Letter',
'data' => $dt,
'config' => $config,
'columnsEnabled' => $columnsEnabled,
'theme_id' => $themeId,
// 'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
// 'wpData'=>SalesOrderM::GetWpDetails($em,$id),
'clientList' => SalesOrderM::GetClientList($em),
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'stageList' => $stage_list, //
'statusList' => $status_list,
'stepsList' => $steps_list,
'stage_list' => ProjectM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)), //
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
} else
return $this->render(
'@Sales/pages/views/view_sales_proposal.html.twig',
array(
'page_title' => 'Proposal Letter',
'data' => $dt,
'config' => $config,
'columnsEnabled' => $columnsEnabled,
'theme_id' => $themeId,
// 'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
// 'wpData'=>SalesOrderM::GetWpDetails($em,$id),
'clientList' => SalesOrderM::GetClientList($em),
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'stageList' => $stage_list,
'statusList' => $status_list,
'stepsList' => $steps_list,
'stage_list' => ProjectM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)),
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
}
public function PrintSalesProposal(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$stage_list = ProjectConstant::$projectStages;
$status_list = ProjectConstant::$projectStatus;
$steps_list = ProjectConstant::$projectSteps;
$themeId = $request->get('themeId', 1);
$defaultColEnabled = array(
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
);
$columnsEnabled = $request->get('columnsEnabled', $defaultColEnabled);
if ($themeId == 2)
$columnsEnabled = array_diff($columnsEnabled, [1, 3, 24, 26, 30, 31, 19, 6, 8, 15, 20, 21, 22, 23, 29]);
if ($request->get('printType', 'technical_proposal') == 'technical_proposal') {
$columnsEnabled = array_diff($columnsEnabled, [6, 8, 10, 12, 15, 18]);
}
$config = $request->get('config', []);
if (is_string($columnsEnabled)) $columnsEnabled = json_decode($columnsEnabled, true);
if (is_string($config)) $config = json_decode($config, true);
if ($config == null) $config = [];
if ($columnsEnabled == null) $columnsEnabled = [];
$dt = SalesOrderM::GetProposalDetails($em, $id, $columnsEnabled, $config);
if (!$dt) {
$url = $this->generateUrl(
'create_sales_proposal'
);
$this->addFlash(
'error',
'Please Create Offer for the project 1st.'
);
return $this->redirect($url . "/" . $id);
}
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/print/print_sales_proposal.html.twig',
array(
//full array here
'pdf' => true,
'config' => $config,
'columnsEnabled' => $columnsEnabled,
'theme_id' => $themeId,
'page_title' => 'Offer ' . $dt['doc_hash'] . ' (' . $dt['general_data']->getClientname() . ')',
'export' => 'pdf,print',
'data' => $dt,
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0,
// 'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
// 'wpData'=>SalesOrderM::GetWpDetails($em,$id),
'clientList' => SalesOrderM::GetClientList($em),
'stageList' => $stage_list,
'statusList' => $status_list,
'stepsList' => $steps_list,
'stage_list' => ProjectM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)),
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
'enable-javascript' => true,
'javascript-delay' => 2000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => $themeId == 3 ? 'attachment; filename="PI_' . $dt['doc_hash'] . ' (' . $dt['general_data']->getClientname() . ')' . '.pdf"' :
'attachment; filename="Offer_' . $dt['doc_hash'] . ' (' . $dt['general_data']->getClientname() . ')' . '.pdf"'
)
);
}
return $this->render(
'@Sales/pages/print/print_sales_proposal.html.twig',
array(
'export' => 'pdf,print',
'config' => $config,
'columnsEnabled' => $columnsEnabled,
'theme_id' => $themeId,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0,
'page_title' => 'Proposal Letter',
'data' => $dt,
// 'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
// 'wpData'=>SalesOrderM::GetWpDetails($em,$id),
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'clientList' => SalesOrderM::GetClientList($em),
'stageList' => $stage_list,
'statusList' => $status_list,
'stepsList' => $steps_list,
'stage_list' => ProjectM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)),
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
}
public function CreateSoAmendment(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['SoAmendment']; //change
// $proj_here = $this->getDoctrine()
// ->getRepository('ApplicationBundle:SoAmendment')
// ->findOneBy(
// array(
// 'soAmendmentId' => $id
// )
// );
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
//construct the files
$file_list = array(
'product_files' => [],
'service_files' => [],
'ar_files' => [],
);
$soAmendmentId = SalesOrderM::CreateNewSoAmendment(
$this->getDoctrine()->getManager(),
$id,
$request->request,
$dochash,
$file_list,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole'); //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SoAmendment']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
$soAmendmentId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
$soAmendmentId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Sales Order Amendment Request Created'
);
$url = $this->generateUrl(
'view_so_amendment'
);
return $this->redirect($url . "/" . $soAmendmentId);
}
}
$projectList = [];
$projectData = [];
$materialData = [];
$boqData = [];
$message = "";
$projectList = $em->getRepository('ApplicationBundle:Project')->findBy(
array(
'projectStep' => array_flip(ProjectConstant::$projectSteps)['BILL OF QUANTITY PLAN'], ///material
'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
),
array('projectDate' => 'desc')
);
$companyId = $this->getLoggedUserCompanyId($request);
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$productList = Inventory::ProductList($em, $companyId, 1);
$subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
$categoryList = Inventory::ProductCategoryList($em, $companyId);
$igList = Inventory::ItemGroupList($em, $companyId);
$unitList = Inventory::UnitTypeList($em);
foreach ($productList as $product) {
$productListArray[] = $product;
}
foreach ($categoryList as $product) {
$categoryListArray[] = $product;
}
foreach ($subCategoryList as $product) {
$subCategoryListArray[] = $product;
}
foreach ($igList as $product) {
$igListArray[] = $product;
}
foreach ($unitList as $product) {
$unitListArray[] = $product;
}
$brandList = Inventory::GetBrandList($em, $companyId);
$brandListArray = [];
foreach ($brandList as $product) {
$brandListArray[] = $product;
}
$qry = $em->getRepository("ApplicationBundle:AccService")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
// 'type'=>1//trade items
));
$sl = [];
$sl_array = [];
foreach ($qry as $product) {
$sl[$product->getServiceId()] = array(
'text' => $product->getServiceName(),
'value' => $product->getServiceId(),
'name' => $product->getServiceName(),
'id' => $product->getServiceId(),
);
$sl_array[] = array(
'text' => $product->getServiceName(),
'value' => $product->getServiceId(),
'name' => $product->getServiceName(),
'id' => $product->getServiceId(),
);
}
$hl = Accounts::HeadList($em);
$debug_data = $request->files->get('product_reference_file');
$userId = $request->getSession()->get(UserConstants::USER_ID);
$userBranchIdList = $request->getSession()->get('branchIdList');
if ($userBranchIdList == null) $userBranchIdList = [];
$userBranchId = $request->getSession()->get('branchId');
return $this->render(
'@Sales/pages/input_forms/create_so_amendment.html.twig',
array(
'page_title' => 'SO Amendment',
'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
// 'clients'=>SalesOrderM::GetClientList($em),
// 'clients_by_ac_head'=>SalesOrderM::GetClientListByAcHead($em),
'users' => Users::getUserListById($em),
'stages' => ProjectConstant::$projectStages,
'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
'sl' => $sl,
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $userId)['options'],
'productList' => $productList,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'unitList' => $unitList,
'brandList' => $brandList,
'branchList' => Client::BranchList($em, $companyId, [], $userBranchIdList),
'brandListArray' => $brandListArray,
'productListArray' => $productListArray,
'subCategoryListArray' => $subCategoryListArray,
'categoryListArray' => $categoryListArray,
'igListArray' => $igListArray,
'unitListArray' => $unitListArray,
'hl' => $hl,
'projectList' => $projectList,
'projectData' => $projectData,
'materialData' => $materialData,
'boqData' => $boqData,
'message' => $message,
'projectId' => $id,
'sl_array' => $sl_array,
'debug_data' => $debug_data,
'canUseOwnPrice' => 0,
'canSkipProductId' => 0,
'canUseZeroPrice' => 0,
'canSetDiscount' => 0,
'maxIndividualDiscountAllowed' => 0,
'maxGrossDiscountAllowed' => 0,
// 'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
)
);
}
public function CheckCreditLimitValidityForSalesOrder(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$repeatCount = 1;
$spec_item_id = 0;
$skip_ids = [];
$so_ids = [];
$succeeded_so_ids = [];
$fail_reasons = [];
$clearUnnecessaryOnly = 0;
$creditLimitEnabled = 0;
if ($request->query->has('soIds'))
$so_ids = $request->query->get('soIds');
if ($request->request->has('soIds'))
$so_ids = $request->request->get('soIds');
$docs = $em->getRepository('ApplicationBundle:SalesOrder')->findBy(
array(
'salesOrderId' => $so_ids,
'orderConfirmationPendingFlag' => 1,
'draftFlag' => [0, null],
// 'approved'=>GeneralConstant::APPROVAL_STATUS_PENDING
// 'id' => $item_id
)
);
foreach ($docs as $doc) {
$client = $em
->getRepository('ApplicationBundle:AccClients')
->findOneby(array(
'clientId' => $doc->getClientId()
));
$creditLimitEnabled = $client->getCreditLimitEnabled() == 1 ? 1 : 0;
//check if credit limit is ok
$order_confirmation_pending_flag = $doc->getOrderConfirmationPendingFlag();
$freezeBalance = 1 * $client->getFreezeBalance();
$client_credit_limit_effective = (1 * $client->getCreditLimit() - 1 * $freezeBalance) - round($doc->getSoAmount()) - 1 * $client->getClientDue();
if (1 * $client_credit_limit_effective < 0 && $client->getCreditLimitEnabled() == 1) {
$fail_reasons[] = "Credit Limit Exceeded";
$em->flush();
// continue;
} else {
}
//confirm if not approved
if ($doc->getApproved() != GeneralConstant::APPROVED) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$doc->getSalesOrderId(),
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$doc->getSalesOrderId(),
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
// $doc->setClientCreatedFlag($post->get('clientCreatedFlag', null));
// $doc->setDraftFlag($post->get('draftFlag', null));
$doc->setOrderConfirmationPendingFlag(0);
$doc->setStage(GeneralConstant::STAGE_INITIATED);
$em->flush();
$succeeded_so_ids[] = $doc->getSalesOrderId();
} else
$fail_reasons[] = "Document is already Approved";
}
return new JsonResponse(array(
'success' => (!empty($succeeded_so_ids)) ? true : false,
'skipIds' => [],
'reasons' => $fail_reasons,
'creditLimitEnabled' => $creditLimitEnabled,
'succeeded_so_ids' => $succeeded_so_ids
));
}
public function ConfirmClientSalesOrder(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$repeatCount = 1;
$spec_item_id = 0;
$skip_ids = [];
$so_ids = [];
$succeeded_so_ids = [];
$fail_reasons = [];
$clearUnnecessaryOnly = 0;
$creditLimitEnabled = 0;
if ($request->query->has('soIds'))
$so_ids = $request->query->get('soIds');
if ($request->request->has('soIds'))
$so_ids = $request->request->get('soIds');
$docs = $em->getRepository('ApplicationBundle:SalesOrder')->findBy(
array(
'salesOrderId' => $so_ids,
'orderConfirmationPendingFlag' => 1,
'draftFlag' => [0, null],
// 'approved'=>GeneralConstant::APPROVAL_STATUS_PENDING
// 'id' => $item_id
)
);
if (empty($docs))
$fail_reasons[] = "Document Not Found in Pending List.";
foreach ($docs as $doc) {
$client = $em
->getRepository('ApplicationBundle:AccClients')
->findOneby(array(
'clientId' => $doc->getClientId()
));
$creditLimitEnabled = $client->getCreditLimitEnabled() == 1 ? 1 : 0;
//check if credit limit is ok
$order_confirmation_pending_flag = $doc->getOrderConfirmationPendingFlag();
$freezeBalance = $client->getFreezeBalance();
$client_credit_limit_effective = (1 * $client->getCreditLimit() - 1 * $freezeBalance) - round($doc->getSoAmount()) - 1 * $client->getClientDue();
if (1 * $client_credit_limit_effective < 0 && $client->getCreditLimitEnabled() == 1) {
$doc->setCreditLimitExceededFlag(1);
$order_confirmation_pending_flag = 1;
$doc->setOrderConfirmationPendingFlag($order_confirmation_pending_flag);
$fail_reasons[] = "Credit Limit Exceeded";
$em->flush();
continue;
} else {
$doc->setCreditLimitExceededFlag(0);
$em->flush();
}
//confirm if not approved
if ($doc->getApproved() != GeneralConstant::APPROVED) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$doc->getSalesOrderId(),
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$doc->getSalesOrderId(),
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
// $doc->setClientCreatedFlag($post->get('clientCreatedFlag', null));
// $doc->setDraftFlag($post->get('draftFlag', null));
$doc->setOrderConfirmationPendingFlag(0);
$doc->setStage(GeneralConstant::STAGE_INITIATED);
$em->flush();
$succeeded_so_ids[] = $doc->getSalesOrderId();
} else
$fail_reasons[] = "Document is already Approved";
}
return new JsonResponse(array(
'success' => (!empty($succeeded_so_ids)) ? true : false,
'skipIds' => [],
'reasons' => $fail_reasons,
'creditLimitEnabled' => $creditLimitEnabled,
'succeeded_so_ids' => $succeeded_so_ids
));
}
public function SubmitClientSalesOrder(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$repeatCount = 1;
$spec_item_id = 0;
$skip_ids = [];
$so_ids = [];
$succeeded_so_ids = [];
$clearUnnecessaryOnly = 0;
if ($request->query->has('soIds'))
$so_ids = $request->query->get('soIds');
if ($request->request->has('soIds'))
$so_ids = $request->request->get('soIds');
$docs = $em->getRepository('ApplicationBundle:SalesOrder')->findBy(
array(
'salesOrderId' => $so_ids,
'draftFlag' => 1,
// 'approved'=>GeneralConstant::APPROVAL_STATUS_PENDING
// 'id' => $item_id
)
);
foreach ($docs as $doc) {
//confirm if not approved
if ($doc->getApproved() != GeneralConstant::APPROVED) {
// $doc->setClientCreatedFlag($post->get('clientCreatedFlag', null));
$doc->setDraftFlag(0);
$doc->setOrderConfirmationPendingFlag(1);
$doc->setStage(GeneralConstant::STAGE_PENDING_CONFIRMATION);
$em->flush();
$succeeded_so_ids[] = $doc->getSalesOrderId();
}
}
return new JsonResponse(array(
'success' => (!empty($succeeded_so_ids)) ? true : false,
'skipIds' => [],
'succeeded_so_ids' => $succeeded_so_ids
));
}
public function ProcessDeliveryOnDirectOrder(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$hasProject = 0;
$extId = $id;
$projectId = 0;
if ($request->query->has('soId'))
$id = $request->query->get('soId');
if ($request->request->has('soId'))
$id = $request->request->get('soId');
if ($id == 0)
return new JsonResponse(array(
'success' => false
));
$companyId = $this->getLoggedUserCompanyId($request);
$so = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
array(
'salesOrderId' => $id
)
);
$drId = 0;
$pvId = 0;
// if($so->getPaymentProcessType()==1) //with order auto
// {
// $pvId =SalesOrderM::addPaymentAutomaticallyForSO($em,$so);
// }
if ($so->getDeliveryProcessType() == 1) //with order auto
{
$drId = SalesOrderM::CreateNewDeliveryReceiptFromScheduleForSo($em, $so, [], $so->getCreatedLoginId(), $so->getCompanyId(), 1);
}
if ($drId != 0)
return new JsonResponse(array(
'success' => true,
'billIds' => [],
'drIds' => [$drId],
'pmntTransIds' => [$pvId],
'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
));
return new JsonResponse(array(
'success' => false
));
}
public function ProcessPaymentOnDirectOrder(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$hasProject = 0;
$extId = $id;
$projectId = 0;
if ($request->query->has('soId'))
$id = $request->query->get('soId');
if ($request->request->has('soId'))
$id = $request->request->get('soId');
if ($id == 0)
return new JsonResponse(array(
'success' => false
));
$companyId = $this->getLoggedUserCompanyId($request);
$so = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
array(
'salesOrderId' => $id
)
);
$drId = 0;
$pvId = 0;
if ($so->getPaymentProcessType() == 1) //with order auto
{
$pvId = SalesOrderM::addPaymentAutomaticallyForSO($em, $so);
}
// if($so->getDeliveryProcessType()==1) //with order auto
// {
// $drId= SalesOrderM::CreateNewDeliveryReceiptFromScheduleForSo($em, $so, [], $so->getCreatedLoginId(), $so->getCompanyId(), 1);
// }
if ($pvId != 0)
return new JsonResponse(array(
'success' => true,
'billIds' => [],
'drIds' => [$drId],
'pmntTransIds' => [$pvId],
'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
));
return new JsonResponse(array(
'success' => false
));
}
public function BackgroundApproveOrder(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$hasProject = 0;
$extId = $id;
$projectId = 0;
$companyId = $this->getLoggedUserCompanyId($request);
$orderId = $id;
//testing direct sale
if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
// if($request->request->has('getInitialData'))
$em = $this->getDoctrine()->getManager();
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
)
);
System::takeFullApproveActions(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$orderId
);
$url = $this->generateUrl(
'view_sales_order'
);
if ($request->request->has('returnJson')) {
$order = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
array(
'salesOrderId' => $orderId, ///material
)
);
$clnt = $em->getRepository('ApplicationBundle:AccClients')->findOneBy(
array(
'clientId' => $order->getClientId(), ///material
)
);
$drs = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
array(
'salesOrderId' => $orderId, ///material
)
);
$bills = $em->getRepository('ApplicationBundle:SalesInvoice')->findBy(
array(
'salesOrderId' => $orderId, ///material
)
);
$billIds = [];
$drIds = [];
$pmntTransIds = [];
foreach ($bills as $bill)
$billIds[] = $bill->getSalesInvoiceId();
foreach ($drs as $dr)
$drIds[] = $dr->getDeliveryReceiptId();
$pmntTransIds = json_decode($order->getOrderPaymentReceiptVoucherIds(), true);
if ($pmntTransIds == null)
$pmntTransIds = [];
return new JsonResponse(array(
'success' => true,
'documentHash' => $order->getDocumentHash(),
'documentId' => $orderId,
'documentIdPadded' => str_pad($orderId, 8, '0', STR_PAD_LEFT),
'documentDate' => $order->getSalesOrderDate()->format('Y-m-d'),
'deliveryProcessType' => $order->getDeliveryProcessType(),
'paymentProcessType' => $order->getPaymentProcessType(),
'clientId' => $order->getClientId(),
'clientMail' => $clnt->getEmail() == null ? '' : $clnt->getEmail(),
'billIds' => $billIds,
'drIds' => $drIds,
'pmntTransIds' => $pmntTransIds,
'viewUrl' => $url . "/" . $orderId,
'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else {
$this->addFlash(
'success',
'New Sales order Created'
);
return $this->redirect($url . "/" . $id);
}
}
return new JsonResponse(array(
'success' => true,
));
}
public function CreateNewOrder(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$hasProject = 0;
$extId = $id;
$projectId = 0;
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->query->has('projectId'))
if ($request->query->get('projectId') != 0) {
$hasProject = 1;
$projectId = $request->query->get('projectId');
}
//testing direct sale
if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
// if($request->request->has('getInitialData'))
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['SalesOrder']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id,
$request->request->has('skipApprovalFlag') ? $request->request->get('skipApprovalFlag') : 0,
$companyId
)) {
if ($request->request->has('returnJson')) {
return new JsonResponse(array(
'success' => false,
'documentHash' => 0,
'documentId' => 0,
'documentIdPadded' => str_pad(0, 8, '0', STR_PAD_LEFT),
'documentDate' => '',
'billIds' => [],
'drIds' => [],
'pmntTransIds' => [],
'viewUrl' => '',
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$funcname = 'SalesOrder';
$doc_id = $extId;
DeleteDocument::$funcname($em, $doc_id, 0, 0);
Client::ProcessTempClients($em, $companyId, $clientIds = [$request->request->get('client_id', null)]);
$orderHere = SalesOrderM::CreateNew(
$this->getDoctrine()->getManager(),
$doc_id,
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
$orderId = $orderHere->getSalesOrderId();
$orderConfirmationPendingFlag = $orderHere->getOrderConfirmationPendingFlag();
$draftFlag = $orderHere->getDraftFlag();
$inhouseShortageFlag = $orderHere->getInhouseShortageFlag();
$clientCreatedFlag = $orderHere->getClientCreatedFlag();
$creditLimitExceededFlag = $orderHere->getCreditLimitExceededFlag();
if ($draftFlag == 0 && $orderConfirmationPendingFlag == 0) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$orderId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('salesMethod', 1),
$request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$orderId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
}
$url = $this->generateUrl(
'view_sales_order'
);
System::AddNewNotification(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
$request->getSession()->get(UserConstants::USER_APP_ID),
$request->getSession()->get(UserConstants::USER_COMPANY_ID),
"Sales Order : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::SALES_DEPARTMENT),
'success',
$url . "/" . $orderId,
"Sales Order"
);
if ($request->request->has('returnJson')) {
$order = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
array(
'salesOrderId' => $orderId,
)
);
$clnt = $em->getRepository('ApplicationBundle:AccClients')->findOneBy(
array(
'clientId' => $order->getClientId(),
)
);
$drs = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
array(
'salesOrderId' => $orderId,
)
);
$bills = $em->getRepository('ApplicationBundle:SalesInvoice')->findBy(
array(
'salesOrderId' => $orderId,
)
);
$billIds = [];
$drIds = [];
$pmntTransIds = [];
foreach ($bills as $bill)
$billIds[] = $bill->getSalesInvoiceId();
foreach ($drs as $dr)
$drIds[] = $dr->getDeliveryReceiptId();
$pmntTransIds = json_decode($order->getOrderPaymentReceiptVoucherIds(), true);
if ($pmntTransIds == null)
$pmntTransIds = [];
return new JsonResponse(array(
'success' => true,
'documentHash' => $order->getDocumentHash(),
'documentId' => $orderId,
'orderConfirmationPendingFlag' => $orderConfirmationPendingFlag,
'draftFlag' => $draftFlag,
'clientCreatedFlag' => $clientCreatedFlag,
'inhouseShortageFlag' => $inhouseShortageFlag,
'creditLimitExceededFlag' => $creditLimitExceededFlag,
'documentIdPadded' => str_pad($orderId, 8, '0', STR_PAD_LEFT),
'documentDate' => $order->getSalesOrderDate()->format('Y-m-d'),
'deliveryProcessType' => $order->getDeliveryProcessType(),
'paymentProcessType' => $order->getPaymentProcessType(),
'clientId' => $order->getClientId(),
'clientMail' => $clnt->getEmail() == null ? '' : $clnt->getEmail(),
'billIds' => $billIds,
'drIds' => $drIds,
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'pmntTransIds' => $pmntTransIds,
'viewUrl' => $url . "/" . $orderId,
'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else {
$this->addFlash(
'success',
'New Sales order Created'
);
return $this->redirect($url . "/" . $orderId);
}
}
}
$projectList = [];
$projectListArray = [];
$dt = $em->getRepository('ApplicationBundle:Project')->findBy(
array(
'projectStep' => array_flip(ProjectConstant::$projectSteps)['SALES ORDER'], ///material
'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
),
array('projectDate' => 'desc')
);
foreach ($dt as $entry) {
$projectListArray[] = array(
'id' => $entry->getProjectId(),
'value' => $entry->getProjectId(),
'name' => $entry->getProjectName(),
'text' => $entry->getProjectName(),
'clientId' => $entry->getClientId(),
);
$projectList[$entry->getProjectId()] = array(
'id' => $entry->getProjectId(),
'value' => $entry->getProjectId(),
'name' => $entry->getProjectName(),
'text' => $entry->getProjectName(),
'clientId' => $entry->getClientId(),
);
}
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$brandListArray = [];
$clientLevelListArray = [];
// $productList = Inventory::ProductList($em, $companyId, 1);
$productList = [];
$subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
$categoryList = Inventory::ProductCategoryList($em, $companyId);
$igList = Inventory::ItemGroupList($em, $companyId);
$unitList = Inventory::UnitTypeList($em);
$brandList = Inventory::GetBrandList($em, $companyId);
$clientLevelList = Inventory::GetClientLevelList($em, $companyId);
$salesLevelList = Inventory::GetSalesLevelList($em, $companyId);
$salesLevelListArray = [];
foreach ($productList as $product) $productListArray[] = $product;
foreach ($categoryList as $product) $categoryListArray[] = $product;
foreach ($subCategoryList as $product) $subCategoryListArray[] = $product;
foreach ($igList as $product) $igListArray[] = $product;
foreach ($unitList as $product) $unitListArray[] = $product;
foreach ($brandList as $product) $brandListArray[] = $product;
foreach ($salesLevelList as $product) $salesLevelListArray[] = $product;
foreach ($clientLevelList as $product) {
$clientLevelListArray[] = $product;
}
$extDocData = [];
$extDocDataDetails = [];
$extDocData = [];
$extDocDetailsData = [];
$itemSegmentData = [];
$segmentData = [];
if ($extId == 0) {
} else {
$extDoc = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
array(
'salesOrderId' => $extId,
)
);
//now if its not editable, redirect to view
if ($extDoc) {
if ($extDoc->getEditFlag() != 1 && $extDoc->getCanBeEditedGenerallyFlag() != 1) {
$url = $this->generateUrl(
'view_sales_order'
);
return $this->redirect($url . "/" . $extId);
} else {
$extDocData = $extDoc;
$itemSegmentData = json_decode($extDocData->getItemSegmentData(), true);
$segmentData = json_decode($extDocData->getSegmentData(), true);
if ($segmentData == null) $segmentData = [];
if ($itemSegmentData == null) $itemSegmentData = [
[
'currCust' => "",
'descCust' => "",
'index' => 0,
'priceCust' => "1",
'scfc' => 0,
'scopeDescription' => "",
'show' => 1,
'title' => "Product & Services",
'unitCust' => "1",
'uomCust' => "Lot",
]
];
$extDocDetailsDataQry = $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy(
array(
'salesOrderId' => $id, ///material
)
);
foreach ($extDocDetailsDataQry as $dt) {
$detailsIds = [];
$specificUnit = [];
$docIds = [];
// $tagDetails = json_decode($dt->getTagData(), true);
// if ($tagDetails == null) $tagDetails = [];
// foreach ($tagDetails as $k => $tagDetail) {
//
//
// $detailsIds[] = isset($tagDetail['details_id']) ? $tagDetail['details_id'] : 0;
// $specificUnit[] = isset($tagDetail['specificUnit']) ? $tagDetail['specificUnit'] : 0;
// $docIds[] = isset($tagDetail['docId']) ? $tagDetail['docId'] : 0;
//
//
// }
$ggObj = [
'alias' => $dt->getAlias(),
'billingSchedule' => "",
'currency' => $extDoc->getCurrency(),
'currencyMultiplyRate' => $extDoc->getCurrencyMultiplyRate(),
'deliveryPorts' => "",
'deliverySchedule' => "",
'dependencyOnIndex' => "0",
'dependencyOnPid' => "0",
'dependencyOnSegment' => "0",
'dependencyOnSid' => "0",
'discountAmount' => $dt->getDiscountAmount(),
'discountRate' => $dt->getDiscountRate(),
'discountedAmount' => $dt->getDiscountedAmount(),
'fdm' => $dt->getProductFdm(),
'finalPrice' => $dt->getFinalPrice(),
'finalAmount' => $dt->getFinalAmount(),
'id' => $dt->getType() == 2 ? $dt->getServiceId() : $dt->getProductId(),
'incoterm' => "",
// 'index' => "1753779068784",
// 'isForeign' => 0,
// 'marginAmount' => "0.000",
// 'marginRate' => "0.000",
// 'markupRate' => "0.000",
'name' => $dt->getProductNameFdm(),
'note' => $dt->getDesc(),
'origin' => $dt->getOrigin(),
'origins' => [$dt->getOrigin()],
// 'recurring' => "1753779068784",
// 'referenceFiles' => "",
// 'referenceNo' => "",
// 'rfqSuppIds' => [],
// 'rowCostTriggerPercentage' => "0",
// 'rowCostTriggerType' => "",
// 'rowId' => '',
// 'scope' => "",
// 'scopeDescription' => "",
// 'scopeId' => 0,
// 'scopeName' => "",
'segmentIndex' => $dt->getSegmentIndex() == null ? 0 : $dt->getSegmentIndex(),
// 'sequence' => "0",
'soItemDelivered' => $dt->getReceived(),
'soItemFound' => 1,
'soItemId' => $dt->getId(),
'taxAmount' => $dt->getIndividualTaxAmount(),
'taxId' => $dt->getTaxConfigId(),
'taxName' => $dt->getTaxConfigName(),
// 'taxAsExpense' => $dt->getTaxAsExpense(),
// 'taxAsExpense' => $dt->getTaxAsExpense(),
'taxRate' => $dt->getIndividualTaxPercentage(),
'totalPrice' => $dt->getAmount(),
'totalSalesPrice' => $dt->getAmount(),
'type' => $dt->getType(),
'unit' => $dt->getQty(),
'unitPrice' => $dt->getPrice(),
'unitSalesPrice' => $dt->getPrice(),
'unitTypeId' => $dt->getUnitTypeId(),
'warranty' => "0",
'specificUnit' => $specificUnit,
'detailsIds' => $detailsIds,
'docIds' => $docIds,
];
$extDocDetailsData[] = $ggObj;
}
}
} else {
}
}
// $clientListById = Client::GetExistingClientList($em, $companyId,['status'=>GeneralConstant::ACTIVE]);
$clientListById = [];
$userId = $request->getSession()->get(UserConstants::USER_ID);
$ownerId = 0;
$ownerLevel = 0;
$salesLevel = 0;
if ($request->getSession()->get(UserConstants::USER_TYPE) == UserConstants::USER_TYPE_CLIENT) {
$thisClientLevel = 0;
$ownerId = $request->getSession()->get(UserConstants::CLIENT_ID);
if ($request->getSession()->has(UserConstants::USER_CLIENT_LEVEL))
$thisClientLevel = $request->getSession()->has(UserConstants::USER_CLIENT_LEVEL);
else {
$thisClient = $em->getRepository('ApplicationBundle:AccClients')->findOneBy(
array(
'clientId' => $ownerId, ///material
)
);
if ($thisClient) {
$thisClientLevel = $thisClient->getClientLevel();
}
}
if ($thisClientLevel == 0 || $thisClientLevel == null || $thisClientLevel == '') {
$thisClientLevel = 0;
}
$ownerLevel = $thisClientLevel;
$salesLevel = $ownerLevel;
}
$warehouse_action_list = GeneralConstant::$warehouse_action_list;
$warehouse_action_list_array = GeneralConstant::$warehouse_action_list_array;
// $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
$userBranchIdList = json_decode($request->getSession()->get('branchIdList'), true);
if ($userBranchIdList == null) $userBranchIdList = [];
$userBranchId = $request->getSession()->get('branchId');
$dataArray = array(
'page_title' => 'New Sales Order',
// 'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
'ExistingClients' => [],
'ClientDetails' => [],
'allowedSalesPersonIds' => Client::AllowedSalesPersonIds($em, $userId, $companyId, []),
// 'ClientDetails' => Client::ClientDetailsAgainstID($em, $companyId, []),
'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager(), [], ['status' => GeneralConstant::ACTIVE]),
'ClientListById' => $clientListById,
'users' => Users::getUserListById($em),
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $userId)['options'],
'hasProject' => $hasProject,
'warehouseList' => Inventory::WarehouseList($em),
'warehouseListArray' => Inventory::WarehouseListArray($em),
'warehouseActionList' => $warehouse_action_list,
'warehouseActionListArray' => $warehouse_action_list_array,
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'projectId' => $projectId,
'projectList' => $projectList,
'productList' => $productList,
'productListArray' => $productListArray,
'projectListArray' => $projectListArray,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'unitList' => $unitList,
'unitListArray' => $unitListArray,
'brandList' => $brandList,
'extDocDataDetails' => $extDocDataDetails,
'extDocData' => $extDocData,
'currencyList' => Inventory::CurrencyList($em),
'colorList' => Inventory::GetColorList($em),
'extData' => $extDocData,
'extDocDetailsData' => $extDocDetailsData,
'itemSegmentData' => $itemSegmentData,
'segmentData' => $segmentData,
// 'ExistingClients' => $clientListById,
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'ownerId' => $ownerId,
'ownerLevel' => $ownerLevel,
'salesLevel' => $salesLevel,
'clientLevelList' => $clientLevelList,
'salesLevelList' => $salesLevelList,
'clientLevelListArray' => $clientLevelListArray,
'salesLevelListArray' => $salesLevelListArray,
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'salesMethodList' => SalesConstant::$salesMethod,
'deliveryProcessTypes' => SalesConstant::$deliveryProcessType,
'paymentProcessTypes' => SalesConstant::$paymentProcessType,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
// 'sales_person_list' => Client::SalesPersonList($em),
'sales_person_list' => [],
'stage_list' => ProjectM::GetWorkStageList($em, $companyId),
'regionList' => Client::RegionList($em, $companyId),
'regionListForClient' => Client::RegionListForClientEntry($em, $companyId),
'branchList' => Client::BranchList($em, $companyId, [], $userBranchIdList),
'userBranchIdList' => $userBranchIdList,
'userBranchId' => $userBranchId,
'headList' => Accounts::HeadList($em),
);
//json
if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) // if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
{
$dataArray['success'] = true;
return new JsonResponse(
$dataArray
);
}
if ($request->query->has('showPos'))
return $this->render(
'@Sales/pages/input_forms/new_sales_order_pos.html.twig',
$dataArray
);
else
return $this->render(
'@Sales/pages/input_forms/new_sales_order.html.twig',
$dataArray
);
}
public function CreateOrder(Request $request)
{
if ($request->isMethod('POST')) {
try {
$em = $this->getDoctrine()->getManager();
$authToken = $request->headers->get('auth-token');
if (!$authToken) {
return new JsonResponse(['error' => 'Invalid or missing auth-token'], 401);
}
$LoginId = 1;
$companyId = $this->getLoggedUserCompanyId($request);
$typeHash = $request->request->get('type_hash', 'SO');
$prefixHash = $request->request->get('prefix_hash', '11');
$approvalRole = $request->request->get('approvalRole', '3');
$timestamp = $request->request->get('timeStampOfForm', time());
$numberHash = MiscActions::GetNumberHash($em, $typeHash, $prefixHash, $approvalRole, $timestamp, 0, $companyId);
$docHash = "{$typeHash}/{$prefixHash}/{$approvalRole}/{$numberHash}";
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
)
);
$request->request->set('number_hash', $numberHash);
$request->request->set('docHash', $docHash);
// Client::ProcessTempClients($em, $companyId, $clientIds = [$request->request->get('client_id', null)]);
$salesOrder = SalesOrderM::CreateNewForApi($em, 0, $request->request, $LoginId, $companyId, 0);
$orderId = $salesOrder->getSalesOrderId();
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$orderId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('salesMethod', 1),
$request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0
);
return new JsonResponse([
'status' => 'success',
'salesOrderId' => $salesOrder->getSalesOrderId(),
'salesOrderNumber' => $salesOrder->getSalesOrderNumber(),
'message' => 'Sales order created successfully'
], 201);
} catch (\Exception $e) {
return new JsonResponse([
'status' => 'error',
'message' => 'Failed to create sales order',
'details' => $e->getMessage()
], 500);
}
} else {
return new JsonResponse("It should be post");
}
}
public function getAllSalesOrderByUser(Request $request)
{
$session = $request->getSession();
$userId = $session->get('userId');
if (!$userId) {
return ResponseStructure::error('User not authenticated', 401);
}
$em = $this->getDoctrine()->getManager();
try {
$salesOrders = SalesOrderHelper::getSalesOrdersByUser($session, $em);
return ResponseStructure::success($salesOrders, 'Sales orders fetched successfully');
} catch (\Exception $e) {
return ResponseStructure::error($e->getMessage(), 500);
}
}
public function CreateNewPointOfSales(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$hasProject = 0;
$extId = $id;
$projectId = 0;
if ($request->query->has('projectId'))
if ($request->query->get('projectId') != 0) {
$hasProject = 1;
$projectId = $request->query->get('projectId');
}
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['SalesOrder']; //change
$dochash = $request->request->get('sales_order_number'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$funcname = 'SalesOrder';
$doc_id = $extId;
DeleteDocument::$funcname($em, $doc_id, 0);
$orderId = SalesOrderM::CreateNew(
$this->getDoctrine()->getManager(),
$doc_id,
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$orderId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$orderId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'New Sales order Created'
);
$url = $this->generateUrl(
'view_sales_order'
);
System::AddNewNotification(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
$request->getSession()->get(UserConstants::USER_APP_ID),
$request->getSession()->get(UserConstants::USER_COMPANY_ID),
"Sales Order : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::SALES_DEPARTMENT),
'success',
$url . "/" . $orderId,
"Sales Order"
);
return $this->redirect($url . "/" . $orderId);
}
}
$projectList = [];
$projectListArray = [];
// $dt=ProjectM::GetProjectListById($em);
$dt = $em->getRepository('ApplicationBundle:Project')->findBy(
array(
'projectStep' => array_flip(ProjectConstant::$projectSteps)['SALES ORDER'], ///material
'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
),
array('projectDate' => 'desc')
);
// $projectList=$dt;
foreach ($dt as $entry) {
$projectListArray[] = array(
'id' => $entry->getProjectId(),
'value' => $entry->getProjectId(),
'name' => $entry->getProjectName(),
'text' => $entry->getProjectName(),
'clientId' => $entry->getClientId(),
);
$projectList[$entry->getProjectId()] = array(
'id' => $entry->getProjectId(),
'value' => $entry->getProjectId(),
'name' => $entry->getProjectName(),
'text' => $entry->getProjectName(),
'clientId' => $entry->getClientId(),
);
// $projectList[]=array(
// 'id'=>$entry['id'],
// 'value'=>$entry['id'],
// 'name'=>$entry['projectName'],
// 'text'=>$entry['projectName'],
// 'clientId'=>$entry['clientId'],
// );
//
}
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$brandListArray = [];
$companyId = $this->getLoggedUserCompanyId($request);
$productList = Inventory::ProductList($em, $companyId, 1);
$subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
$categoryList = Inventory::ProductCategoryList($em, $companyId);
$igList = Inventory::ItemGroupList($em, $companyId);
$unitList = Inventory::UnitTypeList($em);
$brandList = Inventory::GetBrandList($em, $companyId);
foreach ($productList as $product) $productListArray[] = $product;
foreach ($categoryList as $product) $categoryListArray[] = $product;
foreach ($subCategoryList as $product) $subCategoryListArray[] = $product;
foreach ($igList as $product) $igListArray[] = $product;
foreach ($unitList as $product) $unitListArray[] = $product;
foreach ($brandList as $product) $brandListArray[] = $product;
$extDocData = [];
$extDocDataDetails = [];
if ($extId == 0) {
} else {
$extDoc = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
array(
'salesOrderId' => $extId, ///material
)
);
//now if its not editable, redirect to view
if ($extDoc) {
if ($extDoc->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_sales_order'
);
return $this->redirect($url . "/" . $extId);
} else {
$extDocData = $extDoc;
$extDocDataDetails = $em->getRepository('ApplicationBundle:SalesOrderItem')->findOneBy(
array(
'salesOrderId' => $extId, ///material
)
);
}
} else {
}
}
return $this->render(
'@Sales/pages/input_forms/new_point_of_sales.html.twig',
array(
'page_title' => 'New Sales Order',
'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
'ClientList' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
'ClientListById' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
'users' => Users::getUserListById($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
'hasProject' => $hasProject,
'projectId' => $projectId,
'projectList' => $projectList,
'productList' => $productList,
'productListArray' => $productListArray,
'projectListArray' => $projectListArray,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'unitList' => $unitList,
'unitListArray' => $unitListArray,
'brandList' => $brandList,
'extDocDataDetails' => $extDocDataDetails,
'extDocData' => $extDocData,
)
);
}
public function GetExtDataForSo(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$Content = [];
$itemList = [];
$serviceList = [];
$extData = $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy(
array(
'salesOrderId' => $id, ///material
)
);
if (!empty($extData)) {
foreach ($extData as $dt) {
if ($dt->getType() == 1) {
$itemList[] = array(
'id' => $dt->getProductId(),
'unit' => $dt->getQty(),
'balance' => $dt->getBalance(),
'transitQty' => $dt->getTransitQty(),
'delivered' => $dt->getDelivered(),
'prohibitProductChange' => (1 * $dt->getDelivered() + 1 * $dt->getTransitQty()) > 0 ? 1 : 0,
'unitTypeId' => $dt->getUnitTypeId(),
'colorId' => $dt->getColorId(),
'sizeId' => $dt->getSizeId(),
'origin' => $dt->getOrigin(),
'unit_price' => 1 * $dt->getPrice(),
'total_price' => 1 * $dt->getProductAmount(),
'discount_rate' => 1 * $dt->getDiscountRate(),
'discount_amount' => 1 * $dt->getDiscountAmount(),
'discounted_amount' => 1 * $dt->getDiscountedAmount(),
'free_product_ids' => json_decode($dt->getFreeProductIds()),
'so_item_id' => 1 * $dt->getId(),
'free_products_so_item_ids' => json_decode($dt->getFreeProductSoItemIds()),
'free_products_so_item_ids_str' => $dt->getFreeProductSoItemIds(),
'freeProductUnit' => json_decode($dt->getFreeProductUnits()),
'warranty' => $dt->getWarranty(),
'alias' => $dt->getAlias(),
'note' => $dt->getDesc(),
'incoTerm' => $dt->getIncoTerm(),
'taxConfigId' => $dt->getTaxConfigId(),
'taxConfigName' => $dt->getTaxConfigName(),
'tax_amount' => $dt->getIndividualTaxAmount(),
'tax_percentage' => $dt->getIndividualTaxPercentage(),
'ret_data' => [],
'fdm' => $dt->getProductFdm(),
'product_name' => $dt->getProductNameFdm(),
'detailsIds' => [],
'docIds' => [],
);
}
if ($dt->getType() == 2) {
$serviceList[] = array(
'id' => $dt->getServiceId(),
'unit' => $dt->getQty(),
'transitQty' => $dt->getTransitQty(),
'delivered' => $dt->getDelivered(),
'prohibitProductChange' => (1 * $dt->getDelivered() + 1 * $dt->getTransitQty()) > 0 ? 1 : 0,
'unit_price' => 1 * $dt->getPrice(),
'total_price' => 1 * $dt->getProductAmount(),
'alias' => $dt->getAlias(),
'note' => $dt->getDesc(),
'detailsIds' => [],
'so_item_id' => 1 * $dt->getId(),
'incoTerm' => $dt->getIncoTerm(),
'taxConfigId' => $dt->getTaxConfigId(),
'taxConfigName' => $dt->getTaxConfigName(),
'tax_amount' => $dt->getIndividualTaxAmount(),
'tax_percentage' => $dt->getIndividualTaxPercentage(),
);
}
}
}
if (empty($extData))
return new JsonResponse(array("success" => false, "content" => $Content));
else {
// $Content=$engine->render('@Sales/pages/report/selected_client_details_for_so.html.twig', array("cd"=>$CD));
return new JsonResponse(array("success" => true, "content" => array(
'Products' => $itemList,
'Services' => $serviceList
)));
}
}
public function GetAvailableProductQtyForSo(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$productId = $request->request->has('productId') ? $request->request->get('productId') : 0;
$colorId = $request->request->has('colorId') ? $request->request->get('colorId') : 0;
$qty = SalesOrderM::getNonBookedProductQtyForSales($em, $productId, $colorId);
return new JsonResponse(array("success" => true, "qty" => $qty));
}
public function AfterSalesServiceProductStatusList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$routeName = $request->attributes->get('_route');
$filterCondition = "mainTable.CompanyId=1";
// $filterCondition = " mainTable.CompanyId=1 and mainTable.status=1 ";
// if ($routeName != 'client_pending_sales_orders') {
// $filterCondition .= " and ( mainTable.orderConfirmationPendingFlag =0 or mainTable.orderConfirmationPendingFlag is null)";
// }
return $this->render(
'@Sales/pages/list/after_sales_service_status.html.twig',
array(
'page_title' => 'After Sales Service Status',
'data' => [],
'filterCondition' => $filterCondition,
)
);
}
public function SalesOrderList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$routeName = $request->attributes->get('_route');
$filterCondition = " mainTable.CompanyId=1 and mainTable.status=1 ";
$filterCondition .= " and ( mainTable.orderConfirmationPendingFlag =0 or mainTable.orderConfirmationPendingFlag is null)";
return $this->render(
'@Sales/pages/list/sales_order_list.html.twig',
array(
'page_title' => $routeName == 'client_pending_sales_orders' ? 'Confirmation Pending Orders' : 'Sales Orders',
'data' => [],
'orderConfirmationPendingFlag' => 0,
'filterCondition' => $filterCondition,
)
);
}
public function ClientPendingSalesOrderList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$routeName = $request->attributes->get('_route');
$filterCondition = " mainTable.CompanyId=1 and mainTable.status=1 ";
$filterCondition .= " and mainTable.orderConfirmationPendingFlag =1 ";
return $this->render(
'@Sales/pages/list/sales_order_list.html.twig',
array(
'page_title' => 'Confirmation Pending Orders',
'data' => [],
'filterCondition' => $filterCondition,
'orderConfirmationPendingFlag' => 1,
)
);
}
public function ViewSalesOrder(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$mis_data_flag = 0;
if ($request->query->has('mis_print'))
$mis_data_flag = 1;
$dt = SalesOrderM::GetSalesOrderDetails($em, $id, $mis_data_flag);
// $companyId = $this->getLoggedUserCompanyId($request);
$companyId = $dt['so_data']->getCompanyId();
$company_data = Company::getCompanyData($em, $companyId);
$forwardToMailAddress = '';
if ($request->query->has('forwardToMailAddress'))
$forwardToMailAddress = $request->query->get('forwardToMailAddress');
if ($forwardToMailAddress == '')
$forwardToMailAddress = $dt['client_data']->getEmail();
$currentRoute = $request->attributes->get('_route');
if ($currentRoute === 'app_view_sales_order_api') {
if ($id) {
$salesOrderData = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy([
'salesOrderId' => (int)$id
]);
if (!$salesOrderData) {
return new JsonResponse([
'status' => 'false',
'message' => 'Sales order not found.',
'data' => null
], 404);
}
$salesOrderItems = $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy([
'salesOrderId' => (int)$id
]);
$clientId = $salesOrderData->getClientId();
$clientData = $em->getRepository('ApplicationBundle:AccClients')->find($clientId);
if (!$clientData) {
$clientResponse = null;
} else {
$clientResponse = [
"client_id" => (string)$clientData->getClientId(),
"client_name" => $clientData->getClientName(),
"contact_person_name" => $clientData->getContactPersonName(),
"address_contact" => $clientData->getAddressContact(),
"contact_number" => $clientData->getContactNumber() ?? "",
"image" => $clientData->getImage(),
"email" => $clientData->getEmail() ?? "",
"credit_limit" => number_format($clientData->getCreditLimit() ?? 0, 3, '.', ''),
"shipping_address" => $clientData->getShippingAddress() ?? "",
"billing_address" => $clientData->getBillingAddress() ?? "",
"client_due" => $clientData->getClientDue() ?? "0",
"client_level" => (string)($clientData->getClientLevel() ?? 0),
"parent_id" => (string)($clientData->getParentId() ?? 0),
"client_type" => (int)($clientData->getType() ?? 0),
"region_id" => (int)($clientData->getRegionId() ?? 0),
"sales_person_id" => (string)($clientData->getSalesPersonId() ?? 0),
"client_own_balance" => $clientData->getClientOwnBalanceAmount(),
"client_own_due" => $clientData->getClientOwnDueAmount(),
"client_own_sales" => $clientData->getClientOwnSalesAmount(),
"client_own_received" => $clientData->getClientOwnReceivedAmount(),
"status" => (string)$clientData->getStatus(),
"created_at" => $clientData->getCreatedAt() ? [
"date" => $clientData->getCreatedAt()->format('Y-m-d H:i:s.u'),
"timezone_type" => 3,
"timezone" => strtolower($clientData->getCreatedAt()->getTimezone()->getName())
] : null,
"company_id" => (int)$clientData->getCompanyId(),
];
}
$productList = [];
foreach ($salesOrderItems as $index => $item) {
$product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy([
'id' => $item->getProductId()
]);
if (!$product) {
continue;
}
$productList[] = [
'name' => $product->getName(),
'id' => (string)$product->getId(),
'default_image' => $product->getDefaultImage(),
'colors' => $product->getColors() ?? json_encode([""]),
'sizes' => $product->getSizes() ?? json_encode([""]),
'brand_company' => (string)$product->getBrandCompany(),
'product_code' => $product->getProductCode() ?? '',
'curr_sales_price' => $product->getSalesPrice() ?? '',
'curr_purchase_price' => $product->getPurchasePrice() ?? '0',
'qty' => (string)$item->getQty(),
'value' => (string)$item->getQty(),
'rendered_text' => '#' . ($index + 1) . ' ' . $product->getName(),
'text' => $product->getName(),
'currentTs' => (string)time()
];
}
$data = [
'salesOrderId' => $salesOrderData->getSalesOrderId(),
'salesOrderNumber' => $salesOrderData->getSalesOrderNumber(),
'salesOrderDate' => $salesOrderData->getSalesOrderDate() ? $salesOrderData->getSalesOrderDate()->format('Y-m-d H:i:s') : null,
'soAmount' => $salesOrderData->getSoAmount(),
'invoiceAmount' => $salesOrderData->getInvoiceAmount(),
'clientReceivableAmount' => $salesOrderData->getClientReceivableAmount(),
'discountAmount' => $salesOrderData->getDiscountAmount(),
'vatAmount' => $salesOrderData->getVatAmount(),
'paymentTerms' => $salesOrderData->getPaymentTerms(),
'deliveryInstruction' => $salesOrderData->getDeliveryInstruction(),
'documentHash' => $salesOrderData->getDocumentHash(),
'typeHash' => $salesOrderData->getTypeHash(),
'prefixHash' => $salesOrderData->getPrefixHash(),
'assocHash' => $salesOrderData->getAssocHash(),
'numberHash' => $salesOrderData->getNumberHash(),
'refPoNumber' => $salesOrderData->getRefPoNumber(),
'currency' => $salesOrderData->getCurrency(),
'currencyMultiply' => $salesOrderData->getCurrencyMultiply(),
'currencyMultiplyRate' => $salesOrderData->getCurrencyMultiplyRate(),
'status' => $salesOrderData->getStatus(),
'createdAt' => $salesOrderData->getCreatedAt() ? $salesOrderData->getCreatedAt()->format('Y-m-d H:i:s') : null,
'updatedAt' => $salesOrderData->getUpdatedAt() ? $salesOrderData->getUpdatedAt()->format('Y-m-d H:i:s') : null,
'client' => $clientResponse,
'products' => $productList,
];
return new JsonResponse([
'status' => 'success',
'message' => 'Sales order data retrieved successfully.',
'data' => $data
]);
} else {
return new JsonResponse([
'status' => 'false',
'message' => 'Sales order ID is missing!',
'data' => null
], 400);
}
}
return $this->render(
'@Sales/pages/views/sales_order_view.html.twig',
array(
'page_title' => 'View',
'data' => $dt,
'forwardToMailAddress' => $forwardToMailAddress,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
// 'invoice_footer' => $company_data->getInvoiceFooter(),
'projectList' => ProjectM::GetProjectListById($em),
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'salesMethodList' => SalesConstant::$salesMethod,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'sales_person_list' => Client::SalesPersonList($em),
'stage_list' => ProjectM::GetWorkStageList($em, $companyId),
'regionList' => Client::RegionList($em, $companyId),
'regionListForClient' => Client::RegionListForClientEntry($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
'headList' => Accounts::HeadList($em),
'positionList' => Position::getPositionList($em)
)
);
}
public function PrintSalesOrder(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
//mis options flag
$mis_data_flag = 0;
if ($request->query->has('mis_print') || $request->query->has('includeMisFlag'))
$mis_data_flag = 1;
$data = SalesOrderM::GetSalesOrderDetails($em, $id, $mis_data_flag);
//print common options starts
$printTypesEnabled = ['office_copy']; //default
$sendAsPdf = 0;
$printType = 'office_copy';
if ($request->query->has('printType'))
$printType = $request->query->get('printType');
if ($request->query->has('forwardToEmail')) {
$printType = 'forwardToEmail';
// $sendAsPdf=1;
}
if ($request->query->has('attachPdf')) {
$printType = 'forwardToEmail';
$sendAsPdf = $request->query->get('attachPdf');
}
if ($printType == 'all_copy') {
$printTypesEnabled = ['office_copy', 'party_copy'];
}
if ($printType == 'forwardToEmail') {
$printTypesEnabled = ['party_copy'];
}
$forwardToMailAddress = '';
if ($request->query->has('forwardToMailAddress'))
$forwardToMailAddress = $request->query->get('forwardToMailAddress');
if ($forwardToMailAddress == '')
$forwardToMailAddress = $data['client_data']->getEmail();
//print spec options end
$company_data = Company::getCompanyData($em, $companyId);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if (($request->query->has('pdf') || $printType == 'forwardToEmail') && $this->get('knp_snappy.pdf')) {
$html = '';
$pdf_response = '';
$dataForRender = array(
//full array here
'page_title' => 'Sales Order ' . $data['doc_hash'],
'pdf' => true,
'forwardToMailAddress' => $forwardToMailAddress,
'data' => $data,
'printTypesEnabled' => $printTypesEnabled,
'sendAsPdf' => $sendAsPdf,
'export' => 'pdf,print,sendForward',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Sales Order',
'page_header_sub' => 'Add',
'projectList' => ProjectM::GetProjectListById($em),
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'salesMethodList' => SalesConstant::$salesMethod,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'sales_person_list' => Client::SalesPersonList($em),
'stage_list' => ProjectM::GetWorkStageList($em, $companyId),
'regionList' => Client::RegionList($em, $companyId),
'regionListForClient' => Client::RegionListForClientEntry($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
'headList' => Accounts::HeadList($em),
'positionList' => Position::getPositionList($em),
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'users' => Users::getUserListById($em)
);
if ($request->query->has('pdf') || $sendAsPdf == 1) {
//genertae the html only if pdf is returned or attached
$html = $this->renderView(
'@Sales/pages/print/sales_order_print.html.twig',
array(
//full array here
'page_title' => 'Sales Order ' . $data['doc_hash'],
'pdf' => true,
'forwardToMailAddress' => $forwardToMailAddress,
// 'convertImageToBase64'=>true,
'data' => $data,
'printTypesEnabled' => $printTypesEnabled,
'sendAsPdf' => $sendAsPdf,
'export' => 'pdf,print',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Sales Order',
'page_header_sub' => 'Add',
'projectList' => ProjectM::GetProjectListById($em),
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'salesMethodList' => SalesConstant::$salesMethod,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'sales_person_list' => Client::SalesPersonList($em),
'stage_list' => ProjectM::GetWorkStageList($em, $companyId),
'regionList' => Client::RegionList($em, $companyId),
'regionListForClient' => Client::RegionListForClientEntry($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
'headList' => Accounts::HeadList($em),
'positionList' => Position::getPositionList($em),
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'users' => Users::getUserListById($em)
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
}
if ($printType == 'forwardToEmail') {
$bodyHtml = '';
$bodyTemplate = '@Sales/pages/print/sales_order_print.html.twig';
$bodyData = $dataForRender;
$attachments = [];
if ($sendAsPdf == 1) {
$attachments[] = array(
'file' => $pdf_response,
'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'fileType' => 'application/pdf'
);
}
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_SALES_ORDERS_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => $company_data->getName() . ' New Order#' . str_pad($id, 8, '0', STR_PAD_LEFT),
'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
// 'fromAddress'=>'sales@entity.innobd.com',
// 'userName'=>'sales@entity.innobd.com',
// 'password'=>'Y41dh8g0112',
// 'smtpServer'=>'smtp.hostinger.com',
// 'smtpPort'=>587,
// 'emailBody'=>$bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 1,
'companyId' => $companyId,
'companyImagePath' => $company_data->getImage()
));
return new JsonResponse(
array(
'success' => true
)
);
} else {
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="sales_order_' . $id . '.pdf"'
)
);
}
}
return $this->render(
'@Sales/pages/print/sales_order_print.html.twig',
array(
'page_title' => 'Sales Order ' . $data['doc_hash'],
'data' => $data,
// 'convertImageToBase64'=>true,
'printTypesEnabled' => $printTypesEnabled,
'sendAsPdf' => $sendAsPdf,
'forwardToMailAddress' => $forwardToMailAddress,
'export' => 'pdf,print,sendForward',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'Sales Order',
'document_type' => 'Sales Order',
'page_header_sub' => 'Add',
'projectList' => ProjectM::GetProjectListById($em),
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'salesMethodList' => SalesConstant::$salesMethod,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'sales_person_list' => Client::SalesPersonList($em),
'stage_list' => ProjectM::GetWorkStageList($em, $companyId),
'regionList' => Client::RegionList($em, $companyId),
'regionListForClient' => Client::RegionListForClientEntry($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
'headList' => Accounts::HeadList($em),
'positionList' => Position::getPositionList($em),
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'users' => Users::getUserListById($em)
)
);
}
//delivery order
public function DeliveryOrderList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryOrder')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
),
array(
'deliveryOrderDate' => 'DESC'
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getDeliveryOrderDate(),
'id' => $entry->getDeliveryOrderId(),
'doc_hash' => $entry->getDocumentHash(),
// 'so_amount'=>$entry->getSoAmount(),
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render(
'@Sales/pages/list/delivery_orders.html.twig',
array(
'page_title' => 'Delivery Orders',
'data' => $data
)
);
}
public function ViewDeliveryOrder(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetDeliveryOrderDetails($em, $id);
return $this->render(
'@Sales/pages/views/delivery_order_view.html.twig',
array(
'page_title' => 'View',
'data' => $dt,
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['DeliveryOrder'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['DeliveryOrder'],
$id,
$dt['created_by'],
$dt['edited_by']
) : []
)
);
}
public function PrintDeliveryOrder(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = SalesOrderM::GetDeliveryOrderDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
return $this->render(
'@Sales/pages/print/delivery_order_print.html.twig',
array(
'page_title' => 'Delivery Order ' . $data['doc_hash'],
'data' => $data,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Delivery Order',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
)
);
}
//SalesReturn
public function CreateSalesReturn(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object');;
$warehouse_action_list_array = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'array');;
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['SalesReturn']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$StID = SalesOrderM::CreateNewSalesReturn(
$this->getDoctrine()->getManager(),
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesReturn']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
$StID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
$StID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Sales return Added.'
);
$url = $this->generateUrl(
'view_sales_return'
);
return $this->redirect($url . "/" . $StID);
}
}
$slotList = $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
array(
'CompanyId' => $this->getLoggedUserCompanyId($request),
)
);
$INVLIST = [];
foreach ($slotList as $slot) {
$INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
}
return $this->render(
'@Sales/pages/input_forms/sales_return.html.twig',
array(
'page_title' => 'Sales Return',
'warehouseList' => Inventory::WarehouseList($em),
'warehouseListArray' => Inventory::WarehouseListArray($em),
'warehouseActionList' => $warehouse_action_list,
'warehouseActionListArray' => $warehouse_action_list_array,
'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
'deliveryReceipts' => SalesOrderM::DeliveryReceiptList($this->getDoctrine()->getManager()),
'deliveryReceiptsArray' => SalesOrderM::DeliveryReceiptListArray($this->getDoctrine()->getManager()),
'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
'productList' => $productList = Inventory::ProductList($em, $companyId, 1),
'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
'unit_list' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
'prefix_list' => array(
[
'id' => 1,
'value' => 'GN',
'text' => 'GN'
]
),
'assoc_list' => array(
[
'id' => 1,
'value' => 1,
'text' => 'GN'
]
),
'INVLIST' => $INVLIST
)
);
}
public function RefreshMrp(Request $request)
{
$em = $this->getDoctrine()->getManager();
$res = Package::refreshMrp($em);
return new JsonResponse(
array(
'success' => true,
'data' => $res
)
);
}
public function SalesReturnList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesReturn')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
'CompanyId' => $companyId
// 'approved' => GeneralConstant::APPROVED,
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
$clientList = SalesOrderM::GetClientList($em, [], $companyId);
foreach ($q as $entry) {
$clientId = $entry->getClientId();
$data[] = array(
'doc_date' => $entry->getSalesReturnDate(),
'id' => $entry->getSalesReturnId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'stage' => $stage_list[$entry->getStage()],
'client_id' => $clientId,
'client_name' => $clientList[$clientId]['client_name'],
'client_code' => $clientList[$clientId]['client_code'],
'client_alternate_code' => $clientList[$clientId]['client_alternate_code'],
);
}
return $this->render(
'@Sales/pages/list/sales_return_list.html.twig',
array(
'page_title' => 'Sales Return List',
'data' => $data
)
);
}
public function ViewSalesReturn(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetSalesReturnDetails($em, $id);
return $this->render(
'@Sales/pages/views/view_sales_return.html.twig',
array(
'page_title' => 'Sales Return',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
$id,
$dt['created_by'],
$dt['edited_by']
)
)
);
}
public function PrintSalesReturn(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetSalesReturnDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/print/print_sales_return.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Sales return',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
$id,
$dt['created_by'],
$dt['edited_by']
),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="sales_return_' . $id . '.pdf"'
)
);
}
return $this->render(
'@Sales/pages/print/print_sales_return.html.twig',
array(
'page_title' => 'Sales Return',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesReturn'],
$id,
$dt['created_by'],
$dt['edited_by']
),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
}
//after Sales Service order
public function CreateAfterSalesServiceOrder(Request $request, $stage = 0, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object');;
$warehouse_action_list_array = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'array');;
$service = Inventory::ServiceList($em, $companyId);
$issueQuery = $em->getRepository('ApplicationBundle:AfterSalesServiceIssue')->findAll();
$issue = [];
foreach ($issueQuery as $d) {
$issue[$d->getId()] = array(
'id' => $d->getId(),
'documentName' => $d->getCoreIssue(),
'text' => $d->getCoreIssue(),
'isParent' => $d->getIsParent(),
);
}
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
Client::ProcessTempClients($em, $companyId, $clientIds = [$request->request->get('returning_client_id', null)]);
$StID = SalesOrderM::CreateNewAfterSalesServiceOrder(
$this->getDoctrine()->getManager(),
0,
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
$StID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
$StID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Preliminary Info Added.'
);
$url = $this->generateUrl(
'view_after_sales_service_order'
);
return $this->redirect($url . "/" . $StID);
}
}
$slotList = $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
array(
'CompanyId' => $this->getLoggedUserCompanyId($request),
)
);
$INVLIST = [];
foreach ($slotList as $slot) {
$INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
}
return $this->render(
'@Sales/pages/input_forms/after_sales_service_order.html.twig',
array(
'page_title' => 'After Sales Service Order',
'warehouseList' => Inventory::WarehouseList($em),
'warehouseListArray' => Inventory::WarehouseListArray($em),
'warehouseActionList' => $warehouse_action_list,
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'warehouseActionListArray' => $warehouse_action_list_array,
'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
'ClientListByAcHead' => [],
// 'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
'ClientList' => [],
// 'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
'deliveryOrders' => SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
'deliveryReceipts' => SalesOrderM::DeliveryReceiptList($this->getDoctrine()->getManager()),
'deliveryReceiptsArray' => SalesOrderM::DeliveryReceiptListArray($this->getDoctrine()->getManager()),
'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
'productList' => $productList = Inventory::ProductList($em, $companyId, 1),
'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
'unit_list' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
'service' => $service,
'issue' => $issue,
'accessories' => AfterSalesServiceConstant::$accessories,
'prefix_list' => array(
[
'id' => 1,
'value' => 'GN',
'text' => 'GN'
]
),
'assoc_list' => array(
[
'id' => 1,
'value' => 1,
'text' => 'GN'
]
),
'INVLIST' => $INVLIST
)
);
}
public function getIndividualIssue(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
if ($id == 0) {
if ($request->request->has('documentId'))
$id = $request->request->get('documentId');
}
$document = $em->getRepository('ApplicationBundle:AfterSalesServiceIssue')->find($id);
return new JsonResponse(
array(
'success' => true,
'rowId' => $request->request->get('rowId'),
'detailedIssue' => json_decode($document->getDetailedissues()),
'checklist' => json_decode($document->getPreliminaryCheckList()),
)
);
}
public function AfterSalesServiceOrderList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:AfterSalesServiceOrder')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
'CompanyId' => $companyId
// 'approved' => GeneralConstant::APPROVED,
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
$clientList = SalesOrderM::GetClientList($em, [], $companyId);
foreach ($q as $entry) {
$clientId = $entry->getClientId();
$data[] = array(
'doc_date' => $entry->getAfterSalesServiceOrderDate(),
'id' => $entry->getAfterSalesServiceOrderId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'stage' => $stage_list[$entry->getStage()],
'client_id' => $clientId,
'client_name' => $clientList[$clientId]['client_name'],
'client_code' => $clientList[$clientId]['client_code'],
'client_alternate_code' => $clientList[$clientId]['client_alternate_code'],
);
}
return $this->render(
'@Sales/pages/list/after_sales_service_order_list.html.twig',
array(
'page_title' => 'After Sales Service Order List',
'data' => $data
)
);
}
public function ViewAfterSalesServiceOrder(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$afterSalesServiceOrderDetails = $em->getRepository('ApplicationBundle:AfterSalesServiceOrder')->find($id);
$wareHouseActionList = $em->getRepository('ApplicationBundle:WarehouseAction')->findAll();
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object');;
$branchList = Client::BranchList($em, $companyId, []);
$warehouse_action_list_array = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'array');;
// $producByCodelist = Inventory::productByCodeList($em, $this->getLoggedUserCompanyId($request), 'object');;
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')->findOneBy(
array(
'productByCodeId' => $afterSalesServiceOrderDetails->getProductByCodeId()
)
);
// $producByCodelistArray = Inventory::productByCodeList($em, $this->getLoggedUserCompanyId($request), 'array');;
$issueQuery = $em->getRepository('ApplicationBundle:AfterSalesServiceIssue')->findAll();
$issue = [];
foreach ($issueQuery as $d) {
$issue[$d->getId()] = array(
'id' => $d->getId(),
'documentName' => $d->getCoreIssue(),
'text' => $d->getCoreIssue(),
'isParent' => $d->getIsParent(),
);
}
//$dt = SalesOrderM::GetAfterSalesServiceOrderDetails($em, $id);
return $this->render(
'@Sales/pages/views/view_after_sales_service_order.html.twig',
array(
'page_title' => 'View Preliminary Registration',
'afterSalesServiceOrderDetails' => $afterSalesServiceOrderDetails,
'warehouseActionList' => $warehouse_action_list,
'branchList' => $branchList,
'warehouseActionListArray' => $warehouse_action_list_array,
'productByCodeData' => $productByCodeData,
// 'producByCodelistArray' => $producByCodelistArray,
'issue' => $issue,
'accessories' => AfterSalesServiceConstant::$accessories,
'accessoriesFromDb' => json_decode($afterSalesServiceOrderDetails->getAccessories(), true),
)
);
}
public function PrintAfterSalesServiceOrder(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetAfterSalesServiceOrderDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/print/print_after_sales_service_order.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Sales return',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
$id,
$dt['created_by'],
$dt['edited_by']
),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="after_sales_service_order_' . $id . '.pdf"'
)
);
}
return $this->render(
'@Sales/pages/print/print_after_sales_service_order.html.twig',
array(
'page_title' => 'After Sales Service Order',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceOrder'],
$id,
$dt['created_by'],
$dt['edited_by']
),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
}
public function SoAmendmentList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:SoAmendment')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request)
// 'approved' => GeneralConstant::APPROVED,
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getSoAmendmentDate(),
'id' => $entry->getSoAmendmentId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
// 'stage'=>$stage_list[$entry->getStage()]
);
}
return $this->render(
'@Sales/pages/list/so_amendment_list.html.twig',
array(
'page_title' => 'Sales Order Amendment List',
'data' => $data
)
);
}
public function ViewSoAmendment(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetSoAmendmentDetails($em, $id);
return $this->render(
'@Sales/pages/views/view_so_amendment.html.twig',
array(
'page_title' => 'Sales Order Amendment',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
$id,
$dt['created_by'],
$dt['edited_by']
)
)
);
}
public function PrintSoAmendment(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetSoAmendmentDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/print/print_so_amendment.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Sales Order Amendment',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
$id,
$dt['created_by'],
$dt['edited_by']
),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="so_amendment_' . $id . '.pdf"'
)
);
}
return $this->render(
'@Sales/pages/print/print_so_amendment.html.twig',
array(
'page_title' => 'Sales Order Amendment',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SoAmendment'],
$id,
$dt['created_by'],
$dt['edited_by']
),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
}
//ItemReceivedAndReplacement
public function CreateItemReceivedAndReplacement(Request $request)
{
$em = $this->getDoctrine()->getManager();
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object');;
$warehouse_action_list_array = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'array');;
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$StID = SalesOrderM::CreateNewItemReceivedAndReplacement(
$this->getDoctrine()->getManager(),
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
$StID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
$StID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Item Return & Replacement Added.'
);
$url = $this->generateUrl(
'view_irr'
);
return $this->redirect($url . "/" . $StID);
}
}
$slotList = $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
array(
'CompanyId' => $this->getLoggedUserCompanyId($request),
)
);
$INVLIST = [];
foreach ($slotList as $slot) {
$INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
}
$companyId = $this->getLoggedUserCompanyId($request);
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$brandListArray = [];
$productList = Inventory::ProductList($em, $companyId, 1);
$subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
$categoryList = Inventory::ProductCategoryList($em, $companyId);
$igList = Inventory::ItemGroupList($em, $companyId);
$unitList = Inventory::UnitTypeList($em);
$brandList = Inventory::GetBrandList($em, $companyId);
foreach ($productList as $product) $productListArray[] = $product;
foreach ($categoryList as $product) $categoryListArray[] = $product;
foreach ($subCategoryList as $product) $subCategoryListArray[] = $product;
foreach ($igList as $product) $igListArray[] = $product;
foreach ($unitList as $product) $unitListArray[] = $product;
foreach ($brandList as $product) $brandListArray[] = $product;
$salesReturnList = [];
$salesReturnListArray = [];
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesReturn')
->findBy(
array(
'stage' => GeneralConstant::STAGE_INITIATED,
'approved' => 1,
'status' => GeneralConstant::ACTIVE
)
);
foreach ($QD as $dt) {
$salesReturnList[$dt->getSalesReturnId()] = array(
'id' => $dt->getSalesReturnId(),
'name' => $dt->getDocumentHash(),
'soId' => $dt->getSalesOrderId(),
'text' => $dt->getDocumentHash(),
);
$salesReturnListArray[] = array(
'id' => $dt->getSalesReturnId(),
'name' => $dt->getDocumentHash(),
'soId' => $dt->getSalesOrderId(),
'text' => $dt->getDocumentHash(),
);
}
return $this->render(
'@Sales/pages/input_forms/irr.html.twig',
array(
'page_title' => 'Item Return & Replacement',
'warehouseList' => Inventory::WarehouseList($em),
'warehouseListArray' => Inventory::WarehouseListArray($em),
'warehouseActionList' => $warehouse_action_list,
'warehouseActionListArray' => $warehouse_action_list_array,
'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager()),
'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager()),
// 'deliveryOrders'=>SalesOrderM::DeliveryOrderList($this->getDoctrine()->getManager()),
// 'deliveryOrdersArray'=>SalesOrderM::DeliveryOrderListArray($this->getDoctrine()->getManager()),
// 'deliveryReceipts'=>SalesOrderM::DeliveryReceiptList($this->getDoctrine()->getManager()),
// 'deliveryReceiptsArray'=>SalesOrderM::DeliveryReceiptListArray($this->getDoctrine()->getManager()),
'salesReturnList' => $salesReturnList,
'salesReturnListArray' => $salesReturnListArray,
'productList' => $productList,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'unitList' => $unitList,
'brandList' => $brandList,
'brandListArray' => $brandListArray,
'productListArray' => $productListArray,
'subCategoryListArray' => $subCategoryListArray,
'categoryListArray' => $categoryListArray,
'igListArray' => $igListArray,
'unitListArray' => $unitListArray,
'prefix_list' => array(
[
'id' => 1,
'value' => 'GN',
'text' => 'GN'
]
),
'assoc_list' => array(
[
'id' => 1,
'value' => 1,
'text' => 'GN'
]
),
'INVLIST' => $INVLIST
)
);
}
public function ItemReceivedAndReplacementList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:ItemReceivedAndReplacement')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request)
// 'approved' => GeneralConstant::APPROVED,
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getItemReceivedAndReplacementDate(),
'id' => $entry->getItemReceivedAndReplacementId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render(
'@Sales/pages/list/irr_list.html.twig',
array(
'page_title' => 'Item Return & Replacement List',
'data' => $data
)
);
}
public function ViewItemReceivedAndReplacement(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetItemReceivedAndReplacementDetails($em, $id);
return $this->render(
'@Sales/pages/views/view_irr.html.twig',
array(
'page_title' => 'Item Received And Replacement',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
$id,
$dt['created_by'],
$dt['edited_by']
)
)
);
}
public function PrintItemReceivedAndReplacement(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetItemReceivedAndReplacementDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/print/print_irr.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Item Received And Replacement',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
$id,
$dt['created_by'],
$dt['edited_by']
),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="irr_' . $id . '.pdf"'
)
);
}
return $this->render(
'@Sales/pages/print/print_irr.html.twig',
array(
'page_title' => 'Item Return & Replacement',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
$id,
$dt['created_by'],
$dt['edited_by']
),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
}
public function getAllowedSalesPersonIds(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userId = $request->getSession()->get(UserConstants::USER_ID);
if ($request->isMethod('POST') && $request->request->has('returnJson')) {
return new JsonResponse(
array(
'success' => true,
'allowedSalesPersonIds' => Client::AllowedSalesPersonIds($em, $userId, $companyId, [])
)
);
}
$data = [];
return new JsonResponse(
array(
'success' => true,
'allowedSalesPersonIds' => []
)
);
// return $this->render('@Inventory/pages/views/delivery_receipts.html.twig',
// array(
// 'page_title' => 'Delivery Receipts',
// 'data' => $data,
//
// )
// );
}
//delivery Receipts
public function DeliveryReceiptList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$data = [];
return $this->render(
'@Inventory/pages/views/delivery_receipts.html.twig',
array(
'page_title' => 'Delivery Receipts',
'data' => $data,
)
);
}
public function CreateDeliveryReceipt(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userBranchIdList = $request->getSession()->get('branchIdList');
if ($userBranchIdList == null) $userBranchIdList = [];
$userBranchId = $request->getSession()->get('branchId');
$extId = $id;
$skipInventoryHit = null;
if ($request->query->has('skipInventoryHit'))
$skipInventoryHit = $request->query->get('skipInventoryHit');
if ($request->isMethod('POST')) {
$entity_id = array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$request->request->get('drId')
)) {
if ($request->request->has('returnJson')) {
return new JsonResponse(array(
'success' => false,
// 'documentHash' => 0,
'documentId' => 0,
'documentIdPadded' => str_pad(0, 8, '0', STR_PAD_LEFT),
// 'documentDate' => '',
// 'billIds' => [],
// 'drIds' => [],
// 'pmntTransIds' => [],
'viewUrl' => '',
// 'skipApprovalAction' => $request->request->has('skipApprovalAction')?$request->request->get('skipApprovalAction'):0,
// 'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
// 'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
// 'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
// 'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$receiptId = SalesOrderM::CreateNewDeliveryReceipt(
$this->getDoctrine()->getManager(),
$request->request,
$skipInventoryHit,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
$draftFlag = $request->request->has('draftFlag') ? $request->request->get('draftFlag') : 0;
if ($draftFlag == 0) {
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
$receiptId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
$receiptId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
}
$url = $this->generateUrl(
'view_delivery_receipt'
);
if ($request->request->has('returnJson')) {
// $dr = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
// array(
// 'salesOrderId' => $orderId, ///material
//
// )
// );
return new JsonResponse(array(
'success' => true,
// 'documentHash' => $order->getDocumentHash(),
'documentId' => $receiptId,
'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
'viewUrl' => $url . "/" . $receiptId,
));
} else {
$this->addFlash(
'success',
'New Delivery Receipt Created'
);
return $this->redirect($url . "/" . $receiptId);
}
}
}
$debugData = [];
// $dr_data=$em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
// array(
// 'deliveryReceiptId'=>$dr_id
// )
// );
$new_swld = new \DateTime('2017-07-09');
// if ($entry->getWarranty() > 0)
// $new_swld->modify('+' . $entry->getWarranty() . ' month');
$debugData[] = $new_swld->format('Y-m-d');
$debugData[] = $new_swld;
// $debugData[]=$dr_data->getDeliveryReceiptDate();
$debugData[] = '+' . '1' . ' month';
$branchList = Client::BranchList($em, $companyId, [], $userBranchIdList);
$warehouseIds = [];
foreach ($branchList as $br) {
$warehouseIds[] = $br['warehouseId'];
}
$extDocData = [];
$extDocDataDetails = [];
if ($extId == 0) {
} else {
$extDoc = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findOneBy(
array(
'deliveryReceiptId' => $extId, ///material
)
);
//now if its not editable, redirect to view
if ($extDoc) {
if ($extDoc->getEditFlag() != 1 && $extDoc->getDraftFlag() != 1) {
$url = $this->generateUrl(
'view_delivery_receipt'
);
return $this->redirect($url . "/" . $extId);
} else {
$extDocData = $extDoc;
$extDocDataDetails = $em->getRepository('ApplicationBundle:DeliveryReceiptItem')->findOneBy(
array(
'deliveryReceiptId' => $extId, ///material
)
);
}
} else {
}
}
return $this->render(
'@Sales/pages/input_forms/deliveryReceipt.html.twig',
array(
'page_title' => 'New Delivery Receipt',
'extDocDataDetails' => $extDocDataDetails,
'extDocData' => $extDocData,
'extData' => $extDocData,
'ExistingClients' => Accounts::getClientLedgerHeads($em),
'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($em),
'ClientList' => SalesOrderM::GetClientList($em),
'warehouse' => Inventory::WarehouseList($em, $companyId, $warehouseIds),
'salesOrders' => SalesOrderM::SalesOrderListPendingDelivery($em, $warehouseIds),
'salesOrdersArray' => SalesOrderM::SalesOrderListPendingDeliveryArray($em, $warehouseIds),
'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
'debugData' => $debugData,
)
);
}
public function ViewDeliveryReceipt(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetDeliveryReceiptDetails($em, $id);
return $this->render(
'@Sales/pages/views/delivery_receipt_view.html.twig',
array(
'page_title' => 'View',
'data' => $dt,
'warehouseList' => Inventory::WarehouseList($em),
'warehouseActionList' => Inventory::warehouse_action_list($em, $dt['rel_data']->getCompanyId(), 'object'),
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
$id,
$dt['created_by'],
$dt['edited_by']
) : []
)
);
}
public function PrintDeliveryReceipt(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = SalesOrderM::GetDeliveryReceiptDetails($em, $id);
$print_bar_code_flag = 0;
if ($request->query->has('print_bar_code_flag'))
$print_bar_code_flag = $request->query->get('print_bar_code_flag');
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/print/delivery_receipt_print.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Delivery Receipt ' . $data['doc_hash'],
'data' => $data,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Delivery Receipt (Challan)',
'page_header_sub' => 'Add',
'print_bar_code_flag' => $print_bar_code_flag,
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
$id,
$data['created_by'],
$data['edited_by']
),
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="delivery_challan_' . $id . '.pdf"'
)
);
}
return $this->render(
'@Sales/pages/print/delivery_receipt_print.html.twig',
array(
'page_title' => 'Delivery Receipt ' . $data['doc_hash'],
'data' => $data,
'export' => 'pdf,print',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Delivery Receipt (Challan)',
'page_header_sub' => 'Add',
'print_bar_code_flag' => $print_bar_code_flag,
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
)
);
}
public function ServiceChallanList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:ServiceChallan')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
),
array(
'serviceChallanDate' => 'DESC'
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getServiceChallanDate(),
'id' => $entry->getServiceChallanId(),
'doc_hash' => $entry->getDocumentHash(),
// 'so_amount'=>$entry->getSoAmount(),
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render(
'@Inventory/pages/views/sc_list.html.twig',
array(
'page_title' => 'Service Challan List',
'data' => $data
)
);
}
public function ViewServiceChallan(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = SalesOrderM::GetServiceChallanDetails($em, $id);
return $this->render(
'@Inventory/pages/views/view_service_challan.html.twig',
array(
'page_title' => 'View',
'data' => $dt,
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
$id,
$dt['created_by'],
$dt['edited_by']
) : []
)
);
}
public function PrintServiceChallan(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = SalesOrderM::GetServiceChallanDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
return $this->render(
'@Inventory/pages/print/print_service_challan.html.twig',
array(
'page_title' => 'Service Challan ' . $data['doc_hash'],
'data' => $data,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Service Challan',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
)
);
}
//delivery confirmation
//delivery Receipts
public function DeliveryConfirmationList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryConfirmation')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
),
array(
'deliveryConfirmationDate' => 'DESC'
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getDeliveryConfirmationDate(),
'id' => $entry->getDeliveryConfirmationId(),
'doc_hash' => $entry->getDocumentHash(),
// 'so_amount'=>$entry->getSoAmount(),
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render(
'@Sales/pages/list/delivery_confirmations.html.twig',
array(
'page_title' => 'Delivery Confirmations',
'data' => $data
)
);
}
public function ViewDeliveryConfirmation(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dcon = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryConfirmation')
->findOneBy(
array(
'status' => GeneralConstant::ACTIVE,
'deliveryConfirmationId' => $id
)
);
$dt = SalesOrderM::GetDeliveryConfirmationDetails($em, $id, $dcon->getDeliveryReceiptId());
return $this->render(
'@Sales/pages/views/delivery_confirmation_view.html.twig',
array(
'page_title' => 'View',
'delConData' => $dcon,
'data' => $dt,
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['DeliveryConfirmation'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['DeliveryConfirmation'],
$id,
$dt['created_by'],
$dt['edited_by']
) : []
)
);
}
public function PrintDeliveryConfirmation(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = SalesOrderM::GetSalesOrderDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
return $this->render(
'@Sales/pages/print/sales_order_print.html.twig',
array(
'page_title' => 'Sales Order ' . $data['doc_hash'],
'data' => $data,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Sales Order',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
)
);
}
public function GetClientLatestDetails(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$client_id = $id;
$engine = $this->container->get("templating");
$CD = Client::GetClientDetails($em, $client_id);
if ($CD) {
$Content = $engine->render('@Sales/pages/report/selected_client_details.html.twig', array("cd" => $CD));
return new JsonResponse(array("success" => $client_id, "content" => $Content));
}
return new JsonResponse(array("success" => false));
}
public function GetClientLatestDetailsForSo(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$client_id = $id;
$engine = $this->container->get("templating");
$CD = Client::GetClientDetailsForSoHistory($em, $client_id);
if ($CD) {
$Content = $engine->render('@Sales/pages/report/selected_client_details_for_so.html.twig', array("cd" => $CD));
return new JsonResponse(array("success" => true, "content" => $Content, 'cd' => $CD));
}
return new JsonResponse(array("success" => false, 'cd' => $CD));
}
public function GetSoItemLatestDetails(Request $request)
{
$em = $this->getDoctrine()->getManager();
$search_query = [];
$res_data_by_so_item_id = [];
if ($request->query->has('projectId'))
$search_query['projectId'] = $request->query->get('projectId');
$SO = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrder')
->findOneBy(
$search_query
);
if ($SO) {
$SO_ITEMS = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrderItem')
->findBy(
array(
'salesOrderId' => $SO->getSalesOrderId()
)
);
foreach ($SO_ITEMS as $SO_ITEM) {
$res_data_by_so_item_id[$SO_ITEM->getId()] = array(
'soItemId' => $SO_ITEM->getId(),
'units' => $SO_ITEM->getQty(),
'unitTypeId' => $SO_ITEM->getUnitTypeId(),
'balance' => $SO_ITEM->getBalance(),
'delivered' => (1 * $SO_ITEM->getDelivered()) + (1 * $SO_ITEM->getTransitQty()),
'price' => $SO_ITEM->getPrice(),
'productFdm' => $SO_ITEM->getProductFdm(),
);
}
}
if (!empty($res_data_by_so_item_id)) {
return new JsonResponse(array("success" => true, "content" => $res_data_by_so_item_id));
} else {
return new JsonResponse(array("success" => false, "content" => $res_data_by_so_item_id));
}
return new JsonResponse(array("success" => true, "content" => $res_data_by_so_item_id));
}
public function GetTradeOffersForSo(Request $request)
{
$em = $this->getDoctrine()->getManager();
$Content = [];
$Content_by_id = [];
if ($request->isMethod('POST')) {
$now_time = new \DateTime($request->request->get('qDate'));
$now_time_str = $now_time->format('Y-m-d');
// $now_time_str.= " 00:00:00";
// $now_time_str.= " 00:00:00";
$get_kids_sql = "SELECT trade_offer.* FROM trade_offer WHERE trade_offer.approved=" . GeneralConstant::APPROVED .
" AND trade_offer.status=" . GeneralConstant::ACTIVE;
$get_kids_sql .= " AND ((trade_offer.trade_offer_end_date>= '" . $now_time_str . " 23:59:59'";
$get_kids_sql .= " AND trade_offer.trade_offer_start_date<= '" . $now_time_str . " 00:00:00') or perpetual_flag=1)";
$get_kids_sql .= " order by invoke_type desc;";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$pl = $stmt->fetchAll();
foreach ($pl as $d) {
$tmp = $d;
$tmp['payment_sub_types'] = json_decode($tmp['payment_sub_types'], true) ? json_decode($tmp['payment_sub_types'], true) : [];
$tmp['payment_types'] = json_decode($tmp['payment_types'], true) ? json_decode($tmp['payment_types'], true) : [];
$tmp['payment_methods'] = json_decode($tmp['payment_methods'], true) ? json_decode($tmp['payment_methods'], true) : [];
$tmp['client_types'] = json_decode($tmp['client_types'], true) ? json_decode($tmp['client_types'], true) : [];
$tmp['client_ids'] = json_decode($tmp['client_ids'], true) ? json_decode($tmp['client_ids'], true) : [];
$tmp['branch_ids'] = json_decode($tmp['branch_ids'], true) ? json_decode($tmp['branch_ids'], true) : [];
$tmp['region_ids'] = json_decode($tmp['region_ids'], true) ? json_decode($tmp['region_ids'], true) : [];
$tmp['sales_person_ids'] = json_decode($tmp['sales_person_ids'], true) ? json_decode($tmp['sales_person_ids'], true) : [];
$tmp['data'] = json_decode($tmp['data'], true) ? json_decode($tmp['data'], true) : [];;
$Content[] = $tmp;
$Content_by_id[$d['trade_offer_id']] = $tmp;
}
}
if (!empty($Content)) {
return new JsonResponse(array("success" => 1, "content" => $Content, "content_by_id" => $Content_by_id));
}
return new JsonResponse(array("success" => false, "content" => $Content));
}
public function GetPaymentReceiptHeadsForBranch(Request $request)
{
$em = $this->getDoctrine()->getManager();
$Content = [];
$Content_by_id = [];
$Content_by_id['cashHeadIds'] = [];
$Content_by_id['bankHeadIds'] = [];
if ($request->isMethod('POST')) {
$qryArray = [];
if ($request->request->get('branchId') != '')
$qryArray['branchId'] = $request->request->get('branchId');
$QDLIST = $this->getDoctrine()
->getRepository('ApplicationBundle:Branch')
->findBy(
$qryArray
);
foreach ($QDLIST as $QD) {
$cashHeadIds = json_decode($QD->getCashHeadIds(), true);
if ($cashHeadIds == null) $cashHeadIds = [];
$bankHeadIds = json_decode($QD->getbankHeadIds(), true);
if ($bankHeadIds == null) $bankHeadIds = [];
$Content_by_id['cashHeadIds'] = array_merge($Content_by_id['cashHeadIds'], array_diff($cashHeadIds, $Content_by_id['cashHeadIds']));
$Content_by_id['bankHeadIds'] = array_merge($Content_by_id['bankHeadIds'], array_diff($bankHeadIds, $Content_by_id['bankHeadIds']));
// $Content_by_id['cashHeadIds'] = $cashHeadIds;
// $Content_by_id['bankHeadIds'] = $bankHeadIds;
}
}
if (!empty($Content)) {
return new JsonResponse(array("success" => true, "content" => $Content, "content_by_id" => $Content_by_id));
}
return new JsonResponse(array("success" => true, "content" => $Content, "content_by_id" => $Content_by_id));
}
public function GetPaymentReceiptHeadsForBranchApp(Request $request): JsonResponse
{
$em = $this->getDoctrine()->getManager();
$result = [];
if ($request->isMethod('POST')) {
$qryArray = [];
if ($branchId = $request->request->get('branchId')) {
$qryArray['branchId'] = $branchId;
}
$branches = $this->getDoctrine()
->getRepository('ApplicationBundle:Branch')
->findBy($qryArray);
$allHeadIds = [];
foreach ($branches as $branch) {
$cashHeadIds = json_decode($branch->getCashHeadIds(), true) ?? [];
$bankHeadIds = json_decode($branch->getBankHeadIds(), true) ?? [];
$allHeadIds = array_merge($allHeadIds, $cashHeadIds, $bankHeadIds);
}
$allHeadIds = array_unique($allHeadIds);
if (!empty($allHeadIds)) {
$accountHeadRepo = $this->getDoctrine()->getRepository('ApplicationBundle:AccAccountsHead');
$heads = $accountHeadRepo->findBy(['accountsHeadId' => $allHeadIds]);
foreach ($heads as $head) {
$result[] = [
'id' => (string)$head->getAccountsHeadId(),
'name' => $head->getName()
];
}
}
}
$paymentMethods = [
[
'id' => 1,
'name' => 'Cash'
],
[
'id' => 2,
'name' => 'Credit'
]
];
$basedOn = [
[
'id' => 1,
'name' => 'Price'
],
[
'id' => 2,
'name' => 'Quantity'
],
[
'id' => 3,
'name' => 'Days'
],
];
$billStructure = [
[
'id' => 1,
'name' => 'Completion Of Delivery'
],
[
'id' => 1,
'name' => 'Completion Of Days'
]
];
return new JsonResponse([
"success" => true,
"content" => $result,
'paymentMethod' => $paymentMethods,
'billingStructure' => $billStructure,
'basedOn' => $basedOn
]);
}
public function GetSelectedProductsHistory(Request $request)
{
$em = $this->getDoctrine()->getManager();
$engine = $this->container->get("templating");
$pids = array_unique(explode("::", $_POST["pids"]));
$Products = $em->getRepository('ApplicationBundle:InvProducts')->findBy(array(
'id' => $pids
));
$ProductSales = array();
foreach ($Products as $Product) {
$ProductSales[] = array(
"name" => $Product->getName(),
"unit_price" => "100",
"quantity" => "15"
);
}
$Content = $engine->render('@Sales/pages/report/selected_products_details.html.twig', array('pSalesDetails' => $ProductSales));
$stockPosition = $engine->render('@Sales/pages/report/selected_products_stock_position.html.twig', array('pSalesDetails' => $ProductSales));
return new JsonResponse(array("success" => false, "content" => $Content, "stockPosition" => $stockPosition));
}
public function GetModalForTradeOffer(Request $request)
{
$em = $this->getDoctrine()->getManager();
$engine = $this->container->get("templating");
$discount_type = 1;
$itemSelectionType = 1;
if ($request->request->has('discountType'))
$discount_type = $request->request->get('discountType');
if ($request->request->has('itemSelectionType'))
$discount_type = $request->request->get('itemSelectionType');
$Content = '';
if ($discount_type == 1)
$Content = $engine->render('ApplicationBundle:modals/input_forms:trade_offer_modal_1_1.html.twig', array());
else if ($discount_type == 2)
$Content = $engine->render('ApplicationBundle:modals/input_forms:add_product_to_product_list.html.twig', array());
else if ($discount_type == 3)
$Content = $engine->render('ApplicationBundle:modals/input_forms:add_product_to_product_list.html.twig', array());
else
$Content = $engine->render('ApplicationBundle:modals/input_forms:add_product_to_product_list.html.twig', array());
// $stockPosition=$engine->render('@Sales/pages/report/selected_products_stock_position.html.twig', array('pSalesDetails'=>$ProductSales));
return new JsonResponse(array("success" => false, "content" => $Content,));
}
public function CreateServiceOrder(Request $request)
{
return $this->render(
'@Sales/pages/input_forms/new_service_order.html.twig',
array(
'page_title' => 'New Service Order',
'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager())
)
);
}
public function GetSelectedServiceHistory(Request $request)
{
$em = $this->getDoctrine()->getManager();
$engine = $this->container->get("templating");
$pids = array_unique(explode("::", $_POST["pids"]));
$services = $em->getRepository('ApplicationBundle:AccService')->findBy(array(
'id' => $pids
));
$ProductSales = array();
foreach ($services as &$service) {
$ProductSales[] = array(
"name" => $service->getServiceName(),
"unit_price" => "100",
"quantity" => "15"
);
}
$Content = $engine->render('@Sales/pages/report/selected_products_details.html.twig', array('pSalesDetails' => $ProductSales));
return new JsonResponse(array("success" => false, "content" => $Content));
}
public function CreateTransportBill(Request $request)
{
return $this->render(
'@Sales/pages/input_forms/transport_bill.html.twig',
array(
'page_title' => 'New Transport Bill'
)
);
}
public function CreateSalesBill(Request $request)
{
return $this->render(
'@Sales/pages/input_forms/sales_bill.html.twig',
array(
'page_title' => 'New Sales Bill'
)
);
}
public function CreateServiceBill(Request $request)
{
return $this->render(
'@Sales/pages/input_forms/service_bill.html.twig',
array(
'page_title' => 'New Service Bill'
)
);
}
public function CreateClient(Request $request, $id = 0)
{
$exClientId = $id;
if ($exClientId == 0)
$exClientId = $request->query->has("ex_c_id") ? $request->query->get("ex_c_id") : null;
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
if ($request->isMethod('POST')) {
if ($request->request->get('exClientID', false)) {
$IFUpdated = Client::UpdateClient(
$em,
$this->getLoggedUserCompanyId($request),
$request->request->get('exClientID'),
$request->request->get('clientName'),
$request->request->get('contactPersonName'),
$request->request->get('clientDue') == '' ? 0 : $request->request->get('clientDue'),
$request->request->get('initialOpeningBalance') == '' ? 0 : $request->request->get('initialOpeningBalance'),
$request->request->get('salesPersonID'),
$request->request->get('type'),
$request->request->get('regionId'),
$request->request->get('countryId'),
$request->request->get('geographicalRegionId'),
$request->request->get('clientNumericalCode'),
$request->request->get('clientAreaWiseCode'),
$request->request->get('clientShortCode'),
$request->request->get('clientAlternateCode'),
0,
// $request->request->get('divisionId'),
$request->request->get('addressContact'),
$request->request->get('contactNumber'),
$request->request->get('shippingAddress'),
$request->request->get('billingAddress'),
$request->request->get('email'),
$request->request->get('fax'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
$request->request->get('accountsHeadId', '_UNSET_'),
$request->request->get('advanceHeadId', '_UNSET_'),
$request->request->get('allowedBrandIds', null),
$request->request->get('creditLimitEnabled', 0),
$request->request->get('creditLimit', null),
$request->request->get('generalInfoTin', null),
$request->request->get('generalInfoBin', null),
$request->request->get('isIndividual', null),
$request->request->get('defaultCourierId', 0)
);
if ($IFUpdated) {
$this->addFlash(
'success',
'Client Updated'
);
} else {
$this->addFlash(
'error',
'Client have not been updated'
);
}
// return $this->redirectToRoute("create_client");
} else {
Client::CreateNewClient(
$em,
$this->getLoggedUserCompanyId($request),
$request->request->get('clientName'),
$request->request->get('clientDue') == '' ? 0 : $request->request->get('clientDue'),
$request->request->get('initialOpeningBalance') == '' ? 0 : $request->request->get('initialOpeningBalance'),
$request->request->get('contactPersonName'),
$request->request->get('salesPersonID'),
$request->request->get('type'),
$request->request->get('regionId'),
$request->request->get('countryId'),
$request->request->get('geographicalRegionId'),
$request->request->get('clientNumericalCode'),
$request->request->get('clientAreaWiseCode'),
$request->request->get('clientShortCode'),
$request->request->get('clientAlternateCode'),
// $request->request->get('divisionId'),
0,
$request->request->get('addressContact'),
$request->request->get('contactNumber'),
$request->request->get('shippingAddress'),
$request->request->get('billingAddress'),
$request->request->get('email'),
$request->request->get('fax'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('accountsHeadId', '_UNSET_'),
$request->request->get('advanceHeadId', '_UNSET_'),
$request->request->get('allowedBrandIds', null),
$request->request->get('creditLimitEnabled', 0),
$request->request->get('creditLimit', null),
$request->request->get('generalInfoTin', null),
$request->request->get('generalInfoBin', null),
$request->request->get('isIndividual', null),
$request->request->get('defaultCourierId', 0)
);
}
Client::ProcessTempClients($em, $companyId);
}
return $this->render(
'@Sales/pages/input_forms/create_client.html.twig',
array(
'page_title' => 'New Client',
'existingClientID' => $exClientId,
'brand_list' => Inventory::GetBrandList($em, $this->getLoggedUserCompanyId($request)),
'client_types' => Client::ClientTypeList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'region_data' => Client::RegionListForClientEntry($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'geographical_region_data' => Client::GeographicalRegionListForClientEntry($this->getDoctrine()->getManager(), 19, $this->getLoggedUserCompanyId($request)),
'division_list' => Client::DivisionList($this->getDoctrine()->getManager()),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
'sales_person_list_array' => Client::SalesPersonListArray($this->getDoctrine()->getManager()),
'heads' => Accounts::getLedgerHeadsWithParents($em)
)
);
}
public function CreateClientForApp(Request $request, $id = 0)
{
$exClientId = $id;
if ($exClientId == 0)
$exClientId = $request->query->has("ex_c_id") ? $request->query->get("ex_c_id") : null;
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
if ($request->isMethod('POST')) {
if ($request->request->get('exClientID', false)) {
$IFUpdated = Client::UpdateClient(
$em,
$this->getLoggedUserCompanyId($request),
$request->request->get('exClientID'),
$request->request->get('clientName'),
$request->request->get('contactPersonName'),
$request->request->get('clientDue') == '' ? 0 : $request->request->get('clientDue'),
$request->request->get('initialOpeningBalance') == '' ? 0 : $request->request->get('initialOpeningBalance'),
$request->request->get('salesPersonID'),
$request->request->get('type'),
$request->request->get('regionId'),
$request->request->get('countryId'),
$request->request->get('geographicalRegionId'),
$request->request->get('clientNumericalCode'),
$request->request->get('clientAreaWiseCode'),
$request->request->get('clientShortCode'),
$request->request->get('clientAlternateCode'),
0,
// $request->request->get('divisionId'),
$request->request->get('addressContact'),
$request->request->get('contactNumber'),
$request->request->get('shippingAddress'),
$request->request->get('billingAddress'),
$request->request->get('email'),
$request->request->get('fax'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
0,
$request->request->get('accountsHeadId', '_UNSET_'),
$request->request->get('advanceHeadId', '_UNSET_'),
$request->request->get('allowedBrandIds', null),
$request->request->get('creditLimitEnabled', 0),
$request->request->get('creditLimit', null),
$request->request->get('generalInfoTin', null),
$request->request->get('generalInfoBin', null),
$request->request->get('isIndividual', null),
$request->request->get('defaultCourierId', 0)
);
if ($IFUpdated) {
$this->addFlash(
'success',
'Client Updated'
);
} else {
$this->addFlash(
'error',
'Client have not been updated'
);
}
// return $this->redirectToRoute("create_client");
} else {
Client::CreateNewClient(
$em,
$this->getLoggedUserCompanyId($request),
$request->request->get('clientName'),
$request->request->get('clientDue') == '' ? 0 : $request->request->get('clientDue'),
$request->request->get('initialOpeningBalance') == '' ? 0 : $request->request->get('initialOpeningBalance'),
$request->request->get('contactPersonName'),
$request->request->get('salesPersonID'),
$request->request->get('type'),
$request->request->get('regionId'),
$request->request->get('countryId'),
$request->request->get('geographicalRegionId'),
$request->request->get('clientNumericalCode'),
$request->request->get('clientAreaWiseCode'),
$request->request->get('clientShortCode'),
$request->request->get('clientAlternateCode'),
// $request->request->get('divisionId'),
0,
$request->request->get('addressContact'),
$request->request->get('contactNumber'),
$request->request->get('shippingAddress'),
$request->request->get('billingAddress'),
$request->request->get('email'),
$request->request->get('fax'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('accountsHeadId', '_UNSET_'),
$request->request->get('advanceHeadId', '_UNSET_'),
$request->request->get('allowedBrandIds', null),
$request->request->get('creditLimitEnabled', 0),
$request->request->get('creditLimit', null),
$request->request->get('generalInfoTin', null),
$request->request->get('generalInfoBin', null),
$request->request->get('isIndividual', null),
$request->request->get('defaultCourierId', 0)
);
}
Client::ProcessTempClients($em, $companyId);
}
return new JsonResponse(
array(
'success' => true,
)
);
}
public function UpdateClientOnTheFly(Request $request, $id = 0)
{
$exClientId = $id;
if ($exClientId == 0)
$exClientId = $request->request->has("clientId") ? $request->request->get("clientId") : null;
$returnTableData = $request->request->has("returnTableData") ? $request->request->get("returnTableData") : 0;
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$data = [];
if ($request->isMethod('POST')) {
if ($request->request->has('clientId')) {
$entry = Client::UpdateClientOnTheFly(
$em,
$this->getLoggedUserCompanyId($request),
$request->request->get('clientId'),
$request->request->get('clientName'),
$request->request->get('contactPersonName'),
$request->request->get('clientDue') == '' ? 0 : $request->request->get('clientDue'),
$request->request->has('initialOpeningBalance') ? $request->request->get('initialOpeningBalance') : 0,
$request->request->get('salesPersonID'),
$request->request->get('type'),
$request->request->get('regionId'),
$request->request->get('countryId'),
$request->request->get('geographicalRegionId', null),
$request->request->get('clientNumericalCode', ''),
$request->request->get('clientAreaWiseCode', ''),
$request->request->get('clientShortCode', ''),
$request->request->get('clientAlternateCode', ''),
0,
// $request->request->get('divisionId'),
$request->request->get('addressContact', $request->request->get('billingAddress', '')),
$request->request->get('contactNumber'),
$request->request->get('shippingAddress'),
$request->request->get('billingAddress'),
$request->request->get('email'),
$request->request->get('fax', ''),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('tempFlag', 0)
);
if ($entry) {
if ($returnTableData == 1) {
$get_kids_sql = "SELECT * FROM acc_clients
WHERE client_id=" . $entry->getClientId();
// $get_kids_sql .=' ORDER BY name ASC';
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$em->flush();
$check_here = $stmt->fetchAll();
$data = $check_here[0];
$data['id'] = $entry->getClientId();
$data['value'] = $entry->getClientId();
$data['text'] = $entry->getClientName();
} else {
$data = array(
'id' => $entry->getClientId(),
'value' => $entry->getClientId(),
'name' => $entry->getClientName(),
'contactNumber' => $entry->getContactNumber(),
'email' => $entry->getEmail(),
'numericalCode' => $entry->getClientNumericalCode(),
'invoiced' => $entry->getClientInvoiceAmount(),
'received' => $entry->getClientReceived(),
'due' => $entry->getClientDue(),
'clientType' => $entry->getType(),
'regionId' => $entry->getRegionId(),
'accHeadId' => $entry->getAccountsHeadId(),
'salesPersonId' => $entry->getSalesPersonId(),
'advanceHeadId' => $entry->getAdvanceHeadId(),
'tempFlag' => $entry->getTempClientFlag(),
);
}
return new JsonResponse(
array(
'success' => true,
'data' => $data
)
);
} else {
return new JsonResponse(
array(
'success' => false,
'data' => $data
)
);
}
// return $this->redirectToRoute("create_client");
} else {
return new JsonResponse(
array(
'success' => false,
'data' => $data
)
);
}
}
return new JsonResponse(
array(
'success' => false,
'data' => $data
)
);
}
public function UpdateSecondaryClientOnTheFly(Request $request, $id = 0)
{
$exClientId = $id;
if ($exClientId == 0)
$exClientId = $request->request->has("clientId") ? $request->request->get("clientId") : null;
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$data = [];
if ($request->isMethod('POST')) {
if ($request->request->has('clientId')) {
$entry = Client::UpdateSecondaryClientOnTheFly(
$em,
$this->getLoggedUserCompanyId($request),
$request->request->get('clientId'),
$request->request->get('clientName'),
$request->request->get('contactPersonName'),
$request->request->get('clientDue') == '' ? 0 : $request->request->get('clientDue'),
$request->request->has('initialOpeningBalance') ? $request->request->get('initialOpeningBalance') : 0,
$request->request->get('salesPersonID'),
$request->request->get('type'),
$request->request->get('regionId'),
$request->request->get('countryId'),
$request->request->get('geographicalRegionId', null),
$request->request->get('clientNumericalCode', ''),
$request->request->get('clientAreaWiseCode', ''),
$request->request->get('clientShortCode', ''),
$request->request->get('clientAlternateCode', ''),
0,
// $request->request->get('divisionId'),
$request->request->get('addressContact', $request->request->get('billingAddress', '')),
$request->request->get('contactNumber'),
$request->request->get('shippingAddress'),
$request->request->get('billingAddress'),
$request->request->get('email'),
$request->request->get('fax', ''),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('tempFlag', 0)
);
if ($entry) {
$data = array(
'id' => $entry->getClientId(),
'value' => $entry->getClientId(),
'name' => $entry->getClientName(),
'contactNumber' => $entry->getContactNumber(),
'email' => $entry->getEmail(),
'numericalCode' => $entry->getClientNumericalCode(),
'invoiced' => $entry->getClientInvoiceAmount(),
'received' => $entry->getClientReceived(),
'due' => $entry->getClientDue(),
'clientType' => $entry->getType(),
'regionId' => $entry->getRegionId(),
'accHeadId' => $entry->getAccountsHeadId(),
'salesPersonId' => $entry->getSalesPersonId(),
'advanceHeadId' => $entry->getAdvanceHeadId(),
'tempFlag' => $entry->getTempClientFlag(),
);
return new JsonResponse(
array(
'success' => true,
'data' => $data
)
);
} else {
return new JsonResponse(
array(
'success' => false,
'data' => $data
)
);
}
// return $this->redirectToRoute("create_client");
} else {
return new JsonResponse(
array(
'success' => false,
'data' => $data
)
);
}
}
return new JsonResponse(
array(
'success' => false,
'data' => $data
)
);
}
public function ProcessTempClient(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$head_id = $id;
$companyId = $this->getLoggedUserCompanyId($request);
$loginId = $this->getLoggedUserCompanyId($request);
$latestCID = Client::ProcessTempClients($em, $companyId, [], true);
if ($latestCID != 0) {
return new JsonResponse(array(
"success" => true,
"last_id" => $latestCID,
// "r"=>$r,
// "debug_data"=>System::encryptSignature($r)
));
} else {
return new JsonResponse(array(
"success" => false,
"last_id" => $latestCID,
// "r"=>$r,
// "debug_data"=>System::encryptSignature($r)
));
}
// return $this->redirectToRoute('dashboard');
}
public function SalesRegion(Request $request, $id)
{
$cc_id = '';
$cc_name = '';
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$regionId = 0;
$em = $this->getDoctrine()->getManager();
if ($request->request->get('regionId') != '' && $request->request->get('regionId') != 0) {
$em = $this->getDoctrine()->getManager();
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle:Region')
->findOneBy(
array(
'id' => $request->request->get('regionId'),
)
);
$new_cc->setName($request->request->get('name'));
$new_cc->setCode($request->request->get('code'));
$new_cc->setCountryId($request->request->get('countryId'));
$new_cc->setCompanyId($companyId);
$new_cc->setParentRegionId($request->request->get('parentRegionId'));
$new_cc->setSalesPersonId($request->request->get('salesPersonId'));
$new_cc->setRegionHeadId($request->request->get('regionHeadId'));
$new_cc->setSalesPersonIds(json_encode($request->request->get('salesPersonIds')));
$new_cc->setRegionLevelId($request->request->get('regionLevelId'));
$em->flush();
$regionId = $id;
} else {
$new_cc = new Region();
$new_cc->setName($request->request->get('name'));
$new_cc->setCode($request->request->get('code'));
$new_cc->setCountryId($request->request->get('countryId'));
$new_cc->setCompanyId($companyId);
$new_cc->setParentRegionId($request->request->get('parentRegionId'));
$new_cc->setSalesPersonId($request->request->get('salesPersonId'));
$new_cc->setRegionHeadId($request->request->get('regionHeadId'));
$new_cc->setSalesPersonIds(json_encode($request->request->get('salesPersonIds')));
$new_cc->setRegionLevelId($request->request->get('regionLevelId'));
$em->persist($new_cc);
$em->flush();
$regionId = $new_cc->getId();
}
$related_head_for_path_tree = explode('/', $request->request->get('pathTree'));
$related_head_for_path_tree[] = $regionId;
Client::UpdateRegionPath($em, $related_head_for_path_tree, $companyId);
//now update salesperson on any client if available
if ($request->request->has('imposeSalesPersonChange')) {
$clients_for_region = $this->getDoctrine()
->getRepository('ApplicationBundle:AccClients')
->findBy(
array(
'regionId' => $regionId,
)
);
foreach ($clients_for_region as $client) {
$client->setSalesPersonId($request->request->get('salesPersonId'));
}
$em->flush();
}
}
$extRegionData = [];
if ($id != 0) {
$extRegionData = $this->getDoctrine()
->getRepository('ApplicationBundle:Region')
->findOneBy(
array(
'id' => $id
)
);
// $cc_data_list = [];
// foreach ($cc_data as $value) {
// $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
// $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
//
// if ($value->getSupplierCategoryId() == $id) {
// $cc_id = $value->getSupplierCategoryId();
// $cc_name = $value->getName();
// }
// }
}
return $this->render(
'@Sales/pages/input_forms/sales_region.html.twig',
array(
'page_title' => 'Sales Region',
'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $companyId),
'extRegionData' => $extRegionData,
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
// 'countryList'=>SalesOrderM::Co
)
);
}
public function Branch(Request $request, $id)
{
$cc_id = '';
$cc_name = '';
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$new_cc = [];
$regionId = 0;
$warehouseId = $request->request->get('warehouseId');
if ($request->request->get('branchId') != '' && $request->request->get('branchId') != 0) {
$em = $this->getDoctrine()->getManager();
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle:Branch')
->findOneBy(
array(
'branchId' => $request->request->get('branchId'),
)
);
$new_cc->setName($request->request->get('name'));
$new_cc->setAddress($request->request->get('address'));
$new_cc->setDeliveryAddress($request->request->get('deliveryAddress'));
$new_cc->setBillingAddress($request->request->get('billingAddress'));
$new_cc->setWarehouseId($request->request->get('warehouseId'));
$new_cc->setCashHeadIds(json_encode($request->request->get('cashHeadIds')));
$new_cc->setBankHeadIds(json_encode($request->request->get('bankHeadIds')));
$new_cc->setCompanyId($companyId);
$new_cc->setType($request->request->get('type'));
$new_cc->setReplacementAllowed($request->request->get('replacementAllowed', 0));
$new_cc->setDeliveryAllowed($request->request->get('deliveryAllowed', 0));
$new_cc->setSellAllowed($request->request->get('sellAllowed', 0));
$new_cc->setSalesMethod($request->request->get('salesMethod'));
$new_cc->setDeliveryProcessType($request->request->get('deliveryProcessType'));
$new_cc->setPaymentProcessType($request->request->get('paymentProcessType'));
$em->flush();
$branchId = $new_cc->getBranchId();
$this->addFlash(
'success',
'Branch Information Updated'
);
} else {
$new_cc = new Branch();
$new_cc->setName($request->request->get('name'));
$new_cc->setWarehouseId($request->request->get('warehouseId'));
$new_cc->setCashHeadIds(json_encode($request->request->get('cashHeadIds')));
$new_cc->setBankHeadIds(json_encode($request->request->get('bankHeadIds')));
$new_cc->setCompanyId($companyId);
$new_cc->setType($request->request->get('type'));
$new_cc->setSalesMethod($request->request->get('salesMethod'));
$new_cc->setDeliveryProcessType($request->request->get('deliveryProcessType'));
$new_cc->setPaymentProcessType($request->request->get('paymentProcessType'));
$new_cc->setReplacementAllowed($request->request->get('replacementAllowed', 0));
$new_cc->setDeliveryAllowed($request->request->get('deliveryAllowed', 0));
$new_cc->setSellAllowed($request->request->get('sellAllowed', 0));
$em->persist($new_cc);
$em->flush();
$branchId = $new_cc->getBranchId();
$em->flush();
$this->addFlash(
'success',
'New Branch Added'
);
}
//now update salesperson on any client if available
$warehouse = null;
if ($request->request->has('addWarehouseToSystem')) {
if ($warehouseId == 0 || $warehouseId == '') {
$warehouse = new Warehouse();
$warehouse->setCompanyId($companyId);
$warehouse->setName($request->request->get('name'));
$warehouse->setStatus(GeneralConstant::ACTIVE);
$warehouse->setReplacementAllowed($request->request->get('replacementAllowed', 0));
$warehouse->setDeliveryAllowed($request->request->get('deliveryAllowed', 0));
$warehouse->setSellAllowed($request->request->get('sellAllowed', 0));
$em->persist($warehouse);
$em->flush();
$new_cc->setWarehouseId($warehouse->getId());
$em->flush();
} else {
$warehouse = $this->getDoctrine()
->getRepository('ApplicationBundle:Warehouse')
->findOneBy(
array(
'id' => $new_cc->getWarehouseId(),
)
);;
// $warehouse->setCompanyId($companyId);
// $warehouse->setName($request->request->get('name'));
// $warehouse->setStatus(GeneralConstant::ACTIVE);
// $warehouse->setReplacementAllowed($request->request->get('replacementAllowed',0));
// $warehouse->setDeliveryAllowed($request->request->get('deliveryAllowed',0));
// $warehouse->setSellAllowed($request->request->get('sellAllowed',0));
// $em->persist($warehouse);
// $em->flush();
// $new_cc->setWarehouseId($warehouse->getId());
// $em->flush();
}
}
if ($warehouse) {
} else
$warehouse = $this->getDoctrine()
->getRepository('ApplicationBundle:Warehouse')
->findOneBy(
array(
'id' => $new_cc->getWarehouseId(),
)
);;
if ($warehouse) {
$warehouse->setReplacementAllowed($request->request->get('replacementAllowed', 0));
$warehouse->setDeliveryAllowed($request->request->get('deliveryAllowed', 0));
$warehouse->setSellAllowed($request->request->get('sellAllowed', 0));
// $em->persist($warehouse);
// $em->flush();
// $new_cc->setWarehouseId($warehouse->getId());
$em->flush();
}
if ($request->request->has('addCashHeadToSystem')) {
$id_list = json_decode($new_cc->getCashHeadIds(), true);
if ($id_list == [] || $id_list == null) {
if ($id_list == null)
$id_list = [];
//now get the cash parent for branch head
$par_set = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'branch_cash_parent'
));
$par_head = '';
if ($par_set)
$par_head = $par_set->getData();
if ($par_head == '') {
$this->addFlash(
'error',
'Could not add cash head. Parent not found in settings'
);
} else {
//create The head
$accHead = Accounts::CreateNewHead($em, GeneralConstant::OPENING_YEAR, $par_head, 'Cash at ' . $new_cc->getName(), '', 0, 0, 'dr', $request->getSession()->get(UserConstants::USER_LOGIN_ID));
$id_list = Accounts::addNumberToArrayIfNotExists($accHead, $id_list);
$new_cc->setCashHeadIds(json_encode($id_list));
$em->flush();
}
}
}
if ($request->request->has('addBankHeadToSystem')) {
$id_list = json_decode($new_cc->getBankHeadIds(), true);
if ($id_list == [] || $id_list == null) {
if ($id_list == null)
$id_list = [];
//now get the bank parent for branch head
$par_set = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'branch_bank_parent'
));
$par_head = '';
if ($par_set)
$par_head = $par_set->getData();
if ($par_head == '') {
$this->addFlash(
'error',
'Could not add bank head. Parent not found in settings'
);
} else {
//create The head
$accHead = Accounts::CreateNewHead($em, GeneralConstant::OPENING_YEAR, $par_head, 'Bank at ' . $new_cc->getName(), '', 0, 0, 'dr', $request->getSession()->get(UserConstants::USER_LOGIN_ID));
$id_list = Accounts::addNumberToArrayIfNotExists($accHead, $id_list);
$new_cc->setBankHeadIds(json_encode($id_list));
$em->flush();
}
}
}
}
$extData = [];
if ($id != 0) {
$extData = $this->getDoctrine()
->getRepository('ApplicationBundle:Branch')
->findOneBy(
array(
'branchId' => $id
)
);
// $cc_data_list = [];
// foreach ($cc_data as $value) {
// $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
// $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
//
// if ($value->getSupplierCategoryId() == $id) {
// $cc_id = $value->getSupplierCategoryId();
// $cc_name = $value->getName();
// }
// }
}
return $this->render(
'@Sales/pages/input_forms/branch.html.twig',
array(
'page_title' => 'Company Branch',
'branchList' => $this->getDoctrine()
->getRepository('ApplicationBundle:Branch')
->findBy(
array(
'CompanyId' => $companyId
)
),
'extData' => $extData,
'headList' => Accounts::getParentLedgerHeads($em),
'branchTypes' => SalesConstant::$branchTypes,
'branchTypeDetails' => SalesConstant::$branchTypeDetails,
'salesMethodList' => SalesConstant::$salesMethod,
'deliveryProcessTypes' => SalesConstant::$deliveryProcessType,
'paymentProcessTypes' => SalesConstant::$paymentProcessType,
'warehouseList' => Inventory::WarehouseList($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
// 'countryList'=>SalesOrderM::Co
)
);
}
public function SalesPerson(Request $request, $id)
{
$cc_id = '';
$cc_name = '';
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$regionIds = [];
$regionLeaderFlags = [];
$employeeId = 0;
$file_path = null;
foreach ($request->files as $uploadedFile) {
if ($uploadedFile != null) {
$fileName = md5(uniqid()) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' . $request->request->get('userId') . '/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
if ($path != "")
$file_path = 'uploads/FileUploads/' . $request->request->get('userId') . '/' . $path;
}
}
$name = $request->request->get('name');
$LoginID = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
if ($request->request->get('employeeId') != '' && $request->request->get('employeeId') != 0) {
$em = $this->getDoctrine()->getManager();
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle:Employee')
->findOneBy(
array(
'employeeId' => $request->request->get('employeeId'),
)
);
$AccHeadId = $new_cc->getAccountsHeadId();
if ($AccHeadId == 0 || $AccHeadId == null || $AccHeadId == '') {
$general_parent = 0;
$general_parent_head = $em->getRepository('ApplicationBundle:AccAccountsHead')
->findOneBy(array(
'markerHash' => AccountsConstant::GENERAL_EMPLOYEE_PARENT
));
if ($general_parent)
$AccHeadId = Accounts::CreateNewHead($em, GeneralConstant::OPENING_YEAR, $general_parent_head->getAccountsHeadId(), $name, '', 0, 0, 'cr', $LoginID);
else
$AccHeadId = null;
}
$new_cc->setAccountsHeadId($AccHeadId);
$new_cc->setName($request->request->get('name'));
$new_cc->setAllowedBrandIds(json_encode($request->request->get('allowedBrandIds')));
$new_cc->setCountryId($request->request->get('countryId'));
$new_cc->setCompanyId($companyId);
$new_cc->setBranchId($request->request->get('branchId'));
$new_cc->setEmployeeCode($request->request->get('employeeCode'));
$new_cc->setAddressContact($request->request->get('addressContact'));
$new_cc->setContactNumber($request->request->get('contactNumber'));
$new_cc->setPositionId($request->request->get('positionId'));
$new_cc->setUserId($request->request->get('userId'));
$new_cc->setSupervisorId($request->request->get('supervisorId'));
$new_cc->setImage($file_path);
$new_cc->setSalesPersonFlag($request->request->has('salesPersonFlag') ? 1 : 0);
$regionIds = [];
$regionLeaderFlags = [];
if ($request->request->has('regionId')) {
foreach ($request->request->get('regionId') as $key => $val) {
if ($val != '' && $val != 0) {
$regionIds[] = $request->request->get('regionId')[$key];
$regionLeaderFlags[] = $request->request->get('regionLeaderFlag')[$key];
}
}
}
$new_cc->setRegionIds(json_encode($regionIds));
$new_cc->setRegionLeaderFlags(json_encode($regionLeaderFlags));
$em->flush();
$employeeId = $new_cc->getEmployeeId();
} else {
$new_cc = new Employee();
$general_parent = 0;
$general_parent_head = $em->getRepository('ApplicationBundle:AccAccountsHead')
->findOneBy(array(
'markerHash' => AccountsConstant::GENERAL_EMPLOYEE_PARENT
));
if ($general_parent)
$AccHeadId = Accounts::CreateNewHead($em, GeneralConstant::OPENING_YEAR, $general_parent_head->getAccountsHeadId(), $name, '', 0, 0, 'cr', $LoginID);
else
$AccHeadId = null;
$new_cc->setAccountsHeadId($AccHeadId);
$new_cc->setName($request->request->get('name'));
$new_cc->setCountryId($request->request->get('countryId'));
$new_cc->setCompanyId($companyId);
$new_cc->setBranchId($request->request->get('branchId'));
$new_cc->setAllowedBrandIds(json_encode($request->request->get('allowedBrandIds')));
$new_cc->setEmployeeCode($request->request->get('employeeCode'));
$new_cc->setAddressContact($request->request->get('addressContact'));
$new_cc->setContactNumber($request->request->get('contactNumber'));
$new_cc->setPositionId($request->request->get('positionId'));
$new_cc->setUserId($request->request->get('userId'));
$new_cc->setSupervisorId($request->request->get('supervisorId'));
$new_cc->setImage($file_path);
$new_cc->setSalesPersonFlag($request->request->has('salesPersonFlag') ? 1 : 0);
$regionIds = [];
$regionLeaderFlags = [];
if ($request->request->has('regionId')) {
foreach ($request->request->get('regionId') as $key => $val) {
if ($val != '' && $val != 0) {
$regionIds[] = $request->request->get('regionId')[$key];
$regionLeaderFlags[] = $request->request->get('regionLeaderFlag')[$key];
}
}
}
$new_cc->setRegionIds(json_encode($regionIds));
$new_cc->setRegionLeaderFlags(json_encode($regionLeaderFlags));
$em->persist($new_cc);
$em->flush();
$employeeId = $new_cc->getEmployeeId();
}
foreach ($regionIds as $k => $regionId) {
$reg = $this->getDoctrine()
->getRepository('ApplicationBundle:Region')
->findOneBy(
array(
'id' => $regionId,
)
);
if ($reg) {
if ($reg->getSalesPersonIds() == null)
$ext_sp_id_list = [];
else
$ext_sp_id_list = json_decode($reg->getSalesPersonIds(), true);
if ($ext_sp_id_list == null)
$ext_sp_id_list = [];
$ext_sp_id_list = Accounts::addNumberToArrayIfNotExists($employeeId, $ext_sp_id_list);
$reg->setSalesPersonIds(json_encode($ext_sp_id_list));
if ($regionLeaderFlags[$k] == 1) {
$reg->setRegionHeadId($employeeId);
}
$em->flush();
}
}
// Client::UpdateRegionPath($em,$related_head_for_path_tree,$companyId);
//now update salesperson on any client if available
// if($request->request->has('imposeSalesPersonChange'))
// {
// $clients_for_region = $this->getDoctrine()
// ->getRepository('ApplicationBundle:AccClients')
// ->findBy(
// array(
// 'regionId' => $regionId,
// )
// );
// foreach($clients_for_region as $client)
// {
// $client->setSalesPersonId($request->request->get('salesPersonId'));
//
// }
// $em->flush();
// }
}
$extEmployeeData = [];
if ($id != 0) {
$extEmployeeData = $this->getDoctrine()
->getRepository('ApplicationBundle:Employee')
->findOneBy(
array(
'employeeId' => $id
)
);
// $cc_data_list = [];
// foreach ($cc_data as $value) {
// $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
// $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
//
// if ($value->getSupplierCategoryId() == $id) {
// $cc_id = $value->getSupplierCategoryId();
// $cc_name = $value->getName();
// }
// }
}
return $this->render(
'@Sales/pages/input_forms/create_sales_person.html.twig',
array(
'page_title' => 'Sales Person',
'region_data' => Client::RegionList($this->getDoctrine()->getManager(), $companyId),
'extData' => $extEmployeeData,
'brand_list' => Inventory::GetBrandList($em, $this->getLoggedUserCompanyId($request)),
'users' => Users::getUserListById($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
'branch_list' => Client::BranchList($this->getDoctrine()->getManager(), $companyId),
// 'countryList'=>SalesOrderM::Co
)
);
}
public function ConvertUserToSalesPerson(Request $request)
{
$qryArray = [];
$userIdList = [];
$em = $this->getDoctrine()->getManager();
// if($request->request->has('department'))
// {
//
// $positions=$em->getRepository('ApplicationBundle:SysDepartmentPosition')->findBy(
// array(
// 'departmentId'=>$positionId
// )
// );
// }
$companyId = $this->getLoggedUserCompanyId($request);
// $qryArray['CompanyId']=$companyId;
$dt = Client::ConvertUserToSalesPerson($em, $qryArray);
return new JsonResponse(array("success" => true, "content" => $dt));
}
public function CreatePackage(Request $request)
{
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
if (isset($_POST['products'])) {
$Products = array(
'products' => $_POST['products'],
'product_units' => $_POST['product_units'],
'product_unit_price' => $_POST['product_unit_price'],
'product_total_price' => $_POST['product_total_price'],
'product_reference_price' => $_POST['product_reference_price']
);
} else {
$Products = array();
}
if (isset($_POST['services'])) {
$Services = array(
'services' => $_POST['services'],
'services_units' => $_POST['services_units'],
'services_unit_price' => $_POST['services_unit_price'],
'services_total_price' => $_POST['services_total_price'],
'services_reference_price' => $_POST['services_reference_price']
);
} else {
$Services = array();
}
if (isset($_POST['heads'])) {
$ArCosts = array(
'heads' => $_POST['heads'],
'ar_units' => $_POST['ar_units'],
'ar_unit_price' => $_POST['ar_unit_price'],
'ar_total_price' => $_POST['ar_total_price'],
'ar_reference_price' => $_POST['ar_reference_price']
);
} else {
$ArCosts = array();
}
$pckgId = Package::CreatePackage(
$em,
$request->request->get('packageName'),
$request->request->get('categoryID'),
$request->request->get('subCategory'),
$request->request->get('salesWarrenty'),
$request->request->get('note'),
json_encode(
$Products
),
json_encode(
$Services
),
json_encode(
$ArCosts
),
$request->request->get('markupPercentage'),
$request->request->get('totalCost'),
$request->request->get('totalStoreCost'),
$request->request->get('totalNonStoreCost'),
$request->request->get('salesValue'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ProductPackage']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['ProductPackage'],
$pckgId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ProductPackage'],
$pckgId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'New Package Added.'
);
}
return $this->render(
'@Sales/pages/input_forms/create_package.html.twig',
array(
'page_title' => 'Add Package',
'product_list' => Inventory::ProductListArray($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'product_list_obj' => Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request))
)
);
}
public function mrpOld(Request $request, $id = 0)
{
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
if (isset($_POST['products'])) {
$Products = array(
'products' => $_POST['products'],
'product_units' => $_POST['product_units'],
'product_unit_price' => $_POST['product_unit_price'],
'product_total_price' => $_POST['product_total_price'],
'product_reference_price' => $_POST['product_reference_price']
);
} else {
$Products = array();
}
if (isset($_POST['services'])) {
$Services = array(
'services' => $_POST['services'],
'services_units' => $_POST['services_units'],
'services_unit_price' => $_POST['services_unit_price'],
'services_total_price' => $_POST['services_total_price'],
'services_reference_price' => $_POST['services_reference_price']
);
} else {
$Services = array();
}
if (isset($_POST['heads'])) {
$ArCosts = array(
'heads' => $_POST['heads'],
'ar_units' => $_POST['ar_units'],
'ar_unit_price' => $_POST['ar_unit_price'],
'ar_total_price' => $_POST['ar_total_price'],
'ar_reference_price' => $_POST['ar_reference_price']
);
} else {
$ArCosts = array();
}
$mrpId = Package::CreateProductMrpDocument(
$em,
$id,
$request->request->get('product'),
$request->request->get('salesWarrenty'),
$request->request->get('note'),
$request->request->get('product_total_price'),
json_encode(
$Services
),
json_encode(
$ArCosts
),
$request->request->get('markupPercentage'),
$request->request->get('totalCost'),
$request->request->get('totalStoreCost'),
$request->request->get('totalNonStoreCost'),
$request->request->get('salesValue'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
$mrpId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
$mrpId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'New Package Added.'
);
}
return $this->render(
'@Sales/pages/input_forms/create_product_mrp.html.twig',
array(
'page_title' => 'Product Mrp',
'product_list' => Inventory::ProductListArray($this->getDoctrine()->getManager()),
'product_list_obj' => Inventory::ProductList($this->getDoctrine()->getManager())
)
);
// return $this->render('@Sales/pages/input_forms/create_product_mrp.html.twig',
// array(
// 'page_title'=>'Product Mrp',
// 'product_list'=>Inventory::ProductListArray($this->getDoctrine()->getManager()),
// 'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager())
//
// )
// );
}
public function GetPackageDetails(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$package_id = $id;
$details = $em->getRepository('ApplicationBundle:ProductPackage')->findOneBy(array(
'packageId' => $package_id
));
$products = json_decode($details->getProducts(), true);
$cnt = array();
for ($x = 0; $x < count($products["products"]); $x++) {
$cnt[] = array(
"id" => ($x + 1),
"productID" => $products["products"][$x],
"product_units" => $products["product_units"][$x],
"product_unit_price" => $products["product_unit_price"][$x],
"product_sales_multiplier" => $details->getSalesMultiplier(),
"package_unit_price" => $details->getTotalPrice(),
"warranty" => $details->getSalesWarrantyMonths()
);
}
return new JsonResponse(
array(
"success" => true,
"content" => $cnt,
"package_data" => array(
"package_unit_price" => $details->getTotalPrice(),
"package_warranty" => $details->getSalesWarrantyMonths()
)
)
);
}
public function ClientList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$allowed_ids = [];
$companyId = $this->getLoggedUserCompanyId($request);
$listData = SalesOrderM::GetClientListForClientList($em, $request->isMethod('POST') ? 'POST' : 'GET', $request->request, $companyId);
if ($request->isMethod('POST')) {
if ($request->query->has('dataTableQry')) {
return new JsonResponse(
$listData
);
}
}
return $this->render(
'@Sales/pages/list/client_list.html.twig',
// return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
array(
'page_title' => 'Client List',
'data' => SalesOrderM::GetClientList($em, [], $companyId),
'client_types' => Client::GetClientType($em, $companyId),
'region_list' => Client::RegionList($em, $companyId),
'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
)
);
}
public function GetAllBranch()
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('SELECT
b.branchId,b.name,b.address,b.warehouseId, b.type
FROM ApplicationBundle:Branch b');
$result = $query->getArrayResult();
return new JsonResponse([
"branchList" => $result,
]);
}
public function ValidateCartForSalesOrder(Request $request)
{
$data = json_decode($request->getContent(), true);
$em = $this->getDoctrine()->getManager();
$cartItems = $data['data'];
$invalidItems = [];
foreach ($cartItems as $item) {
$productId = $item['id'] ?? null;
$inputPrice = $item['curr_purchase_price'] ?? null;
$inputQty = $item['qty'] ?? null;
if (!$productId) {
$invalidItems[] = ['error' => 'Missing product ID', 'item' => $item];
continue;
}
$product = $em->getRepository('ApplicationBundle:InvProducts')->find($productId);
if (!$product) {
$invalidItems[] = ['error' => 'Product not found', 'id' => $productId];
continue;
}
$dbPrice = $product->getPurchasePrice();
if ($inputPrice !== null && (float)$inputPrice != (float)$dbPrice) {
$invalidItems[] = [
'error' => 'Price mismatch',
'id' => $productId,
'input_price' => $inputPrice,
'current_price' => $dbPrice
];
}
$dbQty = $product->getQty();
if ($inputQty !== null && $dbQty < (int)$inputQty) {
$invalidItems[] = [
'error' => 'Insufficient quantity',
'id' => $productId,
'requested_qty' => $inputQty,
'available_qty' => $dbQty
];
}
}
if (!empty($invalidItems)) {
return new JsonResponse([
'success' => false,
'message' => 'Validation failed',
'issues' => $invalidItems
], 422);
}
return new JsonResponse(['success' => true, 'message' => 'Cart is valid']);
}
public function CreateSalesOrder(Request $request)
{
}
public function ClientListData(Request $request)
{
$em = $this->getDoctrine()->getManager();
$query = $em->createQuery('
SELECT
c.clientId AS client_id,
c.clientName AS client_name,
c.contactPersonName AS contact_person_name,
c.addressContact AS address_contact,
c.contactNumber AS contact_number,
c.image,
c.email,
c.creditLimit As credit_limit,
c.shippingAddress AS shipping_address,
c.billingAddress AS billing_address,
c.clientDue AS client_due,
c.clientLevel AS client_level,
c.parentId AS parent_id,
c.type AS client_type,
c.regionId AS region_id,
c.salesPersonId AS sales_person_id,
c.clientOwnBalanceAmount AS client_own_balance,
c.clientOwnDueAmount AS client_own_due,
c.clientOwnSalesAmount AS client_own_sales,
c.clientOwnReceivedAmount AS client_own_received,
c.status,
c.createdAt AS created_at,
c.CompanyId AS company_id
FROM ApplicationBundle:AccClients c
');
$result = $query->getArrayResult();
return new JsonResponse([
"client_list" => $result,
]);
}
public function PrintClientProfile(Request $request, $id, $idtype)
{
$em = $this->getDoctrine()->getManager();
if ($id == 0) {
$id = $idtype;
$idtype = "CI";
}
$companyId = $this->getLoggedUserCompanyId($request);
$balance_view_method = 0;
$onlyLedgerFlag = 0;
if ($request->query->has('onlyLedgerFlag'))
$onlyLedgerFlag = $request->query->get('onlyLedgerFlag');
$bal_set = $em
->getRepository('ApplicationBundle:AccSettings')
->findOneBy(
array(
'name' => 'ledger_balance_display_method',
)
);
if ($bal_set) {
$balance_view_method = $bal_set->getdata();
}
$start_date = '';
$end_date = '';
if ($request->query->has('start_date'))
$start_date = $request->query->get('start_date');
if ($request->query->has('end_date'))
$end_date = $request->query->get('end_date');
$CD = Client::GetClientProfileDetails($em, $id, $idtype, $start_date, $end_date);
$company_data = Company::getCompanyData($em, $companyId);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/print/client_profile_print.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => $CD['info']['client_name'],
'export' => 'pdf,print',
'data' => $CD,
'start_date' => $start_date,
'end_date' => $end_date,
'provisional' => 1,
'entityList' => GeneralConstant::$Entity_list_details,
'onlyLedgerFlag' => $onlyLedgerFlag,
'balance_view_method' => $balance_view_method,
'document_mark_image' => $document_mark['original'],
'document_type' => 'Client Ledger',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0,
// 'sales_person_list'=>Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $CD['info']['client_name'] . '_' . 'ledger.pdf"'
)
);
}
return $this->render(
'@Sales/pages/print/client_profile_print.html.twig',
array(
'page_title' => 'Client Profile',
'data' => $CD,
'export' => 'pdf,print',
'entityList' => GeneralConstant::$Entity_list_details,
'onlyLedgerFlag' => $onlyLedgerFlag,
'start_date' => $start_date,
'end_date' => $end_date,
'provisional' => 1,
'balance_view_method' => $balance_view_method,
)
);
}
public function ClientProfile(Request $request, $id, $idtype)
{
$em = $this->getDoctrine()->getManager();
if ($id == 0) {
$id = $idtype;
$idtype = "CI";
}
$companyId = $this->getLoggedUserCompanyId($request);
$balance_view_method = 0;
$bal_set = $em
->getRepository('ApplicationBundle:AccSettings')
->findOneBy(
array(
'name' => 'ledger_balance_display_method',
)
);
if ($bal_set) {
$balance_view_method = $bal_set->getdata();
}
$start_date = '';
$end_date = '';
if ($request->query->has('start_date'))
$start_date = $request->query->get('start_date');
if ($request->query->has('end_date'))
$end_date = $request->query->get('end_date');
$CD = Client::GetClientProfileDetails($em, $id, $idtype, $start_date, $end_date);
$company_data = Company::getCompanyData($em, $companyId);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/print/client_profile_print.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => $CD['info']['client_name'],
'export' => 'pdf,print',
'data' => $CD,
'entityList' => GeneralConstant::$Entity_list_details,
'start_date' => $start_date,
'end_date' => $end_date,
'provisional' => 1,
'balance_view_method' => $balance_view_method,
'document_mark_image' => $document_mark['original'],
'document_type' => 'Client Ledger',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0,
// 'sales_person_list'=>Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $CD['info']['client_name'] . '_' . 'ledger.pdf"'
)
);
}
return $this->render(
'@Sales/pages/report/client_profile.html.twig',
array(
'page_title' => 'Client Profile',
'data' => $CD,
'entityList' => GeneralConstant::$Entity_list_details,
'start_date' => $start_date,
'end_date' => $end_date,
'provisional' => 1,
'balance_view_method' => $balance_view_method,
)
);
}
public function ViewClientLedger(Request $request, $id, $idtype)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($id == 0) {
$id = $idtype;
$idtype = "CI";
}
if ($id == 'CI') {
$idtype = "CI";
$id = 0;
}
$clientIdList = [];
$clientTypeIdList = [];
$reportTypeId = 'by_client';
$outputType = 'view';
if ($request->query->has('reportTypeId'))
$reportTypeId = $request->query->get('reportTypeId');
if ($request->query->has('outputType'))
$outputType = $request->query->get('outputType');
if ($request->query->has('pdf'))
$outputType = 'pdf';
if ($reportTypeId == 'by_client') {
if ($request->query->has('clientId'))
$clientIdList = $request->query->get('clientId');
} else if ($reportTypeId == 'by_client_type') {
if ($request->query->has('clientTypeId'))
$clientTypeIdList = $request->query->get('clientTypeId');
$clients = $em
->getRepository('ApplicationBundle:AccClients')
->findBy(
array(
'type' => $clientTypeIdList,
'CompanyId' => $companyId,
)
);
foreach ($clients as $client) {
$clientIdList[] = $client->getClientId();
}
}
$balance_view_method = 0;
$bal_set = $em
->getRepository('ApplicationBundle:AccSettings')
->findOneBy(
array(
'name' => 'ledger_balance_display_method',
)
);
if ($bal_set) {
$balance_view_method = $bal_set->getdata();
}
$start_date = '';
$end_date = '';
if ($request->query->has('start_date'))
$start_date = $request->query->get('start_date');
if ($request->query->has('end_date'))
$end_date = $request->query->get('end_date');
$CD = [];
$clientDataArray = [];
// if($id!=0)
foreach ($clientIdList as $clientId) {
$CD = Client::GetClientProfileDetails($em, $clientId, $idtype, $start_date, $end_date);
$clientDataArray[] = $CD;
}
$company_data = Company::getCompanyData($em, $companyId);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($outputType == 'pdf') {
$html = $this->renderView(
'@Sales/pages/print/client_ledger_print.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Customer Ledger',
'export' => 'pdf,print',
'data' => $CD,
'entityList' => GeneralConstant::$Entity_list_details,
'start_date' => $start_date,
'end_date' => $end_date,
'provisional' => 1,
'outputType' => $outputType,
'clientIdList' => $clientIdList,
'clientTypeIdList' => $clientTypeIdList,
'reportTypeId' => $reportTypeId,
'clientDataArray' => $clientDataArray,
'balance_view_method' => $balance_view_method,
'document_mark_image' => $document_mark['original'],
'document_type' => 'Client Ledger',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0,
// 'sales_person_list'=>Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $CD['info']['client_name'] . '_' . 'ledger.pdf"'
)
);
}
if ($outputType == 'print') {
return $this->render(
'@Sales/pages/print/client_ledger_print.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Customer Ledger',
'export' => 'pdf,print',
'data' => $CD,
'entityList' => GeneralConstant::$Entity_list_details,
'start_date' => $start_date,
'end_date' => $end_date,
'provisional' => 1,
'clientIdList' => $clientIdList,
'clientTypeIdList' => $clientTypeIdList,
'reportTypeId' => $reportTypeId,
'outputType' => $outputType,
'clientDataArray' => $clientDataArray,
'balance_view_method' => $balance_view_method,
'document_mark_image' => $document_mark['original'],
'document_type' => 'Client Ledger',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0,
// 'sales_person_list'=>Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
}
return $this->render(
'@Sales/pages/report/client_ledger.html.twig',
array(
'page_title' => 'Customer ledger',
// 'data'=>$CD,
'clientId' => $id,
'entityList' => GeneralConstant::$Entity_list_details,
'clientIdList' => $clientIdList,
'clientTypeIdList' => $clientTypeIdList,
'reportTypeId' => $reportTypeId,
'outputType' => $outputType,
'clientDataArray' => $clientDataArray,
'clientList' => Client::GetExistingClientList($em, $companyId, []),
'clientTypeList' => Client::GetClientType($em, $companyId),
'start_date' => $start_date,
'end_date' => $end_date,
'provisional' => 1,
'balance_view_method' => $balance_view_method,
)
);
}
public function CreateDeliveryConfirmation(Request $request)
{
if ($request->isMethod('POST')) {
$post = $request->request;
$path = "";
$file_path = "";
foreach ($request->files as $uploadedFile) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
if ($uploadedFile != null) {
$fileName = md5(uniqid()) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/';
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
$file = $uploadedFile->move($upl_dir, $path);
}
}
if ($path != "")
$file_path = 'uploads/FileUploads/' . $path;
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' . $path;
// $img_file = file_get_contents($g_path);
// $r=base64_encode($img_file);
$confirmId = SalesOrderM::CreateNewDeliveryConfirmation(
$this->getDoctrine()->getManager(),
$request->request,
$file_path,
Generic::simpleRandString(),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryConfirmation']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['DeliveryConfirmation'],
$confirmId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['DeliveryConfirmation'],
$confirmId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'New Delivery Confrmation Created'
);
$url = $this->generateUrl(
'view_delivery_confirmation'
);
return $this->redirect($url . "/" . $confirmId);
}
return $this->render(
'@Sales/pages/input_forms/delivery_confirmation.html.twig',
array(
'page_title' => 'Delivery Confirmation',
'deliveryReceipts' => $this->getDoctrine()->getManager()->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(array(
'approved' => GeneralConstant::APPROVED,
'deliveryStatus' => GeneralConstant::APPROVAL_STATUS_PENDING
))
)
);
}
public function CreateDeliveryOrder(Request $request)
{
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$orderId = SalesOrderM::CreateNewDeliveryOrder(
$this->getDoctrine()->getManager(),
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['DeliveryOrder']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['DeliveryOrder'],
$orderId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['DeliveryOrder'],
$orderId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'New Delivery order Created'
);
$url = $this->generateUrl(
'view_delivery_order'
);
return $this->redirect($url . "/" . $orderId);
}
return $this->render(
'@Sales/pages/input_forms/delivery_order.html.twig',
array(
'page_title' => 'New Delivery Order',
'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
'ClientList' => SalesOrderM::GetClientList($this->getDoctrine()->getManager()),
'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'salesOrders' => SalesOrderM::SalesOrderList($this->getDoctrine()->getManager(), $companyId, ['deliveryOrderSkipFlag' => [0, null]]),
'salesOrdersArray' => SalesOrderM::SalesOrderListArray($this->getDoctrine()->getManager(), $companyId, ['deliveryOrderSkipFlag' => [0, null]]),
)
);
}
public function GetItemListForDo(Request $request)
{
if ($request->isMethod('POST')) {
$em = $this->getDoctrine();
$find_array = array( // 'stage' => GeneralConstant::STAGE_PENDING_TAG
);
$Content = [];
$Transport_data = [];
$Lul_data = [];
if ($request->request->get('soId') != '')
$find_array['salesOrderId'] = $request->request->get('soId');
// if($request->request->get('warehouseId')!='')
// $find_array['warehouseId']=$request->request->get('warehouseId');
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrderItem')
->findBy(
$find_array,
array()
);
$SO = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrder')
->findOneBy(
$find_array,
array()
);
$sendData = array(
'salesType' => $SO->getSalesType(),
'packageData' => [],
'productList' => [],
'productListByPackage' => [],
);
$productList = Inventory::ProductList($this->getDoctrine()->getManager(), $SO->getCompanyId());
$serviceList = Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
$pckg_item_cross_match_data = [];
if ($SO->getSalesType() == 1) //package
{
//now package data
$package_data = json_decode($SO->getPackageData(), true);
foreach ($package_data as $pkg) {
$pckg = $pkg['info'];
$pckg_nec_data = array(
'packageId' => $pckg['packageId'],
'packageName' => $pckg['packageName'],
'packageUnits' => $pckg['packageUnits'],
'packageDelivered' => (isset($pckg['packageDelivered'])) ? $pckg['packageDelivered'] : 0,
'packageBalance' => (isset($pckg['packageBalance'])) ? $pckg['packageBalance'] : $pckg['packageUnits'],
'defaultUnit' => 1
);
$sendData['packageData'][] = $pckg_nec_data;
$details = $em->getRepository('ApplicationBundle:ProductPackage')->findOneBy(array(
'packageId' => $pckg['packageId']
));
$pck_prods = json_decode($details->getProducts(), true);
$cnt = array();
for ($x = 0; $x < count($pck_prods["products"]); $x++) {
$pckg_item_cross_match_data[$pckg['packageId']][$pck_prods["products"][$x]] = array(
"product_units" => $pck_prods["product_units"][$x],
);
}
}
foreach ($QD as $product) {
$p_data = array(
'details_id' => $product->getId(),
'productId' => $product->getProductId(),
'productFdm' => $product->getProductFdm(),
'product_name' => $productList[$product->getProductId()]['name'],
'package_id' => $product->getPackageId(),
'qty' => $product->getQty(),
'delivered' => $product->getDelivered(),
'balance' => $product->getBalance(),
// 'unit_package_multiplier'=>1,
'unit_package_multiplier' => $pckg_item_cross_match_data[$product->getPackageId()][$product->getProductId()]['product_units'],
// 'delivered'=>$product->getDelivered(),
);
$sendData['productList'][] = $p_data;
$sendData['productListByPackage'][$product->getPackageId()][] = $p_data;
}
}
if ($SO->getSalesType() == 2 || $SO->getSalesType() == 3) //Spare
{
foreach ($QD as $product) {
$soBalance = $product->getQty();
// $doBalance=$product->getBalance() - $product->getTransitQty();
// $doBalance = $product->getBalance();
// $doBalance = 0;
//now check if any so ir do item id there that is at
//least pending
$approvalPendingDos = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryOrder')
->findBy(
array(
'salesOrderId' => $SO->getSalesOrderId(),
'approved' => [GeneralConstant::APPROVAL_STATUS_PENDING, GeneralConstant::APPROVED]
)
);
foreach ($approvalPendingDos as $appPendDo) {
$appPendDrItem = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryOrderItem')
->findOneBy(
array(
'deliveryOrderId' => $appPendDo->getDeliveryOrderId(),
'salesorderItemId' => $product->getId()
)
);
if ($appPendDrItem) {
$soBalance = $soBalance - $appPendDrItem->getQty();
// $doBalance=$doBalance-$appPendDrItem->getQty();
}
}
$p_data = array(
'details_id' => $product->getId(),
'productId' => $product->getProductId(),
'productFdm' => $product->getProductFdm(),
'service_id' => $product->getServiceId(),
'type' => $product->getType(),
// 'product_name'=>$product->getType()==1?$productList[$product->getProductId()]['name']:'',
'product_name' => ($product->getType() == 1) ?
(isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : $product->getProductNameFdm()) : '',
'service_name' => $product->getType() == 2 ? $serviceList[$product->getServiceId()]['name'] : '',
'package_id' => $product->getPackageId(),
'qty' => $product->getQty(),
// 'delivered' => $product->getDelivered(),
'delivered' => $soBalance,
'balance' => $soBalance,
// 'delivered'=>$product->getDelivered(),
);
$sendData['productList'][] = $p_data;
}
//now package data
}
if ($sendData) {
return new JsonResponse(array("success" => true, "content" => $sendData));
}
return new JsonResponse(array("success" => false));
}
return new JsonResponse(array("success" => false));
}
public function CheckCreditLimitValidityForDr(Request $request)
{
$allowed = 0;
if ($request->isMethod('POST')) {
$id = $request->request->has('soId') ? $request->request->get('soId') : 0;
$drData = $request->request->has('drData') ? $request->request->get('drData') : [];
// $drData=[
// ['soItemId'=>9,'qty'=>9],
// ['soItemId'=>9,'qty'=>9],
// ['soItemId'=>9,'qty'=>9],
// ];
//data will be by soItemId
$em = $this->getDoctrine();
$toGetSoItemsId = [];
$toGetDoItemsId = [];
$drDataBySoItemId = [];
$drDataByDoItemId = [];
$so = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(array(
'salesOrderId' => $id //$id is soId
));
if ($so->getDeliveryOrderSkipFlag() == 1) {
foreach ($drData as $pp) {
$toGetSoItemsId[] = $pp['soItemId'];
$drDataBySoItemId[$pp['soItemId']] = $pp;
}
} else {
foreach ($drData as $pp) {
$toGetDoItemsId[] = $pp['soItemId'];
$drDataByDoItemId[$pp['soItemId']] = $pp;
}
$do_item_data = $em->getRepository('ApplicationBundle:DeliveryOrderItem')->findBy(
array(
'salesorderId' => $id,
'id' => $toGetDoItemsId
)
);
foreach ($do_item_data as $dd) {
$toGetSoItemsId[] = $dd->getSalesorderItemId();
$drDataBySoItemId[$dd->getSalesorderItemId()] = $drDataByDoItemId[$dd->getId()];
}
// $do_item_data = $em->getRepository('ApplicationBundle:SalesOrderItem')->findOneBy(
// array(
//// 'salesOrderId'=>$post_data->get('soId', null),
// 'id' => $post_data->get('do_details_id')[$key]
// )
// );
}
$so_item_data = $em->getRepository('ApplicationBundle:SalesOrderItem')->findBy(
array(
'salesOrderId' => $id,
'id' => $toGetSoItemsId
)
);
$prev_so_amount = $so->getSoAmount();
$total_discounted_amount = 0;
$total_product_amount = 0;
$total_discount = 0;
$total_special_discount = 1 * $so->getSpecialDiscountAmount();
$total_special_discount_rate = 1 * $so->getSpecialDiscountRate();
foreach ($so_item_data as $item) {
$qty = $drDataBySoItemId[$item->getId()]['qty'];
$price = $item->getPrice();
$amount = $qty * $price;
$discountAmount = $amount * ($item->getDiscountRate() / 100);
$discountedAmount = $amount - $discountAmount;
$total_discounted_amount += $discountedAmount;
$total_discount += $discountAmount;
$total_product_amount += $amount;
}
$aitRate = $so->getAitRate();
$vatRate = $so->getVatRate();
if ($aitRate == '' || $aitRate == null) $aitRate = 0;
if ($vatRate == '' || $vatRate == null) $vatRate = 0;
// $so->setVatRate($post->get('vat_rate', null));
$vatAmount = $total_discounted_amount * ($vatRate / 100);
$aitAmount = $total_discounted_amount * ($aitRate / 100);
$total_sales_amount = $total_discounted_amount + $vatAmount + $aitAmount - $total_special_discount;
//now get client
$client = $em->getRepository('ApplicationBundle:AccClients')->findOneBy(array(
'clientId' => $so->getClientId(),
));
if ($client->getCreditLimitEnabled() != 1) {
$allowed = 1;
} else {
$creditLimit = 1 * $client->getCreditLimit();
$freezeBalance = 1 * $client->getFreezeBalance();
$due = 1 * $client->getClientDue();
if (($creditLimit - $freezeBalance) >= ($due + $total_sales_amount))
$allowed = 1;
}
//now package data
return new JsonResponse(array("allowed" => $allowed));
}
return new JsonResponse(array("allowed" => $allowed));
}
public function GetSoDataForSoAmendment(Request $request)
{
if ($request->isMethod('POST')) {
$em = $this->getDoctrine();
$find_array = array( // 'stage' => GeneralConstant::STAGE_PENDING_TAG
);
$Content = [];
$Transport_data = [];
$Lul_data = [];
if ($request->request->get('soId') != '')
$find_array['salesOrderId'] = $request->request->get('soId');
// if($request->request->get('warehouseId')!='')
// $find_array['warehouseId']=$request->request->get('warehouseId');
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrderItem')
->findBy(
$find_array,
array()
);
$SO = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrder')
->findOneBy(
$find_array,
array()
);
$sendData = array(
'salesType' => $SO->getSalesType(),
'packageData' => [],
'productList' => [],
'productListByPackage' => [],
'otherData' => [],
);
$productList = Inventory::ProductList($this->getDoctrine()->getManager(), $SO->getCompanyId());
$serviceList = Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
$pckg_item_cross_match_data = [];
if ($SO->getSalesType() == 1) //package
{
//now package data
$package_data = json_decode($SO->getPackageData(), true);
foreach ($package_data as $pkg) {
$pckg = $pkg['info'];
$pckg_nec_data = array(
'packageId' => $pckg['packageId'],
'packageName' => $pckg['packageName'],
'packageUnits' => $pckg['packageUnits'],
'packageDelivered' => (isset($pckg['packageDelivered'])) ? $pckg['packageDelivered'] : 0,
'packageBalance' => (isset($pckg['packageBalance'])) ? $pckg['packageBalance'] : $pckg['packageUnits'],
'defaultUnit' => 1
);
$sendData['packageData'][] = $pckg_nec_data;
$details = $em->getRepository('ApplicationBundle:ProductPackage')->findOneBy(array(
'packageId' => $pckg['packageId']
));
$pck_prods = json_decode($details->getProducts(), true);
$cnt = array();
for ($x = 0; $x < count($pck_prods["products"]); $x++) {
$pckg_item_cross_match_data[$pckg['packageId']][$pck_prods["products"][$x]] = array(
"product_units" => $pck_prods["product_units"][$x],
);
}
}
foreach ($QD as $product) {
$p_data = array(
'details_id' => $product->getId(),
'productId' => $product->getProductId(),
'productFdm' => $product->getProductFdm(),
'product_name' => $productList[$product->getProductId()]['name'],
'package_id' => $product->getPackageId(),
'qty' => $product->getQty(),
'delivered' => $product->getDelivered(),
'balance' => $product->getBalance(),
// 'unit_package_multiplier'=>1,
'unit_package_multiplier' => $pckg_item_cross_match_data[$product->getPackageId()][$product->getProductId()]['product_units'],
// 'delivered'=>$product->getDelivered(),
);
$sendData['productList'][] = $p_data;
$sendData['productListByPackage'][$product->getPackageId()][] = $p_data;
}
}
if ($SO->getSalesType() == 2 || $SO->getSalesType() == 3) //Spare
{
foreach ($QD as $product) {
$dt = $product;
$p_data = array(
'details_id' => $product->getId(),
'productId' => $product->getProductId(),
'serviceId' => $product->getServiceId(),
'productFdm' => $product->getProductFdm(),
'service_id' => $product->getServiceId(),
'type' => $product->getType(),
'desc' => $product->getDesc(),
'origin' => $product->getOrigin(),
'price' => $product->getPrice(),
'warranty' => $product->getWarranty(),
'unitTypeId' => $product->getUnitTypeId(),
// 'product_name'=>$product->getType()==1?$productList[$product->getProductId()]['name']:'',
'product_name' => ($product->getType() == 1) ?
(isset($productList[$product->getProductId()]) ? $productList[$product->getProductId()]['name'] : $product->getProductNameFdm()) : '',
'service_name' => $product->getType() == 2 ? $serviceList[$product->getServiceId()]['name'] : '',
'package_id' => $product->getPackageId(),
'qty' => $product->getQty(),
'delivered' => $product->getDelivered(),
'balance' => $product->getBalance(),
'id' => $dt->getProductId(),
'alias' => $dt->getDesc(),
'unit' => $dt->getQty(),
'unit_price' => 1 * $dt->getPrice(),
'total_price' => 1 * $dt->getProductAmount(),
'discount_rate' => 1 * $dt->getDiscountRate(),
'discount_amount' => 1 * $dt->getDiscountAmount(),
'discounted_amount' => 1 * $dt->getDiscountedAmount(),
'free_product_ids' => json_decode($dt->getFreeProductIds()),
'so_item_id' => 1 * $dt->getId(),
'free_products_so_item_ids' => json_decode($dt->getFreeProductSoItemIds()),
'free_products_so_item_ids_str' => $dt->getFreeProductSoItemIds(),
'freeProductUnit' => json_decode($dt->getFreeProductUnits()),
'ret_data' => [],
'fdm' => $dt->getProductFdm(),
'detailsIds' => [],
'docIds' => [],
// 'delivered'=>$product->getDelivered(),
);
$sendData['productList'][] = $p_data;
}
//now package data
}
$sendData['otherData']['vatRate'] = $SO->getVatRate();
$sendData['otherData']['vatAmount'] = $SO->getVatAmount();
$sendData['otherData']['invoiceAmount'] = $SO->getInvoiceAmount();
$sendData['otherData']['aitRate'] = $SO->getAitRate();
$sendData['otherData']['aitAmount'] = $SO->getAitAmount();
$sendData['otherData']['sdRate'] = $SO->getSpecialDiscountRate();
$sendData['otherData']['sdAmount'] = $SO->getSpecialDiscountAmount();
if ($sendData) {
return new JsonResponse(array("success" => true, "content" => $sendData));
}
return new JsonResponse(array("success" => false));
}
return new JsonResponse(array("success" => false));
}
public function CreateDebitNote(Request $request)
{
return $this->render(
'@Sales/pages/input_forms/new_debit_note.html.twig',
array(
'page_title' => 'New Debit Note'
)
);
}
//package
public function ProductPackageList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:ProductPackage')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
// 'doc_date'=>$entry->getDeliveryReceiptDate(),
'id' => $entry->getPackageId(),
'doc_hash' => $entry->getDocumentHash(),
'package_amount' => $entry->getTotalPrice(),
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render(
'@Sales/pages/list/product_package_list.html.twig',
array(
'page_title' => 'Packages',
'data' => $data
)
);
}
public function ViewProductPackage(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Package::GetProductPackageDetails($em, $id);
return $this->render(
'@Sales/pages/views/view_product_package.html.twig',
array(
'page_title' => 'View',
'data' => $dt,
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['ProductPackage'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ProductPackage'],
$id,
$dt['created_by'],
$dt['edited_by']
) : []
)
);
}
public function PrintProductPackage(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = Package::GetProductPackageDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
return $this->render(
'@Sales/pages/print/product_package_print.html.twig',
array(
'page_title' => 'Package ' . $data['doc_hash'],
'data' => $data,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Sales Package',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
)
);
}
public function CreateProductMrpDocument(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
MiscActions::RemoveExpiredDocs($em);
$entity_id = array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'];
// $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
// array(
// 'tradeOfferId'=>$id, ///material
//
// ),array('projectDate'=>'desc')
// );
// $client=$em->getRepository('ApplicationBundle:AccClients')->findOneBy(
// array(
// 'clientId'=>$projectData->getClientId(), ///material
//
// ),array('projectDate'=>'desc')
// );
$dochash = $request->request->get('docHash');
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
//construct the files
$file_list = array(
'product_files' => [],
'service_files' => [],
'ar_files' => [],
);
$file_path = null;
// foreach ($request->files as $uploadedFile) {
// if ($uploadedFile != null) {
//
// $fileName = md5(uniqid()) . '.' . $uploadedFile->guessExtension();
// $path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/FileUploads/' . $request->request->get('userId') . '/';
// if (!file_exists($upl_dir)) {
// mkdir($upl_dir, 0777, true);
// }
// $file = $uploadedFile->move($upl_dir, $path);
// if ($path != "")
// $file_path = 'uploads/FileUploads/' . $request->request->get('userId') . '/' . $path;
// }
//
//
// }
//
$spId = SalesOrderM::CreateNewProductPriceList(
$this->getDoctrine()->getManager(),
$id,
$request->request,
$dochash,
$file_path,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
$file_path_list = [];
if ($spId != 0)
if (!empty($request->files)) {
MiscActions::RemoveFilesForEntityDoc($em_goc, 'AccTransactions', $spId);
$storePath = 'uploads/PriceDoc/';
$path = "";
$file_path = "";
$session = $request->getSession();
MiscActions::RemoveExpiredFiles($em_goc);
foreach ($request->files as $uploadedFileGG) {
// if($uploadedFile->getImage())
// var_dump($uploadedFile->getFile());
// var_dump($uploadedFile);
$tempD = $uploadedFileGG;
if (!is_array($uploadedFileGG)) {
$uploadedFileGG = array();
$uploadedFileGG[] = $tempD;
}
foreach ($uploadedFileGG as $uploadedFile) {
if ($uploadedFile != null) {
$extension = $uploadedFile->guessExtension();
$size = $uploadedFile->getSize();
$fileName = 'PRCDOC_' . $spId . '_' . (md5(uniqid())) . '.' . $uploadedFile->guessExtension();
$path = $fileName;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath;
if (!file_exists($upl_dir)) {
mkdir($upl_dir, 0777, true);
}
if (file_exists($upl_dir . '' . $path)) {
chmod($upl_dir . '' . $path, 0755);
unlink($upl_dir . '' . $path);
}
$file = $uploadedFile->move($upl_dir, $path);
$expireNever = 1;
$expireTs = 0;
$EntityFile = new EntityFile();
$EntityFile->setPath($this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path);
$EntityFile->setMarker('_GEN_');
$EntityFile->setExtension($extension);
$EntityFile->setExpireTs($expireTs);
$EntityFile->setSize($size);
$EntityFile->setRelativePath($storePath . $path);
$EntityFile->setEntityName('ProductMrpDocument');
$EntityFile->setEntityBundle('ApplicationBundle');
$EntityFile->setEntityId($spId);
$EntityFile->setEntityIdField('productMrpDocumentId');
$EntityFile->setModifyFieldSetter('setFiles');
$EntityFile->setDocIdForApplicant(0);
$EntityFile->setUserId($session->get(UserConstants::USER_ID, 0));
$EntityFile->setAppId($session->get(UserConstants::USER_APP_ID, 0));
$EntityFile->setEmployeeId($session->get(UserConstants::USER_EMPLOYEE_ID, 0));
$EntityFile->setUserType($session->get(UserConstants::USER_TYPE, 0));
$em_goc->persist($EntityFile);
$em_goc->flush();
$EntityFileId = $EntityFile->getId();
}
if ($path != "")
$file_path_list[] = ($storePath . $path);
}
}
$g_path = $this->container->getParameter('kernel.root_dir') . '/../web/' . $storePath . $path;
$v = $em->getRepository('ApplicationBundle:ProductMrpDocument')->findOneBy(array(
'productMrpDocumentId' => $spId,
));
if ($v) {
$v->setFiles(implode(',', $file_path_list));
$em->flush();
} else {
}
}
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole'); //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
$spId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
$spId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Price Settings Created'
);
$url = $this->generateUrl(
'view_product_mrp_document'
);
$doc_here = $this->getDoctrine()
->getRepository('ApplicationBundle:ProductMrpDocument')
->findOneBy(
array(
'productMrpDocumentId' => $spId
)
);
System::AddNewNotification(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
$request->getSession()->get(UserConstants::USER_APP_ID),
$request->getSession()->get(UserConstants::USER_COMPANY_ID),
"Price List : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::SALES_DEPARTMENT),
'success',
$url . "/" . $spId,
"Price Settings"
);
if ($request->request->has('returnJson')) {
$doc = $doc_here;
return new JsonResponse(array(
'success' => true,
'documentHash' => $doc_here->getDocumentHash(),
'documentId' => $spId,
'documentIdPadded' => str_pad($spId, 8, '0', STR_PAD_LEFT),
'documentDate' => $doc_here->getProductMrpDocumentDate()->format('Y-m-d'),
'documentAmount' => '',
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'viewUrl' => $url . "/" . $spId,
'docPrintMainUrl' => $this->generateUrl('view_product_mrp_document'),
));
} else {
$this->addFlash(
'success',
'New Document Created'
);
return $this->redirect($url . "/" . $spId);
}
}
}
$message = "";
$extData = [];
if ($id != 0) {
$extData = $em->getRepository('ApplicationBundle:ProductMrpDocument')->findOneBy(
array(
'productMrpDocumentId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extData) {
// if ($proposalData->getEditFlag() != 1) {
// $url = $this->generateUrl(
// 'view_trade_offer'
// );
// $this->addFlash(
// 'error',
// 'Sorry You cant Edit the document Right now.'
// );
// return $this->redirect($url . "/" . $id);
// }
}
}
$qry = $em->getRepository("ApplicationBundle:InvProducts")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
'sellable' => 1 //sellable
));
$pl = [];
$pl_array = [];
foreach ($qry as $product) {
$pl[$product->getId()] = array(
'text' => $product->getName(),
'name' => $product->getName(),
'id' => $product->getId(),
'value' => $product->getId(),
'purchase_price' => $product->getPurchasePrice(),
'sales_price' => $product->getSalesPrice(),
'supplier_id' => $product->getBrandCompany(),
);
$pl_array[] = array(
'text' => $product->getName(),
'value' => $product->getId(),
'name' => $product->getName(),
'id' => $product->getId(),
'purchase_price' => $product->getPurchasePrice(),
'sales_price' => $product->getSalesPrice(),
'supplier_id' => $product->getBrandCompany(),
);
}
$qry = $em->getRepository("ApplicationBundle:AccService")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
// 'type'=>1//trade items
));
$sl = [];
$sl_array = [];
foreach ($qry as $product) {
$sl[$product->getServiceId()] = array(
'text' => $product->getServiceName(),
'value' => $product->getServiceId(),
'name' => $product->getServiceName(),
'id' => $product->getServiceId(),
);
$sl_array[] = array(
'text' => $product->getServiceName(),
'value' => $product->getServiceId(),
'name' => $product->getServiceName(),
'id' => $product->getServiceId(),
);
}
$qry = $em->getRepository("ApplicationBundle:ProjectWorkStage")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
// 'type'=>1//trade items
));
$workStages = [];
$workStages_array = [];
foreach ($qry as $product) {
$workStages[$product->getProjectWorkStageId()] = array(
'text' => $product->getStageName(),
'value' => $product->getProjectWorkStageId(),
'name' => $product->getStageName(),
'id' => $product->getProjectWorkStageId(),
);
$workStages_array[] = array(
'text' => $product->getStageName(),
'value' => $product->getProjectWorkStageId(),
'name' => $product->getStageName(),
'id' => $product->getProjectWorkStageId(),
);
}
$hl = Accounts::HeadList($em);
$debug_data = $request->files->get('product_reference_file');
$companyId = $this->getLoggedUserCompanyId($request);
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$productList = Inventory::ProductList($em, $companyId, 0, 0, '', [], 1);
$subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
$categoryList = Inventory::ProductCategoryList($em, $companyId);
$igList = Inventory::ItemGroupList($em, $companyId);
$unitList = Inventory::UnitTypeList($em);
foreach ($productList as $product) {
$productListArray[] = $product;
}
foreach ($categoryList as $product) {
$categoryListArray[] = $product;
}
foreach ($subCategoryList as $product) {
$subCategoryListArray[] = $product;
}
foreach ($igList as $product) {
$igListArray[] = $product;
}
foreach ($unitList as $product) {
$unitListArray[] = $product;
}
$brandList = Inventory::GetBrandList($em, $companyId);
$brandListArray = [];
foreach ($brandList as $product) {
$brandListArray[] = $product;
}
// $colorList=Inventory::GetBrandList($em,$companyId);
// $colorListArray=[];
// foreach ($colorList as $product) {
//
// $colorListArray[] = $product;
// }
return $this->render(
'@Sales/pages/input_forms/create_product_mrp_document.html.twig',
array(
'page_title' => 'Price Settings',
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
// 'clients'=>SalesOrderM::GetClientList($em),
'clients_by_ac_head' => SalesOrderM::GetClientListByAcHead($em),
'users' => Users::getUserListById($em),
'stages' => ProjectConstant::$projectStages,
'productList' => $productList,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'unitList' => $unitList,
'brandList' => $brandList,
'brandListArray' => $brandListArray,
// 'colorList'=>$colorList,
// 'colorListArray'=>$colorListArray,
'productListArray' => $productListArray,
'subCategoryListArray' => $subCategoryListArray,
'categoryListArray' => $categoryListArray,
'igListArray' => $igListArray,
'unitListArray' => $unitListArray,
'sl' => $sl,
'pl' => $pl,
'hl' => $hl,
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'extData' => $extData,
'message' => $message,
'tradeOfferId' => $id,
'regionList' => Client::RegionList($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
'pl_array' => $pl_array,
'sl_array' => $sl_array,
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'debug_data' => $debug_data,
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
// 'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
)
);
}
public function ProductMrpDocumentList(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:ProductMrpDocument')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getProductMrpDocumentDate(),
'id' => $entry->getProductMrpDocumentId(),
'doc_hash' => $entry->getDocumentHash(),
'assigned_amount' => 0,
'stage' => 1
);
}
return $this->render(
'@Sales/pages/list/product_mrp_document_list.html.twig',
array(
'page_title' => 'Mrp Settings',
'data' => $data
)
);
}
public function ProductPriceList(Request $request)
{
$companyId = $this->getLoggedUserCompanyId($request);
$em = $this->getDoctrine()
->getManager();
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:ProductMrp')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
// 'CompanyId' => $companyId
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
// 'doc_date'=>$entry->getProductMrpDocumentDate(),
// 'id'=>$entry->getProductMrpDocumentId(),
'productId' => $entry->getProductId(),
'doc_id' => $entry->getProductMrpDocumentId(),
'doc_hash' => $entry->getDocumentHash(),
'price_data' => json_decode($entry->getPriceByCustomerTypes(), true),
);
}
return $this->render(
'@Sales/pages/list/product_mrp_list.html.twig',
array(
'page_title' => 'Price Settings',
'data' => $data,
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'productList' => Inventory::ProductList($em, $companyId, 1)
)
);
}
//For Product Catalogue
public function ViewProductCatalogueAction(Request $request)
{
$companyId = $this->getLoggedUserCompanyId($request);
$em = $this->getDoctrine()->getManager();
$start_date = $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
$end_date = $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' . ' 23:59:59.999')) : new \DateTime();
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), '');;
$warehouse_action_list_array = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'array');;
$data_searched = [];
if ($request->isMethod('POST'))
$method = 'POST';
else
$method = 'GET';
$post_data = $method == 'POST' ? $request->request : $request->query;
// return new JsonResponse($data_searched);
// Fetch flat product data
$filterQry = $em->getRepository('ApplicationBundle:ProductMrp')->createQueryBuilder('Pr')
->select('Pr.productMrpId', 'Pr.priceByCustomerTypes', 'Pr.currency', 'Pr.minOrderQty')
->addSelect('P.id as pid', 'P.igId', 'P.categoryId', 'P.name', 'P.defaultImage', 'P.unitTypeId', 'P.subCategoryId', 'P.productCode', 'P.note', 'P.productFdm')
->addSelect('IG.id as igId', 'IG.name as itemGroupName')
->addSelect('PC.name as productCategory')
// ->addSelect('PSc.name as subCategoryName')
->addSelect('B.id as brandId', 'B.name as brandCompanyName', 'B.image as brandCompanyImage')
->leftJoin('ApplicationBundle:InvProducts', 'P', 'WITH', 'Pr.productId = P.id')
->leftJoin('ApplicationBundle:InvItemGroup', 'IG', 'WITH', 'P.igId = IG.id')
->leftJoin('ApplicationBundle:InvProductCategories', 'PC', 'WITH', 'P.categoryId = PC.id')
// ->leftJoin('ApplicationBundle:InvProductSubCategories', 'PSc', 'WITH', 'P.subCategoryId = PSc.id')
->leftJoin('ApplicationBundle:BrandCompany', 'B', 'WITH', 'P.brandCompany = B.id')
->leftJoin('ApplicationBundle:ClientType', 'C', 'WITH', 'Pr.priceByCustomerTypes = C.clientTypeId');
if (!empty($post_data->get('productId'))) {
$filterQry->andWhere(' P.id in (' . implode(',', $post_data->get('productId')) . ') ');
}
if (!empty($post_data->get('igId'))) {
$filterQry->andWhere(' P.igId in (' . implode(',', $post_data->get('igId')) . ') ');
}
if (!empty($post_data->get('categoryId'))) {
$filterQry->andWhere(' P.categoryId in (' . implode(',', $post_data->get('categoryId')) . ') ');
}
if (!empty($post_data->get('brandId'))) {
$filterQry->andWhere(' P.brandCompany in (' . implode(',', $post_data->get('brandId')) . ') ');
}
// if(!empty($post_data->get('priceByCustomerTypes'))){
// $filterQry -> andWhere('Pr.priceByCustomerTypes in ('. implode(',', $post_data->get('priceByCustomerTypes')) .') ');
// }
if (!empty($post_data->get('currency'))) {
$filterQry->andWhere(' Pr.currency in (' . implode(',', $post_data->get('currency')) . ') ');
}
$productMrp = $filterQry
->getQuery()
->getResult();
//ClientType name
$clientTypes = $em->getRepository('ApplicationBundle:ClientType')
->createQueryBuilder('ct')
->select('ct.clientTypeId, ct.name')
->getQuery()
->getArrayResult();
$clientTypeList = [];
foreach ($clientTypes as $ct) {
$clientTypeList[$ct['clientTypeId']] = $ct['name'];
}
//UOM name
$unitTypes = $em->getRepository('ApplicationBundle:UnitType')
->createQueryBuilder('ut')
->select('ut.id, ut.name')
->getQuery()
->getArrayResult();
$unitTypeList = [];
foreach ($unitTypes as $ut) {
$unitTypeList[$ut['id']] = $ut['name'];
}
//Item group
$itemGroups = $em->getRepository('ApplicationBundle:InvItemGroup')
->createQueryBuilder('ig')
->select('ig.id, ig.name, ig.categorizationData')
->getQuery()
->getArrayResult();
$itemGroupList = [];
foreach ($itemGroups as $igData) {
$itemGroupList[$igData['id']] = array(
'name' => $igData['name'],
'categorizationData' => json_decode($igData['categorizationData'], true) ??
[
["alias" => "Category", "en" => 1, "inc" => "1"],
["alias" => "Sub Category", "en" => 1, "inc" => "1"],
]
);
}
//Currency name
$currencyTypes = $em->getRepository('ApplicationBundle:Currencies')
->createQueryBuilder('cu')
->select('cu.currencyId, cu.name')
->getQuery()
->getArrayResult();
$currencyTypeList = [];
foreach ($currencyTypes as $cu) {
$currencyTypeList[$cu['currencyId']] = $cu['name'];
}
//Sub-Category
$subCategoryTypes = $em->getRepository('ApplicationBundle:InvProductSubCategories')
->createQueryBuilder('sc')
->select('sc.id, sc.name')
->getQuery()
->getArrayResult();
$subCategoryTypeList = [];
foreach ($subCategoryTypes as $sc) {
$subCategoryTypeList[$sc['id']] = $sc['name'];
}
// dump($subCategoryTypeList);
// Restructure: Item Group → Brand → Products
$structuredData = [];
foreach ($productMrp as $row) {
$igId = $row['igId'];
$brandId = $row['brandId'];
if (!isset($structuredData[$igId])) {
$structuredData[$igId] = [
'name' => $row['itemGroupName'],
// 'categorizationData' => json_decode($row['categorizationData'], true) ??
//
//
// [
// ["alias" => "Category", "en" => 1, "inc" => "1"],
// ["alias" => "Sub Category", "en" => 1, "inc" => "1"],
//
//
// ]
// ,
'brands' => []
];
}
if (!isset($structuredData[$igId]['brands'][$brandId])) {
$structuredData[$igId]['brands'][$brandId] = [
'name' => $row['brandCompanyName'],
'image' => $row['brandCompanyImage'],
'products' => []
];
}
$unitTypeName = isset($unitTypeList[$row['unitTypeId']]) ? $unitTypeList[$row['unitTypeId']] : 'N/A';
$currencyName = isset($currencyTypeList[$row['currency']]) ? $currencyTypeList[$row['currency']] : 'N/A';
// Parse productFdm string for SZ, SO, ST, SH values
preg_match('/SZ(\d+)/', $row['productFdm'], $szMatch);
preg_match('/SO(\d+)/', $row['productFdm'], $soMatch);
preg_match('/ST(\d+)/', $row['productFdm'], $stMatch);
preg_match('/SH(\d+)/', $row['productFdm'], $shMatch);
$subCategoryZeroId = $szMatch[1] ?? null;
$subCategoryOneId = $soMatch[1] ?? null;
$subCategoryTwoId = $stMatch[1] ?? null;
$subCategoryThreeId = $shMatch[1] ?? null;
$structuredData[$igId]['brands'][$brandId]['products'][] = [
'pid' => $row['pid'],
'name' => $row['name'],
'category' => $row['productCategory'],
'minOrderQty' => $row['minOrderQty'],
'productCode' => $row['productCode'],
'unitTypeId' => $row['unitTypeId'],
'unitTypeName' => $unitTypeName,
'currency' => $row['currency'],
'currencyName' => $currencyName,
'productFdm' => $row['productFdm'],
'note' => $row['note'],
// 'categorizationData' => $row['categorizationData'],
// 'price' => $row['priceByCustomerTypes'],
'priceByCustomerTypes' => json_decode($row['priceByCustomerTypes'], true), // decode JSON
'defaultImage' => $row['defaultImage'], // include image
// Sub-category types extracted
'subCategoryZero' => [
'id' => $subCategoryZeroId,
'name' => $subCategoryTypeList[$subCategoryZeroId] ?? 'N/A'
],
'subCategoryOne' => [
'id' => $subCategoryOneId,
'name' => $subCategoryTypeList[$subCategoryOneId] ?? 'N/A'
],
'subCategoryTwo' => [
'id' => $subCategoryTwoId,
'name' => $subCategoryTypeList[$subCategoryTwoId] ?? 'N/A'
],
'subCategoryThree' => [
'id' => $subCategoryThreeId,
'name' => $subCategoryTypeList[$subCategoryThreeId] ?? 'N/A'
],
];
}
$find_by_query = [];
$query_add = '';
// if($method=='POST')
if (!empty($post_data->get('productId'))) {
$find_by_query['productId'] = $post_data->get('productId');
}
if (!empty($post_data->get('currency'))) {
$find_by_query['currency'] = $post_data->get('currency');
}
if (!empty($post_data->get('igId'))) {
$find_by_query['igId'] = $post_data->get('igId');
}
if (!empty($post_data->get('categoryId'))) {
$find_by_query['categoryId'] = $post_data->get('categoryId');
}
if (!empty($post_data->get('brandId'))) {
$find_by_query['brandId'] = $post_data->get('brandId');
}
if (!empty($post_data->get('actionTagId'))) {
$find_by_query['actionTagId'] = $post_data->get('actionTagId');
}
if (!empty($post_data->get('customerTypes'))) {
$find_by_query['customerTypes'] = $post_data->get('customerTypes');
}
return $this->render('@Sales/pages/views/view_product_catalogue.html.twig', [
'page_title' => 'Product Catalogue View',
'start_date' => $start_date,
'end_date' => $end_date,
'openFilter' => empty($post_data->keys()) ? 1 : 0,
'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
'customer' => Client::ClientTypeList($this->getDoctrine()->getManager()),
// 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
'action_tag' => $warehouse_action_list,
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'qry' => $find_by_query,
'data_searched' => $data_searched,
'currencyTypeList' => $currencyTypeList,
'clientTypeList' => $clientTypeList,
'data' => [
'structuredData' => $structuredData,
'itemGroupList' => $itemGroupList,
'clientTypeList' => $clientTypeList,
'subCategoryTypeList' => $subCategoryTypeList,
// 'categorizationData' => $categorizationData
]
]);
}
public function PrintProductCatalogueAction(Request $request)
{
$companyId = $this->getLoggedUserCompanyId($request);
$em = $this->getDoctrine()->getManager();
//From
$mis_data_flag = 0;
if ($request->query->has('mis_print'))
$mis_data_flag = 1;
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
//upto
$start_date = $request->query->has('start_date') ? new \DateTime($request->query->get('start_date')) : '';
$end_date = $request->query->has('end_date') ? (new \DateTime($request->query->get('end_date') . ' ' . ' 23:59:59.999')) : new \DateTime();
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), '');;
$warehouse_action_list_array = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'array');;
$data_searched = [];
if ($request->isMethod('POST'))
$method = 'POST';
else
$method = 'GET';
$post_data = $method == 'POST' ? $request->request : $request->query;
$data_searched = [];
// return new JsonResponse($data_searched);
// Fetch flat product data
$filterQry = $em->getRepository('ApplicationBundle:ProductMrp')->createQueryBuilder('Pr')
->select('Pr.productMrpId', 'Pr.priceByCustomerTypes', 'Pr.currency', 'Pr.minOrderQty')
->addSelect('P.id as pid', 'P.igId', 'P.categoryId', 'P.name', 'P.defaultImage', 'P.unitTypeId', 'P.subCategoryId', 'P.productCode', 'P.note', 'P.productFdm')
->addSelect('IG.id as igId', 'IG.name as itemGroupName')
->addSelect('PC.name as productCategory')
// ->addSelect('PSc.name as subCategoryName')
->addSelect('B.id as brandId', 'B.name as brandCompanyName', 'B.image as brandCompanyImage')
->leftJoin('ApplicationBundle:InvProducts', 'P', 'WITH', 'Pr.productId = P.id')
->leftJoin('ApplicationBundle:InvItemGroup', 'IG', 'WITH', 'P.igId = IG.id')
->leftJoin('ApplicationBundle:InvProductCategories', 'PC', 'WITH', 'P.categoryId = PC.id')
// ->leftJoin('ApplicationBundle:InvProductSubCategories', 'PSc', 'WITH', 'P.subCategoryId = PSc.id')
->leftJoin('ApplicationBundle:BrandCompany', 'B', 'WITH', 'P.brandCompany = B.id')
->leftJoin('ApplicationBundle:ClientType', 'C', 'WITH', 'Pr.priceByCustomerTypes = C.clientTypeId');
if (!empty($post_data->get('productId'))) {
$filterQry->andWhere(' P.id in (' . implode(',', $post_data->get('productId')) . ') ');
}
if (!empty($post_data->get('igId'))) {
$filterQry->andWhere(' P.igId in (' . implode(',', $post_data->get('igId')) . ') ');
}
if (!empty($post_data->get('categoryId'))) {
$filterQry->andWhere(' P.categoryId in (' . implode(',', $post_data->get('categoryId')) . ') ');
}
if (!empty($post_data->get('brandId'))) {
$filterQry->andWhere(' P.brandCompany in (' . implode(',', $post_data->get('brandId')) . ') ');
}
// if(!empty($post_data->get('priceByCustomerTypes'))){
// $filterQry -> andWhere('Pr.priceByCustomerTypes in ('. implode(',', $post_data->get('priceByCustomerTypes')) .') ');
// }
if (!empty($post_data->get('currency'))) {
$filterQry->andWhere(' Pr.currency in (' . implode(',', $post_data->get('currency')) . ') ');
}
$productMrp = $filterQry
->getQuery()
->getResult();
//ClientType name
$clientTypes = $em->getRepository('ApplicationBundle:ClientType')
->createQueryBuilder('ct')
->select('ct.clientTypeId, ct.name')
->getQuery()
->getArrayResult();
$clientTypeList = [];
foreach ($clientTypes as $ct) {
$clientTypeList[$ct['clientTypeId']] = $ct['name'];
}
//UOM name
$unitTypes = $em->getRepository('ApplicationBundle:UnitType')
->createQueryBuilder('ut')
->select('ut.id, ut.name')
->getQuery()
->getArrayResult();
$unitTypeList = [];
foreach ($unitTypes as $ut) {
$unitTypeList[$ut['id']] = $ut['name'];
}
//Item group
$itemGroups = $em->getRepository('ApplicationBundle:InvItemGroup')
->createQueryBuilder('ig')
->select('ig.id, ig.name, ig.categorizationData')
->getQuery()
->getArrayResult();
$itemGroupList = [];
foreach ($itemGroups as $igData) {
$itemGroupList[$igData['id']] = array(
'name' => $igData['name'],
'categorizationData' => json_decode($igData['categorizationData'], true) ??
[
["alias" => "Category", "en" => 1, "inc" => "1"],
["alias" => "Sub Category", "en" => 1, "inc" => "1"],
]
);
}
//Currency name
$currencyTypes = $em->getRepository('ApplicationBundle:Currencies')
->createQueryBuilder('cu')
->select('cu.currencyId, cu.name')
->getQuery()
->getArrayResult();
$currencyTypeList = [];
foreach ($currencyTypes as $cu) {
$currencyTypeList[$cu['currencyId']] = $cu['name'];
}
//Sub-Category
$subCategoryTypes = $em->getRepository('ApplicationBundle:InvProductSubCategories')
->createQueryBuilder('sc')
->select('sc.id, sc.name')
->getQuery()
->getArrayResult();
$subCategoryTypeList = [];
foreach ($subCategoryTypes as $sc) {
$subCategoryTypeList[$sc['id']] = $sc['name'];
}
// Restructure: Item Group → Brand → Products
$structuredData = [];
foreach ($productMrp as $row) {
$igId = $row['igId'];
$brandId = $row['brandId'];
if (!isset($structuredData[$igId])) {
$structuredData[$igId] = [
'name' => $row['itemGroupName'],
// 'categorizationData' => json_decode($row['categorizationData'], true) ??
//
//
// [
// ["alias" => "Category", "en" => 1, "inc" => "1"],
// ["alias" => "Sub Category", "en" => 1, "inc" => "1"],
//
//
// ]
// ,
'brands' => []
];
}
if (!isset($structuredData[$igId]['brands'][$brandId])) {
$structuredData[$igId]['brands'][$brandId] = [
'name' => $row['brandCompanyName'],
'image' => $row['brandCompanyImage'],
'products' => []
];
}
$unitTypeName = isset($unitTypeList[$row['unitTypeId']]) ? $unitTypeList[$row['unitTypeId']] : 'N/A';
$currencyName = isset($currencyTypeList[$row['currency']]) ? $currencyTypeList[$row['currency']] : 'N/A';
// Parse productFdm string for SZ, SO, ST, SH values
preg_match('/SZ(\d+)/', $row['productFdm'], $szMatch);
preg_match('/SO(\d+)/', $row['productFdm'], $soMatch);
preg_match('/ST(\d+)/', $row['productFdm'], $stMatch);
preg_match('/SH(\d+)/', $row['productFdm'], $shMatch);
$subCategoryZeroId = $szMatch[1] ?? null;
$subCategoryOneId = $soMatch[1] ?? null;
$subCategoryTwoId = $stMatch[1] ?? null;
$subCategoryThreeId = $shMatch[1] ?? null;
$structuredData[$igId]['brands'][$brandId]['products'][] = [
'pid' => $row['pid'],
'name' => $row['name'],
'category' => $row['productCategory'],
'minOrderQty' => $row['minOrderQty'],
'note' => $row['note'],
'productCode' => $row['productCode'],
'unitTypeId' => $row['unitTypeId'],
'unitTypeName' => $unitTypeName,
'currency' => $row['currency'],
'currencyName' => $currencyName,
'productFdm' => $row['productFdm'],
// 'categorizationData' => $row['categorizationData'],
// 'price' => $row['priceByCustomerTypes'],
'priceByCustomerTypes' => json_decode($row['priceByCustomerTypes'], true), // decode JSON
'defaultImage' => $row['defaultImage'], // include image
// Sub-category types extracted
'subCategoryZero' => [
'id' => $subCategoryZeroId,
'name' => $subCategoryTypeList[$subCategoryZeroId] ?? 'N/A'
],
'subCategoryOne' => [
'id' => $subCategoryOneId,
'name' => $subCategoryTypeList[$subCategoryOneId] ?? 'N/A'
],
'subCategoryTwo' => [
'id' => $subCategoryTwoId,
'name' => $subCategoryTypeList[$subCategoryTwoId] ?? 'N/A'
],
'subCategoryThree' => [
'id' => $subCategoryThreeId,
'name' => $subCategoryTypeList[$subCategoryThreeId] ?? 'N/A'
],
];
}
$find_by_query = [];
$query_add = '';
// if($method=='POST')
if (!empty($post_data->get('productId'))) {
$find_by_query['productId'] = $post_data->get('productId');
}
if (!empty($post_data->get('currency'))) {
$find_by_query['currency'] = $post_data->get('currency');
}
if (!empty($post_data->get('igId'))) {
$find_by_query['igId'] = $post_data->get('igId');
}
if (!empty($post_data->get('categoryId'))) {
$find_by_query['categoryId'] = $post_data->get('categoryId');
}
if (!empty($post_data->get('brandId'))) {
$find_by_query['brandId'] = $post_data->get('brandId');
}
if (!empty($post_data->get('actionTagId'))) {
$find_by_query['actionTagId'] = $post_data->get('actionTagId');
}
if (!empty($post_data->get('customerTypes'))) {
$find_by_query['customerTypes'] = $post_data->get('customerTypes');
}
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/views/print_product_catalogue.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Product Catalogue Print',
'export' => 'pdf,print',
// 'doc_name' => Product Cata
'start_date' => $start_date,
'end_date' => $end_date,
'openFilter' => empty($post_data->keys()) ? 1 : 0,
'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
// 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
'action_tag' => $warehouse_action_list,
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'qry' => $find_by_query,
'data_searched' => $data_searched,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'currencyTypeList' => $currencyTypeList,
'clientTypeList' => $clientTypeList,
'data' => [
'structuredData' => $structuredData,
'itemGroupList' => $itemGroupList,
'clientTypeList' => $clientTypeList,
'subCategoryTypeList' => $subCategoryTypeList,
// 'categorizationData' => $categorizationData
],
'red' => 0
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Product_catalogue.pdf"'
)
);
}
return $this->render('@Sales/pages/views/print_product_catalogue.html.twig', [
'page_title' => 'Product Catalogue Print',
'export' => 'pdf,print',
// 'doc_name' => Product Cata
'start_date' => $start_date,
'end_date' => $end_date,
'openFilter' => empty($post_data->keys()) ? 1 : 0,
'reportTypeId' => $post_data->has('reportTypeId') ? $post_data->get('reportTypeId') : '',
'reportSeperator' => $post_data->has('reportSeperator') ? $post_data->get('reportSeperator') : '',
'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
// 'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
'action_tag' => $warehouse_action_list,
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'qry' => $find_by_query,
'data_searched' => $data_searched,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'currencyTypeList' => $currencyTypeList,
'data' => [
'structuredData' => $structuredData,
'itemGroupList' => $itemGroupList,
'clientTypeList' => $clientTypeList,
'subCategoryTypeList' => $subCategoryTypeList,
// 'categorizationData' => $categorizationData
]
]);
}
// public function ViewProductCatalogueAction(Request $request)
// {
// $companyId = $this->getLoggedUserCompanyId($request);
// $em = $this->getDoctrine()->getManager();
//
// // Fetch flat product data using Doctrine
// $productMrp = $em->getRepository('ApplicationBundle:ProductMrp')->createQueryBuilder('Pr')
// ->select('Pr.productMrpId', 'Pr.priceByCustomerTypes')
// ->addSelect('P.id as pid', 'P.igId', 'P.categoryId', 'P.name')
// ->addSelect('IG.id as igId', 'IG.name as itemGroupName')
// ->addSelect('PC.name as productCategory')
// ->addSelect('PSc.name as subCategoryName')
// ->addSelect('B.id as brandId', 'B.name as brandCompanyName')
// ->leftJoin('ApplicationBundle:InvProducts', 'P', 'WITH', 'Pr.productId = P.id')
// ->leftJoin('ApplicationBundle:InvItemGroup', 'IG', 'WITH', 'P.igId = IG.id')
// ->leftJoin('ApplicationBundle:InvProductCategories', 'PC', 'WITH', 'P.categoryId = PC.id')
// ->leftJoin('ApplicationBundle:InvProductSubCategories', 'PSc', 'WITH', 'P.subCategoryId = PSc.id')
// ->leftJoin('ApplicationBundle:BrandCompany', 'B', 'WITH', 'P.brandCompany = B.id')
// ->getQuery()
// ->getResult();
//
// // Restructure flat product list into nested structure
// $structuredData = [];
//
// foreach ($productMrp as $row) {
// $igId = $row['igId'];
// $brandId = $row['brandId'];
//
// if (!isset($structuredData[$igId])) {
// $structuredData[$igId] = [
// 'name' => $row['itemGroupName'],
// 'childDataList' => [],
// ];
// }
//
// if (!isset($structuredData[$igId]['childDataList'][$brandId])) {
// $structuredData[$igId]['childDataList'][$brandId] = [
// 'name' => $row['brandCompanyName'],
// 'childDataList' => [],
// ];
// }
//
// $structuredData[$igId]['childDataList'][$brandId]['childDataList'][] = [
// 'pid' => $row['pid'],
// 'igId' => $row['igId'],
// 'brandId' => $row['brandId'],
// 'categoryId' => $row['categoryId'],
// 'name' => $row['name'],
// ];
// }
//
// return new JsonResponse([
// 'structuredData' => $structuredData
// ]);
//
// // ---- Optional: Theme/columns setup if needed later in rendering ----
// $themeId = $request->get('themeId', 1);
// $defaultColEnabled = range(1, 31);
// $columnsEnabled = $request->get('columnsEnabled', $defaultColEnabled);
// $config = $request->get('config', []);
//
// if (is_string($columnsEnabled)) $columnsEnabled = json_decode($columnsEnabled, true);
// if (is_string($config)) $config = json_decode($config, true);
// if ($config == null) $config = [];
// if ($columnsEnabled == null) $columnsEnabled = [];
// }
// public function ViewProductCatalogueAction(Request $request)
// {
//
//// $companyId = $this->getLoggedUserCompanyId($request);
//// $em = $this->getDoctrine()->getManager();
////
//// $q = $this->getDoctrine()
//// ->getRepository('ApplicationBundle:ProductMrp')
//// ->findBy(
//// array(
//// 'status' => GeneralConstant::ACTIVE,
////// 'CompanyId' => $companyId
//// )
//// );
//// $stage_list = array(
//// 0 => 'Pending',
//// 1 => 'Pending',
//// 2 => 'Complete',
//// 4 => 'Partial',
//// );
//// $data = [];
//// foreach ($q as $entry) {
//// $data[] = array(
////// 'doc_date'=>$entry->getProductMrpDocumentDate(),
////// 'id'=>$entry->getProductMrpDocumentId(),
//// 'productId' => $entry->getProductId(),
//// 'doc_id' => $entry->getProductMrpDocumentId(),
//// 'doc_hash' => $entry->getDocumentHash(),
//// 'price_data' => json_decode($entry->getPriceByCustomerTypes(), true),
////
////
//// );
//// }
////
//// return $this->render('@Sales/pages/views/view_product_catalogue_list.html.twig',
//// array(
//// 'page_title' => 'Product Catalogue List',
//// 'data' => $data,
////// 'clientTypeList' => Client::ClientTypeList($em, $companyId),
//// 'productList' => Inventory::ProductList($em, $companyId, 1)
////
//// )
//// );
//
//
// //Alternate
// $companyId = $this->getLoggedUserCompanyId($request);
// $em = $this->getDoctrine()->getManager();
//
//
// $productMrp = $em->getRepository('ApplicationBundle:ProductMrp')->createQueryBuilder('Pr')
// ->select('Pr.productMrpId', 'Pr.priceByCustomerTypes')// all write together
// ->addSelect('IG.name as itemGroupName', 'PSc.name as subCategoryName', 'PC.name as productCategory', 'B.name as brandCompanyName')// separate wise
// ->leftJoin('ApplicationBundle:InvProducts', 'P', 'WITH', 'Pr.productId = P.id')
// ->leftJoin('ApplicationBundle:InvItemGroup', 'IG', 'WITH', 'P.igId = IG.id')
// ->leftJoin('ApplicationBundle:InvProductCategories', 'PC', 'WITH', 'P.categoryId = PC.id')
// ->leftJoin('ApplicationBundle:InvProductSubCategories', 'PSc', 'WITH', 'P.subCategoryId = PSc.id')
// ->leftJoin('ApplicationBundle:BrandCompany', 'B', 'WITH', 'P.brandCompany = B.id')
//// ->where('E.id = :employeeId')
//// ->setParameter('employeeId', $employeeId)
// ->getQuery()//upper query
// ->getResult();//execute
//
// // If image is null or empty, assign empty string
//// if (empty($employeeDetails['image'])) {
//// $employeeDetails['image'] = '';
//// }
//
// return new JsonResponse($productMrp);
//
// //Sample
//// $em = $this->getDoctrine()->getManager();
//// $session = $request->getSession();
//// $employeeId = $session->get(UserConstants::USER_EMPLOYEE_ID);
////
//// $employeeDetails = $em->getRepository('ApplicationBundle:EmployeeDetails')->createQueryBuilder('E')
//// ->select('E.firstname', 'E.lastname', 'E.nid', 'E.tin', 'E.image', 'P.positionName')
//// ->addSelect('A.current_balance')
//// ->leftJoin('ApplicationBundle:SysDepartmentPosition', 'P', 'WITH', 'E.desg = P.positionId')
//// ->leftJoin('ApplicationBundle:Employee', 'EMP', 'WITH', 'EMP.employeeId = E.id')
//// ->leftJoin('ApplicationBundle:AccAccountsHead', 'A', 'WITH', 'EMP.accountsHeadId = A.accountsHeadId')
//// ->where('E.id = :employeeId')
//// ->setParameter('employeeId', $employeeId)
//// ->getQuery()
//// ->getOneOrNullResult(\Doctrine\ORM\Query::HYDRATE_ARRAY);
////
//// // If image is null or empty, assign empty string
//// if (empty($employeeDetails['image'])) {
//// $employeeDetails['image'] = '';
//// }
////
//// return new JsonResponse($employeeDetails);
//
//
//
// //
//
// $em = $this->getDoctrine()->getManager();
//
// $companyId = $this->getLoggedUserCompanyId($request);
// $listData = Inventory::GetProductListForProductListAjaxAction($em, $request->isMethod('POST') ? 'POST' : 'GET', $request->request, $companyId);
// if ($request->isMethod('POST') && $request->request->has('returnJson')) {
// if ($request->query->has('dataTableQry')) {
// return new JsonResponse(
// $listData
// );
// }
// }
//
//
//
// // For theme if change later on
// $themeId=$request->get('themeId',1);
// $defaultColEnabled= array(
// 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
//
// );
// $columnsEnabled=$request->get('columnsEnabled',$defaultColEnabled);
// $config=$request->get('config',[]);
// if(is_string($columnsEnabled))$columnsEnabled=json_decode($columnsEnabled,true);
// if(is_string($config))$config=json_decode($config,true);
// if($config==null)$config=[];
// if($columnsEnabled==null)$columnsEnabled=[];
// //till this
//
//// return $this->render('@Inventory/pages/views/product_catalogue_list.html.twig',
//// array(
//// 'page_title' => 'Product Catalogue List',
//// 'products' => [],
//// //sample
//// 'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
//// 'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
////
////
//// )
//// );
//
// }
public function ViewProductMrpDocument(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Package::GetProductMrpDocumentDetails($em, $id);
return $this->render(
'@Sales/pages/views/view_product_mrp_document.html.twig',
array(
'page_title' => 'View',
'data' => $dt,
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ProductMrpDocument'],
$id,
$dt['created_by'],
$dt['edited_by']
) : []
)
);
}
public function PrintProductMrpDocument(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$data = Package::GetProductMrpDocumentDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
return $this->render(
'@Sales/pages/print/product_mrp_print.html.twig',
array(
'page_title' => 'Product ' . $data['doc_hash'],
'data' => $data,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'MRP settings',
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
)
);
}
public function CreateClientType(Request $request, $id = 0)
{
$cc_id = '';
$cc_name = '';
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$new_cc = [];
$regionId = 0;
// $warehouseId = $request->request->get('warehouseId');
if ($request->request->get('clientTypeId') != '' && $request->request->get('clientTypeId') != 0) {
$em = $this->getDoctrine()->getManager();
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle:ClientType')
->findOneBy(
array(
'clientTypeId' => $request->request->get('clientTypeId'),
)
);
$new_cc->setName($request->request->get('name'));
// $new_cc->setSupplierShortCode($request->request->get('supplierShortCode'));
$new_cc->setCompanyId($companyId);
// $new_cc->setStatus(GeneralConstant::ACTIVE);
$em->flush();
$brandId = $new_cc->getClientTypeId();
$this->addFlash(
'success',
'Type Information Updated'
);
} else {
$new_cc = new ClientType();
$new_cc->setName($request->request->get('name'));
// $new_cc->setSupplierShortCode($request->request->get('supplierShortCode'));
$new_cc->setCompanyId($companyId);
// $new_cc->setStatus(GeneralConstant::ACTIVE);
$em->persist($new_cc);
$em->flush();
$brandId = $new_cc->getClientTypeId();
$this->addFlash(
'success',
'Type Added'
);
}
}
$extData = [];
if ($id != 0) {
$extData = $this->getDoctrine()
->getRepository('ApplicationBundle:ClientType')
->findOneBy(
array(
'clientTypeId' => $id
)
);
// $cc_data_list = [];
// foreach ($cc_data as $value) {
// $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
// $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
//
// if ($value->getSupplierCategoryId() == $id) {
// $cc_id = $value->getSupplierCategoryId();
// $cc_name = $value->getName();
// }
// }
}
return $this->render(
'@Sales/pages/input_forms/client_type.html.twig',
array(
'page_title' => 'Client Type',
'typeList' => $this->getDoctrine()
->getRepository('ApplicationBundle:ClientType')
->findBy(
array(
'CompanyId' => $companyId
)
),
'extData' => $extData,
// 'headList'=>Accounts::getParentLedgerHeads($em),
// 'warehouseList'=>Inventory::WarehouseList($em),
// 'sales_person_list'=>Client::SalesPersonList($this->getDoctrine()->getManager()),
// 'countryList'=>SalesOrderM::Co
)
);
}
public function CreateNewSecondarySaleOrder(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$hasProject = 0;
$extId = $id;
$projectId = 0;
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->query->has('projectId'))
if ($request->query->get('projectId') != 0) {
$hasProject = 1;
$projectId = $request->query->get('projectId');
}
//testing direct sale
if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
// if($request->request->has('getInitialData'))
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['SalesOrder']; //change
$dochash = $request->request->get('docHash'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id,
$request->request->has('skipApprovalFlag') ? $request->request->get('skipApprovalFlag') : 0,
$companyId
)) {
if ($request->request->has('returnJson')) {
return new JsonResponse(array(
'success' => false,
'documentHash' => 0,
'documentId' => 0,
'documentIdPadded' => str_pad(0, 8, '0', STR_PAD_LEFT),
'documentDate' => '',
'billIds' => [],
'drIds' => [],
'pmntTransIds' => [],
'viewUrl' => '',
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$funcname = 'SalesOrder';
$doc_id = $extId;
DeleteDocument::$funcname($em, $doc_id, 0, 0);
Client::ProcessTempClients($em, $companyId, $clientIds = [$request->request->get('client_id', null)]);
$orderId = SalesOrderM::CreateNewSecondarySales(
$this->getDoctrine()->getManager(),
$doc_id,
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info if not pending confirmation
$draftFlag = $request->request->has('draftFlag') ? $request->request->has('draftFlag') : 0;
$clientCreatedFlag = $request->request->has('clientCreatedFlag') ? $request->request->has('clientCreatedFlag') : 0;
$orderConfirmationPendingFlag = $request->request->has('clientCreatedFlag') ? 1 : 0;
if ($draftFlag == 0 && $orderConfirmationPendingFlag == 0) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesOrder']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$orderId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('salesMethod', 1),
$request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$orderId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
}
$url = $this->generateUrl(
'view_sales_order'
);
System::AddNewNotification(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
$request->getSession()->get(UserConstants::USER_APP_ID),
$request->getSession()->get(UserConstants::USER_COMPANY_ID),
"Sales Order : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::SALES_DEPARTMENT),
'success',
$url . "/" . $orderId,
"Sales Order"
);
if ($request->request->has('returnJson')) {
$order = $em->getRepository('ApplicationBundle:SecondarySalesOrder')->findOneBy(
array(
'salesOrderId' => $orderId, ///material
)
);
$clnt = $em->getRepository('ApplicationBundle:AccClients')->findOneBy(
array(
'clientId' => $order->getClientId(), ///material
)
);
$drs = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
array(
'salesOrderId' => $orderId, ///material
)
);
$bills = $em->getRepository('ApplicationBundle:SecondarySalesInvoice')->findBy(
array(
'salesOrderId' => $orderId, ///material
)
);
$billIds = [];
$drIds = [];
$pmntTransIds = [];
foreach ($bills as $bill)
$billIds[] = $bill->getSalesInvoiceId();
foreach ($drs as $dr)
$drIds[] = $dr->getDeliveryReceiptId();
$pmntTransIds = json_decode($order->getOrderPaymentReceiptVoucherIds(), true);
if ($pmntTransIds == null)
$pmntTransIds = [];
return new JsonResponse(array(
'success' => true,
'documentHash' => $order->getDocumentHash(),
'documentId' => $orderId,
'documentIdPadded' => str_pad($orderId, 8, '0', STR_PAD_LEFT),
'documentDate' => $order->getSalesOrderDate()->format('Y-m-d'),
'deliveryProcessType' => $order->getDeliveryProcessType(),
'paymentProcessType' => $order->getPaymentProcessType(),
'clientId' => $order->getClientId(),
'clientMail' => $clnt->getEmail() == null ? '' : $clnt->getEmail(),
'billIds' => $billIds,
'drIds' => $drIds,
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'pmntTransIds' => $pmntTransIds,
'viewUrl' => $url . "/" . $orderId,
'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else {
$this->addFlash(
'success',
'New Sales order Created'
);
return $this->redirect($url . "/" . $orderId);
}
}
}
$projectList = [];
$projectListArray = [];
// $dt=ProjectM::GetProjectListById($em);
$dt = $em->getRepository('ApplicationBundle:Project')->findBy(
array(
'projectStep' => array_flip(ProjectConstant::$projectSteps)['SALES ORDER'], ///material
'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
),
array('projectDate' => 'desc')
);
// $projectList=$dt;
foreach ($dt as $entry) {
$projectListArray[] = array(
'id' => $entry->getProjectId(),
'value' => $entry->getProjectId(),
'name' => $entry->getProjectName(),
'text' => $entry->getProjectName(),
'clientId' => $entry->getClientId(),
);
$projectList[$entry->getProjectId()] = array(
'id' => $entry->getProjectId(),
'value' => $entry->getProjectId(),
'name' => $entry->getProjectName(),
'text' => $entry->getProjectName(),
'clientId' => $entry->getClientId(),
);
// $projectList[]=array(
// 'id'=>$entry['id'],
// 'value'=>$entry['id'],
// 'name'=>$entry['projectName'],
// 'text'=>$entry['projectName'],
// 'clientId'=>$entry['clientId'],
// );
//
}
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$brandListArray = [];
$productList = Inventory::ProductList($em, $companyId, 1);
$subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
$categoryList = Inventory::ProductCategoryList($em, $companyId);
$igList = Inventory::ItemGroupList($em, $companyId);
$unitList = Inventory::UnitTypeList($em);
$brandList = Inventory::GetBrandList($em, $companyId);
foreach ($productList as $product) $productListArray[] = $product;
foreach ($categoryList as $product) $categoryListArray[] = $product;
foreach ($subCategoryList as $product) $subCategoryListArray[] = $product;
foreach ($igList as $product) $igListArray[] = $product;
foreach ($unitList as $product) $unitListArray[] = $product;
foreach ($brandList as $product) $brandListArray[] = $product;
$extDocData = [];
$extDocDataDetails = [];
if ($extId == 0) {
} else {
$extDoc = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
array(
'salesOrderId' => $extId, ///material
)
);
//now if its not editable, redirect to view
if ($extDoc) {
if ($extDoc->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_sales_order'
);
return $this->redirect($url . "/" . $extId);
} else {
$extDocData = $extDoc;
$extDocDataDetails = $em->getRepository('ApplicationBundle:SalesOrderItem')->findOneBy(
array(
'salesOrderId' => $extId, ///material
)
);
}
} else {
}
}
$clientListById = Client::GetExistingSecondaryClientList($em, $companyId);
$userId = $request->getSession()->get(UserConstants::USER_ID);
$warehouse_action_list = GeneralConstant::$warehouse_action_list;
$warehouse_action_list_array = GeneralConstant::$warehouse_action_list_array;
// $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
$userBranchIdList = $request->getSession()->get('branchIdList');
if ($userBranchIdList == null) $userBranchIdList = [];
$userBranchId = $request->getSession()->get('branchId');
$dataArray = array(
'page_title' => 'New Sales Order',
// 'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
'ClientDetails' => Client::SecondaryClientDetailsAgainstID($em, $companyId, []),
'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($this->getDoctrine()->getManager()),
'ClientListById' => $clientListById,
'users' => Users::getUserListById($em),
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $userId)['options'],
'hasProject' => $hasProject,
'warehouseList' => Inventory::WarehouseList($em),
'warehouseListArray' => Inventory::WarehouseListArray($em),
'warehouseActionList' => $warehouse_action_list,
'warehouseActionListArray' => $warehouse_action_list_array,
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
//now restrictions
// 'canUseOwnPrice'=>0,
// 'canSkipProductId'=>0,
// 'canUseZeroPrice'=>0,
// 'canSetDiscount'=>0,
// 'maxIndividualDiscountAllowed'=>0,
// 'maxGrossDiscountAllowed'=>0,
'projectId' => $projectId,
'projectList' => $projectList,
'productList' => $productList,
'productListArray' => $productListArray,
'projectListArray' => $projectListArray,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'unitList' => $unitList,
'unitListArray' => $unitListArray,
'brandList' => $brandList,
'extDocDataDetails' => $extDocDataDetails,
'extDocData' => $extDocData,
'currencyList' => Inventory::CurrencyList($em),
'extData' => $extDocData,
'ExistingClients' => $clientListById,
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'salesMethodList' => SalesConstant::$salesMethod,
'deliveryProcessTypes' => SalesConstant::$deliveryProcessType,
'paymentProcessTypes' => SalesConstant::$paymentProcessType,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'sales_person_list' => Client::SalesPersonList($em),
'stage_list' => ProjectM::GetWorkStageList($em, $companyId),
'regionList' => Client::RegionList($em, $companyId),
'regionListForClient' => Client::RegionListForClientEntry($em, $companyId),
'branchList' => Client::BranchList($em, $companyId, [], $userBranchIdList),
'userBranchIdList' => $userBranchIdList,
'userBranchId' => $userBranchId,
'headList' => Accounts::HeadList($em),
);
//json
if ($request->isMethod('POST') && ($request->request->has('getInitialData'))) // if ($request->isMethod('GET') && ($request->query->has('getInitialData')))
{
$dataArray['success'] = true;
return new JsonResponse(
$dataArray
);
}
if ($request->query->has('showPos'))
return $this->render(
'@Sales/pages/input_forms/new_sales_order_pos.html.twig',
$dataArray
);
else
return $this->render(
'@Sales/pages/input_forms/new_secondary_sales.html.twig',
$dataArray
);
}
public function SecondarySalesOrderList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$companyId = $this->getLoggedUserCompanyId($request);
$userRestrictions = [];
$selectiveDocumentsFlag = 0;
$allowedLoginIds = [];
$salesPersonList = Client::SalesPersonList($this->getDoctrine()->getManager());
$clientList = SalesOrderM::GetClientList($em, [], $companyId);
$userType = $session->get(UserConstants::USER_TYPE);
$userId = $session->get(UserConstants::USER_ID);
$orderQryArray = array('status' => GeneralConstant::ACTIVE);
if ($userType == UserConstants::USER_TYPE_CLIENT) {
$orderQryArray['clientId'] = $session->get(UserConstants::CLIENT_ID);
}
if ($userType == UserConstants::USER_TYPE_GENERAL) {
$userRestrictions = Users::getUserApplicationAccessSettings($em, $userId)['options'];
$selectiveDocumentsFlag = 1; //by default will show only selective
if (isset($userRestrictions['canSeeAllSo'])) {
if ($userRestrictions['canSeeAllSo'] == 1) {
$selectiveDocumentsFlag = 0;
}
}
if ($selectiveDocumentsFlag == 1) {
$allowedLoginIds = MiscActions::getLoginIdsByUserId($em, $session->get(UserConstants::USER_ID));
}
}
if (!$request->request->has('returnJson')) {
//if not for mobile skip the pending orders
$orderQryArray['orderConfirmationPendingFlag'] = [0, null];
$orderQryArray['draftFlag'] = [0, null];
}
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:SecondarySalesOrder')
->findBy(
$orderQryArray,
array(
'salesOrderDate' => 'DESC',
// 'salesOrderId'=>'DESC'
)
);
$stage_list = ['Initiated', 'Pending', 'Complete', 'Partial', 'Pending Tag', 'Pending Confirm.'];
$d = 9;
$data = [];
foreach ($q as $entry) {
$clientId = $entry->getClientId();
// $client=$em->getRepository('ApplicationBundle:AccClients')
// ->findOneBy(
// array(
// 'clientId'=>$clientId
// )
// );
if ($selectiveDocumentsFlag == 1) {
//1st check by sales person
$spCheckFailed = 1;
if (isset($salesPersonList[$entry->getSalesPersonId()])) {
if ($salesPersonList[$entry->getSalesPersonId()]['userId'] == $userId) {
$spCheckFailed = 0;
}
}
if ($spCheckFailed == 0) {
} else if (in_array($entry->getCreatedLoginId(), $allowedLoginIds) || in_array($entry->getEditedLoginId(), $allowedLoginIds)) {
} else {
continue;
}
}
$data[] = array(
'doc_date' => $entry->getSalesOrderDate(),
'doc_date_str' => $entry->getSalesOrderDate()->format('F d, Y'),
'id' => $entry->getSalesOrderId(),
'doc_hash' => $entry->getDocumentHash(),
'sales_person_id' => $entry->getSalesPersonId(),
'sales_person_name' => isset($salesPersonList[$entry->getSalesPersonId()]) ? $salesPersonList[$entry->getSalesPersonId()]['name'] : '',
'so_amount' => $entry->getSoAmount(),
'orderConfirmationPendingFlag' => $entry->getOrderConfirmationPendingFlag(),
'draftFlag' => $entry->getDraftFlag(),
'client_id' => $clientId,
'client_name' => $clientList[$clientId]['client_name'],
'client_code' => $clientList[$clientId]['client_code'],
'client_contact_number' => $clientList[$clientId]['contact_number'],
'client_alternate_code' => $clientList[$clientId]['client_alternate_code'],
'stage' => $stage_list[$entry->getStage()]
);
}
if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
return new JsonResponse(
array(
'page_title' => 'Sales Orders ',
'data' => $data,
'userType' => $userType,
'orderConfirmationPendingFlag' => 0,
'users' => Users::getUserListById($em),
'sales_person_list' => $salesPersonList,
'success' => empty($data) ? false : true
)
);
}
return $this->render(
'@Sales/pages/list/secondary_sales_list.html.twig',
array(
'page_title' => 'Sales Orders',
'data' => $data,
'orderConfirmationPendingFlag' => 0,
'users' => Users::getUserListById($em),
'sales_person_list' => $salesPersonList,
)
);
}
public function ViewSecondarySalesOrder(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$mis_data_flag = 0;
if ($request->query->has('mis_print'))
$mis_data_flag = 1;
$dt = SalesOrderM::GetSecondarySalesOrderDetails($em, $id, $mis_data_flag);
// $companyId = $this->getLoggedUserCompanyId($request);
$companyId = $dt['so_data']->getCompanyId();
$company_data = Company::getCompanyData($em, $companyId);
$forwardToMailAddress = '';
if ($request->query->has('forwardToMailAddress'))
$forwardToMailAddress = $request->query->get('forwardToMailAddress');
if ($forwardToMailAddress == '')
$forwardToMailAddress = $dt['client_data']->getEmail();
return $this->render(
'@Sales/pages/views/secondary_sales_order_view.html.twig',
array(
'page_title' => 'View',
'data' => $dt,
'forwardToMailAddress' => $forwardToMailAddress,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
// 'invoice_footer' => $company_data->getInvoiceFooter(),
'projectList' => ProjectM::GetProjectListById($em),
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesOrder'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'salesMethodList' => SalesConstant::$salesMethod,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'sales_person_list' => Client::SalesPersonList($em),
'stage_list' => ProjectM::GetWorkStageList($em, $companyId),
'regionList' => Client::RegionList($em, $companyId),
'regionListForClient' => Client::RegionListForClientEntry($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
'headList' => Accounts::HeadList($em),
'positionList' => Position::getPositionList($em)
)
);
}
public function PrintSecondarySalesOrder(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
//mis options flag
$mis_data_flag = 0;
if ($request->query->has('mis_print') || $request->query->has('includeMisFlag'))
$mis_data_flag = 1;
$data = SalesOrderM::GetSecondarySalesOrderDetails($em, $id, $mis_data_flag);
//print common options starts
$printTypesEnabled = ['office_copy']; //default
$sendAsPdf = 0;
$printType = 'office_copy';
if ($request->query->has('printType'))
$printType = $request->query->get('printType');
if ($request->query->has('forwardToEmail')) {
$printType = 'forwardToEmail';
// $sendAsPdf=1;
}
if ($request->query->has('attachPdf')) {
$printType = 'forwardToEmail';
$sendAsPdf = $request->query->get('attachPdf');
}
if ($printType == 'all_copy') {
$printTypesEnabled = ['office_copy', 'party_copy'];
}
if ($printType == 'forwardToEmail') {
$printTypesEnabled = ['party_copy'];
}
$forwardToMailAddress = '';
if ($request->query->has('forwardToMailAddress'))
$forwardToMailAddress = $request->query->get('forwardToMailAddress');
if ($forwardToMailAddress == '')
$forwardToMailAddress = $data['client_data']->getEmail();
//print spec options end
$company_data = Company::getCompanyData($em, $companyId);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if (($request->query->has('pdf') || $printType == 'forwardToEmail') && $this->get('knp_snappy.pdf')) {
$html = '';
$pdf_response = '';
$dataForRender = array(
//full array here
'page_title' => 'Sales Order ' . $data['doc_hash'],
'pdf' => true,
'forwardToMailAddress' => $forwardToMailAddress,
'data' => $data,
'printTypesEnabled' => $printTypesEnabled,
'sendAsPdf' => $sendAsPdf,
'export' => 'pdf,print,sendForward',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Sales Order',
'page_header_sub' => 'Add',
'projectList' => ProjectM::GetProjectListById($em),
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'salesMethodList' => SalesConstant::$salesMethod,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'sales_person_list' => Client::SalesPersonList($em),
'stage_list' => ProjectM::GetWorkStageList($em, $companyId),
'regionList' => Client::RegionList($em, $companyId),
'regionListForClient' => Client::RegionListForClientEntry($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
'headList' => Accounts::HeadList($em),
'positionList' => Position::getPositionList($em),
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'users' => Users::getUserListById($em)
);
if ($request->query->has('pdf') || $sendAsPdf == 1) {
//genertae the html only if pdf is returned or attached
$html = $this->renderView(
'@Sales/pages/print/secondary_sales_order_print.html.twig',
array(
//full array here
'page_title' => 'Sales Order ' . $data['doc_hash'],
'pdf' => true,
'forwardToMailAddress' => $forwardToMailAddress,
// 'convertImageToBase64'=>true,
'data' => $data,
'printTypesEnabled' => $printTypesEnabled,
'sendAsPdf' => $sendAsPdf,
'export' => 'pdf,print',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'New Product',
'document_type' => 'Sales Order',
'page_header_sub' => 'Add',
'projectList' => ProjectM::GetProjectListById($em),
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'salesMethodList' => SalesConstant::$salesMethod,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'sales_person_list' => Client::SalesPersonList($em),
'stage_list' => ProjectM::GetWorkStageList($em, $companyId),
'regionList' => Client::RegionList($em, $companyId),
'regionListForClient' => Client::RegionListForClientEntry($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
'headList' => Accounts::HeadList($em),
'positionList' => Position::getPositionList($em),
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'users' => Users::getUserListById($em)
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
}
if ($printType == 'forwardToEmail') {
$bodyHtml = '';
$bodyTemplate = '@Sales/pages/print/secondary_sales_order_print.html.twig';
$bodyData = $dataForRender;
$attachments = [];
if ($sendAsPdf == 1) {
$attachments[] = array(
'file' => $pdf_response,
'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'fileType' => 'application/pdf'
);
}
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/temp/' . 'ledger' . '.pdf'
$new_mail = $this->get('mail_module');
$new_mail->sendMyMail(array(
'senderHash' => '_SALES_ORDERS_',
// 'senderHash'=>'_CUSTOM_',
'forwardToMailAddress' => $forwardToMailAddress,
'subject' => $company_data->getName() . ' New Order#' . str_pad($id, 8, '0', STR_PAD_LEFT),
'fileName' => 'Order#' . str_pad($id, 8, '0', STR_PAD_LEFT) . '.pdf',
'attachments' => $attachments,
'toAddress' => $forwardToMailAddress,
// 'fromAddress'=>'sales@entity.innobd.com',
// 'userName'=>'sales@entity.innobd.com',
// 'password'=>'Y41dh8g0112',
// 'smtpServer'=>'smtp.hostinger.com',
// 'smtpPort'=>587,
// 'emailBody'=>$bodyHtml,
'mailTemplate' => $bodyTemplate,
'templateData' => $bodyData,
'embedCompanyImage' => 1,
'companyId' => $companyId,
'companyImagePath' => $company_data->getImage()
));
return new JsonResponse(
array(
'success' => true
)
);
} else {
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="sales_order_' . $id . '.pdf"'
)
);
}
}
return $this->render(
'@Sales/pages/print/secondary_sales_order_print.html.twig',
array(
'page_title' => 'Sales Order ' . $data['doc_hash'],
'data' => $data,
// 'convertImageToBase64'=>true,
'printTypesEnabled' => $printTypesEnabled,
'sendAsPdf' => $sendAsPdf,
'forwardToMailAddress' => $forwardToMailAddress,
'export' => 'pdf,print,sendForward',
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'page_header' => 'Sales Order',
'document_type' => 'Sales Order',
'page_header_sub' => 'Add',
'projectList' => ProjectM::GetProjectListById($em),
'ExistingClients' => Client::GetExistingClientList($em, $companyId),
'priceList' => Inventory::ProductPriceListByProductId($em, $companyId),
'clientTypeList' => Client::ClientTypeList($em, $companyId),
'clientSelectionTypeList' => SalesConstant::$tradeOfferClientSelectionType,
'discountTypeList' => SalesConstant::$tradeOfferDiscountType,
'salesMethodList' => SalesConstant::$salesMethod,
'specialDiscountCriteria' => SalesConstant::$tradeOfferSpecialDiscountCriteria,
'discountTypeDetailedList' => SalesConstant::$tradeOfferDiscountTypeDetailed,
'itemSelectionTypeList' => SalesConstant::$tradeOfferItemSelectionType,
'paymentTypeList' => SalesConstant::$tradeOfferPaymentType,
'paymentMethodList' => SalesConstant::$tradeOfferPaymentMethod,
'discountValueSelectorList' => SalesConstant::$tradeOfferDiscountValueSelector,
'sales_person_list' => Client::SalesPersonList($em),
'stage_list' => ProjectM::GetWorkStageList($em, $companyId),
'regionList' => Client::RegionList($em, $companyId),
'regionListForClient' => Client::RegionListForClientEntry($em, $companyId),
'branchList' => Client::BranchList($em, $companyId),
'headList' => Accounts::HeadList($em),
'positionList' => Position::getPositionList($em),
// 'type_list'=>$type_list,
// 'mis_data'=>$mis_data,
// 'mis_print'=>$mis_print,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'users' => Users::getUserListById($em)
)
);
}
public function CreateSecondaryClient(Request $request, $id = 0)
{
$exClientId = $id;
if ($exClientId == 0)
$exClientId = $request->query->has("ex_c_id") ? $request->query->get("ex_c_id") : null;
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
if ($request->isMethod('POST')) {
if ($request->request->get('exClientID', false)) {
$IFUpdated = Client::UpdateSecondaryClient(
$em,
$this->getLoggedUserCompanyId($request),
$request->request->get('exClientID'),
$request->request->get('clientName'),
$request->request->get('contactPersonName'),
$request->request->get('clientDue') == '' ? 0 : $request->request->get('clientDue'),
$request->request->get('initialOpeningBalance') == '' ? 0 : $request->request->get('initialOpeningBalance'),
$request->request->get('salesPersonID'),
$request->request->get('type'),
$request->request->get('regionId'),
$request->request->get('countryId'),
$request->request->get('geographicalRegionId'),
$request->request->get('clientNumericalCode'),
$request->request->get('clientAreaWiseCode'),
$request->request->get('clientShortCode'),
$request->request->get('clientAlternateCode'),
0,
// $request->request->get('divisionId'),
$request->request->get('addressContact'),
$request->request->get('contactNumber'),
$request->request->get('shippingAddress'),
$request->request->get('billingAddress'),
$request->request->get('email'),
$request->request->get('fax'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
if ($IFUpdated) {
$this->addFlash(
'success',
'Client Updated'
);
} else {
$this->addFlash(
'error',
'Client have not been updated'
);
}
// return $this->redirectToRoute("create_client");
} else {
Client::CreateNewSecondaryClient(
$em,
$this->getLoggedUserCompanyId($request),
$request->request->get('clientName'),
$request->request->get('clientDue') == '' ? 0 : $request->request->get('clientDue'),
$request->request->get('initialOpeningBalance') == '' ? 0 : $request->request->get('initialOpeningBalance'),
$request->request->get('contactPersonName'),
$request->request->get('salesPersonID'),
$request->request->get('type'),
$request->request->get('regionId'),
$request->request->get('countryId'),
$request->request->get('geographicalRegionId'),
$request->request->get('clientNumericalCode'),
$request->request->get('clientAreaWiseCode'),
$request->request->get('clientShortCode'),
$request->request->get('clientAlternateCode'),
// $request->request->get('divisionId'),
0,
$request->request->get('addressContact'),
$request->request->get('contactNumber'),
$request->request->get('shippingAddress'),
$request->request->get('billingAddress'),
$request->request->get('email'),
$request->request->get('fax'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
}
Client::ProcessTempClients($em, $companyId);
}
return $this->render(
'@Sales/pages/input_forms/ceate_secondary_client.html.twig',
array(
'page_title' => 'New Client',
'existingClientID' => $exClientId,
'client_types' => Client::ClientTypeList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'region_data' => Client::RegionListForClientEntry($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'geographical_region_data' => Client::GeographicalRegionListForClientEntry($this->getDoctrine()->getManager(), 19, $this->getLoggedUserCompanyId($request)),
'division_list' => Client::DivisionList($this->getDoctrine()->getManager()),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
'sales_person_list_array' => Client::SalesPersonListArray($this->getDoctrine()->getManager()),
)
);
}
public function SecondaryClientList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$allowed_ids = [];
$companyId = $this->getLoggedUserCompanyId($request);
$listData = SalesOrderM::GetClientListForSecondaryClientList($em, $request->isMethod('POST') ? 'POST' : 'GET', $request->request, $companyId);
if ($request->isMethod('POST')) {
if ($request->query->has('dataTableQry')) {
return new JsonResponse(
$listData
);
}
}
return $this->render(
'@Sales/pages/list/secondary_client_list.html.twig',
// return $this->render('ApplicationBundle:pages/dashboard:test_pix_invent.html.twig',
array(
'page_title' => 'Client List',
'data' => SalesOrderM::GetSecondaryClientList($em, [], $companyId),
'client_types' => Client::GetClientType($em, $companyId),
'region_list' => Client::RegionList($em, $companyId),
'geographical_region_list' => Client::GeographicalRegionList($em, $companyId)
)
);
}
public function AddSubWarehouse(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
if ($request->isMethod('POST')) {
$new_cc = [];
$regionId = 0;
$warehouseId = $request->request->get('warehouseId');
$createAutomatically = $request->request->has('createAutomatically') ? $request->request->get('createAutomatically') : 0;
$invParentHead = 0;
$inv_parent_data = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'inventory_parent'
));
if ($inv_parent_data)
$invParentHead = $inv_parent_data->getData();
if ($request->request->get('warehouseActionId') != '' && $request->request->get('warehouseActionId') != 0) {
$em = $this->getDoctrine()->getManager();
$subwarehouse = $this->getDoctrine()
->getRepository('ApplicationBundle:WarehouseAction')
->findOneBy(
array(
'id' => $request->request->get('warehouseActionId'),
)
);
$AccHeadID = $request->request->get('accountsHeadId', '_UNCHANGED_');
if ($AccHeadID == '_UNCHANGED_')
$AccHeadID = $subwarehouse->getAccountsHeadId();
else {
if ($createAutomatically == 1 && $invParentHead != 0) {
$AccHeadID = Accounts::CreateNewHead($em, GeneralConstant::OPENING_YEAR, $invParentHead, 'Stock of ' . $request->request->get('name'), '', 0, 0, 'dr', $loginId);
}
}
$subwarehouse->setName($request->request->get('name'));
$subwarehouse->setCompanyId($companyId);
$subwarehouse->setStatus(1);
$subwarehouse->setAccountsHeadId($AccHeadID);
$subwarehouse->setReplacementAllowed($request->request->get('replacementAllowed', 0));
$subwarehouse->setDeliveryAllowed($request->request->get('deliveryAllowed', 0));
$subwarehouse->setSellAllowed($request->request->get('sellAllowed', 0));
$subwarehouse->setCreatedLoginId($loginId);
$em->persist($subwarehouse);
$em->flush();
$inv_head_data = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'warehouse_action_' . $subwarehouse->getId()
));
if (!empty($inv_head_data)) {
$inv_head_data->setData($AccHeadID);
$em->flush();
} else {
$inv_head_data = new AccSettings();
$inv_head_data->setName('warehouse_action_' . $subwarehouse->getId());
$inv_head_data->setData($AccHeadID);
$em->persist($inv_head_data);
$em->flush();
}
$this->addFlash(
'success',
'Sub Warehouse Information Updated'
);
} else {
$subwarehouse = new Warehouse();
$AccHeadID = $request->request->get('accountsHeadId', '_UNCHANGED_');
if ($createAutomatically == 1 && $invParentHead != 0) {
$AccHeadID = Accounts::CreateNewHead($em, GeneralConstant::OPENING_YEAR, $invParentHead, 'Stock of ' . $request->request->get('name'), '', 0, 0, 'dr', $loginId);
}
$subwarehouse->setName($request->request->get('name'));
$subwarehouse->setCompanyId($companyId);
$subwarehouse->setStatus(1);
$subwarehouse->setAccountsHeadId($AccHeadID);
$subwarehouse->setReplacementAllowed($request->request->get('replacementAllowed', 0));
$subwarehouse->setDeliveryAllowed($request->request->get('deliveryAllowed', 0));
$subwarehouse->setSellAllowed($request->request->get('sellAllowed', 0));
$subwarehouse->setCreatedLoginId($loginId);
$em->persist($subwarehouse);
$em->flush();
$inv_head_data = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'warehouse_action_' . $subwarehouse->getId()
));
if (!empty($inv_head_data)) {
$inv_head_data->setData($AccHeadID);
$em->flush();
} else {
$inv_head_data = new AccSettings();
$inv_head_data->setName('warehouse_action_' . $subwarehouse->getId());
$inv_head_data->setData($AccHeadID);
$em->persist($inv_head_data);
$em->flush();
}
$this->addFlash(
'success',
'Sub Warehouse Added'
);
}
}
$extData = [];
if ($id != 0) {
$extData = $this->getDoctrine()
->getRepository('ApplicationBundle:WarehouseAction')
->findOneBy(
array(
'id' => $id
)
);
// $cc_data_list = [];
// foreach ($cc_data as $value) {
// $cc_data_list[$value->getSupplierCategoryId()]['id'] = $value->getSupplierCategoryId();
// $cc_data_list[$value->getSupplierCategoryId()]['name'] = $value->getName();
//
// if ($value->getSupplierCategoryId() == $id) {
// $cc_id = $value->getSupplierCategoryId();
// $cc_name = $value->getName();
// }
// }
}
$subWarehouseDetails = $em->getRepository(WarehouseAction::class)->findAll();
return $this->render(
'@Sales/pages/input_forms/addSubWarehouse.html.twig',
array(
'page_title' => 'Add Sub Warehouse',
'subWarehouseDetails' => $subWarehouseDetails,
'extData' => $extData,
)
);
}
public function AfterSalesServiceIssues(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$afterSalesServiceIssue = [];
if ($id != 0)
$afterSalesServiceIssue = $em->getRepository('ApplicationBundle:AfterSalesServiceIssue')->findOneBy(
array(
'id' => $id
)
);
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
if ($id != 0) {
} else
$afterSalesServiceIssue = new AfterSalesServiceIssue();
$afterSalesServiceIssue->setCoreIssue($request->request->get('coreIssue'));
$afterSalesServiceIssue->setIsParent($request->request->get('isParent'));
$afterSalesServiceIssue->setParentIssueId($request->request->get('parentIssueId'));
$afterSalesServiceIssue->setItemGroupIds(json_encode($request->request->get('itemGroupIds')));
// $detailedIssue = [
// 'detailedIssue' => $request->request->get('detailedIssue'),
// ];
$preliminaryCheckList = [
'preliminaryCheckList' => $request->request->get('preliminaryCheckList'),
];
$services = [
'services' => $request->request->get('services'),
'serviceName' => $request->request->get('serviceName'),
'serviceCost' => $request->request->get('serviceCost'),
'servicePrice' => $request->request->get('servicePrice')
];
//$afterSalaesServiceIssue->setDetailedissues(json_encode($detailedIssue));
$afterSalesServiceIssue->setPreliminaryCheckList(json_encode($preliminaryCheckList));
$afterSalesServiceIssue->setServices(json_encode($services));
$afterSalesServiceIssue->setMargin($request->request->get('margin'));
$afterSalesServiceIssue->setCreatedLoginId($loginId);
$em->persist($afterSalesServiceIssue);
$em->flush();
$this->addFlash(
'success',
'Issue Added'
);
}
$issueDetails = $em->getRepository(AfterSalesServiceIssue::class)->findAll();
return $this->render(
'@Sales/pages/input_forms/create_after_sales_service_issues.html.twig',
array(
'page_title' => 'Create issues',
'issueDetails' => $issueDetails,
'afterSalesServiceIssue' => $afterSalesServiceIssue,
)
);
}
// public function viewPreliminaryRegistration(){
// return $this->render('@Sales/pages/views/view_after_sales_service_order.html.twig',
// array(
// 'page_title' => 'View Preliminary Registration',
// )
// );
// }
public function AssessmentAndConfirmation(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object');;
$warehouse_action_list_array = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'array');;
$service = Inventory::ServiceList($em, $companyId);
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['AssessmentAndConfirmation']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
Client::ProcessTempClients($em, $companyId, $clientIds = [$request->request->get('returning_client_id', null)]);
$StID = SalesOrderM::createNewAssessmentAndConfirmation(
$this->getDoctrine()->getManager(),
0,
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AssessmentAndConfirmation']]['entity_view_route_path_name']
)
);
if ($request->request->get('isConfirm', 0) == 1) {
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['AssessmentAndConfirmation'],
$StID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
}
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AssessmentAndConfirmation'],
$StID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Assessment Modified.'
);
// $url = $this->generateUrl(
// 'view_assessment_and_confirmation_info'
// );
// return $this->redirect($url . "/" . $StID);
}
}
$slotList = $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
array(
'CompanyId' => $this->getLoggedUserCompanyId($request),
)
);
return $this->render(
'@Sales/pages/input_forms/assessment_and_confirmation.html.twig',
array(
'page_title' => 'Assessment And Confirmation',
)
);
}
public function AssessmentAndConfirmationList(Request $request)
{
// return new JsonResponse(
// array(
// 'msg' => "hello"
// )
// );
$em = $this->getDoctrine()->getManager();
$data = [];
return $this->render(
'@Sales/pages/list/assessment_and-confirmation_list.html.twig',
array(
'page_title' => 'Assessment And Confirmation List',
'data' => $data,
)
);
}
public function ViewAssessmentAndConfirmation(Request $request, $id = 0)
{
return $this->render(
'@Sales/pages/views/view_assessment_and_confirmation.html.twig',
array(
'page_title' => 'View Assessment And Confirmation',
)
);
}
public function ServiceOperation(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$routeName = $request->attributes->get('_route');
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['ServiceOperation']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
Client::ProcessTempClients($em, $companyId, $clientIds = [$request->request->get('returning_client_id', null)]);
$StID = SalesOrderM::createNewServiceOperation(
$this->getDoctrine()->getManager(),
0,
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['ServiceOperation']]['entity_view_route_path_name']
)
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['ServiceOperation'],
$StID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('assessmentAction', 1)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['ServiceOperation'],
$StID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Service Action Added.'
);
// $url = $this->generateUrl(
// 'view_service_operation'
// );
// return $this->redirect($url . "/" . $StID);
}
}
return $this->render(
'@Sales/pages/input_forms/service_operation.html.twig',
array(
'page_title' => $routeName == 'service_operation' ? 'Service Operation' : 'Replacement Authorization',
'assessmentActionType' => $routeName == 'service_operation' ? 1 : 2,
)
);
}
public function ServiceOperationList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$data = [];
return $this->render(
'@Sales/pages/list/service_operation_list.html.twig',
array(
'page_title' => 'Service Operation List',
'data' => $data,
)
);
}
public function ViewServiceOperation(Request $request, $id = 0)
{
return $this->render(
'@Sales/pages/views/view_service_operation.html.twig',
array(
'page_title' => 'View Service Operation',
)
);
}
public function AfterSalesServiceDelivery(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$routeName = $request->attributes->get('_route');
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceDelivery']; //change
$dochash = $request->request->get('voucherNumber'); //change
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash
)) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
Client::ProcessTempClients($em, $companyId, $clientIds = [$request->request->get('returning_client_id', null)]);
$afterSalesDeliveryObj = SalesOrderM::createNewAfterSalesServiceDelivery(
$this->getDoctrine()->getManager(),
0,
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
$StID = $afterSalesDeliveryObj->getId();
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = 1; //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceDelivery']]['entity_view_route_path_name']
)
);
$url = $this->generateUrl(
'view_after_sales_service_delivery'
);
System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceDelivery'],
$StID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('assessmentAction', 1)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['AfterSalesServiceDelivery'],
$StID,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$soId = $afterSalesDeliveryObj->getSalesOrderId();
$afterSalesServiceOrderId = $afterSalesDeliveryObj->getAfterSalesServiceOrderId();
if ($request->request->has('returnJson')) {
$order = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
array(
'salesOrderId' => $soId, ///material
)
);
$clnt = $em->getRepository('ApplicationBundle:AccClients')->findOneBy(
array(
'clientId' => $order->getClientId(), ///material
)
);
$drs = $em->getRepository('ApplicationBundle:DeliveryReceipt')->findBy(
array(
'salesOrderId' => $soId, ///material
)
);
$bills = $em->getRepository('ApplicationBundle:SalesInvoice')->findBy(
array(
'salesOrderId' => $soId, ///material
)
);
$billIds = [];
$drIds = [];
$pmntTransIds = [];
foreach ($bills as $bill)
$billIds[] = $bill->getSalesInvoiceId();
foreach ($drs as $dr)
$drIds[] = $dr->getDeliveryReceiptId();
$pmntTransIds = json_decode($order->getOrderPaymentReceiptVoucherIds(), true);
if ($pmntTransIds == null)
$pmntTransIds = [];
return new JsonResponse(array(
'success' => true,
'documentHash' => $order->getDocumentHash(),
'documentId' => $soId,
'documentIdPadded' => str_pad($soId, 8, '0', STR_PAD_LEFT),
'documentDate' => $order->getSalesOrderDate()->format('Y-m-d'),
'deliveryProcessType' => $order->getDeliveryProcessType(),
'paymentProcessType' => $order->getPaymentProcessType(),
'clientId' => $order->getClientId(),
'clientMail' => $clnt->getEmail() == null ? '' : $clnt->getEmail(),
'billIds' => $billIds,
'drIds' => $drIds,
'skipApprovalAction' => $request->request->has('skipApprovalAction') ? $request->request->get('skipApprovalAction') : 0,
'pmntTransIds' => $pmntTransIds,
'viewUrl' => $url . "/" . $soId,
'orderPrintMainUrl' => $this->generateUrl('print_sales_order'),
'invoicePrintMainUrl' => $this->generateUrl('print_sales_invoice'),
'drPrintMainUrl' => $this->generateUrl('print_delivery_receipt'),
'orderPaymentPrintMainUrl' => $this->generateUrl('print_voucher'),
));
} else {
$this->addFlash(
'success',
'Service Action Added.'
);
return $this->redirect($url . "/" . $soId);
}
// $url = $this->generateUrl(
// 'view_service_operation'
// );
// return $this->redirect($url . "/" . $StID);
}
}
return $this->render(
'@Sales/pages/input_forms/after_sales_service_delivery.html.twig',
array(
'page_title' => $routeName == 'service_operation' ? 'After Sales Delivery' : 'After Sales Delivery',
'assessmentActionType' => $routeName == 'after_sales_service_delivery' ? 1 : 2,
'extDocData' => [],
)
);
}
public function AfterSalesServiceDeliveryList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$data = [];
return $this->render(
'@Sales/pages/list/after_sales_service_delivery_list.html.twig',
array(
'page_title' => 'After Sales Delivery List',
'data' => $data,
)
);
}
public function ViewAfterSalesServiceDelivery(Request $request, $id = 0)
{
return $this->render(
'@Sales/pages/views/view_after_sales_service_delivery.html.twig',
array(
'page_title' => 'View After Sales Delivery',
)
);
}
public function PrintAfterSalesServiceDelivery(Request $request, $id = 0)
{
return $this->render(
'@Sales/pages/views/print_after_sales_service_delivery.html.twig',
array(
'page_title' => 'View After Sales Delivery',
)
);
}
public function CreateSalesLead(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['SalesLead'];
// $projectData=$em->getRepository('ApplicationBundle:Project')->findOneBy(
// array(
// 'salesProposalId'=>$id, ///material
//
// ),array('projectDate'=>'desc')
// );
// $client=$em->getRepository('ApplicationBundle:AccClients')->findOneBy(
// array(
// 'clientId'=>$projectData->getClientId(), ///material
//
// ),array('projectDate'=>'desc')
// );
$dochash = $request->request->get('docHash');
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole');
$approveHash = $request->request->get('approvalHash');
if (!DocValidation::isInsertable(
$em,
$entity_id,
$dochash,
$loginId,
$approveRole,
$approveHash,
$id
)) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
//construct the files
$file_list = array(
'product_files' => [],
'service_files' => [],
'ar_files' => [],
);
// if ($request->request->has('products')) {
//
// if ($request->files->has('product_reference_file')) {
// foreach ($request->files->get('product_reference_file') as $uploadedFile) {
//
// $path = "";
//
// if ($uploadedFile != null) {
//
// $fileName = 'p' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
// $path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
// if (!file_exists($upl_dir)) {
// mkdir($upl_dir, 0777, true);
// }
// $file = $uploadedFile->move($upl_dir, $path);
//
// }
// $file_list['product_files'][] = $path;
// }
// }
//
//
// }
// if ($request->request->has('services')) {
// //construct the ref_files array
// $ref_files = [];
// $path = "";
// $file_path = "";
// if ($request->files->has('product_reference_file')) {
// foreach ($request->files->get('service_reference_file') as $uploadedFile) {
//// $uploadedFile = $request->files['service_reference_file_' . $request->request->get('service_uid')[$key]];
// $path = "";
// if ($uploadedFile != null) {
//
// $fileName = 's' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
// $path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
// if (!file_exists($upl_dir)) {
// mkdir($upl_dir, 0777, true);
// }
// $file = $uploadedFile->move($upl_dir, $path);
//
// }
// $file_list['service_files'][] = $path;
// }
// }
//
// }
// if ($request->request->has('heads')) {
// //construct the ref_files array
// $ref_files = [];
// $path = "";
// $file_path = "";
// foreach ($request->files->get('ar_reference_file') as $uploadedFile) {
//// $uploadedFile = $request->files['ar_reference_file_' . $request->request->get('ar_uid')[$key]];
// $path = "";
// if ($uploadedFile != null) {
//
// $fileName = 'a' . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
// $path = $fileName;
// $upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/ProjectDocs/' . $id . '/';
// if (!file_exists($upl_dir)) {
// mkdir($upl_dir, 0777, true);
// }
// $file = $uploadedFile->move($upl_dir, $path);
//
// }
// $file_list['ar_files'][] = $path;
// }
//
// }
// $document_data_id = SalesOrderM::UpdateDocumentData($this->getDoctrine()->getManager(), $request->request->get('documentDataId'), $request->request, $file_list);
$document_data_id = 0;
$spId = SalesOrderM::CreateNewLead(
$this->getDoctrine()->getManager(),
$id,
$document_data_id,
$request->request,
$dochash,
$file_list,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$this->getLoggedUserCompanyId($request)
);
//now add Approval info
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$approveRole = $request->request->get('approvalRole'); //created
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'url' => $this->generateUrl(
GeneralConstant::$Entity_list_details[array_flip(GeneralConstant::$Entity_list)['SalesLead']]['entity_view_route_path_name']
)
);
$currentApprovalData = System::setApprovalInfo(
$this->getDoctrine()->getManager(),
$options,
array_flip(GeneralConstant::$Entity_list)['SalesLead'],
$spId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesLead'],
$spId,
$loginId,
$approveRole,
$request->request->get('approvalHash')
);
$this->addFlash(
'success',
'Sales Proposal Created'
);
$url = $this->generateUrl(
'view_sales_lead'
);
if ($currentApprovalData['inProcess'] == 1) {
System::AddNewNotification(
$this->container->getParameter('notification_enabled'),
$this->container->getParameter('notification_server'),
$request->getSession()->get(UserConstants::USER_APP_ID),
$request->getSession()->get(UserConstants::USER_COMPANY_ID),
"Sales Order : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, GeneralConstant::SALES_DEPARTMENT),
'success',
$url . "/" . $spId,
"Sales Lead"
);
}
return $this->redirect($url . "/" . $spId);
}
}
$projectList = [];
$projectData = [];
$materialData = [];
$boqData = [];
$wpData = [];
$offerData = [];
$proposalData = [];
$leadData = [];
$message = "";
$allDetData = [];
$projectList = $em->getRepository('ApplicationBundle:Project')->findBy(
array(
'projectStep' => array_flip(ProjectConstant::$projectSteps)['PROPOSAL'], ///material
'stage' => array_flip(ProjectConstant::$projectStages)['INITIATED'],
'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
),
array('projectDate' => 'desc')
);
$bgDataListByBgType = [];
$bgDataList = [];
if ($id != 0) {
$leadData = $em->getRepository('ApplicationBundle:SalesLead')->findOneBy(
array(
'leadId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($leadData) {
$bgDataList = json_decode($leadData->getBankGuaranteeData(), true);
if ($bgDataList == null)
$bgDataList = [];
}
}
foreach ($bgDataList as $bgData) {
$bgData['number'] = '';
if ($bgData['id'] != 0) {
$bg = $em->getRepository('ApplicationBundle:AccCheck')->findOneBy(
array(
'CheckId' => $bgData['id'], ///material
)
);
if ($bg) {
$bgData['amount'] = $bg->getCheckAmount();
$bgData['number'] = $bg->getCheckNumber();
$bgData['returnDateTs'] = $bg->getReturnableAfterTs();
$bgData['expireDateTs'] = $bg->getValidUptoTs();
$bgData['dateTs'] = $bg->getCheckDate()->format('U');
}
}
$bgDataListByBgType[$bgData['bankGuaranteeType']] = $bgData;
}
// $bgDataListByBgType=$bgDataList;
// dump($bgDataList);
// dump($leadData->getBankGuaranteeData());
$qry = $em->getRepository("ApplicationBundle:InvProducts")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
'type' => 1 //trade items
));
$pl = [];
$pl_array = [];
foreach ($qry as $product) {
$pl[$product->getId()] = array(
'text' => $product->getName(),
'name' => $product->getName(),
'id' => $product->getId(),
'value' => $product->getId(),
'purchase_price' => $product->getPurchasePrice(),
'sales_price' => $product->getSalesPrice(),
'supplier_id' => $product->getBrandCompany(),
);
$pl_array[] = array(
'text' => $product->getName(),
'value' => $product->getId(),
'name' => $product->getName(),
'id' => $product->getId(),
'purchase_price' => $product->getPurchasePrice(),
'sales_price' => $product->getSalesPrice(),
'supplier_id' => $product->getBrandCompany(),
);
}
$qry = $em->getRepository("ApplicationBundle:AccService")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
// 'type'=>1//trade items
));
$sl = [];
$sl_array = [];
foreach ($qry as $product) {
$sl[$product->getServiceId()] = array(
'text' => $product->getServiceName(),
'value' => $product->getServiceId(),
'name' => $product->getServiceName(),
'id' => $product->getServiceId(),
);
$sl_array[] = array(
'text' => $product->getServiceName(),
'value' => $product->getServiceId(),
'name' => $product->getServiceName(),
'id' => $product->getServiceId(),
);
}
$qry = $em->getRepository("ApplicationBundle:ProjectWorkStage")->findBy(array(
"status" => GeneralConstant::ACTIVE,
'CompanyId' => $this->getLoggedUserCompanyId($request),
// 'type'=>1//trade items
));
$workStages = [];
$workStages_array = [];
foreach ($qry as $product) {
$workStages[$product->getProjectWorkStageId()] = array(
'text' => $product->getStageName(),
'value' => $product->getProjectWorkStageId(),
'name' => $product->getStageName(),
'id' => $product->getProjectWorkStageId(),
);
$workStages_array[] = array(
'text' => $product->getStageName(),
'value' => $product->getProjectWorkStageId(),
'name' => $product->getStageName(),
'id' => $product->getProjectWorkStageId(),
);
}
$hl = Accounts::HeadList($em);
$debug_data = $request->files->get('product_reference_file');
$companyId = $this->getLoggedUserCompanyId($request);
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$brandListArray = [];
$productList = Inventory::ProductList($em, $companyId);
$subCategoryList = Inventory::ProductSubCategoryList($em, $companyId);
$categoryList = Inventory::ProductCategoryList($em, $companyId);
$igList = Inventory::ItemGroupList($em, $companyId);
$unitList = Inventory::UnitTypeList($em);
$brandList = Inventory::GetBrandList($em, $companyId);
foreach ($productList as $product) $productListArray[] = $product;
foreach ($categoryList as $product) $categoryListArray[] = $product;
foreach ($subCategoryList as $product) $subCategoryListArray[] = $product;
foreach ($igList as $product) $igListArray[] = $product;
foreach ($unitList as $product) $unitListArray[] = $product;
foreach ($brandList as $product) $brandListArray[] = $product;
$assignedProjectSiteList = [];
// if($projectId==0)
// {
// $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
// }
// else
// {
//
// $extTrans=$em->getRepository('ApplicationBundle:Project')->findOneBy(
// array(
// 'projectId'=>$projectId, ///material
//
// )
// );
// $assignedProjectSiteList=ProjectM::ProjectSiteList($em,$projectId,$companyId);
// $projectSiteList=ProjectM::ProjectSiteList($em,[],$companyId);
//
//
// //now if its not editable, redirect to view
// if($extTrans) {
// if ($extTrans->getEditFlag() != 1 && $request->query->get('forceEdit',0)==0) {
// $url = $this->generateUrl(
// 'view_project'
// );
// return $this->redirect($url . "/" . $projectId);
// }
// else
// {
// $extDocData=$extTrans;
//// $extDocDetailsData=Accounts::GetVoucherDataForEdit($em,$projectId);
// }
// }
// else
// {
//
// }
//
// }
return $this->render(
'@Sales/pages/input_forms/create_sales_lead.html.twig',
array(
'page_title' => 'Sales Lead',
'ExistingClients' => Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
// 'clients'=>SalesOrderM::GetClientList($em),
'clients_by_ac_head' => SalesOrderM::GetClientListByAcHead($em),
'users' => Users::getUserListById($em),
'stages' => ProjectConstant::$projectStages,
'bankGuaranteeTypes' => AccountsConstant::$BankGuarnteeTypes,
'productList' => $productList,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'igList' => $igList,
'bidDataList' => SalesConstant::$bidDataList,
'unitList' => $unitList,
'brandList' => $brandList,
'brandListArray' => $brandListArray,
'productListArray' => $productListArray,
'subCategoryListArray' => $subCategoryListArray,
'categoryListArray' => $categoryListArray,
'igListArray' => $igListArray,
'unitListArray' => $unitListArray,
'currencyList' => Inventory::CurrencyList($em),
'sl' => $sl,
'pl' => $pl,
'hl' => $hl,
'workStages' => $workStages,
'bgData' => $bgDataListByBgType,
'projectList' => $projectList,
'projectData' => $projectData,
'materialData' => $materialData,
'boqData' => $boqData,
'wpData' => $wpData,
'offerData' => $offerData,
'proposalData' => $proposalData,
'extDocData' => $leadData,
'message' => $message,
'salesProposalId' => $id,
'pl_array' => $pl_array,
'sl_array' => $sl_array,
'workStages_array' => $workStages_array,
'debug_data' => $debug_data,
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
// 'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
)
);
}
public function SalesLeadList(Request $request)
{
$em = $this->getDoctrine()->getManager();
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesProposal')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
),
array(
'salesProposalDate' => 'DESC',
// 'salesOrderId'=>'DESC'
)
);
$stage_list = ['Pending', 'Pending', 'Complete', 'Partial'];
$d = 9;
$data = [];
return $this->render(
'@Sales/pages/list/sales_lead_list.html.twig',
array(
'page_title' => 'Sales Lead',
'data' => $data,
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
'users' => Users::getUserListById($em)
)
);
}
public function ViewSalesLead(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$themeId = $request->get('themeId', 1);
$defaultColEnabled = array(
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, 32
);
$columnsEnabled = $request->get('columnsEnabled', $defaultColEnabled);
$config = $request->get('config', []);
if (is_string($columnsEnabled)) $columnsEnabled = json_decode($columnsEnabled, true);
if (is_string($config)) $config = json_decode($config, true);
if ($config == null) $config = [];
if ($columnsEnabled == null) $columnsEnabled = [];
$dt = SalesOrderM::GetLeadDetails($em, $id, $columnsEnabled, $config);
if (!$dt) {
$url = $this->generateUrl(
'create_sales_lead'
);
$this->addFlash(
'error',
'The Document You asked for was not found.'
);
return $this->redirect($url . "/" . $id);
}
$stage_list = ProjectConstant::$projectStages;
$status_list = ProjectConstant::$projectStatus;
$steps_list = ProjectConstant::$projectSteps;
//now if its not editable, redirect to view
$bgDataListByBgType = [];
$bgDataList = json_decode($dt['general_data']->getBankGuaranteeData(), true);
if ($bgDataList == null)
$bgDataList = [];
foreach ($bgDataList as $bgData) {
$bgData['number'] = '';
if ($bgData['id'] != 0) {
$bg = $em->getRepository('ApplicationBundle:AccCheck')->findOneBy(
array(
'CheckId' => $bgData['id'], ///material
)
);
if ($bg) {
$bgData['amount'] = $bg->getCheckAmount();
$bgData['number'] = $bg->getCheckNumber();
$bgData['returnDateTs'] = $bg->getReturnableAfterTs();
$bgData['expireDateTs'] = $bg->getValidUptoTs();
$bgData['dateTs'] = $bg->getCheckDate()->format('U');
}
}
$bgDataListByBgType[$bgData['bankGuaranteeType']] = $bgData;
}
if ($request->get('returnJson', 0) == 1) {
return new JsonResponse(
array(
'page_title' => 'Proposal Letter',
'data' => $dt,
'config' => $config,
'columnsEnabled' => $columnsEnabled,
'theme_id' => $themeId,
// 'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
// 'wpData'=>SalesOrderM::GetWpDetails($em,$id),
'clientList' => SalesOrderM::GetClientList($em),
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'stageList' => $stage_list, //
'statusList' => $status_list,
'stepsList' => $steps_list,
'stage_list' => ProjectM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)), //
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
} else
return $this->render(
'@Sales/pages/views/view_sales_lead.html.twig',
array(
'page_title' => 'Sales Lead',
'data' => $dt,
'config' => $config,
'columnsEnabled' => $columnsEnabled,
'theme_id' => $themeId,
'bgData' => $bgDataListByBgType,
'bankGuaranteeTypes' => AccountsConstant::$BankGuarnteeTypes,
'bidDataList' => SalesConstant::$bidDataList,
// 'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
// 'wpData'=>SalesOrderM::GetWpDetails($em,$id),
'clientList' => SalesOrderM::GetClientList($em),
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'stageList' => $stage_list,
'statusList' => $status_list,
'stepsList' => $steps_list,
'stage_list' => ProjectM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)),
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
}
public function PrintSalesLead(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$stage_list = ProjectConstant::$projectStages;
$status_list = ProjectConstant::$projectStatus;
$steps_list = ProjectConstant::$projectSteps;
$themeId = $request->get('themeId', 1);
$defaultColEnabled = array(
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
);
$columnsEnabled = $request->get('columnsEnabled', $defaultColEnabled);
if ($themeId == 2)
$columnsEnabled = array_diff($columnsEnabled, [1, 3, 24, 26, 30, 31, 19, 6, 8, 15, 20, 21, 22, 23, 29]);
if ($request->get('printType', 'technical_proposal') == 'technical_proposal') {
$columnsEnabled = array_diff($columnsEnabled, [6, 8, 10, 12, 15, 18]);
}
$config = $request->get('config', []);
if (is_string($columnsEnabled)) $columnsEnabled = json_decode($columnsEnabled, true);
if (is_string($config)) $config = json_decode($config, true);
if ($config == null) $config = [];
if ($columnsEnabled == null) $columnsEnabled = [];
$dt = SalesOrderM::GetProposalDetails($em, $id, $columnsEnabled, $config);
if (!$dt) {
$url = $this->generateUrl(
'create_sales_lead'
);
$this->addFlash(
'error',
'Please Create Offer for the project 1st.'
);
return $this->redirect($url . "/" . $id);
}
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView(
'@Sales/pages/print/print_sales_lead.html.twig',
array(
//full array here
'pdf' => true,
'config' => $config,
'columnsEnabled' => $columnsEnabled,
'theme_id' => $themeId,
'page_title' => 'Offer ' . $dt['doc_hash'] . ' (' . $dt['general_data']->getClientname() . ')',
'export' => 'pdf,print',
'data' => $dt,
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0,
// 'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
// 'wpData'=>SalesOrderM::GetWpDetails($em,$id),
'clientList' => SalesOrderM::GetClientList($em),
'stageList' => $stage_list,
'statusList' => $status_list,
'stepsList' => $steps_list,
'stage_list' => ProjectM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)),
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
// 'orientation' => 'landscape',
// 'enable-javascript' => true,
// 'javascript-delay' => 1000,
'no-stop-slow-scripts' => false,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
// 'images' => true,
// 'cookie' => array(),
'dpi' => 300,
'image-dpi' => 300,
// 'enable-external-links' => true,
// 'enable-internal-links' => true
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Offer ' . $dt['doc_hash'] . ' (' . $dt['general_data']->getClientname() . ')' . '.pdf"'
)
);
}
return $this->render(
'@Sales/pages/print/print_sales_proposal.html.twig',
array(
'export' => 'pdf,print',
'config' => $config,
'columnsEnabled' => $columnsEnabled,
'theme_id' => $themeId,
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0,
'page_title' => 'Proposal Letter',
'data' => $dt,
// 'boqData'=>SalesOrderM::GetBoqDetails($em,$id),
// 'wpData'=>SalesOrderM::GetWpDetails($em,$id),
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'clientList' => SalesOrderM::GetClientList($em),
'stageList' => $stage_list,
'statusList' => $status_list,
'stepsList' => $steps_list,
'stage_list' => ProjectM::GetWorkStageList($em, $this->getLoggedUserCompanyId($request)),
'auto_created' => $dt['auto_created'],
'approval_data' => System::checkIfApprovalExists(
$em,
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
),
'document_log' => $dt['auto_created'] == 0 ? System::getDocumentLog(
$this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesProposal'],
$id,
$dt['created_by'],
$dt['edited_by']
) : [],
'users' => Users::getUserListById($em),
'sales_person_list' => Client::SalesPersonList($this->getDoctrine()->getManager()),
)
);
}
public function helperDataForClient(Request $request)
{
$entityManager = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$clientTypes = Client::ClientTypeListForApp($entityManager, $companyId);
$regionData = Client::RegionListForClientEntryForApp($entityManager, $companyId);
$geographicalRegionData = Client::GeographicalRegionListForClientEntry($entityManager, 19, $companyId);
$divisionList = Client::DivisionList($entityManager);
$salesPersonList = Client::SalesPersonListForApp($entityManager);
$data = [
'client_types' => $clientTypes,
'region_data' => $regionData,
'geographical_region_data' => $geographicalRegionData,
'division_list' => $divisionList,
'sales_person_list' => $salesPersonList
];
return new JsonResponse($data);
}
public function getSalesInvoiceListForApp()
{
$em = $this->getDoctrine()->getManager();
$salesInvoiceDetails = $em->getRepository('ApplicationBundle:SalesInvoice')
->createQueryBuilder('S')
->select('S.salesInvoiceNumber, S.salesInvoiceDate, S.invoiceAmount, S.receivedAmount, C.clientName')
->leftJoin('ApplicationBundle:AccClients', 'C', 'WITH', 'S.clientId = C.clientId')
->getQuery()
->getArrayResult();
$formatted = array_map(function ($item) {
$hasAllData = isset($item['salesInvoiceNumber'], $item['salesInvoiceDate'], $item['invoiceAmount'], $item['clientName'], $item['receivedAmount']);
if ($hasAllData && $item['salesInvoiceNumber'] && $item['salesInvoiceDate'] && $item['invoiceAmount'] && $item['clientName']) {
return [
'salesInvoiceNumber' => $item['salesInvoiceNumber'],
'salesInvoiceDate' => ($item['salesInvoiceDate'] instanceof \DateTimeInterface) ? $item['salesInvoiceDate']->format('Y-m-d') : "",
'invoiceAmount' => $item['invoiceAmount'],
'clientName' => $item['clientName'],
'paidBalance' => $item['receivedAmount'] ?? "0"
];
}
return [
'salesInvoiceNumber' => '',
'salesInvoiceDate' => '',
'invoiceAmount' => '',
'clientName' => '',
'paidBalance' => ''
];
}, $salesInvoiceDetails);
return new JsonResponse([
'message' => 'success',
'data' => $formatted
]);
}
}