Files
wms-app/app/revenue/manage_order.php
T
Thanakorn 693c72f9ea Fix transfer quantity, unify date format, align demo seeds
Stock Transfer list showed 0.00 (read in instead of out); stock-out/transfer forms show the location quantity; dates display as YYYY-MM-DD HH:mm:ss. Demo seeds map product accounts and use product names and supplier batches.
2026-09-15 13:09:19 +07:00

507 lines
20 KiB
PHP

<?php
session_start();
require '../config.php';
require '../include_header.php';
$order_id = (int)($_GET['id'] ?? 0);
?>
<body>
<?php require '../include_topbar.php'; ?>
<?php require '../include_sidebar_ac.php'; ?>
<main id="content" class="content py-15">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="mb-6 d-flex justify-content-between align-items-center">
<div>
<h1 class="fs-3 mb-1" id="page_title">
<?php echo $order_id ? 'Sales Order Detail' : 'New Sales Order'; ?>
</h1>
<p class="mb-0 text-muted" id="page_subtitle">
<?php echo $order_id ? '' : 'Create a pending sales order for WMS warehouse assignment'; ?>
</p>
</div>
<a href="<?php echo $server_url?>revenue/order.php" class="btn btn-light">
<i class="ti ti-arrow-left me-1"></i>Back
</a>
</div>
</div>
</div>
<div class="row g-5">
<div class="col-lg-8">
<div class="card mb-5">
<div class="card-body p-5">
<h2 class="fs-5 mb-4">Order Information</h2>
<div class="row gx-5">
<div class="mb-3 col-lg-6">
<label class="form-label">Contact</label>
<input type="text" id="contact" class="form-control contact_search"
placeholder="Search contact..." autocomplete="off">
<input type="hidden" id="contact_id">
</div>
<div class="mb-3 col-lg-6">
<label class="form-label">Order Date</label>
<input type="text" id="order_date" class="form-control"
placeholder="DD/MM/YYYY" autocomplete="off">
</div>
<div class="mb-3 col-lg-12">
<label class="form-label">Notes</label>
<textarea id="notes" class="form-control" rows="2"
placeholder="Internal notes..."></textarea>
</div>
</div>
</div>
</div>
<div class="card mb-5">
<div class="card-body p-5">
<div class="d-flex justify-content-between align-items-center mb-4">
<h2 class="fs-5 mb-0">Order Items</h2>
<button class="btn btn-sm btn-outline-primary" id="btn_add_item" onclick="add_item_row()">
<i class="ti ti-plus me-1"></i>Add Item
</button>
</div>
<div class="table-responsive">
<table class="table mb-0" id="item_table">
<thead class="table-light">
<tr>
<th style="width:120px;">SKU</th>
<th>Description</th>
<th style="width:90px;">Qty</th>
<th style="width:120px;">Unit Price</th>
<th style="width:80px;">Tax%</th>
<th style="width:120px;">Total</th>
<th style="width:40px;"></th>
</tr>
</thead>
<tbody id="item_tbody"></tbody>
</table>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="card mb-5 d-none" id="status_card">
<div class="card-body p-4">
<h2 class="fs-5 mb-3">Status</h2>
<div id="badge_status" class="mb-2"></div>
<p class="mb-0 small fw-semibold text-muted" id="order_number_display"></p>
</div>
</div>
<div class="alert alert-warning mb-5" id="wms_status_alert">
<div class="d-flex gap-2">
<i class="ti ti-building-warehouse mt-1"></i>
<div>
<div class="fw-semibold" id="wms_status_title">Pending WMS assignment</div>
<div class="small" id="wms_status_message">
This order will be sent to WMS as pending. WMS staff assign warehouses before confirmation.
</div>
</div>
</div>
</div>
<div class="card mb-5">
<div class="card-body p-4">
<h2 class="fs-5 mb-3">Summary</h2>
<div class="d-flex justify-content-between mb-2">
<span class="text-muted">Subtotal</span>
<span id="summary_subtotal">0.00</span>
</div>
<div class="d-flex justify-content-between align-items-center mb-2">
<span class="text-muted">Discount</span>
<input type="number" id="discount" class="form-control form-control-sm text-end"
style="width:110px;" value="0" min="0" step="any" oninput="recalc_totals()">
</div>
<div class="d-flex justify-content-between mb-2">
<span class="text-muted">Tax</span>
<span id="summary_tax" class="fw-semibold">0.00</span>
</div>
<div class="d-flex justify-content-between align-items-center mb-2">
<span class="text-muted small">Tax Adj.</span>
<input type="number" id="tax_adjustment" class="form-control form-control-sm text-end"
style="width:90px;" value="0" min="-0.3" max="0.3" step="0.01" oninput="recalc_totals()">
</div>
<div class="d-flex justify-content-between align-items-center mb-3">
<span class="text-muted">Shipping</span>
<input type="number" id="shipping_fee" class="form-control form-control-sm text-end"
style="width:110px;" value="0" min="0" step="any" oninput="recalc_totals()">
</div>
<hr>
<div class="d-flex justify-content-between fw-bold fs-5">
<span>Grand Total</span>
<span id="summary_grand_total">0.00</span>
</div>
</div>
</div>
<div class="card">
<div class="card-body p-4 d-flex flex-column gap-2">
<button class="btn btn-primary w-100" id="btn_save" onclick="save_order()">
<i class="ti ti-device-floppy me-1"></i>Save Pending SO
</button>
<button class="btn btn-outline-primary w-100 d-none" id="btn_invoice" onclick="proceed_to_invoice()">
<i class="ti ti-file-invoice me-1"></i>Create Invoice
</button>
<a href="#" class="btn btn-outline-primary w-100 d-none" id="link_invoice">
<i class="ti ti-file-invoice me-1"></i>View Invoice
</a>
<button class="btn btn-outline-danger w-100 d-none" id="btn_cancel" onclick="cancel_order()">
<i class="ti ti-x me-1"></i>Cancel Order
</button>
<button class="btn btn-outline-danger w-100 d-none" id="btn_delete" onclick="delete_order()">
<i class="ti ti-trash me-1"></i>Delete Order
</button>
<a href="<?php echo $server_url?>revenue/order.php" class="btn btn-light w-100">
Back
</a>
</div>
</div>
</div>
</div>
</div>
</main>
<?php require '../include_ending.php'; ?>
<script>
// custom.js globals: remove_item(), init_product_search_inputs(), escape_html(), format_number()
const can_delete = ['admin', 'owner'].includes(user_role);
var order_id = <?php echo $order_id; ?>;
var order_data = null;
var item_index = 0;
var status_badge = {
'-2': '<span class="badge bg-danger">Pending Warehouse</span>',
'-1': '<span class="badge bg-secondary">Cancelled</span>',
'0': '<span class="badge bg-warning text-dark">Draft</span>',
'1': '<span class="badge bg-info text-white">Confirmed</span>',
};
function recalc_totals() {
var subtotal = 0;
var tax_sum = 0;
$('#item_tbody tr').each(function() {
var qty = parseFloat($(this).find('.item_qty').val()) || 0;
var price = parseFloat($(this).find('.item_price').val()) || 0;
var tax_rate = parseFloat($(this).find('.item_tax_rate').val()) || 0;
var total = qty * price;
var tax_amt = round_dp(total * tax_rate / 100, 4);
$(this).find('.item_total').text(format_number(total, 2));
$(this).find('.item_tax_amount').val(tax_amt);
subtotal += total;
tax_sum += tax_amt;
});
var discount = parseFloat($('#discount').val()) || 0;
var tax_adjustment = parseFloat($('#tax_adjustment').val()) || 0;
var shipping = parseFloat($('#shipping_fee').val()) || 0;
var derived_tax = round_dp(tax_sum, 2);
$('#summary_subtotal').text(format_number(subtotal, 2));
$('#summary_tax').text(format_number(derived_tax, 2));
$('#summary_grand_total').text(format_number(subtotal - discount + derived_tax + tax_adjustment + shipping, 2));
}
function add_item_row(item) {
item = item || {};
var idx = item_index++;
var row = `<tr id="item_row_${idx}">
<td>
<input type="text" class="form-control form-control-sm item_sku product_search"
placeholder="SKU..." value="${escape_html(item.product_sku || '')}" autocomplete="off"
data-product-name-target=".item_desc">
</td>
<td>
<input type="text" class="form-control form-control-sm item_desc"
placeholder="Description..." value="${escape_html(item.product_name || item.description || '')}" autocomplete="off">
</td>
<td>
<input type="number" class="form-control form-control-sm item_qty"
value="${item.quantity || 1}" min="0.0001" step="any" oninput="recalc_totals()">
</td>
<td>
<input type="number" class="form-control form-control-sm item_price"
value="${item.unit_price || item.price || 0}" min="0" step="any" oninput="recalc_totals()">
</td>
<td>
<input type="number" class="form-control form-control-sm item_tax_rate"
value="${parseFloat(item.tax_rate || 0).toFixed(2)}" min="0" max="100" step="0.01" oninput="recalc_totals()">
<input type="hidden" class="item_tax_amount" value="${item.tax_amount || 0}">
</td>
<td class="item_total text-end align-middle">
${format_number((item.quantity || 1) * (item.unit_price || item.price || 0), 2)}
</td>
<td class="align-middle">
<a href="javascript:void(0);" class="link-danger remove_item_btn" onclick="remove_item(${idx})">
<i class="ti ti-trash fs-5"></i>
</a>
</td>
</tr>`;
$('#item_tbody').append(row);
if (window.init_product_search_inputs) {
window.init_product_search_inputs(`#item_row_${idx}`);
}
recalc_totals();
}
function collect_items() {
var items = [];
var idx = 0;
$('#item_tbody tr').each(function() {
var sku = $(this).find('.item_sku').val().trim();
var name = $(this).find('.item_desc').val().trim();
var qty = parseFloat($(this).find('.item_qty').val()) || 0;
var price = parseFloat($(this).find('.item_price').val()) || 0;
var tax_rate = parseFloat($(this).find('.item_tax_rate').val()) || 0;
var tax_amt = parseFloat($(this).find('.item_tax_amount').val()) || 0;
if (!sku || qty <= 0) { idx++; return; }
items.push({
item_id: idx,
product_sku: sku,
product_name: name,
warehouse_id: 0,
zone: '',
aisle: '',
bin: '',
lot_number: '',
serial_number: '',
quantity: qty,
unit_price: price,
total_price: round_dp(qty * price, 4),
tax_rate: tax_rate,
tax_amount: tax_amt,
stock_out_id: 0,
});
idx++;
});
return items;
}
function set_mode(status, has_active_invoice, active_invoice_id) {
status = parseInt(status);
has_active_invoice = has_active_invoice || false;
active_invoice_id = parseInt(active_invoice_id) || 0;
var editable = status === -2;
$('#contact, #order_date, #notes, #discount, #tax_adjustment, #shipping_fee, #btn_add_item')
.prop('disabled', !editable);
$('.item_sku, .item_desc, .item_qty, .item_price, .item_tax_rate').prop('disabled', !editable);
$('.remove_item_btn').toggleClass('d-none', !editable);
$('#btn_save').toggleClass('d-none', !editable);
if (status === -2) {
$('#wms_status_title').text('Pending WMS assignment');
$('#wms_status_message').text('This order is pending. WMS staff will assign warehouses before confirmation.');
} else if (status === 0) {
$('#wms_status_title').text('Managed on WMS side');
$('#wms_status_message').text('This order is now Draft in WMS. Continue warehouse assignment and confirmation from the WMS order screen.');
} else {
$('#wms_status_title').text('Managed on WMS side');
$('#wms_status_message').text('This order has moved beyond Revenue editing. Continue operational updates from the WMS order screen.');
}
$('#btn_cancel').toggleClass('d-none', status !== -2);
$('#btn_delete').toggleClass('d-none', !can_delete || !order_id);
var is_existing = order_id > 0;
var can_invoice = is_existing && status >= 1 && status !== -1 && !has_active_invoice;
var invoice_title = !is_existing ? 'Save the order before creating an invoice'
: status < 1 ? 'WMS must confirm the sales order before accounting can create an invoice'
: status === -1 ? 'Cancelled orders cannot be invoiced'
: has_active_invoice ? 'An active invoice already exists for this order'
: '';
$('#btn_invoice')
.toggleClass('d-none', !is_existing || has_active_invoice)
.prop('disabled', !can_invoice)
.attr('title', invoice_title);
$('#link_invoice')
.toggleClass('d-none', !has_active_invoice || !active_invoice_id)
.attr('href', active_invoice_id
? '<?php echo $server_url?>revenue/manage_invoice.php?id=' + active_invoice_id
: '#');
}
function retrieve_order() {
if (!order_id) return Promise.resolve();
return ajax_request({
url: '<?php echo $server_url?>order/api/engine/retrieve_order.php',
autoPrepare: true,
checkRequired: 0,
action: 'read',
data: { id: order_id },
onSuccess: function(res) {
order_data = res.output;
var o = order_data;
if (!['revenue', 'quotation'].includes(String(o.source || ''))) {
bootbox.alert('This is not a Revenue sales order.');
return;
}
$('#page_title').text(o.order_number);
$('#page_subtitle').text(parseInt(o.status) === -2 ? 'Pending sales order' : 'View sales order');
$('#status_card').removeClass('d-none');
$('#badge_status').html(status_badge[String(o.status)] || o.status);
$('#order_number_display').text(o.order_number);
$('#contact').val(o.contact_name || '');
$('#contact_id').val(o.contact_id || 0);
$('#order_date').val(o.order_date ? format_date_input(o.order_date) : '');
$('#notes').val(o.notes || '');
$('#discount').val(o.discount || 0);
$('#tax_adjustment').val(o.tax_adjustment || 0);
$('#shipping_fee').val(o.shipping_fee || 0);
$('#item_tbody').empty();
item_index = 0;
(o.items || []).forEach(function(item) { add_item_row(item); });
recalc_totals();
set_mode(o.status, res.has_active_invoice, res.active_invoice_id);
}
});
}
function save_order() {
var items = collect_items();
if (!items.length) {
bootbox.alert('Please add at least one line item.');
return;
}
ajax_request({
url: '<?php echo $server_url?>revenue/api/engine/manage_order.php',
autoPrepare: true,
checkRequired: 0,
action: order_id ? 'update' : 'create',
data: {
id: order_id,
contact_id: $('#contact_id').val() || 0,
order_date: to_iso_date($('#order_date').val()),
items: JSON.stringify(items),
discount: $('#discount').val() || 0,
tax_adjustment: $('#tax_adjustment').val() || 0,
shipping_fee: $('#shipping_fee').val() || 0,
notes: $('#notes').val(),
},
onSuccess: function(res) {
if (!order_id && res.new_id) {
window.location.href = '<?php echo $server_url?>revenue/manage_order.php?id=' + res.new_id;
} else {
retrieve_order();
}
}
});
}
function proceed_to_invoice() {
if (!order_id) return;
bootbox.confirm({
message: 'Create an invoice from this sales order?',
buttons: {
confirm: { label: 'Create Invoice', className: 'btn-primary' },
cancel: { label: 'Back', className: 'btn-secondary' }
},
callback: function(result) {
if (!result) return;
ajax_request({
url: '<?php echo $server_url?>revenue/api/engine/proceed_to_invoice.php',
autoPrepare: true,
checkRequired: 0,
action: 'create',
data: { order_id: order_id },
onSuccess: function(res) {
if (res.new_id) {
window.location.href = '<?php echo $server_url?>revenue/manage_invoice.php?id=' + res.new_id;
} else {
retrieve_order();
}
}
});
}
});
}
function delete_order() {
bootbox.confirm({
message: 'Delete this order? Unconfirmed stock-out rows will also be removed.',
buttons: { confirm: { label: 'Delete', className: 'btn-danger' }, cancel: { label: 'Back', className: 'btn-secondary' } },
callback: function(result) {
if (!result) return;
ajax_request({
url: '<?php echo $server_url?>order/api/engine/delete_order.php',
autoPrepare: false,
checkRequired: 0,
action: 'delete',
data: { id: order_id },
onSuccess: function() { window.location.href = '<?php echo $server_url?>revenue/order.php'; }
});
}
});
}
function cancel_order() {
bootbox.confirm({
message: 'Cancel this pending sales order? It will be removed from WMS queue.',
buttons: {
confirm: { label: 'Yes, Cancel', className: 'btn-danger' },
cancel: { label: 'Back', className: 'btn-secondary' }
},
callback: function(result) {
if (!result) return;
ajax_request({
url: '<?php echo $server_url?>order/api/engine/cancel_order.php',
autoPrepare: true,
checkRequired: 0,
action: 'update',
data: { id: order_id },
onSuccess: function() {
retrieve_order();
}
});
}
});
}
$(document).on('contact:selected', '#contact', function(e, contact) {
$('#contact_id').val(contact.id);
});
$(document).on('product:selected', '.item_sku', function(e, product) {
var $row = $(this).closest('tr');
var price = parseFloat(product.price || 0);
if (!(parseFloat($row.find('.item_price').val()) > 0) && price > 0) {
$row.find('.item_price').val(price);
}
$row.find('.item_tax_rate').val(parseFloat(product.tax_rate || 0).toFixed(2));
recalc_totals();
});
$(async function() {
try {
if (order_id) {
await retrieve_order();
} else {
$('#order_date').val(flatpickr.formatDate(new Date(), 'd/m/Y'));
add_item_row();
set_mode(-2, false, 0);
}
flatpickr('#order_date', { dateFormat: 'd/m/Y', allowInput: true });
} catch(e) { console.log(e); }
});
</script>
</body>
</html>