ria/app/Models/TrpProductionModel.php
2025-03-24 18:03:01 +05:30

299 lines
11 KiB
PHP

<?php
namespace App\Models;
use CodeIgniter\Model;
use Predis\Client;
class TrpProductionModel extends Model
{
protected $table = 't_trpProductionDetails';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = ['id','date', 'gasReceiptBg', 'gasReceiptPg', 'physicalGasConsumption', 'trpPlusDrierGasConsumption',
'trpPhysicalGasPerTon', 'panelGasConsumption','panelGasPerTon','edRunningHours','edProduction','edUsage',
'trpProduction', 'trpProductionPerHour', 'waterReceipt', 'waterConsumption' ,'ebReading',
'ebReadingPerUnitTon'];
protected bool $allowEmptyInserts = false;
protected bool $updateOnlyChanged = true;
protected array $casts = [];
protected array $castHandlers = [];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
public function trpProductionDetails($startDate,$endDate){
$data =[];
// Subquery definition
$subquery = $this->db->table('t_materialmaster')
->select('materialCode')
->where('Category' ,'328')
->get()
->getResultArray();
$materialCodes = array_column($subquery, 'materialCode'); // Extracts 'materialCode' values
// Define your table
$builder = $this->db->table('t_trpProductionMaintenanceDetails tpmd');
// Select required columns
$builder->select(
'tpmd.date,
tpmd.openingTime,
tpmd.closingTime,
tpmd.totalHours,
tpmd.coldStart,
tpmd.breakdownHours,
tpmd.burnerFiringHours,
tpmd.sandFeedingHours,
tpd.gasReceiptBg,
tpd.gasReceiptPg,
tpd.physicalGasConsumption,
IFNULL(tdmd.totalGasConsumption, 0) AS drierGasConsumption,
IFNULL(tcmd.totalGasConsumption, 0) AS coatingGasConsumption,
tpd.trpPlusDrierGasConsumption,
tpd.trpPhysicalGasPerTon,
tpd.panelGasConsumption,
tpd.panelGasPerTon,
tigrdot.* ,
tpd.edRunningHours,
tpd.edProduction,
tpd.edUsage,
tpd.trpProduction,
tpd.trpProductionPerHour,
tsu.total_kgs AS coating,
invItems.* ,
tpd.waterReceipt,
tpd.waterConsumption,
tpd.ebReading,
tpd.ebReadingPerUnitTon,
tpmd.workingPersonEngineers,
tpmd.workingPersonSupervisiors,
tpmd.workingPersonOperators,
tpmd.rollerDrivers,
tpmd.natureOfMaintenance,
tpmd.location,
tpmd.description,
tpwd.msSeperation,
tpwd.edWaste,
tpwd.coolerBags,
tpwd.edPlus20Waste,
tpwd.cycloneWaste'
);
// Join with other tables
$builder->join('t_trpProductionDetails tpd', 'tpd.date = tpmd.date', 'inner');
$builder->join('t_trpProductionWasteDetails tpwd', 'tpwd.date = tpmd.date', 'inner');
$builder->join('t_trp_sand_use tsu', 'tsu.date = tpmd.date', 'left');
// Subquery: Coating Machine Gas Consumption
$subquery1 = $this->db->table('t_coatingmachinedetails')
->select('date, SUM(totalGasConsumption) AS totalGasConsumption')
->groupBy('date')
->getCompiledSelect(false); // Convert Query Builder to raw SQL;
$builder->join("({$subquery1}) tcmd", 'tcmd.date = tpmd.date', 'left');
// Subquery: Drier Machine Gas Consumption
$subquery2 = $this->db->table('t_driermachinedetails')
->select('date, SUM(total_gas_consumption) AS totalGasConsumption')
->groupBy('date')
->getCompiledSelect(false); // Convert Query Builder to raw SQL;
$builder->join("({$subquery2}) tdmd", 'tdmd.date = tpmd.date', 'left');
// Subquery: Core Sand Reclaimed by Clients
$crsClientList = $this->db->table('ip_clients clients')
->distinct()
->select( 'clients.client_name')
->join('ip_invoices inv', 'inv.client_id = clients.client_id')
->join('ip_invoice_items invItems', 'inv.invoice_id = invItems.invoice_id')
->whereIn('invItems.item_product_id', [81, 93])
->where("invItems.item_date_added BETWEEN '$startDate' AND '$endDate'", null, false) // Use BETWEEN for date filtering
->get()
->getResultArray();
$crsClientList = array_column($crsClientList, 'client_name');
// Initialize an empty array for dynamic SQL conditions
$caseStatementsCrs = [];
// Loop through the client list and build dynamic SUM(CASE WHEN...)
foreach ($crsClientList as $index => $client) {
$crsClientList[$index] = $client."_crs";
$clientCrs = $client."_crs";
// Add the condition to the array
$caseStatementsCrs[] = "SUM(CASE WHEN clients.client_name = " . $this->db->escape($client) . " THEN invItems.item_quantity ELSE 0 END) AS `$clientCrs`";
}
// Convert array to a comma-separated string
$caseSQLCrs = implode(', ', $caseStatementsCrs);
// Subquery: Get unique invoice_id with item_date_added and total item_quantity per invoice
$subquery = $this->db->table('ip_invoice_items')
->select('invoice_id, item_date_added, item_quantity')
->whereIn('item_product_id', [81, 93])
->groupBy(['invoice_id'])
->getCompiledSelect(); // Convert to raw SQL for subquery
// Main Query: Use the subquery as invItems and join with ip_invoices and ip_clients
$subquery3 = $this->db->table("($subquery) invItems")
->select(array_merge(['invItems.item_date_added'], $caseStatementsCrs)) // Add dynamic SUM(CASE WHEN..)
->join('ip_invoices inv', 'inv.invoice_id = invItems.invoice_id', 'left')
->join('ip_clients clients', 'clients.client_id = inv.client_id', 'left')
->where("invItems.item_date_added BETWEEN '$startDate' AND '$endDate'", null, false) // Use BETWEEN for date filtering
->groupBy('invItems.item_date_added')
->getCompiledSelect(false); // Convert Query Builder to raw SQL;
$builder->join("({$subquery3}) invItems", 'invItems.item_date_added = tpmd.date', 'left');
$materialCodes = ! empty($materialCodes) ? $materialCodes : ['600374','600422','600434'];
$wcsSupplierList = $this->db->table('t_igr_details tigrd')
->distinct()
->select('ts.SupplierName as supplierName')
->join('t_igr_master tigm', 'tigm.IGRNo = tigrd.IGRNo', 'left')
->join('t_purchaseorder_master tpom', 'tpom.PONO = tigm.PONO', 'left')
->join('t_supplierdetailsn ts', 'tpom.SupplierID = ts.SupplierID', 'left')
->whereIn('tigrd.MaterialCode', $materialCodes)
->where("DATE(tigrd.CreatedDate) BETWEEN '$startDate' AND '$endDate'", null, false) // Use BETWEEN for date filtering
->get()
->getResultArray();
$wcsSupplierList = array_column($wcsSupplierList, 'supplierName');
// Initialize an empty array for dynamic SQL conditions
$caseStatementsWcs = [];
// Loop through the client list and build dynamic SUM(CASE WHEN...)
foreach ($wcsSupplierList as $index => $supplier) {
$wcsSupplierList[$index] = $supplier."_wcs";
$supplierWcs = $supplier."_wcs";
// Add the condition to the array
$caseStatementsWcs[] = "SUM(CASE WHEN ts.SupplierName = " . $this->db->escape($supplier) . " THEN tigrd.QuantityAsPerInvoice ELSE 0 END) AS `$supplierWcs` ";
}
// Convert array to a comma-separated string
$caseSQLWcs = implode(', ', $caseStatementsWcs);
// Subquery: Waste Core Sand Suppliers
$subquery4 = $this->db->table('t_igr_details tigrd')
->select([
'DATE(tigrd.CreatedDate) AS CreatedDate', // Convert CreatedDate to DATE format
$caseSQLWcs
])
->join('t_igr_master tigm', 'tigm.IGRNo = tigrd.IGRNo', 'left')
->join('t_purchaseorder_master tpom', 'tpom.PONO = tigm.PONO', 'left')
->join('t_supplierdetailsn ts', 'tpom.SupplierID = ts.SupplierID', 'left')
->whereIn('tigrd.MaterialCode', $materialCodes)
->where("DATE(tigrd.CreatedDate) BETWEEN '$startDate' AND '$endDate'", null, false) // Use BETWEEN for date filtering
->groupBy('DATE(tigm.CreatedDate)')
->getCompiledSelect(false); // Convert Query Builder to raw SQL
// Correcting the JOIN condition
$builder->join("($subquery4) tigrdot", "CAST(tigrdot.CreatedDate AS DATE) = CAST(tpmd.date AS DATE)", 'left');
// Where conditions for main query
$builder->where('tpmd.date >=', $startDate);
$builder->where('tpmd.date <=', $endDate);
// Order by date
$builder->orderBy('tpmd.date', 'ASC');
// Execute the query
$query = $builder->get();
$result = $query->getResultArray();
return [$result,$crsClientList,$wcsSupplierList];
}
}