<?php
namespace ApplicationBundle\Controller;
use ApplicationBundle\Constants\AccountsConstant;
use ApplicationBundle\Constants\GeneralConstant;
use ApplicationBundle\Constants\HumanResourceConstant;
use ApplicationBundle\Constants\InventoryConstant;
use ApplicationBundle\Constants\LabelConstant;
use ApplicationBundle\Constants\UserConstants;
use ApplicationBundle\Entity\Carton;
use ApplicationBundle\Entity\InvItemInOut;
use ApplicationBundle\Entity\StockReceivedNote;
use ApplicationBundle\Entity\ProductByCode;
use ApplicationBundle\Entity\StockReceivedNoteItem;
use ApplicationBundle\Entity\ConsumptionType;
use ApplicationBundle\Entity\LabelFormat;
use ApplicationBundle\Entity\UnitType;
use ApplicationBundle\Entity\EmployeeAttendance;
use ApplicationBundle\Entity\EmployeeAttendanceLog;
use ApplicationBundle\Modules\Sales\Client;
use ApplicationBundle\Modules\User\Users;
use ApplicationBundle\Constants\ProjectConstant;
use ApplicationBundle\Interfaces\SessionCheckInterface;
use ApplicationBundle\Entity\InvProductCategories;
use ApplicationBundle\Helper\Generic;
use ApplicationBundle\Modules\Accounts\Accounts;
use ApplicationBundle\Modules\Inventory\Inventory;
use ApplicationBundle\Modules\Purchase\Purchase;
use ApplicationBundle\Modules\Sales\SalesOrderM;
use ApplicationBundle\Modules\Production\ProductionM;
use ApplicationBundle\Modules\System\System;
use ApplicationBundle\Modules\HumanResource\HumanResource;
use ApplicationBundle\Modules\Purchase\Supplier;
use ApplicationBundle\Modules\System\DeleteDocument;
use ApplicationBundle\Modules\System\DocValidation;
use ApplicationBundle\Modules\System\MiscActions;
use ApplicationBundle\Modules\User\Company;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class InventoryController extends GenericController implements SessionCheckInterface
{
public function GetInitialDataForProductSelectVendorAppAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$em_goc = $this->getDoctrine()->getManager('company_group');
$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);
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$skipProductList = $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
$productList = ($skipProductList == 1) ? [] : 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);
$defaultSuffix = 'lemon-o';
$pidsByCategory = [];
$pidsBySubCategory = [];
$pidsByIg = [];
$pidsByBrand = [];
foreach ($igList as $key => $product) {
if ($product['classSuffix'] == '') {
$product['classSuffix'] = $defaultSuffix;
$igList[$key]['classSuffix'] = $defaultSuffix;
}
$igListArray[] = $product;
}
foreach ($categoryList as $product) {
if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
$product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
$categoryListArray[] = $product;
}
foreach ($subCategoryList as $product) {
if ($product['classSuffix'] == '' && isset($igList[$product['igId']]))
$product['classSuffix'] = $igList[$product['igId']]['classSuffix'];
$subCategoryListArray[] = $product;
}
foreach ($unitList as $product) {
$unitListArray[] = $product;
}
$brandListArray = [];
foreach ($brandList as $product) {
$brandListArray[] = $product;
}
foreach ($productList as $key => $product) {
// $productListArray[] = $product;
$product['igName'] = $igList[$product['igId']]['name'];
$product['categoryName'] = $categoryList[$product['categoryId']]['name'];
$product['subCategoryName'] = $subCategoryList[$product['subCategoryId']]['name'];
$product['brandName'] = $brandList[$product['brandCompany']]['name'];
$pidsByCategory[$product['categoryId']][] = $key;
$pidsBySubCategory[$product['subCategoryId']][] = $key;
$pidsIg[$product['igId']][] = $key;
$pidsByBrand[$product['brandCompany']][] = $key;
// $pidsBySubCategory=[];
// $pidsByIg=[];
$productListArray[] = $product;
$productList[$key] = $product;
}
$data = [
''
];
// if ($request->request->has('returnJson') || $request->query->has('returnJson'))
{
return new JsonResponse(
array(
'page_title' => ' ',
'data' => $data,
'productList' => $productList,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'unitList' => $unitList,
'brandList' => $brandList,
'productListArray' => $productListArray,
'subCategoryListArray' => $subCategoryListArray,
'categoryListArray' => $categoryListArray,
'igListArray' => $igListArray,
'unitListArray' => $unitListArray,
'brandListArray' => $brandListArray,
'pidsByCategory' => $pidsByCategory,
'pidsBySubCategory' => $pidsBySubCategory,
'pidsByBrand' => $pidsByBrand,
'pidsByIg' => $pidsByIg,
'success' => true
)
);
}
}
public function GetRefreshedItemAction(Request $request, $type = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$productListArray = [];
$subCategoryListArray = [];
$categoryListArray = [];
$igListArray = [];
$unitListArray = [];
$skipProductList = $request->request->has('skipProductList') ? $request->request->get('skipProductList') : 0;
$productList = ($skipProductList == 1) ? [] : Inventory::ProductList($em, $companyId, $type);
$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;
}
$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);
$hl_array = Accounts::getParentLedgerHeads($em, "", "", [], 1, $this->getLoggedUserCompanyId($request));
return new JsonResponse(
array(
// 'page_title'=>'BOM',
// 'clients'=>SalesOrderM::GetClientList($em),
// 'clients_by_ac_head'=>SalesOrderM::GetClientListByAcHead($em),
'productList' => $productList,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'unitList' => $unitList,
'brandList' => $brandList,
'productListArray' => $productListArray,
'subCategoryListArray' => $subCategoryListArray,
'categoryListArray' => $categoryListArray,
'igListArray' => $igListArray,
'unitListArray' => $unitListArray,
'brandListArray' => $brandListArray,
"success" => true,
'users' => Users::getUserListById($em),
'stages' => ProjectConstant::$projectStages,
'sl' => $sl,
'hl' => $hl,
'hl_array' => $hl_array,
'sl_array' => $sl_array,
// 'product_list_obj'=>Inventory::ProductList($this->getDoctrine()->getManager(),$this->getLoggedUserCompanyId($request))
)
);
}
public function GetProductListForMisAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$productIds = $request->query->get('productId');
$fdmList = [];
$find_array = array('id' => $productIds);
if ($request->query->get('fdmList')) {
$find_array = array();
$fdmList = $productIds = $request->query->get('fdmList');
}
// $find_array=array('id' => $productIds);
$products = $this->getDoctrine()
->getRepository('ApplicationBundle:InvProducts')
->findBy(
$find_array
);
$productList = [];
$productListForShow = [];
foreach ($products as $entry) {
$productList[$entry->getId()] = array(
'id' => $entry->getId(),
'name' => $entry->getName(),
'fdm' => $entry->getProductFdm(),
);
}
$products_in_stock = $this->getDoctrine()
->getRepository('ApplicationBundle:InventoryStorage')
->findBy(
$find_array
);
$warehouseList = Inventory::WarehouseList($em);
if (!empty($fdmList)) {
foreach ($products_in_stock as $dt) {
// if()
$matched_a_product = 0;
foreach ($fdmList as $fdm) {
$matchFdm = Inventory::MatchFdm($fdm, $productList[$dt->getProductId()]['fdm']);
if ($matchFdm['hasMatched'] == 1) {
if ($matchFdm['isIdentical'] == 1 || $matchFdm['FirstBelongsToSecond'] == 1) {
$matched_a_product = 1;
if (isset($productListForShow[$dt->getProductId()])) {
} else {
$productListForShow[$dt->getProductId()] = array(
'id' => $productList[$dt->getProductId()]['id'],
'name' => $productList[$dt->getProductId()]['name'],
'fdm' => $productList[$dt->getProductId()]['fdm'],
);
}
if (isset($productListForShow[$dt->getProductId()]['warehouse_' . $dt->getWarehouseId()]))
$productListForShow[$dt->getProductId()]['warehouse_' . $dt->getWarehouseId()] += $dt->getQty();
else {
$productListForShow[$dt->getProductId()]['warehouse_' . $dt->getWarehouseId()] = $dt->getQty();
}
break;
}
}
}
if ($matched_a_product == 0) {
continue;
}
if (isset($productList[$dt->getProductId()]['warehouse_' . $dt->getWarehouseId()]))
$productList[$dt->getProductId()]['warehouse_' . $dt->getWarehouseId()] += $dt->getQty();
else
$productList[$dt->getProductId()]['warehouse_' . $dt->getWarehouseId()] = $dt->getQty();
}
} else {
foreach ($products_in_stock as $dt) {
// if()
if (isset($productList[$dt->getProductId()]['warehouse_' . $dt->getWarehouseId()]))
$productList[$dt->getProductId()]['warehouse_' . $dt->getWarehouseId()] += $dt->getQty();
else
$productList[$dt->getProductId()]['warehouse_' . $dt->getWarehouseId()] = $dt->getQty();
}
$productListForShow = $productList;
}
$engine = $this->container->get("templating");
// $SD=Supplier::GetSupplierDetailsForMis($em,$supplier_id);
if ($productList) {
$Content = $engine->render('ApplicationBundle:pages/inventory/report:selected_item_stock.html.twig', array("productList" => $productListForShow, 'warehouseList' => $warehouseList));
return new JsonResponse(array("success" => true, "content" => $Content, 'productListForShow' => $productListForShow));
}
return new JsonResponse(array("success" => false));
}
public function CreateProductAction(Request $request, $id = 0)
{
$ex_id = 0;
$prod_det = [];
$product_duplicate = 0;
$group_type = 1;//item
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$route = $request->get('_route');
if ($route == 'create_service')
$group_type = 2;//service
$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');;
// $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
// file_put_contents($path, json_encode(array(
// 'sessionDataString'=>$request->request->get('sessionDataString'),
// 'sessionData'=>json_decode($request->request->get('sessionDataString')),
//// 'invData'=>$data_searched,
//
// )));//overwrite
if ($request->isMethod('POST')) {
if ($id == 0)
$id = $request->request->has('ex_id') ? $request->request->get('ex_id') : 0;
if ($id == 0) {
if ($group_type == 2)
$ext_pr = $this->getDoctrine()
->getRepository('ApplicationBundle:AccService')
->findOneBy(
array(
'serviceName' => $request->request->get('name'),
)
);
else
$ext_pr = $this->getDoctrine()
->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'name' => $request->request->get('name'),
)
);
if ($ext_pr)
$product_duplicate = 1;
}
if ($product_duplicate == 1) {
$this->addFlash(
'error',
'Duplicate Entry Found'
);
} else {
$image_list = [];
$defaultImage = "";
$defaultImageUploadedFile = null;
$upl_dir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/Products/';
// if ($request->files->has('product_default_image')) {
//
//
//// foreach ($request->files->get('product_default_image') as $uploadedFile)
// $defaultImageUploadedFile = $request->files->get('product_default_image');
// {
//
// $path = "";
//
// if ($defaultImageUploadedFile != null) {
//
// $fileName = 'p' . md5(uniqid()) . '.' . $defaultImageUploadedFile->guessExtension();
// $path = $fileName;
//
// if (!file_exists($upl_dir)) {
// mkdir($upl_dir, 0777, true);
// }
//// $file = $uploadedFile->move($upl_dir, $path);
//
// }
// $file_list[] = $path;
// $defaultImage = $path;
// }
//
//
// }
// if ($request->files->has('product_images')) {
//
//
// foreach ($request->files->get('product_default_image') as $ind=>$uploadedFile)
// {
//
// $path = "";
//
// if ($uploadedFile != null) {
//
// $fileName = 'p_'.$ind . md5(uniqid()) . '.' . $uploadedFile->guessExtension();
// $path = $fileName;
//
// if (!file_exists($upl_dir)) {
// mkdir($upl_dir, 0777, true);
// }
//// $file = $uploadedFile->move($upl_dir, $path);
//
// }
// $image_list[] = $path;
// if($defaultImage=='' && $ind==0) {
// $defaultImage = $path;
// $uploadedFile = $path;
// }
//
// }
//
//
// }
if ($group_type == 2) {
$ig = $this->getDoctrine()
->getRepository('ApplicationBundle:InvItemGroup')
->findOneBy(
array(
'id' => $request->request->get('itemgroupId')
)
);
$defaultPurchaseActionTagId = $request->request->get('defaultPurchaseActionTagId', '');
$ledgerHitAs = $request->request->get('ledgerHitAs', '');
$defaultExpenseId = $request->request->get('defaultExpenseId', '');
Inventory::CreateNewService(
$this->getDoctrine()->getManager(),
$request->request->get('ex_id'),
$request->request->get('name'),
$companyId,
$request->request->get('typeId'),
$request->request->get('categoryId'),
$request->request->get('brandCompany'),
$request->request->get('subCategoryId'),
$request->request->get('itemgroupId'),
$request->request->get('unitTypeId'),
$request->request->get('note'),
$request->request->get('alias', ''),
$request->request->get('categorization_1', ''),
$request->request->get('categorization_2', ''),
$request->request->get('categorization_3', ''),
$request->request->get('categorization_4', ''),
$request->request->get('purchasePrice', 0),
$request->request->get('salesPrice', 0),
$request->request->get('productFdm', ''),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
($ledgerHitAs != '') ? $ledgerHitAs : $ig->getLedgerHitAs(),
($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId : $ig->getDefaultPurchaseActionTagId(),
($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId : $ig->getDefaultExpenseId()
);
$this->addFlash(
'success',
'Service Have Been Added/Updated'
);
} else {
$ig = $this->getDoctrine()
->getRepository('ApplicationBundle:InvItemGroup')
->findOneBy(
array(
'id' => $request->request->get('itemgroupId')
)
);
$defaultPurchaseActionTagId = $request->request->get('defaultPurchaseActionTagId', '');
$ledgerHitAs = $request->request->get('ledgerHitAs', '');
$defaultExpenseId = $request->request->get('defaultExpenseId', '');
$crateData=[];
$crateData=[];
foreach ($request->request->get('product_crate', []) as $crateIndex=>$crateId)
{
$crateData[]=array(
'id'=>$crateId,
'qty'=>$request->request->get('product_qty', []),
);
}
$sizesData=[];
foreach ($request->request->get('product_crate', []) as $crateIndex=>$crateId)
{
$sizesData[]=array(
'size'=>$request->request->get('product_size', []),
'dimension'=>$request->request->get('product_dimension', []),
'dimensionUnitType'=>$request->request->get('product_dimension_unit_type', []),
'weight'=>$request->request->get('product_weight', []),
'weightUnitType'=>$request->request->get('product_weight_unit_type', []),
);
}
Inventory::CreateNewProduct(
$this->getDoctrine()->getManager(),
$request->request->get('ex_id', 0),
$request->request->get('name', ''),
$request->request->get('model_no', ''),
$this->getLoggedUserCompanyId($request),
$request->request->get('typeId', 1),
$request->request->get('categoryId', null),
$request->request->get('hasSerial', null),
$ig->getDraccountsHeadId(),
$ig->getCraccountsHeadId(),
($defaultPurchaseActionTagId != null && $defaultPurchaseActionTagId != '') ? $defaultPurchaseActionTagId : $ig->getDefaultPurchaseActionTagId(),
$ig->getVatAsExpenseFlag(),
$request->request->get('brandCompany', null),
$request->request->get('subCategoryId', null),
$request->request->get('yearlyDepreciation', 0),
$request->request->get('purchaseWarrantyMonths', 0),
$request->request->get('salesWarrantyMonths', 0),
$request->request->get('startingBalanceUnit', 0),
$request->request->get('reorderLevel', 0),
$request->request->get('note', ''),
$request->request->get('alias', ''),
$request->request->get('itemgroupId', null),
$request->request->get('unitTypeId', null),
$request->request->get('hsCode', ''),
$request->request->get('skuCode', ''),
$request->files->get('dataSheets', null),
$request->request->get('partId', ''),
$request->request->get('productCode', ''),
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$request->request->get('purchasePrice', 0),
$request->request->get('salesPrice', 0),
$request->files->get('product_default_image', null),
$upl_dir,
$request->files->get('product_images', []),
$request->request->get('expiryDays', 0),
$request->request->get('dimension', ''),
$request->request->get('dimensionUnitTypeId', 0),
$request->request->get('productFdm', ''),
$request->request->get('weight', ''),
$request->request->get('weightUnitTypeId', 0),
$request->request->get('specification', null),
$request->request->get('ingredient', null),
$request->request->get('nutrition', null),
$request->request->get('segregatePriceByColorsFlag', null),
$request->request->get('segregatePriceBySizesFlag', null),
$request->request->get('categorization_1', ''),
$request->request->get('categorization_2', ''),
$request->request->get('categorization_3', ''),
$request->request->get('categorization_4', ''),
$request->request->get('weightVarianceValue', 0),
$request->request->get('weightVarianceType', 0),
$request->request->get('singleWeight', ''),
$request->request->get('singleWeightUnitTypeId', 0),
$request->request->get('singleWeightVarianceValue', 0),
$request->request->get('singleWeightVarianceType', 0),
$request->request->get('cartonWeightVarianceValue', 0),
$request->request->get('cartonWeightVarianceType', 0),
$request->request->get('cartonCapacityCount', 0),
$request->request->get('tac', ''),
$request->request->get('sellable', 0),
$request->request->get('abstract', 0),
$request->request->get('tags', ''),
$request->request->get('markerFlags', ''),
$request->request->get('defaultColorId', 0),
$request->request->get('product_color', []),
$request->request->get('product_size', []),
($ledgerHitAs != '') ? $ledgerHitAs : $ig->getLedgerHitAs(),
($defaultExpenseId != null && $defaultExpenseId != '') ? $defaultExpenseId : $ig->getDefaultExpenseId(),
$crateData,
$sizesData
);
$this->addFlash(
'success',
'Product Have Been Added/Updated'
);
}
}
if ($request->request->has('returnJson')) {
return new JsonResponse(array(
'success' => true
));
}
if ($group_type == 2)
return $this->redirectToRoute("create_service");
else
return $this->redirectToRoute("create_product");
}
if ($id != 0) {
$ex_id = $id;
if ($group_type == 2)
$prod_det = $this->getDoctrine()->getRepository('ApplicationBundle:AccService')->findOneBy(array(
'serviceId' => $id//for now for stock of goods
// 'opening_locked'=>0
));
else
$prod_det = $this->getDoctrine()->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
'id' => $id//for now for stock of goods
// 'opening_locked'=>0
));
}
$inv_head = $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'warehouse_action_1'//for now for stock of goods
));
return $this->render('ApplicationBundle:pages/inventory/input_forms:create_product.html.twig',
array(
'page_title' => $group_type == 2 ? 'Service Entry' : 'Product Entry',
'group_type' => $group_type,
'inv_head' => $inv_head ? $inv_head->getData() : '',
// 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
'services' => Inventory::ServiceList($this->getDoctrine()->getManager()),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'itemgroup' => Inventory::ItemGroupList($em, $companyId, $group_type),
'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
'data' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager(), 1),
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
'ex_id' => $ex_id,
'warehouse_action_list' => $warehouse_action_list,
'warehouse_action_list_array' => $warehouse_action_list_array,
'markerFlags' => InventoryConstant::$SPECIAL_MARKER_ARRAY,
'ex_prod_det' => $prod_det
)
);
}
public function ProductListAction(Request $request)
{
$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
);
}
}
$inv_head = $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'warehouse_action_1'//for now for stock of goods
));
return $this->render('ApplicationBundle:pages/inventory/view:product_list.html.twig',
array(
'page_title' => 'Product List',
'inv_head' => $inv_head ? $inv_head->getData() : '',
// 'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
'products' => [],
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
// 'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
)
);
}
public function SalesVsDeliveryListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$userType = $session->get(UserConstants::USER_TYPE);
$userId = $session->get(UserConstants::USER_ID);
$orderQryArray = array('status' => GeneralConstant::ACTIVE,
'approved' => GeneralConstant::APPROVED,
// 'stage' => GeneralConstant::STAGE_PENDING
);
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));
// }
// }
$inv_head = $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'warehouse_action_1'//for now for stock of goods
));
if ($request->query->has('queryDate')) {
$date = new \DateTime($request->query->get('queryDate'));
} else {
$today = new \DateTime();
$todayStr = $today->format('Y-m-d');
$date = new \DateTime($todayStr);
}
$orderQryArray['salesOrderDate'] = $date;
$salesOrders = $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrder')->findBy($orderQryArray);
$so_ids = [];
$so_data = [];
$so_item_ids = [];
$so_item_data = [];
foreach ($salesOrders as $salesOrder) {
if ($salesOrder->getSalesOrderDate() > $date)
continue;
$so_ids[] = $salesOrder->getSalesOrderId();
$so_data[$salesOrder->getSalesOrderId()] = array(
"id" => $salesOrder->getSalesOrderId(),
"documentHash" => $salesOrder->getDocumentHash(),
"clientId" => $salesOrder->getClientId(),
);
}
$salesOrderItems = $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrderItem')->findBy(array(
'salesOrderId' => $so_ids,
));
foreach ($salesOrderItems as $salesOrderItem) {
$so_item_ids[] = $salesOrderItem->getId();
$so_item_data[$salesOrderItem->getId()] = array(
"id" => $salesOrderItem->getId(),
"productId" => $salesOrderItem->getProductId(),
"productName" => $salesOrderItem->getProductNameFdm(),
"salesOrderId" => $salesOrderItem->getSalesOrderId(),
"clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
"soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
// "documentHash"=>$salesOrder->getDocumentHash(),
"qty" => $salesOrderItem->getQty(),
"transitQty" => $salesOrderItem->getTransitQty(),
"deliveredQty" => $salesOrderItem->getDelivered(),
);
}
return $this->render('ApplicationBundle:pages/inventory/view:sales_vs_delivery_status.html.twig',
array(
'page_title' => 'Order Vs. Disperse',
'inv_head' => $inv_head ? $inv_head->getData() : '',
'so_data' => $so_data,
'queryDate' => $date,
'so_item_data' => $so_item_data,
'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
// 'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
)
);
}
public function DeliveryPendingOrderListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $request->getSession();
$userType = $session->get(UserConstants::USER_TYPE);
$userId = $session->get(UserConstants::USER_ID);
$orderQryArray = array('status' => GeneralConstant::ACTIVE,
'approved' => GeneralConstant::APPROVED,
'stage' => GeneralConstant::STAGE_PENDING
);
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));
// }
// }
$inv_head = $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'warehouse_action_1'//for now for stock of goods
));
if ($request->query->has('queryDate')) {
$date = new \DateTime($request->query->get('queryDate'));
} else {
$today = new \DateTime();
$todayStr = $today->format('Y-m-d');
$date = new \DateTime($todayStr);
}
// $orderQryArray['salesOrderDate'] = $date;
$salesOrders = $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrder')->findBy($orderQryArray);
$so_ids = [];
$so_data = [];
$so_item_ids = [];
$so_item_data = [];
foreach ($salesOrders as $salesOrder) {
if ($salesOrder->getSalesOrderDate() > $date)
continue;
$so_ids[] = $salesOrder->getSalesOrderId();
$so_data[$salesOrder->getSalesOrderId()] = array(
"id" => $salesOrder->getSalesOrderId(),
"documentHash" => $salesOrder->getDocumentHash(),
"clientId" => $salesOrder->getClientId(),
);
}
$salesOrderItems = $this->getDoctrine()->getRepository('ApplicationBundle:SalesOrderItem')->findBy(array(
'salesOrderId' => $so_ids,
));
foreach ($salesOrderItems as $salesOrderItem) {
$so_item_ids[] = $salesOrderItem->getId();
$so_item_data[$salesOrderItem->getId()] = array(
"id" => $salesOrderItem->getId(),
"productId" => $salesOrderItem->getProductId(),
"productName" => $salesOrderItem->getProductNameFdm(),
"salesOrderId" => $salesOrderItem->getSalesOrderId(),
"clientId" => $so_data[$salesOrderItem->getSalesOrderId()]['clientId'],
"soDocumentHash" => $so_data[$salesOrderItem->getSalesOrderId()]['documentHash'],
// "documentHash"=>$salesOrder->getDocumentHash(),
"qty" => $salesOrderItem->getQty(),
"transitQty" => $salesOrderItem->getTransitQty(),
"deliveredQty" => $salesOrderItem->getDelivered(),
);
}
return $this->render('ApplicationBundle:pages/inventory/view:delivery_pending_order_list.html.twig',
array(
'page_title' => 'Pending Delivery',
'inv_head' => $inv_head ? $inv_head->getData() : '',
'so_data' => $so_data,
'queryDate' => $date,
'so_item_data' => $so_item_data,
'clientList' => Client::GetExistingClientList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'products' => Inventory::ProductList($this->getDoctrine()->getManager()),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
'brandCompany' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
// 'data'=>Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
)
);
}
public function ItemGroupAction(Request $request, $id = 0)
{
$ex_id = 0;
$det = [];
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$group_type = 1;//item
$route = $request->get('_route');
if ($route == 'service_group')
$group_type = 2;//service
$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')) {
Inventory::CreateItemGroup($this->getDoctrine()->getManager(),
$request->request->get('ex_id'),
$this->getLoggedUserCompanyId($request),
$request->request,
$request->getSession()->get(UserConstants::USER_LOGIN_ID));
}
$inv_head = $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'warehouse_action_1'//for now for stock of goods
));
if ($id != 0) {
$ex_id = $id;
$det = $this->getDoctrine()->getRepository('ApplicationBundle:InvItemGroup')->findOneBy(array(
'id' => $id//for now for stock of goods
// 'opening_locked'=>0
));
}
return $this->render('ApplicationBundle:pages/inventory/input_forms:item_group.html.twig',
array(
'page_title' => $group_type == 1 ? "Item Groups" : "Service Groups",
'inv_head' => $inv_head ? $inv_head->getData() : '',
'group_type' => $group_type,
'igList' => Inventory::ItemGroupList($em, $companyId, $group_type),
'warehouse_action_list' => $warehouse_action_list,
// 'data'=>Inventory::ItemGroupFormRelatedData($this->getDoctrine()->getManager()),
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
'ex_id' => $ex_id,
'ex_det' => $det
)
);
}
public function addStartingOpeningInOutAction(Request $request, $refreshed_opening = 0)
{
//be very careful!!
$em = $this->getDoctrine()->getManager();
// $last_refresh_date="";
//steps
//1. set all inventory to their opening position
$assign_list = array();
$data = array();
if ($refreshed_opening == 0) {
$new_cc = $em
->getRepository('ApplicationBundle:AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
$date_start = new \DateTime($new_cc->getData());
$date_start_str = $date_start->format('Y-m-d');
$closingQuery = "SELECT * from inv_closing_balance where `date` <='" . $date_start_str . " 00:00:00' and opening=0 order by product_id desc, `date` asc ";
// $transQuery = "SELECT * from inv_item_transaction where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
$stmt = $em->getConnection()->prepare($closingQuery);
$stmt->execute();
$iniClosing = $stmt->fetchAll();
// $stmt = $em->getConnection()->prepare($transQuery);
// $stmt->execute();
// $iniTrans = $stmt->fetchAll();
$singleClosing_byProductId = array();
//now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
foreach ($iniClosing as $item) {
if (!isset($singleClosing_byProductId[$item['product_id']])) {
$singleClosing_byProductId[$item['product_id']] = array(
'date' => $item['date'],
'qtyAdd' => $item['qty_addition'],
'qtySub' => '0',
'valueAdd' => $item['addition'],
'valueSub' => '0',
'fromWarehouse' => 0,
'toWarehouse' => $item['warehouse_id'],
'fromWarehouseSub' => 0,
'toWarehouseSub' => $item['action_tag_id'],
'price' => ($item['addition'] / $item['qty_addition'])
);
}
}
//now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
// foreach ($iniTrans as $item) {
// if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
// $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
// $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
// $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
// $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
// }
// }
foreach ($singleClosing_byProductId as $key => $item) {
if (!isset($data[$key])) {
$data[$key][] = $item;
}
}
//now that we go the data we can empty the closing table
// $get_kids_sql ='UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
// truncate `inv_closing_balance`;
// truncate `inventory_storage`;
// truncate `inv_item_transaction`;';
// $stmt = $em->getConnection()->prepare($get_kids_sql);
// $stmt->execute();
// $stmt->closeCursor();
// $stmt->fetchAll();
$total_inv_value_in = 0;
foreach ($data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$new = new InvItemInOut();
$new->setProductId($key);
$new->setWarehouseId($entry['toWarehouse']);
$new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
$new->setActionTagId($entry['toWarehouseSub']);
$new->setTransactionDate($transDate);
$new->setQty($entry['qtyAdd']);
$new->setPrice($entry['price']);
$new->setAmount($entry['qtyAdd'] * $entry['price']);
$new->setEntity(0);// opening =0
$new->setEntityId(0);// opening =0
$new->setDebitCreditHeadId(0);// opening =0
$new->setVoucherIds(null);// opening =0
$em->persist($new);
$em->flush();
$total_inv_value_in += $entry['qtyAdd'] * $entry['price'];
}
}
}
$refreshed_opening = 1;
// $terminate=1;
// $last_refresh_date=$last_refresh_date_obj->format('Y-m-d');
return new JsonResponse(array(
"success" => true,
));
//now call the function which will add the 1st ever entry or opening entry
}
//now if opening was refreshed before then we can get the next date provided that no transaction on start date
return new JsonResponse(array(
"success" => false,
));
}
public function RefreshInventoryAction(Request $request, $refreshed_opening = 0)
{
//be very careful!!
$em = $this->getDoctrine()->getManager();
$refreshed_opening = 0;
$last_refresh_date = "";
$last_refresh_date_obj = "";
$terminate = 0;
$companyId = $this->getLoggedUserCompanyId($request);
$modifyAccTransaction = $request->request->has('modify_acc_trans_flag') ? $request->request->get('modify_acc_trans_flag') : 0;
$modifyProductionPrice = $request->request->has('modify_production_price') ? $request->request->get('modify_production_price') : 0;
// $last_refresh_date="";
if ($request->isMethod('POST')) {
//steps
//1. set all inventory to their opening position
$assign_list = array();
$data = array();
if ($request->request->has('inventory_refreshed'))
$refreshed_opening = $request->request->get('inventory_refreshed');
if ($request->request->has('last_refresh_date'))
$last_refresh_date = $request->request->get('last_refresh_date');
if ($refreshed_opening == 0) {
// System::log_it($this->container->getParameter('kernel.root_dir'), "",
// 'inventory_refresh_debug', 0); //last er 1 is append
$new_cc = $em
->getRepository('ApplicationBundle:AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
$date_start = new \DateTime($new_cc->getData());
$date_start_str = $date_start->format('Y-m-d');
$closingQuery = "SELECT * from inv_closing_balance where `date` <='" . $date_start_str . " 00:00:00' and opening=0 order by product_id desc, `date` asc ";
// $transQuery = "SELECT * from inv_item_transaction where `transaction_date` <='" . $date_start_str . " 00:00:00' order by product_id desc, `transaction_date` asc ";
$stmt = $em->getConnection()->prepare($closingQuery);
$stmt->execute();
$iniClosing = $stmt->fetchAll();
// $stmt = $em->getConnection()->prepare($transQuery);
// $stmt->execute();
// $iniTrans = $stmt->fetchAll();
$singleClosing_byProductId = array();
//now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
foreach ($iniClosing as $item) {
if (!isset($singleClosing_byProductId[$item['product_id']])) {
$singleClosing_byProductId[$item['product_id']] = array(
'date' => $item['date'],
'qtyAdd' => $item['qty_addition'],
'qtySub' => '0',
'valueAdd' => $item['addition'],
'valueSub' => '0',
'fromWarehouse' => 0,
'toWarehouse' => $item['warehouse_id'],
'fromWarehouseSub' => 0,
'toWarehouseSub' => $item['action_tag_id'],
'price' => $item['qty_addition'] != 0 ? ($item['addition'] / $item['qty_addition']) : $item['addition']
);
}
}
//now we will do like this if the product is already assigned to closing that means the last opening and closing is already assigned
// foreach ($iniTrans as $item) {
// if (!isset($singleClosing_byProductId[$item['product_id']]['fromWarehouse'])) {
// $singleClosing_byProductId[$item['product_id']]['fromWarehouse'] = 0;
// $singleClosing_byProductId[$item['product_id']]['toWarehouse'] = $item['warehouse_id'];
// $singleClosing_byProductId[$item['product_id']]['fromWarehouseSub'] = 0;
// $singleClosing_byProductId[$item['product_id']]['toWarehouseSub'] = $item['action_tag_id'];
// }
// }
foreach ($singleClosing_byProductId as $key => $item) {
if (!isset($data[$key])) {
$data[$key][] = $item;
}
}
//new one
//chekc if ultra opening stock received note exists if not create it
$mo = $em
->getRepository('ApplicationBundle:StockReceivedNote')
->findOneBy(
array(
'documentHash' => '_MASTER_OPENING_',
'typeHash' => 'SR',
'prefixHash' => 4,
'assocHash' => '_MASTER_OPENING_',
'numberHash' => 1,
)
);
if (!$mo) {
//doensot exist to add :)
// $products = $post_data->get('products');
// $qty = $post_data->get('qty');
// $note = $post_data->get('note');
$new = new StockReceivedNote();
$new->setStockReceivedNoteDate(new \DateTime($date_start_str));
$new->setCompanyId($companyId);
$new->setDocumentHash('_MASTER_OPENING_');
$new->setTypeHash('SR');
$new->setPrefixHash(4);
$new->setAssocHash('_MASTER_OPENING_');
$new->setNumberHash(1);
$new->setCreditHeadId(0);
$new->setStockTransferId(0);
$new->setSalesOrderId(0);
$new->setType(4);
$new->setStatus(GeneralConstant::ACTIVE);
$new->setWarehouseId(0);
$new->setNote('');
$new->setAutoCreated(1);
$new->setApproved(GeneralConstant::APPROVED);
// $new->setIndentTagged(0);
$new->setStage(GeneralConstant::STAGE_COMPLETE);
$new->setCreatedLoginId(0);
$new->setEditedLoginId(0);
$em->persist($new);
$em->flush();
$SRID = $new->getStockReceivedNoteId();
$last_refresh_date_obj = $new->getStockReceivedNoteDate();
//now add items to details
foreach ($data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
$new = new StockReceivedNoteItem();
$new->setStockReceivedNoteId($SRID);
$new->setStockTransferItemId(0);
$salesCodeRange = [];
$salesCodeRangeStr = '';
$new->setSalesCodeRange("[" . $salesCodeRangeStr . "]");
$new->setQty($entry['qtyAdd']);
$new->setPrice($entry['price']);
$new->setBalance($entry['qtyAdd']);
$new->setProductId($key);
$new->setWarrantyMon(0);
$new->setWarehouseId($entry['toWarehouse']);
$new->setWarehouseActionId($entry['toWarehouseSub']);
$em->persist($new);
$em->flush();
}
}
}
// for ($i = 0; $i < count($products); $i++) {
//
//
// $srItem = self::CreateNewStockReceivedNoteItem($em, $post_data, $i, $new->getStockReceivedNoteId(), $LoginID);
// }
}
if ($mo)
$last_refresh_date_obj = $mo->getStockReceivedNoteDate();
$last_refresh_date_obj->modify('-1 day');///new so that it willstart form this day on next call
//new ends
//now that we go the data we can empty the closing table
$get_kids_sql = "UPDATE `inv_products` SET qty=0, curr_purchase_price=0, purchase_price_wo_expense=0 WHERE 1;
UPDATE `purchase_order` SET expense_amount=0, expense_pending_balance_amount=0, grn_tag_pending_expense_invoice_ids='[]' WHERE 1;
truncate `inv_closing_balance`;
truncate `inventory_storage`;
truncate `inv_item_transaction`;";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$stmt->closeCursor();
// $stmt->fetchAll();
// foreach ($data as $key => $item) {
// if (!empty($item)) {
// foreach ($item as $entry) {
// $transDate = new \DateTime($entry['date']);
// Inventory::addItemToInventoryCompact($em,
// $key,
// $entry['fromWarehouse'],
// $entry['toWarehouse'],
// $entry['fromWarehouseSub'],
// $entry['toWarehouseSub'],
// $transDate,
// $entry['qtyAdd'],
// $entry['qtySub'],
// $entry['valueAdd'],
// $entry['valueSub'],
// $entry['price'],
// $this->getLoggedUserCompanyId($request));
// if ($last_refresh_date_obj == '') {
// $last_refresh_date_obj = $transDate;
// } else if ($transDate < $last_refresh_date_obj) {
// $last_refresh_date_obj = $transDate;
// }
// }
// }
// }
$refreshed_opening = 1;
// $terminate=1;
if ($last_refresh_date_obj == "") {
$last_refresh_date = $date_start_str;
} else {
$last_refresh_date = $last_refresh_date_obj->format('Y-m-d');
}
return new JsonResponse(array(
"success" => true,
"last_refresh_date" => $last_refresh_date,
"inventory_refreshed" => $refreshed_opening
));
//now call the function which will add the 1st ever entry or opening entry
}
//now if opening was refreshed before then we can get the next date provided that no transaction on start date
if ($last_refresh_date != '')
$last_refresh_date_obj = new \DateTime($last_refresh_date);
else {
$new_cc = $em
->getRepository('ApplicationBundle:AccSettings')
->findOneBy(
array(
'name' => 'accounting_year_start',
)
);
$last_refresh_date_obj = new \DateTime($new_cc->getData());
$last_refresh_date = $last_refresh_date_obj->format('Y-m-d');
}
$last_refresh_date_obj->modify('+1 day');
$today = new \DateTime();
if ($last_refresh_date_obj > $today) {
$terminate = 1;
}
$last_refresh_date = $last_refresh_date_obj->format('Y-m-d');
//ok now we got the date so get grn item on this date
//GRN
$query = "SELECT grn_item.*, grn.grn_date, grn.document_hash from grn_item
join grn on grn.grn_id=grn_item.grn_id
where grn.grn_date ='" . $last_refresh_date . " 00:00:00' and grn.approved=1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$queryData = $stmt->fetchAll();
$grn_ids = [];
foreach ($queryData as $item) {
$data[$item['product_id']][] = array(
'date' => $last_refresh_date,
'entity' => array_flip(GeneralConstant::$Entity_list)['Grn'],
'entityId' => $item['grn_id'],
'colorId' => $item['color_id'],
'sizeId' => $item['size_id'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => $item['qty'],
'qtySub' => 0,
'valueAdd' => ($item['qty'] * $item['price_with_expense']),
'valueSub' => 0,
'price' => $item['price_with_expense'],
'fromWarehouse' => 0,
'toWarehouse' => $item['warehouse_id'],
'fromWarehouseSub' => 0,
// 'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
'toWarehouseSub' => $item['warehouse_action_id']
);
if (!in_array($item['grn_id'], $grn_ids))
$grn_ids[] = $item['grn_id'];
}
//now add grns
foreach ($data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
$entry['valueAdd'],
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_SUPPLER
);
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
}
}
}
///adding grn vouhcer mod here too incase it wasnot in the distributed IG for heads
// $grn=$em->getRepository('ApplicationBundle:Grn')->findBy(array(
// 'grnId'=>$grn_ids,
// 'modifyVoucherFlag'=>1 //have to add this flag
// ));
foreach ($grn_ids as $grn_id) {
if ($modifyAccTransaction == 1)
Inventory::ModifyGrnTransactions($em, $grn_id, 1);
else
Inventory::ModifyGrnTransactions($em, $grn_id);
}
//adding voucher ends
$inv_head_list_by_wa = [];
$inv_head_list = [];
$cogs_head = 0;
$cogs_head = 0;
$internal_proj = 0;
// if ($project) {
// if ($project->getProjectType() == 2) {
// $cogs_head = $project->getInternalProjectAssetHeadId();
// $internal_proj = 1;
// } else {
// $cogs_head_qry = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
// 'name' => 'cogs'
// ));
// $cogs_head = $cogs_head_qry->getData();
// }
// } else {
$cogs_head_qry = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'cogs'
));
$cogs_head = $cogs_head_qry->getData();
// }
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object');
foreach ($warehouse_action_list as $wa) {
$inv_head_data = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'warehouse_action_' . $wa['id'])
);
if ($inv_head_data) {
$inv_head_list_by_wa[$wa['id']] = $inv_head_data->getData();
$inv_head_list[] = $inv_head_data->getData();
}
}
$data = [];
//____________STOCK_RECEIVED___________________
$docEntity = "StockReceivedNote";
$docEntityIdField = "stockReceivedNoteId";
$accTransactionDataByDocId = [];
$query = "SELECT stock_received_note_item.*, stock_received_note.stock_received_note_date, stock_received_note.type, stock_received_note.document_hash from stock_received_note_item
join stock_received_note on stock_received_note.stock_received_note_id=stock_received_note_item.stock_received_note_id
where stock_received_note.stock_received_note_date ='" . $last_refresh_date . " 00:00:00' and stock_received_note.approved=1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$queryData = $stmt->fetchAll();
$grn_ids = [];
foreach ($queryData as $item) {
$data[$item['product_id']][] = array(
'date' => $last_refresh_date,
'entity' => array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
'entityId' => $item['stock_received_note_id'],
'colorId' => $item['color_id'],
'sizeId' => $item['size_id'],
'type' => $item['type'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => $item['qty'],
'qtySub' => 0,
'valueAdd' => ($item['qty'] * $item['price']),
'valueSub' => 0,
'price' => $item['price'],
'fromWarehouse' => 0,
'toWarehouse' => $item['warehouse_id'],
'fromWarehouseSub' => 0,
// 'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
'toWarehouseSub' => $item['warehouse_action_id']
);
// if (!in_array($item['grn_id'], $grn_ids))
// $grn_ids[] = $item['grn_id'];
}
foreach ($data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
$entry['valueAdd'],
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
$entry['type'] == 4 ?
GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_OPENING :
($entry['type'] == 3 ? GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_STOCK_IN :
GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT)
);
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if (!isset($accTransactionDataByDocId[$entry['entityId']]))
$accTransactionDataByDocId[$entry['entityId']] = array();
if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = 1 * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
else
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += (1 * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
}
}
}
if ($modifyAccTransaction == 1) {
foreach ($accTransactionDataByDocId as $docId => $transData) {
$docHere = $em->getRepository('ApplicationBundle:' . $docEntity)->findOneBy(array(
$docEntityIdField => $docId,
));;
if ($docHere) {
$curr_v_ids = json_decode($docHere->getVoucherIds(), true);
if ($curr_v_ids == null)
$curr_v_ids = [];
$skipVids = [];
$toChangeVid = 0;
$voucher = null;
foreach ($curr_v_ids as $vid) {
if (in_array($vid, $skipVids))
continue;
$skipVids[] = $vid; //to prevent duplicate query
$voucher = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
'transactionId' => $vid,
));;
if ($voucher) {
if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
$toChangeVid = $vid;
} else {
continue;
}
}
}
if ($toChangeVid == 0) {
$toChangeVid = Accounts::CreateNewTransaction(0,
$em,
$docHere->getStockReceivedNoteDate()->format('Y-m-d'),
0,
AccountsConstant::VOUCHER_JOURNAL,
'Journal For Stock Received Inventory Ledger Hit for Document- ' . $docHere->getDocumentHash(),
'JV/GN/0/' . Accounts::GetVNoHash($em, 'jv', 'gn', 0),
'JV',
'GN',
0,
Accounts::GetVNoHash($em, 'jv', 'gn', 0),
0,
$docHere->getCreatedLoginId(),
$docHere->getCompanyId(),
'',
0,
1
);
$em->flush();
$voucher = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
'transactionId' => $toChangeVid,
));;
}
DeleteDocument::AccTransactions($em, $toChangeVid, 0);
$tot_inv_amount = 0;
foreach ($transData as $k => $v) {
$tot_inv_amount += (1 * $v);
Accounts::CreateNewTransactionDetails($em,
'',
$toChangeVid,
Generic::CurrToInt($v),
$k,
'Inventory Inward For - ' . $docHere->getDocumentHash(),
AccountsConstant::DEBIT,
0,
[],
[],
$docHere->getCreatedLoginId()
);
}
$stockReceivedType = $docHere->getType();
$to_balance_head = 0;
if (in_array($stockReceivedType, [2, 3]))
$to_balance_head = $docHere->getCreditHeadId();
else {
$inv_transit_head = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'inv_on_transit_head')
);
if ($inv_transit_head)
$to_balance_head = $inv_transit_head->getData();
}
Accounts::CreateNewTransactionDetails($em,
'',
$toChangeVid,
Generic::CurrToInt($tot_inv_amount),
$to_balance_head,
in_array($stockReceivedType, [2, 3]) ? 'Balancing of Stock in Items for -' . $docHere->getDocumentHash() : 'In Transit Items for -' . $docHere->getDocumentHash(),
AccountsConstant::CREDIT,
0,
[],
[],
$docHere->getCreatedLoginId()
);
if ($voucher)
$voucher->setTransactionAmount($tot_inv_amount);
$curr_v_ids = json_decode($docHere->getVoucherIds(), true);
if ($curr_v_ids != null)
$docHere->setVoucherIds(json_encode(array_merge($curr_v_ids, array_diff([$toChangeVid], $curr_v_ids))));
else
$docHere->setVoucherIds(json_encode([$toChangeVid]));
$em->flush();
// System::UpdatePostDatedTransactionById($em, $toChangeVid);
}
}
}
$data = [];
$query = "SELECT purchase_invoice.* from purchase_invoice
where purchase_invoice.purchase_invoice_date ='" . $last_refresh_date . " 00:00:00' and purchase_invoice.approved=1
";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$queryData = $stmt->fetchAll();
foreach ($queryData as $pi) {
$transDate = new \DateTime($pi['purchase_invoice_date']);
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
Accounts::CalibrateProductPriceWithPi($em, $pi['purchase_invoice_id'], 1);
}
$data = [];
$query = "SELECT expense_invoice.* from expense_invoice
where expense_invoice.expense_invoice_date ='" . $last_refresh_date . " 00:00:00' and expense_invoice.approved=1 and
expense_invoice_type_id=1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$queryData = $stmt->fetchAll();
foreach ($queryData as $ei) {
$transDate = new \DateTime($ei['expense_invoice_date']);
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
$grn_ids = json_decode($ei['grn_id_list'], true);
if ($grn_ids == null)
$grn_ids = [];
// if (!empty($grn_ids)) {
//
//
// if ($ei->getExpenseInvocationStrategyOnGrn() != 2) {
// $grn = $em->getRepository('ApplicationBundle:Grn')->findBy(array(
// 'purchaseOrderId' => $ei->getPurchaseOrderId()
// ));
//
// }
// else
// {
// $po = $em->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(array(
// 'purchaseOrderId' => $ei['purchase_order_id']
// ));
//
// if ($po) {
// $po->setExpenseAmount($po->getExpenseAmount() + $ei['invoice_amount']);
// }
// continue; //grn expense will be there anyway
// }
//
//
//
// }
Accounts::CalibrateProductPriceWithExpense($em, $ei['expense_invoice_id']);
// $po = $em->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(array(
// 'purchaseOrderId' => $ei['purchase_order_id']
// ));
//
//
// //first get the total valuation
// if ($po) {
// $total_product_value = 0;
// $total_pending_expense = 0;
// $po_item_data = $em->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(array(
//// 'productId' => $item->getProductId(),
// 'purchaseOrderId' => $ei['purchase_order_id']
// ));
//
//
// foreach ($po_item_data as $it) {
//// $product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
//// 'id' => $item->getProductId()
//// ));
//
// $poqty = $it->getReceived();
// $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);
// $total_product_value += (1 * $po_price);
//
//
// }
//
//
// //now we know the total grn price value. lets get the fraction increase
// $total_pending_expense = $ei['invoice_amount'];
// if ($total_product_value != 0)
// $fraction_increase = ($total_pending_expense) / ($total_product_value);
// else
// $fraction_increase = 0;
//
// foreach ($po_item_data as $it) {
// $item = $it;
// $product = $em->getRepository('ApplicationBundle:InvProducts')->findOneBy(array(
// 'id' => $it->getProductId()
// ));
// if (!$product)
// continue;
//
//// $items_in_inventory=$em->getRepository('ApplicationBundle:InventoryStorage')->findBy(array(
//// 'productId'=>$item->getProductId()
//// ));
//
// $poqty = $it->getReceived();
// $po_price = ($poqty * $it->getPrice()) - ($poqty * $it->getPrice() * $po->getDiscountRate() / 100);;
//
// $existing_qty = $product->getQty();;
//
//
// $increased_po_price = ($po_price * $fraction_increase);
//
// //now lets see homuch is the total price
// $new_purchase_price = $product->getPurchasePrice();
//
// if ($increased_po_price != 0) {
// $last_grn_item = $em->getRepository('ApplicationBundle:GrnItem')->findOneBy(array(
// 'purchaseOrderItemId' => $item->getId()
// ));
// if ($last_grn_item) {
//
// $data[$last_grn_item->getProductId()][] = array(
// 'date' => $last_refresh_date,
//
// 'entity' => array_flip(GeneralConstant::$Entity_list)['ExpenseInvoice'],
// 'entityId' => $ei['expense_invoice_id'],
// 'colorId' => $last_grn_item->getColorId(),
// 'sizeId' => $last_grn_item->getSizeId(),
// 'entityDocHash' => $ei['document_hash'],
// 'qtyAdd' => 0,
// 'qtySub' => 0,
// 'valueAdd' => $increased_po_price,
//// 'valueAdd' => $increased_po_price>=0?$increased_po_price:0,
//// 'valueSub' => ($item['qty'] * $item['price']),
//// 'valueSub' => $increased_po_price<0?((-1)*$increased_po_price):0,
// 'valueSub' => 0,
// 'price' => '_UNSET_',
// 'fromWarehouse' => 0,
// 'toWarehouse' => $last_grn_item->getWarehouseId(),
// 'fromWarehouseSub' => 0,
//// 'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
// 'toWarehouseSub' => $last_grn_item->getWarehouseActionId()
// );
//
//// Inventory::SetInvClosingBalance($em, $item->getProductId(), $last_grn_item->getWarehouseId(), GeneralConstant::ITEM_TRANSACTION_DIRECTION_IN, (new \DateTime($ei['expense_invoice_date']))->format('Y-m-d'), 0, $increased_po_price, GeneralConstant::WAREHOUSE_ACTION_GOODS, 0, 0, 8);
////
//// $total_item_price = $increased_po_price + ($product->getPurchasePrice() * ($existing_qty));
//// if ($existing_qty != 0)
//// $new_purchase_price = $total_item_price / $existing_qty;
//
//
// $total_pending_expense -= $increased_po_price;
// }
// }
// }
//
//
//
//
//
//
// } else {
// continue;
// }
}
$data = [];
//____________STOCK_TRANSFER___________________
$docEntity = "StockTransfer";
$docEntityIdField = "stockTransferId";
$accTransactionDataByDocId = [];
$query = "SELECT stock_transfer_item.*, stock_transfer.stock_transfer_date, stock_transfer.document_hash, stock_transfer.transfer_action_type from stock_transfer_item
join stock_transfer on stock_transfer.stock_transfer_id=stock_transfer_item.stock_transfer_id
where stock_transfer.stock_transfer_date ='" . $last_refresh_date . " 00:00:00' and stock_transfer.approved=1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$queryData = $stmt->fetchAll();
$grn_ids = [];
foreach ($queryData as $item) {
$data[$item['product_id']][] = array(
'date' => $last_refresh_date,
'transfer_action_type' => $item['transfer_action_type'],
'entity' => array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
'entityId' => $item['stock_transfer_id'],
'colorId' => $item['color_id'],
'sizeId' => $item['size_id'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => $item['transfer_action_type'] == 4 ? $item['qty'] : 0,
'qtySub' => $item['qty'],
'valueAdd' => 0,
// 'valueSub' => ($item['qty'] * $item['price']),
'valueSub' => '_AUTO_',
'price' => $item['price'],
'fromWarehouse' => $item['warehouse_id'],
'toWarehouse' => $item['transfer_action_type'] == 4 ? $item['to_warehouse_id'] : 0,
'fromWarehouseSub' => $item['warehouse_action_id'],
// 'toWarehouseSub'=> InventoryConstant::WAREHOUSE_ACTION_GOODS
'toWarehouseSub' => $item['transfer_action_type'] == 4 ? $item['to_warehouse_action_id'] : 0
);
// if (!in_array($item['grn_id'], $grn_ids))
// $grn_ids[] = $item['grn_id'];
}
//now add grns
foreach ($data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
$entry['valueAdd'],
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
$entry['transfer_action_type'] == 4 ? GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_INTER_WAREHOUSE : GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_TRANSIT
);
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if (!isset($accTransactionDataByDocId[$entry['entityId']]))
$accTransactionDataByDocId[$entry['entityId']] = array();
if ($entry['transfer_action_type'] == 4) {
if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = 1 * $entry['qtySub'] * $modifiedData['slot_cost_price'];
else
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += (1 * $entry['qtySub'] * $modifiedData['slot_cost_price']);
}
if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
else
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
}
}
}
if ($modifyAccTransaction == 1) {
foreach ($accTransactionDataByDocId as $docId => $transData) {
$docHere = $em->getRepository('ApplicationBundle:' . $docEntity)->findOneBy(array(
$docEntityIdField => $docId,
));;
if ($docHere) {
$curr_v_ids = json_decode($docHere->getVoucherIds(), true);
if ($curr_v_ids == null)
$curr_v_ids = [];
$skipVids = [];
$toChangeVid = 0;
$voucher = null;
foreach ($curr_v_ids as $vid) {
if (in_array($vid, $skipVids))
continue;
$skipVids[] = $vid; //to prevent duplicate query
$voucher = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
'transactionId' => $vid,
));;
if ($voucher) {
if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
$toChangeVid = $vid;
} else {
continue;
}
}
}
if ($toChangeVid == 0) {
$toChangeVid = Accounts::CreateNewTransaction(0,
$em,
$docHere->getStockTransferDate()->format('Y-m-d'),
0,
AccountsConstant::VOUCHER_JOURNAL,
'Journal For Stock Transfer Inventory Ledger Hit for Document- ' . $docHere->getDocumentHash(),
'JV/GN/0/' . Accounts::GetVNoHash($em, 'jv', 'gn', 0),
'JV',
'GN',
0,
Accounts::GetVNoHash($em, 'jv', 'gn', 0),
0,
$docHere->getCreatedLoginId(),
$docHere->getCompanyId(),
'',
0,
1
);
$em->flush();
$voucher = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
'transactionId' => $toChangeVid,
));;
}
DeleteDocument::AccTransactions($em, $toChangeVid, 0);
$tot_inv_amount = 0;
foreach ($transData as $k => $v) {
$tot_inv_amount += (1 * $v);
Accounts::CreateNewTransactionDetails($em,
'',
$toChangeVid,
Generic::CurrToInt($v),
$k,
$v >= 0 ? 'Inventory Inward For - ' . $docHere->getDocumentHash() : 'Inventory Outward For - ' . $docHere->getDocumentHash(),
$v >= 0 ? AccountsConstant::DEBIT : AccountsConstant::CREDIT,
0,
[],
[],
$docHere->getCreatedLoginId()
);
}
// $stockReceivedType = $docHere->getType();
$to_balance_head = 0;
if ($docHere->getTransferActionType() == 4) {
} else {
$inv_transit_head = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'inv_on_transit_head')
);
if ($inv_transit_head)
$to_balance_head = $inv_transit_head->getData();
}
if ($to_balance_head != 0) {
Accounts::CreateNewTransactionDetails($em,
'',
$toChangeVid,
Generic::CurrToInt($tot_inv_amount),
$to_balance_head,
'In Transit Items for -' . $docHere->getDocumentHash(),
$tot_inv_amount >= 0 ? AccountsConstant::CREDIT : AccountsConstant::DEBIT,
0,
[],
[],
$docHere->getCreatedLoginId()
);
}
if ($voucher)
$voucher->setTransactionAmount($tot_inv_amount);
$curr_v_ids = json_decode($docHere->getVoucherIds(), true);
if ($curr_v_ids != null)
$docHere->setVoucherIds(json_encode(array_merge($curr_v_ids, array_diff([$toChangeVid], $curr_v_ids))));
else
$docHere->setVoucherIds(json_encode([$toChangeVid]));
$em->flush();
// System::UpdatePostDatedTransactionById($em, $toChangeVid);
}
}
}
$data = [];
//____________IRR___________________
$docEntity = "ItemReceivedAndReplacement";
$docEntityIdField = "itemReceivedAndReplacementId";
$accTransactionDataByDocId = [];
$query = "SELECT irr_item.*, item_received_replacement.irr_date, item_received_replacement.document_hash from irr_item
join item_received_replacement on item_received_replacement.irr_id=irr_item.irr_id
where item_received_replacement.irr_date ='" . $last_refresh_date . " 00:00:00' and item_received_replacement.approved=1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$queryData = $stmt->fetchAll();
$irr_add_data = [];
$irr_replace_data = [];
$irr_dispose_data = [];
foreach ($queryData as $item) {
$irr_add_data[$item['received_product_id']][] = array(
'date' => $last_refresh_date,
'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
'entityId' => $item['irr_id'],
'colorId' => $item['received_product_color_id'],
'sizeId' => $item['received_product_color_id'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => $item['received_qty'],
'qtySub' => 0,
'valueAdd' => ($item['received_qty'] * $item['received_unit_purchase_price']),
'valueSub' => 0,
'price' => $item['received_unit_purchase_price'],
'fromWarehouse' => 0,
'toWarehouse' => $item['received_warehouse_id'],
'fromWarehouseSub' => 0,
'toWarehouseSub' => $item['received_warehouse_action_id']
);
$irr_replace_data[$item['replaced_product_id']][] = array(
'date' => $last_refresh_date,
'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
'entityId' => $item['irr_id'],
'colorId' => $item['replaced_product_color_id'],
'sizeId' => $item['replaced_product_color_id'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => 0,
'qtySub' => $item['replaced_qty'],
'valueAdd' => 0,
'valueSub' => ($item['replaced_qty'] * $item['replaced_unit_purchase_price']),
'price' => $item['replaced_unit_purchase_price'],
'fromWarehouse' => $item['replaced_warehouse_id'],
'toWarehouse' => 0,
'fromWarehouseSub' => $item['replaced_warehouse_action_id'],
'toWarehouseSub' => 0
);
$irr_dispose_data[$item['received_product_id']][] = array(
'date' => $last_refresh_date,
'entity' => array_flip(GeneralConstant::$Entity_list)['ItemReceivedAndReplacement'],
'entityId' => $item['irr_id'],
'colorId' => $item['received_product_color_id'],
'sizeId' => $item['received_product_size_id'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => 0,
'qtySub' => $item['dispose_qty'],
'valueAdd' => 0,
'valueSub' => ($item['dispose_qty'] * $item['received_unit_purchase_price']),
'price' => $item['received_unit_purchase_price'],
'fromWarehouse' => $item['received_warehouse_id'],
'toWarehouse' => 0,
'fromWarehouseSub' => $item['received_warehouse_id'],
'toWarehouseSub' => 0
);
}
//now add irrs
foreach ($irr_add_data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
$entry['valueAdd'],
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
);
if ($modifiedData)
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
}
}
}
foreach ($irr_replace_data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
$entry['valueAdd'],
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash']);
if ($modifiedData)
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
}
}
}
foreach ($irr_dispose_data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
$entry['valueAdd'],
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
);
if ($modifiedData)
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
}
}
}
$data = [];
//____________DELIVERY_RECEIPT___________________
$docEntity = "DeliveryReceipt";
$docEntityIdField = "deliveryReceiptId";
$accTransactionDataByDocId = [];
$query = "SELECT delivery_receipt_item.*, delivery_receipt.delivery_receipt_date, delivery_receipt.document_hash, delivery_receipt.skip_inventory_hit from delivery_receipt_item
join delivery_receipt on delivery_receipt.delivery_receipt_id=delivery_receipt_item.delivery_receipt_id
where delivery_receipt.delivery_receipt_date ='" . $last_refresh_date . " 00:00:00' and delivery_receipt.approved=1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$queryData = $stmt->fetchAll();
foreach ($queryData as $item) {
$product = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $item['product_id']
)
);
$curr_purchase_price = $product->getPurchasePrice();
if ($item['skip_inventory_hit'] != 1) {
$data[$item['product_id']][] = array(
'date' => $last_refresh_date,
'entity' => array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
'entityId' => $item['delivery_receipt_id'],
'colorId' => $item['color_id'],
'sizeId' => $item['size_id'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => 0,
'qtySub' => ($item['qty'] * $item['unit_multiplier']),
'valueAdd' => 0,
'valueSub' => '_AUTO_',
'price' => $curr_purchase_price,
'fromWarehouse' => $item['warehouse_id'],
'toWarehouse' => 0,
'fromWarehouseSub' => $item['warehouse_action_id'] != null ? $item['warehouse_action_id'] : GeneralConstant::WAREHOUSE_ACTION_GOODS,
'toWarehouseSub' => 0
);
}
$get_kids_sql = "UPDATE `delivery_receipt_item` SET current_purchase_price='" . $curr_purchase_price . "' WHERE id=" . $item['id'] . ";";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
}
foreach ($data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
$entry['valueAdd'],
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CLIENT
);
if ($modifiedData)
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if (!isset($accTransactionDataByDocId[$entry['entityId']]))
$accTransactionDataByDocId[$entry['entityId']] = array();
if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
else
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
}
}
}
if ($modifyAccTransaction == 1) {
//for now we are suuming there is only receipt without confirmation needed
foreach ($accTransactionDataByDocId as $docId => $transData) {
$docHereDr = $em->getRepository('ApplicationBundle:' . $docEntity)->findOneBy(array(
$docEntityIdField => $docId,
));;
$so = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(
array(
'salesOrderId' => $docHereDr->getSalesOrderId()
)
);
$query = $em->getRepository('ApplicationBundle:SalesInvoice')
->createQueryBuilder('p');
$query->where('p.salesOrderId = :soID')
->setParameter('soID', $docHereDr->getSalesOrderId());
$query->andWhere("p.deliveryReceiptIds LIKE '%" . $docId . "%' ");
$query->setMaxResults(1);
$results = $query->getQuery()->getResult();
$docHere = null;
if (!empty($results))
$docHere = $results[0];
if ($docHere) {
$curr_v_ids = json_decode($docHere->getVoucherIds(), true);
if ($curr_v_ids == null)
$curr_v_ids = [];
$skipVids = [];
$toChangeVid = 0;
$voucher = null;
foreach ($curr_v_ids as $vid) {
if (in_array($vid, $skipVids))
continue;
$skipVids[] = $vid; //to prevent duplicate query
$voucher = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
'transactionId' => $vid,
));;
if ($voucher) {
if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
$toChangeVid = $vid;
} else {
continue;
}
if (strpos($voucher->getDescription(), 'Inventory') !== false) {
// echo "Word Found!";
$toChangeVid = $vid;
} else {
continue;
}
}
}
if ($toChangeVid == 0) {
$toChangeVid = Accounts::CreateNewTransaction(0,
$em,
$docHere->getSalesInvoiceDate()->format('Y-m-d'),
0,
AccountsConstant::VOUCHER_JOURNAL,
'Journal For Inventory balance for Sales Invoice ' . $docHere->getDocumentHash(),
'JV/GN/0/' . Accounts::GetVNoHash($em, 'jv', 'gn', 0),
'JV',
'GN',
0,
Accounts::GetVNoHash($em, 'jv', 'gn', 0),
0,
$docHere->getCreatedLoginId(),
$docHere->getCompanyId(),
'',
0,
1,
0, '', $so->getBranchId(),
AccountsConstant::INVOICE_REVENUE_JOURNAL,
array_flip(GeneralConstant::$Entity_list)['SalesInvoice'], $docHere->getSalesInvoiceId(), $docHere->getDocumentHash()
);
$em->flush();
$voucher = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
'transactionId' => $toChangeVid,
));;
}
// DeleteDocument::AccTransactions($em, $toChangeVid, 0);
//now remove cogs or inventory related transactions
$voucherDetails = $em->getRepository('ApplicationBundle:AccTransactionDetails')->findBy(array(
'transactionId' => $toChangeVid,
));;
foreach ($voucherDetails as $vdtls) {
if (in_array($vdtls->getAccountsHeadId(), $inv_head_list)) {
$em->remove($vdtls);
$em->flush();
}
if ($cogs_head == $vdtls->getAccountsHeadId()) {
$em->remove($vdtls);
$em->flush();
}
}
$tot_inv_amount = 0;
foreach ($transData as $k => $v) {
$tot_inv_amount += (1 * $v);
Accounts::CreateNewTransactionDetails($em,
'',
$toChangeVid,
Generic::CurrToInt($v),
$k,
$v >= 0 ? 'Inventory Inward For - ' . $docHere->getDocumentHash() : 'Inventory Outward For - ' . $docHere->getDocumentHash(),
AccountsConstant::DEBIT,
0,
[],
[],
$docHere->getCreatedLoginId()
);
}
// $stockReceivedType = $docHere->getType();
$to_balance_head = 0;
// if ($docHere->getTransferActionType() == 4)
if (1) {
} else {
$inv_transit_head = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'inv_on_transit_head')
);
if ($inv_transit_head)
$to_balance_head = $inv_transit_head->getData();
}
if ($to_balance_head != 0) {
Accounts::CreateNewTransactionDetails($em,
'',
$toChangeVid,
Generic::CurrToInt($tot_inv_amount),
$to_balance_head,
$tot_inv_amount >= 0 ? 'Inventory Outward For - ' . $docHere->getDocumentHash() : 'Inventory in transit For - ' . $docHere->getDocumentHash(),
AccountsConstant::CREDIT,
0,
[],
[],
$docHere->getCreatedLoginId()
);
}
if ($voucher)
$voucher->setTransactionAmount($tot_inv_amount);
$curr_v_ids = json_decode($docHere->getVoucherIds(), true);
if ($curr_v_ids != null)
$docHere->setVoucherIds(json_encode(array_merge($curr_v_ids, array_diff([$toChangeVid], $curr_v_ids))));
else
$docHere->setVoucherIds(json_encode([$toChangeVid]));
$em->flush();
// System::UpdatePostDatedTransactionById($em, $toChangeVid);
}
}
}
$data = [];
//____________STOCK_CONSUMPTION___________________
$docEntity = "StockConsumptionNote";
$docEntityIdField = "stockConsumptionNoteId";
$accTransactionDataByDocId = [];
$query = "SELECT stock_consumption_note_item.*, stock_consumption_note.stock_consumption_note_date, stock_consumption_note.document_hash, stock_consumption_note.data
from stock_consumption_note_item
join stock_consumption_note on stock_consumption_note.stock_consumption_note_id=stock_consumption_note_item.stock_consumption_note_id
where stock_consumption_note.stock_consumption_note_date ='" . $last_refresh_date . " 00:00:00' and stock_consumption_note.approved=1";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$queryData = $stmt->fetchAll();
$consumption_data = [];
$produced_data = [];
$checked_stcm_ids = [];
foreach ($queryData as $item) {
// $product=$em->getRepository('ApplicationBundle:InvProducts')
// ->findOneBy(
// array(
// 'id'=>$item['product_id']
// )
// );
//
// $curr_purchase_price=$product->getPurchasePrice();
if (!in_array($item['stock_consumption_note_id'], $checked_stcm_ids)) {
$conversion_data = json_decode($item['data'], true);
if ($conversion_data == null)
$conversion_data = [];
if (isset($conversion_data['conversionData'])) {
if (isset($conversion_data['conversionData']['converted_products'])) {
$curr_spec_data = $conversion_data['conversionData'];
foreach ($curr_spec_data['converted_products'] as $pika_key => $val) {
$consumption_data[$val][] = array(
'date' => $last_refresh_date,
'type' => 2,
'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
'entityId' => $item['stock_consumption_note_id'],
'colorId' => isset($curr_spec_data['converted_product_colors'][$pika_key]) ? (1 * $curr_spec_data['converted_product_colors'][$pika_key]) : 0,
'sizeId' => isset($curr_spec_data['converted_product_sizes'][$pika_key]) ? (1 * $curr_spec_data['converted_product_sizes'][$pika_key]) : 0,
'entityDocHash' => $item['document_hash'],
'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? (1 * $curr_spec_data['converted_product_units'][$pika_key]) : 0,
'qtySub' => 0,
'valueAdd' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? ($curr_spec_data['converted_product_unit_price'][$pika_key] * $curr_spec_data['converted_product_units'][$pika_key]) : 0,
'valueSub' => 0,
'price' => isset($curr_spec_data['converted_product_units'][$pika_key]) ? (1 * $curr_spec_data['converted_product_unit_price'][$pika_key]) : 0,
'fromWarehouse' => 0,
'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key]) ? (1 * $curr_spec_data['converted_warehouseId'][$pika_key]) : 0,
'fromWarehouseSub' => 0,
'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key]) ? (1 * $curr_spec_data['converted_warehouseActionId'][$pika_key]) : 0
);
}
}
}
// if(isset($conversion_data['expenseCost'] ))
// if(isset($conversion_data['expenseCost']['expense_heads'] ))
// {
// $curr_spec_data=$conversion_data['expenseCost'];
// foreach($curr_spec_data['expense_heads'] as $pika_key=>$val)
// {
//
// $consumption_data[$val][] = array(
// 'date' => $last_refresh_date,
// 'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
// 'entityId' => $item['stock_consumption_note_id'],
// 'entityDocHash' => $item['document_hash'],
// 'qtyAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_units'][$pika_key]):0,
// 'qtySub' => 0,
// 'valueAdd' => isset($curr_spec_data['converted_product_units'][$pika_key])?($curr_spec_data['converted_product_unit_price'][$pika_key]*$curr_spec_data['converted_product_units'][$pika_key]):0,
// 'valueSub' => 0,
// 'price' => isset($curr_spec_data['converted_product_units'][$pika_key])?(1*$curr_spec_data['converted_product_unit_price'][$pika_key]):0,
// 'fromWarehouse' => 0,
// 'toWarehouse' => isset($curr_spec_data['converted_warehouseId'][$pika_key])?(1*$curr_spec_data['converted_warehouseId'][$pika_key]):0,
// 'fromWarehouseSub' => 0,
// 'toWarehouseSub' => isset($curr_spec_data['converted_warehouseActionId'][$pika_key])?(1*$curr_spec_data['converted_warehouseActionId'][$pika_key]):0
// );
// }
// }
$checked_stcm_ids[] = $item['stock_consumption_note_id'];
}
$consumption_data[$item['product_id']][] = array(
'date' => $last_refresh_date,
'type' => 1,
'entity' => array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
'entityId' => $item['stock_consumption_note_id'],
'colorId' => $item['color_id'],
'sizeId' => $item['size_id'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => 0,
'qtySub' => ($item['qty'] * 1),
'valueAdd' => 0,
'valueSub' => (($item['qty']) * ($item['price'])),
'price' => $item['price'],
'fromWarehouse' => $item['warehouse_id'],
'toWarehouse' => 0,
'fromWarehouseSub' => $item['warehouse_action_id'],
'toWarehouseSub' => 0
);
// $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
// $stmt = $em->getConnection()->prepare($get_kids_sql);
// $stmt->execute();
}
foreach ($consumption_data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
$entry['valueAdd'],
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
$entry['type'] == 1 ? GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION : GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION
);
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
}
}
}
$data = [];
//____________PRODUCTION___________________
$docEntity = "Production";
$docEntityIdField = "productionId";
$accTransactionDataByDocId = [];
$consumedAmountByProductionId = [];
$query = "SELECT * from production_process_settings
where approved=1 order by production_process_settings_id asc ";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$processList = $stmt->fetchAll();
// $processList=[];
foreach ($processList as $process) {
$query = "SELECT production_entry_item.*, production.production_date, production.document_hash
from production_entry_item
join production on production_entry_item.production_id=production.production_id
where production_entry_item.process_settings_id =" . $process['production_process_settings_id'] . " and production.production_date ='" . $last_refresh_date . " 00:00:00' and production.approved=1 order by production_id asc ";
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$queryData = $stmt->fetchAll();
$produced_data = [];
$rejected_data = [];
$consumed_data = [];
foreach ($queryData as $item) {
// $product=$em->getRepository('ApplicationBundle:InvProducts')
// ->findOneBy(
// array(
// 'id'=>$item['product_id']
// )
// );
//
// $curr_purchase_price=$product->getPurchasePrice();
if ($item['price'] == '')
$item['price'] = 0;
if ($item['price'] < 0)
$item['price'] = 0;
$item['production_nature_id'];
$consumed_data[$item['product_id']][] = array(
'date' => $last_refresh_date,
'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
'entityId' => $item['production_id'],
'colorId' => $item['color_id'],
'sizeId' => $item['size_id'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => 0,
'qtySub' => ($item['additional_consumed_qty'] * 1) + (1 * $item['consumed_qty']),
'valueAdd' => 0,
'valueSub' => '_AUTO_',
'price' => $item['price'],
'fromWarehouse' => $item['warehouse_id'],
'toWarehouse' => 0,
'fromWarehouseSub' => $item['consumed_item_action_tag_id'],
'toWarehouseSub' => 0,
'production_nature_id' => $item['production_nature_id'],
);
$produced_data[$item['product_id']][] = array(
'date' => $last_refresh_date,
'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
'entityId' => $item['production_id'],
'colorId' => $item['color_id'],
'sizeId' => $item['size_id'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => ($item['accepted_qty'] * 1),
'qtySub' => 0,
'valueAdd' => (($item['accepted_qty'] * 1) * ($item['price'])),
'valueSub' => 0,
'price' => $item['price'],
'fromWarehouse' => 0,
'toWarehouse' => $item['warehouse_id'],
'fromWarehouseSub' => 0,
'toWarehouseSub' => $item['produced_item_action_tag_id'],
'production_nature_id' => $item['production_nature_id'],
);
$rejected_data[$item['product_id']][] = array(
'date' => $last_refresh_date,
'entity' => array_flip(GeneralConstant::$Entity_list)['Production'],
'entityId' => $item['production_id'],
'colorId' => $item['color_id'],
'sizeId' => $item['size_id'],
'entityDocHash' => $item['document_hash'],
'qtyAdd' => ($item['rejected_qty'] * 1),
'qtySub' => 0,
'valueAdd' => (($item['rejected_qty'] * 1) * ($item['price'])),
'valueSub' => 0,
'price' => $item['price'],
'fromWarehouse' => 0,
'toWarehouse' => $item['warehouse_id'],
'fromWarehouseSub' => 0,
'toWarehouseSub' => $item['rejected_item_action_tag_id'],
'production_nature_id' => $item['production_nature_id'],
);
// $get_kids_sql ="UPDATE `delivery_receipt_item` SET current_purchase_price='".$curr_purchase_price."' WHERE id=".$item['id'].";";
// $stmt = $em->getConnection()->prepare($get_kids_sql);
// $stmt->execute();
}
foreach ($consumed_data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
$entry['valueAdd'],
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_CONSUMPTION);
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if (!isset($consumedAmountByProductionId[$entry['entityId']]))
$consumedAmountByProductionId[$entry['entityId']] = (1 * $entry['qtySub'] * $modifiedData['slot_cost_price']);
else
$consumedAmountByProductionId[$entry['entityId']] += (1 * $entry['qtySub'] * $modifiedData['slot_cost_price']);
if (!isset($accTransactionDataByDocId[$entry['entityId']]))
$accTransactionDataByDocId[$entry['entityId']] = array();
if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
else
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
}
}
}
foreach ($produced_data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$productionNature = $entry['production_nature_id'];
if (in_array($productionNature, [1, 2])) {
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
// $entry['valueAdd'],
$consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if (!isset($accTransactionDataByDocId[$entry['entityId']]))
$accTransactionDataByDocId[$entry['entityId']] = array();
if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = 1 * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
else
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += (1 * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
// if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
// $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
// else
// $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
} else {
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
0,
0,
// $entry['valueAdd'],
$consumedAmountByProductionId[$entry['entityId']], //temp need to add calculation for rjected qty later
0,
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if (!isset($accTransactionDataByDocId[$entry['entityId']]))
$accTransactionDataByDocId[$entry['entityId']] = array();
if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = 1 * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
else
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += (1 * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
// if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]]))
// $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] = (-1) * $entry['qtySub'] * $modifiedData['slot_cost_price'];
// else
// $accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['fromWarehouseSub']]] += ((-1) * $entry['qtySub'] * $modifiedData['slot_cost_price']);
}
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
}
}
}
foreach ($rejected_data as $key => $item) {
if (!empty($item)) {
foreach ($item as $entry) {
$transDate = new \DateTime($entry['date']);
$modifiedData = Inventory::addItemToInventoryCompact($em,
$key,
isset($entry['colorId']) ? $entry['colorId'] : 0,
isset($entry['sizeId']) ? $entry['sizeId'] : 0,
$entry['fromWarehouse'],
$entry['toWarehouse'],
$entry['fromWarehouseSub'],
$entry['toWarehouseSub'],
$transDate,
$entry['qtyAdd'],
$entry['qtySub'],
$entry['valueAdd'],
$entry['valueSub'],
$entry['price'],
$this->getLoggedUserCompanyId($request),
0,
$entry['entity'],
$entry['entityId'],
$entry['entityDocHash'],
GeneralConstant::ITEM_TRANSACTION_SPECIAL_TYPE_FROM_TO_PRODUCTION);
System::log_it($this->container->getParameter('kernel.root_dir'), "Date: " . ($transDate->format('Y-m-d')) .
"--- Product # _" . $modifiedData['productId'] . "_ " . $modifiedData['productName'] . "" .
"----- Modified Price: " . $modifiedData['modified_price'] . " " .
"----- Document # _" . $modifiedData['entityName'] . "_ " . $modifiedData['entityDocHash'] . "" .
"",
'inventory_refresh_debug', 1); //last er 1 is append
if (!isset($accTransactionDataByDocId[$entry['entityId']]))
$accTransactionDataByDocId[$entry['entityId']] = array();
if (!isset($accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]]))
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] = (-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price'];
else
$accTransactionDataByDocId[$entry['entityId']][$inv_head_list_by_wa[$entry['toWarehouseSub']]] += ((-1) * $entry['qtyAdd'] * $modifiedData['slot_cost_price']);
if ($last_refresh_date_obj == '') {
$last_refresh_date_obj = $transDate;
} else if ($transDate < $last_refresh_date_obj) {
$last_refresh_date_obj = $transDate;
}
}
}
}
}
if ($modifyAccTransaction == 1) {
foreach ($accTransactionDataByDocId as $docId => $transData) {
$docHere = $em->getRepository('ApplicationBundle:' . $docEntity)->findOneBy(array(
$docEntityIdField => $docId,
));;
if ($docHere) {
$curr_v_ids = json_decode($docHere->getVoucherIds(), true);
if ($curr_v_ids == null)
$curr_v_ids = [];
$skipVids = [];
$toChangeVid = 0;
$voucher = null;
foreach ($curr_v_ids as $vid) {
if (in_array($vid, $skipVids))
continue;
$skipVids[] = $vid; //to prevent duplicate query
$voucher = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
'transactionId' => $vid,
));;
if ($voucher) {
if ($voucher->getDocumentType() == AccountsConstant::VOUCHER_JOURNAL) {
$toChangeVid = $vid;
} else {
continue;
}
}
}
if ($toChangeVid == 0) {
$toChangeVid = Accounts::CreateNewTransaction(0,
$em,
$docHere->getProductionDate()->format('Y-m-d'),
0,
AccountsConstant::VOUCHER_JOURNAL,
'Journal For Stock Transfer Inventory Ledger Hit for Document- ' . $docHere->getDocumentHash(),
'JV/GN/0/' . Accounts::GetVNoHash($em, 'jv', 'gn', 0),
'JV',
'GN',
0,
Accounts::GetVNoHash($em, 'jv', 'gn', 0),
0,
$docHere->getCreatedLoginId(),
$docHere->getCompanyId(),
'',
0,
1
);
$em->flush();
$voucher = $em->getRepository('ApplicationBundle:AccTransactions')->findOneBy(array(
'transactionId' => $toChangeVid,
));;
}
DeleteDocument::AccTransactions($em, $toChangeVid, 0);
$tot_inv_amount = 0;
foreach ($transData as $k => $v) {
$tot_inv_amount += (1 * $v);
Accounts::CreateNewTransactionDetails($em,
'',
$toChangeVid,
Generic::CurrToInt($v),
$k,
$v >= 0 ? 'Inventory Inward For - ' . $docHere->getDocumentHash() : 'Inventory Outward For - ' . $docHere->getDocumentHash(),
AccountsConstant::DEBIT,
0,
[],
[],
$docHere->getCreatedLoginId()
);
}
// $stockReceivedType = $docHere->getType();
$to_balance_head = 0;
// if ($docHere->getTransferActionType() == 4)
if (1) {
} else {
$inv_transit_head = $em->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'inv_on_transit_head')
);
if ($inv_transit_head)
$to_balance_head = $inv_transit_head->getData();
}
if ($to_balance_head != 0) {
Accounts::CreateNewTransactionDetails($em,
'',
$toChangeVid,
Generic::CurrToInt($tot_inv_amount),
$to_balance_head,
$tot_inv_amount >= 0 ? 'Inventory Outward For - ' . $docHere->getDocumentHash() : 'Inventory in transit For - ' . $docHere->getDocumentHash(),
AccountsConstant::CREDIT,
0,
[],
[],
$docHere->getCreatedLoginId()
);
}
if ($voucher)
$voucher->setTransactionAmount($tot_inv_amount);
$curr_v_ids = json_decode($docHere->getVoucherIds(), true);
if ($curr_v_ids != null)
$docHere->setVoucherIds(json_encode(array_merge($curr_v_ids, array_diff([$toChangeVid], $curr_v_ids))));
else
$docHere->setVoucherIds(json_encode([$toChangeVid]));
$em->flush();
// System::UpdatePostDatedTransactionById($em, $toChangeVid);
}
}
}
if ($terminate == 0) {
return new JsonResponse(array(
"success" => true,
"last_refresh_date" => $last_refresh_date,
"inventory_refreshed" => $refreshed_opening
));
} else {
return new JsonResponse(array(
"success" => false,
"last_refresh_date" => $last_refresh_date,
"inventory_refreshed" => $refreshed_opening
));
}
}
return new JsonResponse(array(
"success" => false,
"last_refresh_date" => $last_refresh_date,
"inventory_refreshed" => $refreshed_opening
));
//2 .now make an array with necessary data based on challan and grn for now willl need consumption later
//broken into transactions not closing
//structure---> $data['productId']=array(
//'date'=>'2017-09-02 00:00:00'
//'qtyAdd'=>'2'
//'qtySub'=>'0'
//'valueAdd'=>'2000'
//'valueSub'=>'0'
//'fromWarehouse'=>'0'
//'toWarehouse'=>'0'
//'fromWarehouseSub'=>'0'
//'toWarehouseSub'=>'0'
//)
//
}
public function OpeningItemAction(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')) {
$pp = trim($request->request->get('purchasePrice'));
//replace comma with space
$pp = str_replace(",", "", $pp);
if ($request->request->get('productId') != '') {
foreach ($request->request->get('warehouseId') as $key => $value) {
$data = array(
'productId' => $request->request->get('productId'),
'warehouseId' => $request->request->get('warehouseId')[$key],
'warehouseActionId' => $request->request->get('warehouseActionId')[$key],
'purchasePrice' => $pp,
'date' => new \DateTime($request->request->get('date')),
'qty' => $request->request->get('qty')[$key],
);
$transDate = new \DateTime($request->request->get('date'));
$new = new InvItemInOut();
$new->setProductId($request->request->get('productId'));
$new->setWarehouseId($request->request->get('warehouseId')[$key]);
$new->setTransactionType(AccountsConstant::ITEM_TRANSACTION_DIRECTION_IN);
$new->setActionTagId($request->request->get('warehouseActionId')[$key]);
$new->setTransactionDate($transDate);
$new->setQty($request->request->get('qty')[$key]);
$new->setPrice($pp);
$new->setAmount($request->request->get('qty')[$key] * $pp);
$new->setEntity(0);// opening =0
$new->setEntityId(0);// opening =0
$new->setDebitCreditHeadId(0);// opening =0
$new->setVoucherIds(null);// opening =0
$em->persist($new);
$em->flush();
// $total_inv_value_in_by_id += $request->request->get('qty')[$key] * $pp;
Inventory::AddOpeningInventoryStock($em, $data, $request->getSession()->get(UserConstants::USER_LOGIN_ID));
}
}
}
$inv_head = $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => 'warehouse_action_1'//for now for stock of goods
));
return $this->render('ApplicationBundle:pages/inventory/input_forms:opening_item_assign.html.twig',
array(
'page_title' => "Opening Items",
'inv_head' => $inv_head ? $inv_head->getData() : '',
'products' => $this->getDoctrine()->getRepository('ApplicationBundle:InvProducts')->findBy(array(
'status' => GeneralConstant::ACTIVE//for now for stock of goods
// 'opening_locked'=>0
)),
'warehouseList' => Inventory::WarehouseList($em),
'warehouseActionList' => $warehouse_action_list
)
);
}
public function CreateProductCategoryAction(Request $request)
{
if ($request->isMethod('POST')) {
$cat_data = Inventory::CreateCategory($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request), $request->request->get('cat_name'), $request->request->get('itemgroupId'), $request->getSession()->get(UserConstants::USER_LOGIN_ID));
if ($cat_data['id'] != '')
return new JsonResponse(array("success" => true, 'cat_data' => $cat_data));
}
return new JsonResponse(array("success" => false,));
// return $this->redirectToRoute("create_product");
}
public function CreateProductSubCategoryAction(Request $request)
{
if ($request->isMethod('POST')) {
$spec_data = Inventory::CreateSubCategory($this->getDoctrine()->getManager(),
$this->getLoggedUserCompanyId($request), $request->request->get('spec_name'),
$request->request->get('level', 0),
$request->request->get('parentId', 0),
$request->request->get('itemgroupId'),
$request->request->get('categoryId'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID));
if ($spec_data['id'] != '')
return new JsonResponse(array("success" => true, 'spec_data' => $spec_data));
}
return new JsonResponse(array("success" => false,));
// return $this->redirectToRoute("create_product");
}
public function CreateProductBrandAction(Request $request)
{
if ($request->isMethod('POST')) {
$data = Inventory::CreateBrand($this->getDoctrine()->getManager(),
$this->getLoggedUserCompanyId($request), $request->request->get('brand_name'),
$request->getSession()->get(UserConstants::USER_LOGIN_ID));
if ($data['id'] != '')
return new JsonResponse(array("success" => true, 'data' => $data));
}
return new JsonResponse(array("success" => false,));
// return $this->redirectToRoute("create_product");
}
public function CreateIssueNoteAction(Request $request)
{
return $this->render('ApplicationBundle:pages/inventory/input_forms:issue_note.html.twig',
array(
'page_title' => 'Issue Note'
)
);
}
public function ProcessDraftDeliveryReceiptAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$extId = $id;
$receiptId = $id;
$allowed = 0;
if ($request->isMethod('POST')) {
$receiptId = $request->request->get('deliveryReceiptId');
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceipt')
->findOneBy(
array(
'deliveryReceiptId' => $receiptId
),
array()
);
$soId = $QD->getSalesOrderId();
$drData = [];
$dr_item_data = $em->getRepository('ApplicationBundle:DeliveryReceiptItem')->findBy(
array(
'deliveryReceiptId' => $receiptId,
)
);
foreach ($dr_item_data as $dr_item) {
$drData[] = array(
'soItemId' => $dr_item->getSalesorderItemId(),
'qty' => $dr_item->getQty()
);
}
// $drData=[
// ['soItemId'=>9,'qty'=>9],
// ['soItemId'=>9,'qty'=>9],
// ['soItemId'=>9,'qty'=>9],
// ];
$toGetSoItemsId = [];
$toGetDoItemsId = [];
$drDataBySoItemId = [];
$drDataByDoItemId = [];
$so = $em->getRepository('ApplicationBundle:SalesOrder')->findOneBy(array(
'salesOrderId' => $soId //$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' => $soId,
'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();
$due = 1 * $client->getClientDue();
if ($creditLimit >= ($due + $total_sales_amount))
$allowed = 1;
}
//now package data
if ($allowed == 0) {
return new JsonResponse(array(
'success' => false,
// 'documentHash' => $order->getDocumentHash(),
'documentId' => $receiptId,
'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
'viewUrl' => '',
));
}
$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');
$receiptId = $request->request->get('deliveryReceiptId');
$sig = DocValidation::isSignatureOk($em, $loginId, $approveHash);
// $this->addFlash(
// 'success',
// 'New Transaction Added.'
// );
$success = $sig == 0 ? false : true;
if ($success == true) {
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceipt')
->findOneBy(
array(
'deliveryReceiptId' => $receiptId
),
array()
);
$draftFlag = $QD->getDraftFlag();
if ($draftFlag == 1) {
//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)
);
$QD->setDraftFlag(0);
$em->flush();
}
$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',
'Action Successful'
);
return $this->redirect($url . "/" . $receiptId);
}
}
}
return new JsonResponse(array(
'success' => false,
// 'documentHash' => $order->getDocumentHash(),
'documentId' => $receiptId,
'documentIdPadded' => str_pad($receiptId, 8, '0', STR_PAD_LEFT),
'viewUrl' => '',
));
}
public function CreateDeliveryReceiptAction(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('ApplicationBundle:pages/inventory/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 CreateServiceChallanAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$entity_id = array_flip(GeneralConstant::$Entity_list)['ServiceChallan']; //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)
) {
$this->addFlash(
'error',
'Sorry Could not insert Data.'
);
} else {
$receiptId = SalesOrderM::CreateNewServiceChallan($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)['ServiceChallan']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
$receiptId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID)
);
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['ServiceChallan'],
$receiptId,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$this->addFlash(
'success',
'New Service Challan Created'
);
$url = $this->generateUrl(
'view_service_challan'
);
return $this->redirect($url . "/" . $receiptId);
}
}
return $this->render('ApplicationBundle:pages/inventory/input_forms:create_service_challan.html.twig',
array(
'page_title' => 'New Service Challan',
'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()),
'serviceList' => Inventory::ServiceList($em, $this->getLoggedUserCompanyId($request))
)
);
}
public function GetItemListForDrAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$drId = $request->request->has('drId') ? $request->request->get('drId') : 0;
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($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('doId') != '')
$find_array['deliveryOrderId'] = $request->request->get('doId');
// if($request->request->get('warehouseId')!='')
// $find_array['warehouseId']=$request->request->get('warehouseId');
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryOrderItem')
->findBy(
$find_array,
array()
);
// if($request->request->get('wareHouseId')!='')
$DO = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryOrder')
->findOneBy(
$find_array,
array()
);
$sendData = array(
// 'salesType'=>$SO->getSalesType(),
// 'packageData'=>[],
'productList' => [],
// 'productListByPackage'=>[],
);
$productList = Inventory::ProductList($this->getDoctrine()->getManager());
$pckg_item_cross_match_data = [];
$unitList = Inventory::UnitTypeList($em);
$colorList = Inventory::GetColorList($em);
foreach ($QD as $product) {
// if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
if ((1 * $product->getBalance()) <= 0)
continue;
$fdm = $product->getProductFdm();
$productData = Inventory::GetProductDataFromFdm($em, $fdm, $DO->getCompanyId(), 0);
$find_query = array();
$soItem = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrderItem')
->findOneBy(
array(
'id' => $product->getSalesorderItemId()
)
);
if (!$soItem)
continue;
// $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
// $soBalance = $soItem->getBalance();
$soBalance = $soItem->getQty();
// $doBalance=$product->getBalance() - $product->getTransitQty();
// $doBalance = $product->getBalance();
$doBalance = $product->getQty();
//now check if any so ir do item id there that is at
//least pending
$approvalPendingDrs = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceipt')
->findBy(
array(
'deliveryOrderId' => $DO->getDeliveryOrderId(),
'approved' => [2, GeneralConstant::APPROVAL_STATUS_PENDING, GeneralConstant::APPROVED]
)
);
foreach ($approvalPendingDrs as $appPendDr) {
$appPendDrItem = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceiptItem')
->findOneBy(
array(
'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
'salesorderItemId' => $product->getSalesorderItemId()
)
);
if ($appPendDrItem) {
if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
$soBalance = $soBalance - $appPendDrItem->getQty();
$doBalance = $doBalance - $appPendDrItem->getQty();
}
}
}
$colorId = $product->getColorId();
$size = $product->getSizeId();
// $find_query['colorId']=
if ($productData['productId'] != 0) {
$find_query['productId'] = $productData['productId'];
if ($colorId == '' || $colorId == 0 || $colorId == null)
$colorId = $productData['defaultColorId'];
if ($size == '' || $size == 0 || $size == null)
$size = $productData['defaultSize'];
$find_query['productId'] = $productData['productId'];
} else {
if ($productData['igId'] != 0) {
$find_query['igId'] = $productData['igId'];
}
if ($productData['categoryId'] != 0) {
$find_query['categoryId'] = $productData['categoryId'];
}
if ($productData['subCategoryId'] != 0) {
$find_query['subCategoryId'] = $productData['subCategoryId'];
}
if ($productData['brandId'] != 0) {
$find_query['brandId'] = $productData['brandId'];
}
}
$find_query['warehouseId'] = $request->request->get('warehouseId');
$find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
if ($colorId == '' || $colorId == 0 || $colorId == null) {
// $find_query['color'] = $colorId;
} else
$find_query['color'] = $colorId;
if ($size == '' || $size == 0 || $size == null) {
// $find_query['size'] = $size;
} else
$find_query['size'] = 0;
$inventory_by_warehouse_list = $this->getDoctrine()
->getRepository('ApplicationBundle:InventoryStorage')
->findBy(
$find_query,
array()
);
$new_pid = $productData['productId'];
$p_data = array(
'details_id' => $product->getId(),
// 'productId'=>$new_pid,
'productIdList' => [],
'multList' => [],
'drItemIds' => [],
'drItemQty' => [],
'drItemCodeIds' => [],
'drItemCartonIds' => [],
'colorIds' => [],
'colorNames' => [],
'sizeIds' => [],
'productNameList' => [],
'availableInventoryList' => [],
'warehouseActionId' => [],
'warehouseActionName' => [],
'availableBarcodes' => [],
'availableBarcodesStr' => [],
// 'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
// 'available_inventory'=>0,
// 'package_id'=>$product->getPackageId(),
'qty' => $product->getQty(),
'delivered' => $product->getDelivered(),
// 'deliverable' => $product->getDeliverable() - $product->getTransitQty(),
'deliverable' => min($soBalance, $doBalance),
// 'balance' => $product->getBalance(),
'balance' => min($soBalance, $doBalance),
'productNameFdm' => $product->getProductNameFdm(),
'productFdm' => $product->getProductFdm(),
// 'delivered'=>$product->getDelivered(),
);
foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
if ($inventory_by_warehouse->getQty() <= 0)
continue;
$unitType = $product->getUnitTypeId();
$mult_unit = 1;
if ($drId != 0) {
$drItem = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceiptItem')
->findOneBy(
array(
'deliveryReceiptId' => $drId,
'productId' => $inventory_by_warehouse->getProductId(),
'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
'colorId' => $inventory_by_warehouse->getColor() == 0 ? [0, null, ''] : $inventory_by_warehouse->getColor(),
'sizeId' => $inventory_by_warehouse->getSize() == 0 ? [0, null, ''] : $inventory_by_warehouse->getSize(),
)
);
if ($drItem) {
$p_data['drItemIds'][] = $drItem->getId();
$p_data['drItemQty'][] = $drItem->getQty();
$codes = json_decode($drItem->getProductByCodeIds(), true);
if ($codes == null)
$codes = [];
$p_data['drItemCodeIds'][] = $codes;
$codes = json_decode($drItem->getCartonIds(), true);
if ($codes == null)
$codes = [];
$p_data['drItemCartonIds'][] = $codes;
} else {
$p_data['drItemIds'][] = 0;
$p_data['drItemQty'][] = 0;
$p_data['drItemCodeIds'][] = 0;
$p_data['drItemCartonIds'][] = 0;
}
} else {
$p_data['drItemIds'][] = 0;
$p_data['drItemQty'][] = 0;
$p_data['drItemCodeIds'][] = 0;
$p_data['drItemCartonIds'][] = 0;
}
if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
$mult_unit = 1 * $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
}
};
if ($mult_unit == 0)
$mult_unit = 1;
$inv_product_id = $inventory_by_warehouse->getProductId();
$p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
$p_data['multList'][] = $mult_unit;
$p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
$p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
$p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
$p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
$p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
// $p_data['availableInventoryList'][]=$inventory_by_warehouse?(($inventory_by_warehouse->getQty())*$mult_unit):0;
$p_data['colorIds'][] = $inventory_by_warehouse ? $inventory_by_warehouse->getColor() : 0;
$p_data['sizeIds'][] = $inventory_by_warehouse ? $inventory_by_warehouse->getSize() : 0;
$p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
}
$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 GetItemListForDrBySoAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), '');;
if ($request->isMethod('POST')) {
$em = $this->getDoctrine();
$find_array = array(// 'stage' => GeneralConstant::STAGE_PENDING_TAG
// 'type'=>1//product only
);
$find_item_array = array(// 'stage' => GeneralConstant::STAGE_PENDING_TAG
'type' => 1//product only
);
$Content = [];
$Transport_data = [];
$Lul_data = [];
$drId = $request->request->has('drId') ? $request->request->get('drId') : 0;
if ($request->request->get('soId') != '') {
$find_array['salesOrderId'] = $request->request->get('soId');
$find_item_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_item_array,
array()
);
// if($request->request->get('wareHouseId')!='')
$DO = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrder')
->findOneBy(
$find_array,
array()
);
$sendData = array(
// 'salesType'=>$SO->getSalesType(),
// 'packageData'=>[],
'productList' => [],
// 'productListByPackage'=>[],
);
$productList = Inventory::ProductList($this->getDoctrine()->getManager());
$pckg_item_cross_match_data = [];
$unitList = Inventory::UnitTypeList($em);
$colorList = Inventory::GetColorList($em);
foreach ($QD as $product) {
if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
continue;
// $soBalance=$soItem->getBalance() - $soItem->getTransitQty();
// $soBalance = $soItem->getBalance();
$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
$approvalPendingDrs = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceipt')
->findBy(
array(
'salesOrderId' => $DO->getSalesOrderId(),
'approved' => [2, GeneralConstant::APPROVAL_STATUS_PENDING, GeneralConstant::APPROVED]
)
);
foreach ($approvalPendingDrs as $appPendDr) {
$appPendDrItem = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceiptItem')
->findOneBy(
array(
'deliveryReceiptId' => $appPendDr->getDeliveryReceiptId(),
// 'salesorderItemId' => $product->getId(),
'salesorderItemId' => $product->getId()
)
);
if ($appPendDrItem) {
if ($drId != $appPendDrItem->getDeliveryReceiptId()) {
$soBalance = $soBalance - $appPendDrItem->getQty();
}
// $doBalance=$doBalance-$appPendDrItem->getQty();
}
}
$fdm = $product->getProductFdm();
$productData = Inventory::GetProductDataFromFdm($em, $fdm, $DO->getCompanyId(), 0);
$find_query = array();
$colorId = $product->getColorId();
$size = $product->getSizeId();
// $find_query['colorId']=
if ($productData['productId'] != 0) {
$find_query['productId'] = $productData['productId'];
if ($colorId == '' || $colorId == 0 || $colorId == null)
$colorId = $productData['defaultColorId'];
if ($size == '' || $size == 0 || $size == null)
$size = $productData['defaultSize'];
} else {
if ($productData['igId'] != 0) {
$find_query['igId'] = $productData['igId'];
}
if ($productData['categoryId'] != 0) {
$find_query['categoryId'] = $productData['categoryId'];
}
if ($productData['subCategoryId'] != 0) {
$find_query['subCategoryId'] = $productData['subCategoryId'];
}
if ($productData['brandId'] != 0) {
$find_query['brandId'] = $productData['brandId'];
}
}
$find_query['warehouseId'] = $request->request->get('warehouseId');
$find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
if ($colorId == '' || $colorId == 0 || $colorId == null) {
// $find_query['color'] = $colorId;
} else
$find_query['color'] = $colorId;
if ($size == '' || $size == 0 || $size == null) {
// $find_query['size'] = $size;
} else
$find_query['size'] = 0;
$inventory_by_warehouse_list = $this->getDoctrine()
->getRepository('ApplicationBundle:InventoryStorage')
->findBy(
$find_query,
array()
);
$new_pid = $productData['productId'];
$unitType = $product->getUnitTypeId();
$p_data = array(
'details_id' => $product->getId(),
'unitType' => $unitType,
'productIdList' => [],
'multList' => [],
'drItemIds' => [],
'drItemQty' => [],
'drItemCodeIds' => [],
'drItemCartonIds' => [],
'colorIds' => [],
'colorNames' => [],
'sizeIds' => [],
'productNameList' => [],
'availableInventoryList' => [],
'warehouseActionId' => [],
'warehouseActionName' => [],
'availableBarcodes' => [],
'availableBarcodesStr' => [],
// 'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
// 'available_inventory'=>0,
// 'package_id'=>$product->getPackageId(),
'qty' => $product->getQty(),
'delivered' => $product->getDelivered(),
// 'deliverable' => $product->getBalance() - $product->getTransitQty(),
// 'balance' => $product->getBalance() - $product->getTransitQty(),
'deliverable' => $soBalance,
// 'deliverable' => $product->getBalance(),
'balance' => $soBalance,
// 'balance' => $product->getBalance(),
'productNameFdm' => $product->getProductNameFdm(),
'productFdm' => $product->getProductFdm(),
// 'delivered'=>$product->getDelivered(),
);
foreach ($inventory_by_warehouse_list as $inventory_by_warehouse) {
if ($inventory_by_warehouse->getQty() <= 0)
continue;
$mult_unit = 1;
if ($drId != 0) {
$drItem = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceiptItem')
->findOneBy(
array(
'deliveryReceiptId' => $drId,
'productId' => $inventory_by_warehouse->getProductId(),
'warehouseActionId' => $inventory_by_warehouse->getActionTagId(),
'colorId' => $inventory_by_warehouse->getColor() == 0 ? [0, null, ''] : $inventory_by_warehouse->getColor(),
'sizeId' => $inventory_by_warehouse->getSize() == 0 ? [0, null, ''] : $inventory_by_warehouse->getSize(),
)
);
if ($drItem) {
$p_data['drItemIds'][] = $drItem->getId();
$p_data['drItemQty'][] = $drItem->getQty();
$codes = json_decode($drItem->getProductByCodeIds(), true);
if ($codes == null)
$codes = [];
$p_data['drItemCodeIds'][] = $codes;
$codes = json_decode($drItem->getCartonIds(), true);
if ($codes == null)
$codes = [];
$p_data['drItemCartonIds'][] = $codes;
} else {
$p_data['drItemIds'][] = 0;
$p_data['drItemQty'][] = 0;
$p_data['drItemCodeIds'][] = 0;
$p_data['drItemCartonIds'][] = 0;
}
} else {
$p_data['drItemIds'][] = 0;
$p_data['drItemQty'][] = 0;
$p_data['drItemCodeIds'][] = 0;
$p_data['drItemCartonIds'][] = 0;
}
if ($unitType != $inventory_by_warehouse->getUnitTypeId()) {
if (isset($unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType])) {
$mult_unit = 1 * $unitList[$inventory_by_warehouse->getUnitTypeId()]['conversion'][$unitType];
}
};
if ($mult_unit == 0)
$mult_unit = 1;
$inv_product_id = $inventory_by_warehouse->getProductId();
$p_data['productIdList'][] = $inventory_by_warehouse->getProductId();
$p_data['multList'][] = $mult_unit;
$p_data['warehouseActionId'][] = $inventory_by_warehouse->getActionTagId();
$p_data['warehouseActionName'][] = $warehouse_action_list[$inventory_by_warehouse->getActionTagId()];
$p_data['productNameList'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['name'] : '';
$p_data['serialEnabled'][] = isset($productList[$inv_product_id]) ? $productList[$inv_product_id]['has_serial'] : 0;
$p_data['availableInventoryList'][] = $inventory_by_warehouse ? (($inventory_by_warehouse->getQty()) / $mult_unit) : 0;
$p_data['colorIds'][] = $inventory_by_warehouse ? $inventory_by_warehouse->getColor() : 0;
$p_data['sizeIds'][] = $inventory_by_warehouse ? $inventory_by_warehouse->getSize() : 0;
$p_data['colorNames'][] = isset($colorList[$inventory_by_warehouse->getColor()]) ? $colorList[$inventory_by_warehouse->getColor()]['name'] : '';
}
$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 GetItemListForStockReqBySoAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$em = $this->getDoctrine();
$find_array = array(// 'stage' => GeneralConstant::STAGE_PENDING_TAG
);
$Content = [];
$Transport_data = [];
$Lul_data = [];
$find_array['serviceId'] = [0, null];
$sendData = array(
// 'salesType'=>$SO->getSalesType(),
// 'packageData'=>[],
'productList' => [],
// 'productListByPackage'=>[],
);
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()
);
// if($request->request->get('wareHouseId')!='')
// $DO = $this->getDoctrine()
// ->getRepository('ApplicationBundle:SalesOrder')
// ->findOneBy(
// $find_array,
// array()
// );
$productList = Inventory::ProductList($this->getDoctrine()->getManager());
$pckg_item_cross_match_data = [];
$unitList = Inventory::UnitTypeList($em);
foreach ($QD as $product) {
// if ((1 * $product->getBalance() - $product->getTransitQty()) <= 0)
// continue;
$fdm = $product->getProductFdm();
$unitType = $product->getUnitTypeId();
$p_data = array(
'details_id' => $product->getId(),
'unitType' => $unitType,
'productIdList' => [],
'multList' => [],
'productNameList' => [],
'availableInventoryList' => [],
'warehouseActionId' => [],
'warehouseActionName' => [],
'availableBarcodes' => [],
'availableBarcodesStr' => [],
// 'product_name'=>isset($productList[$new_pid])?$productList[$new_pid]['name']:'',
// 'available_inventory'=>0,
// 'package_id'=>$product->getPackageId(),
'qty' => $product->getQty(),
'delivered' => $product->getDelivered(),
// 'deliverable' => $product->getBalance() - $product->getTransitQty(),
// 'balance' => $product->getBalance() - $product->getTransitQty(),
'deliverable' => $product->getBalance(),
'balance' => $product->getBalance(),
'productNameFdm' => $product->getProductNameFdm(),
'productFdm' => $product->getProductFdm(),
// '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 GetBarcodesListForStAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$sendData = [];
$warehouse_action_list = Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), '');;
if ($request->isMethod('POST')) {
$em = $this->getDoctrine();
$find_query = array();
$find_query['warehouseId'] = $request->request->get('warehouseId');
$find_query['actionTagId'] = $request->request->get('warehouseActionId');
$find_query['productId'] = $request->request->get('productId');
$find_query['CompanyId'] = $this->getLoggedUserCompanyId($request);
$inventory_by_warehouse_list = $this->getDoctrine()
->getRepository('ApplicationBundle:InventoryStorage')
->findBy(
$find_query,
array()
);
$new_pid = $request->request->get('productId');
$p_data = array();
//now get bacodes if available
// $query = "SELECT product_by_code_id, GROUP_CONCAT(DISTINCT sales_code SEPARATOR ',') sales_code_list_str
//FROM product_by_code
//where company_id=" . $this->getLoggedUserCompanyId($request).
// " and product_id=".$inv_product_id.
// " and warehouse_id=".$inventory_by_warehouse->getWarehouseId().
// " and warehouse_action_id=".$inventory_by_warehouse->getActionTagId();
// " GROUP BY product_by_code_id" ;
$query = "SELECT product_by_code_id, sales_code
FROM product_by_code
where company_id=" . $this->getLoggedUserCompanyId($request) .
" and product_id=" . $request->request->get('productId') .
" and warehouse_id=" . $request->request->get('warehouseId') .
" and warehouse_action_id=" . $request->request->get('warehouseActionId');
$stmt = $em->getConnection()->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll();
$sales_code_list_str = '';
foreach ($results as $pika => $result) {
if ($pika != 0)
$sales_code_list_str .= ',';
$sales_code_list_str .= str_pad($result['sales_code'], 13, '0', STR_PAD_LEFT);
}
if ($results) {
$p_data['availableBarcodes'] = $sales_code_list_str != '' || $sales_code_list_str != null
? explode(',', $sales_code_list_str) : [];
$p_data['availableBarcodesStr'] = $sales_code_list_str != '' || $sales_code_list_str != null
? $sales_code_list_str : "";
//
} else {
$p_data['availableBarcodes'] = [];
$p_data['availableBarcodesStr'] = "";
//
}
$sendData = $p_data;
}
//now package data
if (!empty($sendData['availableBarcodes'])) {
return new JsonResponse(array("success" => true, "content" => $sendData));
}
return new JsonResponse(array("success" => false));
}
public function GetItemListForSalesReturnAction(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('drId') != '')
$find_array['deliveryReceiptId'] = $request->request->get('drId');
// if($request->request->get('warehouseId')!='')
// $find_array['warehouseId']=$request->request->get('warehouseId');
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceiptItem')
->findBy(
$find_array,
array()
);
// if($request->request->get('wareHouseId')!='')
$DR = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceipt')
->findOneBy(
$find_array,
array()
);
$sendData = array(
'productList' => [],
);
$productList = Inventory::ProductList($this->getDoctrine()->getManager());
$pckg_item_cross_match_data = [];
$unitList = Inventory::UnitTypeList($em);
foreach ($QD as $product) {
if ((1 * $product->getQty()) <= 0)
continue;
$new_pid = $product->getProductId();
$sales_code_range = [];
if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
$sales_code_range = json_decode($product->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
} else {
$max_int_length = strlen((string)PHP_INT_MAX) - 1;
$json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $product->getSalesCodeRange());
$sales_code_range = json_decode($json_without_bigints, true);
}
$p_data = array(
'details_id' => $product->getId(),
'dr_id' => $product->getDeliveryReceiptId(),
'productId' => $new_pid,
'product_name' => isset($productList[$new_pid]) ? $productList[$new_pid]['name'] : '',
'qty' => $product->getQty(),
'delivered' => $product->getDelivered(),
'unitTypeId' => $product->getUnitTypeId(),
'deliverable' => $product->getDeliverable(),
'balance' => $product->getBalance(),
'salesCodeRangeStr' => $product->getSalesCodeRange(),
'salesCodeRange' => $sales_code_range,
'sales_codes' => $sales_code_range,
'sales_price' => $product->getPrice(),
'purchase_price' => $product->getCurrentPurchasePrice()
// '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 GetItemListForIrrAction(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('srId') != '')
$find_array['salesReturnId'] = $request->request->get('srId');
// if($request->request->get('warehouseId')!='')
// $find_array['warehouseId']=$request->request->get('warehouseId');
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesReturnItem')
->findBy(
$find_array,
array()
);
// if($request->request->get('wareHouseId')!='')
$sendData = array(
'productList' => [],
);
$productList = Inventory::ProductList($this->getDoctrine()->getManager());
$pckg_item_cross_match_data = [];
$unitList = Inventory::UnitTypeList($em);
foreach ($QD as $product) {
if ((1 * $product->getReceivedBalance()) <= 0 && (1 * $product->getReplacedBalance()) <= 0)
continue;
$DR_ITEM = null;
$DR_TAGGED_CODES = [];
$DR_TAGGED_CODES_FOR_SELECTIZE = [];
$RESTRICT_RECEIVED_CODES_FLAG = 0;
$sales_code_range = [];
if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
$sales_code_range = json_decode($product->getReceivedCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
} else {
$max_int_length = strlen((string)PHP_INT_MAX) - 1;
$json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $product->getReceivedCodeRange());
$sales_code_range = json_decode($json_without_bigints, true);
}
$DR_TAGGED_CODES = $sales_code_range;
if (!empty($DR_TAGGED_CODES)) {
$RESTRICT_RECEIVED_CODES_FLAG = 1;
foreach ($DR_TAGGED_CODES as $DTC) {
$DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
'value' => $DTC
);
}
}
// if ($product->getTaggedDetailsId() != 0 && $product->getTaggedDetailsId() != null) {
//
// $DR_ITEM = $this->getDoctrine()
// ->getRepository('ApplicationBundle:DeliveryReceiptItem')
// ->findOneBy(
// array(
// 'id' => $product->getTaggedDetailsId()
// ),
// array()
// );
// if ($DR_ITEM) {
// if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
//
// $DR_TAGGED_CODES = json_decode($DR_ITEM->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
// } else {
//
// $max_int_length = strlen((string)PHP_INT_MAX) - 1;
// $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $DR_ITEM->getSalesCodeRange());
// $DR_TAGGED_CODES = json_decode($json_without_bigints, true);
// }
//
// if ($DR_TAGGED_CODES == null)
// $DR_TAGGED_CODES = [];
// if (!empty($DR_TAGGED_CODES)) {
// $RESTRICT_RECEIVED_CODES_FLAG = 1;
// foreach ($DR_TAGGED_CODES as $DTC) {
// $DR_TAGGED_CODES_FOR_SELECTIZE[] = array(
// 'value' => $DTC
// );
// }
// }
// }
// }
$p_data = array(
'details_id' => $product->getId(),
'receivedDrTaggedCodes' => $DR_TAGGED_CODES,
'receivedDrTaggedCodesStr' => implode(',', $DR_TAGGED_CODES),
'receivedDrTaggedCodesForSel' => $DR_TAGGED_CODES_FOR_SELECTIZE,
'receivedRestrictCodesFlag' => $RESTRICT_RECEIVED_CODES_FLAG,
'receivedProductId' => $product->getReceivedProductId(),
'receivedBalance' => $product->getReceivedBalance(),
'receivedUnitSalesPrice' => $product->getReceivedUnitSalesPrice(),
'receivedUnitPurchasePrice' => $product->getReceivedUnitPurchasePrice(),
'receivedProductName' => isset($productList[$product->getReceivedProductId()]) ? $productList[$product->getReceivedProductId()]['name'] : '',
'replacedProductId' => $product->getReplacedProductId(),
'replacedBalance' => $product->getReplacedBalance(),
'replacedUnitSalesPrice' => $product->getReplacedUnitSalesPrice(),
'replacedUnitPurchasePrice' => $product->getReplacedUnitPurchasePrice(),
'replacedProductName' => isset($productList[$product->getReplacedProductId()]) ? $productList[$product->getReplacedProductId()]['name'] : '',
'disposeBalance' => $product->getDisposeBalance(),
'unusedBalance' => $product->getUnusedBalance(),
'disposeTag' => $product->getDisposeTag(),
'unitTypeId' => $product->getUnitTypeId(),
// '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 LabelFormatAction(Request $request, $id = 0)
{
$data = array(
'formatId' => '',
'formatCode' => '',
'name' => '',
'labelType' => 0,
'width' => 60,
'pageWidth' => 6,
'height' => 39,
'pageHeight' => 2,
'formatData' => '',
);
if ($request->isMethod('POST')) {
$post = $request->request;
$exists_already = 0;
if ($request->request->get('formatId') != '') {
$query_here = $this->getDoctrine()
->getRepository('ApplicationBundle:LabelFormat')
->findOneBy(
array(
'formatId' => $request->request->get('formatId')
)
);
if (!empty($query_here)) {
$exists_already = 1;
$new = $query_here;
} else
$new = new LabelFormat();
} else
$new = new LabelFormat();
$new->setName($request->request->get('name'));
$new->setLabelType($request->request->get('labelType'));
$new->setWidth($request->request->get('width'));
$new->setHeight($request->request->get('height'));
$new->setFormatCode($request->request->get('formatCode'));
$new->setActive(GeneralConstant::ACTIVE);
$new->setPageHeight($request->request->get('pageHeight'));
$new->setPageWidth($request->request->get('pageWidth'));
$new->setFormatData($request->request->get('formatData'));
if ($exists_already == 0)
$new->setCreatedLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$new->setEditLoginId($request->getSession()->get(UserConstants::USER_LOGIN_ID));
$new->setCompanyId($request->getSession()->get(UserConstants::USER_COMPANY_ID));
$em = $this->getDoctrine()->getManager();
$em->persist($new);
$em->flush();
}
if ($id != 0) {
$query_here = $this->getDoctrine()
->getRepository('ApplicationBundle:LabelFormat')
->findOneBy(
array(
'formatId' => $id
)
);
if ($query_here)
$data = $query_here;
} else if ($request->query->has('formatId')) {
$query_here = $this->getDoctrine()
->getRepository('ApplicationBundle:LabelFormat')
->findOneBy(
array(
'formatId' => $request->query->get('formatId')
)
);
if ($query_here)
$data = $query_here;
}
return $this->render(
'ApplicationBundle:pages/inventory/input_forms:label_format.html.twig',
array(
'page_title' => 'Label Format',
'data' => $data,
'labelTypeList' => LabelConstant::$label_type_list,
'labelFieldsList' => LabelConstant::$label_fields_list,
'formatList' => $this->getDoctrine()
->getRepository('ApplicationBundle:LabelFormat')
->findBy(
array( // 'formatId' => $request->query->get('formatId')
)
)
// 'incomeLedgerHeads'=>Accounts::getChildLedgerHeads($this->getDoctrine()->getManager(),AccountsConstant::INCOME)
)
);
}
public function GetServiceListForScAction(Request $request)
{
if ($request->isMethod('POST')) {
$em = $this->getDoctrine();
$find_array = array(
'type' => 2//service
);
$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()
);
// if($request->request->get('wareHouseId')!='')
$SO = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrder')
->findOneBy(
array(
'salesOrderId' => $request->request->get('soId')
),
array()
);
$sendData = array(
// 'salesType'=>$SO->getSalesType(),
// 'packageData'=>[],
'productList' => [],
// 'productListByPackage'=>[],
);
$serviceList = Inventory::ServiceList($this->getDoctrine()->getManager(), $SO->getCompanyId());
$pckg_item_cross_match_data = [];
foreach ($QD as $product) {
$p_data = array(
'details_id' => $product->getId(),
'service_id' => $product->getServiceId(),
'service_name' => $serviceList[$product->getServiceId()]['name'],
'available_inventory' => $product->getBalance(),
// 'package_id'=>$product->getPackageId(),
'qty' => $product->getQty(),
'delivered' => $product->getDelivered(),
// 'deliverable'=>$product->getDeliverable(),
'balance' => $product->getBalance(),
// 'delivered'=>$product->getDelivered(),
);
$sendData['serviceList'][] = $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 CreateReceivedNoteAction(Request $request)
{
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['Grn']; //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)
) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$data = $request->request;
$grnId = Inventory::CreateGrn($this->getDoctrine()->getManager(), $data, $request->getSession()->get(UserConstants::USER_LOGIN_ID));
//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)['Grn']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['Grn'],
$grnId,
$request->getSession()->get(UserConstants::USER_LOGIN_ID));
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['Grn'], $grnId,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$this->addFlash(
'success',
'New GRN Added.'
);
$url = $this->generateUrl(
'view_grn'
);
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),
"Good Received Note : " . $dochash . " Has Been Created And is Under Processing",
'pos',
System::getPositionIdsByDepartment($em, [GeneralConstant::SALES_DEPARTMENT, GeneralConstant::PURCHASE_DEPARTMENT, GeneralConstant::ACCOUNTS_DEPARTMENT, GeneralConstant::INVENTORY_DEPARTMENT]),
'success',
$url . "/" . $grnId,
"GRN"
);
return $this->redirect($url . "/" . $grnId);
}
}
return $this->render('ApplicationBundle:pages/inventory/input_forms:received_note.html.twig',
array(
'page_title' => 'GRN',
'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
'material_inward' => $this->getDoctrine()
->getRepository('ApplicationBundle:MaterialInward')
->findBy(
array(
'stage' => GeneralConstant::STAGE_PENDING_TAG
)
)
// 'po'=>Inventory::getPurchaseOrderList
)
);
}
public function GetQcListForGrnAction(Request $request)
{
if ($request->isMethod('POST')) {
$find_array = array(
'stage' => GeneralConstant::STAGE_PENDING_TAG
);
$Content = [];
$ContentByProductId = [];
$Transport_data = [];
$Lul_data = [];
$unitList = Inventory::UnitTypeList($this->getDoctrine()->getManager());
if ($request->request->get('poId') != '')
$find_array['purchaseOrderId'] = $request->request->get('poId');
if ($request->request->get('warehouseId') != '')
$find_array['warehouseId'] = $request->request->get('warehouseId');
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:MaterialInward')
->findBy(
$find_array,
array(
'inwardDate' => 'ASC',
'qcDate' => 'ASC'
)
);
$warehouse = Inventory::WarehouseList($this->getDoctrine()->getManager());
$poList = Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
$productList = Inventory::ProductList($this->getDoctrine()->getManager());
$lotNumArray = [];
foreach ($QD as $entry) {
// $inwardDate=strtotime($entry->getInwardDate());
// $qcDate=strtotime($entry->getQcDate());
$inwardDate = ($entry->getInwardDate() instanceof \DateTime) ? $entry->getInwardDate()->format('m/d/Y') : '';
$qcDate = ($entry->getQcDate() instanceof \DateTime) ? $entry->getQcDate()->format('m/d/Y') : '';
if (!in_array($entry->getLotNumber(), $lotNumArray))
$lotNumArray[] = $entry->getLotNumber();
if (isset($ContentByProductId[$entry->getPurchaseOrderItemId()])) {
$ContentByProductId[$entry->getPurchaseOrderItemId()]['inwardDateList'][] = $inwardDate;
$ContentByProductId[$entry->getPurchaseOrderItemId()]['qcDateList'][] = $inwardDate;
$ContentByProductId[$entry->getPurchaseOrderItemId()]['qcIdList'][] = $entry->getQcId();
$ContentByProductId[$entry->getPurchaseOrderItemId()]['appQtyList'][] = $entry->getApprovedQty();
$ContentByProductId[$entry->getPurchaseOrderItemId()]['totQty'] += (1 * $entry->getApprovedQty());
} else {
$ContentByProductId[$entry->getPurchaseOrderItemId()] = array(
'productName' => $productList[$entry->getProductId()]['name'],
'productUnitName' => $unitList[$productList[$entry->getProductId()]['unit_type']]['name'],
'qcHash' => $entry->getDocumentHash(),
'warehouseName' => $warehouse[$entry->getWarehouseId()]['name'],
'inwardDate' => $inwardDate,
'inwardDateList' => [$inwardDate],
'qcDateList' => [$qcDate],
'qcIdList' => [$entry->getQcId()],
'qcDate' => $qcDate,
'poQty' => $entry->getPoQty(),
'poPrevbalance' => $entry->getPoBalance(),
'appQty' => $entry->getApprovedQty(),
'appQtyList' => [$entry->getApprovedQty()],
'totQty' => $entry->getApprovedQty(),
'poBalance' => $entry->getPoBalance() - $entry->getApprovedQty(),
'qcId' => $entry->getQcId(),
'productId' => $entry->getProductId()
);
}
$Expense_Cost[$entry->getQcId()] = json_decode($entry->getExpenseCost());
$Expense_Id[$entry->getQcId()] = json_decode($entry->getExpenseId());
}
foreach ($ContentByProductId as $c) {
$Content[] = $c;
}
if ($QD) {
return new JsonResponse(array("success" => true, "content" => $Content, "lotNumber" => implode(', ', $lotNumArray), 'Expense_Cost' => $Expense_Cost, 'Expense_Id' => $Expense_Id));
}
return new JsonResponse(array("success" => false));
}
return new JsonResponse(array("success" => false));
}
public function GetSrListForIrAction(Request $request)
{
if ($request->isMethod('POST')) {
$find_array = array();
$Content = [];
if ($request->request->get('srId') != '')
$find_array['stockRequisitionId'] = $request->request->get('srId');
$find_array['forceSkipTag'] = [0, null];
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:StockRequisitionItem')
->findBy(
$find_array
);
$itemList = Inventory::ItemGroupList($this->getDoctrine()->getManager());
$catgoryList = Inventory::ProductCategoryList($this->getDoctrine()->getManager());
$productList = Inventory::ProductList($this->getDoctrine()->getManager());
$unitList = Inventory::UnitTypeList($this->getDoctrine()->getManager());
$fdmData = array();
$em = $this->getDoctrine()->getManager();
$matchType = 'MAXIMUM';
if ($request->request->has('matchType') != '') {
$matchType = $request->request->get('matchType');
}
if ($matchType == 'MINIMUM') {
foreach ($QD as $entry) {
if ($entry->getTagPendingAmount() <= 0)
continue;
$productData = Inventory::GetProductDataFromFdm($em, $entry->getProductFdm());
$combined_id = $entry->getProductFdm();
if (isset($fdmData[$combined_id])) {
$fdmData[$combined_id]['unit'] += $entry->getTagPendingAmount();
$fdmData[$combined_id]['specific_unit'][] = $entry->getTagPendingAmount();
$fdmData[$combined_id]['detailsIds'][] = $entry->getId();
$fdmData[$combined_id]['docIds'][] = $entry->getStockRequisitionId();
} else {
$fdmData[$combined_id] = array(
'id' => 0,
'alias' => $entry->getNote(),
'unit' => $entry->getTagPendingAmount(),
'specific_unit' => [$entry->getTagPendingAmount()],
'warranty' => 0,
'unitTypeId' => 0,
'unit_price' => 0,
'fdm' => $combined_id,
'extDetailsId' => 0,
'product_name' => $productData['productName'],
'total_price' => 0,
'detailsIds' => [$entry->getId()],
'docIds' => [$entry->getStockRequisitionId()],
);
}
}
}
if ($matchType == 'MAXIMUM') {
foreach ($QD as $entry) {
if ($entry->getTagPendingAmount() <= 0)
continue;
$productData = Inventory::GetProductDataFromFdm($em, $entry->getProductFdm());
$combined_id = $entry->getProductFdm();
$assigned = 0;
foreach ($fdmData as $key_ind => $rel_val) {
$matchFdm = Inventory::MatchFdm($key_ind, $combined_id);
if ($matchFdm['hasMatched'] == 1) {
if ($matchFdm['isIdentical'] == 1) {
$fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
$fdmData[$key_ind]['alias'] .= (', ' . $entry->getNote());
$fdmData[$key_ind]['detailsIds'][] = $entry->getId();
$fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
$fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
$fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
$assigned = 1;
} elseif ($matchFdm['SecondBelongsToFirst'] == 1) {
$fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
$fdmData[$key_ind]['alias'] .= (', ' . $entry->getNote());
$fdmData[$key_ind]['detailsIds'][] = $entry->getId();
$fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
$fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
$fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
$assigned = 1;
} elseif ($matchFdm['FirstBelongsToSecond'] == 1) {
$fdmData[$key_ind]['unit'] += $entry->getTagPendingAmount();
$fdmData[$key_ind]['alias'] .= (', ' . $entry->getNote());
$fdmData[$key_ind]['detailsIds'][] = $entry->getId();
$fdmData[$key_ind]['docIds'][] = $entry->getStockRequisitionId();
$fdmData[$key_ind]['specific_unit'][] = $entry->getTagPendingAmount();
$fdmData[$key_ind]['specific_unit_type_id'][] = $entry->getUnitTypeId();
$fdmData[$combined_id] = $fdmData[$key_ind];
unset($fdmData[$key_ind]);
$assigned = 1;
}
} else {
}
if ($assigned == 1)
break;
}
if ($assigned == 0) {
$fdmData[$combined_id] = array(
'id' => 0,
'alias' => $entry->getNote(),
'unit' => $entry->getTagPendingAmount(),
'specific_unit' => [$entry->getTagPendingAmount()],
'specific_unit_type_id' => [$entry->getUnitTypeId()],
'warranty' => 0,
'unitTypeId' => $productData['unitTypeId'],
// 'unitTypeId' => $productData['unitTypeId'],
'unit_price' => 0,
'fdm' => $combined_id,
'extDetailsId' => 0,
'product_name' => htmlspecialchars($productData['productName']),
'total_price' => 0,
'detailsIds' => [$entry->getId()],
'docIds' => [$entry->getStockRequisitionId()],
);
}
if (isset($fdmData[$combined_id])) {
} else {
}
}
}
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:StockRequisition')
->findBy(
array('stockRequisitionId' => $request->request->get('srId'))
);
$contentNote = "";
foreach ($QD as $r) {
$contentNote .= $r->getNote();
$contentNote .= " , ";
}
foreach ($fdmData as $dt) {
$Content[] = $dt;
}
if ($Content) {
return new JsonResponse(array("success" => true, "content" => $Content, "contentNote" => $contentNote));
}
return new JsonResponse(array("success" => false));
}
return new JsonResponse(array("success" => false));
}
public function GetGrnListForEiAction(Request $request)
{
if ($request->isMethod('POST')) {
$find_array = array(
'stage' => GeneralConstant::STAGE_PENDING_TAG,
'approved' => GeneralConstant::APPROVED,
'invoiceTagged' => 1
);
$Content = [];
$Content_obj = [];
$warehouse = Inventory::WarehouseList($this->getDoctrine()->getManager());
$poList = Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
$productList = Inventory::ProductList($this->getDoctrine()->getManager());
if ($request->request->get('poId') != '')
$find_array['purchaseOrderId'] = $request->request->get('poId');
if ($request->request->get('grnId') != '')
$find_array['grnId'] = $request->request->get('grnId');
$unit_type = Inventory::UnitTypeList($this->getDoctrine()->getManager());
$QD_GRN = $this->getDoctrine()
->getRepository('ApplicationBundle:Grn')
->findBy(
$find_array,
array(
'grnDate' => 'ASC'
)
);
$poId = 0;
//
// $expense_id=$QD_GRN->getExpenseId()!=''?json_decode($QD_GRN->getExpenseId()):[];
// $expense_list=$QD_GRN->getExpenseCost()!=''?json_decode($QD_GRN->getExpenseCost()):[];
// $expense_tagged=$QD_GRN->getExpenseTagged()!=''?json_decode($QD_GRN->getExpenseTagged()):[];
$partyId = $request->request->get('partyId');
$bill_details = [];
$bill_details_data = [];
$bill_details_for_grn = [];
$exp_list = InventoryConstant::$Expense_list_details;
$supp_list = Inventory::ProductSupplierList($this->getDoctrine()->getManager());
$head_qry = $this->getDoctrine()
->getRepository('ApplicationBundle:AccAccountsHead')
->findAll();
$head_list = [];
$head_list_by_advance = [];
foreach ($head_qry as $data) {
$head_list[$data->getAccountsHeadId()] = array(
'id' => $data->getAccountsHeadId(),
'name' => $data->getName(),
'advanceTagged' => $data->getAdvanceTagged(),
'advanceOf' => $data->getAdvanceOf(),
'balance' => $data->getCurrentBalance()
);
if ($data->getAdvanceOf() != null && $data->getAdvanceOf() != 0 && $data->getAdvanceOf() != '')
$head_list_by_advance[$data->getAdvanceOf()] = array(
'id' => $data->getAccountsHeadId(),
'name' => $data->getName(),
'advanceTagged' => $data->getAdvanceTagged(),
'advanceOf' => $data->getAdvanceOf(),
'balance' => $data->getCurrentBalance()
);
}
$exp_def_head = [];
foreach ($exp_list as $key => $item) {
$def_settings = $this->getDoctrine()->getRepository('ApplicationBundle:AccSettings')->findOneBy(array(
'name' => $item['name'] . '_onsite_head'
));
if ($def_settings)
$exp_def_head[$item['id']] = $def_settings->getData();
else
$exp_def_head[$item['id']] = '';
}
$bill_details_by_party = [];
// System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($QD_GRN),'debug_data');
// System::log_it($this->container->getParameter('kernel.root_dir'),$partyId,'debug_data');
// System::log_it($this->container->getParameter('kernel.root_dir'),"\nexp list here".json_encode($exp_list),'debug_data');
//
foreach ($QD_GRN as $key => $value) {
$expense_id = $value->getExpenseId() != '' ? json_decode($value->getExpenseId(), true) : [];
$expense_list = $value->getExpenseCost() != '' ? json_decode($value->getExpenseCost(), true) : [];
$expense_tagged = $value->getExpenseTagged() != '' ? json_decode($value->getExpenseTagged(), true) : [];
// System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_id),'debug_data');
// System::log_it($this->container->getParameter('kernel.root_dir'),json_encode($expense_list),'debug_data');
foreach ($exp_list as $chabi => $entry) {
// System::log_it($this->container->getParameter('kernel.root_dir'),"\nChabi ".$chabi,'debug_data');
// System::log_it($this->container->getParameter('kernel.root_dir'),"\nkeys are ".array_keys($expense_id),'debug_data');
if (array_key_exists($chabi, $expense_id)) {
// System::log_it($this->container->getParameter('kernel.root_dir'),"\nFOUND KEY!! ",'debug_data');
if ($partyId == '') //all
{
foreach ($expense_id[$chabi] as $index => $my_val) {
$partyHeadId = $my_val != 0 ? $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' ? $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
$advance_balance = 0;
if ($partyHeadId != 0) {
$curr = $head_list[$partyHeadId]['advanceTagged'] == 1 ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
$advance_balance = ($curr > $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
$head_list[$partyHeadId]['advanceTagged'] == 1 ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
}
$bill_details_by_party[$my_val][] = array(
'partyId' => $my_val,
'partyName' => $my_val != 0 ? $head_list[$my_val]['name'] : 'On site Payment',
'partyHeadId' => $partyHeadId,
'expTypeId' => $chabi,
'expTypeName' => $exp_list[$chabi]['name'],
'expTypeAlias' => $exp_list[$chabi]['alias'],
'expAmount' => $expense_list[$chabi][$index],
'hasAdvance' => $partyHeadId != 0 ? $head_list[$partyHeadId]['advanceTagged'] : 0,
'AdvanceHeadId' => $partyHeadId != 0 ? ($head_list[$partyHeadId]['advanceTagged'] == 1 ? $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
'AdvanceBalance' => $advance_balance,
'grnId' => $value->getGrnId(),
'grnName' => $value->getDocumentHash(),
);
}
} else {
foreach ($expense_id[$chabi] as $index => $my_val) {
if (in_array($my_val, $partyId)) {
$partyHeadId = $my_val != 0 ? $head_list[$my_val]['id'] : ($exp_def_head[$entry['id']] != '' ? $head_list[$exp_def_head[$entry['id']]]['id'] : 0);
$advance_balance = 0;
if ($partyHeadId != 0) {
$curr = $head_list[$partyHeadId]['advanceTagged'] == 1 ? ($head_list_by_advance[$partyHeadId]['balance']) : 0;
$advance_balance = ($curr > $expense_list[$chabi][$index]) ? $expense_list[$chabi][$index] : $curr;
$head_list[$partyHeadId]['advanceTagged'] == 1 ? ($head_list_by_advance[$partyHeadId]['balance'] -= $advance_balance) : 0;
}
$bill_details_by_party[$my_val][] = array(
'partyId' => $my_val,
'partyName' => $my_val != 0 ? $head_list[$my_val]['name'] : 'On site Payment',
'partyHeadId' => $partyHeadId,
'expTypeId' => $chabi,
'expTypeName' => $exp_list[$chabi]['name'],
'expTypeAlias' => $exp_list[$chabi]['alias'],
'expAmount' => $expense_list[$chabi][$index],
'hasAdvance' => $partyHeadId != 0 ? $head_list[$partyHeadId]['advanceTagged'] : 0,
'AdvanceHeadId' => $partyHeadId != 0 ? ($head_list[$partyHeadId]['advanceTagged'] == 1 ? $head_list_by_advance[$partyHeadId]['id'] : 0) : 0,
'AdvanceBalance' => $advance_balance,
'grnId' => $value->getGrnId(),
'grnName' => $value->getDocumentHash(),
);
}
}
}
}
}
}
// $Content_obj=
//
// foreach($Content_obj as $item)
// {
// $Content[]=$item;
//
// }
$list_of_keys = array_keys($bill_details_by_party);
if ($bill_details_by_party) {
return new JsonResponse(array("success" => true, "content" => $bill_details_by_party, 'index' => $list_of_keys, 'h_l_b_a' => $head_list_by_advance));
}
return new JsonResponse(array("success" => false));
}
return new JsonResponse(array("success" => false));
}
public function GetServiceListForPiAction(Request $request)
{
if ($request->isMethod('POST')) {
// $find_array=array(
// 'stage' => GeneralConstant::STAGE_PENDING_TAG,
// 'approved'=>GeneralConstant::APPROVED
// );
$Content = [];
$Content_obj = [];
$ContentService = [];
$Content_service_obj = [];
// $warehouse=Inventory::WarehouseList($this->getDoctrine()->getManager());
// $poList=Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
// $productList=Inventory::ProductList($this->getDoctrine()->getManager());
$serviceList = Inventory::ServiceList($this->getDoctrine()->getManager());
if ($request->request->get('poId') != '')
$poId = $request->request->get('poId');
if ($request->request->get('grnId') != '')
$find_array['grnId'] = $request->request->get('grnId');
$unit_type = Inventory::UnitTypeList($this->getDoctrine()->getManager());
//adding service data temporarily
$po = $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(
array('purchaseOrderId' => $poId));
$multiply_type = $po->getCurrencyMultiply();
$multiply_rate = $po->getCurrencyMultiplyRate();
$multiplier = ($multiply_type * 1) == 1 ? (1 * $multiply_rate) :
(($multiply_rate * 1) != 0 ? (1 / $multiply_rate) : 1);
$po_items = $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
array('purchaseOrderId' => $poId));
foreach ($po_items as $item) {
// $po_item_list[$item->getProductId()]=$item;
//temporary service add
if ($item->getType() == 2)
$Content_service_obj[$item->getId()] = array(
'serviceId' => $item->getServiceId(),
'poItemId' => $item->getId(),
'colorId' => 0,
'sizeId' => 0,
'serviceName' => $serviceList[$item->getServiceId()]['name'],
'qty' => $item->getQty(),
'balance' => $item->getBalance(),
'unit_name' => '',
'unit_price' => $item->getPrice() * $multiplier,
'grn_id' => 0,
);
//temprary service add end
}
//temporary service data adding done
$po_data = [];
$po_data = array(
'docHash' => $po->getDocumentHash(),
'docDate' => $po->getPurchaseOrderDate(),
'supplierId' => $po->getSupplierId(),
'supplierName' => $po->getSupplierId(),
'vatRate' => $po->getVatRate(),
'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
'aitRate' => $po->getAitRate(),
'aitAmount' => $po->getAitAmount(),
'tdsRate' => $po->getTdsRate(),
'tdsAmount' => $po->getTdsAmount(),
'vdsRate' => $po->getVdsRate(),
'vdsAmount' => $po->getVdsAmount(),
'discountRate' => $po->getDiscountRate(),
'discountAmount' => $po->getVatAmount(),
);
foreach ($Content_obj as $item) {
$Content[] = $item;
}
foreach ($Content_service_obj as $item) {
$ContentService[] = $item;
}
if ($Content || $ContentService) {
return new JsonResponse(array("success" => true, "content" => $Content, "contentService" => $ContentService, "po_data" => $po_data));
}
return new JsonResponse(array("success" => false));
}
return new JsonResponse(array("success" => false));
}
public function GetGrnListForPiAction(Request $request)
{
if ($request->isMethod('POST')) {
$find_array = array(
'stage' => GeneralConstant::STAGE_PENDING_TAG,
'approved' => GeneralConstant::APPROVED
);
$Content = [];
$Content_obj = [];
$ContentService = [];
$Content_service_obj = [];
$warehouse = Inventory::WarehouseList($this->getDoctrine()->getManager());
$poList = Purchase::PurchaseOrderList($this->getDoctrine()->getManager());
$productList = Inventory::ProductList($this->getDoctrine()->getManager());
$serviceList = Inventory::ServiceList($this->getDoctrine()->getManager());
if ($request->request->get('poId') != '')
$find_array['purchaseOrderId'] = $request->request->get('poId');
if ($request->request->get('grnId') != '')
$find_array['grnId'] = $request->request->get('grnId');
$unit_type = Inventory::UnitTypeList($this->getDoctrine()->getManager());
$QD_GRN = $this->getDoctrine()
->getRepository('ApplicationBundle:Grn')
->findBy(
$find_array,
array(
'grnDate' => 'ASC'
)
);
$poId = 0;
foreach ($QD_GRN as $value) {
$grn_items = $this->getDoctrine()->getRepository('ApplicationBundle:GrnItem')->findBy(
array('grnId' => $value->getGrnId()));
$po_items = $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
array('purchaseOrderId' => $value->getPurchaseOrderId()));
$poId = $value->getPurchaseOrderId();
$po_item_list = [];
foreach ($po_items as $item) {
$po_item_list[$item->getProductId()] = $item;
}
foreach ($grn_items as $entry) {
//adding transaction
// System::log_it($this->container->getParameter('kernel.root_dir'),$entry->getProductId(),'debug_data');
$Content_obj[$entry->getId()] = array(
'productId' => $entry->getProductId(),
'poItemId' => $entry->getId(),
'productName' => $productList[$entry->getProductId()]['name'],
'colorId' => $entry->getColorId(),
'sizeId' => $entry->getSizeId(),
'qty' => isset($Content_obj[$entry->getId()]) ? $Content_obj[$entry->getId()]['qty'] + $entry->getQty() : $entry->getQty(),
'unit_name' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
// 'unit_price'=>$po_item_list[$entry->getProductId()]->getPrice(),
'unit_price' => $entry->getPrice(),
'grn_id' => $entry->getId(),
);
}
// for
}
//adding service data temporarily
$po = $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findOneBy(
array('purchaseOrderId' => $poId));
$multiply_type = $po->getCurrencyMultiply();
$multiply_rate = $po->getCurrencyMultiplyRate();
$multiplier = ($multiply_type * 1) == 1 ? (1 * $multiply_rate) :
(($multiply_rate * 1) != 0 ? (1 / $multiply_rate) : 1);
$po_items = $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
array('purchaseOrderId' => $poId));
foreach ($po_items as $item) {
// $po_item_list[$item->getProductId()]=$item;
//temporary service add
if ($item->getType() == 2)
$Content_service_obj[$item->getId()] = array(
'serviceId' => $item->getServiceId(),
'poItemId' => $item->getId(),
'colorId' => 0,
'sizeId' => 0,
'serviceName' => $serviceList[$item->getServiceId()]['name'],
'qty' => $item->getQty(),
'balance' => $item->getBalance(),
'unit_name' => '',
'unit_price' => $item->getPrice() * $multiplier,
'grn_id' => 0,
);
//temprary service add end
}
//temporary service data adding done
$po_data = [];
$po_data = array(
'docHash' => $po->getDocumentHash(),
'docDate' => $po->getPurchaseOrderDate(),
'supplierId' => $po->getSupplierId(),
'supplierName' => $po->getSupplierId(),
'vatRate' => $po->getVatRate(),
'advanceAmount' => $po->getAdvanceAmount() * $multiplier,
'aitRate' => $po->getAitRate(),
'aitAmount' => $po->getAitAmount(),
'tdsRate' => $po->getTdsRate(),
'tdsAmount' => $po->getTdsAmount(),
'vdsRate' => $po->getVdsRate(),
'vdsAmount' => $po->getVdsAmount(),
'discountRate' => $po->getDiscountRate(),
'discountAmount' => $po->getVatAmount(),
);
foreach ($Content_obj as $item) {
$Content[] = $item;
}
foreach ($Content_service_obj as $item) {
$ContentService[] = $item;
}
if ($Content) {
return new JsonResponse(array("success" => true, "content" => $Content, "contentService" => $ContentService, "po_data" => $po_data));
}
return new JsonResponse(array("success" => false));
}
return new JsonResponse(array("success" => false));
}
public function GetPoDetailsForPiAction(Request $request, $poId)
{
}
public function GetPoDetailsAction(Request $request, $poId)
{
if ($request->isMethod('POST')) {
$po = $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrder')->findBy(
array('purchaseOrderId' => $poId));
$po_items = $this->getDoctrine()->getRepository('ApplicationBundle:PurchaseOrderItem')->findBy(
array('purchaseOrderId' => $poId));
$productList = Inventory::ProductList($this->getDoctrine()->getManager());
$unit_type = Inventory::UnitTypeList($this->getDoctrine()->getManager());
$Content = [];
$po_items_list = [];
foreach ($po_items as $entry) {
$po_items_list[] = array(
'productId' => $entry->getProductId(),
'productName' => $productList[$entry->getProductId()]['name'],
'price' => $entry->getPrice(),
'unit' => $unit_type[$productList[$entry->getProductId()]['unit_type']]['name'],
'received' => $entry->getReceived(),
'qty' => $entry->getQty(),
'balance' => $entry->getBalance()
);
}
$po_data = [];
$po_data = array(
'docHash' => $po->getDocumentHash(),
'docDate' => $po->getPurchaseOrderDate(),
'supplierId' => $po->getSupplierId(),
'supplierName' => $po->getSupplierId(),
);
if ($po_data) {
return new JsonResponse(array("success" => true, "content" => $po_data));
}
return new JsonResponse(array("success" => false));
}
return new JsonResponse(array("success" => false));
}
public function CreateSalesReplacementAction(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)['SalesReplacement']; //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 = Inventory::CreateNewSalesReplacement(
$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)['SalesReplacement']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
$StID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['SalesReplacement'], $StID,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$this->addFlash(
'success',
'Stock Transfer Added.'
);
$url = $this->generateUrl(
'view_st'
);
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('ApplicationBundle:pages/inventory/input_forms:sales_replacement.html.twig',
array(
'page_title' => 'Sales Replacement Note',
'warehouseList' => Inventory::WarehouseList($em),
'warehouseListArray' => Inventory::WarehouseListArray($em),
'warehouseActionList' => $warehouse_action_list,
'warehouseActionListArray' => $warehouse_action_list_array,
'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
'product_list_array' => Inventory::ProductListDetailedArray($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 SalesReplacementListAction(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesReplacement')
->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->getSalesReplacementDate(),
'id' => $entry->getSalesReplacementId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render('ApplicationBundle:pages/inventory/view:stock_transfer_list.html.twig',
array(
'page_title' => 'Stock Transfer List',
'data' => $data
)
);
}
public function ViewSalesReplacementAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetSalesReplacementDetails($em, $id);
return $this->render('ApplicationBundle:pages/inventory/view:view_stock_transfer.html.twig',
array(
'page_title' => 'Stock Transfer',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public function PrintSalesReplacementAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetSalesReplacementDetails($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('ApplicationBundle:pages/inventory/print:print_stock_transfer.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Stock Transfer',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
$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="stock_transfer_' . $id . '.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_stock_transfer.html.twig',
array(
'page_title' => 'Stock Transfer',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['SalesReplacement'],
$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 CreateStockTransferAction(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)['StockTransfer']; //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)
) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$StID = Inventory::CreateNewStockTransfer(
$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)['StockTransfer']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
$StID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID), $request->request->get('prefix_hash')
);
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockTransfer'], $StID,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$this->addFlash(
'success',
'Stock Transfer Added.'
);
$url = $this->generateUrl(
'view_st'
);
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('ApplicationBundle:pages/inventory/input_forms:stock_transfer_note.html.twig',
array(
'page_title' => 'Stock Transfer Note',
'warehouseList' => Inventory::WarehouseList($em),
'warehouseListArray' => Inventory::WarehouseListArray($em),
'colorList' => Inventory::GetColorList($em),
'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
'srList' => [],
'warehouseActionList' => $warehouse_action_list,
'warehouseActionListArray' => $warehouse_action_list_array,
'item_list' => Inventory::ItemGroupList($em),
'item_list_array' => Inventory::ItemGroupListArray($em),
'category_list_array' => Inventory::ProductCategoryListArray($em),
'product_list_array' => Inventory::ProductListDetailedArray($em),
// 'product_list_array' => [],
'product_list' => Inventory::ProductList($em, $companyId),
// 'product_list' => [],
'prefix_list' => array(
[
'id' => 1,
'value' => 'GN',
'text' => 'GN'
]
),
'assoc_list' => array(
[
'id' => 1,
'value' => 1,
'text' => 'GN'
]
),
'INVLIST' => $INVLIST
)
);
}
public function GetSrItemForTransferAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$search_query = [];
$res_data_by_so_item_id = [];
$Content = [];
$productionProcessSettings = array(
'id' => 0
);
if ($request->query->has('srId'))
$search_query['stockRequisitionId'] = $request->query->get('srId');
$DT = $this->getDoctrine()
->getRepository('ApplicationBundle:StockRequisitionItem')
->findBy(
$search_query
);
$Content = array(
'requisitioned_product_item_id' => [],
'requisitioned_products' => [],
'requisitioned_product_fdm' => [],
'requisitioned_product_name' => [],
'requisitioned_product_units' => [],
'requisitioned_product_unit_type' => [],
'requisitioned_product_balance' => [],
);
foreach ($DT as $dt) {
// $data=json_decode($DT->getData(),true);
$Content['requisitioned_products'][] = $dt->getProductId();
$Content['requisitioned_product_item_id'][] = $dt->getId();
$Content['requisitioned_product_fdm'][] = $dt->getProductFdm();
$Content['requisitioned_product_name'][] = $dt->getProductNameFdm();
$Content['requisitioned_product_units'][] = $dt->getQty();
$Content['requisitioned_product_balance'][] = $dt->getAlottmentPendingAmount();
}
$INVLIST = [];
if (!empty($Content)) {
return new JsonResponse(array("success" => true, "content" => $Content, "INVLIST" => $INVLIST));
} else {
return new JsonResponse(array("success" => false, "content" => $Content, "INVLIST" => $INVLIST));
}
}
public function StockTransferListAction(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:StockTransfer')
->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->getStockTransferDate(),
'id' => $entry->getStockTransferId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render('ApplicationBundle:pages/inventory/view:stock_transfer_list.html.twig',
array(
'page_title' => 'Stock Transfer List',
'data' => $data
)
);
}
public function ViewStockTransferAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetStockTransferDetails($em, $id);
return $this->render('ApplicationBundle:pages/inventory/view:view_stock_transfer.html.twig',
array(
'page_title' => 'Stock Transfer',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public function PrintStockTransferAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetStockTransferDetails($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('ApplicationBundle:pages/inventory/print:print_stock_transfer.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Stock Transfer',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
$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="stock_transfer_' . $id . '.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_stock_transfer.html.twig',
array(
'page_title' => 'Stock Transfer',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockTransfer'],
$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 CreateStockConsumptionNoteAction(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)['StockConsumptionNote']; //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 Could not insert Data.'
);
} else {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$StID = Inventory::CreateNewStockConsumptionNote(
$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)['StockConsumptionNote']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
$StID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'], $StID,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$this->addFlash(
'success',
'Stock Consumption Added.'
);
$url = $this->generateUrl(
'view_stock_consumption_note'
);
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();
}
$consumptionTypeQry = $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
array(
'CompanyId' => $this->getLoggedUserCompanyId($request),
)
);
$consumptionTypeList = [];
$consumptionTypeListArray = [];
foreach ($consumptionTypeQry as $entry) {
$p = array(
'name' => $entry->getName(),
'id' => $entry->getConsumptionTypeId(),
'accounts_head_id' => $entry->getAccountsHeadId(),
'cost_center_id' => $entry->getCostCenterId(),
);
$consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
$consumptionTypeListArray[] = $p;
}
//add bill list
$service_purchase_bill_query = $this->getDoctrine()
->getRepository('ApplicationBundle:PurchaseInvoice')
->findBy(
array(
'typeHash' => 'SPB',
'approved' => GeneralConstant::APPROVED
)
);
$service_purchase_bill_list = [];
$service_purchase_bill_list_array = [];
$bill = array(
'id' => 0,
'type' => 'SPB',
'name' => 'New Expense',
'text' => 'New Expense',
'amount' => 0,
);
$service_purchase_bill_list[0] = $bill;
$service_purchase_bill_list_array[] = $bill;
foreach ($service_purchase_bill_query as $d) {
$bill = array(
'id' => $d->getPurchaseInvoiceId(),
'type' => 'SPB',
'name' => $d->getDocumentHash(),
'text' => $d->getDocumentHash(),
'amount' => $d->getInvoiceAmount(),
);
$service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
$service_purchase_bill_list_array[] = $bill;
}
return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_consumption_note.html.twig',
array(
'page_title' => 'Stock Consumption Note',
'warehouseList' => Inventory::WarehouseList($em),
'warehouseListArray' => Inventory::WarehouseListArray($em),
'consumptionTypeList' => $consumptionTypeList,
'consumptionTypeListArray' => $consumptionTypeListArray,
'service_purchase_bill_list' => $service_purchase_bill_list,
'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
'warehouseActionList' => $warehouse_action_list,
'warehouseActionListArray' => $warehouse_action_list_array,
'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
'product_list' => Inventory::ProductListDetailed($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 StockConsumptionNoteListAction(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:StockConsumptionNote')
->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->getStockConsumptionNoteDate(),
'id' => $entry->getStockConsumptionNoteId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render('ApplicationBundle:pages/inventory/view:stock_consumption_note_list.html.twig',
array(
'page_title' => 'Stock Consumption Note List',
'data' => $data
)
);
}
public function ViewStockConsumptionNoteAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetStockConsumptionNoteDetails($em, $id);
$consumptionTypeQry = $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
array(
'CompanyId' => $this->getLoggedUserCompanyId($request),
)
);
$consumptionTypeList = [];
$consumptionTypeListArray = [];
foreach ($consumptionTypeQry as $entry) {
$p = array(
'name' => $entry->getName(),
'id' => $entry->getConsumptionTypeId(),
'accounts_head_id' => $entry->getAccountsHeadId(),
'cost_center_id' => $entry->getCostCenterId(),
);
$consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
$consumptionTypeListArray[] = $p;
}
//add bill list
$service_purchase_bill_query = $this->getDoctrine()
->getRepository('ApplicationBundle:PurchaseInvoice')
->findBy(
array(
'typeHash' => 'SPB',
'approved' => GeneralConstant::APPROVED
)
);
$service_purchase_bill_list = [];
$service_purchase_bill_list_array = [];
$bill = array(
'id' => 0,
'type' => 'SPB',
'name' => 'New Expense',
'text' => 'New Expense',
'amount' => 0,
);
$service_purchase_bill_list[0] = $bill;
$service_purchase_bill_list_array[] = $bill;
foreach ($service_purchase_bill_query as $d) {
$bill = array(
'id' => $d->getPurchaseInvoiceId(),
'type' => 'SPB',
'name' => $d->getDocumentHash(),
'text' => $d->getDocumentHash(),
'amount' => $d->getInvoiceAmount(),
);
$service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
$service_purchase_bill_list_array[] = $bill;
}
return $this->render('ApplicationBundle:pages/inventory/view:view_stock_consumption_note.html.twig',
array(
'page_title' => 'Stock Transfer',
'data' => $dt,
'service_purchase_bill_list' => $service_purchase_bill_list,
'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
'consumptionTypeList' => $consumptionTypeList,
'consumptionTypeListArray' => $consumptionTypeListArray,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public function PrintStockConsumptionNoteAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetStockConsumptionNoteDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
$consumptionTypeQry = $em->getRepository('ApplicationBundle:ConsumptionType')->findBy(
array(
'CompanyId' => $this->getLoggedUserCompanyId($request),
)
);
$consumptionTypeList = [];
$consumptionTypeListArray = [];
foreach ($consumptionTypeQry as $entry) {
$p = array(
'name' => $entry->getName(),
'id' => $entry->getConsumptionTypeId(),
'accounts_head_id' => $entry->getAccountsHeadId(),
'cost_center_id' => $entry->getCostCenterId(),
);
$consumptionTypeList[$entry->getConsumptionTypeId()] = $p;
$consumptionTypeListArray[] = $p;
}
//add bill list
$service_purchase_bill_query = $this->getDoctrine()
->getRepository('ApplicationBundle:PurchaseInvoice')
->findBy(
array(
'typeHash' => 'SPB',
'approved' => GeneralConstant::APPROVED
)
);
$service_purchase_bill_list = [];
$service_purchase_bill_list_array = [];
$bill = array(
'id' => 0,
'type' => 'SPB',
'name' => 'New Expense',
'text' => 'New Expense',
'amount' => 0,
);
$service_purchase_bill_list[0] = $bill;
$service_purchase_bill_list_array[] = $bill;
foreach ($service_purchase_bill_query as $d) {
$bill = array(
'id' => $d->getPurchaseInvoiceId(),
'type' => 'SPB',
'name' => $d->getDocumentHash(),
'text' => $d->getDocumentHash(),
'amount' => $d->getInvoiceAmount(),
);
$service_purchase_bill_list[$d->getPurchaseInvoiceId()] = $bill;
$service_purchase_bill_list_array[] = $bill;
}
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView('ApplicationBundle:pages/inventory/print:print_stock_consumption_note.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Stock Consumption',
'export' => 'pdf,print',
'data' => $dt,
'service_purchase_bill_list' => $service_purchase_bill_list,
'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
$id,
$dt['created_by'],
$dt['edited_by']),
'document_mark_image' => $document_mark['original'],
'consumptionTypeList' => $consumptionTypeList,
'consumptionTypeListArray' => $consumptionTypeListArray,
'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="stock_consumption_note_' . $id . '.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_stock_consumption_note.html.twig',
array(
'page_title' => 'Stock Consumption',
'export' => 'pdf,print',
'data' => $dt,
'service_purchase_bill_list' => $service_purchase_bill_list,
'service_purchase_bill_list_array' => $service_purchase_bill_list_array,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockConsumptionNote'],
$id,
$dt['created_by'],
$dt['edited_by']),
'document_mark_image' => $document_mark['original'],
'consumptionTypeList' => $consumptionTypeList,
'consumptionTypeListArray' => $consumptionTypeListArray,
'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 CreateStockReceivedNoteAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$extDocData = [];
$userId = $request->getSession()->get(UserConstants::USER_ID);
$warehouse_action_list = Inventory::warehouse_action_list($em, $companyId, 'object');;
$warehouse_action_list_array = Inventory::warehouse_action_list($em, $companyId, 'array');;
// $userBranchList=json_decode($request->getSession()->get('branchIdList'),true);
$userBranchIdList = $request->getSession()->get('branchIdList');
if ($userBranchIdList == null) $userBranchIdList = [];
$userBranchId = $request->getSession()->get('branchId');
if ($request->isMethod('POST') && !($request->request->has('getInitialData'))) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['StockReceivedNote']; //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)
) {
if ($request->request->has('returnJson')) {
return new JsonResponse(array(
'success' => false,
'documentHash' => 0,
'documentId' => 0,
'billIds' => [],
'drIds' => [],
'pmntTransIds' => [],
'viewUrl' => '',
'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 {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$StID = Inventory::CreateNewStockReceivedNote(
$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)['StockReceivedNote']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$StID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'], $StID,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$url = $this->generateUrl(
'view_srcv'
);
if ($request->request->has('returnJson')) {
return new JsonResponse(array(
'success' => true,
'documentHash' => $dochash,
'documentId' => $StID,
'viewUrl' => $url . "/" . $StID,
));
} else {
$this->addFlash(
'success',
'Stock Received Note Added.'
);
return $this->redirect($url . "/" . $StID);
}
}
}
$slotList = $em->getRepository('ApplicationBundle:InventoryStorage')->findBy(
array(
'CompanyId' => $this->getLoggedUserCompanyId($request),
)
);
if ($id == 0) {
} else {
$extDoc = $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
array(
'salesOrderId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extDoc) {
if ($extDoc->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_srcv'
);
return $this->redirect($url . "/" . $id);
} else {
$extDocData = $extDoc;
$extDocDataDetails = $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findOneBy(
array(
'stockReceivedNoteId' => $id, ///material
)
);
}
} else {
}
}
$INVLIST = [];
foreach ($slotList as $slot) {
$INVLIST[$slot->getWarehouseId() . '_' . $slot->getActionTagId() . '_' . $slot->getproductId()] = $slot->getQty();
}
$dataArray = array(
'page_title' => 'Stock Received Note',
// 'ExistingClients'=>Accounts::getClientLedgerHeads($this->getDoctrine()->getManager()),
'ClientListByAcHead' => SalesOrderM::GetClientListByAcHead($this->getDoctrine()->getManager()),
'users' => Users::getUserListById($em),
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $userId)['options'],
'warehouseList' => Inventory::WarehouseList($em),
'warehouseListArray' => Inventory::WarehouseListArray($em),
'warehouseActionList' => $warehouse_action_list,
'warehouseActionListArray' => $warehouse_action_list_array,
'extDocData' => $extDocData,
'credit_head_list' => Accounts::getParentLedgerHeads($em, 'pv', '', [], 1, $companyId),
'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
// 'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
// 'product_list' => Inventory::ProductList($em, $companyId),
'salesOrderList' => SalesOrderM::SalesOrderList($em, $companyId),
'prefix_list' => array(
[
'id' => 1,
'value' => 'GN',
'text' => 'GN'
]
),
'assoc_list' => array(
[
'id' => 1,
'value' => 1,
'text' => 'GN'
]
),
'INVLIST' => $INVLIST,
'stList' => Inventory::StockTransferList($em, $companyId, [], GeneralConstant::STAGE_PENDING_TAG, 0),
'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
);
}
return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_received_note.html.twig',
$dataArray
);
}
public function GetItemListForStockReceivedAction(Request $request)
{
if ($request->isMethod('POST')) {
$em = $this->getDoctrine();
$receiveType = 1;//transfer
if ($request->request->has('receiveType'))
$receiveType = $request->request->get('receiveType');
$QD = [];
if ($receiveType == 1)
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:StockTransferItem')
->findBy(
array(
// 'CompanyId'=> $this->getLoggedUserCompanyId($request),
'stockTransferId' => $request->request->get('stId')
),
array()
);
if ($receiveType == 2)
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:SalesOrderItem')
->findBy(
array(
// 'CompanyId'=> $this->getLoggedUserCompanyId($request),
'salesOrderId' => $request->request->get('soId')
),
array()
);
// if($request->request->get('wareHouseId')!='')
//
// $DO=$this->getDoctrine()
// ->getRepository('ApplicationBundle:DeliveryOrder')
// ->findOneBy(
// $find_array,
// array(
//
// )
// );
$sendData = array(
// 'salesType'=>$SO->getSalesType(),
// 'packageData'=>[],
'productList' => [],
// 'productListByPackage'=>[],
);
$productList = Inventory::ProductList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request));
$pckg_item_cross_match_data = [];
foreach ($QD as $product) {
// $b_code=json_decode($product->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
$b_code = [];
if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
$to_analyze_codes_str = $receiveType == 1 ? $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
if ($to_analyze_codes_str != null)
$b_code = json_decode($to_analyze_codes_str, true, 512, JSON_BIGINT_AS_STRING);
else
$b_code = [];
} else {
$to_analyze_codes_str = $receiveType == 1 ? $product->getNonDeliveredSalesCodeRange() : $product->getNonReceivedSalesCodeRange();
if ($to_analyze_codes_str != null) {
$max_int_length = strlen((string)PHP_INT_MAX) - 1;
$json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $to_analyze_codes_str);
$b_code = json_decode($json_without_bigints, true);
} else {
$b_code = [];
}
}
$b_code_data = [];
foreach ($b_code as $d) {
$b_code_data[] = array(
'id' => 1 * $d,
'name' => str_pad($d, 13, '0', STR_PAD_LEFT),
);
}
$p_data = array(
'details_id' => $product->getId(),
'productId' => $product->getProductId(),
'product_name' => $productList[$product->getProductId()]['name'],
'product_barcodes' => $b_code_data,
// 'available_inventory'=>$inventory_by_warehouse?$inventory_by_warehouse->getQty():0,
// 'package_id'=>$product->getPackageId(),
'qty' => $receiveType == 1 ? $product->getQty() : $product->getToBeReceived(),
'unit_price' => $receiveType == 1 ? $product->getPrice() : $productList[$product->getProductId()]['purchase_price'],
'balance' => $receiveType == 1 ? $product->getBalance() : ($product->getToBeReceived() - $product->getReceived()),
// '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 StockReceivedNoteListAction(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:StockReceivedNote')
->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->getStockReceivedNoteDate(),
'id' => $entry->getStockReceivedNoteId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render('ApplicationBundle:pages/inventory/view:stock_received_note_list.html.twig',
array(
'page_title' => 'Stock Received List',
'data' => $data
)
);
}
public function ViewStockReceivedNoteAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetStockReceivedNoteDetails($em, $id);
return $this->render('ApplicationBundle:pages/inventory/view:view_stock_received_note.html.twig',
array(
'page_title' => 'Stock Received Note',
'data' => $dt,
'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public function PrintStockReceivedNoteAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetStockReceivedNoteDetails($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('ApplicationBundle:pages/inventory/print:print_stock_received_note.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Stock Received Note',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$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="stock_received_note_' . $id . '.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_stock_received_note.html.twig',
array(
'page_title' => 'Stock Received Note',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$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 CreateStoreRequisitionSlipAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
// $id;
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['StoreRequisition']; //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, $id)
) {
$this->addFlash(
'error',
'Sorry, could not insert Data.'
);
} else {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$IrID = Inventory::CreateNewStoreRequisition($id,
$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 = $request->request->get('approvalRole');
$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)['StoreRequisition']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
$IrID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StoreRequisition'], $IrID,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$this->addFlash(
'success',
'New Indent Added.'
);
$url = $this->generateUrl(
'view_ir'
);
return $this->redirect($url . "/" . $IrID);
}
}
$extDocData = [];
$extDocDetailsData = [];
if ($id == 0) {
} else {
$extDoc = $em->getRepository('ApplicationBundle:StoreRequisition')->findOneBy(
array(
'storeRequisitionId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extDoc) {
if ($extDoc->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_ir'
);
return $this->redirect($url . "/" . $id);
} else {
$extDocData = $extDoc;
$extDocDetailsData = $em->getRepository('ApplicationBundle:StoreRequisitionItem')->findBy(
array(
'storeRequisitionId' => $id, ///material
)
);;
}
} else {
}
}
$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;
$sr_list = [];
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:StockRequisition')
->findBy(
array(
'indentTagged' => 0,
'approved' => 1
)
);
foreach ($QD as $dt) {
$sr_list[$dt->getStockRequisitionId()] = array(
'id' => $dt->getStockRequisitionId(),
'name' => $dt->getDocumentHash(),
'text' => $dt->getDocumentHash(),
);
}
return $this->render('ApplicationBundle:pages/inventory/input_forms:store_requisition.html.twig',
array(
'page_title' => 'Indent Requisition Slip',
'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
'sr_list' => $sr_list,
'productList' => $productList,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'extId' => $id,
'extDocDetailsData' => $extDocDetailsData,
'extDocData' => $extDocData,
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'unitList' => $unitList,
'brandList' => $brandList,
'brandListArray' => $brandListArray,
'productListArray' => $productListArray,
'subCategoryListArray' => $subCategoryListArray,
'categoryListArray' => $categoryListArray,
'igListArray' => $igListArray,
'unitListArray' => $unitListArray,
'prefix_list' => array(
[
'id' => 1,
'value' => 'GN',
'text' => 'General'
],
[
'id' => 1,
'value' => 'SD',
'text' => 'For Sales Demand'
]
),
'assoc_list' => array(
[
'id' => 1,
'value' => 1,
'text' => 'GN'
]
)
)
);
}
public function CreateStockRequisitionSlipAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
if ($request->isMethod('POST')) {
$em = $this->getDoctrine()->getManager();
$entity_id = array_flip(GeneralConstant::$Entity_list)['StockRequisition']; //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, $id)
) {
$this->addFlash(
'error',
'Sorry, could not insert Data.'
);
} else {
if ($request->request->has('check_allowed'))
$check_allowed = 1;
$SrID = Inventory::CreateNewStockRequisition($id,
$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 = $request->request->get('approvalRole');
$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)['StockRequisition']]
['entity_view_route_path_name']
)
);
System::setApprovalInfo($this->getDoctrine()->getManager(), $options,
array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
$SrID,
$request->getSession()->get(UserConstants::USER_LOGIN_ID) //journal voucher
);
System::createEditSignatureHash($this->getDoctrine()->getManager(), array_flip(GeneralConstant::$Entity_list)['StockRequisition'], $SrID,
$loginId,
$approveRole,
$request->request->get('approvalHash'));
$this->addFlash(
'success',
'New Requisition Added.'
);
$url = $this->generateUrl(
'view_sr'
);
// return $this->redirect($url . "/" . $SrID);
}
}
$extDocData = [];
$extDocDetailsData = [];
if ($id == 0) {
} else {
$extDoc = $em->getRepository('ApplicationBundle:StockRequisition')->findOneBy(
array(
'stockRequisitionId' => $id, ///material
)
);
//now if its not editable, redirect to view
if ($extDoc) {
if ($extDoc->getEditFlag() != 1) {
$url = $this->generateUrl(
'view_sr'
);
return $this->redirect($url . "/" . $id);
} else {
$extDocData = $extDoc;
$extDocDetailsData = $em->getRepository('ApplicationBundle:StockRequisitionItem')->findBy(
array(
'stockRequisitionId' => $id, ///material
)
);;
}
} else {
}
}
$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;
return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_requisition_slip.html.twig',
array(
'page_title' => 'Stock Requisition Slip',
'item_list' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'item_list_array' => Inventory::ItemGroupListArray($this->getDoctrine()->getManager()),
'category_list_array' => Inventory::ProductCategoryListArray($this->getDoctrine()->getManager()),
'product_list_array' => Inventory::ProductListDetailedArray($this->getDoctrine()->getManager()),
'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
'userRestrictions' => Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'],
'productList' => $productList,
'extId' => $id,
'extDocDetailsData' => $extDocDetailsData,
'extDocData' => $extDocData,
'subCategoryList' => $subCategoryList,
'categoryList' => $categoryList,
'igList' => $igList,
'unitList' => $unitList,
'brandList' => $brandList,
'brandListArray' => $brandListArray,
'productListArray' => $productListArray,
'subCategoryListArray' => $subCategoryListArray,
'categoryListArray' => $categoryListArray,
'igListArray' => $igListArray,
'unitListArray' => $unitListArray,
'productionBomList' => ProductionM::ProductionBomList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'productionScheduleList' => ProductionM::ProductionScheduleList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'prefix_list' => array(
[
'id' => 1,
'value' => 'GN',
'text' => 'General'
],
[
'id' => 1,
'value' => 'SD',
'text' => 'For Sales Demand'
]
),
'projectList' => $em->getRepository('ApplicationBundle:Project')->findBy(
array(
'status' => array_flip(ProjectConstant::$projectStatus)['PROCESSING']
), array('projectDate' => 'desc')
),
'salesOrderList' => SalesOrderM::SalesOrderListPendingDelivery($em),
'assoc_list' => array(
[
'id' => 1,
'value' => 'GN',
'text' => 'General'
]
)
)
);
}
public function CreateStockReturnAction(Request $request)
{
return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_return.html.twig',
array(
'page_title' => 'Stock Return',
// 'dataList'=>$dta_list
)
);
}
public function MaterialInwardAction(Request $request)
{
$data = [];
if ($request->isMethod('POST')) {
//first of all resolve the transport costs
$total_price_value = 0;
$data_list = $dt = $this->getDoctrine()
->getRepository('ApplicationBundle:PurchaseOrderItem')
->findBy(
array(
'purchaseOrderId' => $request->request->get('poId'),
'productId' => $request->request->get('products')
)
);
$purchase_items = [];
foreach ($data_list as $key => $value) {
$purchase_items[$value->getProductId()] = $value;
}
foreach ($request->request->get('products') as $key => $entry) {
$total_price_value = $total_price_value + ($request->request->get('receivedQty')[$key]) * ($purchase_items[$entry]->getPrice());
}
$po_data = Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$request->request->get('poId')];
$supplier_id = $po_data['supplier_id'];
$supplier_name = Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
foreach ($request->request->get('products') as $key => $entry) {
if ($request->request->get('receivedQty')[$key] > 0)
Inventory::NewMaterialInward($this->getDoctrine()->getManager(),
$request->request,
$key,
$request->request->get('poId'),
$request->request->get('purchaseOrderItemId'),
$supplier_id,
$request->request->get('warehouseId'),
$request->request->get('lotNumber'),
$request->request->get('type_hash'),
$request->request->get('prefix_hash'),
$request->request->get('assoc_hash'),
$request->request->get('number_hash'),
$request->request->get('docHash'),
$request->request->get('docDate'),
$purchase_items[$entry],
$total_price_value,
$request->getSession()->get(UserConstants::USER_LOGIN_ID));
}
$warehouse_name = Inventory::WarehouseList($this->getDoctrine()->getManager())[$request->request->get('warehouseId')]['name'];
// $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
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),
"A stack of material Has Arrived at The " . $warehouse_name . " From Supplier: " . $supplier_name . ". The P/O number is " . $po_data['name'] . " .",
'all',
"",
'information',
"",
"Inbound Material"
);
// 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),"Eco is the best",'all','','success',null);
}
return $this->render('ApplicationBundle:pages/inventory/input_forms:material_inward.html.twig',
array(
'page_title' => 'Material Inward',
'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
'expense_details_list_array' => InventoryConstant::$Expense_list_details_array,
'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
"unitList" => Inventory::UnitTypeList($this->getDoctrine()->getManager())
// 'po'=>Inventory::getPurchaseOrderList
)
);
}
public function QualityControlAction(Request $request)
{
$checked_qc_list_flag = 0;
if ($request->query->has('checked_qc_list_flag'))
$checked_qc_list_flag = $request->query->has('checked_qc_list_flag');
if ($request->isMethod('POST')) {
foreach ($request->request->get('qc_checked', []) as $key => $entry) {
$em = $this->getDoctrine()->getManager();
$data = $this->getDoctrine()
->getRepository('ApplicationBundle:MaterialInward')
->findOneBy(
array(
'qcId' => $entry
)
);
if ($request->request->get('approvedQty')[$entry] <= 0) {
$em->remove($data);
$em->flush();
} else {
$data->setApprovedQty($request->request->get('approvedQty')[$entry]);
$data->setRejectedQty($data->getInwardQty() - $request->request->get('approvedQty')[$entry]);
$data->setQcDate(new \DateTime($request->request->get('qcDate')));
$data->setStage(GeneralConstant::STAGE_PENDING_TAG);
$em->flush();
}
//notification
$po_data = Purchase::PurchaseOrderList($this->getDoctrine()->getManager())[$data->getPurchaseOrderId()];
$supplier_id = $po_data['supplier_id'];
$supplier_name = Purchase::GetSupplierList($this->getDoctrine()->getManager())[$supplier_id]['supplier_name'];
$product_name = Inventory::ProductList($this->getDoctrine()->getManager())[$data->getProductId()]['name'];
$qty = $request->request->get('approvedQty')[$entry];
$warehouse_name = Inventory::WarehouseList($this->getDoctrine()->getManager())[$data->getWarehouseId()]['name'];
// $supplier_name=Inv($this->getDoctrine()->getManager())[$request->request->get('warehouseId')];
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),
$qty . " among " . $data->getInwardQty() . " units of " . $product_name . " has passed the Quality Control in " .
$warehouse_name . " From Supplier: " . $supplier_name . ". The P/O number is " . $po_data['name'] . " .",
'all',
"",
'success',
"",
"Quality Control"
);
}
}
return $this->render('ApplicationBundle:pages/inventory/input_forms:qc.html.twig',
array(
'page_title' => 'Quality Control',
'checked_qc_list_flag' => $checked_qc_list_flag,
'warehouse' => Inventory::WarehouseListArray($this->getDoctrine()->getManager()),
'warehouse_indexed' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'supplier' => Inventory::ProductSupplierList($this->getDoctrine()->getManager()),
'supplier_list_array' => Inventory::ProductSupplierListArray($this->getDoctrine()->getManager()),
'po_list_array' => Purchase::PurchaseOrderListArray($this->getDoctrine()->getManager()),
'po_list' => Purchase::PurchaseOrderList($this->getDoctrine()->getManager()),
'product_list' => Inventory::ProductList($this->getDoctrine()->getManager()),
'material_inward' => $this->getDoctrine()
->getRepository('ApplicationBundle:MaterialInward')
->findBy(
array(
'stage' => $checked_qc_list_flag == 0 ? GeneralConstant::STAGE_PENDING : GeneralConstant::STAGE_PENDING_TAG
)
)
// 'po'=>Inventory::getPurchaseOrderList
)
);
}
public function InventoryTransactionViewAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$qry_data = array(
'warehouseId' => [0],
'igId' => [0],
'brandId' => [0],
'categoryId' => [0],
'actionTagId' => [0],
);
$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 = [];
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$print_title = "Inventory Report";
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->isMethod('POST'))
$method = 'POST';
else
$method = 'GET';
{
$data_searched = Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
$request->request, $method,
$request->getSession()->get(UserConstants::USER_LOGIN_ID),
$companyId);
if ($request->query->has('returnJson') || $request->request->has('returnJson')) {
return new JsonResponse(
array(
'success' => true,
// 'page_title' => 'Product Details',
// 'company_data' => $company_data,
'page_title' => 'Inventory Transactions',
'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_products' => Inventory::NewProductFormRelatedData($this->getDoctrine()->getManager()),
'action_tag' => $warehouse_action_list,
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'data_searched' => $data_searched
)
);
} else if ($request->request->get('print_data_enabled') == 1) {
$print_sub_title = "";
return $this->render('ApplicationBundle:pages/inventory/print:print_inventory_data.html.twig',
array(
'page_title' => 'Inventory Report',
'page_header' => 'Report',
'print_title' => $print_title,
'document_type' => 'Journal voucher',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'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' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'data_searched' => $data_searched
)
);
}
}
return $this->render('ApplicationBundle:pages/inventory/report:inventory_transaction_view.html.twig',
array(
'page_title' => 'Inventory Transactions',
'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' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'data_searched' => $data_searched
)
);
}
public function StockConsumptionViewAction(Request $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();
$qry_data = array(
'warehouseId' => [0],
'igId' => [0],
'brandId' => [0],
'categoryId' => [0],
'actionTagId' => [0],
);
$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 = [];
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, 1);
$data = [];
$print_title = "Inventory Report";
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->isMethod('POST'))
$method = 'POST';
else
$method = 'GET';
$post_data = $method == 'POST' ? $request->request : $request->query;
$data_searched = Inventory::GetStockConsumptionData($this->getDoctrine()->getManager(),
$post_data,
$method,
$start_date,
$end_date,
$request->getSession()->get(UserConstants::USER_LOGIN_ID));
if ($post_data->get('print_data_enabled') == 1) {
$print_sub_title = "";
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView('ApplicationBundle:pages/inventory/print:print_stock_consumption.html.twig',
array(
'pdf' => 'true',
'page_title' => 'Inventory Report',
'page_header' => 'Report',
'print_title' => $print_title,
'document_type' => 'Journal voucher',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'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') : '',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'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' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'data_searched' => $data_searched,
'export' => 'all'
)
);
$pdf_response = $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
'orientation' => count($data_searched['query_columns_filter']) > 4 ? 'landscape' : 'portrait',
'no-stop-slow-scripts' => true,
'no-background' => false,
'lowquality' => false,
'encoding' => 'utf-8',
'dpi' => 300,
'image-dpi' => 300,
));
return new Response(
$pdf_response,
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="Stock_Consumption.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_stock_consumption.html.twig',
array(
'page_title' => 'Inventory Report',
'page_header' => 'Report',
'print_title' => $print_title,
'document_type' => 'Journal voucher',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'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') : '',
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'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' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'data_searched' => $data_searched,
'export' => 'all'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/report:stock_consumption.html.twig',
array(
'page_title' => 'Stock Consumption',
'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' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'data_searched' => $data_searched
)
);
}
public function ItemViewAction(Request $request)
{
return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_return.html.twig',
array(
'page_title' => 'Stock Return'
)
);
}
public function ProductViewAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$productData = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $id
)
);
$currInvList = $em->getRepository('ApplicationBundle:InventoryStorage')
->findBy(
array(
'productId' => $id
)
);
$trans_history = $em->getRepository('ApplicationBundle:InvItemTransaction')
->findBy(
array(
'productId' => $id
), array(
'transactionDate' => 'ASC',
'id' => 'ASC'
)
);
$productDataObj = array();
if ($request->isMethod('POST') && $request->request->has('returnJson')) {
$getters = array_filter(get_class_methods($productData), function ($method) {
return 'get' === substr($method, 0, 3);
});
foreach ($getters as $getter) {
if ($getter == 'getGlobalId')
continue;
// if ($getter == 'getId')
// continue;
$Fieldname = str_replace('get', '', $getter);
$productDataObj[$Fieldname] = $productData->{$getter}(); // `foo!`
}
if ($request->request->has('genInfoOnly') && $request->request->get('genInfoOnly') == 1) {
$dataArray = array(
'success' => true,
'page_title' => 'Product Details',
'company_data' => $company_data,
'productData' => $productData,
'productDataObj' => $productDataObj,
'defaultImageAppendUrl' => '/uploads/Products/',
);
} else {
$dataArray = array(
'success' => true,
'page_title' => 'Product Details',
'company_data' => $company_data,
'productData' => $productData,
'productDataObj' => $productDataObj,
'currInvList' => $currInvList,
'trans_history' => $trans_history,
'entityList' => GeneralConstant::$Entity_list_details,
// '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),
'warehouse_action_list' => Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object'),
'warehouseList' => Inventory::WarehouseList($em),
'defaultImageAppendUrl' => '/uploads/Products/',
);
}
return new JsonResponse(
$dataArray
);
}
$dataArray = array(
'page_title' => 'Product Details',
'company_data' => $company_data,
'productData' => $productData,
'currInvList' => $currInvList,
'trans_history' => $trans_history,
'entityList' => GeneralConstant::$Entity_list_details,
// '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),
'warehouse_action_list' => Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object'),
'warehouseList' => Inventory::WarehouseList($em),
);
return $this->render('ApplicationBundle:pages/inventory/view:product_view.html.twig', $dataArray
);
}
public function CheckForProductInWarehouseAction(Request $request, $queryStr = '')
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$data = [
'availableQty' => 0,
'productByCodesArray' => [],
'indRowId' => 0
];
$html = '';
$productByCodeData = [];
if ($request->isMethod('POST')) {
$warehouseId = $request->request->get('warehouseId', 0);
$warehouseActionId = $request->request->get('warehouseActionId', 0);
$productId = $request->request->get('productId', 0);
$indRowId = $request->request->get('indRowId', 0);
$data['indRowId'] = $indRowId;
$inStorage = $em->getRepository('ApplicationBundle:InventoryStorage')
->findBy(
array(
'productId' => $productId,
'warehouseId' => $warehouseId,
'actionTagId' => $warehouseActionId,
'CompanyId' => $companyId,
)
);
foreach ($inStorage as $strg) {
$data['availableQty'] += 1 * $strg->getQty();
}
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')
->findBy(
array(
'productId' => $productId,
'warehouseId' => $warehouseId,
'warehouseActionId' => $warehouseActionId,
'CompanyId' => $companyId,
)
);
foreach ($productByCodeData as $pbc) {
$data['productByCodesArray'][] = array(
'id' => $pbc->getProductByCodeId(),
'productId' => $pbc->getProductId(),
'warehouseId' => $pbc->getWarehouseId(),
'warehouseActionId' => $pbc->getWarehouseActionId(),
// 'sales_code'=>sprintf("%013d",$d['sales_code']),
'sales_code' => str_pad($pbc->getSalesCode(), 13, '0', STR_PAD_LEFT),
// 'sales_code'=>$d['sales_code'],
);
}
return new JsonResponse(array(
'success' => true,
'data' => $data,
)
);
}
return new JsonResponse(
array(
'success' => false,
'data' => $data,
)
);
}
public function ProductByCodeListAjaxAction(Request $request, $queryStr = '')
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$html = '';
$productByCodeData = [];
if ($request->request->has('query') && $queryStr == '')
$queryStr = $request->request->get('queryStr');
$get_kids_sql = "select product_by_code_id id, product_id, warehouse_id, warehouse_action_id,
sales_code ,
serial_no,
imei1,
imei2,
imei3,
imei4
from product_by_code
where ( CONVERT(sales_code,char) like '%" . $queryStr . "%'
or CONVERT(serial_no,char) like '%" . $queryStr . "%'
or CONVERT(imei1,char) like '%" . $queryStr . "%'
or CONVERT(imei2,char) like '%" . $queryStr . "%'
or CONVERT(imei3,char) like '%" . $queryStr . "%'
or CONVERT(imei4,char) like '%" . $queryStr . "%'
) ";
if ($request->query->has('warehouseId'))
$get_kids_sql .= " and warehouse_id=" . $request->query->get('warehouseId') . " ";
if ($request->query->has('position'))
$get_kids_sql .= " and position=" . $request->query->get('position') . " ";
if ($request->query->has('deliveryReceiptId'))
$get_kids_sql .= " and deliveryReceiptId=" . $request->query->get('deliveryReceiptId') . " ";
if ($request->query->has('warehouseActionId'))
$get_kids_sql .= " and warehouse_action_id=" . $request->query->get('warehouseActionId') . " ";
if ($request->query->has('productId'))
$get_kids_sql .= " and product_id=" . $request->query->get('productId') . " ";
$get_kids_sql .= " and company_id=" . $companyId . " limit 25";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$get_kids = $stmt->fetchAll();
if (!empty($get_kids)) {
foreach ($get_kids as $d) {
$dt = array(
'id' => $d['id'],
'productId' => $d['product_id'],
'warehouseId' => $d['warehouse_id'],
'warehouseActionId' => $d['warehouse_action_id'],
// 'sales_code'=>sprintf("%013d",$d['sales_code']),
'sales_code' => str_pad($d['sales_code'], 13, '0', STR_PAD_LEFT),
'serial_no' => str_pad($d['serial_no'], 13, '0', STR_PAD_LEFT),
'imei1' => str_pad($d['imei1'], 13, '0', STR_PAD_LEFT),
'imei2' => str_pad($d['imei2'], 13, '0', STR_PAD_LEFT),
'imei3' => str_pad($d['imei3'], 13, '0', STR_PAD_LEFT),
'imei4' => str_pad($d['imei4'], 13, '0', STR_PAD_LEFT),
// 'sales_code'=>$d['sales_code'],
);
$data[] = $dt;
}
}
// if($request->query->has('returnJson'))
{
return new JsonResponse(
array(
'success' => true,
// 'page_title' => 'Product Details',
// 'company_data' => $company_data,
'data' => $data,
// 'exId'=>$id,
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
}
}
public function selectDataAjaxAction(Request $request, $queryStr = '')
{
$em = $this->getDoctrine()->getManager();
if ($request->request->get('entity_group', 0)) {
$companyId = 0;
$em = $this->getDoctrine()->getManager('company_group');
} else {
if ($request->request->get('appId', 0) != 0) {
$gocEnabled = 0;
if ($this->container->hasParameter('entity_group_enabled'))
$gocEnabled = $this->container->getParameter('entity_group_enabled');
else
$gocEnabled = 1;
if ($gocEnabled == 1) {
$dataToConnect = System::changeDoctrineManagerByAppId(
$this->getDoctrine()->getManager('company_group'),
$gocEnabled,
$request->request->get('appId', 0)
);
if (!empty($dataToConnect)) {
$connector = $this->container->get('application_connector');
$connector->resetConnection(
'default',
$dataToConnect['dbName'],
$dataToConnect['dbUser'],
$dataToConnect['dbPass'],
$dataToConnect['dbHost'],
$reset = true
);
$em = $this->getDoctrine()->getManager();
}
}
}
$companyId = $this->getLoggedUserCompanyId($request);
}
if ($companyId) {
$company_data = [];
// $company_data = Company::getCompanyData($em, $companyId);
} else {
$companyId = 0;
$company_data = [];
}
$data = [];
$data_by_id = [];
$html = '';
$productByCodeData = [];
$setValueArray = [];
$setValue = 0;
$setValueType = 0;// 0 for id , 1 for query
$selectAll = 0;
if ($queryStr == '_EMPTY_')
$queryStr = '';
if ($request->request->has('query'))
$queryStr = $request->request->get('query');
if ($queryStr == '_EMPTY_')
$queryStr = '';
$queryStr = str_replace('_FSLASH_', '/', $queryStr);
if ($queryStr === '#setValue:') {
$queryStr = '';
}
if (!(strpos($queryStr, '#setValue:') === false)) {
$setValueArrayBeforeFilter = explode(',', str_replace('#setValue:', '', $queryStr));
foreach ($setValueArrayBeforeFilter as $svf) {
if ($svf == '_ALL_') {
$selectAll = 1;
$setValueArray = [];
continue;
}
if (is_numeric($svf)) {
$setValueArray[] = ($svf * 1);
$setValue = $svf * 1;
}
}
$queryStr = '';
}
// if (!(strpos($queryStr, '#setValueByQuery:') === false)) {
// $setValueArrayBeforeFilter = explode(',', str_replace('#setValueByQuery:', '', $queryStr));
//
// foreach ($setValueArrayBeforeFilter as $svf) {
// if ($svf == '_ALL_') {
// $selectAll = 1;
// $setValueArray = [];
// continue;
// }
// if (is_numeric($svf)) {
// $setValueArray[] = ($svf * 1);
// $setValue = $svf * 1;
// }
// }
//
// $queryStr = '';
//
//
// }
// $setValue = str_replace('#setValue:','',$queryStr);
$valueField = $request->request->has('valueField') ? $request->request->get('valueField') : 'id';
$itemLimit = $request->request->has('itemLimit') ? $request->request->get('itemLimit') : 25;
$selectorId = $request->request->has('selectorId') ? $request->request->get('selectorId') : '_NONE_';
$textField = $request->request->has('textField') ? $request->request->get('textField') : 'name';
$table = $request->request->has('tableName') ? $request->request->get('tableName') : '';
$isMultiple = $request->request->has('isMultiple') ? $request->request->get('isMultiple') : 0;
$orConditions = $request->request->has('orConditions') ? $request->request->get('orConditions') : [];
$andConditions = $request->request->has('andConditions') ? $request->request->get('andConditions') : [];
$andOrConditions = $request->request->has('andOrConditions') ? $request->request->get('andOrConditions') : [];
$mustConditions = $request->request->has('mustConditions') ? $request->request->get('mustConditions') : [];
$joinTableData = $request->request->has('joinTableData') ? $request->request->get('joinTableData') : [];
$renderTextFormat = $request->request->has('renderTextFormat') ? $request->request->get('renderTextFormat') : '';
$setDataForSingle = $request->request->has('setDataForSingle') ? $request->request->get('setDataForSingle') : 0;
$dataId = $request->request->has('dataId') ? $request->request->get('dataId') : 0;
$lastChildrenOnly = $request->request->has('lastChildrenOnly') ? $request->request->get('lastChildrenOnly') : 0;
$parentIdField = $request->request->has('parentIdField') ? $request->request->get('parentIdField') : 'parent_id';
$skipDefaultCompanyId = $request->request->has('skipDefaultCompanyId') ? $request->request->get('skipDefaultCompanyId') : 1;
$offset = $request->request->has('offset') ? $request->request->get('offset') : 0;
$returnTotalMatchedEntriesFlag = $request->request->has('returnTotalMatched') ? $request->request->get('returnTotalMatched') : 0;
$nextOffset = 0;
$totalMatchedEntries = 0;
$convertToObjectFieldList = $request->request->has('convertToObject') ? $request->request->get('convertToObject') : [];
$convertDateToStringFieldList = $request->request->has('convertDateToStringFieldList') ? $request->request->get('convertDateToStringFieldList') : [];
$orderByConditions = $request->request->has('orderByConditions') ? $request->request->get('orderByConditions') : [];
$convertToUrl = $request->request->has('convertToUrl') ? $request->request->get('convertToUrl') : [];
if (is_string($andConditions)) $andConditions = json_decode($andConditions, true);
if (is_string($orConditions)) $orConditions = json_decode($orConditions, true);
if (is_string($andOrConditions)) $andOrConditions = json_decode($andOrConditions, true);
if (is_string($mustConditions)) $mustConditions = json_decode($mustConditions, true);
if (is_string($joinTableData)) $joinTableData = json_decode($joinTableData, true);
if (is_string($convertToObjectFieldList)) $convertToObjectFieldList = json_decode($convertToObjectFieldList, true);
if (is_string($orderByConditions)) $orderByConditions = json_decode($orderByConditions, true);
if (is_string($convertToUrl)) $convertToUrl = json_decode($convertToUrl, true);
if ($table == '') {
return new JsonResponse(
array(
'success' => false,
// 'page_title' => 'Product Details',
// 'company_data' => $company_data,
'currentTs' => (new \Datetime())->format('U'),
'isMultiple' => $isMultiple,
'setValueArray' => $setValueArray,
'setValue' => $setValue,
'data' => $data,
'dataId' => $dataId,
'selectorId' => $selectorId,
'dataById' => $data_by_id,
'selectedId' => 0,
'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
)
);
}
$restrictionData = array(
// 'table'=>'relevantField in restriction'
'warehouse_action' => 'warehouseActionIds',
'branch' => 'branchIds',
'warehouse' => 'warehouseIds',
'production_process_settings' => 'productionProcessIds',
);
$restrictionIdList = [];
$filterQryForCriteria = "select ";
$selectQry = "";
// $selectQry=" `$table`.* ";
$selectFieldList = $request->request->has('selectFieldList') ? $request->request->get('selectFieldList') : ['*'];
$selectPrefix = $request->request->has('selectPrefix') ? $request->request->get('selectPrefix') : '';
if (is_string($selectFieldList)) $selectFieldList = json_decode($selectFieldList, true);
foreach ($selectFieldList as $selField) {
if ($selectQry != '')
$selectQry .= ", ";
if ($selField == '*')
$selectQry .= " `$table`.$selField ";
else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
if ($selectPrefix == '')
$selectQry .= " count(*) ";
else
$selectQry .= (" count(* ) $selectPrefix" . "_RESULT_COUNT_ ");
} else {
if ($selectPrefix == '')
$selectQry .= " `$table`.`$selField` ";
else
$selectQry .= (" `$table`.`$selField` $selectPrefix" . "$selField ");
}
}
$joinQry = " from $table ";
// $filterQryForCriteria = "select * from $table ";
foreach ($joinTableData as $joinIndex => $joinTableDatum) {
// $conditionStr.=' 1=1 ';
$joinTableName = isset($joinTableDatum['tableName']) ? $joinTableDatum['tableName'] : '=';
$joinTableAlias = $joinTableName . '_' . $joinIndex;
$joinTablePrimaryField = isset($joinTableDatum['joinFieldPrimary']) ? $joinTableDatum['joinFieldPrimary'] : ''; //field of main table
$joinTableOnField = isset($joinTableDatum['joinOn']) ? $joinTableDatum['joinOn'] : ''; //field of joining table
$fieldJoinType = isset($joinTableDatum['fieldJoinType']) ? $joinTableDatum['fieldJoinType'] : '=';
$tableJoinType = isset($joinTableDatum['tableJoinType']) ? $joinTableDatum['tableJoinType'] : 'join';//or inner join
$selectFieldList = isset($joinTableDatum['selectFieldList']) ? $joinTableDatum['selectFieldList'] : ['*'];
$selectPrefix = isset($joinTableDatum['selectPrefix']) ? $joinTableDatum['selectPrefix'] : '';
$joinAndConditions = isset($joinTableDatum['joinAndConditions']) ? $joinTableDatum['joinAndConditions'] : [];
if (is_string($joinAndConditions)) $joinAndConditions = json_decode($joinAndConditions, true);
foreach ($selectFieldList as $selField) {
if ($selField == '*')
$selectQry .= ", `$joinTableAlias`.$selField ";
else if ($selField == 'count(*)' || $selField == '_RESULT_COUNT_') {
if ($selectPrefix == '')
$selectQry .= ", count(`$joinTableAlias`." . $joinTableOnField . ") ";
else
$selectQry .= (", count(`$joinTableAlias`." . $joinTableOnField . ") $selectPrefix" . "_RESULT_COUNT_ ");
} else {
if ($selectPrefix == '')
$selectQry .= ", `$joinTableAlias`.`$selField` ";
else
$selectQry .= (", `$joinTableAlias`.`$selField` $selectPrefix" . "$selField ");
}
}
$joinQry .= " $tableJoinType $joinTableName $joinTableAlias on ";
// if($joinTablePrimaryField!='')
// $joinQry .= " `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
// $joinAndString = '';
$joinAndString = '';
if ($joinTablePrimaryField != '')
$joinAndString .= " `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
foreach ($joinAndConditions as $andCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
$cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($joinAndString != '')
$joinAndString .= " and ";
if ($ctype == 'like') {
$joinAndString .= ("`$joinTableAlias`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinAndString != '')
$joinAndString .= " and ";
$joinAndString .= ("`$joinTableAlias`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$joinAndString .= ("`$joinTableAlias`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($joinAndString != '')
$joinAndString .= " and ";
$joinAndString .= ("`$joinTableAlias`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$joinAndString .= " ( ";
if (in_array('null', $cvalue)) {
$joinAndString .= " `$joinTableAlias`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
if (in_array('', $cvalue)) {
$joinAndString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
$joinAndString .= "`$joinTableAlias`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$joinAndString .= "`$joinTableAlias`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
if (in_array('', $cvalue)) {
$joinAndString .= "`$joinTableAlias`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$joinAndString .= " and ";
}
$joinAndString .= "`$joinTableAlias`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
// if (!(strpos($cvalue, '.') === false) && !(strpos($cvalue, '_PRIMARY_TABLE_') === false)) {
// $fullCfieldArray = explode('.', $cfield);
// $aliasInCondition = $fullCfieldArray[0];
// $cfield = $fullCfieldArray[1];
// }
if ($cvalue == 'null' || $cvalue == 'Null')
$joinAndString .= "`$joinTableAlias`.$cfield is null ";
else
$joinAndString .= "`$joinTableAlias`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$joinAndString .= "`$joinTableAlias`.$cfield is not null ";
else
$joinAndString .= "`$joinTableAlias`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$joinAndString .= "`$joinTableAlias`.$cfield $ctype '" . $cvalue . "' ";
else
$joinAndString .= "`$joinTableAlias`.$cfield $ctype " . $cvalue . " ";
}
}
}
// if ($joinAndString != '') {
// if ($conditionStr != '')
// $conditionStr .= (" and (" . $joinAndString . ") ");
// else
// $conditionStr .= (" (" . $joinAndString . ") ");
// }
if ($joinAndString != '')
$joinQry .= $joinAndString;
// $joinQry .= " `$joinTableAlias`.`$joinTableOnField` $fieldJoinType `$table`.`$joinTablePrimaryField` ";
}
$filterQryForCriteria .= $selectQry;
$filterQryForCriteria .= $joinQry;
if ($skipDefaultCompanyId == 0 && $companyId != 0 && !$request->request->get('entity_group', 0))
$filterQryForCriteria .= " where `$table`.`company_id`=" . $companyId . " ";
else
$filterQryForCriteria .= " where 1=1 ";
$conditionStr = "";
if (isset($restrictionData[$table])) {
$userRestrictionData = Users::getUserApplicationAccessSettings($em, $request->getSession()->get(UserConstants::USER_ID))['options'];
if (isset($userRestrictionData[$restrictionData[$table]])) {
$restrictionIdList = $userRestrictionData[$restrictionData[$table]];
if ($restrictionIdList == null)
$restrictionIdList = [];
}
if (!empty($restrictionIdList))
$conditionStr .= " `$table`.$valueField in (" . implode(',', $restrictionIdList) . ") ";
}
$aliasInCondition = $table;
if (!empty($setValueArray) || $selectAll == 1) {
if (!empty($setValueArray)) {
if ($conditionStr != '')
$conditionStr .= " and ";
$conditionStr .= " `$aliasInCondition`.$valueField in (" . implode(',', $setValueArray) . ") ";
}
} else {
$andString = '';
foreach ($andConditions as $andCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($andCondition['type']) ? $andCondition['type'] : '=';
$cfield = isset($andCondition['field']) ? $andCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andCondition['value']) ? $andCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($andString != '')
$andString .= " and ";
if ($ctype == 'like') {
$andString .= ("`$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andString != '')
$andString .= " and ";
$andString .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$andString .= ("`$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andString != '')
$andString .= " and ";
$andString .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$andString .= " ( ";
if (in_array('null', $cvalue)) {
$andString .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andString .= " and ";
}
if (in_array('', $cvalue)) {
$andString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andString .= " and ";
}
$andString .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
if (in_array('null', $cvalue)) {
$andString .= "`$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andString .= " and ";
}
if (in_array('', $cvalue)) {
$andString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andString .= " and ";
}
$andString .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andString .= "`$aliasInCondition`.$cfield is null ";
else
$andString .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andString .= "`$aliasInCondition`.$cfield is not null ";
else
$andString .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$andString .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$andString .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($andString != '') {
if ($conditionStr != '')
$conditionStr .= (" and (" . $andString . ") ");
else
$conditionStr .= (" (" . $andString . ") ");
}
$orString = '';
foreach ($orConditions as $orCondition) {
$ctype = isset($orCondition['type']) ? $orCondition['type'] : '=';
$cfield = isset($orCondition['field']) ? $orCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($orCondition['value']) ? $orCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($orString != '')
$orString .= " or ";
if ($ctype == 'like') {
$orString .= ("`$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($orString != '')
$orString .= " or ";
$orString .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$orString .= ("`$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($orString != '')
$orString .= " or ";
$orString .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'not_in') {
$orString .= " ( ";
if (in_array('null', $cvalue)) {
$orString .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$orString .= " or ";
}
if (in_array('', $cvalue)) {
$orString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$orString .= " or ";
}
$orString .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'in') {
$orString .= " ( ";
if (in_array('null', $cvalue)) {
$orString .= " `$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$orString .= " or ";
}
if (in_array('', $cvalue)) {
$orString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$orString .= " or ";
}
$orString .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$orString .= "`$aliasInCondition`.$cfield is null ";
else
$orString .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$orString .= "`$aliasInCondition`.$cfield is not null ";
else
$orString .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$orString .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$orString .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($orString != '') {
if ($conditionStr != '')
$conditionStr .= (" or (" . $orString . ") ");
else
$conditionStr .= (" (" . $orString . ") ");
}
$andOrString = '';
foreach ($andOrConditions as $andOrCondition) {
$ctype = isset($andOrCondition['type']) ? $andOrCondition['type'] : '=';
$cfield = isset($andOrCondition['field']) ? $andOrCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($andOrCondition['value']) ? $andOrCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($andOrString != '')
$andOrString .= " or ";
if ($ctype == 'like') {
$andOrString .= (" `$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andOrString != '')
$andOrString .= " or ";
$andOrString .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
} else if ($ctype == 'not like') {
$andOrString .= (" `$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($andOrString != '')
$andOrString .= " or ";
$andOrString .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'in') {
$andOrString .= " ( ";
if (in_array('null', $cvalue)) {
$andOrString .= " `$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (in_array('', $cvalue)) {
$andOrString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (!empty($cvalue))
$andOrString .= " `$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
else
$andOrString .= " ) ";
} else if ($ctype == 'not_in') {
$andOrString .= " ( ";
if (in_array('null', $cvalue)) {
$andOrString .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (in_array('', $cvalue)) {
$andOrString .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$andOrString .= " or ";
}
if (!empty($cvalue))
$andOrString .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
else
$andOrString .= " ) ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andOrString .= "`$aliasInCondition`.$cfield is null ";
else
$andOrString .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$andOrString .= "`$aliasInCondition`.$cfield is not null ";
else
$andOrString .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$andOrString .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$andOrString .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($andOrString != '') {
if ($conditionStr != '')
$conditionStr .= (" and (" . $andOrString . ") ");
else
$conditionStr .= (" (" . $andOrString . ") ");
}
}
$mustStr = '';
///now must conditions
foreach ($mustConditions as $mustCondition) {
// $conditionStr.=' 1=1 ';
$ctype = isset($mustCondition['type']) ? $mustCondition['type'] : '=';
$cfield = isset($mustCondition['field']) ? $mustCondition['field'] : '';
$aliasInCondition = $table;
if (!(strpos($cfield, '.') === false)) {
$fullCfieldArray = explode('.', $cfield);
$aliasInCondition = $fullCfieldArray[0];
$cfield = $fullCfieldArray[1];
}
$cvalue = isset($mustCondition['value']) ? $mustCondition['value'] : $queryStr;
if ($cfield != '' && $cvalue != '_EMPTY_' && $cvalue != '' && $cvalue != '#setValue:') {
if ($mustStr != '')
$mustStr .= " and ";
if ($ctype == 'like') {
$mustStr .= ("(`$aliasInCondition`.$cfield like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($mustStr != '')
$mustStr .= " or ";
$mustStr .= ("`$aliasInCondition`.$cfield like '%" . $word . "%' ");
}
$mustStr .= " )";
} else if ($ctype == 'not like') {
$mustStr .= ("`$aliasInCondition`.$cfield not like '%" . $cvalue . "%' ");
$wordsBySpaces = explode(' ', $cvalue);
foreach ($wordsBySpaces as $word) {
if ($mustStr != '')
$mustStr .= " and ";
$mustStr .= ("`$aliasInCondition`.$cfield not like '%" . $word . "%' ");
}
} else if ($ctype == 'in') {
$mustStr .= " ( ";
if (in_array('null', $cvalue)) {
$mustStr .= " `$aliasInCondition`.$cfield is null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$mustStr .= " or ";
}
if (in_array('', $cvalue)) {
$mustStr .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$mustStr .= " or ";
}
$mustStr .= "`$aliasInCondition`.$cfield in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == 'not_in') {
$mustStr .= " ( ";
if (in_array('null', $cvalue)) {
$mustStr .= " `$aliasInCondition`.$cfield is not null";
$cvalue = array_diff($cvalue, ['null']);
if (!empty($cvalue))
$mustStr .= " and ";
}
if (in_array('', $cvalue)) {
$mustStr .= "`$aliasInCondition`.$cfield = '' ";
$cvalue = array_diff($cvalue, ['']);
if (!empty($cvalue))
$mustStr .= " and ";
}
$mustStr .= "`$aliasInCondition`.$cfield not in (" . implode(',', $cvalue) . ") ) ";
} else if ($ctype == '=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$mustStr .= "`$aliasInCondition`.$cfield is null ";
else
$mustStr .= "`$aliasInCondition`.$cfield = $cvalue ";
} else if ($ctype == '!=') {
if ($cvalue == 'null' || $cvalue == 'Null')
$mustStr .= "`$aliasInCondition`.$cfield is not null ";
else
$mustStr .= "`$aliasInCondition`.$cfield != $cvalue ";
} else {
if (is_string($cvalue))
$mustStr .= "`$aliasInCondition`.$cfield $ctype '" . $cvalue . "' ";
else
$mustStr .= "`$aliasInCondition`.$cfield $ctype " . $cvalue . " ";
}
}
}
if ($mustStr != '') {
if ($conditionStr != '')
$conditionStr .= (" and (" . $mustStr . ") ");
else
$conditionStr .= (" (" . $mustStr . ") ");
}
if ($conditionStr != '')
$filterQryForCriteria .= (" and (" . $conditionStr . ") ");
if ($lastChildrenOnly == 1) {
if ($filterQryForCriteria != '')
$filterQryForCriteria .= ' and';
$filterQryForCriteria .= "`$table`.`$valueField` not in ( select distinct $parentIdField from $table)";
}
if (!empty($orderByConditions)) {
$filterQryForCriteria .= " order by ";
$fone = 1;
foreach ($orderByConditions as $orderByCondition) {
if ($fone != 1) {
$filterQryForCriteria .= " , ";
}
if (isset($orderByCondition['valueList'])) {
if (is_string($orderByCondition['valueList'])) $orderByCondition['valueList'] = json_decode($orderByCondition['valueList'], true);
if ($orderByCondition['valueList'] == null)
$orderByCondition['valueList'] = [];
$filterQryForCriteria .= " field(" . $orderByCondition['field'] . "," . implode(',', $orderByCondition['valueList']) . "," . $orderByCondition['field'] . ") " . $orderByCondition['sortType'] . " ";
} else
$filterQryForCriteria .= " " . $orderByCondition['field'] . " " . $orderByCondition['sortType'] . " ";
$fone = 0;
}
}
if ($returnTotalMatchedEntriesFlag == 1) {
// $stmt = $em->getConnection()->prepare($get_kids_sql);
// $stmt->execute();
// $get_kids = $stmt->fetchAll();
}
if ($filterQryForCriteria != '')
if (!empty($setValueArray) || $selectAll == 1) {
} else {
if ($itemLimit != '_ALL_')
$filterQryForCriteria .= " limit $offset, $itemLimit ";
else
$filterQryForCriteria .= " limit $offset, 18446744073709551615 ";
}
$get_kids_sql = $filterQryForCriteria;
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$get_kids = $stmt->fetchAll();
$selectedId = 0;
if ($table == 'warehouse_action') {
if (empty($get_kids)) {
$get_kids_sql_2 = "select * from warehouse_action";
$stmt = $em->getConnection()->prepare($get_kids_sql_2);
$stmt->execute();
$get_kids2 = $stmt->fetchAll();
if (empty($get_kids2))
$get_kids = GeneralConstant::$warehouse_action_list;
}
}
if (!empty($get_kids)) {
$nextOffset = $offset + count($get_kids);
$nextOffset++;
foreach ($get_kids as $pa) {
if (!empty($setValueArray) && $selectAll == 0) {
if (!in_array($pa[$valueField], $setValueArray))
continue;
}
if (!empty($restrictionIdList)) {
if (!in_array($pa[$valueField], $restrictionIdList))
continue;
}
if ($selectAll == 1) {
$setValueArray[] = $pa[$valueField];
$setValue = $pa[$valueField];
} else if (count($get_kids) == 1 && $setDataForSingle == 1) {
$setValueArray[] = $pa[$valueField];
$setValue = $pa[$valueField];
}
if ($valueField != '')
$pa['value'] = $pa[$valueField];
$renderedText = $renderTextFormat;
$compare_array = [];
if ($renderTextFormat != '') {
$renderedText = $renderTextFormat;
$compare_arrayFull = [];
$compare_array = [];
$toBeReplacedData = array(// 'curr'=>'tobereplaced'
);
preg_match_all("/__\w+__/", $renderedText, $compare_arrayFull);
if (isset($compare_arrayFull[0]))
$compare_array = $compare_arrayFull[0];
// $compare_array= preg_split("/__\w+__/",$renderedText);
foreach ($compare_array as $cmpdt) {
$tbr = str_replace("__", "", $cmpdt);
if ($tbr != '') {
if (isset($pa[$tbr])) {
if ($pa[$tbr] == null)
$renderedText = str_replace($cmpdt, '', $renderedText);
else
$renderedText = str_replace($cmpdt, $pa[$tbr], $renderedText);
} else {
$renderedText = str_replace($cmpdt, '', $renderedText);
}
}
}
}
$pa['rendered_text'] = $renderedText;
$pa['text'] = ($textField != '' ? $pa[$textField] : '');
// $pa['compare_array'] = $compare_array;
foreach ($convertToObjectFieldList as $convField) {
if (isset($pa[$convField])) {
$taA = json_decode($pa[$convField], true);
if ($taA == null) $taA = [];
$pa[$convField] = $taA;
} else {
$pa[$convField] = [];
}
}
foreach ($convertDateToStringFieldList as $convField) {
if (is_array($convField)) {
$fld = $convField['field'];
$frmt = isset($convField['format']) ? $convField['format'] : 'Y-m-d H:i:s';
} else {
$fld = $convField;
$frmt = 'Y-m-d H:i:s';
}
if (isset($pa[$fld])) {
$taA = new \DateTime($pa[$fld]);
$pa[$fld] = $taA->format($frmt);
}
}
foreach ($convertToUrl as $convField) {
$fld = $convField;
if (isset($pa[$fld])) {
$pa[$fld] =
$this->generateUrl(
$pa[$fld], [
// 'refRoute' => $refRoute
], UrlGenerator::ABSOLUTE_URL
);
}
}
$pa['currentTs'] = (new \Datetime())->format('U');
$data[] = $pa;
if ($valueField != '') {
$data_by_id[$pa[$valueField]] = $pa;
$selectedId = $pa[$valueField];
}
}
}
// if($request->query->has('returnJson'))
{
return new JsonResponse(
array(
'success' => true,
'data' => $data,
'tableName' => $table,
'setValue' => $setValue,
'currentTs' => (new \Datetime())->format('U'),
'restrictionIdList' => $restrictionIdList,
'andConditions' => $andConditions,
'queryStr' => $queryStr,
'isMultiple' => $isMultiple,
'nextOffset' => $nextOffset,
'totalMatchedEntries' => $totalMatchedEntries,
'selectorId' => $selectorId,
'setValueArray' => $setValueArray,
'conditionStr' => $conditionStr,
// 'andStr' => $andString,
// 'andOrStr' => $andOrString,
'dataById' => $data_by_id,
'selectedId' => $selectedId,
'dataId' => $dataId,
'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
)
);
}
}
public function updatePlanningItemSequenceAction(Request $request, $queryStr = '')
{
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare("select `id` , parent_id, sequence from planning_item where sequence is null
ORDER BY parent_id ASC, id ASC
");
$stmt->execute();
$query_output = $stmt->fetchAll();
foreach ($query_output as $dupe) {
System::updatePlanningItemSequence($em, $dupe["id"]);
}
System::updatePlanningItemSequence(
$em,
$request->request->get('planningItemId', 0),
$request->request->get('assignType', '_ASSIGN_') ///can be _MOVE_UP_ or _MOVE_DOWN_
);
// if($request->query->has('returnJson'))
return new JsonResponse(
array(
'success' => true,
'data' => [],
)
);
}
public function insertDataAjaxAction(Request $request, $queryStr = '')
{
$em = $this->getDoctrine()->getManager();
// if($request->query->has('big_data_test'))
// {
// for($t=0;$t<$request->request->get('big_data_test',10000);$t++) {
// $em = $this->getDoctrine()->getManager('company_group');
// $NOTIFICATION = new EntityNotification();
// $NOTIFICATION->setAppId(1);
// $NOTIFICATION->setCompanyId(0);
// $NOTIFICATION->setCompanyId(0);
// $NOTIFICATION->setBody('Test Description'.$t);
// $NOTIFICATION->setTitle('Test Title'.$t);
// $NOTIFICATION->setExpireTs(0);
// $NOTIFICATION->setIsBuddybee(0);
// $NOTIFICATION->setType(0);
// $em->persist($NOTIFICATION);
// $em->flush();
// }
//
// return new JsonResponse(
// array(
// 'success' => true,
// 'data' => [],
//
//
// )
// );
//
//
// }
if ($request->request->get('entity_group', 0)) {
$companyId = 0;
$em = $this->getDoctrine()->getManager('company_group');
} else
$companyId = $this->getLoggedUserCompanyId($request);
if ($companyId) {
$company_data = [];
// $company_data = Company::getCompanyData($em, $companyId);
} else {
$companyId = 0;
$company_data = [];
}
// $theEntity= new EntityNotification();
// $entityName = 'EntityNotification';
//
// $className='\\CompanyGroupBundle\\Entity\\'.$entityName;
//
//
// $theEntity= new $className();
$dataToAdd = $request->request->has('dataToAdd') ? $request->request->get('dataToAdd') : [];
if (is_string($dataToAdd)) $dataToAdd = json_decode($dataToAdd, true);
if ($dataToAdd == null) $dataToAdd = [];
$dataToRemove = $request->request->has('dataToRemove') ? $request->request->get('dataToRemove') : [];
if (is_string($dataToRemove)) $dataToAdd = json_decode($dataToRemove, true);
if ($dataToRemove == null) $dataToRemove = [];
$relData = [];
if (is_string($dataToAdd)) $dataToAdd = json_decode($dataToAdd, true);
$updatedDataList = [];
foreach ($dataToAdd as $dataInd => $dat) {
$entityName = $dat['entityName'];
$idField = $dat['idField'];
$findByField = isset($dat['findByField']) ? $dat['findByField'] : '';
$findByValue = isset($dat['findByValue']) ? $dat['findByValue'] : '';
$returnRefIndex = $dat['returnRefIndex'];
$findById = $dat['findId'];
$dataFields = isset($dat['dataFields']) ? $dat['dataFields'] : [];
$noCreation = isset($dat['noCreation']) ? $dat['noCreation'] : 0;
$additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
$preAdditionalSql = isset($dat['preAdditionalSql']) ? $dat['preAdditionalSql'] : '';
if ($preAdditionalSql != '') {
// if ($entityName == 'PlanningItem') {
//
// $stmt='select disctinct parent_id from planning_item;';
// $stmt->execute();
// $get_kids = $stmt->fetchAll();
// $p_ids=[];
// foreach($get_kids as $g)
// {
// $p_ids[]=$g['parent_id'];
// }
//
//
//
$stmt = $em->getConnection()->prepare($preAdditionalSql);
$stmt->execute();
$stmt->closeCursor();
//
//
}
if ($entityName == 'PlanningItem') {
$stmt = $em->getConnection()->prepare("select `id` , parent_id, sequence from planning_item where sequence is null
ORDER BY parent_id ASC, id ASC
");
$stmt->execute();
$query_output = $stmt->fetchAll();
foreach ($query_output as $dupe) {
System::updatePlanningItemSequence($em, $dupe["id"]);
}
}
$className = ($request->request->get('entity_group', 0) ? '\\CompanyGroupBundle\\Entity\\' : '\\ApplicationBundle\\Entity\\') . $entityName;
if (
($findById == 0 || $findById == '_NA_') && $findByField == '' && $noCreation == 0
) {
$theEntity = new $className();
// $theEntity= new EntityNotification();
} else {
if ($findByField != '') {
$theEntity = $em->getRepository(($request->request->get('entity_group', 0) ? 'CompanyGroupBundle:' : 'ApplicationBundle:') . $entityName)->findOneBy(
array
(
$findByField => $findByValue,
)
);
} else {
$theEntity = $em->getRepository(($request->request->get('entity_group', 0) ? 'CompanyGroupBundle:' : 'ApplicationBundle:') . $entityName)->findOneBy(
array
(
$idField => $findById,
)
);
}
}
if (!$theEntity && $noCreation == 0)
$theEntity = new $className();
foreach ($dataFields as $dt) {
$setMethod = 'set' . ucfirst($dt['field']);
$getMethod = 'get' . ucfirst($dt['field']);
$type = isset($dt['type']) ? $dt['type'] : '_VALUE_';
$action = isset($dt['action']) ? $dt['action'] : '_REPLACE_';
if (method_exists($theEntity, $setMethod)) {
$oldValue = $theEntity->{$getMethod}();
$newValue = $oldValue;
if ($type == '_VALUE_') {
$newValue = $dt['value'];
}
if ($type == '_DECIMAL_') {
$newValue = 1 * $dt['value'];
}
if ($type == '_DATE_') {
$newValue = new \DateTime($dt['value']);
}
if ($type == '_ARRAY_') {
$oldValue = json_decode($oldValue);
if ($oldValue == null) $oldValue = [];
if ($action == '_REPLACE_') {
$newValue = json_encode($dt['value']);
}
if ($action == '_APPEND_') {
$newValue = array_merge($oldValue, array_values(array_diff([$dt['value']], $oldValue)));
}
if ($action == '_MERGE_') {
$newValue = array_merge($oldValue, array_values(array_diff($dt['value'], $oldValue)));
}
if ($action == '_EXCLUDE_') {
$newValue = array_values(array_diff($oldValue, [$dt['value']]));
}
if ($action == '_EXCLUDE_ARRAY_') {
$newValue = array_values(array_diff($oldValue, $dt['value']));
}
$newValue = json_encode($newValue);
}
$theEntity->{$setMethod}($newValue); // `foo!`
// $theEntity->setCompletionPercentage(78); // `foo!`
}
}
if ($additionalSql != '') {
// if ($entityName == 'PlanningItem') {
//
// $stmt='select disctinct parent_id from planning_item;';
// $stmt->execute();
// $get_kids = $stmt->fetchAll();
// $p_ids=[];
// foreach($get_kids as $g)
// {
// $p_ids[]=$g['parent_id'];
// }
//
//
//
$stmt = $em->getConnection()->prepare($additionalSql);
$stmt->execute();
$stmt->closeCursor();
//
//
}
if (($findById == 0 || $findById == '_NA_') && $noCreation == 0) {
$em->persist($theEntity);
$em->flush();
$getMethod = 'get' . ucfirst($idField);
$relData[$returnRefIndex] = $theEntity->{$getMethod}();
} else if ($theEntity) {
$em->flush();
$getMethod = 'get' . ucfirst($idField);
$relData[$returnRefIndex] = $theEntity->{$getMethod}();
}
if ($entityName == 'PlanningItem') {
$stmt = $em->getConnection()->prepare('select distinct parent_id from planning_item;');
$stmt->execute();
$get_kids = $stmt->fetchAll();
$p_ids = [];
foreach ($get_kids as $g) {
$p_ids[] = $g['parent_id'];
}
$stmt = $em->getConnection()->prepare('UPDATE planning_item d SET d.`has_child` =0 WHERE d.id NOT IN (' . implode(',', $p_ids) . ');
UPDATE planning_item d SET d.`has_child` =1 WHERE d.id IN (' . implode(',', $p_ids) . ')');
$stmt->execute();
$stmt->closeCursor();
$updatedData = System::updatePlanningItemSequence($em, $theEntity->getId());
$theEntity = $updatedData['primaryOne'];
$theEntityUpdated = $theEntity;
if ($theEntityUpdated->getEntryType() == 4)///cashflow
{
MiscActions::AddCashFlowProjection($em, 0, [
'planningItemId' => $theEntityUpdated->getId(),
'fundRequisitionId' => 0,
'concernedPersonId' => 0,
'type' => 1, //exp
'subType' => 1, //1== khoroch hobe 2: ashbe
'cashFlowType' => 1, //2== RCV /in 1: Payment/out
'creationType' => 1, //auto
'amountType' => 1, //fund
'cashFlowAmount' => 0,
'expAstAmount' => 0,
'accumulatedCashFlowAmount' => 0,
'accumulatedCashFlowBalance' => 0,
'accumulatedExpAstAmount' => 0,
'relevantExpAstHeadId' => 0,
'balancingHeadId' => 0,
'cashFlowHeadId' => 0,
'cashFlowHeadType' => 1,
'relevantProductIds' => [],
'reminderDateTs' => 0,
'cashFlowDateTs' => 0,
'expAstRealizationDateTs' => 0,
]);
}
}
else if ($entityName == 'TaskLog') {
$session = $request->getSession();
if ($theEntity) {
$empId = $session->get(UserConstants::USER_EMPLOYEE_ID, 0);
$currTime = new \DateTime();
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
);
$positionsArray = [
array(
'employeeId' => $empId,
'userId' => $session->get(UserConstants::USER_ID, 0),
'sysUserId' => $session->get(UserConstants::USER_ID, 0),
'timeStamp' => $currTime->format(DATE_ISO8601),
'lat' => 23.8623834,
'lng' => 90.3979294,
'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING,
// 'userId'=>$session->get(UserConstants::USER_ID, 0),
)
];
if (is_string($positionsArray)) $positionsArray = json_decode($positionsArray, true);
if ($positionsArray == null) $positionsArray = [];
$dataByAttId = [];
$workPlaceType = '_UNSET_';
foreach ($positionsArray as $findex => $d) {
$sysUserId = 0;
$userId = 0;
$empId = 0;
$dtTs = 0;
$timeZoneStr = '+0000';
if (isset($d['employeeId'])) $empId = $d['employeeId'];
if (isset($d['userId'])) $userId = $d['userId'];
if (isset($d['sysUserId'])) $sysUserId = $d['sysUserId'];
if (isset($d['tsMilSec'])) {
$dtTs = ceil((1 * $d['tsMilSec']) / 1000);
}
if ($dtTs == 0) {
$currTsTime = new \DateTime();
$dtTs = $currTsTime->format('U');
} else {
$currTsTime = new \DateTime('@' . $dtTs);
}
$currTsTime->setTimezone(new \DateTimeZone('UTC'));
$attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' . $timeZoneStr);
$EmployeeAttendance = $this->getDoctrine()
->getRepository(EmployeeAttendance::class)
->findOneBy(array('employeeId' => $empId, 'date' => $attDate));
if (!$EmployeeAttendance) {
$d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
$positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
$EmployeeAttendance = new EmployeeAttendance;
} else {
if ($EmployeeAttendance->getCurrentLocation() == 'out') {
$d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
$positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN;
} else {
$d['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
$positionsArray[$findex]['markerId'] = HumanResourceConstant::ATTENDANCE_MARKER_GENERAL_TRACKING;
}
}
$attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, $request, $EmployeeAttendance, $attDate, $dtTs, $timeZoneStr, $d['markerId']);
if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_IN) {
$workPlaceType = '_STATIC_';
}
if (!isset($dataByAttId[$attendanceInfo->getId()]))
$dataByAttId[$attendanceInfo->getId()] = array(
'attendanceInfo' => $attendanceInfo,
'empId' => $empId,
'lat' => 0,
'lng' => 0,
'address' => 0,
'sysUserId' => $sysUserId,
'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'positionArray' => []
);
$posData = array(
'ts' => $dtTs,
'lat' => $d['lat'],
'lng' => $d['lng'],
'marker' => $d['markerId'],
'src' => 2,
);
$posDataArray = array(
$dtTs,
$d['lat'],
$d['lng'],
$d['markerId'],
2
);
$dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
//this markerId will be calclulted and modified to check if user is in our out of office/workplace later
$dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
$dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
$dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat']; //for last lat lng etc
$dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng']; //for last lat lng etc
if (isset($d['address']))
$dataByAttId[$attendanceInfo->getId()]['address'] = $d['address']; //for last lat lng etc
// $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
}
$response = array(
'success' => true,
);
foreach ($dataByAttId as $attInfoId => $d) {
$response = HumanResource::setAttendanceLogFlutterApp($em,
$d['empId'],
$d['sysUserId'],
$d['companyId'],
$d['appId'],
$request,
$d['attendanceInfo'],
$options,
$d['positionArray'],
$d['lat'],
$d['lng'],
$d['address'],
$d['markerId']
);
}
$session->set(UserConstants::USER_CURRENT_TASK_ID, $theEntity->getId());
$session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID, $theEntity->getPlanningItemId());
}
else {
$session->set(UserConstants::USER_CURRENT_TASK_ID, 0);
$session->set(UserConstants::USER_CURRENT_PLANNING_ITEM_ID, 0);
$empId = $session->get(UserConstants::USER_EMPLOYEE_ID, 0);
$currTime = new \DateTime();
$options = array(
'notification_enabled' => $this->container->getParameter('notification_enabled'),
'notification_server' => $this->container->getParameter('notification_server'),
);
$positionsArray = [
array(
'employeeId' => $empId,
'userId' => $session->get(UserConstants::USER_ID, 0),
'sysUserId' => $session->get(UserConstants::USER_ID, 0),
'timeStamp' => $currTime->format(DATE_ISO8601),
'lat' => 23.8623834,
'lng' => 90.3979294,
'markerId' => HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT,
// 'userId'=>$session->get(UserConstants::USER_ID, 0),
)
];
if (is_string($positionsArray)) $positionsArray = json_decode($positionsArray, true);
if ($positionsArray == null) $positionsArray = [];
$dataByAttId = [];
$workPlaceType = '_UNSET_';
foreach ($positionsArray as $findex => $d) {
$sysUserId = 0;
$userId = 0;
$empId = 0;
$dtTs = 0;
$timeZoneStr = '+0000';
if (isset($d['employeeId'])) $empId = $d['employeeId'];
if (isset($d['userId'])) $userId = $d['userId'];
if (isset($d['sysUserId'])) $sysUserId = $d['sysUserId'];
if (isset($d['tsMilSec'])) {
$dtTs = ceil((1 * $d['tsMilSec']) / 1000);
}
if ($dtTs == 0) {
$currTsTime = new \DateTime();
$dtTs = $currTsTime->format('U');
} else {
$currTsTime = new \DateTime('@' . $dtTs);
}
$currTsTime->setTimezone(new \DateTimeZone('UTC'));
$attDate = new \DateTime($currTsTime->format('Y-m-d') . ' 00:00:00' . $timeZoneStr);
$EmployeeAttendance = $this->getDoctrine()
->getRepository(EmployeeAttendance::class)
->findOneBy(array('employeeId' => $empId, 'date' => $attDate));
if (!$EmployeeAttendance) {
continue;
} else {
}
$attendanceInfo = HumanResource::StoreAttendance($em, $empId, $sysUserId, $request, $EmployeeAttendance, $attDate, $dtTs, $timeZoneStr, $d['markerId']);
if ($d['markerId'] == HumanResourceConstant::ATTENDANCE_MARKER_CLOCK_OUT) {
$workPlaceType = '_STATIC_';
}
if (!isset($dataByAttId[$attendanceInfo->getId()]))
$dataByAttId[$attendanceInfo->getId()] = array(
'attendanceInfo' => $attendanceInfo,
'empId' => $empId,
'lat' => 0,
'lng' => 0,
'address' => 0,
'sysUserId' => $sysUserId,
'companyId' => $request->getSession()->get(UserConstants::USER_COMPANY_ID),
'appId' => $request->getSession()->get(UserConstants::USER_APP_ID),
'positionArray' => []
);
$posData = array(
'ts' => $dtTs,
'lat' => $d['lat'],
'lng' => $d['lng'],
'marker' => $d['markerId'],
'src' => 2,
);
$posDataArray = array(
$dtTs,
$d['lat'],
$d['lng'],
$d['markerId'],
2
);
$dataByAttId[$attendanceInfo->getId()]['markerId'] = $d['markerId'];
//this markerId will be calclulted and modified to check if user is in our out of office/workplace later
$dataByAttId[$attendanceInfo->getId()]['attendanceInfo'] = $attendanceInfo;
$dataByAttId[$attendanceInfo->getId()]['positionArray'][] = $posData;
$dataByAttId[$attendanceInfo->getId()]['lat'] = $d['lat']; //for last lat lng etc
$dataByAttId[$attendanceInfo->getId()]['lng'] = $d['lng']; //for last lat lng etc
if (isset($d['address']))
$dataByAttId[$attendanceInfo->getId()]['address'] = $d['address']; //for last lat lng etc
// $dataByAttId[$attendanceInfo->getId()]['positionArray'][]=$posDataArray;
}
$response = array(
'success' => true,
);
foreach ($dataByAttId as $attInfoId => $d) {
$response = HumanResource::setAttendanceLogFlutterApp($em,
$d['empId'],
$d['sysUserId'],
$d['companyId'],
$d['appId'],
$request,
$d['attendanceInfo'],
$options,
$d['positionArray'],
$d['lat'],
$d['lng'],
$d['address'],
$d['markerId']
);
}
}
$theEntityUpdated = $theEntity;
} else
$theEntityUpdated = $theEntity;
// $new = new \CompanyGroupBundle\Entity\EntityItemGroup();
$getters = [];
if ($theEntityUpdated)
$getters = array_filter(get_class_methods($theEntityUpdated), function ($method) {
return 'get' === substr($method, 0, 3);
});
$updatedData = [];
foreach ($getters as $getter) {
$indForThis = str_replace('get', '', $getter);
$indForThis = lcfirst($indForThis);
$updatedData[$indForThis] = $theEntityUpdated->{$getter}();
}
$updatedDataList[$dataInd] = $updatedData;
}
foreach ($dataToRemove as $dataInd => $dat) {
$entityName = $dat['entityName'];
$idField = $dat['idField'];
$findById = $dat['findId'];
$additionalSql = isset($dat['additionalSql']) ? $dat['additionalSql'] : '';
$theEntityList = $em->getRepository(($request->request->get('entity_group', 0) ? 'CompanyGroupBundle:' : 'ApplicationBundle:') . $entityName)->findBy(
array
(
$idField => $findById,
)
);
foreach ($theEntityList as $dt) {
$em->remove($dt);
$em->flush();
}
if ($additionalSql != '') {
// if ($entityName == 'PlanningItem') {
//
// $stmt='select disctinct parent_id from planning_item;';
// $stmt->execute();
// $get_kids = $stmt->fetchAll();
// $p_ids=[];
// foreach($get_kids as $g)
// {
// $p_ids[]=$g['parent_id'];
// }
//
//
//
$stmt = $em->getConnection()->prepare($additionalSql);
$stmt->execute();
$stmt->closeCursor();
//
//
}
$updatedDataList[$dataInd] = [];
}
// if ($table == '') {
// return new JsonResponse(
// array(
// 'success' => false,
//// 'page_title' => 'Product Details',
//// 'company_data' => $company_data,
// 'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
//
// )
// );
// }
// if($request->query->has('returnJson'))
return new JsonResponse(
array(
'success' => true,
'data' => $relData,
'updatedDataList' => $updatedDataList,
)
);
}
public function GetAvailableQtyAction(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;
$dataId = $request->request->has('dataId') ? $request->request->get('dataId') : 0;
$allowedWarehouseIds = $request->request->has('warehouseId') ? [$request->request->get('warehouseId')] : [];
$allowedWarehouseActionIds = $request->request->has('warehouseActionId') ? [$request->request->get('warehouseActionId')] : [];
$qty = Inventory::getProductQty($em, $productId, $allowedWarehouseIds, $allowedWarehouseActionIds, $colorId);
return new JsonResponse(array("success" => true,
"qty" => $qty,
"dataId" => $dataId,
));
}
public
function ProductListSelectAjaxAction(Request $request, $queryStr = '')
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$data_by_id = [];
$html = '';
$productByCodeData = [];
if ($queryStr == '_EMPTY_')
$queryStr = '';
if ($request->request->has('query') && $queryStr == '')
$queryStr = $request->request->get('queryStr');
if ($queryStr == '_EMPTY_')
$queryStr = '';
// $queryStr=urldecode($queryStr);
$queryStr = str_replace('_FSLASH_', '/', $queryStr);
$filterQryForCriteria = "select * from inv_products where company_id=" . $companyId . " ";
if ($request->request->has('sellableOnly') && $request->request->get('sellableOnly') != 0)
$filterQryForCriteria .= " and sellable=1";
if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
$filterQryForCriteria .= " and sub_category_id=" . $request->request->get('subCategoryId');
else if ($request->request->has('categoryId') && $request->request->get('categoryId') != '')
$filterQryForCriteria .= " and category_id=" . $request->request->get('categoryId');
else if ($request->request->has('igId') && $request->request->get('igId') != '')
$filterQryForCriteria .= " and ig_id=" . $request->request->get('igId');
if ($request->request->has('brandId') && $request->request->get('brandId') != '')
$filterQryForCriteria .= " and brand_company=" . $request->request->get('brandId');
if ($request->request->has('restrictedBrandIds') && $request->request->get('restrictedBrandIds') != [])
$filterQryForCriteria .= " and brand_company in (" . implode(',', $request->request->get('restrictedBrandIds')) . ")";
if ($request->request->has('productIds'))
$filterQryForCriteria .= " and id in (" . implode(',', $request->request->get('productIds')) . ") ";
else if ($request->request->has('productCode'))
$filterQryForCriteria .= " and product_code like '%" . $request->request->get('productCode') . "%' ";
else if ($queryStr != '')
$filterQryForCriteria .= " and (product_code like '%" . $queryStr . "%' or `name` like '%" . $queryStr . "%' or model_no like '%" . $queryStr . "%') ";
if ($filterQryForCriteria != '')
$filterQryForCriteria .= " limit 25";
$get_kids_sql = $filterQryForCriteria;
// if ($request->request->has('productIds'))
//
// $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
// else if ($request->request->has('productCode'))
// $get_kids_sql = "select * from inv_products where product_code like '%" . $request->request->get('productCode') . "%' and company_id=" . $companyId . " limit 1";
// else if ($filterQryForCriteria!='')
// $get_kids_sql = $filterQryForCriteria;
//
// else
// $get_kids_sql = "select * from inv_products where (product_code like '%" . $queryStr . "%' or `name` like '%" . $queryStr . "%' or model_no like '%" . $queryStr . "%') and company_id=" . $companyId . " limit 25";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$get_kids = $stmt->fetchAll();
$productId = 0;
if (!empty($get_kids)) {
foreach ($get_kids as $product) {
$pa = array();
$pa['id'] = $product['id'];
$pa['name'] = $product['name'];
$pa['id_name'] = $product['id'] . '. ' . $product['name'];
$pa['id_mn'] = $product['id'] . '. ' . $product['model_no'];;
$pa['id_name_mn'] = $product['id'] . '. ' . $product['name'] . ' ( ' . $product['model_no'] . ' )';
$pa['globalId'] = $product['global_id'];
$pa['classSuffix'] = $product['class_suffix'];
$pa['productFdm'] = $product['product_fdm'];
$pa['modelNo'] = $product['model_no'];
$pa['partId'] = $product['part_id'];
$pa['hsCode'] = $product['hs_code'];
$pa['productCode'] = $product['product_code'];
$pa['text'] = $product['name'];
$pa['value'] = $product['id'];
$pa['tac'] = $product['tac'];
$pa['igId'] = $product['ig_id'];
$pa['categoryId'] = $product['category_id'];
$pa['subCategoryId'] = $product['sub_category_id'];
$pa['brandCompany'] = $product['brand_company'];
$pa['sales_price'] = $product['curr_sales_price'];
$pa['purchase_price'] = $product['curr_purchase_price'];
$pa['unit_type'] = $product['unit_type_id'];
$pa['single_weight'] = $product['single_weight'];
$pa['single_weight_variance_type'] = $product['single_weight_variance_type'];
$pa['single_weight_variance_value'] = $product['single_weight_variance_value'];
$pa['weight'] = $product['weight'];
$pa['weight_variance_type'] = $product['weight_variance_type'];
$pa['weight_variance_value'] = $product['weight_variance_value'];
$pa['carton_capacity_count'] = $product['carton_capacity_count'];
$pa['type'] = $product['type'];
$pa['qty'] = $product['qty'];
// $pa['alias'] = '';
$pa['alias'] = $product['alias'];
$pa['note'] = $product['note'];
$pa['defaultTaxConfigId'] = $product['default_tax_config_id'] == null ? 0 : $product['default_tax_config_id'];
$tax_config_ids = json_decode($product['tax_config_ids'], true);
if ($tax_config_ids == null)
$tax_config_ids = [];
$pa['taxConfigIds'] = $tax_config_ids;
$inco_terms = json_decode($product['inco_terms'], true);
if ($inco_terms == null)
$inco_terms = [];
$pa['incoTerms'] = $inco_terms;
$pa['defaultIncoTerm'] = $product['default_inco_term'] == null ? 0 : $product['default_inco_term'];
$pa['has_serial'] = $product['has_serial'];
$pa['expiry_days'] = 1 * $product['expiry_days'];
$pa['image'] = $product['default_image'];
$pa['sales_warranty'] = $product['sales_warranty_months'];;
$pa['defaultColorId'] = $product['default_color_id'];;
$allowedColorIds = json_decode($product['colors'], true);
if ($allowedColorIds == null) $allowedColorIds = [];
if (!in_array($product['default_color_id'], $allowedColorIds))
$allowedColorIds[] = $product['default_color_id'];
$pa['allowedColorIds'] = $allowedColorIds;;
$data[] = $pa;
$data_by_id[$product['id']] = $pa;
$productId = $product['id'];
}
}
// if($request->query->has('returnJson'))
{
return new JsonResponse(
array(
'success' => true,
// 'page_title' => 'Product Details',
// 'company_data' => $company_data,
'data' => $data,
'dataById' => $data_by_id,
'productId' => $productId,
'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
// 'exId'=>$id,
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
}
}
public
function labelFormatSelectAjaxAction(Request $request, $queryStr = '')
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$data_by_id = [];
$html = '';
$productByCodeData = [];
if ($queryStr == '_EMPTY_')
$queryStr = '';
if ($request->request->has('query') && $queryStr == '')
$queryStr = $request->request->get('queryStr');
if ($queryStr == '_EMPTY_')
$queryStr = '';
$filterQryForCriteria = "select * from label_format where company_id=" . $companyId . " ";
if ($request->request->has('dataType') && $request->request->get('dataType') != '_ALL_')
$filterQryForCriteria .= " and label_type=" . $request->request->get('dataType');
if ($request->request->has('formatId') && $request->request->get('formatId') != 0)
$filterQryForCriteria .= " and format_id=" . $request->request->get('formatId');
else if ($queryStr != '')
$filterQryForCriteria .= " and ( `name` like '%" . $queryStr . "%' or `format_code` like '%" . $queryStr . "%') ";
if ($filterQryForCriteria != '')
$filterQryForCriteria .= " limit 25";
$get_kids_sql = $filterQryForCriteria;
// if ($request->request->has('productIds'))
//
// $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
// else if ($request->request->has('productCode'))
// $get_kids_sql = "select * from inv_products where product_code like '%" . $request->request->get('productCode') . "%' and company_id=" . $companyId . " limit 1";
// else if ($filterQryForCriteria!='')
// $get_kids_sql = $filterQryForCriteria;
//
// else
// $get_kids_sql = "select * from inv_products where (product_code like '%" . $queryStr . "%' or `name` like '%" . $queryStr . "%' or model_no like '%" . $queryStr . "%') and company_id=" . $companyId . " limit 25";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$get_kids = $stmt->fetchAll();
$productId = 0;
if (!empty($get_kids)) {
foreach ($get_kids as $product) {
$pa = array();
$pa['id'] = $product['format_id'];
$pa['name'] = $product['name'];
$pa['format_code'] = $product['format_code'] . '. ' . $product['name'];
$pa['id_code_name'] = $product['format_id'] . '. ' . $product['format_code'] . ' - ' . $product['name'] . ' ';
$pa['text'] = $product['name'];
$pa['value'] = $product['format_id'];
$data[] = $pa;
$data_by_id[$product['format_id']] = $pa;
$productId = $product['format_id'];
}
}
// if($request->query->has('returnJson'))
{
return new JsonResponse(
array(
'success' => true,
// 'page_title' => 'Product Details',
// 'company_data' => $company_data,
'data' => $data,
'dataById' => $data_by_id,
'productId' => $productId,
'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
// 'exId'=>$id,
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
}
}
public
function CategoryListSelectAjaxAction(Request $request, $queryStr = '')
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$data_by_id = [];
$html = '';
$productByCodeData = [];
if ($queryStr == '_EMPTY_')
$queryStr = '';
if ($request->request->has('query') && $queryStr == '')
$queryStr = $request->request->get('queryStr');
if ($queryStr == '_EMPTY_')
$queryStr = '';
$filterQryForCriteria = "select * from inv_product_categories where company_id=" . $companyId . " ";
if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
$filterQryForCriteria .= " and ig_id=" . $request->request->get('igId');
$filterQryForCriteria .= " and ( `name` like '%" . $queryStr . "%' ) ";
if ($filterQryForCriteria != '')
$filterQryForCriteria .= " limit 25";
$get_kids_sql = $filterQryForCriteria;
// if ($request->request->has('productIds'))
//
// $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
// else if ($request->request->has('productCode'))
// $get_kids_sql = "select * from inv_products where product_code like '%" . $request->request->get('productCode') . "%' and company_id=" . $companyId . " limit 1";
// else if ($filterQryForCriteria!='')
// $get_kids_sql = $filterQryForCriteria;
//
// else
// $get_kids_sql = "select * from inv_products where (product_code like '%" . $queryStr . "%' or `name` like '%" . $queryStr . "%' or model_no like '%" . $queryStr . "%') and company_id=" . $companyId . " limit 25";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$get_kids = $stmt->fetchAll();
$productId = 0;
if (!empty($get_kids)) {
foreach ($get_kids as $product) {
$pa = array();
$pa['id'] = $product['id'];
$pa['name'] = $product['name'];
$pa['name_with_id'] = '#' . $product['id'] . '. ' . $product['name'];
$pa['globalId'] = $product['global_id'];
$pa['text'] = $product['name'];
$pa['value'] = $product['id'];
$pa['igId'] = $product['ig_id'];
// $pa['categoryId'] = $product['category_id'];
// $pa['subCategoryId'] = $product['sub_category_id'];
$data[] = $pa;
$data_by_id[$product['id']] = $pa;
$productId = $product['id'];
}
}
// if($request->query->has('returnJson'))
{
return new JsonResponse(
array(
'success' => true,
// 'page_title' => 'Product Details',
// 'company_data' => $company_data,
'data' => $data,
'dataById' => $data_by_id,
'productId' => $productId,
'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
// 'exId'=>$id,
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
}
}
public
function SubCategoryListSelectAjaxAction(Request $request, $queryStr = '')
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$data_by_id = [];
$html = '';
$productByCodeData = [];
if ($queryStr == '_EMPTY_')
$queryStr = '';
if ($request->request->has('query') && $queryStr == '')
$queryStr = $request->request->get('queryStr');
if ($queryStr == '_EMPTY_')
$queryStr = '';
$filterQryForCriteria = "select * from inv_product_sub_categories where company_id=" . $companyId . " ";
if ($request->request->has('subCategoryId') && $request->request->get('subCategoryId') != '')
$filterQryForCriteria .= " and sub_category_id=" . $request->request->get('subCategoryId');
if ($request->request->has('categoryId') && $request->request->get('categoryId') != '' && $request->request->get('categoryId') != 0)
$filterQryForCriteria .= " and category_id=" . $request->request->get('categoryId');
if ($request->request->has('igId') && $request->request->get('igId') != '' && $request->request->get('igId') != 0)
$filterQryForCriteria .= " and ig_id=" . $request->request->get('igId');
if ($request->request->has('parentId') && $request->request->get('parentId') != '' && $request->request->get('parentId') != 0)
if ($request->request->get('parentId') != 0)
$filterQryForCriteria .= " and parent_id=" . $request->request->get('parentId');
else
$filterQryForCriteria .= " and ( parent_id =0 or parent_id is null ) ";
if ($request->request->has('level') && $request->request->get('level') != '')
if ($request->request->get('level') != 0)
$filterQryForCriteria .= " and level=" . $request->request->get('level');
else
$filterQryForCriteria .= " and ( level =0 or level is null) ";
$filterQryForCriteria .= " and ( `name` like '%" . $queryStr . "%' ) ";
if ($filterQryForCriteria != '')
$filterQryForCriteria .= " limit 25";
$get_kids_sql = $filterQryForCriteria;
// if ($request->request->has('productIds'))
//
// $get_kids_sql = "select * from inv_products where id in (".implode(',',$request->request->get('productIds')).") and company_id=" . $companyId . " limit 1";
// else if ($request->request->has('productCode'))
// $get_kids_sql = "select * from inv_products where product_code like '%" . $request->request->get('productCode') . "%' and company_id=" . $companyId . " limit 1";
// else if ($filterQryForCriteria!='')
// $get_kids_sql = $filterQryForCriteria;
//
// else
// $get_kids_sql = "select * from inv_products where (product_code like '%" . $queryStr . "%' or `name` like '%" . $queryStr . "%' or model_no like '%" . $queryStr . "%') and company_id=" . $companyId . " limit 25";
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$get_kids = $stmt->fetchAll();
$productId = 0;
if (!empty($get_kids)) {
foreach ($get_kids as $product) {
$pa = array();
$pa['id'] = $product['id'];
$pa['name'] = $product['name'];
$pa['name_with_id'] = '#' . $product['id'] . '. ' . $product['name'];
$pa['globalId'] = $product['global_id'];
$pa['parentId'] = $product['parent_id'];
$pa['text'] = $product['name'];
$pa['value'] = $product['id'];
$pa['igId'] = $product['ig_id'];
$pa['categoryId'] = $product['category_id'];
// $pa['subCategoryId'] = $product['sub_category_id'];
$data[] = $pa;
$data_by_id[$product['id']] = $pa;
$productId = $product['id'];
}
}
// if($request->query->has('returnJson'))
{
return new JsonResponse(
array(
'success' => true,
// 'page_title' => 'Product Details',
// 'company_data' => $company_data,
'data' => $data,
'dataById' => $data_by_id,
'productId' => $productId,
'ret_data' => $request->request->has('ret_data') ? $request->request->get('ret_data') : [],
// 'exId'=>$id,
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
}
}
public
function ProductByCodeViewAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$html = '';
$productByCodeData = [];
if ($id != 0) {
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')
->findOneBy(
array(
'productByCodeId' => $id
)
);
} else {
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')
->findOneBy(
array(
// 'productByCodeId' => $id,
'CompanyId' => $companyId
), array(
'productByCodeId' => 'DESC'
)
);
if ($productByCodeData)
$id = $productByCodeData->getProductByCodeId();
}
if ($id != 0) {
$productData = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $productByCodeData->getProductId()
)
);
$currInvList = $em->getRepository('ApplicationBundle:InventoryStorage')
->findBy(
array(
'productId' => $id
)
);
$html = $this->renderView('ApplicationBundle:pages/inventory/view:product_by_code_snippet.html.twig',
array(
'page_title' => 'Product Details',
'company_data' => $company_data,
'productByCodeData' => $productByCodeData,
'productData' => $productData,
'currInvList' => $currInvList,
'exId' => $id,
'clientList' => Client::GetExistingClientList($em, $companyId),
'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
'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),
'warehouse_action_list' => Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object'),
'warehouseList' => Inventory::WarehouseList($em),
)
);
} else {
$html = $this->renderView('ApplicationBundle:pages/inventory/view:product_by_code_snippet.html.twig',
array(
'exId' => $id,
)
);
}
if ($request->query->has('returnJson')) {
return new JsonResponse(
array(
'success' => true,
'page_title' => 'Product Details',
'company_data' => $company_data,
'renderedHtml' => $html,
'exId' => $id,
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
} else {
// $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
// ->findBy(
// array(
//// 'productByCodeId' => $id,
// 'CompanyId'=>$companyId
// )
// );
$productByCodeList = []; //called by ajax
return $this->render('ApplicationBundle:pages/inventory/view:product_by_code_view.html.twig',
array(
'page_title' => 'Product Details',
'company_data' => $company_data,
'renderedHtml' => $html,
'exId' => $id,
'productByCodeList' => $productByCodeList,
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
}
}
public
function ConsumptionSettingsAction(Request $request, $id)
{
$cc_id = '';
$cc_name = '';
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$consumptionTypeId = 0;
if ($request->isMethod('POST')) {
$new_cc = [];
if ($request->request->get('consumptionTypeId') != '' && $request->request->get('consumptionTypeId') != 0) {
$em = $this->getDoctrine()->getManager();
$new_cc = $this->getDoctrine()
->getRepository('ApplicationBundle:ConsumptionType')
->findOneBy(
array(
'consumptionTypeId' => $request->request->get('consumptionTypeId'),
)
);
$new_cc->setName($request->request->get('name'));
$new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
$new_cc->setCompanyId($companyId);
$em->flush();
$consumptionTypeId = $new_cc->getConsumptionTypeId();
$this->addFlash(
'success',
'Consumption Information Updated'
);
} else {
$new_cc = new ConsumptionType();
$new_cc->setName($request->request->get('name'));
$new_cc->setAccountsHeadId(json_encode($request->request->get('headId')));
$new_cc->setCompanyId($companyId);
$em->persist($new_cc);
$em->flush();
$consumptionTypeId = $new_cc->getConsumptionTypeId();
$em->flush();
$this->addFlash(
'success',
'New Consumption Type Added'
);
}
}
$extData = [];
if ($id != 0) {
$extData = $this->getDoctrine()
->getRepository('ApplicationBundle:ConsumptionType')
->findOneBy(
array(
'consumptionTypeId' => $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('ApplicationBundle:pages/inventory/input_forms:consumption_settings.html.twig',
array(
'page_title' => 'Consumption Settings',
'consumptionTypeList' => $this->getDoctrine()
->getRepository('ApplicationBundle:ConsumptionType')
->findBy(
array(
'CompanyId' => $companyId
)
),
'extData' => $extData,
'headList' => Accounts::getParentLedgerHeads($em),
// 'countryList'=>SalesOrderM::Co
)
);
}
public
function ProductByCodeCheckAssignPrintAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$html = '';
$productByCodeData = [];
$productDataWeightPackageGm = '';
$productDataWeightVarianceValue = 0;
$productDataWeightVarianceType = 0;
$productByCodeDataObj = [];
$dr_id = 0;//for dr_id
$skipRenderData = 0;
if ($request->query->has('skipRenderData'))
$skipRenderData = $request->query->get('skipRenderData');
if ($id != 0) {
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')
->findOneBy(
array(
'productByCodeId' => $id
)
);
} else {
if ($request->query->has('scanCode')) {
$query = $em->getRepository('ApplicationBundle:ProductByCode')
->createQueryBuilder('p');
if ($request->query->has('assigned')) {
$query->where('p.assigned > :av')
->setParameter('av', $request->query->get('assigned'));
} else
$query->where("1=0");
$query->orWhere("p.salesCode LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->orWhere("p.serialNo LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->orWhere("p.imei1 LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->orWhere("p.imei2 LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->orWhere("p.imei3 LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->orWhere("p.imei4 LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->setMaxResults(1);
$results = $query->getQuery()->getResult();
$productByCodeData = isset($results[0]) ? $results[0] : null;
} else
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')
->findOneBy(
array(
// 'productByCodeId' => $id,
'CompanyId' => $companyId
), array(
'productByCodeId' => 'DESC'
)
);
if ($productByCodeData)
$id = $productByCodeData->getProductByCodeId();
}
if ($id != 0) {
$productByCodeDataObj = array(
'salesCode' => $productByCodeData->getSalesCode(),
'sales_code' => $productByCodeData->getSalesCode(),
'sn' => $productByCodeData->getSerialNo(),
'serialNo' => $productByCodeData->getSerialNo(),
'imei1' => $productByCodeData->getImei1(),
'imei2' => $productByCodeData->getImei2(),
'soId' => $productByCodeData->getSalesOrderId(),
'poId' => $productByCodeData->getPurchaseOrderId(),
'irrId' => $productByCodeData->getIrrId(),
'productId' => $productByCodeData->getProductId(),
'productByCodeId' => $productByCodeData->getProductByCodeId(),
'warehouseId' => $productByCodeData->getWarehouseId(),
'warehouseActionId' => $productByCodeData->getWarehouseActionId(),
'stId' => $productByCodeData->getStockTransferId(),
'srId' => $productByCodeData->getStockReceivedNoteId(),
'scmpId' => $productByCodeData->getStockConsumptionNoteId(),
'clientId' => $productByCodeData->getClientId(),
'supplierId' => $productByCodeData->getSupplierId(),
'drId' => $productByCodeData->getDeliveryReceiptId(),
'consumerName' => $productByCodeData->getConsumerName(),
'drItemData' => [],
// 'salesCodes' => $productByCodeData->getDeliveryReceiptId(),
);
$productData = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $productByCodeData->getProductId()
)
);
if ($productByCodeData->getProductionId() != null) {
$productionDataHere = $em->getRepository('ApplicationBundle:Production')
->findOneBy(
array(
'productionId' => $productByCodeData->getProductionId()
)
);
if ($productionDataHere) {
$productDataWeightPackageGm = $productionDataHere->getPackageWeight();
$productDataWeightVarianceValue = $productionDataHere->getPackageWeightVarianceValue();
$productDataWeightVarianceType = $productionDataHere->getPackageWeightVarianceType();
}
} else {
if ($productData) {
$productDataWeightPackageGm = $productData->getWeight();
$productDataWeightVarianceValue = $productData->getWeightVarianceValue();
$productDataWeightVarianceType = $productData->getWeightVarianceType();
}
}
if ($productData) {
$productByCodeDataObj['unitTypeId'] = $productData->getUnitTypeId();
$productByCodeDataObj['purchasePrice'] = $productData->getPurchasePrice();
$productByCodeDataObj['productFdm'] = $productData->getProductFdm();
$productByCodeDataObj['productName'] = $productData->getName();
if ($request->request->has('forSalesReturn') || $request->query->has('forSalesReturn')) {
$QD = $this->getDoctrine()
->getRepository('ApplicationBundle:DeliveryReceiptItem')
->findOneBy(
array(
'deliveryReceiptId' => $productByCodeData->getDeliveryReceiptId(),
'productId' => $productByCodeData->getProductId(),
)
);
// if($request->request->get('wareHouseId')!='')
if ($QD) {
$new_pid = $QD->getProductId();
$sales_code_range = [];
if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
$sales_code_range = json_decode($QD->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
} else {
$max_int_length = strlen((string)PHP_INT_MAX) - 1;
$json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $QD->getSalesCodeRange());
$sales_code_range = json_decode($json_without_bigints, true);
}
$p_data = array(
'details_id' => $QD->getId(),
'productId' => $new_pid,
'dr_id' => $productByCodeData->getDeliveryReceiptId(),
'product_name' => $productData->getName(),
'qty' => $QD->getQty(),
'delivered' => $QD->getDelivered(),
'unitTypeId' => $QD->getUnitTypeId(),
'deliverable' => $QD->getDeliverable(),
'balance' => $QD->getBalance(),
'salesCodeRangeStr' => $QD->getSalesCodeRange(),
'salesCodeRange' => $sales_code_range,
'sales_codes' => $sales_code_range,
'sales_price' => $QD->getPrice(),
'purchase_price' => $QD->getCurrentPurchasePrice()
// 'delivered'=>$product->getDelivered(),
);
$productByCodeDataObj['drItemData'][] = $p_data;
}
}
}
$currInvList = $em->getRepository('ApplicationBundle:InventoryStorage')
->findBy(
array(
'productId' => $id
)
);
$html = ($skipRenderData == 1 ? '' : $this->renderView('ApplicationBundle:pages/inventory/view:product_by_code_for_print_check_snippet.html.twig',
array(
'page_title' => 'Details',
'company_data' => $company_data,
'productByCodeData' => $productByCodeData,
'productByCodeDataObj' => $productByCodeDataObj,
'productData' => $productData,
'currInvList' => $currInvList,
'productDataWeightPackageGm' => $productDataWeightPackageGm,
'productDataWeightVarianceValue' => $productDataWeightVarianceValue,
'productDataWeightVarianceType' => $productDataWeightVarianceType,
'exId' => $id,
'clientList' => Client::GetExistingClientList($em, $companyId),
'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
'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),
'warehouse_action_list' => Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object'),
'warehouseList' => Inventory::WarehouseList($em),
)
));
} else {
$html = ($skipRenderData == 1 ? '' : $this->renderView('ApplicationBundle:pages/inventory/view:product_by_code_for_print_check_snippet.html.twig',
array(
'exId' => $id,
)
));
}
if ($request->query->has('returnJson')) {
return new JsonResponse(
array(
'success' => true,
'page_title' => 'Product Details',
'company_data' => $company_data,
'renderedHtml' => $html,
'exId' => $id,
'productByCodeDataObj' => $productByCodeDataObj,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
} else {
// $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
// ->findBy(
// array(
//// 'productByCodeId' => $id,
// 'CompanyId'=>$companyId
// )
// );
$productByCodeList = []; //called by ajax
return $this->render('ApplicationBundle:pages/inventory/view:product_by_code_assign_check_print.html.twig',
array(
'page_title' => 'Serial Manager',
'company_data' => $company_data,
'renderedHtml' => $html,
'exId' => $id,
'productByCodeList' => $productByCodeList,
'productByCodeDataObj' => $productByCodeDataObj,
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
}
}
public
function TestProductByCodeCheckAssignPrintAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$html = '';
$productByCodeData = [];
$productByCodeDataObj = [];
if ($id != 0) {
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')
->findOneBy(
array(
'productByCodeId' => $id
)
);
} else {
if ($request->query->has('scanCode')) {
$query = $em->getRepository('ApplicationBundle:ProductByCode')
->createQueryBuilder('p');
if ($request->query->has('assigned')) {
$query->where('p.assigned > :av')
->setParameter('av', $request->query->get('assigned'));
} else
$query->where("1=0");
$query->orWhere("p.salesCode LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->orWhere("p.serialNo LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->orWhere("p.imei1 LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->orWhere("p.imei2 LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->orWhere("p.imei3 LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->orWhere("p.imei4 LIKE '%" . $request->query->get('scanCode') . "%' ");
$query->setMaxResults(1);
$results = $query->getQuery()->getResult();
$productByCodeData = isset($results[0]) ? $results[0] : null;
} else
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')
->findOneBy(
array(
// 'productByCodeId' => $id,
'CompanyId' => $companyId
), array(
'productByCodeId' => 'DESC'
)
);
if ($productByCodeData)
$id = $productByCodeData->getProductByCodeId();
}
if ($id != 0) {
$productByCodeDataObj = array(
'sn' => $productByCodeData->getSalesCode(),
'imei1' => $productByCodeData->getImei1(),
'imei2' => $productByCodeData->getImei2(),
'colorId' => $productByCodeData->getColorId(),
);
$productData = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $productByCodeData->getProductId()
)
);
$currInvList = $em->getRepository('ApplicationBundle:InventoryStorage')
->findBy(
array(
'productId' => $id
)
);
$html = $this->renderView('ApplicationBundle:pages/inventory/view:test_product_by_code_for_print_check_snippet.html.twig',
array(
'page_title' => 'Details',
'company_data' => $company_data,
'productByCodeData' => $productByCodeData,
'productData' => $productData,
'currInvList' => $currInvList,
'exId' => $id,
'clientList' => Client::GetExistingClientList($em, $companyId),
'supplierList' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
'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),
'warehouse_action_list' => Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object'),
'warehouseList' => Inventory::WarehouseList($em),
)
);
} else {
$html = $this->renderView('ApplicationBundle:pages/inventory/view:test_product_by_code_for_print_check_snippet.html.twig',
array(
'exId' => $id,
)
);
}
if ($request->query->has('returnJson')) {
return new JsonResponse(
array(
'success' => true,
'page_title' => 'Product Details',
'company_data' => $company_data,
'renderedHtml' => $html,
'exId' => $id,
'productByCodeDataObj' => $productByCodeDataObj,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
} else {
// $productByCodeList=$em->getRepository('ApplicationBundle:ProductByCode')
// ->findBy(
// array(
//// 'productByCodeId' => $id,
// 'CompanyId'=>$companyId
// )
// );
$productByCodeList = []; //called by ajax
return $this->render('ApplicationBundle:pages/inventory/view:test_product_by_code_assign_check_print.html.twig',
array(
'page_title' => ' Test Serial Manager',
'company_data' => $company_data,
'renderedHtml' => $html,
'exId' => $id,
'productByCodeList' => $productByCodeList,
'productByCodeDataObj' => $productByCodeDataObj,
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
}
}
public
function DeleteProductAction(Request $request, $id = '')
{
$em = $this->getDoctrine()->getManager();
$idListArray = [];
if ($request->isMethod('POST')) {
if ($id == 0)
$id = $request->request->get('productId');
//now check the product closing , if nothing then we cna remove it
$query_here = $this->getDoctrine()
->getRepository('ApplicationBundle:InvClosingBalance')
->findBy(
array(
'productId' => $request->request->get('productId')
)
);
if (!empty($query_here)) {
return new JsonResponse(
array(
'success' => false,
)
);
} else {
$qry = $em->getRepository('ApplicationBundle:ProductByCode')->findBy(array(
'productId' => $id
));
foreach ($qry as $det) {
//remove any barcoded products
$em->remove($det);
$em->flush();
}
$qry = $em->getRepository('ApplicationBundle:InvProducts')->findBy(array(
'id' => $id
));
foreach ($qry as $det) {
//remove any barcoded products
$em->remove($det);
$em->flush();
}
$qry = $em->getRepository('ApplicationBundle:InvItemTransaction')->findBy(array(
'productId' => $id
));
foreach ($qry as $det) {
//remove any barcoded products
$em->remove($det);
$em->flush();
}
return new JsonResponse(
array(
'success' => true,
)
);
}
}
return new JsonResponse(
array(
'success' => false,
)
);
}
public
function RegisterProductAction(Request $request, $idListStr = '')
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$session = $request->getSession();
// System::setSessionForUser($session );
$idListArray = [];
if ($idListStr != '')
$idListArray = explode(',', $idListStr);
$data = [];
// if ($request->isMethod('POST')) {
// $post = $request->request;
// if ($request->request->get('formatId') != '') {
// $query_here = $this->getDoctrine()
// ->getRepository('ApplicationBundle:CheckFormat')
// ->findOneBy(
// array(
// 'formatId' => $request->request->get('formatId')
// )
// );
// if (!empty($query_here))
// $new = $query_here;
// } else
// $new = new CheckFormat();
// $new->setName($request->request->get('name'));
// $new->setWidth($request->request->get('width'));
// $new->setHeight($request->request->get('height'));
// $new->setCheckPayToLeft($request->request->get('checkPayToLeft'));
// $new->setCheckPayToTop($request->request->get('checkPayToTop'));
// $new->setCheckAmountLeft($request->request->get('checkAmountLeft'));
// $new->setCheckAmountTop($request->request->get('checkAmountTop'));
// $new->setCheckAiWLeft($request->request->get('checkAiWLeft'));
// $new->setCheckAiWTop($request->request->get('checkAiWTop'));
// $new->setCheckDateLeft($request->request->get('checkDateLeft'));
// $new->setCheckDateTop($request->request->get('checkDateTop'));
// $new->setCheckDatePartLeft($request->request->get('checkDatePartLeft'));
// $new->setCheckDatePartTop($request->request->get('checkDatePartTop'));
// $new->setCheckDateD1Left($request->request->get('checkDateD1Left'));
// $new->setCheckDateD2Left($request->request->get('checkDateD2Left'));
// $new->setCheckDateM1Left($request->request->get('checkDateM1Left'));
// $new->setCheckDateM2Left($request->request->get('checkDateM2Left'));
// $new->setCheckDateY1Left($request->request->get('checkDateY1Left'));
// $new->setCheckDateY2Left($request->request->get('checkDateY2Left'));
// $new->setCheckDateY3Left($request->request->get('checkDateY3Left'));
// $new->setCheckDateY4Left($request->request->get('checkDateY4Left'));
// $new->setDateDividerDisabled($request->request->has('dateDividerDisabled') ? 1 : 0);
// $new->setCheckImage($request->request->get('checkImage'));
//
// $em = $this->getDoctrine()->getManager();
// $em->persist($new);
// $em->flush();
//
// }
// if (!empty($idListArray)) {
// $query_here = $this->getDoctrine()
// ->getRepository('ApplicationBundle:ProductByCode')
// ->findBy(
// array(
// 'productByCodeId' => $idListArray
// )
// );
// if (!empty($query_here))
// $data = $query_here;
//
// }
// else if ($request->query->has('formatId')) {
// $query_here = $this->getDoctrine()
// ->getRepository('ApplicationBundle:CheckFormat')
// ->findOneBy(
// array(
// 'formatId' => $request->query->get('formatId')
// )
// );
// if (!empty($query_here))
// $data = $query_here;
// }
$data = [];
$html = '';
$productByCodeData = [];
if ($request->query->has('returnJson')) {
return new JsonResponse(
array(
'success' => true,
'page_title' => 'Product Details',
'company_data' => $company_data,
'renderedHtml' => $html,
'data' => $data,
'idListArray' => $idListArray,
// 'exId'=>$id,
// 'productByCodeData' => $productByCodeData,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
} else {
return $this->render('ApplicationBundle:pages/inventory/input_forms:register_product.html.twig',
array(
'page_title' => 'Register Product',
'company_data' => $company_data,
'renderedHtml' => $html,
// 'exIdList'=>$i,
'idListArray' => $idListArray,
'data' => $data,
'productByCodeList' => [],
'productByCodeData' => [],
'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),
'warehouse_action_list' => Inventory::warehouse_action_list($em, $this->getLoggedUserCompanyId($request), 'object'),
'warehouseList' => Inventory::WarehouseList($em),
)
);
}
}
public
function BrandViewAction(Request $request)
{
return $this->render('ApplicationBundle:pages/inventory/input_forms:stock_return.html.twig',
array(
'page_title' => 'Stock Return'
)
);
}
public
function PrintTableDataAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$company_data = Company::getCompanyData($em, 1);
$data = [];
$print_title = "test";
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
$mis_data = [];
$p = 1;
return $this->render('ApplicationBundle:pages/inventory/print:print_table_data.html.twig',
array(
'page_title' => 'Data Report',
'data' => $data,
'page_header' => 'Report',
'print_title' => $print_title,
'document_type' => 'Journal voucher',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
// 'type_list'=>$type_list,
'mis_data' => $mis_data,
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'p' => $p
)
);
}
public
function ReplacementReportAction(Request $request)
{
$qry_data = array(
'warehouseId' => [0],
'igId' => [0],
'brandId' => [0],
'categoryId' => [0],
'actionTagId' => [0],
);
$em = $this->getDoctrine()->getManager();
$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 = [];
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$print_title = "Inventory Report";
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
$post_data = $request->request;
$start_date = $post_data->has('start_date') ? $post_data->get('start_date') : '';
$end_date = $post_data->has('end_date') ? $post_data->get('end_date') : '';
if ($request->isMethod('POST'))
$method = 'POST';
else
$method = 'GET';
{
// $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
$data_searched = Inventory::GetReplacementReportData($this->getDoctrine()->getManager(),
$request->request, $method,
$request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
return new JsonResponse(
array(
'page_title' => 'Inventory ',
'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId, 0, 0, '_INVENTORY_VIEW_'),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'action_tag' => $warehouse_action_list,
'start_date' => $start_date,
'end_date' => $end_date,
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'data_searched' => $data_searched,
'success' => empty($data_searched['query_result']) ? false : true
)
);
}
if ($request->request->get('print_data_enabled') == 1) {
$print_sub_title = "";
return $this->render('ApplicationBundle:pages/inventory/print:print_replacement_report.html.twig',
array(
'page_title' => 'Replacement Report',
'page_header' => 'Report',
'print_title' => $print_title,
'document_type' => 'Journal voucher',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId, 0, 0, '_INVENTORY_VIEW_'),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'brands' => 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' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'start_date' => $start_date,
'end_date' => $end_date,
'data_searched' => $data_searched
)
);
}
}
return $this->render('ApplicationBundle:pages/inventory/report:replacement_report.html.twig',
array(
'page_title' => 'Replacement Report',
'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId, 0, 0, '_INVENTORY_VIEW_'),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
// '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' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'start_date' => $start_date,
'end_date' => $end_date,
'data_searched' => $data_searched,
'success' => empty($data_searched['query_result']) ? false : true
)
);
}
public
function InventoryViewAction(Request $request)
{
$qry_data = array(
'warehouseId' => [0],
'igId' => [0],
'brandId' => [0],
'categoryId' => [0],
'actionTagId' => [0],
);
$em = $this->getDoctrine()->getManager();
$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 = [];
$companyId = $this->getLoggedUserCompanyId($request);
$company_data = Company::getCompanyData($em, $companyId);
$data = [];
$print_title = "Inventory Report";
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->isMethod('POST'))
$method = 'POST';
else
$method = 'GET';
{
// $path=$this->container->getParameter('kernel.root_dir') . '/gifnoc/invdata.json';
$data_searched = Inventory::GetInventoryViewData($this->getDoctrine()->getManager(),
$request->request, $method,
$request->getSession()->get(UserConstants::USER_LOGIN_ID), $companyId);
if ($request->request->has('returnJson') || $request->query->has('returnJson')) {
return new JsonResponse(
array(
'page_title' => 'Inventory ',
'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId, 0, 0, '_INVENTORY_VIEW_'),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'action_tag' => $warehouse_action_list,
'unit_type' => Inventory::UnitTypeList($this->getDoctrine()->getManager()),
'warehouse' => Inventory::WarehouseList($this->getDoctrine()->getManager()),
'qry' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'data_searched' => $data_searched,
'success' => empty($data_searched['query_result']) ? false : true
)
);
}
if ($request->request->get('print_data_enabled') == 1) {
$print_sub_title = "";
return $this->render('ApplicationBundle:pages/inventory/print:print_inventory_data.html.twig',
array(
'page_title' => 'Inventory Report',
'page_header' => 'Report',
'print_title' => $print_title,
'document_type' => 'Journal voucher',
'document_mark_image' => $document_mark['original'],
'page_header_sub' => 'Add',
'item_data' => [],
'received' => 2,
'return' => 1,
'total_w_vat' => 1,
'total_vat' => 1,
'total_wo_vat' => 1,
'invoice_id' => 'abcd1234',
'invoice_footer' => $company_data->getInvoiceFooter(),
'created_by' => 'created by',
'created_at' => '',
'red' => 0,
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId, 0, 0, '_INVENTORY_VIEW_'),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
'brands' => 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' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'data_searched' => $data_searched
)
);
}
}
return $this->render('ApplicationBundle:pages/inventory/report:inventory_view.html.twig',
array(
'page_title' => 'Inventory',
'products' => Inventory::ProductList($this->getDoctrine()->getManager(), $companyId, 0, 0, '_INVENTORY_VIEW_'),
'categories' => Inventory::ProductCategoryList($this->getDoctrine()->getManager()),
'itemgroup' => Inventory::ItemGroupList($this->getDoctrine()->getManager()),
'brands' => Inventory::ProductBrandList($this->getDoctrine()->getManager()),
'sub_categories' => Inventory::ProductSubCategoryList($this->getDoctrine()->getManager(), $this->getLoggedUserCompanyId($request)),
// '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' => isset($data_searched['query_filter']) ? $data_searched['query_filter'] : [],
'data_searched' => $data_searched
)
);
}
public
function GrnListAction(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:Grn')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
// 'approved' => GeneralConstant::APPROVED,
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getGrnDate(),
'id' => $entry->getGrnId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'stage' => $stage_list[$entry->getStage()]
);
}
return $this->render('ApplicationBundle:pages/inventory/view:grn_list.html.twig',
array(
'page_title' => 'Grn List',
'data' => $data
)
);
}
public
function ViewGrnAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetGrnDetails($em, $id);
return $this->render('ApplicationBundle:pages/inventory/view:view_grn.html.twig',
array(
'page_title' => 'View',
'data' => $dt,
'forceRefreshBarcode' => $request->query->has('forceRefreshBarcode') ? $request->query->get('forceRefreshBarcode') : 0,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['Grn'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['Grn'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public
function PrintGrnAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetGrnDetails($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('ApplicationBundle:pages/inventory/print:print_received_note.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Grn',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['Grn'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['Grn'],
$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="grn.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_received_note.html.twig',
array(
'page_title' => 'Grn',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['Grn'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['Grn'],
$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 PrintGrnBarcodeAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetGrnDetails($em, $id);
$company_data = Company::getCompanyData($em, 1);
$repeatCount = 1;
if ($request->query->has('repeatCount'))
$repeatCount = $request->query->get('repeatCount');
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView('ApplicationBundle:pages/inventory/print:print_grn_barcodes.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Grn Barcodes',
'export' => 'print',
'data' => $dt,
'repeatCount' => $repeatCount,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['Grn'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['Grn'],
$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="grn_barcodes.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_grn_barcodes.html.twig',
array(
'page_title' => 'Grn barcodes',
// 'export'=>'pdf,print',
'data' => $dt,
'repeatCount' => $repeatCount,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['Grn'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['Grn'],
$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 GenerateBarcodeAction(Request $request, $type, $id, $item_id)
{
$em = $this->getDoctrine()->getManager();
$repeatCount = 1;
$spec_item_id = 0;
$skip_ids = [];
$clearUnnecessaryOnly = 0;
if ($request->query->has('skipIds'))
$skip_ids = $request->query->get('skipIds');
if ($request->query->has('clearUnnecessaryOnly'))
$clearUnnecessaryOnly = $request->query->get('clearUnnecessaryOnly');
if ($type == 'srcv') {
$doc_data = $em->getRepository('ApplicationBundle:StockReceivedNote')->findOneBy(
array(
'stockReceivedNoteId' => $id
)
);
if ($item_id == '_single_') {
$doc_item_data = $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
array(
'stockReceivedNoteId' => $id,
// 'id' => $item_id
)
);
} else {
$doc_item_data = $em->getRepository('ApplicationBundle:StockReceivedNoteItem')->findBy(
array(
'stockReceivedNoteId' => $id,
'id' => $item_id
)
);
}
$inv_acc_data = [
'fa_amount' => 0,
'tg_amount' => 0,
];
$inv_acc_data_by_head = [
];
$new_non_delivered_sales_code_range = [];
foreach ($doc_item_data as $entry) {
//adding transaction
$sales_code_range_ser = [];
if (in_array($entry->getId(), $skip_ids))
continue;
$product = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $entry->getProductId()
)
);
$stitem = $em->getRepository('ApplicationBundle:StockTransferItem')
->findOneBy(
array(
'id' => $entry->getStockTransferItemId(),
'productId' => $entry->getProductId()
)
);
if ($product) {
if ($product->getHasSerial() == 1) {
//clear if exists
if ($clearUnnecessaryOnly == 1) {
$get_kids_sql = "DELETE FROM product_by_code
WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
// $get_kids_sql .=' ORDER BY name ASC';
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$em->flush();
} else {
$get_kids_sql = "DELETE FROM product_by_code
WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
// $get_kids_sql .=' ORDER BY name ASC';
$stmt = $em->getConnection()->prepare($get_kids_sql);
$stmt->execute();
$em->flush();
}
// $check_here = $stmt->fetchAll();
//now addng product by code
$sales_code_range = [];
if ($doc_data->getType() == 3 || $doc_data->getType() == 4) {
// if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
// $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
$product_action_tag_id = $entry->getWarehouseActionId();
$barcodeData = Inventory::GenerateBarcode($em, $entry->getProductId(), $entry->getQty(),
$doc_data->getStockReceivedNoteDate(), $entry->getWarrantyMon(), 0, $doc_data->getCompanyId(), $entry->getWarehouseId(),
$entry->getWarehouseActionId(), $entry->getPurchaseCodeRange(), null, null, null, null, $doc_data->getStockReceivedNoteId()
);
$sales_code_range = $barcodeData['sales_code_range'];
$entry->setSalesCodeRange(json_encode($sales_code_range));
$em->flush();
}
// else {
// if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
//
// $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
// } else {
//
// $max_int_length = strlen((string)PHP_INT_MAX) - 1;
// $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
// $sales_code_range = json_decode($json_without_bigints, true);
// }
// if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
//
// $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
// } else {
//
// $max_int_length = strlen((string)PHP_INT_MAX) - 1;
// $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
// $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
// }
//// $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
//// $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
// $new_non_delivered_sales_code_range = [];
// foreach ($non_delivered_sales_code_range as $ndsc) {
// if (!(in_array($ndsc, $sales_code_range)))
// $new_non_delivered_sales_code_range[] = $ndsc;
// }
// if ($sales_code_range != null) {
// foreach ($sales_code_range as $ind => $dt) {
// $np = $em->getRepository('ApplicationBundle:ProductByCode')
// ->findOneBy(
// array(
// 'salesCode' => [$dt],
// 'productId' => $entry->getProductId()
// )
// );
//
// if ($np) {
// $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
// $np->setProductId($entry->getProductId());
// $np->setWarehouseId($entry->getWarehouseId());
// $np->setWarehouseActionId($entry->getWarehouseActionId());
// $np->setPosition(1);//in warehouse
// $np->setStockReceivedNoteId($id);
//
//
// $np->setLastInDate($doc_data->getStockReceivedNoteDate());
// $np->setStatus(GeneralConstant::ACTIVE);
// $trans_history = json_decode($np->getTransactionHistory(), true);
// $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
// 'direction' => 'in',
// 'warehouseId' => $entry->getWarehouseId(),
// 'warehouseActionId' => $entry->getWarehouseActionId(),
// 'fromWarehouseId' => $stitem->getWarehouseId(),
// 'fromWarehouseActionId' => $stitem->getWarehouseActionId()
// );
// $np->setTransactionHistory(json_encode(
// $trans_history
// ));
//
//
// $em->persist($np);
// $em->flush();
// }
// }
// }
// }
}
}
//adding transaction
if ($stitem) {
$stitem->setNonDeliveredSalesCodeRange(json_encode($new_non_delivered_sales_code_range));
}
$spec_item_id = $entry->getId();
if ($item_id == '_single_') {
break;
}
}
}
if ($type == 'irr') {
$doc_data = $em->getRepository('ApplicationBundle:ItemReceivedAndReplacement')->findOneBy(
array(
'itemReceivedAndReplacementId' => $id
)
);
if ($item_id == '_single_') {
$doc_item_data = $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
array(
'itemReceivedAndReplacementId' => $id,
// 'id' => $item_id
)
);
} else {
$doc_item_data = $em->getRepository('ApplicationBundle:ItemReceivedAndReplacementItem')->findBy(
array(
'itemReceivedAndReplacementId' => $id,
'id' => $item_id
)
);
}
$inv_acc_data = [
'fa_amount' => 0,
'tg_amount' => 0,
];
$inv_acc_data_by_head = [
];
$new_non_delivered_sales_code_range = [];
foreach ($doc_item_data as $entry) {
//adding transaction
$sales_code_range_ser = [];
if (in_array($entry->getId(), $skip_ids))
continue;
$product = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $entry->getReceivedProductId()
)
);
if ($product) {
if ($product->getHasSerial() == 1) {
//clear if exists
// if($clearUnnecessaryOnly==1) {
// $get_kids_sql = "DELETE FROM product_by_code
// WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
//// $get_kids_sql .=' ORDER BY name ASC';
//
// $stmt = $em->getConnection()->prepare($get_kids_sql);
// $stmt->execute();
// $em->flush();
// }
// else{
// $get_kids_sql = "DELETE FROM product_by_code
// WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
//// $get_kids_sql .=' ORDER BY name ASC';
//
// $stmt = $em->getConnection()->prepare($get_kids_sql);
// $stmt->execute();
// $em->flush();
// }
// $check_here = $stmt->fetchAll();
//now addng product by code
$sales_code_range = [];
if ($entry->getReceivedQty() > 0) {
// if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
// $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
// $product_action_tag_id = $entry->getWarehouseActionId();
$barcodeData = Inventory::GenerateBarcode($em, $entry->getReceivedProductId(), $entry->getReceivedQty(),
$doc_data->getItemReceivedAndReplacementDate(), 0, 0, $doc_data->getCompanyId(), $entry->getReceivedWarehouseId(),
$entry->getReceivedWarehouseActionId(), null, null, null, null, null, null, null, null, $doc_data->getItemReceivedAndReplacementId()
);
$sales_code_range = $barcodeData['sales_code_range'];
$entry->setReceivedCodeRange(json_encode($sales_code_range));
$em->flush();
}
// else {
// if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
//
// $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
// } else {
//
// $max_int_length = strlen((string)PHP_INT_MAX) - 1;
// $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
// $sales_code_range = json_decode($json_without_bigints, true);
// }
// if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
//
// $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
// } else {
//
// $max_int_length = strlen((string)PHP_INT_MAX) - 1;
// $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
// $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
// }
//// $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
//// $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
// $new_non_delivered_sales_code_range = [];
// foreach ($non_delivered_sales_code_range as $ndsc) {
// if (!(in_array($ndsc, $sales_code_range)))
// $new_non_delivered_sales_code_range[] = $ndsc;
// }
// if ($sales_code_range != null) {
// foreach ($sales_code_range as $ind => $dt) {
// $np = $em->getRepository('ApplicationBundle:ProductByCode')
// ->findOneBy(
// array(
// 'salesCode' => [$dt],
// 'productId' => $entry->getProductId()
// )
// );
//
// if ($np) {
// $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
// $np->setProductId($entry->getProductId());
// $np->setWarehouseId($entry->getWarehouseId());
// $np->setWarehouseActionId($entry->getWarehouseActionId());
// $np->setPosition(1);//in warehouse
// $np->setStockReceivedNoteId($id);
//
//
// $np->setLastInDate($doc_data->getStockReceivedNoteDate());
// $np->setStatus(GeneralConstant::ACTIVE);
// $trans_history = json_decode($np->getTransactionHistory(), true);
// $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
// 'direction' => 'in',
// 'warehouseId' => $entry->getWarehouseId(),
// 'warehouseActionId' => $entry->getWarehouseActionId(),
// 'fromWarehouseId' => $stitem->getWarehouseId(),
// 'fromWarehouseActionId' => $stitem->getWarehouseActionId()
// );
// $np->setTransactionHistory(json_encode(
// $trans_history
// ));
//
//
// $em->persist($np);
// $em->flush();
// }
// }
// }
// }
}
}
//adding transaction
$spec_item_id = $entry->getId();
if ($item_id == '_single_') {
break;
}
}
}
if ($type == 'prdcn') {
$doc_data = $em->getRepository('ApplicationBundle:Production')->findOneBy(
array(
'productionId' => $id
)
);
if ($item_id == '_single_') {
$doc_item_data = $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
array(
'productionId' => $id,
// 'id' => $item_id
)
);
} else {
$doc_item_data = $em->getRepository('ApplicationBundle:ProductionEntryItem')->findBy(
array(
'productionId' => $id,
'id' => $item_id
)
);
}
$inv_acc_data = [
'fa_amount' => 0,
'tg_amount' => 0,
];
$inv_acc_data_by_head = [
];
$new_non_delivered_sales_code_range = [];
foreach ($doc_item_data as $entry) {
//adding transaction
$sales_code_range_ser = [];
if (in_array($entry->getId(), $skip_ids))
continue;
$product = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $entry->getProductId()
)
);
if ($product) {
if ($product->getHasSerial() == 1) {
//clear if exists
// if($clearUnnecessaryOnly==1) {
// $get_kids_sql = "DELETE FROM product_by_code
// WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
//// $get_kids_sql .=' ORDER BY name ASC';
//
// $stmt = $em->getConnection()->prepare($get_kids_sql);
// $stmt->execute();
// $em->flush();
// }
// else{
// $get_kids_sql = "DELETE FROM product_by_code
// WHERE product_id=" . $entry->getProductId() . " and stock_received_note_id=" . $doc_data->getStockReceivedNoteId();
//// $get_kids_sql .=' ORDER BY name ASC';
//
// $stmt = $em->getConnection()->prepare($get_kids_sql);
// $stmt->execute();
// $em->flush();
// }
// $check_here = $stmt->fetchAll();
//now addng product by code
$sales_code_range = [];
if ($entry->getProducedQty() > 0) {
// if($product->getDefaultPurchaseActionTagId()!=0 &&$product->getDefaultPurchaseActionTagId()!=null)
// $product_action_tag_id=$product->getDefaultPurchaseActionTagId();
// $product_action_tag_id = $entry->getWarehouseActionId();
$barcodeData = Inventory::GenerateBarcode($em, $entry->getProductId(), $entry->getProducedQty(),
$doc_data->getProductionDate(), 0, 0, $doc_data->getCompanyId(), $entry->getWarehouseId(),
$entry->getProducedItemActionTagId(), null, null, null, null, null, null, null, $doc_data->getProductionId(), null
);
$sales_code_range = $barcodeData['sales_code_range'];
$entry->setSalesCodeRange(json_encode($sales_code_range));
$em->flush();
}
// else {
// if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
//
// $sales_code_range = json_decode($entry->getSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
// } else {
//
// $max_int_length = strlen((string)PHP_INT_MAX) - 1;
// $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $entry->getSalesCodeRange());
// $sales_code_range = json_decode($json_without_bigints, true);
// }
// if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
//
// $non_delivered_sales_code_range = json_decode($stitem->getNonDeliveredSalesCodeRange(), true, 512, JSON_BIGINT_AS_STRING);
// } else {
//
// $max_int_length = strlen((string)PHP_INT_MAX) - 1;
// $json_without_bigints = preg_replace('/:\s*(-?\d{' . $max_int_length . ',})/', ': "$1"', $stitem->getNonDeliveredSalesCodeRange());
// $non_delivered_sales_code_range = json_decode($json_without_bigints, true);
// }
//// $non_delivered_sales_code_range= json_decode($stitem->getNonDeliveredSalesCodeRange(),true,512,JSON_BIGINT_AS_STRING);
//// $new_non_delivered_sales_code_range= array_merge(array_diff($non_delivered_sales_code_range, $sales_code_range));
// $new_non_delivered_sales_code_range = [];
// foreach ($non_delivered_sales_code_range as $ndsc) {
// if (!(in_array($ndsc, $sales_code_range)))
// $new_non_delivered_sales_code_range[] = $ndsc;
// }
// if ($sales_code_range != null) {
// foreach ($sales_code_range as $ind => $dt) {
// $np = $em->getRepository('ApplicationBundle:ProductByCode')
// ->findOneBy(
// array(
// 'salesCode' => [$dt],
// 'productId' => $entry->getProductId()
// )
// );
//
// if ($np) {
// $non_delivered_sales_code_range = array_merge(array_diff($non_delivered_sales_code_range, array($dt)));
// $np->setProductId($entry->getProductId());
// $np->setWarehouseId($entry->getWarehouseId());
// $np->setWarehouseActionId($entry->getWarehouseActionId());
// $np->setPosition(1);//in warehouse
// $np->setStockReceivedNoteId($id);
//
//
// $np->setLastInDate($doc_data->getStockReceivedNoteDate());
// $np->setStatus(GeneralConstant::ACTIVE);
// $trans_history = json_decode($np->getTransactionHistory(), true);
// $trans_history[] = array('date' => $doc_data->getStockReceivedNoteDate()->format('Y-m-d'),
// 'direction' => 'in',
// 'warehouseId' => $entry->getWarehouseId(),
// 'warehouseActionId' => $entry->getWarehouseActionId(),
// 'fromWarehouseId' => $stitem->getWarehouseId(),
// 'fromWarehouseActionId' => $stitem->getWarehouseActionId()
// );
// $np->setTransactionHistory(json_encode(
// $trans_history
// ));
//
//
// $em->persist($np);
// $em->flush();
// }
// }
// }
// }
}
}
//adding transaction
$spec_item_id = $entry->getId();
if ($item_id == '_single_') {
break;
}
}
}
return new JsonResponse(array(
'success' => $spec_item_id != 0 ? true : false,
'skipIds' => [],
'spec_item_id' => $spec_item_id
));
// return $this->render('ApplicationBundle:pages/inventory/print:print_srcv_barcodes.html.twig',
// array(
// 'page_title' => 'Srcv barcodes',
//// 'export'=>'pdf,print',
// 'data' => $dt,
// 'repeatCount' => $repeatCount,
// 'item_id' => $item_id,
// 'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
// $id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
// 'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
// array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
// $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 PrintLabelAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
// $dt = Inventory::GetDrDetails($em, $id, $item_id);
$repeatCount = 1;
$assignProductId = '';
$productByCodeIds = [];
$print_selection_type = 1;
$print_selection_string = 1;
$assignLabelFormatId = 0;
$assignColorId = 0;
$assignProductionScheduleId = 0;
$warehouseId = '';
$warehouseActionId = '';
$toAssignPosition = '';
$printFlag = $request->request->has('printFlag') ? $request->request->get('printFlag') : 1;
$returnJson = $request->request->has('returnJson') ? $request->request->get('returnJson') : 0;
if ($returnJson == 1)
$printFlag = 0;
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->query->has('repeatCount'))
$repeatCount = $request->query->get('repeatCount');
if ($request->request->has('print_selection_type'))
$print_selection_type = $request->request->get('print_selection_type');
if ($request->request->has('print_selection_string'))
$print_selection_string = $request->request->get('print_selection_string');
if ($request->request->has('productByCodeIds'))
$productByCodeIds = json_decode($request->request->get('productByCodeIds'), true);
if ($request->request->has('formatId'))
$assignLabelFormatId = $request->request->get('formatId');
if ($printFlag == 0) {
if ($request->request->has('productSelector'))
$assignProductId = $request->request->get('productSelector');
if ($request->request->has('colorId'))
$assignColorId = $request->request->get('colorId');
if ($request->request->has('productionScheduleId'))
$assignProductionScheduleId = $request->request->get('productionScheduleId');
if ($request->request->has('warehouseId'))
$warehouseId = $request->request->get('warehouseId');
if ($request->request->has('warehouseActionId'))
$warehouseActionId = $request->request->get('warehouseActionId');
if ($request->request->has('position'))
$toAssignPosition = $request->request->get('position');
if ($assignColorId == '')
$assignColorId = 0;
}
if ($productByCodeIds == null)
$productByCodeIds = [];
$productByCodeData = [];
$productList = [];
$productIds = [];
if ($print_selection_type == 2) {
//range
$productByCodeIds = Inventory::getIdsFromIdSelectionStr($print_selection_string);
}
$labelData = [
'formatId' => 0
];
$formatId = 0;
if (!empty($productByCodeIds)) {
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')
->findBy(
array(
'productByCodeId' => $productByCodeIds
)
);
foreach ($productByCodeData as $d) {
if ($d->getStage() < 10) $d->setStage(11);
if ($assignProductId != '') {
$d->setProductId($assignProductId);
}
if ($assignColorId != 0) {
$d->setColorId($assignColorId);
} else {
$productData = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $assignProductId
)
);
if ($productData) {
$d->setColorId($productData->getDefaultColorId());
}
}
if ($assignLabelFormatId != 0 && $assignLabelFormatId != '') {
$d->setDefaultLabelFormatId($assignLabelFormatId);
$d->setDeviceLabelFormatId($assignLabelFormatId);
}
$toAssignPosition != '' ? $d->setPosition($toAssignPosition) : '';
$warehouseId != '' ? $d->setWarehouseId($warehouseId) : '';
$warehouseActionId != '' ? $d->setWarehouseActionId($warehouseActionId) : '';
if ($assignProductionScheduleId != 0 && $assignProductionScheduleId != '') {
$d->setProductionScheduleId($assignProductionScheduleId);
$productionSchedule = $em->getRepository('ApplicationBundle:ProductionSchedule')
->findOneBy(
array(
'productionScheduleId' => $assignProductionScheduleId
)
);
if ($productionSchedule) {
if ($assignLabelFormatId != 0 && $assignLabelFormatId != '') {
//becuase it will assigned at previous lines
} else {
$d->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
$d->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
}
$d->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
$d->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
}
}
$em->flush();
if ($d->getProductId() != '' || $d->getProductId() != null)
$productIds[] = $d->getProductId();
$formatId = $d->getDeviceLabelFormatId();
}
}
$labelFormatHere = $em->getRepository('ApplicationBundle:LabelFormat')
->findOneBy(
array(
'formatId' => $formatId,
// 'CompanyId' => $companyId
)
);
if ($labelFormatHere) {
$formatData = json_decode($labelFormatHere->getFormatData(), true);
if ($formatData == null) $formatData = [];
$labelData = array(
'id' => $labelFormatHere->getFormatId(),
'formatId' => $labelFormatHere->getFormatId(),
'labelType' => $labelFormatHere->getLabelType(),
'name' => $labelFormatHere->getName(),
'width' => $labelFormatHere->getWidth(),
'pageWidth' => $labelFormatHere->getPageWidth(),
'height' => $labelFormatHere->getheight(),
'pageHeight' => $labelFormatHere->getPageHeight(),
'formatData' => $formatData,
);
}
$productList = Inventory::ProductList($em, $this->getLoggedUserCompanyId($request), 1, 0, '', $productIds);
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
$dt = $productByCodeData;
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView('ApplicationBundle:pages/inventory/print:print_label.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Device Labels',
'export' => 'print',
'repeatCount' => $repeatCount,
'labelData' => $labelData,
'brandList' => Inventory::GetBrandList($em, $companyId),
// 'item_id' => $item_id,
'data' => $dt,
'productList' => $productList,
'approval_data' => [],
'document_log' => [],
'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="device_labels.pdf"'
)
);
}
$url = $this->generateUrl(
'print_label'
);
if ($returnJson == 1 && $printFlag == 0) {
// $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 return $this->render('ApplicationBundle:pages/inventory/print:print_label.html.twig',
array(
'page_title' => 'Product Labels',
// 'export'=>'pdf,print',
'data' => $dt,
'productList' => $productList,
'repeatCount' => $repeatCount,
// 'item_id' => $item_id,
'labelData' => $labelData,
'brandList' => Inventory::GetBrandList($em, $companyId),
'approval_data' => [],
'document_log' => [],
'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 PrintCartonLabelAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
// $dt = Inventory::GetDrDetails($em, $id, $item_id);
$repeatCount = 1;
$assignProductId = '';
$productByCodeIds = [];
$cartonId = 0;
if ($id != 0)
$cartonId = $id;
$colorText = '';
$weightText = '';
if ($request->query->has('repeatCount'))
$repeatCount = $request->query->get('repeatCount');
if ($request->request->has('printCartonId'))
$cartonId = $request->request->get('printCartonId');
if ($request->request->has('printCartonColorText'))
$colorText = $request->request->get('printCartonColorText');
if ($request->request->has('printCartonWeightText'))
$weightText = $request->request->get('printCartonWeightText');
$labelData = [
'formatId' => 0
];
if ($productByCodeIds == null)
$productByCodeIds = [];
$productByCodeData = [];
$cartonData = [];
$product = [];
if ($cartonId != 0) {
$cartonData = $em->getRepository('ApplicationBundle:Carton')
->findOneBy(
array(
'id' => $cartonId
)
);
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')
->findBy(
array(
'cartonId' => $cartonId
)
);
// if(!empty($productByCodeData))
// $product = $em->getRepository('ApplicationBundle:InvProducts')
// ->findOneBy(
// array(
// 'id' => $productByCodeData[0]->getProductId()
// )
// );
// else
$product = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $cartonData->getProductId()
)
);
$formatId = $cartonData->getCartonLabelFormatId();
$labelFormatHere = $em->getRepository('ApplicationBundle:LabelFormat')
->findOneBy(
array(
'formatId' => $formatId,
// 'CompanyId' => $companyId
)
);
if ($labelFormatHere) {
$formatData = json_decode($labelFormatHere->getFormatData(), true);
if ($formatData == null) $formatData = [];
$labelData = array(
'id' => $labelFormatHere->getFormatId(),
'formatId' => $labelFormatHere->getFormatId(),
'labelType' => $labelFormatHere->getLabelType(),
'name' => $labelFormatHere->getName(),
'width' => $labelFormatHere->getWidth(),
'pageWidth' => $labelFormatHere->getPageWidth(),
'height' => $labelFormatHere->getheight(),
'pageHeight' => $labelFormatHere->getPageHeight(),
'formatData' => $formatData,
);
}
}
$company_data = Company::getCompanyData($em, 1);
$document_mark = array(
'original' => '/images/Original-Stamp-PNG-Picture.png',
'copy' => ''
);
$dt = $productByCodeData;
if ($request->query->has('pdf') && $this->get('knp_snappy.pdf')) {
$html = $this->renderView('ApplicationBundle:pages/inventory/print:print_carton_label.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Carton Labels',
'export' => 'print',
'labelData' => $labelData,
'repeatCount' => $repeatCount,
// 'item_id' => $item_id,
'data' => $dt,
'cartonData' => $cartonData,
'product' => $product,
'colorText' => $colorText,
'weightText' => $weightText,
'approval_data' => [],
'document_log' => [],
'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="device_labels.pdf"'
)
);
}
if ($request->query->has('previewOnly')) {
$html = $this->renderView('ApplicationBundle:pages/inventory/print:print_carton_label.html.twig',
array(
'page_title' => 'Carton Labels',
// 'export'=>'pdf,print',
'data' => $dt,
'skip_parameters' => 1,
'labelData' => $labelData,
'cartonData' => $cartonData,
'product' => $product,
'colorText' => $colorText,
'weightText' => $weightText,
'repeatCount' => $repeatCount,
// 'item_id' => $item_id,
'approval_data' => [],
'document_log' => [],
'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
)
);
if ($request->query->has('returnJson')) {
return new JsonResponse(
array(
'success' => true,
'page_title' => 'Product Details',
'company_data' => $company_data,
'renderedHtml' => $html,
// 'productData' => $productData,
// 'currInvList' => $currInvList,
// '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),
// 'warehouse_action_list' => Inventory::warehouse_action_list($em,$this->getLoggedUserCompanyId($request),'object'),
// 'warehouseList' => Inventory::WarehouseList($em),
)
);
}
}
return $this->render('ApplicationBundle:pages/inventory/print:print_carton_label.html.twig',
array(
'page_title' => 'Carton Labels',
// 'export'=>'pdf,print',
'data' => $dt,
'cartonData' => $cartonData,
'product' => $product,
// 'productByCodeData' => $productByCodeData,
'colorText' => $colorText,
'weightText' => $weightText,
'repeatCount' => $repeatCount,
'labelData' => $labelData,
// 'item_id' => $item_id,
'approval_data' => [],
'document_log' => [],
'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 AssignInfoToProductByCodeAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
// $dt = Inventory::GetDrDetails($em, $id, $item_id);
$cartonId = '';
$passStatus = 5;
$assignProductId = '';
$assignProductionId = '';
$assignProductionScheduleId = '';
$gbWeightGm = '';
$dvWeightGm = '';
$cartonWeightGm = '';
if ($request->request->has('cartonId'))
$cartonId = $request->request->get('cartonId');
if ($request->request->has('passStatus'))
$passStatus = $request->request->get('passStatus');
if ($request->request->has('productByCodeId'))
$id = $request->request->get('productByCodeId');
if ($request->request->has('productId'))
$assignProductId = $request->request->get('productId');
if ($request->request->has('productionId'))
$assignProductionId = $request->request->get('productionId');
if ($request->request->has('productionScheduleId'))
$assignProductionScheduleId = $request->request->get('productionScheduleId');
if ($request->request->has('gbWeightGm'))
$gbWeightGm = $request->request->get('gbWeightGm');
if ($request->request->has('dvWeightGm'))
$dvWeightGm = $request->request->get('dvWeightGm');
if ($request->request->has('cartonWeightGm'))
$cartonWeightGm = $request->request->get('cartonWeightGm');
$cartonAssignedAlready = 0;
$otherData = array(
'currentCartonBalance' => 0,
'currentCartonCapacity' => 0,
'currentCartonAssigned' => 0,
'currentCartonFull' => 0,
);
if ($id != 0 && $id != '') {
$productByCodeData = $em->getRepository('ApplicationBundle:ProductByCode')
->findOneBy(
array(
'productByCodeId' => $id
)
);
if ($assignProductId != '') $productByCodeData->setProductId($assignProductId);
if ($productByCodeData->getCartonId() != '' || $productByCodeData->getCartonId() != null)
$cartonAssignedAlready = 1;
else if ($cartonId != '') $productByCodeData->setCartonId($cartonId);
if ($dvWeightGm != '') $productByCodeData->setSingleWeightGm($dvWeightGm);
if ($gbWeightGm != '') {
$productByCodeData->setPackagedWeightGm($gbWeightGm);
}
$colorText = '_NA_';
if ($passStatus != 5) $productByCodeData->setStage($passStatus);
$productByCodeData->setCompanyId($companyId);
if ($assignProductionId != '') {
$productByCodeData->setProductionId($assignProductionId);
$productionData = $em->getRepository('ApplicationBundle:Production')
->findOneBy(
array(
'productionId' => $assignProductionId
)
);
if ($assignProductId != '' && $assignProductId != null && $assignProductId != 0)
$productionItemData = $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
array(
'productionId' => $assignProductionId,
'productId' => $assignProductId,
'type' => 1,
)
);
else
$productionItemData = $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
array(
'productionId' => $assignProductionId,
// 'productId' => $assignProductId,
'type' => 1,
)
);
$assignProductionScheduleId = $productionData->getProductionScheduleId();
if ($productionItemData) {
$productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
$productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
$productByCodeData->setPosition(1);//in inventory
$productByCodeData->setSerialAssigned(1);
$productByCodeData->setColorId($productionItemData->getColorId());
$productByCodeData->setColorText($productionItemData->getColorText());
$productByCodeData->setLastInDate($productionItemData->getProductionDate());
$productByCodeData->setStatus(GeneralConstant::ACTIVE);
if ($passStatus == 1)//passed
{
// $transDate = new \DateTime();
// Inventory::addItemToInventoryCompact($em,
// $productionItemData->getProductId(),
// $productionItemData->getWarehouseId(),
// $productionItemData->getWarehouseId(),
// $productionData->getProducedItemActionTagId(),
// $productionData->getProducedItemActionTagId(), //finised goods hobe
// $transDate,
// 1,
// 1,
// $entry['valueAdd'],
// $entry['valueSub'],
// $entry['price'],
// $this->getLoggedUserCompanyId($request),
// 0,
// $entry['entity'],
// $entry['entityId'],
// $entry['entityDocHash']
// );
}
$transHistory = json_decode($productByCodeData->getTransactionHistory(), true);
if ($transHistory == null)
$transHistory = [];
$transHistory[] = array(
'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
'direction' => 'in',
'warehouseId' => $productionItemData->getWarehouseId(),
'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
'fromWarehouseId' => 0,
'fromWarehouseActionId' => 0 //stock of goods
);
$productByCodeData->setTransactionHistory(json_encode($transHistory));
}
}
if ($assignProductionScheduleId != 0 && $assignProductionScheduleId != '') {
$productByCodeData->setProductionScheduleId($assignProductionScheduleId);
$productionSchedule = $em->getRepository('ApplicationBundle:ProductionSchedule')
->findOneBy(
array(
'productionScheduleId' => $assignProductionScheduleId
)
);
if ($productionSchedule) {
$productByCodeData->setDefaultLabelFormatId($productionSchedule->getDefaultLabelFormatId());
$productByCodeData->setDeviceLabelFormatId($productionSchedule->getDeviceLabelFormatId());
$productByCodeData->setBoxLabelFormatId($productionSchedule->getBoxLabelFormatId());
$productByCodeData->setCartonLabelFormatId($productionSchedule->getCartonLabelFormatId());
if ($productByCodeData->getProductionId() == null || $productByCodeData->getProductionId() == '' || $productByCodeData->getProductionId() == 0) {
$productionItemData = $em->getRepository('ApplicationBundle:ProductionEntryItem')->findOneBy(
array(
'productionScheduleId' => $assignProductionScheduleId,
'productId' => $productionSchedule->getProducedProductId(),
'type' => 1,
)
);
// $assignProductionScheduleId=$productionData->getProductionScheduleId();
if ($productionItemData) {
$productByCodeData->setProductionId($productionItemData->getProductionId());
$productByCodeData->setWarehouseId($productionItemData->getWarehouseId());
$productByCodeData->setWarehouseActionId($productionItemData->getProducedItemActionTagId());
$productByCodeData->setPosition(1);//in inventory
$productByCodeData->setSerialAssigned(1);
$productByCodeData->setColorId($productionItemData->getColorId());
$productByCodeData->setColorText($productionItemData->getColorText());
$productByCodeData->setLastInDate($productionItemData->getProductionDate());
$productByCodeData->setStatus(GeneralConstant::ACTIVE);
if ($passStatus == 1)//passed
{
// $transDate = new \DateTime();
// Inventory::addItemToInventoryCompact($em,
// $productionItemData->getProductId(),
// $productionItemData->getWarehouseId(),
// $productionItemData->getWarehouseId(),
// $productionData->getProducedItemActionTagId(),
// $productionData->getProducedItemActionTagId(), //finised goods hobe
// $transDate,
// 1,
// 1,
// $entry['valueAdd'],
// $entry['valueSub'],
// $entry['price'],
// $this->getLoggedUserCompanyId($request),
// 0,
// $entry['entity'],
// $entry['entityId'],
// $entry['entityDocHash']
// );
}
$transHistory = json_decode($productByCodeData->getTransactionHistory(), true);
if ($transHistory == null)
$transHistory = [];
$transHistory[] = array(
'date' => $productionItemData->getProductionDate()->format('Y-m-d'),
'direction' => 'in',
'warehouseId' => $productionItemData->getWarehouseId(),
'warehouseActionId' => $productionItemData->getProducedItemActionTagId(),
'fromWarehouseId' => 0,
'fromWarehouseActionId' => 0 //stock of goods
);
$productByCodeData->setTransactionHistory(json_encode($transHistory));
}
}
}
}
// $productByCodeData->setPurchaseWarrantyLastDate($new_pwld);
$em->flush();
//now adding carton
}
if ($cartonId != '') {
$carton = $em->getRepository('ApplicationBundle:Carton')
->findOneBy(
array(
'id' => $cartonId
)
);
if ($cartonWeightGm != '') $carton->setCartonWeightGm($cartonWeightGm);
$otherData['currentCartonCapacity'] = $carton->getCartonCapacityCount();
if ($cartonAssignedAlready == 0)
$carton->setCartonAssignedCount((1 * $carton->getCartonAssignedCount()) + 1);
$otherData['currentCartonAssigned'] = $carton->getCartonAssignedCount();
$otherData['currentCartonBalance'] = $otherData['currentCartonCapacity'] - $otherData['currentCartonAssigned'];
if ($otherData['currentCartonAssigned'] >= $otherData['currentCartonCapacity'])
$otherData['currentCartonFull'] = 1;
$em->flush();
}
if ($cartonId != '') {
// if($cartonAssignedAlready==1)
// {
$productByCodeDataListForThisCarton = $em->getRepository('ApplicationBundle:ProductByCode')
->findBy(
array(
'cartonId' => $cartonId
)
);
$carton = $em->getRepository('ApplicationBundle:Carton')
->findOneBy(
array(
'id' => $cartonId
)
);
$total_carton_predicted_weight = 0;
$colorTextList = [];
$cartonProductByCodeIds = [];
foreach ($productByCodeDataListForThisCarton as $pikamaster) {
if (!in_array($pikamaster->getProductByCodeId(), $cartonProductByCodeIds))
$cartonProductByCodeIds[] = $pikamaster->getProductByCodeId();
if (!in_array($pikamaster->getColorText(), $colorTextList) && $pikamaster->getColorText() != null)
$colorTextList[] = $pikamaster->getColorText();
$total_carton_predicted_weight += (1 * $pikamaster->getPackagedWeightGm());
if ($passStatus != 5)
if ($pikamaster->getStage() < $passStatus)
$pikamaster->setStage($passStatus);
}
if ($carton)
$carton->setCartonCalculatedWeightGm($total_carton_predicted_weight);
if ($passStatus != 5)
$carton->setStage($passStatus);
$carton->setColors(implode(',', $colorTextList));
$carton->setCartonProductByCodeIds(json_encode($cartonProductByCodeIds));
$em->flush();
}
return new JsonResponse(array(
'success' => true,
'otherData' => $otherData,
));
}
public
function RefreshCartonListAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
// $dt = Inventory::GetDrDetails($em, $id, $item_id);
$cartonListArray = [];
$cartonList = [];
$assignableCartonList = [];
$assignableCartonListArray = [];
$assignable = 0;
$cartonId = '';
$passStatus = 5;
$assignProductId = '';
$assignProductionId = '';
$assignProductionScheduleId = '';
if ($request->request->has('productionId'))
$assignProductionId = $request->request->get('productionId');
if ($request->request->has('productionScheduleId'))
$assignProductionScheduleId = $request->request->get('productionScheduleId');
if ($request->request->has('assignable'))
$assignable = $request->request->get('assignable');
$cartonAssignedAlready = 0;
$otherData = array(
'currentCartonBalance' => 0,
'currentCartonCapacity' => 0,
'currentCartonAssigned' => 0,
'currentCartonFull' => 0,
);
//1st get all cartons for this production id
$cartonList = $em->getRepository('ApplicationBundle:Carton')
->findBy(
array(
// 'productionId' => $assignProductionId,
'productionScheduleId' => $assignProductionScheduleId
)
);
$foundAssignable = 0;
$setId = 0;
$lastdmySer = '';
foreach ($cartonList as $carton) {
$cartonData = array(
'id' => $carton->getId(),
'name' => $carton->getCartonNumber(),
'colors' => $carton->getColors(),
'cartonCapacityCount' => $carton->getCartonCapacityCount(),
'cartonAssignedCount' => $carton->getCartonAssignedCount(),
);
$cartonListArray[] = $cartonData;
$cartonList[$cartonData['id']] = $cartonData;
if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
$foundAssignable = 1;
$setId = $cartonData['id'];
$assignableCartonList[$cartonData['id']] = $cartonData;
$assignableCartonListArray[] = $cartonData;
}
}
if ($assignable == 1 && $foundAssignable == 0) {
// $productionData = $em->getRepository('ApplicationBundle:Production')
// ->findOneBy(
// array(
// 'productionId' => $assignProductionId
// )
// );
$productionScheduleData = $em->getRepository('ApplicationBundle:ProductionSchedule')
->findOneBy(
array(
'productionScheduleId' => $assignProductionScheduleId
)
);
$productId = 0;
$product = [];
$productModel = '';
if ($productionScheduleData)
$productId = $productionScheduleData->getProducedProductId();
// $productionItem = $em->getRepository('ApplicationBundle:ProductionEntryItem')
// ->findOneBy(
// array(
// 'productionId' => $assignProductionId,
// 'type' => 1
// )
// );
if ($productId != 0) {
// $productId = $productionItem->getProductId();
$product = $em->getRepository('ApplicationBundle:InvProducts')
->findOneBy(
array(
'id' => $productId,
)
);
$productModel = $product->getModelNo();
}
$carton = new Carton();
$carton_capacity = $productionScheduleData->getCartonCapacity();
$carton->setProductId($productId);
$carton->setProductionId($assignProductionId);
$carton->setProductionScheduleId($assignProductionScheduleId);
if ($productionScheduleData) {
$carton->setCartonLabelFormatId($productionScheduleData->getCartonLabelFormatId());
}
$carton->setCartonCapacityCount($carton_capacity == null ? 0 : $carton_capacity);
$carton->setCartonAssignedCount(0);
$carton->setCompanyId($this->getLoggedUserCompanyId($request));
$today = new \DateTime();
$dmy = $productModel . '-' . ($today->format('m')) . '-' . ($today->format('Y')) . '-' . $productionScheduleData->getBatchNumber();
$ser = 0;
$carton->setCartonNumberDmy($dmy);
$carton->setCartonNumberLastSer(1 * (($today->format('h')) . '' . ($today->format('i'))));
$carton->setCartonNumber($dmy . '-' . ($today->format('h')) . '' . ($today->format('i')));
$em->persist($carton);
$em->flush();
$cartonData = array(
'id' => $carton->getId(),
'name' => $carton->getCartonNumber(),
'colors' => $carton->getColors(),
'cartonCapacityCount' => $carton->getCartonCapacityCount(),
'cartonAssignedCount' => $carton->getCartonAssignedCount(),
);
$cartonListArray[] = $cartonData;
$cartonList[$cartonData['id']] = $cartonData;
if ($cartonData['cartonCapacityCount'] > $cartonData['cartonAssignedCount']) {
$foundAssignable = 1;
$setId = $cartonData['id'];
$assignableCartonList[$cartonData['id']] = $cartonData;
$assignableCartonListArray[] = $cartonData;
}
}
return new JsonResponse(array(
'success' => true,
'cartonList' => $cartonList,
'cartonListArray' => $cartonListArray,
'assignableCartonList' => $assignableCartonList,
'assignableCartonListArray' => $assignableCartonListArray,
'setId' => $setId,
));
}
public
function PrintDrBarcodeAction(Request $request, $id, $item_id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetDrDetails($em, $id, $item_id);
$repeatCount = 1;
if ($request->query->has('repeatCount'))
$repeatCount = $request->query->get('repeatCount');
$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('ApplicationBundle:pages/inventory/print:print_dr_barcodes.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Challan Barcodes',
'export' => 'print',
'repeatCount' => $repeatCount,
'item_id' => $item_id,
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
$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="srcv_barcodes.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_dr_barcodes.html.twig',
array(
'page_title' => 'Challan barcodes',
// 'export'=>'pdf,print',
'data' => $dt,
'repeatCount' => $repeatCount,
'item_id' => $item_id,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['DeliveryReceipt'],
$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 PrintIrrBarcodeAction(Request $request, $id, $item_id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetIrrDetails($em, $id, $item_id);
$repeatCount = 1;
if ($request->query->has('repeatCount'))
$repeatCount = $request->query->get('repeatCount');
$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('ApplicationBundle:pages/inventory/print:print_irr_barcodes.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Sales Return Barcodes',
'export' => 'print',
'repeatCount' => $repeatCount,
'item_id' => $item_id,
'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_barcodes.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_irr_barcodes.html.twig',
array(
'page_title' => 'Sales Return barcodes',
// 'export'=>'pdf,print',
'data' => $dt,
'repeatCount' => $repeatCount,
'item_id' => $item_id,
'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 PrintSrcvBarcodeAction(Request $request, $id, $item_id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetSrcvDetails($em, $id, $item_id);
$repeatCount = 1;
if ($request->query->has('repeatCount'))
$repeatCount = $request->query->get('repeatCount');
$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('ApplicationBundle:pages/inventory/print:print_srcv_barcodes.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Grn Barcodes',
'export' => 'print',
'repeatCount' => $repeatCount,
'item_id' => $item_id,
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$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="srcv_barcodes.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_srcv_barcodes.html.twig',
array(
'page_title' => 'Srcv barcodes',
// 'export'=>'pdf,print',
'data' => $dt,
'repeatCount' => $repeatCount,
'item_id' => $item_id,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockReceivedNote'],
$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
)
);
}
//product by code
public
function ImeiListExcelUploadAction(Request $request)
{
$lastIndex = $request->request->get('lastIndex', 0);
if ($request->isMethod('POST')) {
$post = $request->request;
if ($request->request->has('chunkData')) {
//now getting the relevant checks
$check_list = [];
$csv_data = $request->request->get('chunkData', []);
$em = $this->getDoctrine()->getManager();
foreach ($csv_data as $ind => $data_row) {
// if ($ind == 1)
// continue;
$np = $this->getDoctrine()
->getRepository('ApplicationBundle:ProductByCode')
->findOneBy(
array(
'salesCode' => isset($data_row[4]) ? $data_row[4] : 0,
// 'approved' => GeneralConstant::APPROVED,
)
);
if (!$np)
$np = new ProductByCode();
// $np = new ProductByCode();
$np->setCompanyId($this->getLoggedUserCompanyId($request));
if (isset($data_row[1])) $np->setProductId($data_row[1]);
if (isset($data_row[0])) $np->setLcNumber($data_row[0]);
if (isset($data_row[2])) $np->setCartonNumber($data_row[2]);
if (isset($data_row[3])) $np->setSerialNo($data_row[3]);
$np->setSerialAssigned(isset($data_row[10]) ? $data_row[10] : 0);
if (isset($data_row[4])) $np->setImei1($data_row[4]);
if (isset($data_row[5])) $np->setImei2($data_row[5]);
if (isset($data_row[6])) $np->setImei3($data_row[6]);
if (isset($data_row[7])) $np->setImei4($data_row[7]);
if (isset($data_row[8])) $np->setBtMac($data_row[8]);
if (isset($data_row[9])) $np->setWlanMac($data_row[9]);
$np->setWarehouseId(isset($data_row[11]) ? $data_row[11] : 0);
$np->setWarehouseActionId(isset($data_row[12]) ? $data_row[12] : 0);
$np->setPosition(isset($data_row[13]) ? $data_row[13] : 0);//in inventory
$np->setPurchaseOrderId(0);
$np->setGrnId(0);
$np->setStage(0);
if (isset($data_row[3])) $np->setSalesCodeRange(json_encode([$data_row[3]]));
// $np->setSalesCode($data_row[3]);
if (isset($data_row[4])) $np->setSalesCode($data_row[4]); //IMEI
$np->setSalesCodeSer(0);
$np->setSalesCodeDmy('');
$np->setPurchaseCodeRange("");
$np->setPurchaseReceiptDate(null);
$np->setLastInDate(null);
$np->setStatus(GeneralConstant::ACTIVE);
$np->setTransactionHistory(json_encode([
]
));
$np->setPurchaseWarrantyLastDate(null);
$em->persist($np);
$em->flush();
}
return new JsonResponse(array(
"success" => true,
"lastIndex" => $lastIndex,
"file_path" => '',
"csv_data" => $csv_data,
// "debug_data"=>System::encryptSignature($r)
));
} else {
$path = "";
$file_path = "";
// var_dump($request->files);
// var_dump($request->getFile());
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;
//
// $img_file = file_get_contents($g_path);
// $r=base64_encode($img_file);
$row = 1;
$csv_data = [];
if (($handle = fopen($g_path, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$csv_data[$row] = $data;
// echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
// for ($c=0; $c < $num; $c++) {
// echo $data[$c] . "<br />\n";
// }
}
fclose($handle);
}
//now getting the relevant checks
$check_list = [];
$em = $this->getDoctrine()->getManager();
foreach ($csv_data as $ind => $data_row) {
if ($ind == 1)
continue;
$np = new ProductByCode();
$np->setCompanyId($this->getLoggedUserCompanyId($request));
$np->setProductId($data_row[1]);
$np->setLcNumber($data_row[0]);
$np->setCartonNumber($data_row[2]);
$np->setSerialNo($data_row[3]);
$np->setSerialAssigned(0);
$np->setImei1($data_row[4]);
$np->setImei2($data_row[5]);
$np->setImei3($data_row[6]);
$np->setImei4($data_row[7]);
$np->setBtMac($data_row[8]);
$np->setWlanMac($data_row[9]);
$np->setWarehouseId(0);
$np->setWarehouseActionId(0);
$np->setPosition(0);//in inventory
$np->setPurchaseOrderId(0);
$np->setGrnId(0);
$np->setStage(0);
$np->setSalesCodeRange(json_encode([$data_row[3]]));
// $np->setSalesCode($data_row[3]);
$np->setSalesCode($data_row[4]); //IMEI
$np->setSalesCodeSer(0);
$np->setSalesCodeDmy('');
$np->setPurchaseCodeRange("");
$np->setPurchaseReceiptDate(null);
$np->setLastInDate(null);
$np->setStatus(GeneralConstant::ACTIVE);
$np->setTransactionHistory(json_encode([
]
));
$np->setPurchaseWarrantyLastDate(null);
$em->persist($np);
$em->flush();
}
return new JsonResponse(array(
"success" => true,
"lastIndex" => $lastIndex,
"file_path" => $file_path,
"csv_data" => $csv_data,
// "debug_data"=>System::encryptSignature($r)
));
}
}
return new JsonResponse(array(
"success" => false,
"file_path" => '',
"csv_data" => [],
"lastIndex" => $lastIndex,
));
}
public
function ProductByCodeListAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$listData = Inventory::GetProductListForProductByCodeListAjaxAction($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
);
}
}
$q = [];
// $q = $this->getDoctrine()
// ->getRepository('ApplicationBundle:ProductByCode')
// ->findBy(
// array(
// 'status' => GeneralConstant::ACTIVE,
//// 'approved' => GeneralConstant::APPROVED,
// )
//
// );
//temp start
// foreach($q as $np) {
// if($np->getPosition()==1) { /// only starting ones or in warehouse ones
// $temp_obj = json_decode($np->getTransactionHistory());
// if ($temp_obj != null) {
// $transHistory = [];
// $transHistory[] = $temp_obj;
// $np->setTransactionHistory(json_encode($transHistory));
// }
// }
// $em->flush();
// }
///temp end
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
// foreach($q as $entry)
// {
// $data[]=array(
// 'doc_date'=>$entry->getStockRequisitionDate(),
// 'id'=>$entry->getStockRequisitionId(),
// 'doc_hash'=>$entry->getDocumentHash(),
// 'approval_status'=>GeneralConstant::$approvalStatus[$entry->getApproved()],
// 'stage'=>$stage_list[$entry->getStage()]
//
// );
// }
return $this->render('ApplicationBundle:pages/inventory/view:product_by_code_list.html.twig',
array(
'page_title' => 'Product List',
'data' => $q,
// 'listData' => $listData,
'products' => Inventory::ProductList($em),
'warehouseList' => Inventory::WarehouseList($em)
)
);
}
//SR
public
function SrListAction(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:StockRequisition')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
// 'approved' => GeneralConstant::APPROVED,
)
,
array(
'stockRequisitionDate' => 'DESC'
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getStockRequisitionDate(),
'id' => $entry->getStockRequisitionId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'stage' => $stage_list[$entry->getStage()],
'indentTagged' => $entry->getIndentTagged(),
'srIds' => $entry->getSrIds(),
'irIds' => $entry->getIrIds(),
'prIds' => $entry->getPrIds(),
'poIds' => $entry->getPoIds(),
);
}
return $this->render('ApplicationBundle:pages/inventory/view:sr_list.html.twig',
array(
'page_title' => 'Stock Requisition List',
'data' => $data
)
);
}
public
function ViewSrAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetSrDetails($em, $id);
return $this->render('ApplicationBundle:pages/inventory/view:view_stock_requisition.html.twig',
array(
'page_title' => 'Stock requisition',
'data' => $dt,
'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public
function PrintSrAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetSrDetails($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('ApplicationBundle:pages/inventory/print:print_sr.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Stock REquisition',
'export' => 'pdf,print',
'data' => $dt,
'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
$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="stock_requisition_' . $id . '.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_sr.html.twig',
array(
'page_title' => 'Stock Requisition',
'export' => 'pdf,print',
'data' => $dt,
'userList' => Users::getUserListById($this->getDoctrine()->getManager()),
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StockRequisition'],
$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
)
);
}
//IR
public
function IrListAction(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:StoreRequisition')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
// 'approved' => GeneralConstant::APPROVED,
),
array(
'storeRequisitionDate' => 'DESC'
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getStoreRequisitionDate(),
'id' => $entry->getStoreRequisitionId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'stage' => $stage_list[$entry->getStage()],
'prTagged' => $entry->getIndentTagged(),
'srIds' => $entry->getSrIds(),
'irIds' => $entry->getIrIds(),
'prIds' => $entry->getPrIds(),
'poIds' => $entry->getPoIds(),
);
}
return $this->render('ApplicationBundle:pages/inventory/view:ir_list.html.twig',
array(
'page_title' => 'Indent Requisition List',
'data' => $data
)
);
}
public
function ViewIrAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetIrDetails($em, $id);
return $this->render('ApplicationBundle:pages/inventory/view:view_indent_requisition.html.twig',
array(
'page_title' => 'Indent',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public
function PrintIrAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetIrDetails($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('ApplicationBundle:pages/inventory/print:print_ir.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Indent Requisition',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
$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="indent_' . $id . '.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_ir.html.twig',
array(
'page_title' => 'Indent Requisition',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['StoreRequisition'],
$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
)
);
}
//PR
public
function PrListAction(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:PurchaseRequisition')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
// 'approved' => GeneralConstant::APPROVED,
),
array(
'purchaseRequisitionDate' => 'DESC'
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getPurchaseRequisitionDate(),
'id' => $entry->getPurchaseRequisitionId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'acquisition_status' => $entry->getAcquisitionStatus(),
'acquisition_start_date' => $entry->getAcquisitionStartDate(),
'acquisition_end_date' => $entry->getAcquisitionEndDate(),
'acquisition_method' => $entry->getquotationAcquisitionMethod(),
'poTagged' => $entry->getPoTagged(),
'typeHash' => $entry->getTypehash(),
'srIds' => $entry->getSrIds(),
'irIds' => $entry->getIrIds(),
'prIds' => $entry->getPrIds(),
'poIds' => $entry->getPoIds(),
);
}
return $this->render('ApplicationBundle:pages/inventory/view:pr_list.html.twig',
array(
'page_title' => 'Purchase Requisition List',
'data' => $data
)
);
}
public
function ServiceRequisitionListAction(Request $request)
{
$q = $this->getDoctrine()
->getRepository('ApplicationBundle:PurchaseRequisition')
->findBy(
array(
'status' => GeneralConstant::ACTIVE,
// 'approved' => GeneralConstant::APPROVED,
),
array(
'purchaseRequisitionDate' => 'DESC'
)
);
$stage_list = array(
0 => 'Pending',
1 => 'Pending',
2 => 'Complete',
4 => 'Partial',
);
$data = [];
foreach ($q as $entry) {
$data[] = array(
'doc_date' => $entry->getPurchaseRequisitionDate(),
'id' => $entry->getPurchaseRequisitionId(),
'doc_hash' => $entry->getDocumentHash(),
'approval_status' => GeneralConstant::$approvalStatus[$entry->getApproved()],
'poTagged' => $entry->getPoTagged(),
'typeHash' => $entry->getTypehash(),
'srIds' => $entry->getSrIds(),
'irIds' => $entry->getIrIds(),
'prIds' => $entry->getPrIds(),
'poIds' => $entry->getPoIds(),
);
}
return $this->render('ApplicationBundle:pages/inventory/view:service_requisition_list.html.twig',
array(
'page_title' => 'Service Requisition List',
'data' => $data
)
);
}
public
function ViewPrAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetPrDetails($em, $id);
$companyId = $this->getLoggedUserCompanyId($request);
return $this->render('ApplicationBundle:pages/inventory/view:view_purchase_requisition.html.twig',
array(
'page_title' => 'Purchase Requisition',
'data' => $dt,
'branchList' => Client::BranchList($em, $companyId),
'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public
function ViewServiceRequisitionAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetPrDetails($em, $id);
return $this->render('ApplicationBundle:pages/inventory/view:view_purchase_requisition.html.twig',
array(
'page_title' => 'Service Requisition',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
$id,
$dt['created_by'],
$dt['edited_by'])
)
);
}
public
function PrintPrAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$dt = Inventory::GetPrDetails($em, $id);
$companyId = $this->getLoggedUserCompanyId($request);
$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('ApplicationBundle:pages/inventory/print:print_pr.html.twig',
array(
//full array here
'pdf' => true,
'page_title' => 'Purchase Requisition',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
$id,
$dt['created_by'],
$dt['edited_by']),
'document_mark_image' => $document_mark['original'],
'branchList' => Client::BranchList($em, $companyId),
'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
'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="purchase_requisition_' . $id . '.pdf"'
)
);
}
return $this->render('ApplicationBundle:pages/inventory/print:print_pr.html.twig',
array(
'page_title' => 'Purchase Requisition',
'export' => 'pdf,print',
'data' => $dt,
'approval_data' => System::checkIfApprovalExists($em, array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
$id, $request->getSession()->get(UserConstants::USER_LOGIN_ID)),
'document_log' => System::getDocumentLog($this->getDoctrine()->getManager(),
array_flip(GeneralConstant::$Entity_list)['PurchaseRequisition'],
$id,
$dt['created_by'],
$dt['edited_by']),
'document_mark_image' => $document_mark['original'],
'company_name' => $company_data->getName(),
'company_data' => $company_data,
'branchList' => Client::BranchList($em, $companyId),
'supplier_list' => Supplier::GetSupplierList($this->getDoctrine()->getManager(), []),
'company_address' => $company_data->getAddress(),
'company_image' => $company_data->getImage(),
'invoice_footer' => $company_data->getInvoiceFooter(),
'red' => 0
)
);
}
public
function CreateSecondaryDeliveryReceiptAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
$userBranchIdList = $request->getSession()->get('branchIdList');
if ($userBranchIdList == null) $userBranchIdList = [];
$userBranchId = $request->getSession()->get('branchId');
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)
) {
$this->addFlash(
'error',
'Sorry Couldnot insert Data.'
);
} else {
$receiptId = SalesOrderM::CreateNewSecondaryDeliveryReceipt($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
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)
);
$this->addFlash(
'success',
'New Delivery Receipt Created'
);
$url = $this->generateUrl(
'view_delivery_receipt'
);
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'];
}
return $this->render('ApplicationBundle:pages/inventory/input_forms:secondaryDeliveryReceipt.html.twig',
array(
'page_title' => 'New Delivery Receipt',
'ExistingClients' => Accounts::getClientLedgerHeads($em),
'ClientListByAcHead' => SalesOrderM::GetSecondaryClientListByAcHead($em),
'ClientList' => SalesOrderM::GetSecondaryClientList($em),
'warehouse' => Inventory::WarehouseList($em, $companyId, $warehouseIds),
'salesOrders' => SalesOrderM::SecondarySalesOrderListPendingDelivery($em, $warehouseIds),
'salesOrdersArray' => SalesOrderM::SecondarySalesOrderListPendingDeliveryArray($em, $warehouseIds),
'deliveryOrders' => SalesOrderM::DeliveryOrderListPendingDelivery($em),
'deliveryOrdersArray' => SalesOrderM::DeliveryOrderListPendingDeliveryArray($em),
'debugData' => $debugData,
)
);
}
public
function AddUnitTypeAction(Request $request, $id = 0)
{
$em = $this->getDoctrine()->getManager();
$companyId = $this->getLoggedUserCompanyId($request);
if ($request->isMethod('POST')) {
$loginId = $request->getSession()->get(UserConstants::USER_LOGIN_ID);
$unitType = new UnitType();
$unitType->setName($request->request->get('name'));
$unitType->setStatus(1);
$em->persist($unitType);
$em->flush();
$this->addFlash(
'success',
'Unit Type Added'
);
}
$unitTypeDeatails = $em->getRepository(UnitType::class)->findAll();
return $this->render('ApplicationBundle:pages/inventory/input_forms:addUnitType.html.twig',
array(
'page_title' => 'Add Unit Type',
'unitTypeDeatails' => $unitTypeDeatails
)
);
}
public
function SubcategoryListAction()
{
return $this->render('ApplicationBundle:pages/inventory/input_forms:subCategoryList.html.twig',
array(
'page_title' => 'Sub Category List',
)
);
}
}