From 9ddce65adf75602d17bd5f5dc86fdffd315f7ea4 Mon Sep 17 00:00:00 2001 From: Khurshid Alam Date: Sun, 6 Nov 2022 19:53:39 +0600 Subject: [PATCH] Security Update --- core/ajax/ajax_call.php | 2 +- core/ajax/ajax_data.php | 111 +- core/ajax/ajax_pos.php | 12 +- core/ajax/ajax_pos_back.php | 638 +++++ core/ajax/ajax_sms.php | 10 +- core/functions.php | 2 +- module/accounts/ajax.php | 8 +- module/expenses/ajax.php | 16 +- module/home.php | 85 +- module/incomes/ajax.php | 8 +- module/journals/ajax.php | 720 ++++++ module/journals/journal-list.php | 68 + module/journals/journal-records.php | 72 + module/my-shop/ajax.php | 6 +- module/peoples/ajax.php | 6 +- module/products/ajax.php | 16 +- module/reports/ajax.php | 18 +- module/reports/ajax_back.php | 2057 ----------------- .../expense-report/expense-report-non-cat.php | 6 +- .../expense-report/expense-report-single.php | 6 +- module/reports/sales-report.php | 2 +- 21 files changed, 1709 insertions(+), 2160 deletions(-) create mode 100644 core/ajax/ajax_pos_back.php create mode 100644 module/journals/ajax.php create mode 100644 module/journals/journal-list.php create mode 100644 module/journals/journal-records.php delete mode 100644 module/reports/ajax_back.php diff --git a/core/ajax/ajax_call.php b/core/ajax/ajax_call.php index c99f320..b0c3545 100644 --- a/core/ajax/ajax_call.php +++ b/core/ajax/ajax_call.php @@ -28,7 +28,7 @@ - "> + "> diff --git a/core/ajax/ajax_data.php b/core/ajax/ajax_data.php index 046a5e5..6739f22 100644 --- a/core/ajax/ajax_data.php +++ b/core/ajax/ajax_data.php @@ -171,8 +171,8 @@ $warehouse_id = isset($_GET["warehouse_id"]) ? (int)safe_input($_GET["warehouse_id"]) : ""; $customer_id = isset($_GET["cid"]) ? (int)safe_input($_GET["cid"]) : ""; - $product_qnt = (isset($_GET["pqnt"]) and !empty($_GET["pqnt"])) ? $_GET["pqnt"] : get_options("defaultSaleQnt"); - $packet = ( isset($_GET["packet"]) and !empty($_GET["packet"]) ) ? $_GET["packet"] : 0; + $product_qnt = (isset($_GET["pqnt"]) and !empty($_GET["pqnt"])) ? safe_entities($_GET["pqnt"]) : get_options("defaultSaleQnt"); + $packet = ( isset($_GET["packet"]) and !empty($_GET["packet"]) ) ? safe_entities($_GET["packet"]) : 0; $customerType = "consumer"; $selectCustomerType = easySelectA(array( @@ -1711,4 +1711,111 @@ } + + + +if(isset($_GET['page']) and $_GET['page'] == "salesOverviewChartData") { + + $type = isset($_GET["type"]) ? $_GET["type"] : "daily"; + + if( $type === "weekly" ) { + + $weeklySalesData = easySelectD(" + SELECT + concat(date_format(db_date, '%D %M')) AS label, + if(sales_quantity is null, 0, sum(sales_quantity)) as sales_quantity + FROM time_dimension + LEFT JOIN ( + SELECT + sales_delivery_date, + sum(sales_quantity) as sales_quantity + FROM {$table_prefeix}sales + WHERE is_trash = 0 + GROUP BY sales_delivery_date + ) AS sales on sales_delivery_date = db_date + WHERE db_date BETWEEN NOW() - INTERVAL 30 WEEK AND NOW() + group by week(db_date) + "); + + $weeklySalesOverviewLabel = array(); + $weeklySalesOverviewData = array(); + + if( $weeklySalesData !== false ) { + + foreach($weeklySalesData["data"] as $sales ) { + array_push($weeklySalesOverviewLabel, $sales["label"] ); + array_push($weeklySalesOverviewData, $sales["sales_quantity"] ); + } + + } + + + $weeklySalesData = array( + "labels" => $weeklySalesOverviewLabel, + "datasets" => array( + array( + "label" => __("Weekly Sales"), + "borderColor" => "green", + "borderWidth" => 2, + "data" => $weeklySalesOverviewData + ) + ) + ); + + echo json_encode($weeklySalesData); + + + } else { + + + /** Daily Sales Calculatin */ + + $dailySalesData = easySelectD(" + SELECT + db_date AS label, + if(sales_quantity is null, 0, sales_quantity) as sales_quantity + FROM time_dimension + LEFT JOIN ( + SELECT + sales_delivery_date, + sum(sales_quantity) as sales_quantity + FROM {$table_prefeix}sales + WHERE is_trash = 0 + GROUP BY sales_delivery_date + ) AS sales on sales_delivery_date = db_date + WHERE db_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW() + "); + + $dailySalesOverviewLabel = array(); + $dailySalesOverviewData = array(); + + if( $dailySalesData !== false ) { + + foreach($dailySalesData["data"] as $sales ) { + array_push($dailySalesOverviewLabel, $sales["label"] ); + array_push($dailySalesOverviewData, $sales["sales_quantity"] ); + } + + } + + + $dailySalesData = array( + "labels" => $dailySalesOverviewLabel, + "datasets" => array( + array( + "label" => __("Daily Sales"), + "borderColor" => "green", + "borderWidth" => 2, + "data" => $dailySalesOverviewData + ) + ) + ); + + echo json_encode($dailySalesData); + + } + + +} + ?> \ No newline at end of file diff --git a/core/ajax/ajax_pos.php b/core/ajax/ajax_pos.php index 7ada381..08cd6d0 100644 --- a/core/ajax/ajax_pos.php +++ b/core/ajax/ajax_pos.php @@ -235,9 +235,9 @@ ( '{$stock_type}', '". safe_input($salesDate) ."', - '{$sales_id}', + '". safe_input($sales_id) ."', '". safe_input($warehouseId) ."', - '". $getData["userShopId"] ."', + '". safe_input($getData["userShopId"]) ."', '". safe_input($productId) ."', '{$batchProduct["batch_id"]}', '". safe_input($getData["productSalePirce"][$key]) ."', @@ -286,9 +286,9 @@ ( '{$stock_type}', '". safe_input($salesDate) ."', - '{$sales_id}', + '". safe_input($sales_id) ."', '". safe_input($warehouseId) ."', - '". $getData["userShopId"] ."', + '". safe_input($getData["userShopId"]) ."', '". safe_input($productId) ."', ". ( empty($getData["productBatch"][$key]) ? "NULL" : "'". safe_input($getData["productBatch"][$key]) . "'" ) .", '". safe_input($getData["productSalePirce"][$key]) ."', @@ -375,9 +375,9 @@ ( '{$stock_type}', '". safe_input($salesDate) ."', - '{$sales_id}', + '". safe_input($sales_id) ."', '". safe_input($warehouseId) ."', - '". $getData["userShopId"] ."', + '". safe_input($getData["userShopId"]) ."', '". $bp["bg_item_product_id"] ."', NULL, '". $bpItemSalePrice ."', diff --git a/core/ajax/ajax_pos_back.php b/core/ajax/ajax_pos_back.php new file mode 100644 index 0000000..c8f12d8 --- /dev/null +++ b/core/ajax/ajax_pos_back.php @@ -0,0 +1,638 @@ + $sales_status, //"Delivered", + "sales_delivery_date" => $salesDate, + "sales_customer_id" => $customerId, + "sales_shop_id" => $_SESSION["sid"], + "sales_quantity" => $salesQuantity, + "sales_shipping" => $salesShippingCharge, + "sales_update_by" => $_SESSION["uid"], + "sales_total_item" => $salesTotalItems, + "sales_total_packets" => $getData["totalPackets"], + "sales_tariff_charges_details" => serialize( array("tariff" => $getData["tariffChargesName"], "value" => $getData["tariffChargesAmount"]) ), + "sales_by_pos" => 1, + "sales_note" => $salesNote, + "is_wastage" => ( isset($getData["saleOptions"]) and $getData["saleOptions"] === "wastage" ) ? 1 : 0 + //"is_return" => ( isset($getData["saleOptions"]) and $getData["saleOptions"] === "return" ) ? 1 : 0, + ), + array ( + "sales_id" => $sales_id + ) + ); + + // Delete the previous sales items while updating + easyPermDelete( + "product_stock", + array( + "stock_sales_id" => $sales_id + ) + ); + + + +} else { // If there is no sales id defined then insert new one + + $selectSalesReference = easySelect( + "sales", + "sales_reference", + array(), + array ( + "sales_by_pos" => 1, + " AND sales_reference LIKE 'SALE/POS/{$_SESSION['sid']}{$_SESSION['uid']}/%'", + " AND sales_reference is not null" + ), + array ( + "sales_id" => "DESC" + ), + array ( + "start" => 0, + "length" => 1 + ) + ); + + // Referense Format: SALE/POS/n + $salesReferences = "SALE/POS/".$_SESSION['sid'].$_SESSION['uid']."/"; + + // check if there is minimum one records + if($selectSalesReference) { + $getLastReferenceNo = explode($salesReferences, $selectSalesReference["data"][0]["sales_reference"])[1]; + $salesReferences = $salesReferences . ((int)$getLastReferenceNo+1); + } else { + $salesReferences = "SALE/POS/".$_SESSION['sid'].$_SESSION['uid']."/1"; + } + + // Insert Sales into db + $insertSales = easyInsert( + "sales", + array ( + "sales_status" => $sales_status, //$_POST["posAction"] === "sale_is_hold" ? "Hold" : "Delivered", + "sales_order_date" => ( isset($_POST["orderDate"]) and !empty($_POST["orderDate"]) ) ? $_POST["orderDate"] : null, + "sales_delivery_date" => $salesDate, + "sales_reference" => $salesReferences, + "sales_customer_id" => $customerId, + "sales_warehouse_id" => $warehouseId, + "sales_shop_id" => $_SESSION["sid"], + "sales_quantity" => $salesQuantity, + "sales_shipping" => $salesShippingCharge, + "sales_created_by" => $_SESSION["uid"], + "sales_total_item" => $salesTotalItems, + "sales_total_packets" => $getData["totalPackets"], + "sales_tariff_charges_details" => serialize( array("tariff" => $getData["tariffChargesName"], "value" => $getData["tariffChargesAmount"]) ), + "sales_by_pos" => 1, + "sales_note" => $salesNote, + "is_wastage" => ( isset($getData["saleOptions"]) and $getData["saleOptions"] === "wastage" ) ? 1 : 0, + //"is_return" => ( isset($getData["saleOptions"]) and $getData["saleOptions"] === "return" ) ? 1 : 0 + "is_exchange" => min($getData["productQnt"]) < 0 ? 1 : 0 // if there negative quantity then mark as exchange + ), + array(), + true + ); + + // if sale not insert then throw an error + if( !isset($insertSales["last_insert_id"]) ) { + + $returnError = array ( + "saleStatus" => "error", + "msg" => __("An unknown error occured. Please contact with the administrator.") + ); + + echo json_encode($returnError); + return; + } + + $sales_id = "LAST_INSERT_ID()"; //$insertSales["last_insert_id"]; + +} + + +// Need to generator after insert sales items +$salesTotalAmount = 0; +$salesTotalProductDiscount = 0; +$salesTotalOrderDiscount = 0; +$salesGrandTotal = 0; +$salesChanges = 0; + + +$insertSaleItems = "INSERT INTO {$table_prefeix}product_stock( + stock_type, + stock_entry_date, + stock_sales_id, + stock_warehouse_id, + stock_shop_id, + stock_product_id, + stock_batch_id, + stock_item_price, + stock_item_qty, + stock_item_discount, + stock_item_subtotal, + stock_item_description, + stock_created_by, + is_bundle_item +) VALUES "; + + +// 'Order Placed', 'In Production', 'Processing', 'Hold', 'Delivered', 'Cancelled' +/** + * 'initial', 'sale-production', 'sale-processing', 'sale', 'sale-order', 'wastage-sale', 'sale-return', 'purchase', 'purchase-order', + * 'purchase-return', 'transfer-in', 'transfer-out', 'specimen-copy', 'specimen-copy-return', 'undeclared' + */ + +// Declare stock type +$stock_type = "undeclared"; +if( isset($_POST["saleOptions"]) and $_POST["saleOptions"] === "wastage" ) { + $stock_type = "wastage-sale"; +} else if( $_POST["posAction"] === "sale_is_hold") { // if sale is hold then stock type will undeclared + $stock_type = "undeclared"; +} elseif($sales_status === "Delivered") { + $stock_type = "sale"; +} elseif($sales_status === "Order Placed") { + $stock_type = "sale-order"; +} elseif($sales_status === "In Production") { + $stock_type = "sale-production"; +} elseif($sales_status === "Processing") { + $stock_type = "sale-processing"; +} + +// Insert product items into sale table +foreach($getData["productID"] as $key => $productId) { + + /** + * For expiry products add batches + * + * If the batch is not set then set it programatically + */ + if( $getData["productHasExpiryDate"][$key] and empty($getData["productBatch"][$key]) ) { + + $select_batch_product = easySelectA(array( + "table" => "product_batches as product_batches", + "fields" => "product_batches.product_id as pid, batch_number, product_batches.batch_id as batch_id, batch_expiry_date, if(stock_in is null, 0, round(stock_in, 2) ) as stock_in", + "join" => array( + "left join ( select + vp_id, + warehouse, + batch_id, + sum(base_stock_in/base_qty) as stock_in + FROM product_base_stock + where warehouse = '{$warehouseId}' + group by batch_id + ) as product_base_stock on product_base_stock.vp_id = product_batches.product_id and product_base_stock.batch_id = product_batches.batch_id" + ), + "where" => array( + "product_batches.is_trash = 0 and stock_in > 0 and date(batch_expiry_date) > curdate() and product_batches.product_id" => $productId + ), + "orderby" => array( + "batch_expiry_date" => "ASC" // which batch expire first + ) + )); + + + $totalBatchProductQnt = $getData["productQnt"][$key]; + + foreach($select_batch_product["data"] as $index=> $batchProduct) { + + /** Calculate the current batch quantity */ + $currentBatchQnt = $totalBatchProductQnt > $batchProduct["stock_in"] ? $batchProduct["stock_in"] : $totalBatchProductQnt; + + // Calculate the total amount + $salesTotalAmount += $getData["productSalePirce"][$key] * $currentBatchQnt; + + // Calculate the product/items Discount + $itemDiscountAmount = calculateDiscount($getData["productSalePirce"][$key], $getData["productDiscount"][$key]); + + // Calculate the total product/items Discount + $salesTotalProductDiscount += $itemDiscountAmount * $currentBatchQnt; + + // Calculate item amount after discount + $itemAmoutnAfterDiscount = $getData["productSalePirce"][$key] - $itemDiscountAmount; + + $salesItemSubTotal = $currentBatchQnt * $itemAmoutnAfterDiscount; + + $insertSaleItems .= " + ( + '{$stock_type}', + '". safe_input($salesDate) ."', + '{$sales_id}', + '". safe_input($warehouseId) ."', + '". $_SESSION["sid"] ."', + '". safe_input($productId) ."', + '{$batchProduct["batch_id"]}', + '". safe_input($getData["productSalePirce"][$key]) ."', + '{$currentBatchQnt}', + '". $itemDiscountAmount ."', + '". $salesItemSubTotal ."', + '". safe_input($getData["productItemDetails"][$key]) ."', + '". $_SESSION["uid"] ."', + '". 0 ."' + ),"; + + + /** + * If totalBatchProductQnt is less then or equal to of current batch stock in + * the break the loop + */ + if($totalBatchProductQnt <= $batchProduct["stock_in"]) { + break; + } + + /** + * If totalBatchProductQnt is not less then or equal to of current batch stock in + * the minus the batch stock value from totalBatchProductQnt and continue the loop + */ + $totalBatchProductQnt -= $batchProduct["stock_in"]; + + } + + } else { + + // Calculate the total amount + $salesTotalAmount += $getData["productSalePirce"][$key] * $getData["productQnt"][$key]; + + // Calculate the product/items Discount + $itemDiscountAmount = calculateDiscount($getData["productSalePirce"][$key], $getData["productDiscount"][$key]); + + // Calculate the total product/items Discount + $salesTotalProductDiscount += $itemDiscountAmount * $getData["productQnt"][$key]; + + // Calculate item amount after discount + $itemAmoutnAfterDiscount = $getData["productSalePirce"][$key] - $itemDiscountAmount; + + $salesItemSubTotal = $getData["productQnt"][$key] * $itemAmoutnAfterDiscount; + + $insertSaleItems .= " + ( + '{$stock_type}', + '". safe_input($salesDate) ."', + '{$sales_id}', + '". safe_input($warehouseId) ."', + '". $_SESSION["sid"] ."', + '". safe_input($productId) ."', + ". ( empty($getData["productBatch"][$key]) ? "NULL" : "'". safe_input($getData["productBatch"][$key]) . "'" ) .", + '". safe_input($getData["productSalePirce"][$key]) ."', + '". safe_input($getData["productQnt"][$key]) ."', + '". $itemDiscountAmount ."', + '". $salesItemSubTotal ."', + '". safe_input($getData["productItemDetails"][$key]) ."', + '". $_SESSION["uid"] ."', + '". 0 ."' + ),"; + + } + + // Select products, which have sub products and insert sub/bundle products + $subProducts = easySelectA(array( + "table" => "products as product", + "fields" => "bg_item_product_id, + bg_product_price as sale_price, + bg_product_qnt + ", + "join" => array( + "inner join {$table_prefeix}bg_product_items on bg_product_id = product_id" + ), + "where" => array( + "product.has_sub_product = 1 and product.product_id = {$productId}" + ) + )); + + + // Insert sub/ bundle products + if($subProducts !== false) { + + // check if the bundle product sale price is changed by user + $increasedRate = "0%"; + $decreasedRate = "0%"; + if( $getData["productSalePirce"][$key] > $getData["productMainSalePirce"][$key] ) { // If the price is Increased + + // Calculate the increased amount + $increasedAmount = $getData["productSalePirce"][$key] - $getData["productMainSalePirce"][$key]; + + // Calculate the increased purcentage + $increasedRate = ( $increasedAmount * 100 ) / $getData["productMainSalePirce"][$key] ; + + } else if( $getData["productSalePirce"][$key] < $getData["productMainSalePirce"][$key] ) { // If the price is decrased + + // Calculate the decreased amount + $decreasedAmount = $getData["productMainSalePirce"][$key] - $getData["productSalePirce"][$key]; + + // Calculate the decreased purcentage + $decreasedRate = ( $decreasedAmount * 100 ) / $getData["productMainSalePirce"][$key] ; + + } + + + foreach($subProducts["data"] as $bpKey => $bp) { + + // Store the Bundle/ Sub Product Item Sale Price + $bpItemSalePrice = $bp["sale_price"]; + + // Check if increased is not 0% + if( $increasedRate != "0%" ) { + + // Increase the price if it was increased in Bundle price by user + $bpItemSalePrice += calculateDiscount($bpItemSalePrice, $increasedRate . "%"); + + } else if( $decreasedRate != "0%" ) { + + // Decreased the price if it was increased in Bundle price by user + $bpItemSalePrice -= calculateDiscount($bpItemSalePrice, $decreasedRate . "%"); + + } + + + // Calculate the Bundle/Sub item quantity + $bpItemQnt = $getData["productQnt"][$key] * $bp["bg_product_qnt"]; + + // In bundle/Sub item, the discount takes from bundle product not from the item product + $bpItemDiscountAmount = calculateDiscount( $bpItemSalePrice, $getData["productDiscount"][$key] ); + + $bpItemSubTotal = ( $bpItemSalePrice - $bpItemDiscountAmount) * $bpItemQnt; + + + $insertSaleItems .= " + ( + '{$stock_type}', + '". safe_input($salesDate) ."', + '{$sales_id}', + '". safe_input($warehouseId) ."', + '". $_SESSION["sid"] ."', + '". $bp["bg_item_product_id"] ."', + NULL, + '". $bpItemSalePrice ."', + '". $bpItemQnt ."', + '". $bpItemDiscountAmount ."', + '". $bpItemSubTotal ."', + '', + '". $_SESSION["uid"] ."', + '". 1 ."' + ),"; + + } + } + +} + + + +// Calculate total Payments +$salesPaidAmount = array_sum($_POST["posSalePaymentAmount"]); + +// delete previous payment in purpose of editing sale +easyDelete( + "received_payments", + array( + "received_payments_sales_id" => $sales_id, + ) +); + + + +//echo "Sales Total amount: $salesTotalAmount \n"; +//echo "Total Product Discount $salesTotalProductDiscount \n"; + +// Calculate subtotal by minusing product discount +$subtotal = $salesTotalAmount - $salesTotalProductDiscount; +//echo "Subtotal: $subtotal \n"; + +// Calculate order discount from subtotal +$salesOrderDiscount = calculateDiscount($subtotal, $getData["orderDiscountValue"]); +//echo "Order Discount: $salesOrderDiscount \n"; + +// Calculate total amount after discount +$salesAmountAfterDiscount = $subtotal - $salesOrderDiscount; +//echo "Amount After Discount: $salesAmountAfterDiscount \n"; + +// Calculate Sales Tariff +$tariffCharges = array_sum($getData["tariffChargesAmount"]); +//echo "Tariff: $tariffCharges \n"; + +// Calculate Net total (Amount after discount + Tax) +$netTotal = $salesAmountAfterDiscount + $tariffCharges; +//echo "Net total: $netTotal \n"; + +$adjustAmount = empty($getData["adjustAmount"]) ? 0 : $getData["adjustAmount"]; + +// Calculate Grand total by Adding shiping charge with net total +$salesGrandTotal = $netTotal + $salesShippingCharge + $adjustAmount; +//echo "Grand Total: $salesGrandTotal \n"; + +//Round Sales grand total with max decimal place in calculation +$salesGrandTotal = round($salesGrandTotal, get_options("decimalPlaces") ); + + +// Calculate Change amount +$salesChanges = ($salesGrandTotal < $salesPaidAmount) ? ($salesPaidAmount - $salesGrandTotal) : 0; +//echo "Change: $salesChanges \n"; + +// Calculate Due amount +$salesDue = ($salesGrandTotal > $salesPaidAmount) ? ($salesGrandTotal - $salesPaidAmount) : 0; +//echo "Due: $salesDue \n"; + + +// Insert each payments +foreach( $_POST["posSalePaymentAmount"] as $paymentKey => $paymentAmount ) { + + // Insert Sales Payment into received payments table + if($paymentAmount > 0) { + + easyInsert( + "received_payments", + array ( + "received_payments_type" => "Sales Payments", + "received_payments_datetime" => $salesDate . date(" H:i:s"), + "received_payments_shop" => $_SESSION["sid"], + "received_payments_accounts" => empty($_POST["posSalePaymentBankAccount"][$paymentKey]) ? $_SESSION["aid"] : $_POST["posSalePaymentBankAccount"][$paymentKey], + "received_payments_sales_id" => $sales_id, + "received_payments_from" => $customerId, + "received_payments_amount" => $paymentAmount, //$salesGrandTotal - $salesDue + /** + * This not is deprected. Will be remove in near update. + * ***************************************************** + * Here we substract salesDue from salesGrandTotal, and do not use salesPaidAmount directly + * Becase salesPaidAmount can be grater then salesGrandTotal and there can have a change amount. + * Suppose, Total bill is 490, customer paid 500. Here we can not insert piad amount 500. We have insert + * 490 as paid amount and the rest will be changed. + */ + "received_payments_method" => $_POST["posSalePaymentMethod"][$paymentKey], + "received_payments_reference" => $_POST["posSalePaymentReference"][$paymentKey], + "received_payments_details" => '', + "received_payments_add_by" => $_SESSION["uid"] + ) + ); + + } else if( $paymentAmount < 0 ) { + + // If there have return amount to customer then add into payments_return table as ourgoing + easyInsert( + "payments_return", + array( + "payments_return_type" => "Outgoing", + "payments_return_date" => $salesDate . date(" H:i:s"), + "payments_return_accounts" => empty($_POST["posSalePaymentBankAccount"][$paymentKey]) ? $_SESSION["aid"] : $_POST["posSalePaymentBankAccount"][$paymentKey], + "payments_return_customer_id" => $customerId, + "payment_return_method" => $_POST["posSalePaymentMethod"][$paymentKey], + "payments_return_amount" => abs($paymentAmount), + "payments_return_description" => "Return payment made on product return", + "payments_return_by" => $_SESSION["uid"] + ) + ); + + } + + // Update Accounts Balance + if( empty($_POST["posSalePaymentBankAccount"][$paymentKey]) ) { + + updateAccountBalance($_SESSION["aid"]); + + } else { + + updateAccountBalance($_POST["posSalePaymentBankAccount"][$paymentKey]); + + } + +} + + +// Generate the payment status +$salesPaymentStatus = "due"; +if($salesGrandTotal <= $salesPaidAmount) { + + $salesPaymentStatus = "paid"; + +} else if($salesGrandTotal > $salesPaidAmount and $salesPaidAmount > 0) { + + $salesPaymentStatus = "partial"; + +} + +// Update the Sale +$updateSale = easyUpdate( + "sales", + array ( + "sales_total_amount" => $salesTotalAmount, + "sales_product_discount" => $salesTotalProductDiscount, + "sales_discount" => $salesOrderDiscount, + "sales_tariff_charges" => $tariffCharges, + "sales_shipping" => empty($getData["shippingCharge"]) ? 0 : $getData["shippingCharge"], + "sales_adjustment" => $adjustAmount, + "sales_grand_total" => $salesGrandTotal, + "sales_paid_amount" => $salesPaidAmount, + "sales_change" => $salesChanges, + "sales_due" => $salesDue, + "sales_payment_status" => $salesPaymentStatus + ), + array ( + "sales_id" => $sales_id + ) +); + + + +//var_dump($salesChanges > 0 and $salesGrandTotal - $salesDue < 0); + + +/** + * **************************************************************************************************** + * This ultimately not required. Now commenting, will be deleted later + * **************************************************************************************************** + * + * If there have ammount to return and the customer want to keep it as balance + * Then, add the amount as received payment. + * + * In this situation the salesChange treated as return + * and there will be no account selected, because the money/balance is adding from poruduct return + * + */ + + /* +if( $salesChanges > 0 and $salesGrandTotal - $salesDue < 0 ) { + easyInsert( + "received_payments", + array ( + "received_payments_type" => "Received Payments", + "received_payments_datetime" => $salesDate . date(" H:i:s"), + "received_payments_shop" => $_SESSION["sid"], + "received_payments_accounts" => NULL, // in this situation the there will be no accounts. Because the balance is adding from product return + "received_payments_sales_id" => $sales_id, + "received_payments_from" => $customerId, + "received_payments_amount" => abs($salesChanges), + "received_payments_method" => $salesPayingBy, + "received_payments_details" => "Added as balance from return", + "received_payments_add_by" => $_SESSION["uid"] + ) + ); +} +*/ + + + +// Return the Success msg +if($updateSale === true) { + + echo substr_replace($insertSaleItems, ";", -1, 1); + + // Insert sale items + runQuery(substr_replace($insertSaleItems, ";", -1, 1)); + + + if( !empty($conn->get_all_error) ) { + + echo json_encode(array ( + "saleStatus" => "error", + "msg" => __($conn->get_all_error[0]. ". Please check the error log for more information.") + )); + + // If there have any error then rollback/undo the data + runQuery("ROLLBACK;"); + + } else { + + // If there have not any error then commit/save the data permanently + runQuery("COMMIT;"); + + // Return success Msg with sales id + echo json_encode( array ( + "saleStatus" => "success", + "salesId" => $sales_id + )); + + } + +} + + +?> \ No newline at end of file diff --git a/core/ajax/ajax_sms.php b/core/ajax/ajax_sms.php index e6d2b34..842ca0d 100644 --- a/core/ajax/ajax_sms.php +++ b/core/ajax/ajax_sms.php @@ -4,7 +4,7 @@ if(isset($_GET['page']) and $_GET['page'] == "sendSMS") { // Include the modal header - modal_header("Send SMS to " . $_GET["name"], full_website_address() . "/info/?module=sms&page=sendSMSCommand"); + modal_header("Send SMS to " . safe_entities($_GET["name"]) , full_website_address() . "/info/?module=sms&page=sendSMSCommand"); ?> @@ -29,7 +29,7 @@ - + @@ -91,8 +91,8 @@ if(isset($_GET['page']) and $_GET['page'] == "sendSMSCommand") { if(send_sms( - str_replace(";", ",", $_POST["numbers"]), - $_POST["message"] + str_replace(";", ",", safe_entities($_POST["numbers"]) ), + safe_entities($_POST["message"]) )) { echo "
SMS Sent Successfully.
"; diff --git a/core/functions.php b/core/functions.php index c0bf2ed..bff1914 100644 --- a/core/functions.php +++ b/core/functions.php @@ -12,7 +12,7 @@ function safe_input($data, $encoding = true) { $data = trim($data); if($encoding === true) { $data = stripslashes($data); - $data = htmlspecialchars($data); + $data = htmlspecialchars($data, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401); } $data = mysqli_real_escape_string($GLOBALS['conn'], $data); return $data; diff --git a/module/accounts/ajax.php b/module/accounts/ajax.php index 055d760..d97cdc6 100644 --- a/module/accounts/ajax.php +++ b/module/accounts/ajax.php @@ -1389,8 +1389,8 @@ ) as payment_return on payments_return_customer_id = customer_id where customer.is_trash = 0 and customer_name like '{$search}%' - group by customer_id order by customer_name {$requestData['order'][0]['dir']} - LIMIT {$requestData['start']}, {$requestData['length']} + group by customer_id order by customer_name ". safe_input($requestData['order'][0]['dir']) ." + LIMIT ". safe_input($requestData['start']) .", ". safe_input($requestData['length']) ." " ); @@ -1500,8 +1500,8 @@ ) as payment_adjustment on pa_company = company_id where company.is_trash = 0 and company_name like '{$search}%' - group by company_id order by company_name {$requestData['order'][0]['dir']} - LIMIT {$requestData['start']}, {$requestData['length']} + group by company_id order by company_name ". safe_input($requestData['order'][0]['dir']) ." + LIMIT ". safe_input($requestData['start']) .", ". safe_input($requestData['length']) ." " ); diff --git a/module/expenses/ajax.php b/module/expenses/ajax.php index 623f344..cb088b7 100644 --- a/module/expenses/ajax.php +++ b/module/expenses/ajax.php @@ -509,7 +509,7 @@ $paymentAttachment = NULL; if($_FILES["paymentAttachment"]["size"] > 0) { - $paymentAttachment = easyUpload($_FILES["paymentAttachment"], "attachments/payments/cheque/" . date("M, Y"), $_POST["paymentChequeNo"] ); + $paymentAttachment = easyUpload($_FILES["paymentAttachment"], "attachments/payments/cheque/" . date("M, Y"), safe_entities($_POST["paymentChequeNo"]) ); if(!isset($paymentAttachment["success"])) { return _e($paymentAttachment); @@ -776,7 +776,7 @@ $paymentAttachment = NULL; if($_FILES["paymentAttachment"]["size"] > 0) { - $paymentAttachment = easyUpload($_FILES["paymentAttachment"], "attachments/payments/cheque/" . date("M, Y"), $_POST["paymentChequeNo"] ); + $paymentAttachment = easyUpload($_FILES["paymentAttachment"], "attachments/payments/cheque/" . date("M, Y"), safe_entities($_POST["paymentChequeNo"]) ); if(!isset($paymentAttachment["success"])) { return _e($paymentAttachment); @@ -1603,7 +1603,7 @@ function (data, status) { ); if($insertSalary === true and $updatePayableSalary === true) { - _s("%s successfully added", $_POST['salaryTypes']); + _s("%s successfully added", safe_entities($_POST['salaryTypes']) ); } else { _e($insertSalary . $updatePayableSalary); } @@ -1927,7 +1927,7 @@ function (data, status) { ); if($UpdateSalary === true and $updatePayableSalary === true) { - _s("%s successfully updated", $_POST['salaryType']); + _s("%s successfully updated", safe_entities($_POST['salaryType']) ); } else { _e($insertSalary . $updatePayableSalary); } @@ -2725,7 +2725,7 @@ function(data, status) { $paymentAttachment = NULL; if($_FILES["dueBillPaymentAttachment"]["size"] > 0) { - $paymentAttachment = easyUpload($_FILES["dueBillPaymentAttachment"], "attachments/payments/cheque/" . date("M, Y"), $_POST["dueBillPaymentChequeNo"] ); + $paymentAttachment = easyUpload($_FILES["dueBillPaymentAttachment"], "attachments/payments/cheque/" . date("M, Y"), safe_entities($_POST["dueBillPaymentChequeNo"]) ); if(!isset($paymentAttachment["success"])) { return _e($paymentAttachment); @@ -3312,7 +3312,7 @@ function(data, status) { - "> + ">
@@ -3653,7 +3653,7 @@ function(data, status) { left join ( select advance_payment_pay_to, sum(advance_payment_amount) as advance_payment_amount_sum from {$table_prefeix}advance_payments group by advance_payment_pay_to ) as get_advance_payments on advance_payment_pay_to = emp_id left join ( select payment_to_employee, sum(payment_amount) as payment_amount_sum from {$table_prefeix}payments where payment_type = 'Advance Adjustment' group by payment_to_employee ) as get_payments on payment_to_employee = emp_id left join ( select payments_return_emp_id, sum(payments_return_amount) as payments_return_amount_sum from {$table_prefeix}payments_return group by payments_return_emp_id ) as get_advance_return on payments_return_emp_id = emp_id - where emp_id = {$_POST['advancePaymentAdjustEmployee']}" + where emp_id = " . safe_input($_POST['advancePaymentAdjustEmployee']) )["data"][0]; $totalPaymentAmount = array_sum($_POST["paymentAmount"]); @@ -4428,7 +4428,7 @@ function(data, status) { - "> + ">
diff --git a/module/home.php b/module/home.php index 8d84324..02261f3 100644 --- a/module/home.php +++ b/module/home.php @@ -80,10 +80,16 @@

+ + +
- +
@@ -223,37 +229,9 @@ = DATE_SUB(NOW(), INTERVAL 30 DAY) group by sales_delivery_date - "); - - $dateStart = date('Y-m-d', strtotime('today - 30 days')); - - $i = 0; - $newdate = array(); - $newvalue = array(); - - while($dateStart <= date("Y-m-d")) { - - $dateStart = date("Y-m-d", strtotime("$dateStart + 1 day")); - - if(isset($salesData["data"][$i]) && $salesData["data"][$i]["sales_delivery_date"] == $dateStart){ - - array_push($newdate, $salesData["data"][$i]["sales_delivery_date"]); - array_push($newvalue, $salesData["data"][$i]["sales_quantity"]); - $i++; + - }else{ - - array_push($newdate, $dateStart); - array_push($newvalue, 0); - - } - - } - - $salesDate = __(json_encode($newdate)); - $salesAmount = json_encode($newvalue); + ?> @@ -261,20 +239,12 @@ diff --git a/module/incomes/ajax.php b/module/incomes/ajax.php index be4d549..a10978b 100644 --- a/module/incomes/ajax.php +++ b/module/incomes/ajax.php @@ -445,7 +445,7 @@ " class="form-control">
- "> + ">
@@ -537,7 +537,7 @@ } - $sucessMsg = sprintf(__("Successfully updated. Please Click Here to print the receipt."), " onClick='BMS.MAIN.printPage(this.href, event);' href='". full_website_address() ."/invoice-print/?invoiceType=moneyReceipt&id=". $_POST["advanceCollectionId"] ."'"); + $sucessMsg = sprintf(__("Successfully updated. Please Click Here to print the receipt."), " onClick='BMS.MAIN.printPage(this.href, event);' href='". full_website_address() ."/invoice-print/?invoiceType=moneyReceipt&id=". safe_entities($_POST["advanceCollectionId"]) ."'"); echo "
{$sucessMsg}
"; @@ -1072,7 +1072,7 @@ function(data, status) { - "> + ">
@@ -1163,7 +1163,7 @@ function(data, status) { } - $sucessMsg = sprintf(__("Successfully updated. Please Click Here to print the receipt."), " onClick='BMS.MAIN.printPage(this.href, event);' href='". full_website_address() ."/invoice-print/?invoiceType=moneyReceipt&id=". $_POST["receivedPaymentId"] ."'"); + $sucessMsg = sprintf(__("Successfully updated. Please Click Here to print the receipt."), " onClick='BMS.MAIN.printPage(this.href, event);' href='". full_website_address() ."/invoice-print/?invoiceType=moneyReceipt&id=". safe_entities($_POST["receivedPaymentId"]) ."'"); echo "
{$sucessMsg}
"; diff --git a/module/journals/ajax.php b/module/journals/ajax.php new file mode 100644 index 0000000..6212d08 --- /dev/null +++ b/module/journals/ajax.php @@ -0,0 +1,720 @@ + 0)); + +/************************** Add New Journal **********************/ +if(isset($_GET['page']) and $_GET['page'] == "newJournal") { + + // Include the modal header + modal_header("Create New Journal", full_website_address() . "/xhr/?module=journals&page=addNewJournal"); + + ?> + +
+
+ + " class="form-control datePicker" required> +
+
+ + +
+
+ + +
+
+ +
+ + + $_POST["journalDate"], + "journals_name" => $_POST["journalName"], + "journals_opening_balance" => $_POST["journalOpeningBalance"], + "journals_add_by" => $_SESSION["uid"] + ), + array ( + "journals_date" => $_POST["journalDate"], + " AND journals_name" => $_POST["journalName"], + ) + ); + + if($addJournal === true) { + _s("Journal Successfully Added."); + } else { + _e($addJournal); + } + +} + + +/*************************** Journal List ***********************/ +if(isset($_GET['page']) and $_GET['page'] == "journalList") { + + $requestData = $_REQUEST; + $getData = []; + + // List of all columns name + $columns = array( + "", + "journals_id", + "journals_name" + ); + + // Count Total recrods + $totalFilteredRecords = $totalRecords = easySelectA(array( + "table" => "journals", + "fields" => "count(*) as totalRow", + "where" => array( + "is_trash = 0" + ) + ))["data"][0]["totalRow"]; + + if($requestData['length'] == -1) { + $requestData['length'] = $totalRecords; + } + + if(!empty($requestData["search"]["value"])) { // get data with search + + $getData = easySelect( + "journals", + "journals_id, journals_date, journals_name, journals_opening_balance, if(journal_incoming_payment is null, 0, journal_incoming_payment) as journal_incoming_payment_sum, if(journal_outgoing_payment is null, 0, journal_outgoing_payment) as journal_outgoing_payment_sum", + array ( + "left join ( select journal_records_journal_id, sum(journal_records_payment_amount) as journal_incoming_payment from {$table_prefeix}journal_records where journal_records_payments_type = 'Incoming' group by journal_records_journal_id ) as journal_incoming_records on journal_incoming_records.journal_records_journal_id = journals_id", + "left join ( select journal_records_journal_id, sum(journal_records_payment_amount) as journal_outgoing_payment from {$table_prefeix}journal_records where journal_records_payments_type = 'Outgoing' group by journal_records_journal_id ) as journal_outgoing_records on journal_outgoing_records.journal_records_journal_id = journals_id" + ), + array ( + "journals_name LIKE" => $requestData['search']['value'] . "%" + ), + array ( + $columns[$requestData['order'][0]['column']] => $requestData['order'][0]['dir'] + ), + array ( + "start" => $requestData['start'], + "length" => $requestData['length'] + ) + ); + + $totalFilteredRecords = $getData ? $getData["count"] : 0; + + } else { // Get data withouth search + + $getData = easySelect( + "journals", + "journals_id, journals_date, journals_name, journals_opening_balance, if(journal_incoming_payment is null, 0, journal_incoming_payment) as journal_incoming_payment_sum, if(journal_outgoing_payment is null, 0, journal_outgoing_payment) as journal_outgoing_payment_sum", + array ( + "left join ( select journal_records_journal_id, sum(journal_records_payment_amount) as journal_incoming_payment from {$table_prefeix}journal_records where journal_records_payments_type = 'Incoming' group by journal_records_journal_id ) as journal_incoming_records on journal_incoming_records.journal_records_journal_id = journals_id", + "left join ( select journal_records_journal_id, sum(journal_records_payment_amount) as journal_outgoing_payment from {$table_prefeix}journal_records where journal_records_payments_type = 'Outgoing' group by journal_records_journal_id ) as journal_outgoing_records on journal_outgoing_records.journal_records_journal_id = journals_id" + ), + array(), + array ( + $columns[$requestData['order'][0]['column']] => $requestData['order'][0]['dir'] + ), + array ( + "start" => $requestData['start'], + "length" => $requestData['length'] + ) + ); + + } + + $allData = []; + // Check if there have more then zero data + if(isset($getData['data'])) { + + foreach($getData['data'] as $key => $value) { + $journalStatus = "Unbalanced"; + + if( ( $value["journals_opening_balance"] + $value["journal_incoming_payment_sum"] ) == $value["journal_outgoing_payment_sum"] ) { + $journalStatus = "Balanced"; + } + + $allNestedData = []; + $allNestedData[] = ""; + $allNestedData[] = $value["journals_date"]; + $allNestedData[] = $value["journals_name"]; + $allNestedData[] = to_money($value["journals_opening_balance"]); + $allNestedData[] = to_money( ( $value["journals_opening_balance"] + $value["journal_incoming_payment_sum"] ) - $value["journal_outgoing_payment_sum"] ); + $allNestedData[] = $journalStatus; + $allNestedData[] = ' Edit'; + + $allData[] = $allNestedData; + } + } + + + $jsonData = array ( + "draw" => intval( $requestData['draw'] ), + "recordsTotal" => intval( $totalRecords ), + "recordsFiltered" => intval( $totalFilteredRecords ), + "data" => $allData + ); + + // Encode in Json Formate + echo json_encode($jsonData); +} + + +/************************** Add New Journal **********************/ +if(isset($_GET['page']) and $_GET['page'] == "editJournal") { + + $selectJournal = easySelect( + "journals", + "*", + array(), + array ( + "journals_id" => $_GET["journal_id"] + ) + )["data"][0]; + + // Include the modal header + modal_header("Edit Journal", full_website_address() . "/xhr/?module=journals&page=UpdateJournal"); + + ?> + +
+
+ + +
+
+ + +
+
+ + +
+ "> + +
+ +
+ + + $_POST["journalDate"], + "journals_name" => $_POST["journalName"], + "journals_opening_balance" => $_POST["journalOpeningBalance"] + ), + array ( + "journals_id" => $_POST["journal_id"] + ) + ); + + if($updateJournal === true) { + _s("Journal successfully updated."); + } else { + _e($updateJournal); + } + +} + + +/************************** Add New Journal **********************/ +if(isset($_GET['page']) and $_GET['page'] == "newJournalRecords") { + + // Include the modal header + modal_header("New Journal Record", full_website_address() . "/xhr/?module=journals&page=addNewJournalRecord"); + + ?> + +
+
+ + +
+
+ +
+ + +
+
+
+ + " class="form-control datePicker" required> +
+
+ + +
+
+ + +
+
+ + +
+ +
+ +
+ + + $_SESSION['uid'], + " AND journal_records_reference is not null" + ), + array ( + "journal_records_id" => "DESC" + ), + array ( + "start" => 0, + "length" => 1 + ) + ); + + // Referense Format: SALE/POS/n + $journalRecordReferences = "JR/{$_SESSION['uid']}/"; + + // check if there is minimum one records + if($selectJournalRecordReference !== false) { + $getLastReferenceNo = (int)explode($journalRecordReferences, $selectJournalRecordReference["data"][0]["journal_records_reference"])[1]; + $journalRecordReferences = $journalRecordReferences . ($getLastReferenceNo+1); + } else { + $journalRecordReferences = "JR/{$_SESSION['uid']}/1"; + } + + + $addJournal = easyInsert( + "journal_records", + array ( + "journal_records_datetime" => $_POST["journalRecordsDate"] .' '. date('H:i:s'), + "journal_records_reference" => $journalRecordReferences, + "journal_records_journal_id" => $_POST["journalID"], + "journal_records_accounts" => $_POST["journalRecordPaymentFromAccount"], + "journal_records_payments_type" => $_POST["journalRecrodPaymentType"], + "journal_records_payment_amount" => $_POST["journalRecordsAmount"], + "journal_records_narration" => $_POST["journalRecordsNarration"], + "journal_records_add_by" => $_SESSION["uid"] + ), + array ( + "journal_records_journal_id" => $_POST["journalID"], + " AND journal_records_accounts" => $_POST["journalRecordPaymentFromAccount"], + " AND journal_records_payment_amount" => $_POST["journalRecordsAmount"], + " AND journal_records_narration" => $_POST["journalRecordsNarration"], + " AND journal_records_payments_type" => $_POST["journalRecrodPaymentType"], + " AND date(journal_records_datetime)" => $_POST["journalRecordsDate"], + " AND journal_records_add_by" => $_SESSION["uid"] + ), + true + ); + + if( isset($addJournal["status"]) and $addJournal["status"] === "success" ) { + + // Update Accounts Balance + updateAccountBalance($_POST["journalRecordPaymentFromAccount"]); + + $successMsg = sprintf(__("Journal record successfully added. The refernece is %s. Click Here to print the receipt."), $journalRecordReferences, " onClick='BMS.MAIN.printPage(this.href, event);' href='". full_website_address() ."/invoice-print/?invoiceType=moneyReceiptJournalRecords&autoPrint=true&id=". $addJournal["last_insert_id"] ."'"); + + echo "
{$successMsg}
"; + + } else { + _e($addJournal); + } + +} + + +/*************************** Journal List ***********************/ +if(isset($_GET['page']) and $_GET['page'] == "journalRecordList") { + + $requestData = $_REQUEST; + $getData = []; + + // List of all columns name + $columns = array( + "", + "journal_records_datetime", + "journal_records_reference", + "journals_name", + "accounts_name", + "category_name", + "journal_records_payments_type", + "journal_records_payment_amount", + "journal_records_narration" + ); + + // Count Total recrods + $totalFilteredRecords = $totalRecords = easySelectA(array( + "table" => "journal_records", + "fields" => "count(*) as totalRow", + "where" => array( + "is_trash = 0" + ) + ))["data"][0]["totalRow"]; + + if($requestData['length'] == -1) { + $requestData['length'] = $totalRecords; + } + + if(!empty($requestData["search"]["value"])) { // get data with search + + $getData = easySelect( + "journal_records as journal_records", + "journal_records_id, journal_records_datetime, journal_records_reference, journal_records_journal_id, journals_name, journal_records_accounts, accounts_name, journal_records_payments_type, journal_records_payment_amount, journal_records_narration", + array ( + "left join {$table_prefeix}journals on journals_id = journal_records_journal_id", + "left join {$table_prefeix}accounts on accounts_id = journal_records_accounts" + ), + array ( + "journal_records.is_trash = 0", + " and journals_name LIKE" => $requestData['search']['value'] . "%", + " OR journal_records_reference LIKE" => $requestData['search']['value'] . "%", + " OR journal_records_narration LIKE" => $requestData['search']['value'] . "%" + ), + array ( + $columns[$requestData['order'][0]['column']] => $requestData['order'][0]['dir'] + ), + array ( + "start" => $requestData['start'], + "length" => $requestData['length'] + ) + ); + + $totalFilteredRecords = $getData ? $getData["count"] : 0; + + } else { // Get data withouth search + + $getData = easySelect( + "journal_records as journal_records ", + "journal_records_id, journal_records_datetime, journal_records_reference, journal_records_journal_id, journals_name, journal_records_accounts, accounts_name, journal_records_payments_type, journal_records_payment_amount, journal_records_narration", + array ( + "left join {$table_prefeix}journals on journals_id = journal_records_journal_id", + "left join {$table_prefeix}accounts on accounts_id = journal_records_accounts" + ), + array("journal_records.is_trash = 0"), + array ( + $columns[$requestData['order'][0]['column']] => $requestData['order'][0]['dir'] + ), + array ( + "start" => $requestData['start'], + "length" => $requestData['length'] + ) + ); + + } + + $allData = []; + // Check if there have more then zero data + if(isset($getData['data'])) { + + foreach($getData['data'] as $key => $value) { + $allNestedData = []; + $allNestedData[] = ""; + $allNestedData[] = $value["journal_records_datetime"]; + $allNestedData[] = $value["journal_records_reference"]; + $allNestedData[] = $value["journals_name"]; + $allNestedData[] = $value["accounts_name"]; + $allNestedData[] = $value["journal_records_payments_type"]; + $allNestedData[] = $value["journal_records_payment_amount"]; + $allNestedData[] = $value["journal_records_narration"]; + $allNestedData[] = '
+ + +
'; + + $allData[] = $allNestedData; + } + } + + + $jsonData = array ( + "draw" => intval( $requestData['draw'] ), + "recordsTotal" => intval( $totalRecords ), + "recordsFiltered" => intval( $totalFilteredRecords ), + "data" => $allData + ); + + // Encode in Json Formate + echo json_encode($jsonData); +} + + +/************************** Add New Journal **********************/ +if(isset($_GET['page']) and $_GET['page'] == "editJournalRecord") { + + // Include the modal header + modal_header("Edit Journal Record", full_website_address() . "/xhr/?module=journals&page=updateJournalRecord"); + + $journalRecord = easySelect( + "journal_records as journal_records", + "*", + array( + "left join {$table_prefeix}journals on journal_records_journal_id = journals_id " + ), + array( + "journal_records_id" => $_GET['id'], + " and journal_records.is_trash" => 0 + ) + )["data"][0]; + + ?> + +
+
+ + +
+
+ +
+ + +
+
+
+ + " class="form-control datePicker" required> +
+
+ + +
+
+ + " required> +
+
+ + +
+ "> + +
+ +
+ + + $_POST['journal_record_id'], + " and journal_records.is_trash" => 0 + ) + )["data"][0]["journal_records_payment_amount"]; + + $accounts_balance += accounts_balance($_POST["journalRecordPaymentFromAccount"]); + + if(empty($_POST["journalID"])) { + return _e("Please select journal."); + } else if(empty($_POST["journalRecrodPaymentType"])) { + return _e("Please select payment type."); + } else if(empty($_POST["journalRecordsDate"])) { + return _e("Please select date."); + } else if(empty($_POST["journalRecordPaymentFromAccount"])) { + return _e("Please select account."); + } else if(empty($_POST["journalRecordsAmount"])) { + return _e("Please enter amount."); + } else if(!negative_value_is_allowed($_POST["journalRecordPaymentFromAccount"]) and $_POST["journalRecrodPaymentType"] === "Outgoing" and $accounts_balance < $_POST["journalRecordsAmount"] ) { + return _e("Transfer amount is exceeded of account balance (%.2f)", number_format($accounts_balance, 2)); + } + + $updateJournalRecord = easyUpdate( + "journal_records", + array ( + "journal_records_datetime" => $_POST["journalRecordsDate"] .' '. date('H:m:s'), + "journal_records_journal_id" => $_POST["journalID"], + "journal_records_accounts" => $_POST["journalRecordPaymentFromAccount"], + "journal_records_payments_type" => $_POST["journalRecrodPaymentType"], + "journal_records_payment_amount" => $_POST["journalRecordsAmount"], + "journal_records_narration" => $_POST["journalRecordsNarration"] + ), + array ( + "journal_records_id" => $_POST["journal_record_id"] + ) + ); + + if($updateJournalRecord === true) { + // Update Accounts Balance + updateAccountBalance($_POST["journalRecordPaymentFromAccount"]); + + echo _s("Journal record successfully updated."); + + } else { + _e($updateJournalRecord); + } + +} + + +/***************** Delete Journal Records ****************/ +if(isset($_GET['page']) and $_GET['page'] == "deleteJournalRecords") { + + // Select accounts id of delected journal records + $selectAccountId = easySelect( + "journal_records", + "journal_records_accounts", + array(), + array ( + "journal_records_id" => $_POST["datatoDelete"] + ) + )["data"][0]["journal_records_accounts"]; + + // Delect the journal records + $deleteData = easyDelete( + "journal_records", + array( + "journal_records_id" => $_POST["datatoDelete"] + ) + ); + + if($deleteData === true) { + // Update accounts Balance + updateAccountBalance($selectAccountId); + echo 1; + } +} + + +?> \ No newline at end of file diff --git a/module/journals/journal-list.php b/module/journals/journal-list.php new file mode 100644 index 0000000..da58148 --- /dev/null +++ b/module/journals/journal-list.php @@ -0,0 +1,68 @@ + +
+ +
+

+ + ' . __('New Journal') . ''; + } ?> +

+
+ + +
+
+
+
+ + +
+

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ +
+ +
+ + +
+ +
+ + diff --git a/module/journals/journal-records.php b/module/journals/journal-records.php new file mode 100644 index 0000000..5c535ce --- /dev/null +++ b/module/journals/journal-records.php @@ -0,0 +1,72 @@ + +
+ +
+

+ + ' . __("New Entry") . ''; + } ?> +

+
+ + +
+
+
+
+ + +
+

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +
+ +
+ +
+ + +
+ +
+ + diff --git a/module/my-shop/ajax.php b/module/my-shop/ajax.php index 9f8c77d..452735e 100644 --- a/module/my-shop/ajax.php +++ b/module/my-shop/ajax.php @@ -573,7 +573,7 @@ $paymentAttachment = NULL; if($_FILES["paymentAttachment"]["size"] > 0) { - $paymentAttachment = easyUpload($_FILES["paymentAttachment"], "attachments/payments/cheque/" . date("M, Y"), $_POST["paymentChequeNo"] ); + $paymentAttachment = easyUpload($_FILES["paymentAttachment"], "attachments/payments/cheque/" . date("M, Y"), safe_entities($_POST["paymentChequeNo"]) ); if(!isset($paymentAttachment["success"])) { return _e($paymentAttachment); @@ -1278,7 +1278,7 @@ // Update Accounts Balance updateAccountBalance($_POST["advanceCollectionAccounts"]); - $successMsg = sprintf(__("Advance collected successfully updated. Click Here to print the receipt."), " onClick='BMS.MAIN.printPage(this.href, event);' href='". full_website_address() ."/invoice-print/?invoiceType=moneyReceipt&id=". $_POST["shopAdvanceCollectionId"] ."'"); + $successMsg = sprintf(__("Advance collected successfully updated. Click Here to print the receipt."), " onClick='BMS.MAIN.printPage(this.href, event);' href='". full_website_address() ."/invoice-print/?invoiceType=moneyReceipt&id=". safe_entities($_POST["shopAdvanceCollectionId"]) ."'"); echo "
{$successMsg}
"; @@ -1940,7 +1940,7 @@ function(data, status) { - "> + ">
diff --git a/module/peoples/ajax.php b/module/peoples/ajax.php index a4e15b5..6949283 100644 --- a/module/peoples/ajax.php +++ b/module/peoples/ajax.php @@ -1302,7 +1302,7 @@ if($updateUser === true) { // Set language cookie - setcookie("lang", $_POST["userLanguage"], 0, "/"); + setcookie("lang", safe_entities($_POST["userLanguage"]), 0, "/"); _s("Profile has been successfully updated."); @@ -1743,8 +1743,8 @@ // Include the modal header modal_header("New Customer", full_website_address() . "/xhr/?module=peoples&page=addNewCustomer"); - $customerName = ( isset($_GET["val"]) and !is_numeric($_GET["val"]) ) ? $_GET["val"] : ""; - $customerMobile = ( isset($_GET["val"]) and is_numeric($_GET["val"]) ) ? $_GET["val"] : ""; + $customerName = ( isset($_GET["val"]) and !is_numeric($_GET["val"]) ) ? safe_entities($_GET["val"]) : ""; + $customerMobile = ( isset($_GET["val"]) and is_numeric($_GET["val"]) ) ? safe_entities($_GET["val"]) : ""; ?>
diff --git a/module/products/ajax.php b/module/products/ajax.php index 48a7121..54a2712 100644 --- a/module/products/ajax.php +++ b/module/products/ajax.php @@ -6,7 +6,7 @@ // Include the modal header modal_header("New Category", full_website_address() . "/xhr/?module=products&page=addNewCategory"); - $categoryName = isset($_GET["val"]) ? $_GET["val"] : ""; + $categoryName = isset($_GET["val"]) ? safe_entities($_GET["val"]) : ""; ?>
@@ -317,7 +317,8 @@ $productPhoto = NULL; if($_FILES["productPhoto"]["size"] > 0) { - $productPhoto = easyUpload($_FILES["productPhoto"], "products/{$_POST["productCode"]}", "main__" . $_POST["productCode"]); + $product_code = safe_entities($_GET["packet"]); + $productPhoto = easyUpload($_FILES["productPhoto"], "products/{$product_code}", "main__" . $product_code); if(!isset($productPhoto["success"])) { return _e($productPhoto); @@ -871,7 +872,8 @@ // update the product photo if($_FILES["productPhoto"]["size"] > 0) { - $productPhoto = easyUpload($_FILES["productPhoto"], "products/{$_POST["productCode"]}", "main__" . $_POST["productCode"]); + $product_code = safe_entities($_POST["productCode"]); + $productPhoto = easyUpload($_FILES["productPhoto"], "products/{$product_code}", "main__" . $product_code); if(!isset($productPhoto["success"])) { return _e($productPhoto); @@ -1814,7 +1816,7 @@ // Include the modal header modal_header("New Product Edition", full_website_address() . "/xhr/?module=products&page=addNewProductEdition"); - $edition_name = isset( $_GET["val"] ) ? $_GET["val"] : ""; + $edition_name = isset( $_GET["val"] ) ? safe_entities($_GET["val"]) : ""; ?>
@@ -2038,7 +2040,7 @@ // Include the modal header modal_header("New Product Brand", full_website_address() . "/xhr/?module=products&page=addNewProductBrand"); - $brand_name = isset( $_GET["val"] ) ? $_GET["val"] : ""; + $brand_name = isset( $_GET["val"] ) ? safe_entities($_GET["val"]) : ""; ?>
@@ -2497,7 +2499,7 @@ " class="form-control">
- "> + ">
@@ -3097,7 +3099,7 @@ // Include the modal header modal_header("New Generic", full_website_address() . "/xhr/?module=products&page=addNewProductGeneric"); - $generic_name = isset( $_GET["val"] ) ? $_GET["val"] : ""; + $generic_name = isset( $_GET["val"] ) ? safe_entities($_GET["val"]) : ""; ?>
diff --git a/module/reports/ajax.php b/module/reports/ajax.php index 9df9481..3ec9bc2 100644 --- a/module/reports/ajax.php +++ b/module/reports/ajax.php @@ -1150,7 +1150,7 @@ where payments_categorie.is_trash = 0 and payment_category_name LIKE '{$search}%' having total_amount_in_this_category > 0 order by payment_category_name ". safe_input($requestData['order'][0]['dir']) ." - LIMIT ". safe_input($requestData['start']) .", ". $requestData['length'] ." + LIMIT ". safe_input($requestData['start']) .", ". safe_input($requestData['length']) ." " ); @@ -1337,7 +1337,9 @@ salary_description from {$table_prefeix}salaries as salaries left join {$table_prefeix}employees on salary_emp_id = emp_id - where salaries.is_trash = 0 and salaries.salary_type = '{$paymentType}' and salaries.salary_month between '{$dateRange[0]}' and '{$dateRange[1]}' and concat( emp_firstname, ' ', emp_lastname ) like '%{$search}%' order by salary_id DESC + where salaries.is_trash = 0 and salaries.salary_type = '{$paymentType}' and + salaries.salary_month between '{$dateRange[0]}' and '{$dateRange[1]}' and concat( emp_firstname, ' ', emp_lastname ) like '%{$search}%' + order by salary_id DESC " ); @@ -1479,8 +1481,8 @@ ) as loan_installment on loan_installment_provider = emp_id where employee.is_trash = 0 $departmentFilter $empTypeFilter and ( emp_firstname like '{$search}%' or emp_PIN = '{$search}') - order by {$columns[$requestData['order'][0]['column']]} {$requestData['order'][0]['dir']} - LIMIT {$requestData['start']}, {$requestData['length']} + order by {$columns[$requestData['order'][0]['column']]} ". safe_input($requestData['order'][0]['dir']) ." + LIMIT ". safe_input($requestData['start']) .", ". safe_input($requestData['length']) ." " ); @@ -1585,8 +1587,8 @@ product_name like '{$requestData["search"]["value"]}%' or batch_number like '{$requestData["search"]["value"]}%' ) - order by {$columns[$requestData['order'][0]['column']]} {$requestData['order'][0]['dir']} - limit {$requestData['start']},{$requestData['length']} + order by {$columns[$requestData['order'][0]['column']]} ". safe_input($requestData['order'][0]['dir']) ." + LIMIT ". safe_input($requestData['start']) .", ". safe_input($requestData['length']) ." "); @@ -1606,8 +1608,8 @@ left join {$table_prefeix}product_batches as product_batches on product_batches.batch_id = pbs.batch_id left join {$table_prefeix}warehouses on warehouse_id = warehouse WHERE pbs.batch_expiry_date < curdate() - order by {$columns[$requestData['order'][0]['column']]} {$requestData['order'][0]['dir']} - limit {$requestData['start']},{$requestData['length']} + order by {$columns[$requestData['order'][0]['column']]} ". safe_input($requestData['order'][0]['dir']) ." + LIMIT ". safe_input($requestData['start']) .", ". safe_input($requestData['length']) ." "); } diff --git a/module/reports/ajax_back.php b/module/reports/ajax_back.php deleted file mode 100644 index 7f89d6a..0000000 --- a/module/reports/ajax_back.php +++ /dev/null @@ -1,2057 +0,0 @@ - "products", - "fields" => "count(*) as totalRow", - "where" => array( - "is_trash = 0" - ) - ))["data"][0]["totalRow"]; - - if($requestData['length'] == -1) { - $requestData['length'] = $totalRecords; - } - - $soldDateRange[0] = ""; - $soldDateRange[1] = ""; - if( !empty($requestData["columns"][12]['search']['value']) ) { - - $soldDateRange = explode(" - ", safe_input($requestData["columns"][12]['search']['value'])); - - } - - if(!empty($requestData["search"]["value"]) or !empty($requestData["columns"][1]['search']['value']) or !empty($requestData["columns"][2]['search']['value']) or !empty($requestData["columns"][3]['search']['value']) or !empty($requestData["columns"][4]['search']['value']) ) { // get data with search - - $edition_filter = empty($requestData["columns"][4]['search']['value']) ? "AND product.product_type != 'Child'" : "AND product_edition = {$requestData["columns"][4]['search']['value']} "; - - $warehouse_filter = empty($requestData["columns"][1]['search']['value']) ? "" : " = " . $requestData["columns"][1]['search']['value']; - - - $getData = easySelectA(array( - "table" => "products as product", - "fields" => " - product.product_id as pid, product_type, concat(product_name, ' ', if(product_group is null, '', product_group) ) as product_name, - brand_name, product_purchase_price, product_sale_price, product_edition, product_unit, product_category_id, category_name, - if(initial_qty is null, 0, round(initial_qty, 2) ) as initial_qty, - if(production_qty is null, 0, round(production_qty, 2)) as production_qty, - if(sale_qty is null, 0, round(sale_qty, 2) ) as sale_qty, - if(wastage_sale_qty is null, 0, round(wastage_sale_qty, 2) ) as wastage_sale_qty, - if(sale_return_qty is null, 0, round(sale_return_qty, 2) ) as sale_return_qty, - if(purchase_qty is null, 0, round(purchase_qty, 2) ) as purchase_qty, - if(purchase_order_qty is null, 0, round(purchase_order_qty, 2) ) as purchase_order_qty, - if(purchase_return_qty is null, 0, round(purchase_return_qty, 2) ) as purchase_return_qty, - if(transfer_in_qty is null, 0, round(transfer_in_qty, 2) ) as transfer_in_qty, - if(transfer_out_qty is null, 0, round(transfer_out_qty, 2) ) as transfer_out_qty, - if(specimen_copy_qty is null, 0, round(specimen_copy_qty, 2) ) as specimen_copy_qty, - if(specimen_copy_return_qty is null, 0, round(specimen_copy_return_qty, 2) ) as specimen_copy_return_qty, - if(expired_qty is null, 0, round(expired_qty, 2) ) as expired_qty, - if(stock_qty is null, 0, round(stock_qty, 2) ) as stock_qty, - if(sale_item_subtotal is null, 0, round(sale_item_subtotal, 2)) as total_sold_amount, - if(purchase_item_subtotal is null, 0, round(purchase_item_subtotal, 2)) as total_purchased_amount, - if(sale_qty_in_range is null, 0, round(sale_qty_in_range,2 )) as sale_qty_in_range, - child_product as child_product_list - ", - "join" => array( - "left join ( - select - stock_product_id, - sum(case when stock_type = 'initial' then stock_item_qty end) as initial_qty, - sum(case when stock_type = 'sale-production' then stock_item_qty end) as production_qty, - sum(case when stock_type = 'sale' then stock_item_qty end) as sale_qty, - sum(case when stock_type = 'sale' and stock_entry_date between '{$soldDateRange[0]}' and '{$soldDateRange[1]}' then stock_item_qty end) as sale_qty_in_range, - sum(case when stock_type = 'sale' then stock_item_subtotal end) as sale_item_subtotal, - sum(case when stock_type = 'wastage-sale' then stock_item_qty end) as wastage_sale_qty, - sum(case when stock_type = 'sale-return' then stock_item_qty end) as sale_return_qty, - sum(case when stock_type = 'purchase' then stock_item_qty end) as purchase_qty, - sum(case when stock_type = 'purchase' then stock_item_subtotal end) as purchase_item_subtotal, - sum(case when stock_type = 'purchase-order' then stock_item_qty end) as purchase_order_qty, - sum(case when stock_type = 'purchase-return' then stock_item_qty end) as purchase_return_qty, - sum(case when stock_type = 'transfer-in' then stock_item_qty end) as transfer_in_qty, - sum(case when stock_type = 'transfer-out' then stock_item_qty end) as transfer_out_qty, - sum(case when stock_type = 'specimen-copy' then stock_item_qty end) as specimen_copy_qty, - sum(case when stock_type = 'specimen-copy-return' then stock_item_qty end) as specimen_copy_return_qty - from {$table_prefeix}product_stock - where is_trash = 0 and stock_warehouse_id $warehouse_filter - group by stock_product_id - ) as product_stock on stock_product_id = product_id", - "left join ( - select - vp_id, - sum(case when batch_expiry_date < curdate() then base_stock_in/base_qty end) as expired_qty, - sum(case when batch_expiry_date is null or batch_expiry_date > curdate() then base_stock_in/base_qty end) as stock_qty - from product_base_stock - where warehouse $warehouse_filter - group by vp_id - ) as base_stock on base_stock.vp_id = product.product_id", - "left join ( - SELECT - product_parent_id, - group_concat(product_id) as child_product - FROM {$table_prefeix}products - where is_trash = 0 - group by product_parent_id - ) as child_product on child_product.product_parent_id = product_id", - "left join {$table_prefeix}product_category on product_category_id = category_id", - "left join {$table_prefeix}product_brands on product_brand_id = brand_id", - ), - "where" => array( - "product.is_trash = 0 {$edition_filter}", - " AND product_name LIKE" => "%" . $requestData['search']['value'] . "%", - " AND product_brand_id" => $requestData["columns"][2]['search']['value'], - " AND product_category_id" => $requestData["columns"][3]['search']['value'] - ), - "orderby" => array( - $columns[$requestData['order'][0]['column']] => $requestData['order'][0]['dir'] - ), - "limit" => array ( - "start" => $requestData['start'], - "length" => $requestData['length'] - ) - )); - - - $totalFilteredRecords = $getData ? $getData['count'] : 0; - - } else { // Get data withouth search - - $getData = easySelectA(array( - "table" => "products as product", - "fields" => " - product.product_id as pid, product_type, concat(product_name, ' ', if(product_group is null, '', product_group) ) as product_name, - brand_name, product_purchase_price, product_sale_price, product_edition, product_unit, product_category_id, category_name, - if(initial_qty is null, 0, round(initial_qty, 2) ) as initial_qty, - if(production_qty is null, 0, round(production_qty, 2)) as production_qty, - if(sale_qty is null, 0, round(sale_qty, 2) ) as sale_qty, - if(wastage_sale_qty is null, 0, round(wastage_sale_qty, 2) ) as wastage_sale_qty, - if(sale_return_qty is null, 0, round(sale_return_qty, 2) ) as sale_return_qty, - if(purchase_qty is null, 0, round(purchase_qty, 2) ) as purchase_qty, - if(purchase_order_qty is null, 0, round(purchase_order_qty, 2) ) as purchase_order_qty, - if(purchase_return_qty is null, 0, round(purchase_return_qty, 2) ) as purchase_return_qty, - if(transfer_in_qty is null, 0, round(transfer_in_qty, 2) ) as transfer_in_qty, - if(transfer_out_qty is null, 0, round(transfer_out_qty, 2) ) as transfer_out_qty, - if(specimen_copy_qty is null, 0, round(specimen_copy_qty, 2) ) as specimen_copy_qty, - if(specimen_copy_return_qty is null, 0, round(specimen_copy_return_qty, 2) ) as specimen_copy_return_qty, - if(expired_qty is null, 0, round(expired_qty, 2) ) as expired_qty, - if(stock_qty is null, 0, round(stock_qty, 2) ) as stock_qty, - if(sale_item_subtotal is null, 0, round(sale_item_subtotal, 2)) as total_sold_amount, - if(purchase_item_subtotal is null, 0, round(purchase_item_subtotal, 2)) as total_purchased_amount, - if(sale_qty_in_range is null, 0, round(sale_qty_in_range,2 )) as sale_qty_in_range, - child_product as child_product_list - ", - "join" => array( - "left join ( - select - stock_product_id, - sum(case when stock_type = 'initial' then stock_item_qty end) as initial_qty, - sum(case when stock_type = 'sale-production' then stock_item_qty end) as production_qty, - sum(case when stock_type = 'sale' then stock_item_qty end) as sale_qty, - sum(case when stock_type = 'sale' and stock_entry_date between '{$soldDateRange[0]}' and '{$soldDateRange[1]}' then stock_item_qty end) as sale_qty_in_range, - sum(case when stock_type = 'sale' then stock_item_subtotal end) as sale_item_subtotal, - sum(case when stock_type = 'wastage-sale' then stock_item_qty end) as wastage_sale_qty, - sum(case when stock_type = 'sale-return' then stock_item_qty end) as sale_return_qty, - sum(case when stock_type = 'purchase' then stock_item_qty end) as purchase_qty, - sum(case when stock_type = 'purchase' then stock_item_subtotal end) as purchase_item_subtotal, - sum(case when stock_type = 'purchase-order' then stock_item_qty end) as purchase_order_qty, - sum(case when stock_type = 'purchase-return' then stock_item_qty end) as purchase_return_qty, - sum(case when stock_type = 'transfer-in' then stock_item_qty end) as transfer_in_qty, - sum(case when stock_type = 'transfer-out' then stock_item_qty end) as transfer_out_qty, - sum(case when stock_type = 'specimen-copy' then stock_item_qty end) as specimen_copy_qty, - sum(case when stock_type = 'specimen-copy-return' then stock_item_qty end) as specimen_copy_return_qty - from {$table_prefeix}product_stock - group by stock_product_id - ) as product_stock on stock_product_id = product_id", - "left join ( - select - vp_id, - sum(case when batch_expiry_date < curdate() then base_stock_in/base_qty end) as expired_qty, - sum(case when batch_expiry_date is null or batch_expiry_date > curdate() then base_stock_in/base_qty end) as stock_qty - from product_base_stock - group by vp_id - ) as base_stock on base_stock.vp_id = product.product_id", - "left join ( - SELECT - product_parent_id, - group_concat(product_id) as child_product - FROM {$table_prefeix}products - where is_trash = 0 - group by product_parent_id - ) as child_product on child_product.product_parent_id = product_id", - "left join {$table_prefeix}product_category on product_category_id = category_id", - "left join {$table_prefeix}product_brands on product_brand_id = brand_id", - ), - "where" => array( - "product.is_trash = 0 and product.product_type != 'Child' " - ), - "orderby" => array( - $columns[$requestData['order'][0]['column']] => $requestData['order'][0]['dir'] - ), - "limit" => array ( - "start" => $requestData['start'], - "length" => $requestData['length'] - ) - )); - - } - - $allData = []; - - //print_r($getData); - - // Check if there have more then zero data - if($getData) { - - foreach($getData['data'] as $key => $value) { - - $allNestedData = []; - - /** - * For variable to product, we have to show all variation count in main product - * - * And When click on the variable product, The all variation will be shown - */ - if( $value["product_type"] === "Variable" and $value["child_product_list"] !== null ) { - - $variations = easySelectA(array( - "table" => "products as product", - "fields" => " - product.product_id as pid, product_type, concat(product_name, ' ', if(product_group is null, '', product_group) ) as product_name, - brand_name, product_purchase_price, product_sale_price, product_edition, product_unit, product_category_id, category_name, - if(initial_qty is null, 0, round(initial_qty, 2)) as initial_qty, - if(production_qty is null, 0, round(production_qty, 2)) as production_qty, - if(sale_qty is null, 0, round(sale_qty, 2)) as sale_qty, - if(wastage_sale_qty is null, 0, round(wastage_sale_qty, 2)) as wastage_sale_qty, - if(sale_return_qty is null, 0, round(sale_return_qty, 2)) as sale_return_qty, - if(purchase_qty is null, 0, round(purchase_qty, 2)) as purchase_qty, - if(purchase_order_qty is null, 0, round(purchase_order_qty, 2)) as purchase_order_qty, - if(purchase_return_qty is null, 0, round(purchase_return_qty, 2)) as purchase_return_qty, - if(transfer_in_qty is null, 0, round(transfer_in_qty, 2)) as transfer_in_qty, - if(transfer_out_qty is null, 0, round(transfer_out_qty, 2)) as transfer_out_qty, - if(specimen_copy_qty is null, 0, round(specimen_copy_qty, 2)) as specimen_copy_qty, - if(specimen_copy_return_qty is null, 0, round(specimen_copy_return_qty, 2)) as specimen_copy_return_qty, - if(expired_qty is null, 0, round(expired_qty, 2)) as expired_qty, - if(stock_qty is null, 0, round(stock_qty, 2)) as stock_qty, - if(sale_item_subtotal is null, 0, round(sale_item_subtotal, 2)) as total_sold_amount, - if(purchase_item_subtotal is null, 0, round(purchase_item_subtotal, 2)) as total_purchased_amount, - if(sale_qty_in_range is null, 0, round(sale_qty_in_range,2 )) as sale_qty_in_range - ", - "join" => array( - "left join ( - select - stock_product_id, - sum(case when stock_type = 'initial' then stock_item_qty end) as initial_qty, - sum(case when stock_type = 'sale-production' then stock_item_qty end) as production_qty, - sum(case when stock_type = 'sale' then stock_item_qty end) as sale_qty, - sum(case when stock_type = 'sale' and stock_entry_date between '{$soldDateRange[0]}' and '{$soldDateRange[1]}' then stock_item_qty end) as sale_qty_in_range, - sum(case when stock_type = 'sale' then stock_item_subtotal end) as sale_item_subtotal, - sum(case when stock_type = 'wastage-sale' then stock_item_qty end) as wastage_sale_qty, - sum(case when stock_type = 'sale-return' then stock_item_qty end) as sale_return_qty, - sum(case when stock_type = 'purchase' then stock_item_qty end) as purchase_qty, - sum(case when stock_type = 'purchase' then stock_item_subtotal end) as purchase_item_subtotal, - sum(case when stock_type = 'purchase-order' then stock_item_qty end) as purchase_order_qty, - sum(case when stock_type = 'purchase-return' then stock_item_qty end) as purchase_return_qty, - sum(case when stock_type = 'transfer-in' then stock_item_qty end) as transfer_in_qty, - sum(case when stock_type = 'transfer-out' then stock_item_qty end) as transfer_out_qty, - sum(case when stock_type = 'specimen-copy' then stock_item_qty end) as specimen_copy_qty, - sum(case when stock_type = 'specimen-copy-return' then stock_item_qty end) as specimen_copy_return_qty - from {$table_prefeix}product_stock - where is_trash = 0 and stock_warehouse_id $warehouse_filter - group by stock_product_id - ) as product_stock on stock_product_id = product_id", - "left join ( - select - vp_id, - sum(case when batch_expiry_date < curdate() then base_stock_in/base_qty end) as expired_qty, - sum(case when batch_expiry_date is null or batch_expiry_date > curdate() then base_stock_in/base_qty end) as stock_qty - from product_base_stock - where warehouse $warehouse_filter - group by vp_id - ) as base_stock on base_stock.vp_id = product.product_id", - "left join {$table_prefeix}product_category on product_category_id = category_id", - "left join {$table_prefeix}product_brands on product_brand_id = brand_id", - ), - "where" => array( - "product.product_id in({$value['child_product_list']})" - ), - - )); - - - - $allChildProduct = []; - - // Store the total count for main product - $mainProduct = array( - "initial_qty" => 0, - "production_qty" => 0, - "purchase_qty" => 0, - "purchase_return_qty" => 0, - "transfer_in_qty" => 0, - "transfer_out_qty" => 0, - "sale_qty" => 0, - "sale_qty_in_range" => 0, - "sale_return_qty" => 0, - "specimen_copy_qty" => 0, - "specimen_copy_return_qty" => 0, - "expired_qty" => 0, - "stock_qty" => 0, - "stock_value" => 0, - "stock_balance" => 0, - "total_purchased_amount" => 0, - "total_sold_amount" => 0 - ); - - if($variations !== false) { - - // cp = child product - foreach($variations["data"] as $cpKey => $cpVal ) { - - $childProduct = []; - - $childProduct[] = ""; - //$childProduct[] = "{$cpVal['product_name']}"; - $childProduct[] = "{$cpVal['product_name']} - "; - - $childProduct[] = $cpVal["brand_name"]; - $childProduct[] = $cpVal["category_name"]; - $childProduct[] = $cpVal["product_edition"]; - $childProduct[] = $cpVal["initial_qty"]; - $childProduct[] = $cpVal["production_qty"]; - $childProduct[] = number_format($cpVal["purchase_qty"], 2); - $childProduct[] = $cpVal["purchase_return_qty"]; - $childProduct[] = $cpVal["transfer_in_qty"]; - $childProduct[] = $cpVal["transfer_out_qty"]; - $childProduct[] = number_format($cpVal["sale_qty"], 2) ; - $childProduct[] = $cpVal["sale_qty_in_range"]; - $childProduct[] = $cpVal["sale_return_qty"]; - $childProduct[] = $cpVal["specimen_copy_qty"]; - $childProduct[] = $cpVal["specimen_copy_return_qty"]; - $childProduct[] = $cpVal["expired_qty"]; - $childProduct[] = $cpVal["stock_qty"]; - $childProduct[] = $cpVal["product_unit"]; - $childProduct[] = $cpVal["stock_qty"] * $cpVal["product_sale_price"]; - $childProduct[] = $cpVal["stock_qty"] * $cpVal["product_purchase_price"]; - $childProduct[] = $cpVal["total_purchased_amount"]; - $childProduct[] = $cpVal["total_sold_amount"]; - - $allChildProduct[] = $childProduct; - - - - // Store main product details - $mainProduct["initial_qty"] += $cpVal["initial_qty"]; - $mainProduct["production_qty"] += $cpVal["production_qty"]; - $mainProduct["purchase_qty"] += $cpVal["purchase_qty"]; - $mainProduct["purchase_return_qty"] += $cpVal["purchase_return_qty"]; - $mainProduct["transfer_in_qty"] += $cpVal["transfer_in_qty"]; - $mainProduct["transfer_out_qty"] += $cpVal["transfer_out_qty"]; - $mainProduct["sale_qty"] += $cpVal["sale_qty"]; - $mainProduct["sale_qty_in_range"] += $cpVal["sale_qty_in_range"]; - $mainProduct["sale_return_qty"] += $cpVal["sale_return_qty"]; - $mainProduct["specimen_copy_qty"] += $cpVal["specimen_copy_qty"]; - $mainProduct["specimen_copy_return_qty"] += $cpVal["specimen_copy_return_qty"]; - $mainProduct["expired_qty"] += $cpVal["expired_qty"]; - $mainProduct["stock_qty"] += $cpVal["stock_qty"]; - $mainProduct["stock_value"] += $cpVal["stock_qty"] * $cpVal["product_sale_price"]; - $mainProduct["stock_balance"] += $cpVal["stock_qty"] * $cpVal["product_purchase_price"]; - $mainProduct["total_purchased_amount"] += $cpVal["total_purchased_amount"]; - $mainProduct["total_sold_amount"] += $cpVal["total_sold_amount"]; - - } - - } - - - $allNestedData[] = ""; - $allNestedData[] = "{$value['product_name']}"; - $allNestedData[] = $value["brand_name"]; - $allNestedData[] = $value["category_name"]; - $allNestedData[] = ""; - $allNestedData[] = $mainProduct["initial_qty"]; - $allNestedData[] = $mainProduct["production_qty"]; - $allNestedData[] = $mainProduct["purchase_qty"]; - $allNestedData[] = $mainProduct["purchase_return_qty"]; - $allNestedData[] = $mainProduct["transfer_in_qty"]; - $allNestedData[] = $mainProduct["transfer_out_qty"]; - $allNestedData[] = $mainProduct["sale_qty"]; - $allNestedData[] = $mainProduct["sale_qty_in_range"]; - $allNestedData[] = $mainProduct["sale_return_qty"]; - $allNestedData[] = $mainProduct["specimen_copy_qty"]; - $allNestedData[] = $mainProduct["specimen_copy_return_qty"]; - $allNestedData[] = $mainProduct["expired_qty"]; - $allNestedData[] = $mainProduct["stock_qty"]; - $allNestedData[] = $value["product_unit"]; - $allNestedData[] = $mainProduct["stock_value"]; - $allNestedData[] = $mainProduct["stock_balance"]; - $allNestedData[] = $mainProduct["total_purchased_amount"]; - $allNestedData[] = $mainProduct["total_sold_amount"]; - $allNestedData["child"] = $allChildProduct; - - - } else { - - - $allNestedData[] = ""; - $allNestedData[] = "{$value['product_name']} - "; - $allNestedData[] = $value["brand_name"]; - $allNestedData[] = $value["category_name"]; - $allNestedData[] = $value["product_edition"]; - $allNestedData[] = $value["initial_qty"]; - $allNestedData[] = $value["production_qty"]; - $allNestedData[] = $value["purchase_qty"]; - $allNestedData[] = $value["purchase_return_qty"]; - $allNestedData[] = $value["transfer_in_qty"]; - $allNestedData[] = $value["transfer_out_qty"]; - $allNestedData[] = $value["sale_qty"]; - $allNestedData[] = $value["sale_qty_in_range"]; - $allNestedData[] = $value["sale_return_qty"]; - $allNestedData[] = $value["specimen_copy_qty"]; - $allNestedData[] = $value["specimen_copy_return_qty"]; - $allNestedData[] = $value["expired_qty"]; - $allNestedData[] = $value["stock_qty"]; - $allNestedData[] = $value["product_unit"]; - $allNestedData[] = $value["stock_qty"] * $value["product_sale_price"]; - $allNestedData[] = $value["stock_qty"] * $value["product_purchase_price"]; - $allNestedData[] = $value["total_purchased_amount"]; - $allNestedData[] = $value["total_sold_amount"]; - - } - - - $allData[] = $allNestedData; - - } - - } - - - $jsonData = array ( - "draw" => intval( $requestData['draw'] ), - "recordsTotal" => intval( $totalRecords ), - "recordsFiltered" => intval( $totalFilteredRecords ), - "data" => $allData - ); - - // Encode in Json Formate - echo json_encode($jsonData); -} - -/*************************** Customer Reports ***********************/ -if(isset($_GET['page']) and $_GET['page'] == "updateProductStock") { - - $pid = safe_input($_POST["datatoUpdate"]); - - // Delete previous stock belongs to this product id - runQuery("DELETE FROM product_base_stock WHERE product_id = {$pid}"); - - // Insert New Stocks - runQuery(" - INSERT INTO product_base_stock - (product_id, vp_id, warehouse, base_stock_in, base_qty, batch_id, batch_expiry_date) - SELECT - product_stock.stock_product_id as product_id, - product.product_id AS vp_id, - stock_warehouse_id as warehouse, - sum( - ( -- All stock in sunch as purchase, return etc - CASE WHEN ( - stock_type = 'initial' OR - stock_type = 'adjustment' OR - stock_type = 'sale-production' OR - stock_type = 'sale-return' OR - stock_type = 'purchase' OR - stock_type = 'specimen-copy-return' OR - stock_type = 'transfer-in' - ) and stock_item_qty IS NOT NULL - THEN stock_item_qty - ELSE 0 - END - - - -- subtract stock out from stock in - - -- All stock out, such as sale, specimen copy etc - CASE WHEN ( - stock_type = 'sale' OR - stock_type = 'wastage-sale' OR - stock_type = 'purchase-return' OR - stock_type = 'specimen-copy' OR - stock_type = 'transfer-out' - ) and stock_item_qty IS NOT NULL - THEN stock_item_qty - ELSE 0 - END - ) - - * -- And multiply with base quantity, which is taken from product unit - - if(vp_unit.base_qnt is null, 1, vp_unit.base_qnt) - - ) as base_stock_in, - if(np_unit.base_qnt is null, 1, np_unit.base_qnt) as base_qty, - stock_batch_id as batch_id, - batch_expiry_date - FROM `ro_products` as product - left join ro_products as vp on vp.product_parent_id = product.product_parent_id and vp.product_variations = product.product_variations or vp.product_id = product.product_id - left join ro_product_stock as product_stock on vp.product_id = product_stock.stock_product_id - left join ro_product_units as vp_unit on vp.product_unit = vp_unit.unit_name -- vp = variable product - left join ro_product_units as np_unit on product.product_unit = np_unit.unit_name -- np = normal product - left join ro_product_batches as batch on batch.batch_id = stock_batch_id and batch.product_id = stock_product_id - where stock_warehouse_id is not null and product_stock.is_trash = 0 and - product_stock.stock_product_id = '{$pid}' - group by product.product_id, product_stock.stock_product_id, stock_warehouse_id, stock_batch_id; - "); - - - echo '{ - "title": "Stock has been successfully updated.", - "icon": "success" - }'; - - -} - -/*************************** Customer Reports ***********************/ -if(isset($_GET['page']) and $_GET['page'] == "customerReports") { - - $requestData = $_REQUEST; - $getData = []; - $search = safe_input($requestData['search']['value']); - - // List of all columns name - $columns = array( - "", - "customer_name" - ); - - // Count Total recrods - $totalFilteredRecords = $totalRecords = easySelectA(array( - "table" => "customers", - "fields" => "count(*) as totalRow", - "where" => array( - "is_trash = 0" - ) - ))["data"][0]["totalRow"]; - - if($requestData['length'] == -1) { - $requestData['length'] = $totalRecords; - } - - $getDateRange = ( isset( $requestData['columns'][1]['search']['value']) and !empty($requestData['columns'][1]['search']['value']) ) ? safe_input($requestData['columns'][1]['search']['value']) : "1970-01-01 - " . date("Y-12-31"); - $dateRange = explode(" - ", $getDateRange); - - - $getData = easySelectD( - "select customer_id, customer_name, - if(sales_grand_total_in_filtered_date is null, 0, round(sales_grand_total_in_filtered_date, 2)) as sales_grand_total_in_filtered_date, - if(wastage_sale_grand_total_in_filtered_date is null, 0, round(wastage_sale_grand_total_in_filtered_date, 2)) as wastage_sale_grand_total_in_filtered_date, - if(sales_shipping_in_filtered_date is null, 0, round(sales_shipping_in_filtered_date, 2)) as sales_shipping_in_filtered_date, - if(product_returns_grand_total_in_filtered_date is null, 0, round(product_returns_grand_total_in_filtered_date, 2)) as product_returns_grand_total_in_filtered_date, - if(received_payments_amount_in_filtered_date is null, 0, round(received_payments_amount_in_filtered_date, 2)) as received_payments_amount_in_filtered_date, - if(received_payments_bonus_in_filtered_date is null, 0, round(received_payments_bonus_in_filtered_date, 2)) as received_payments_bonus_in_filtered_date, - if(discounts_amount_in_filtered_date is null, 0, round(discounts_amount_in_filtered_date, 2)) as discounts_amount_in_filtered_date, - round(( - if(customer_opening_balance is null, 0, customer_opening_balance) + - if(total_return_before_filtered_date is null, 0, total_return_before_filtered_date) + - if(received_payments_amount_before_filtered_date is null, 0, received_payments_amount_before_filtered_date) + - if(received_payments_bonus_before_filtered_date is null, 0, received_payments_bonus_before_filtered_date) + - if(discounts_amount_before_filtered_date is null, 0, discounts_amount_before_filtered_date) - ) - ( - if(sales_grand_total_before_filtered_date is null, 0, sales_grand_total_before_filtered_date) + - if(wastage_sale_grand_total_before_filtered_date is null, 0, wastage_sale_grand_total_before_filtered_date) - ), 2) as previous_balance, - upazila_name, district_name - from {$table_prefeix}customers as customer - left join {$table_prefeix}upazilas on customer_upazila = upazila_id - left join {$table_prefeix}districts on customer_district = district_id - left join ( - select - sales_customer_id, - sum( case when is_return = 0 and sales_delivery_date between '{$dateRange[0]}' and '{$dateRange[1]}' then sales_grand_total end ) as sales_grand_total_in_filtered_date, - sum( case when is_return = 0 and sales_delivery_date < '{$dateRange[0]}' then sales_grand_total end ) as sales_grand_total_before_filtered_date, - sum( case when is_return = 0 and sales_delivery_date between '{$dateRange[0]}' and '{$dateRange[1]}' then sales_shipping end ) as sales_shipping_in_filtered_date, - sum( case when is_return = 1 and sales_delivery_date between '{$dateRange[0]}' and '{$dateRange[1]}' then sales_grand_total end ) as product_returns_grand_total_in_filtered_date, - sum( case when is_return = 1 and sales_delivery_date < '{$dateRange[0]}' then sales_grand_total end ) as total_return_before_filtered_date - from {$table_prefeix}sales where is_trash = 0 group by sales_customer_id - ) as sales on customer_id = sales_customer_id - left join ( select - wastage_sale_customer, - sum( case when wastage_sale_date between '{$dateRange[0]}' and '{$dateRange[1]}' then wastage_sale_grand_total end ) as wastage_sale_grand_total_in_filtered_date, - sum( case when wastage_sale_date < '{$dateRange[0]}' then wastage_sale_grand_total end ) as wastage_sale_grand_total_before_filtered_date - from {$table_prefeix}wastage_sale where is_trash = 0 group by wastage_sale_customer - ) as wastage_sale on wastage_sale_customer = sales_customer_id - left join ( select - received_payments_from, - sum( case when date(received_payments_datetime) between '{$dateRange[0]}' and '{$dateRange[1]}' then received_payments_amount end ) as received_payments_amount_in_filtered_date, - sum( case when date(received_payments_datetime) < '{$dateRange[0]}' then received_payments_amount end ) as received_payments_amount_before_filtered_date, - sum( case when date(received_payments_datetime) between '{$dateRange[0]}' and '{$dateRange[1]}' then received_payments_bonus end ) as received_payments_bonus_in_filtered_date, - sum( case when date(received_payments_datetime) < '{$dateRange[0]}' then received_payments_bonus end ) as received_payments_bonus_before_filtered_date - from {$table_prefeix}received_payments where is_trash = 0 and received_payments_type != 'Discounts' group by received_payments_from - ) as received_payments on customer_id = received_payments.received_payments_from - left join ( select - received_payments_from, - sum( case when date(received_payments_datetime) between '{$dateRange[0]}' and '{$dateRange[1]}' then received_payments_amount end ) as discounts_amount_in_filtered_date, - sum( case when date(received_payments_datetime) < '{$dateRange[0]}' then received_payments_amount end ) as discounts_amount_before_filtered_date - from {$table_prefeix}received_payments where is_trash = 0 and received_payments_type = 'Discounts' group by received_payments_from - ) as given_discounts on customer_id = given_discounts.received_payments_from - where customer.is_trash = 0 and customer_name like '{$search}%' - group by customer_id order by customer_name {$requestData['order'][0]['dir']} - LIMIT {$requestData['start']}, {$requestData['length']} - " - ); - - $totalFilteredRecords = $getData ? $getData["count"] : 0; - - - $allData = []; - // Check if there have more then zero data - if($getData) { - - foreach($getData['data'] as $key => $value) { - - - $allNestedData = []; - $allNestedData[] = ""; - $allNestedData[] = "{$value['customer_name']}, {$value['upazila_name']}, {$value['district_name']}"; - $allNestedData[] = $value["previous_balance"]; - $allNestedData[] = ( $value["sales_grand_total_in_filtered_date"] + $value["wastage_sale_grand_total_in_filtered_date"] ) - $value["sales_shipping_in_filtered_date"]; - $allNestedData[] = $value["sales_shipping_in_filtered_date"]; - $allNestedData[] = $value["received_payments_amount_in_filtered_date"]; - $allNestedData[] = $value["received_payments_bonus_in_filtered_date"]; - $allNestedData[] = $value["product_returns_grand_total_in_filtered_date"]; - $allNestedData[] = $value["discounts_amount_in_filtered_date"]; - $allNestedData[] = round(( - $value["previous_balance"] + $value["received_payments_amount_in_filtered_date"] + - $value["received_payments_bonus_in_filtered_date"] + $value["product_returns_grand_total_in_filtered_date"]) - - ( - ($value["sales_grand_total_in_filtered_date"] + $value["wastage_sale_grand_total_in_filtered_date"]) - $value["discounts_amount_in_filtered_date"] - ), 2); - - $allData[] = $allNestedData; - } - } - - - $jsonData = array ( - "draw" => intval( $requestData['draw'] ), - "recordsTotal" => intval( $totalRecords ), - "recordsFiltered" => intval( $totalFilteredRecords ), - "data" => $allData - ); - - // Encode in Json Formate - echo json_encode($jsonData); -} - - -/*************************** Day By Day Customer Reports ***********************/ -if(isset($_GET['page']) and $_GET['page'] == "customerStatement") { - - $requestData = $_REQUEST; - $getData = []; - - // Count Total recrods - $totalFilteredRecords = $totalRecords = 0; - $allData = []; - - if( isset($_GET["cid"]) ) { - - $dateRange = explode(" - ", safe_input($requestData["dateRange"])); - $customer_id = safe_input($_GET["cid"]); - - $previous_balance = easySelectD(" - SELECT - @balance := ( - if(customer_opening_balance is null, 0, customer_opening_balance) + - if(total_returned_before_filtered_date is null, 0, total_returned_before_filtered_date) + - if(total_payment_before_filtered_date is null, 0, total_payment_before_filtered_date) - ) - ( - if(total_purchased_before_filtered_date is null, 0, total_purchased_before_filtered_date) + - if(total_wastage_purched_before_filtered_date is null, 0, total_wastage_purched_before_filtered_date) + - if(total_payment_return_before_filtered_date is null, 0, total_payment_return_before_filtered_date) - ) - FROM {$table_prefeix}customers as customers - left join ( select - sales_customer_id, - sum(case when is_return = 0 then sales_grand_total end) as total_purchased_before_filtered_date, - sum(case when is_return = 1 then sales_due end) as total_returned_before_filtered_date - from {$table_prefeix}sales where is_trash = 0 and sales_delivery_date < '{$dateRange[0]}' group by sales_customer_id - ) as sales on sales_customer_id = customer_id - left join ( select - wastage_sale_customer, - sum(wastage_sale_grand_total) as total_wastage_purched_before_filtered_date - from {$table_prefeix}wastage_sale where is_trash = 0 and wastage_sale_date < '{$dateRange[0]}' group by wastage_sale_customer - ) as wastage_sale on wastage_sale_customer = customer_id - left join ( select - received_payments_from, - sum(received_payments_amount) + sum(received_payments_bonus) as total_payment_before_filtered_date - from {$table_prefeix}received_payments where is_trash = 0 and date(received_payments_datetime) < '{$dateRange[0]}' group by received_payments_from - ) as payments on received_payments_from = customer_id - left join (select - payments_return_customer_id, - sum(payments_return_amount) as total_payment_return_before_filtered_date - from {$table_prefeix}payments_return - where is_trash = 0 and payments_return_type = 'Outgoing' and date(payments_return_date) < '{$dateRange[0]}' - group by payments_return_customer_id - ) as payment_return on customer_id = payments_return_customer_id - where customer_id = {$customer_id} - "); - - - $getData = easySelectD(" - select dates, record_id, customers, reference, reference_link, description, purchase_amount, discount, shipping, debit, credit, @balance := ( @balance + credit ) - debit as balance from - ( - select - 1 as sortby, - sales_delivery_date as dates, - sales_id as record_id, - sales_customer_id as customers, - sales_reference as reference, - '/xhr/?module=reports&page=showInvoiceProducts&id=' as reference_link, - combine_description( if(is_exchange=1, 'Product Exchange', 'Product Purchase'), sales_note) as description, - sales_total_amount as purchase_amount, - (sales_product_discount + sales_discount) as discount, - sales_shipping as shipping, - if(sales_grand_total > 0, sales_grand_total, 0) as debit, - if(sales_grand_total < 0, abs(sales_grand_total), 0) as credit - from {$table_prefeix}sales - where is_trash = 0 and is_return = 0 and sales_delivery_date between '{$dateRange[0]}' and '{$dateRange[1]}' group by sales_id - UNION ALL - select - 2 as sortby, - sales_delivery_date as dates, - sales_id as record_id, - sales_customer_id as customers, - sales_reference as reference, - '/xhr/?module=reports&page=showInvoiceProducts&id=' as reference_link, - combine_description('Product Return', sales_note) as description, - '', - '', - '', - 0 as debit, - sales_grand_total as credit - from {$table_prefeix}sales - where is_trash = 0 and is_return = 1 and sales_delivery_date between '{$dateRange[0]}' and '{$dateRange[1]}' group by sales_id - UNION ALL - select - 3 as sortby, - date(received_payments_datetime), - '', - received_payments_from, - received_payments_reference, - '', - combine_description(received_payments_type, received_payments_details), - '', - '', - '', - 0 as debit, - received_payments_amount as credit - from {$table_prefeix}received_payments where is_trash = 0 and date(received_payments_datetime) between '{$dateRange[0]}' and '{$dateRange[1]}' group by received_payments_id - UNION ALL - select - 4 as sortby, - date(received_payments_datetime), - '', - received_payments_from, - received_payments_reference, - '', - combine_description('Given Bonus', received_payments_details), - '', - '', - '', - 0 as debit, - received_payments_bonus as credit - from {$table_prefeix}received_payments where is_trash = 0 and - received_payments_bonus > 0 and - date(received_payments_datetime) between '{$dateRange[0]}' and '{$dateRange[1]}' - group by received_payments_id - UNION ALL - select - 5 as sortby, - wastage_sale_date, - wastage_sale_id, - wastage_sale_customer, - concat('Sale/Wastage/', wastage_sale_id), - '/xhr/?module=sales&page=viewWastageSale&id=', - combine_description('Wastage Sales', concat(wastage_sale_reference, ', ', wastage_sale_note)), - '', - '', - '', - wastage_sale_grand_total as debit, - 0 as credit - from {$table_prefeix}wastage_sale where is_trash = 0 and wastage_sale_date between '{$dateRange[0]}' and '{$dateRange[1]}' group by wastage_sale_id - UNION ALL - select - 6 as sortby, - payments_return_date, - '', - payments_return_customer_id, - '', - '', - combine_description('Payment return ', payments_return_description) as description, - '', - '', - '', - payments_return_amount as debit, - 0 as credit - from {$table_prefeix}payments_return where is_trash = 0 and payments_return_date between '{$dateRange[0]}' and '{$dateRange[1]}' group by payments_return_id - UNION ALL - select - 7 as sortby, - incomes_date, - '', - incomes_from, - '', - '', - combine_description('Received Payments ', incomes_description) as description, - '', - '', - '', - 0 as debit, - incomes_amount as credit - from {$table_prefeix}incomes where is_trash = 0 and incomes_date between '{$dateRange[0]}' and '{$dateRange[1]}' group by incomes_id - - ) as get_data - where customers = {$customer_id} and date(dates) between '{$dateRange[0]}' and '{$dateRange[1]}' - order by dates, sortby - "); - - $totalFilteredRecords = $totalRecords = $getData !== false ? $getData["count"] : 0; - - // Check if there have more then zero data - if(isset($getData['count']) and $getData['count'] > 0) { - - foreach($getData['data'] as $key => $value) { - - $allNestedData = []; - $allNestedData[] = ""; - $allNestedData[] = date("d/m/Y", strtotime($value["dates"])); - $allNestedData[] = "{$value['reference']}"; - $allNestedData[] = $value["description"]; - $allNestedData[] = $value["purchase_amount"]; - $allNestedData[] = $value["discount"]; - $allNestedData[] = $value["shipping"]; - $allNestedData[] = number_format($value["debit"], 0, "", ""); - $allNestedData[] = number_format($value["credit"], 0, "", ""); - $allNestedData[] = number_format($value["balance"], 2) ; - - $allData[] = $allNestedData; - } - } - - } - - - - $jsonData = array ( - "draw" => intval( $requestData['draw'] ), - "recordsTotal" => intval( $totalRecords ), - "recordsFiltered" => intval( $totalFilteredRecords ), - "data" => $allData - ); - - // Encode in Json Formate - echo json_encode($jsonData); -} - - -/************************** Invoice Product **********************/ -if(isset($_GET['page']) and $_GET['page'] == "showInvoiceProducts") { - - // Select sales - $selectSale = easySelect( - "sales", - "*", - array ( - "left join {$table_prefeix}customers on sales_customer_id = customer_id" - ), - array ( - "sales_id" => $_GET["id"] - ) - ); - - // Select Sales item - $selectSalesItems = easySelectA(array( - "table" => "product_stock", - "fields" => "product_name, stock_item_price, stock_item_qty, stock_item_subtotal", - "join" => array( - "left join {$table_prefeix}products on product_id = stock_product_id" - ), - "where" => array( - "is_bundle_item = 0 and stock_sales_id" => $_GET["id"] - ) - )); - - $sales = $selectSale["data"][0]; - - ?> - - - - - - $_GET["id"] - ) - ); - - // Select return item - $selectProductReturnItems = easySelect( - "product_return_items", - "*", - array(), - array ( - "product_return_items_returns_id" => $_GET["id"] - ) - ); - - $return = $selectReturn["data"][0]; - - ?> - - - - - - - - - - "; - return; - } - $totalPurchased = 0; - echo "Customer: " . $selectPurchased["data"][0]["customer_name"]; - echo "

"; - - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - - foreach($selectPurchased["data"] as $key => $value) { - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - $totalPurchased += $value['stock_item_qty']; - } - - echo ""; - echo ""; - echo ""; - echo ""; - - echo "
DateProductQuantity
{$value['sales_delivery_date']}{$value['product_name']}". number_format($value['stock_item_qty'], 0) ."
Total:{$totalPurchased}
"; - ?> - -
- - "payments_categories", - "fields" => "count(*) as totalRow", - "where" => array( - "is_trash = 0" - ) - ))["data"][0]["totalRow"]; - - if($requestData['length'] == -1) { - $requestData['length'] = $totalRecords; - } - - $getData = easySelectD( - "SELECT - payment_category_id, payment_category_name, - if(payment_items_amount_sum is null, 0, payment_items_amount_sum) + if(bill_items_amount_sum is null, 0, bill_items_amount_sum) as total_amount_in_this_category - from {$table_prefeix}payments_categories as payments_categorie - left join ( SELECT - payment_items_category_id, - sum(payment_items_amount) as payment_items_amount_sum - from {$table_prefeix}payment_items where is_trash = 0 and payment_items_date between '{$dateRange[0]}' and '{$dateRange[1]}' group by payment_items_category_id - ) as payments_items on payment_items_category_id = payment_category_id - left join ( SELECT - bill_items_category, - sum(bill_items_amount) as bill_items_amount_sum - from {$table_prefeix}bill_items where is_trash = 0 and date(bill_items_add_on) between '{$dateRange[0]}' and '{$dateRange[1]}' group by bill_items_category - ) as bill_items on bill_items_category = payment_category_id - where payments_categorie.is_trash = 0 and payment_category_name LIKE '{$search}%' - having total_amount_in_this_category > 0 - order by payment_category_name {$requestData['order'][0]['dir']} - LIMIT {$requestData['start']}, {$requestData['length']} - " - ); - - - $salaryPaymentData = easySelectD( - "SELECT - salary_type, - sum(salary_amount) as total_salary_amount_by_type - from {$table_prefeix}salaries where is_trash = 0 and salary_type LIKE '{$search}%' and salary_month between '{$dateRange[0]}' and '{$dateRange[1]}' group by salary_type - " - ); - - - if ( isset( $requestData['columns'][1]['search']['value']) and !empty($requestData['columns'][1]['search']['value']) ) { - $totalFilteredRecords = $getData["count"] + $salaryPaymentData["count"]; - } - - - $allData = []; - - // not category payments - if(isset($salaryPaymentData['count']) and $salaryPaymentData['count'] > 0) { - - foreach($salaryPaymentData['data'] as $key => $value) { - - $allNestedData = []; - $allNestedData[] = ""; - $allNestedData[] = "{$value['salary_type']} Payments"; - $allNestedData[] = $value["total_salary_amount_by_type"]; - $allData[] = $allNestedData; - } - } - - // Check if there have more then zero data in category payment - if(isset($getData['count']) and $getData['count'] > 0) { - - foreach($getData['data'] as $key => $value) { - - $allNestedData = []; - $allNestedData[] = ""; - $allNestedData[] = "{$value['payment_category_name']}"; - $allNestedData[] = $value["total_amount_in_this_category"]; - $allData[] = $allNestedData; - } - } - - - $jsonData = array ( - "draw" => intval( $requestData['draw'] ), - "recordsTotal" => intval( $totalRecords ), - "recordsFiltered" => intval( $totalFilteredRecords ), - "data" => $allData - ); - - // Encode in Json Formate - echo json_encode($jsonData); -} - - -/*************************** Expense Reports Signle ***********************/ -if(isset($_GET['page']) and $_GET['page'] == "expenseReportsSignle") { - - $requestData = $_REQUEST; - $getData = []; - $search = safe_input($requestData['search']['value']); - $cat_id = safe_input($_GET['cid']); - - $getDateRange = ( isset( $_GET["dateRange"] ) and !empty( $_GET["dateRange"] ) ) ? safe_input( $_GET["dateRange"] ) : "1970-01-01 - " . date("Y-12-31"); - $dateRange = explode(" - ", $getDateRange); - - // List of all columns name - $columns = array( - "", - "customer_name" - ); - - // Count Total recrods - $totalFilteredRecords = $totalRecords = easySelectD( - "SELECT category_id from - ( - (select - payment_items_category_id as category_id - from {$table_prefeix}payment_items where is_trash = 0 and payment_items_date between '{$dateRange[0]}' and '{$dateRange[1]}' order by payment_items_id DESC) - UNION ALL - (select - bill_items_category as category_id - from {$table_prefeix}bill_items where is_trash = 0 and date(bill_items_add_on) between '{$dateRange[0]}' and '{$dateRange[1]}') - ) as getData - where category_id = {$cat_id} - " - )["count"]; - - if($requestData['length'] == -1) { - $requestData['length'] = $totalRecords; - } - - $getData = easySelectD( - "SELECT category_id, item_date, item_amount, item_description from - ( - (select - 1 as sortby, - payment_items_category_id as category_id, - payment_items_date as item_date, - payment_items_amount as item_amount, - payment_items_description as item_description - from {$table_prefeix}payment_items where is_trash = 0 and payment_items_date between '{$dateRange[0]}' and '{$dateRange[1]}' order by payment_items_id DESC) - UNION ALL - (select - 2 as sortby, - bill_items_category as category_id, - bill_items_date as item_date, - bill_items_amount as item_amount, - bill_items_note as item_description - from {$table_prefeix}bill_items where is_trash = 0 and date(bill_items_add_on) between '{$dateRange[0]}' and '{$dateRange[1]}') - ) as getData - where category_id = {$cat_id} - order by item_date {$requestData['order'][0]['dir']}, sortby ASC, item_description DESC - LIMIT {$requestData['start']}, {$requestData['length']} - " - ); - - - $allData = []; - // Check if there have more then zero data - if(isset($getData['count']) and $getData['count'] > 0) { - - foreach($getData['data'] as $key => $value) { - - $allNestedData = []; - $allNestedData[] = ""; - $allNestedData[] = $value["item_date"]; - $allNestedData[] = $value["item_amount"]; - $allNestedData[] = $value["item_description"]; - $allData[] = $allNestedData; - } - } - - - $jsonData = array ( - "draw" => intval( $requestData['draw'] ), - "recordsTotal" => intval( $totalRecords ), - "recordsFiltered" => intval( $totalFilteredRecords ), - "data" => $allData - ); - - // Encode in Json Formate - echo json_encode($jsonData); -} - -/*************************** Expense Reports Non Category ***********************/ -if(isset($_GET['page']) and $_GET['page'] == "expenseReportsNonCat") { - - $requestData = $_REQUEST; - $getData = []; - $search = safe_input($requestData['search']['value']); - $paymentType = safe_input($_GET['paymentType']); - - $getDateRange = ( isset( $_GET["dateRange"] ) and !empty( $_GET["dateRange"] ) ) ? safe_input( $_GET["dateRange"] ) : "1970-01-01 - " . date("Y-12-31"); - $dateRange = explode(" - ", $getDateRange); - - // List of all columns name - $columns = array( - "", - "salary_month" - ); - - // Count Total recrods - $totalFilteredRecords = $totalRecords = easySelectD( - "SELECT - count(*) as totalRow - from {$table_prefeix}salaries as salaries - where salaries.is_trash = 0 and salaries.salary_type = '{$paymentType}' and salaries.salary_month between '{$dateRange[0]}' and '{$dateRange[1]}' - " - )["data"][0]["totalRow"]; - - if($requestData['length'] == -1) { - $requestData['length'] = $totalRecords; - } - - $getData = easySelectD( - "SELECT - salary_month, - concat( emp_firstname, ' ', emp_lastname ) as payee_name, - salary_amount, - salary_description - from {$table_prefeix}salaries as salaries - left join {$table_prefeix}employees on salary_emp_id = emp_id - where salaries.is_trash = 0 and salaries.salary_type = '{$paymentType}' and salaries.salary_month between '{$dateRange[0]}' and '{$dateRange[1]}' and concat( emp_firstname, ' ', emp_lastname ) like '%{$search}%' order by salary_id DESC - " - ); - - $allData = []; - // Check if there have more then zero data - if(isset($getData['count']) and $getData['count'] > 0) { - - foreach($getData['data'] as $key => $value) { - - $allNestedData = []; - $allNestedData[] = ""; - $allNestedData[] = date("M, Y", strtotime($value["salary_month"]) ) ; - $allNestedData[] = $value["payee_name"]; - $allNestedData[] = $value["salary_amount"]; - $allNestedData[] = $value["salary_description"]; - $allData[] = $allNestedData; - } - } - - - $jsonData = array ( - "draw" => intval( $requestData['draw'] ), - "recordsTotal" => intval( $totalRecords ), - "recordsFiltered" => intval( $totalFilteredRecords ), - "data" => $allData - ); - - // Encode in Json Formate - echo json_encode($jsonData); -} - - -/*************************** Customer Reports ***********************/ -if(isset($_GET['page']) and $_GET['page'] == "employeeReports") { - - $requestData = $_REQUEST; - $getData = []; - $search = safe_input($requestData['search']['value']); - - - // List of all columns name - $columns = array( - "", - "abs(emp_PIN)", - "dep_name", - "total_salary_added_in_range", - "total_overtime_added_in_range", - "total_bonus_added_in_range", - "", - "total_salary_paid_in_range", - "total_overtime_paid_in_range", - "total_bonus_paid_in_range", - "" - ); - - // Count Total recrods - $totalFilteredRecords = $totalRecords = easySelectA(array( - "table" => "employees", - "fields" => "count(*) as totalRow", - "where" => array( - "is_trash = 0" - ) - ))["data"][0]["totalRow"]; - - if($requestData['length'] == -1) { - $requestData['length'] = $totalRecords; - } - - $getDateRange = ( isset( $requestData['columns'][1]['search']['value']) and !empty($requestData['columns'][1]['search']['value']) ) ? safe_input($requestData['columns'][1]['search']['value']) : "1970-01-01 - " . date("Y-12-31"); - $dateRange = explode(" - ", $getDateRange); - - /** For dynamic operator searching from datatable */ - $departmentFilter = (array)json_decode($requestData['columns'][2]['search']['value']); - $empTypeFilter = (array)json_decode($requestData['columns'][3]['search']['value']); - - if( isset($departmentFilter["operator"]) ) { - $departmentFilter = "and emp_department_id {$departmentFilter["operator"]} '{$departmentFilter["search"]}'"; - } else { - $departmentFilter = empty($requestData['columns'][2]['search']['value']) ? "" : "and emp_department_id = '{$requestData['columns'][2]['search']['value']}'"; - } - - if( isset($empTypeFilter["operator"]) ) { - $empTypeFilter = "and emp_type {$empTypeFilter["operator"]} '{$empTypeFilter["search"]}'"; - } else { - $empTypeFilter = empty($requestData['columns'][3]['search']['value']) ? "" : "and emp_type = '{$requestData['columns'][3]['search']['value']}'"; - } - - - - $getData = easySelectD( - "select - emp_id, dep_name, emp_firstname, emp_lastname, emp_type, emp_PIN, emp_opening_salary, emp_opening_overtime, emp_opening_bonus, - if(total_salary_added is null, 0, round(total_salary_added, 2)) as total_salary_added, - if(total_overtime_added is null, 0, round(total_overtime_added, 2)) as total_overtime_added, - if(total_bonus_added is null, 0, round(total_bonus_added, 2)) as total_bonus_added, - if(total_salary_added_in_range is null, 0, round(total_salary_added_in_range, 2)) as total_salary_added_in_range, - if(total_overtime_added_in_range is null, 0, round(total_overtime_added_in_range, 2)) as total_overtime_added_in_range, - if(total_bonus_added_in_range is null, 0, round(total_bonus_added_in_range, 2)) as total_bonus_added_in_range, - - if(total_salary_paid is null, 0, round(total_salary_paid, 2)) as total_salary_paid, - if(total_overtime_paid is null, 0, round(total_overtime_paid, 2)) as total_overtime_paid, - if(total_bonus_paid is null, 0, round(total_bonus_paid, 2)) as total_bonus_paid, - if(total_salary_paid_in_range is null, 0, round(total_salary_paid_in_range, 2)) as total_salary_paid_in_range, - if(total_overtime_paid_in_range is null, 0, round(total_overtime_paid_in_range, 2)) as total_overtime_paid_in_range, - if(total_bonus_paid_in_range is null, 0, round(total_bonus_paid_in_range, 2)) as total_bonus_paid_in_range, - if(total_loan_adjustment is null, 0, round(total_loan_adjustment, 2)) as total_loan_adjustment - from {$table_prefeix}employees as employee - left join {$table_prefeix}emp_department on emp_department_id = dep_id - left join ( select - salary_emp_id, - sum( case when salary_type = 'Salary' then salary_amount end ) as total_salary_added, - sum( case when salary_type = 'Overtime' then salary_amount end ) as total_overtime_added, - sum( case when salary_type = 'Bonus' then salary_amount end ) as total_bonus_added, - sum( case when salary_type = 'Salary' and date(salary_add_on) between '{$dateRange[0]}' and '{$dateRange[1]}' then salary_amount end ) as total_salary_added_in_range, - sum( case when salary_type = 'Overtime' and date(salary_add_on) between '{$dateRange[0]}' and '{$dateRange[1]}' then salary_amount end ) as total_overtime_added_in_range, - sum( case when salary_type = 'Bonus' and date(salary_add_on) between '{$dateRange[0]}' and '{$dateRange[1]}' then salary_amount end ) as total_bonus_added_in_range - - from {$table_prefeix}salaries - where is_trash = 0 - group by salary_emp_id - ) as salaries on salary_emp_id = emp_id - left join( select - payment_items_employee, - sum( case when payment_items_type = 'Salary' then payment_items_amount end ) as total_salary_paid, - sum( case when payment_items_type = 'Overtime' then payment_items_amount end ) as total_overtime_paid, - sum( case when payment_items_type = 'Bonus' then payment_items_amount end ) as total_bonus_paid, - sum( case when payment_items_type = 'Salary' and payment_items_date between '{$dateRange[0]}' and '{$dateRange[1]}' then payment_items_amount end ) as total_salary_paid_in_range, - sum( case when payment_items_type = 'Overtime' and payment_items_date between '{$dateRange[0]}' and '{$dateRange[1]}' then payment_items_amount end ) as total_overtime_paid_in_range, - sum( case when payment_items_type = 'Bonus' and payment_items_date between '{$dateRange[0]}' and '{$dateRange[1]}' then payment_items_amount end ) as total_bonus_paid_in_range - from {$table_prefeix}payment_items - where is_trash = 0 - group by payment_items_employee - ) as payments on payment_items_employee = emp_id - left join( select - loan_installment_provider, - sum(loan_installment_paying_amount) as total_loan_adjustment - from {$table_prefeix}loan_installment where is_trash = 0 - group by loan_installment_provider - ) as loan_installment on loan_installment_provider = emp_id - where employee.is_trash = 0 $departmentFilter $empTypeFilter and ( emp_firstname like '{$search}%' or emp_PIN = '{$search}') - - order by {$columns[$requestData['order'][0]['column']]} {$requestData['order'][0]['dir']} - LIMIT {$requestData['start']}, {$requestData['length']} - " - ); - - $totalFilteredRecords = $getData ? $getData["count"] : 0; - - - $allData = []; - // Check if there have more then zero data - if($getData) { - - foreach($getData['data'] as $key => $value) { - - - $total_salary_due = ( $value["emp_opening_salary"] + $value["total_salary_added"] ) - ( $value["total_salary_paid"] + $value["total_loan_adjustment"] ); - $total_overtime_due = ( $value["emp_opening_overtime"] + $value["total_overtime_added"] ) - $value["total_overtime_paid"]; - $total_bonus_due = ( $value["emp_opening_bonus"] + $value["total_bonus_added"] ) - $value["total_bonus_paid"]; - $total_wage_due = $total_salary_due + $total_overtime_due + $total_bonus_due; - - $allNestedData = []; - $allNestedData[] = ""; - $allNestedData[] = $value["emp_firstname"] . ' ' . $value["emp_lastname"] . ' (' . $value["emp_PIN"] . ')'; - $allNestedData[] = $value["dep_name"]; - $allNestedData[] = $value["emp_type"]; - $allNestedData[] = $value["total_salary_added_in_range"]; - $allNestedData[] = $value["total_overtime_added_in_range"]; - $allNestedData[] = $value["total_bonus_added_in_range"]; - $allNestedData[] = $value["total_salary_added_in_range"] + $value["total_overtime_added_in_range"] + $value["total_bonus_added_in_range"]; - - $allNestedData[] = $value["total_salary_paid_in_range"]; - $allNestedData[] = $value["total_overtime_paid_in_range"]; - $allNestedData[] = $value["total_bonus_paid_in_range"]; - $allNestedData[] = $value["total_salary_paid_in_range"] + $value["total_overtime_paid_in_range"] + $value["total_bonus_paid_in_range"]; - - $allNestedData[] = $value["emp_opening_salary"]; - $allNestedData[] = $value["emp_opening_overtime"]; - $allNestedData[] = $value["emp_opening_bonus"]; - $allNestedData[] = $value["emp_opening_salary"] + $value["emp_opening_overtime"] + $value["emp_opening_bonus"]; - - $allNestedData[] = $total_salary_due; - $allNestedData[] = $total_overtime_due; - $allNestedData[] = $total_bonus_due; - $allNestedData[] = $value["total_loan_adjustment"]; - $allNestedData[] = $total_wage_due; - - $allData[] = $allNestedData; - } - } - - - $jsonData = array ( - "draw" => intval( $requestData['draw'] ), - "recordsTotal" => intval( $totalRecords ), - "recordsFiltered" => intval( $totalFilteredRecords ), - "data" => $allData - ); - - // Encode in Json Formate - echo json_encode($jsonData); - -} - - - -/*************************** Expired Product Report ***********************/ -if(isset($_GET['page']) and $_GET['page'] == "expiredProductList") { - - $requestData = $_REQUEST; - $getData = []; - - // List of all columns name - $columns = array( - "", - "product_name", - "expired_qty", - "batch_number", - "expiry_date" - - ); - - // Count Total recrods - $totalFilteredRecords = $totalRecords = easySelectD( - "SELECT count(*) as totalRow FROM product_base_stock where batch_expiry_date < curdate() " - )["data"][0]["totalRow"]; - - if($requestData['length'] == -1) { - $requestData['length'] = $totalRecords; - } - - if(!empty($requestData["search"]["value"]) ) { // get data with search - - - $getData = easySelectD(" - SELECT - product_name, - round(base_stock_in / base_qty, 2) as expired_qty, - batch_number, - pbs.batch_expiry_date as expiry_date - FROM product_base_stock as pbs - left join {$table_prefeix}products as product on product.product_id = pbs.product_id - left join {$table_prefeix}product_batches as product_batches on product_batches.batch_id = pbs.batch_id - WHERE pbs.batch_expiry_date < curdate() and base_stock_in > 0 and ( - product_name like '{$requestData["search"]["value"]}%' - or batch_number like '{$requestData["search"]["value"]}%' - ) - order by {$columns[$requestData['order'][0]['column']]} {$requestData['order'][0]['dir']} - limit {$requestData['start']},{$requestData['length']} - "); - - - $totalFilteredRecords = $getData ? $getData["count"] : 0; - - } else { // Get data withouth search - - $getData = easySelectD(" - SELECT - product_name, - round(base_stock_in / base_qty, 2) as expired_qty, - batch_number, - warehouse_name, - pbs.batch_expiry_date as expiry_date - FROM product_base_stock as pbs - left join {$table_prefeix}products as product on product.product_id = pbs.product_id - left join {$table_prefeix}product_batches as product_batches on product_batches.batch_id = pbs.batch_id - left join {$table_prefeix}warehouses on warehouse_id = warehouse - WHERE pbs.batch_expiry_date < curdate() - order by {$columns[$requestData['order'][0]['column']]} {$requestData['order'][0]['dir']} - limit {$requestData['start']},{$requestData['length']} - "); - - } - - $allData = []; - // Check if there have more then zero data - if($getData) { - - foreach($getData['data'] as $key => $value) { - $allNestedData = []; - $allNestedData[] = ""; - - $allNestedData[] = $value["product_name"]; - $allNestedData[] = $value["warehouse_name"]; - $allNestedData[] = $value["expired_qty"]; - $allNestedData[] = $value["batch_number"]; - $allNestedData[] = $value["expiry_date"]; - - $allData[] = $allNestedData; - } - } - - - $jsonData = array ( - "draw" => intval( $requestData['draw'] ), - "recordsTotal" => intval( $totalRecords ), - "recordsFiltered" => intval( $totalFilteredRecords ), - "data" => $allData - ); - - // Encode in Json Formate - echo json_encode($jsonData); - -} - - - - -/*************************** locationWiseSalesReport ***********************/ -if(isset($_GET['page']) and $_GET['page'] == "locationWiseSalesReport") { - - $requestData = $_REQUEST; - $getData = []; - - // Count Total recrods - $totalFilteredRecords = $totalRecords = 0; - $allData = []; - - if( isset($_GET["pid"]) ) { - - - $getData = easySelectA(array( - "table" => "product_stock as product_stock", - "fields" => "customer_name, sum(stock_item_qty) as total_item_qty, district_name", - "join" => array( - "left join {$table_prefeix}sales on sales_id = stock_sales_id", - "left join {$table_prefeix}customers on customer_id = sales_customer_id", - "left join {$table_prefeix}districts on district_id = customer_district" - ), - "where" => array( - "product_stock.stock_type = 'sale' and product_stock.is_trash = 0 and customer_district" => $_GET["location"], - " and stock_product_id" => $_GET["pid"] - ), - "groupby" => "sales_customer_id" - - )); - - $totalFilteredRecords = $totalRecords = $getData !== false ? $getData["count"] : 0; - - // Check if there have more then zero data - if(isset($getData['count']) and $getData['count'] > 0) { - - foreach($getData['data'] as $key => $value) { - - $allNestedData = []; - $allNestedData[] = ""; - $allNestedData[] = $value["customer_name"]; - $allNestedData[] = $value["district_name"]; - $allNestedData[] = $value["total_item_qty"]; - - $allData[] = $allNestedData; - } - } - - } - - - - $jsonData = array ( - "draw" => intval( $requestData['draw'] ), - "recordsTotal" => intval( $totalRecords ), - "recordsFiltered" => intval( $totalFilteredRecords ), - "data" => $allData - ); - - // Encode in Json Formate - echo json_encode($jsonData); - -} - - -/*************************** Product Ledger ***********************/ -if(isset($_GET['page']) and $_GET['page'] == "productLedger") { - - $requestData = $_REQUEST; - $getData = []; - - // Count Total recrods - $totalFilteredRecords = $totalRecords = 0; - $allData = []; - - if( isset($_GET["pid"]) ) { - - $pid = safe_input($_GET["pid"]); - $wid = safe_input($_GET["wid"]); - - $warehouse_filter = ""; - if( !empty($wid) ) { - $warehouse_filter = " AND stock_warehouse_id = '{$wid}'"; - } - - easySelectD("SELECT @balance := 0;"); - - $getData = easySelectD(" - select entry_date, record_id, reference, record_user_id, reference_link, description, stock_in, stock_out, @balance := ( @balance + stock_in ) - stock_out as balance, emp_firstname, emp_lastname from - ( - SELECT - 1 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - concat('STOCK/ENTRY/', stock_se_id) as reference, - stock_se_id as record_id, - stock_created_by as record_user_id, - '/xhr/?module=stock-management&page=viewStockEntryProduct&id=' as reference_link, - combine_description('Initial Stock Entry', se_note) as description, - stock_item_qty as stock_in, - 0 as stock_out - FROM {$table_prefeix}product_stock as initial - LEFT JOIN {$table_prefeix}stock_entries on se_id = stock_se_id - WHERE initial.is_trash = 0 - AND initial.stock_type = 'initial' - AND initial.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - UNION ALL - SELECT - 2 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - if(purchase_reference is null or purchase_reference = '', concat('Purchase/', stock_purchase_id), purchase_reference ) as reference, - stock_purchase_id as record_id, - stock_created_by as record_user_id, - '/xhr/?module=stock-management&page=viewPurchasedProduct&id=' as reference_link, - combine_description('Purchase', purchase_note) as description, - stock_item_qty as stock_in, - 0 as stock_out - FROM {$table_prefeix}product_stock as purchase - LEFT JOIN {$table_prefeix}purchases on purchase_id = stock_purchase_id - WHERE purchase.is_trash = 0 - AND purchase.stock_type = 'purchase' - AND purchase.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - UNION ALL - SELECT - 3 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - if(purchase_reference is null or purchase_reference = '', concat('Purchase/', stock_purchase_id), purchase_reference ) as reference, - stock_purchase_id as record_id, - stock_created_by as record_user_id, - '/xhr/?module=stock-management&page=viewPurchasedProduct&id=' as reference_link, - combine_description('Purchase Return', purchase_note) as description, - 0 as stock_in, - stock_item_qty as stock_out - FROM {$table_prefeix}product_stock as purchase_return - LEFT JOIN {$table_prefeix}purchases on purchase_id = stock_purchase_id - WHERE purchase_return.is_trash = 0 - AND purchase_return.stock_type = 'purchase-return' - AND purchase_return.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - UNION ALL - SELECT - 4 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - sales_reference as reference, - stock_sales_id as record_id, - stock_created_by as record_user_id, - '/xhr/?module=reports&page=showInvoiceProducts&id=' as reference_link, - combine_description('Sale', sales_note) as description, - 0 as stock_in, - stock_item_qty as stock_out - FROM {$table_prefeix}product_stock as sales - LEFT JOIN {$table_prefeix}sales on sales_id = stock_sales_id - WHERE sales.is_trash = 0 - AND sales.stock_type = 'sale' - AND sales.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - UNION ALL - SELECT - 5 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - sales_reference as reference, - stock_sales_id as record_id, - stock_created_by as record_user_id, - '/xhr/?module=reports&page=showInvoiceProducts&id=' as reference_link, - combine_description('Wastage Product Sale', sales_note) as description, - 0 as stock_in, - stock_item_qty as stock_out - FROM {$table_prefeix}product_stock as wastage_sale - LEFT JOIN {$table_prefeix}sales on sales_id = stock_sales_id - WHERE wastage_sale.is_trash = 0 - AND wastage_sale.stock_type = 'wastage-sale' - AND wastage_sale.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - UNION ALL - SELECT - 6 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - sales_reference as reference, - stock_sales_id as record_id, - stock_created_by as record_user_id, - '/xhr/?module=reports&page=showInvoiceProducts&id=' as reference_link, - combine_description('Sale Return', sales_note) as description, - stock_item_qty as stock_in, - 0 as stock_out - FROM {$table_prefeix}product_stock as sale_return - LEFT JOIN {$table_prefeix}sales on sales_id = stock_sales_id - WHERE sale_return.is_trash = 0 - AND sale_return.stock_type = 'sale-return' - AND sale_return.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - UNION ALL - SELECT - 7 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - if(stock_transfer_reference is null or stock_transfer_reference = '', concat('Transfer/', stock_transfer_in.stock_transfer_id), stock_transfer_reference ) as reference, - stock_transfer_in.stock_transfer_id as record_id, - stock_created_by as record_user_id, - '/xhr/?module=stock-management&page=viewTransferedProduct&id=' as reference_link, - concat('Stock Transfer in from ', warehouse_name) as description, - stock_item_qty as stock_in, - 0 as stock_out - FROM {$table_prefeix}product_stock as stock_transfer_in - LEFT JOIN {$table_prefeix}stock_transfer as stock_transfer on stock_transfer.stock_transfer_id = stock_transfer_in.stock_transfer_id - LEFT JOIN {$table_prefeix}warehouses on warehouse_id = stock_transfer_from_warehouse - WHERE stock_transfer_in.is_trash = 0 - AND stock_transfer_in.stock_type = 'transfer-in' - AND stock_transfer_in.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - UNION ALL - SELECT - 8 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - if(stock_transfer_reference is null or stock_transfer_reference = '', concat('Transfer/', stock_transfer_out.stock_transfer_id), stock_transfer_reference ) as reference, - stock_transfer_out.stock_transfer_id as record_id, - stock_created_by as record_user_id, - '/xhr/?module=stock-management&page=viewTransferedProduct&id=' as reference_link, - concat('Stock Transfer out to ', warehouse_name) as description, - 0 as stock_in, - stock_item_qty as stock_out - FROM {$table_prefeix}product_stock as stock_transfer_out - LEFT JOIN {$table_prefeix}stock_transfer as stock_transfer on stock_transfer.stock_transfer_id = stock_transfer_out.stock_transfer_id - LEFT JOIN {$table_prefeix}warehouses on warehouse_id = stock_transfer_to_warehouse - WHERE stock_transfer_out.is_trash = 0 - AND stock_transfer_out.stock_type = 'transfer-out' - AND stock_transfer_out.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - UNION ALL - SELECT - 9 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - concat('Specimen/', stock_sc_id) as reference, - stock_sc_id as record_id, - stock_created_by as record_user_id, - '/invoice-print/?autoPrint=false&invoiceType=scpecimenCopy&id=' as reference_link, - 'Spcimen Copy' as description, - 0 as stock_in, - stock_item_qty as stock_out - FROM {$table_prefeix}product_stock as spcimen_copy - LEFT JOIN {$table_prefeix}specimen_copies on sc_id = stock_sc_id - WHERE spcimen_copy.is_trash = 0 - AND spcimen_copy.stock_type = 'specimen-copy' - AND spcimen_copy.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - UNION ALL - SELECT - 10 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - concat('Specimen/', stock_sc_id) as reference, - stock_sc_id as record_id, - stock_created_by as record_user_id, - '/invoice-print/?autoPrint=false&invoiceType=scpecimenCopy&id=' as reference_link, - 'Spcimen Copy' as description, - 0 as stock_in, - stock_item_qty as stock_out - FROM {$table_prefeix}product_stock as spcimen_copy_return - LEFT JOIN {$table_prefeix}specimen_copies on sc_id = stock_sc_id - WHERE spcimen_copy_return.is_trash = 0 - AND spcimen_copy_return.stock_type = 'specimen-copy-return' - AND spcimen_copy_return.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - UNION ALL - SELECT - 11 as sortby, - concat(stock_entry_date, ' ', DATE_FORMAT(stock_item_add_on, '%H:%i:%s') ) as entry_date, - concat('STOCK/ENTRY/', stock_se_id) as reference, - stock_se_id as record_id, - stock_created_by as record_user_id, - '/xhr/?module=stock-management&page=viewStockEntryProduct&id=' as reference_link, - combine_description('Adjustment', se_note) as description, - if(stock_item_qty < 0, 0, stock_item_qty) as stock_in, - if(stock_item_qty < 0, abs(stock_item_qty), 0) as stock_out - FROM {$table_prefeix}product_stock as initial - LEFT JOIN {$table_prefeix}stock_entries on se_id = stock_se_id - WHERE initial.is_trash = 0 - AND initial.stock_type = 'adjustment' - AND initial.stock_product_id = '{$pid}' - {$warehouse_filter} - GROUP BY stock_id - - - ) as get_data - LEFT JOIN {$table_prefeix}users as user on user.user_id = get_data.record_user_id - LEFT JOIN {$table_prefeix}employees on emp_id = user_emp_id - order by entry_date, sortby ASC - "); - - - - // ('initial', 'sale-production', 'sale-processing', 'sale', 'sale-order', 'wastage-sale', 'sale-return', 'purchase', 'purchase-order', - // 'purchase-return', 'transfer-in', 'transfer-out', 'specimen-copy', 'specimen-copy-return', 'undeclared') default 'undeclared', - - - //print_r($getData); - - $totalFilteredRecords = $totalRecords = $getData !== false ? $getData["count"] : 0; - - // Check if there have more then zero data - if(isset($getData['count']) and $getData['count'] > 0) { - - foreach($getData['data'] as $key => $value) { - - //, record_id, reference, reference_link, description, stock_in, stock_out, @balance := ( @balance + stock_in ) - stock_out as balance from - - $allNestedData = []; - $allNestedData[] = ""; - $allNestedData[] = $value["entry_date"]; - $allNestedData[] = "{$value['reference']}"; - $allNestedData[] = $value["description"] . " by- {$value["emp_firstname"]} {$value["emp_lastname"]}"; - $allNestedData[] = $value["stock_in"]; - $allNestedData[] = $value["stock_out"]; - $allNestedData[] = $value["balance"]; - - $allData[] = $allNestedData; - } - } - - } - - - - $jsonData = array ( - "draw" => intval( $requestData['draw'] ), - "recordsTotal" => intval( $totalRecords ), - "recordsFiltered" => intval( $totalFilteredRecords ), - "data" => $allData - ); - - // Encode in Json Formate - echo json_encode($jsonData); -} - - - -?> \ No newline at end of file diff --git a/module/reports/expense-report/expense-report-non-cat.php b/module/reports/expense-report/expense-report-non-cat.php index afcd35e..e9d5760 100644 --- a/module/reports/expense-report/expense-report-non-cat.php +++ b/module/reports/expense-report/expense-report-non-cat.php @@ -11,7 +11,7 @@
@@ -19,7 +19,7 @@
-

()

+

()

@@ -61,6 +61,6 @@ diff --git a/module/reports/expense-report/expense-report-single.php b/module/reports/expense-report/expense-report-single.php index 5b05f38..530bdb3 100644 --- a/module/reports/expense-report/expense-report-single.php +++ b/module/reports/expense-report/expense-report-single.php @@ -17,7 +17,7 @@
@@ -25,7 +25,7 @@
-

()

+

()

@@ -65,6 +65,6 @@ diff --git a/module/reports/sales-report.php b/module/reports/sales-report.php index 67c298a..1d5f019 100644 --- a/module/reports/sales-report.php +++ b/module/reports/sales-report.php @@ -9,7 +9,7 @@