ria/app/Models/TrpProductionModel.php
2025-02-15 18:02:36 +05:30

272 lines
10 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 = ['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
// dd($this->db->getLastQuery());
// Convert the array of material codes to a comma-separated string
// $materialCodesString = "'" . implode("','", $materialCodes) . "'";
// dd($materialCodes);
// 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',
'tpmd.workingPersonEngineers',
'tpmd.workingPersonSupervisiors',
'tpmd.workingPersonOperators',
'tpmd.rollerDrivers',
'tpmd.natureOfMaintenance',
'tpmd.location',
'tpmd.description',
'tpd.gasReceiptBg',
'tpd.gasReceiptPg',
'tpd.physicalGasConsumption',
'tpd.trpPlusDrierGasConsumption',
'tpd.trpPhysicalGasPerTon',
'tpd.panelGasConsumption',
'tpd.panelGasPerTon',
'tpd.edRunningHours',
'tpd.edProduction',
'tpd.edUsage',
'tpd.trpProduction',
'tpd.trpProductionPerHour',
'tpd.waterReceipt',
'tpd.waterConsumption',
'tpd.ebReading',
'tpd.ebReadingPerUnitTon',
'tpwd.msSeperation',
'tpwd.edWaste',
'tpwd.coolerBags',
'tpwd.edPlus20Waste',
'tpwd.cycloneWaste',
// Aggregated gas consumption
'IFNULL(tcmd.totalGasConsumption, 0) AS coatingGasConsumption',
'IFNULL(tdmd.totalGasConsumption, 0) AS drierGasConsumption',
'tsu.total_kgs AS coating' ,
'tigrdot.*',
'invItems.*'
]);
// 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 >=', $startDate)
->where('invItems.item_date_added <=', $endDate)
->get()
->getResultArray();
$crsClientList = array_column($crsClientList, 'client_name');
// Initialize an empty array for dynamic SQL conditions
$caseStatements = [];
// Loop through the client list and build dynamic SUM(CASE WHEN...)
foreach ($crsClientList as $client) {
// Escape column name (remove spaces and special characters)
$safeClient = str_replace(' ', '_', $client);
// Add the condition to the array
$caseStatements[] = "SUM(CASE WHEN clients.client_name = " . $this->db->escape($client) . " THEN invItems.item_quantity ELSE 0 END) AS `$safeClient`";
}
// Convert array to a comma-separated string
$caseSQL = implode(', ', $caseStatements);
$subquery3 = $this->db->table('ip_invoice_items invItems')
->select([
'invItems.item_date_added',
$caseSQL
])
->join('ip_invoices inv', 'inv.invoice_id = invItems.invoice_id', 'left')
->join('ip_clients clients', 'clients.client_id = inv.client_id', 'left')
->whereIn('invItems.item_product_id', [81, 93])
->where('invItems.item_date_added >=', $startDate)
->where('invItems.item_date_added <=', $endDate)
->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'];
// Subquery: Waste Core Sand Suppliers
$subquery4 = $this->db->table('t_igr_details tigrd')
->select([
'DATE(tigrd.CreatedDate) AS CreatedDate', // Convert CreatedDate to DATE format
"SUM(CASE WHEN ts.SupplierName = 'Ashok leyland limited foundry divn-SPU' THEN tigrd.QuantityAsPerInvoice ELSE 0 END) AS ALs_wcs",
"SUM(CASE WHEN ts.SupplierName = 'Ashok leyland limited foundry divn-ENU' THEN tigrd.QuantityAsPerInvoice ELSE 0 END) AS ALe_wcs",
"SUM(CASE WHEN ts.SupplierName = 'MADRAS ENGINEERING INDUSTRIES PRIVATE LIMITED' THEN tigrd.QuantityAsPerInvoice ELSE 0 END) AS ME_wcs",
"SUM(CASE WHEN ts.SupplierName = 'SIDDHARTH INDUSTRIES' THEN tigrd.QuantityAsPerInvoice ELSE 0 END) AS SI_wcs",
"SUM(CASE WHEN ts.SupplierName = 'Caparo Engineering India Limited' THEN tigrd.QuantityAsPerInvoice ELSE 0 END) AS caparo_wcs",
"SUM(CASE WHEN ts.SupplierName = 'NEMAK ALUMINIUM CASTING INDIA PVT LTD' THEN tigrd.QuantityAsPerInvoice ELSE 0 END) AS Nemak_wcs",
"SUM(CASE WHEN ts.SupplierName = 'DR Axion India Private Limited' THEN tigrd.QuantityAsPerInvoice ELSE 0 END) AS DR_wcs"
])
->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('tigrd.CreatedDate >=', $startDate)
->where('tigrd.CreatedDate <=', $endDate)
->groupBy('DATE(tigrd.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;
}
}