ria/app/Views/stock/bagStockDetails.php
2025-03-27 18:48:26 +05:30

1449 lines
61 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<style type="text/css">
.num {
text-align: right;
}
.fht-table,
.fht-table thead,
.fht-table tfoot,
.fht-table tbody,
.fht-table tr,
.fht-table th,
.fht-table td {
margin: 0;
}
.grab {
cursor: grab; /* Default open-hand cursor */
}
.grab:active {
cursor: grabbing; /* Closed-hand cursor when dragging */
}
.fht-table td {
text-align: center;
}
.fht-table td:hover {
background-color: rgb(170, 222, 167);
color:rgb(2, 2, 2);
transform: scale(1.25); /* Increases size by 25% */
transition: transform 0.5s ease-in-out; /* Smooth scaling effect */
}
.fht-table tr:hover {
background-color: rgb(170, 222, 167);
color:rgb(2, 2, 2);
}
.fht-table {
border: 0 none;
height: auto;
width: auto;
border-collapse: collapse;
border-spacing: 0;
/*table-layout: fixed; Algoritmo de distribucion fijo */
white-space: nowrap;
}
.fht-table th,
.fht-table td {
overflow: hidden;
}
.fht-table-wrapper,
.fht-table-wrapper .fht-thead,
.fht-table-wrapper .fht-tfoot,
.fht-table-wrapper .fht-fixed-column .fht-tbody,
.fht-table-wrapper .fht-fixed-body .fht-tbody,
.fht-table-wrapper .fht-tbody {
overflow: hidden;
position: relative;
}
.fht-table-wrapper .fht-fixed-body .fht-tbody,
.fht-table-wrapper .fht-tbody {
overflow: auto;
}
.fht-table-wrapper .fht-table .fht-cell {
overflow: hidden;
height: 1px;
}
.fht-table-wrapper .fht-fixed-column,
.fht-table-wrapper .fht-fixed-body {
top: 0;
left: 0;
position: absolute;
}
.fht-table-wrapper .fht-fixed-column {
z-index: 1;
}
.fht-fixed-body .fht-thead table {
margin-right: 20px;
border: 0 none;
}
/*For Examples*/
.ContenedorTabla {
height: 500px;
margin: 0 auto;
overflow: auto;
width: auto;
position: relative;
}
.header,
.main {
display: inline-block;
height: auto;
width: 100%;
}
.titulosHeader {
border-bottom: 1px solid #e8bb25;
height: auto;
margin-bottom: 10px;
padding-bottom: 8px;
padding-top: 8px;
width: 100%;
}
._Separador {
background-color: #fff;
height: 12px;
border-left: 1px solid #ccc;
border-right: 1px solid #ccc;
width: 7px;
}
._Separador div {
width: 4px;
}
/*style excel*/
.excel_cell {
border: 1px solid #CCC;
color: #222;
text-align: center;
font-size: 13px;
font-weight: normal;
padding: 4px;
white-space: pre-line;
empty-cells: show;
}
._cell_header {
background-color: #EEE;
}
._cell_Default {
background-color: #FFF;
text-align: left;
}
.excel_cell div {
width: 30px;
height: 20px;
}
.celda_encabezado_general {
background-color: #50bbd9;
border: 1px solid #ccc;
color: #ffffff;
font-weight: bold;
padding: 6px 10px;
text-align: center;
}
.celda_encabezado_total {
background-color:#ffffff !important;
border: 1px solid #ffffff;
color: #ffffff !important;
font-weight: bold;
padding: 6px 10px;
text-align: center;
}
.celda_normal {
/*background-color: #fff;*/
/* <!-- ad9271 into ffffff brown-light to green-light --> */
text-align: center;
border: 1px solid #ccc;
padding: 10px 6px;
}
/* Make entire thead sticky */
.fht-table thead {
position: sticky;
top: 0;
z-index: 20; /* Ensure the entire header stays above table rows */
background-color: #50bbd9; /* Header background color */
}
.dropdown-menu {
z-index :25 ;
}
/* Ensure each <th> in thead stays sticky */
.fht-table thead th {
position: sticky;
top: 0;
z-index: 11; /* Higher than table rows but lower than first column */
background-color: #50bbd9; /* Green background */
color: #ffffff;
border: 1px solid #ddd;
padding: 10px;
white-space: normal; /* Allows text to wrap */
word-wrap: break-word; /* Breaks long words if needed */
text-align: center; /* Centers text for better alignment */
}
/* Sticky First Column */
.fht-table th:nth-child(1),
.fht-table td:nth-child(1) {
position: sticky;
left: 0;
background-color: #50bbd9;
z-index: 15; /* Ensures it stays above other cells */
border-right: 2px solid #ddd;
color: #ffffff;
}
/* Table Wrapper for Scrolling */
.table-responsive {
overflow-x: auto;
overflow-y: auto;
max-height: 450px;
max-width: 100%;
position: relative;
}
td{
min-width: 100px;
max-width: 100px;
}
/* .fht-table td[contenteditable="true"] {
background-color: lightyellow;
color:rgb(13, 7, 7);
} */
tfoot tr {
background-color:rgb(235, 236, 203);
}
body[data-layout-mode = horizontal] .container-fluid{
max-width: 100%;
}
.card-body{
padding-top : 0;
padding-bottom: 0;
}
.card{ margin-bottom: 5px;}
</style>
<?php
$date = DateTime::createFromFormat('M-Y', $month);
$startDate = $date->modify('first day of this month')->format('Y-m-d');
$endDate = $date->modify('last day of this month')->format('Y-m-d');
$datesInMonth = [];
$period = new DatePeriod(
new DateTime($startDate),
new DateInterval('P1D'),
(new DateTime($endDate))->modify('+1 day')
);
foreach ($period as $day) {
$datesInMonth[] = $day->format('Y-m-d');
}
?>
<div class="content-page">
<div class="content">
<!-- Start Content-->
<div class="container-fluid">
<!-- start page title -->
<div>
<div class="row">
<div class="col-6">
<div class="page-title-box page-title-box-alt">
<div class="page-title-right">
<ol class="breadcrumb m-0">
<li class="breadcrumb-item"><a href="javascript: void(0);">Stocks</a></li>
<li class="breadcrumb-item active">
<h4 class="page-title">Bag Stock Details </h4>
</li>
</ol>
</div>
</div>
</div>
<div class="col-6 text-right">
<!-- Right-aligned buttons or links can be added here -->
</div>
</div>
<div class="row">
<div class="col-12">
<div class="card" id="fullscreenDiv">
<div class="modal fade" id="bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-md" >
<div class="modal-content" >
<div class="modal-header">
<h4 class="modal-title" id="myLargeModalLabel">Navigation Options</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="row">
<!-- bag Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="bagDropdown">Select Bag</label>
<select id="bagDropdown" class="form-control select2">
<option value="">Select Bag</option>
<?php foreach($bagMaterials as $bagMaterial): ?>
<option value=" <?= $bagMaterial['MaterialName']?>">
<?= $bagMaterial['MaterialName']?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<!-- Date Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="dateDropdown">Select Date</label>
<select id="dateDropdown" class="form-control select2">
<?php foreach($datesInMonth as $selectDate): ?>
<?php $selectDate=DateTime::createFromFormat('Y-m-d', $selectDate)->format('d-m-Y'); ?>
<option value="<?=$selectDate?>"><?=$selectDate?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
<button class="btn btn-primary float-right" onclick="navigateToBag()">Navigate</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div class="card-body">
<form id="changeMonthForm" action="<?= base_url('bagStockDetails'); ?>" method="post">
<div class="row">
<div class="col-2">
<input type="text" name="month" id="month" value="<?php echo "$month" ?>"
class="form-control mt-2"
style="z-index:30;" readonly>
</div>
<div class="col-10 text-right d-flex" style="justify-content: end;" >
<input type="text" id="searchInput" placeholder="Search..."
class="mt-2"
style="padding: 8px;margin-bottom: 10px;width: 250px;border: 1px solid #ccc;
border-radius: 5px;margin-right:15px;">
<?php
if($month == date('M-Y') ){
?>
<i class="fa fa-cog btn-lg mt-2"
style="font-size: x-large; cursor:pointer;"
title = "Customize"
data-target="#customizeModalId"
data-toggle="modal">
</i>
<?php
}
?>
<i class="fa fa-rocket btn-lg mt-2"
title="Navigation"
data-toggle="modal"
data-target="#bs-example-modal-lg"
style="font-size: x-large; cursor:pointer;">
</i>
<i class="fa fa-download btn-lg mt-2"
title="Excel Download"
style="font-size: x-large; cursor:pointer;"
id="bagStockExport">
</i>
<i class="fe-maximize noti-icon btn-lg mt-2"
title="Full Screen"
style="font-size: x-large; cursor:pointer;"
onclick="toggleDivFullscreen()" >
</i>
<i class="fas fa-save btn-lg mt-2"
title="Save"
style="font-size: x-large; cursor:pointer;"
id="saveId" >
</i>
</div>
</div>
</form>
<form action="<?= base_url('bagStockDetails'); ?>" method="post">
<!-- modal placed here for submission of form -->
<!---------------------------------------
this modal is used to customize table header
1)list table header order
2)choose which material/machines you want
------------------------------------------------------------>
<div>
<div class="modal fade" id="customizeModalId" tabindex="-1" role="dialog" aria-labelledby="customizeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-md">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="customizeModalLabel">Customize</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="row">
<!-- Dropdown to add back removed items -->
<div class="col">
<div class="form-group">
<label for="customizeHeader"> Add For This Month </label>
<select id="customizeHeader" class="form-control" onchange="addBackToList()">
<option value="">Select</option>
<?php
foreach($activeBagMaterials as $index => $activeBagMaterial){ ?>
<option value="<?=$activeBagMaterial['MaterialCode']?>">
<?=$activeBagMaterial['MaterialCode']?> - <?=$activeBagMaterial['MaterialName']?>
</option>
<?php
}
?>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col">
<h5>List of Selected Items</h5>
<div id="selectedItemsContainer">
<ul id="sortableList">
<?php foreach ($bagMaterials as $bagMaterial): ?>
<div class="sortable-item" draggable="true" id="<?=$bagMaterial['MaterialCode']?>_container">
<input type = "checkbox"
id = "<?=$bagMaterial['MaterialCode']?>_checkboxId"
name = "customisedMaterialCodes[]"
value = "<?= $bagMaterial['MaterialCode'] ?>"
onclick = "removeSelectedMaterial(this)"
checked>
<label class="grab" for="<?= $bagMaterial['MaterialCode'] ?>_checkboxId">
<?= $bagMaterial['MaterialCode'] ?> - <?= $bagMaterial['MaterialName']; ?>
</label>
<br>
</div>
<?php endforeach; ?>
</ul>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary float-right"> Apply </button>
</div>
</div>
</div>
</div>
</div>
<!-- hidden fields -->
<input type="hidden" name="month" value="<?php echo "$month" ?>" >
</form>
<div class="table-responsive" id="table-responsive">
<table id="bagStockDetailsTableId" class="fht-table">
<thead class="celda_encabezado_general bag-table-head" style="padding: 10px;">
<tr>
<th class="celda_encabezado_general" colspan="1">Material </th>
<?php foreach($bagMaterials as $bagMaterial){ ?>
<!-- this will loop till materials present -->
<th class="celda_encabezado_general" colspan="4">
<?= $bagMaterial['MaterialName']?>
</th>
<?php } ?>
</tr>
<tr>
<th class="celda_encabezado_general" colspan="1"> Customer </th>
<?php foreach($bagMaterials as $bagMaterial){ ?>
<!-- this will loop till materials present -->
<th class="celda_encabezado_general" colspan="4"
data-materialCode="<?=$bagMaterial['MaterialCode']?>"
oninput="customerChange(this)" contenteditable="true">
<?= $bagMaterial['customers']?>
</th>
</th>
<?php } ?>
</tr>
<tr>
<th class="celda_encabezado_general" colspan="1">Date </th>
<?php foreach($bagMaterials as $bagMaterial){ ?>
<!-- this will loop till materials present -->
<th class="celda_encabezado_general" style="display:none">Date</th>
<th class="celda_encabezado_general" style="display:none"> Material</th>
<th class="celda_encabezado_general" style="display:none"> Customer</th>
<th class="celda_encabezado_general">Opening Stock</th>
<th class="celda_encabezado_general">Receipt</th>
<th class="celda_encabezado_general">Used</th>
<th class="celda_encabezado_general">Balance Stock</th>
<?php } ?>
</tr>
</thead>
<tbody style="background-color: #fff;" >
<?php if(!empty($groupedBagStockDetails))
{
$summary = [] ;
foreach($groupedBagStockDetails as $groupedBagStockDetailsIndex => $bagStockDetails){
?>
<tr
<?php
$currentDate = date('d-m-Y');
$dateInMonthDmYFormat= DateTime::createFromFormat('Y-m-d', $bagStockDetails[0]['date'])->format('d-m-Y');
if ($dateInMonthDmYFormat === $currentDate) { echo 'style="background: #cef0ad;"';}
?>
>
<?php foreach($bagStockDetails as $bagStockIndex => $bagStock){ ?>
<?php if ($bagStockIndex == 0): ?>
<?php
$startDate = DateTime::createFromFormat('Y-m-d', $bagStock['date'])->format('d-m-Y');
?>
<td class="celda_normal">
<?= $startDate ?>
</td>
<?php endif; ?>
<td style="display:none">
<?= $bagStock['date']?>
</td>
<td style="display:none"
data-id="<?=$bagStock['date']?> <?=$bagStock['materialCode']?>"
class="materialCode" ><?= $bagStock['materialCode']?>
</td>
<td style="display:none" class="celda_normal customer"
data-materialCode="<?=$bagStock['materialCode']?>"
data-id="<?=$bagStock['date']?> <?=$bagStock['materialCode']?>">
<?= $bagStock['customer']?>
</td>
<td class="celda_normal openingStock"
data-id="<?=$bagStock['date']?> <?=$bagStock['materialCode']?>"
<?php if ($groupedBagStockDetailsIndex == 0): ?>
oninput="openingStockChange(this)"
contenteditable="true"
<?php endif; ?>
><?= $bagStock['opening'] ?? " " ?>
</td>
<td class="celda_normal receiptStock"
data-id="<?=$bagStock['date']?> <?=$bagStock['materialCode']?>"
oninput="receiptStockChange(this)"
contenteditable="true"
>
<?= $bagStock['receipt'] ?? " " ?>
</td>
<td class="celda_normal usedStock"
data-id="<?=$bagStock['date']?> <?=$bagStock['materialCode']?>"
oninput="usedStockChange(this)"
contenteditable="true"
>
<?= $bagStock['used'] ?? " " ?>
</td>
<td class="celda_normal balanceStock"
data-id="<?=$bagStock['date']?> <?=$bagStock['materialCode']?>">
<?= $bagStock['balanceStock'] ?? " " ?>
</td>
<?php
//before closing inner loop we just adding the total values insidde it
$materialCode = $bagStock['materialCode']; // Unique identifier
// Initialize the material entry if it doesn't exist
if (!isset($summary[$materialCode])) {
$summary[$materialCode] = [
'opening' => "-" ,
'receipt' => 0 ,
'used' => 0 ,
'balanceStock' => 0 ,
];
}
// Sum values for the material
$summary[$materialCode]['opening'] = "-" ;
$summary[$materialCode]['receipt'] += is_numeric( $bagStock['receipt']) ? $bagStock['receipt'] : 0 ;
$summary[$materialCode]['used'] += is_numeric( $bagStock['used']) ? $bagStock['used'] : 0 ;
$summary[$materialCode]['balanceStock'] = is_numeric( $bagStock['balanceStock']) ? $bagStock['balanceStock'] : 0 ;
} ?>
</tr>
<?php } ?>
<tfoot>
<tr>
<td style="background-color:rgb(189, 9, 6); color:#ffff;">
<b> Total </b>
</td>
<?php foreach($summary as $each){
?>
<td class="celda_normal "><?=$each['opening']?></td>
<td class="celda_normal "><?=$each['receipt']?></td>
<td class="celda_normal "><?=$each['used']?></td>
<td class="celda_normal "><?=$each['balanceStock']?></td>
<?php } ?>
</tr>
</tfoot>
<!-- this else condition work if groupedBagStockDetails is empty and creating new records
with initial values 0 for entire month -->
<?php } else {
// dd($bagMaterials);
// dd($previousMonthBagStockDetails); ?>
<?php foreach($datesInMonth as $datesInMonthIndex => $dateInMonth){ ?>
<tr
<?php
$currentDate = date('d-m-Y');
$dateInMonthDmYFormat=DateTime::createFromFormat('Y-m-d', $dateInMonth)->format('d-m-Y');
if ($dateInMonthDmYFormat === $currentDate) { echo 'style="background: #cef0ad;"';}
?>
>
<?php
foreach($bagMaterials as $bagMaterialIndex => $bagMaterial){ ?>
<!-- this will loop till materials present -->
<?php if ($bagMaterialIndex == 0): ?>
<?php
$startDate =DateTime::createFromFormat('Y-m-d', $dateInMonth)->format('d-m-Y');
?>
<td class="celda_normal">
<?= $startDate ?>
</td>
<?php endif; ?>
<td class="celda_normal" style="display:none">
<?= $dateInMonth?>
</td>
<td class="celda_normal" style="display:none"
data-id="<?=$dateInMonth?> <?=$bagMaterial['MaterialCode']?>">
<?= $bagMaterial['MaterialCode']?>
</td>
<td class="celda_normal customer" style="display:none"
data-materialCode="<?=$bagMaterial['MaterialCode']?>"
data-id="<?=$dateInMonth?> <?=$bagMaterial['MaterialCode']?>">
<?= $bagMaterial['customers']?>
</td>
<td class="celda_normal openingStock"
data-id="<?=$dateInMonth?> <?=$bagMaterial['MaterialCode']?>"
<?php if($datesInMonthIndex == 0){ ?>
oninput="openingStockChange(this)"
contenteditable="true"
<?php }?>
>
<?php
foreach($previousMonthBagStockDetails as $index => $previousMonthBagStockDetail)
{
if($previousMonthBagStockDetail['materialCode'] == $bagMaterial['MaterialCode']){
echo $previousMonthBagStockDetail['balanceStock'] ;
break;
}
}
?>
</td>
<td class="celda_normal receiptStock"
data-id="<?=$dateInMonth?> <?=$bagMaterial['MaterialCode']?>"
oninput="receiptStockChange(this)"
contenteditable="true"> <?= " " ?> </td>
<td class="celda_normal usedStock"
data-id="<?=$dateInMonth?> <?=$bagMaterial['MaterialCode']?>"
oninput="usedStockChange(this)" contenteditable="true"> <?= " " ?> </td>
<td class="celda_normal balanceStock"
data-id="<?=$dateInMonth?> <?=$bagMaterial['MaterialCode']?>"
>
<?php
foreach($previousMonthBagStockDetails as $index => $previousMonthBagStockDetail)
{
if($previousMonthBagStockDetail['materialCode'] == $bagMaterial['MaterialCode']){
echo $previousMonthBagStockDetail['balanceStock'] ;
break;
}
}
?>
</td>
<?php } ?>
</tr>
<?php } ?>
<?php }?>
</tbody>
</table>
</div>
</div>
</div> <!-- End card-body -->
</div> <!-- End card -->
</div> <!-- End col -->
</div> <!-- End row -->
</div>
</div> <!-- End container-fluid -->
</div>
</div>
<div >
<!-- <div class="modal fade" id="bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-md" >
<div class="modal-content" >
<div class="modal-header">
<h4 class="modal-title" id="myLargeModalLabel">Navigation Options</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="row">
<!-- bag Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="bagDropdown">Select Bag</label>
<select id="bagDropdown" class="form-control select2">
<option value="">Select Bag</option>
<?php foreach($bagMaterials as $bagMaterial): ?>
<option value=" <?= $bagMaterial['MaterialName']?>">
<?= $bagMaterial['MaterialName']?>
</option>
<?php endforeach; ?>
</select>
</div>
</div>
<!-- Date Dropdown -->
<div class="col-md-6">
<div class="form-group">
<label for="dateDropdown">Select Date</label>
<select id="dateDropdown" class="form-control select2">
<?php foreach($datesInMonth as $selectDate): ?>
<?php $selectDate=DateTime::createFromFormat('Y-m-d', $selectDate)->format('d-m-Y'); ?>
<option value="<?=$selectDate?>"><?=$selectDate?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
<button class="btn btn-primary float-right" onclick="navigateToBag()">Navigate</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>/.modal -->
</div>
<script>
$(document).ready(function(){
$('.select2').select2();
})
</script>
<script>
function navigateToBag() {
$('.close').click();
const bagDropdown = document.getElementById('bagDropdown');
const dateDropdown = document.getElementById('dateDropdown');
const selectedBag = bagDropdown.value;
const selectedDate = dateDropdown.value;
const table = document.getElementById('bagStockDetailsTableId');
const headerCells = table.querySelectorAll('thead tr:nth-child(1) th');
const rows = table.querySelectorAll('tbody tr');
let targetColumnIndex = -1;
headerCells.forEach((header, index) => {
if (header.innerText.replace(/\s+/g, '') === selectedBag.replace(/\s+/g, '')) {
targetColumnIndex = index;
return;
}
});
if (targetColumnIndex === -1) {
console.log("Bag column not found.");
return;
}
let targetRow = null;
rows.forEach(row => {
const dateCell = row.querySelector('td:first-child');
if (dateCell && dateCell.textContent.trim() === selectedDate) {
targetRow = row;
}
});
if (!targetRow) {
console.log("Date row not found.");
return;
}
console.log(targetColumnIndex);
console.log(targetRow);
targetColumnIndex = targetColumnIndex * 7;
targetRow.cells[targetColumnIndex].scrollIntoView({
behavior: 'smooth',
inline: 'center',
block: 'center'
});
const highlightDuration = 10000;
for (let i = targetColumnIndex-4 ; i <= targetColumnIndex ; i++) {
const cell = targetRow.cells[i];
if (cell) {
cell.style.transition = "background-color 0.5s";
cell.style.backgroundColor = "#df9675";
setTimeout(() => {
cell.style.backgroundColor = "";
}, highlightDuration);
}
}
}
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#saveId').click(function () {
//table to json function
var updateBagStockDetails = tableToJson();
alert('Updation may take a while, And we appreciate your patience..!!');
$('#loader').show();
$.ajax({
data: {
updateBagStockDetails
},
type: "POST",
url: "<?php echo base_url() ?>updateBagStockDetails",
success: function (data) {
if (data) {
$('#loader').hide();
console.log(data);
alert(data);
window.location.reload();
}
},
error: function(xhr, status, error) {
alert("An error occurred while processing the request. Please try again.");
console.error("Error Code:", xhr.status);
console.error("Error Message:", error);
console.error("Response Text:", xhr.responseText);
},
complete: function() {
$('#loader').hide();
}
});
});
});
</script>
<script>
function tableToJson() {
const table = $('#bagStockDetailsTableId');
const rows = [];
//this table to json is customized for bagstock not for all
table.find('tbody tr').each(function() {
const rowCells = $(this).find('td');
const date = rowCells.eq(0).text().trim();
/** we get eight entries against a material so we loop from 1 to 7 and so on
in a single row **/
for (let i = 1; i < rowCells.length; i += 7) {
const rowData = {
date: rowCells.eq(i).text().trim(),
materialCode: rowCells.eq(i+1).text().trim(),
customer: rowCells.eq(i+2).text().trim(),
opening: rowCells.eq(i+3).text().trim(),
receipt: rowCells.eq(i+4).text().trim(),
used: rowCells.eq(i+5).text().trim(),
balanceStock: rowCells.eq(i + 6).text().trim()
};
rows.push(rowData);
}
});
return JSON.stringify(rows, null, 2);
}
</script>
<script>
function openingStockChange(tdElement) {
try{
let dataId = tdElement.getAttribute('data-id');
let [date,materialCode] = tdElement.getAttribute('data-id').split(' ');
let openingStock = validateInput( tdElement.innerText );
let usedStock = validateInput(document.querySelector(`td.usedStock[data-id="${dataId}"]`).innerText);
let receiptStock = validateInput(document.querySelector(`td.receiptStock[data-id="${dataId}"]`).innerText);
let currentBalanceStock = (Number(openingStock) + Number(receiptStock)) - Number(usedStock);
document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock == 0 ? " " : currentBalanceStock;
updateStockValue( date,materialCode,currentBalanceStock )
} catch(error){
console.error("There is an error updating stock ..!!" + error);
}
}
function receiptStockChange(tdElement) {
try{
let dataId = tdElement.getAttribute('data-id');
let [date,materialCode] = tdElement.getAttribute('data-id').split(' ');
let openingStock = validateInput(document.querySelector(`td.openingStock[data-id="${dataId}"]`).innerText);
let receiptStock = validateInput(tdElement.innerText);
let usedStock = validateInput(document.querySelector(`td.usedStock[data-id="${dataId}"]`).innerText);
let currentBalanceStock = (Number(openingStock) + Number(receiptStock)) - Number(usedStock);
document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock == 0 ? " " : currentBalanceStock ;
updateStockValue( date,materialCode,currentBalanceStock )
} catch(error){
console.error("There is an error updating stock ..!!" + error);
}
}
function usedStockChange(tdElement) {
try {
let dataId = tdElement.getAttribute('data-id');
let [date,materialCode] = tdElement.getAttribute('data-id').split(' ');
let openingStock = validateInput(document.querySelector(`td.openingStock[data-id="${dataId}"]`).innerText);
let receiptStock = validateInput(document.querySelector(`td.receiptStock[data-id="${dataId}"]`).innerText);
let usedStock = validateInput(tdElement.innerText);
let currentBalanceStock = ( Number(openingStock) + Number(receiptStock) ) - Number(usedStock);
document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock == 0 ? " " : currentBalanceStock ;
updateStockValue( date,materialCode,currentBalanceStock )
} catch (error) {
console.error("There is an error updating stock ..!!" + error);
}
}
</script>
<script>
function updateStockValue( date, materialCode, currentBalanceStock ){
const table = $('#bagStockDetailsTableId');
const rows = [];
table.find('tbody tr').each(function() {
const rowCells = $(this).find('td');
const otherDate = rowCells.eq(1).text().trim();
if( new Date(otherDate) > new Date(date) ){ //other records present after it
/**this data-id ,openingStock ,used stock , current Balance Stock
is for changing subsequent dates not the earlier one **/
let dataId = `${otherDate} ${materialCode}`;
document.querySelector(`td.openingStock[data-id="${dataId}"]`).innerText = currentBalanceStock == 0 ? " " : currentBalanceStock;
let usedStock = validateInput(document.querySelector(`td.usedStock[data-id="${dataId}"]`).innerText);
let receiptStock = validateInput(document.querySelector(`td.receiptStock[data-id="${dataId}"]`).innerText);
currentBalanceStock = (Number(currentBalanceStock) + Number(receiptStock)) - Number(usedStock);
document.querySelector(`td.balanceStock[data-id="${dataId}"]`).innerText = currentBalanceStock == 0 ? " " : currentBalanceStock;
}
})
}
function customerChange(thElement){
let materialCode = thElement.getAttribute('data-materialCode');
let newCustomerValue = thElement.innerText;
let matchingCustomerData = document.querySelectorAll(`td.customer[data-materialCode="${materialCode}"]`);
matchingCustomerData.forEach((element,index)=>{
element.innerText=newCustomerValue;
})
}
function validateInput(input) {
if ( input == '' || input == ' ' || input == '-' ) {
return 0;
}
if(typeof input === 'string' && input.split('').map(char => char.charCodeAt(0))[0] == 10 ){
return 0 ;
}
// Validate against the regex
const isValid = /^-?\d*\.?\d*$/.test(input);
if (!isValid) {
alert('Invalid input! Please enter a valid number.');
return 0;
}
return input;
}
</script>
<script>
$(document).ready(function(){
function exportTableToExcel(tableID, filename = '') {
let table = document.getElementById(tableID);
let cloneTable = table.cloneNode(true); // Clone the table to modify
// Remove hidden rows
$(cloneTable).find('tr').filter(function () {
return $(this).css('display') === 'none';
}).remove();
// Remove hidden columns
$(cloneTable).find('th, td').each(function () {
if ($(this).css('display') === 'none') {
$(this).remove();
}
});
$(cloneTable).find('tbody tr').each(function() {
let firstTd = $(this).find('td').eq(0); // Get the first column (Date)
// Convert Date Format (Assuming it's in YYYY-MM-DD format)
let originalDate = firstTd.text().trim(); // Get the text value
let parts = originalDate.split('-'); // Split into [YYYY, MM, DD]
if (parts.length === 3) {
let formattedDate = `${parts[2]}-${parts[1]}-${parts[0]}`; // Rearrange to DD-MM-YYYY
firstTd.text(formattedDate); // Update the cell value
}
// Apply left alignment to the date column
firstTd.css("text-align", "left");
});
let ws = XLSX.utils.table_to_sheet(cloneTable); // Convert modified table to sheet
let wb = XLSX.utils.book_new(); // Create a new workbook
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); // Append sheet to workbook
XLSX.writeFile(wb, filename || 'export.xlsx'); // Save the file
}
let tableId = 'bagStockDetailsTableId';
document.getElementById('bagStockExport').addEventListener('click',function(){
exportTableToExcel(tableId,'Bag_Stock_Details<?=$month?>.xlsx');
})
})
</script>
<script>
document.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
let activeElement = document.activeElement;
// Check if the focused element is inside a table
let cell = activeElement.closest("td, th");
let table = activeElement.closest("table");
if (table && cell) {
event.preventDefault(); // Prevent form submission
let columnIndex = cell.cellIndex; // Get the current column index
let currentRow = cell.parentElement; // Get the current row
let nextRow = currentRow.nextElementSibling; // Get the next row
// Move to the same column in the next row if available
if (nextRow) {
let nextCell = nextRow.cells[columnIndex];
if (nextCell) {
nextCell.focus();
}
}
}
}
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function () {
const list = document.getElementById("sortableList");
let draggedItem = null;
function attachDragEvents(item) {
item.setAttribute("draggable", "true");
item.addEventListener("dragstart", (event) => {
draggedItem = event.target;
event.target.classList.add("dragging");
});
item.addEventListener("dragend", (event) => {
event.target.classList.remove("dragging");
});
}
list.addEventListener("dragover", (event) => {
event.preventDefault(); // Allow dropping
const dragging = document.querySelector(".dragging");
const closestItem = getClosestItem(list, event.clientY);
if (closestItem) {
list.insertBefore(dragging, closestItem);
} else {
list.appendChild(dragging);
}
});
function getClosestItem(container, y) {
const items = [...container.querySelectorAll(".sortable-item:not(.dragging)")];
return items.reduce((closest, child) => {
const box = child.getBoundingClientRect();
const offset = y - box.top - box.height / 2;
return offset < 0 && offset > closest.offset
? { offset, element: child }
: closest;
}, { offset: Number.NEGATIVE_INFINITY }).element;
}
// Attach drag events to existing items
document.querySelectorAll(".sortable-item").forEach(attachDragEvents);
window.removeSelectedMaterial = function (checkbox) {
let container = checkbox.closest(".sortable-item");
let materialCode = checkbox.value;
let materialName = container.querySelector("label").innerText;
container.remove();
};
window.addBackToList = function () {
let dropdown = document.getElementById("customizeHeader");
let selectedOption = dropdown.options[dropdown.selectedIndex];
if (selectedOption.value !== "") {
let materialCode = selectedOption.value;
let materialName = selectedOption.text;
let container = document.createElement("div");
container.classList.add("sortable-item");
container.id = materialCode + "_container";
container.innerHTML = `
<input type="checkbox" id="${materialCode}_checkboxId"
name="customisedMaterialCodes[]" value="${materialCode}"
onclick="removeSelectedMaterial(this)" checked>
<label class="grab" for="${materialCode}_checkboxId"> ${materialName} </label>
<br>
`;
attachDragEvents(container);
document.getElementById("sortableList").appendChild(container);
}
};
});
</script>
<script>
$(document).ready(function () {
$('#month').change(function(){
$('#changeMonthForm').submit();
})
$('#month').datepicker({
format: "M-yyyy", // Format as "Jan-2025"
minViewMode: 1, // Month-Year Picker
autoclose: true,
todayHighlight: true
}).on('focus', function() {
$(this).datepicker('show'); // Ensure it opens on focus
});
});
</script>
<script>
$(document).ready(function(){
$('#customizeHeader').select2();
})
</script>
<script>
function toggleDivFullscreen() {
let div = document.getElementById("fullscreenDiv");
let tableResponsive = document.getElementById("table-responsive"); // Select the table container inside div
if (!document.fullscreenElement) {
div.requestFullscreen().then(() => {
div.style.width = "100vw"; // Full viewport width
div.style.height = "100vh"; // Full viewport height
// If .table-responsive exists, set its height to 90vh
if (tableResponsive) {
tableResponsive.style.maxHeight = "90vh";
tableResponsive.style.overflowY = "auto"; // Allow scrolling if needed
}
// Delay Select2 reinitialization
setTimeout(() => {
$('.select2').select2();
}, 1000);
}).catch(err => console.log("Error enabling fullscreen:", err));
} else {
document.exitFullscreen().then(() => {
div.style.width = "100%";
div.style.height = "100%";
// Reset .table-responsive height when exiting fullscreen
if (tableResponsive) {
tableResponsive.style.height = "auto";
}
}).catch(err => console.log("Error exiting fullscreen:", err));
}
}
$("#searchInput").on("keyup", function () {
let value = $(this).val().toLowerCase(); // Convert input to lowercase for case-insensitive search
$(".table-responsive tbody tr").filter(function () {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1);
});
});
</script>