// LPO Form Logic initInvoiceForm('lpoProductSearchInput', 'lpoSearchSuggestions', 'lpoItemsTableBody', 'lpo_grand_display', 'lpo_subtotal_display', 'lpo_vat_display'); initInvoiceForm('editLpoProductSearchInput', 'editLpoSearchSuggestions', 'editLpoItemsTableBody', 'edit_lpo_grand_display', 'edit_lpo_subtotal_display', 'edit_lpo_vat_display'); const parseLpoQuotationButtonPayload = (btn) => { if (!btn || !btn.dataset || !btn.dataset.json) return {}; try { return JSON.parse(btn.dataset.json); } catch (error) { console.warn('Failed to parse LPO/Quotation payload from button data.', error); return {}; } }; const renderExistingDocumentItems = (items, tableBodyId, grandTotalId, subtotalId, totalVatId) => { const tableBody = document.getElementById(tableBodyId); const grandTotalEl = document.getElementById(grandTotalId); const subtotalEl = document.getElementById(subtotalId); const totalVatEl = document.getElementById(totalVatId); if (!tableBody) return; tableBody.innerHTML = ''; if (!Array.isArray(items) || items.length === 0) { if (typeof recalculate === 'function') { recalculate(tableBody, grandTotalEl, subtotalEl, totalVatEl); } return; } items.forEach(item => { addItemToTable({ id: item.item_id || item.id, name_en: item.name_en || item.item_name_en || 'Item', name_ar: item.name_ar || item.item_name_ar || '', sku: item.sku || '', vat_rate: item.vat_rate || 0, stock_quantity: item.stock_quantity || 0 }, tableBody, null, null, grandTotalEl, subtotalEl, totalVatEl, { quantity: item.quantity, unit_price: item.unit_price }); }); }; document.querySelectorAll('.edit-lpo-btn').forEach(btn => { btn.addEventListener('click', function() { const data = parseLpoQuotationButtonPayload(this); if (Object.keys(data).length === 0) return; const supplierSelect = document.getElementById('edit_lpo_supplier_id'); const supplierId = data.supplier_id ?? ''; const supplierLabel = data.supplier_name || ''; invoiceEnsureSelectOption('edit_lpo_supplier_id', supplierId, supplierLabel); const lpoIdInput = document.getElementById('edit_lpo_id'); const lpoDateInput = document.getElementById('edit_lpo_date'); const deliveryDateInput = document.getElementById('edit_lpo_delivery_date'); const statusSelect = document.getElementById('edit_lpo_status'); const termsInput = document.getElementById('edit_lpo_terms'); if (lpoIdInput) lpoIdInput.value = data.id || ''; if (supplierSelect) { invoiceSetBlankSelectOptionLabel(supplierSelect, (supplierId === '' && supplierLabel) ? supplierLabel : '---'); supplierSelect.value = supplierId; invoiceSyncSelect2Value(supplierSelect); } if (lpoDateInput) lpoDateInput.value = data.lpo_date || ''; if (deliveryDateInput) deliveryDateInput.value = data.delivery_date || ''; if (statusSelect) statusSelect.value = data.status || 'pending'; if (termsInput) termsInput.value = data.terms_conditions || ''; renderExistingDocumentItems(data.items || [], 'editLpoItemsTableBody', 'edit_lpo_grand_display', 'edit_lpo_subtotal_display', 'edit_lpo_vat_display'); }); }); document.querySelectorAll('.view-lpo-btn').forEach(btn => { btn.addEventListener('click', function() { const data = JSON.parse(this.dataset.json); window.viewAndPrintLPO(data); }); }); window.viewAndPrintLPO = function(data) { const modal = new bootstrap.Modal(document.getElementById('viewLpoModal')); const content = document.getElementById('lpoDetailsContent'); const logoUrl = companySettings.company_logo || ''; const companyHeader = `
${logoUrl ? `Logo` : ''}

${companySettings.company_name || 'Your Company'}

${companySettings.company_address || ''}
Phone: ${companySettings.company_phone || ''} | Email: ${companySettings.company_email || ''} ${companySettings.tax_number ? `
TRN: ${companySettings.tax_number}` : ''}

LOCAL PURCHASE ORDER

LPO-${data.id.toString().padStart(5, '0')}

`; let itemsHtml = ''; data.items.forEach((item, index) => { itemsHtml += ` ${index + 1} ${item.name_en}
${item.name_ar} ${formatQuantity(item.quantity)} ${parseFloat(item.unit_price).toFixed(3)} ${parseFloat(item.vat_rate || 0).toFixed(2)}% ${parseFloat(item.total_amount).toFixed(3)} `; }); content.innerHTML = ` ${companyHeader}
Supplier

${data.supplier_name}

${data.supplier_phone ? `Phone: ${data.supplier_phone}` : ''}

Details
Date: ${data.lpo_date}
Delivery: ${data.delivery_date || '---'}
Status: ${data.status.toUpperCase()}
${itemsHtml}
# Description Qty Unit Price VAT Total
Subtotal OMR ${parseFloat(data.total_amount).toFixed(3)}
VAT Amount OMR ${parseFloat(data.vat_amount).toFixed(2)}
Grand Total OMR ${parseFloat(data.total_with_vat).toFixed(3)}
${data.terms_conditions ? `
Terms & Conditions

${data.terms_conditions.replace(/\n/g, '
')}

` : ''}

Prepared By

Authorized Signature

`; window.printLPO = function() { const printWindow = window.open('', '_blank'); printWindow.document.write('LPO-' + data.id + ''); printWindow.document.write(''); printWindow.document.write(''); printWindow.document.write(''); printWindow.document.write(content.innerHTML); printWindow.document.write(''); printWindow.document.close(); setTimeout(() => { printWindow.print(); printWindow.close(); }, 500); }; modal.show(); }; // Quotation Form Logic initInvoiceForm('quotProductSearchInput', 'quotSearchSuggestions', 'quotItemsTableBody', 'quot_grand_display', 'quot_subtotal_display', 'quot_vat_display'); initInvoiceForm('editQuotProductSearchInput', 'editQuotSearchSuggestions', 'editQuotItemsTableBody', 'edit_quot_grand_display', 'edit_quot_subtotal_display', 'edit_quot_vat_display'); document.querySelectorAll('.edit-quotation-btn').forEach(btn => { btn.addEventListener('click', function() { const data = parseLpoQuotationButtonPayload(this); if (Object.keys(data).length === 0) return; const customerSelect = document.getElementById('edit_quot_customer_id'); const customerId = data.customer_id ?? ''; const customerLabel = data.customer_name || data.party_name || ''; invoiceEnsureSelectOption('edit_quot_customer_id', customerId, customerLabel); const quotationIdInput = document.getElementById('edit_quotation_id'); const quotationDateInput = document.getElementById('edit_quot_date'); const validUntilInput = document.getElementById('edit_quot_valid'); const statusSelect = document.getElementById('edit_quot_status'); if (quotationIdInput) quotationIdInput.value = data.id || ''; if (customerSelect) { invoiceSetBlankSelectOptionLabel(customerSelect, (customerId === '' && customerLabel) ? customerLabel : '---'); customerSelect.value = customerId; invoiceSyncSelect2Value(customerSelect); } if (quotationDateInput) quotationDateInput.value = data.quotation_date || ''; if (validUntilInput) validUntilInput.value = data.valid_until || ''; if (statusSelect) statusSelect.value = data.status || 'pending'; renderExistingDocumentItems(data.items || [], 'editQuotItemsTableBody', 'edit_quot_grand_display', 'edit_quot_subtotal_display', 'edit_quot_vat_display'); }); }); document.querySelectorAll('.convert-quotation-btn').forEach(btn => { btn.addEventListener('click', function() { if (confirm('Convert this quotation to an invoice? This will reduce stock.')) { const f = document.createElement('form'); f.method = 'POST'; f.innerHTML = ``; document.body.appendChild(f); f.submit(); } }); }); // View Quotation Logic window.viewAndPrintQuotation = function(data, autoPrint = false) { const modal = new bootstrap.Modal(document.getElementById('viewQuotationModal')); const content = document.getElementById('quotationPrintableArea'); let itemsHtml = ''; data.items.forEach((item, index) => { itemsHtml += ` ${index + 1} ${item.name_en}
${item.name_ar} ${formatQuantity(item.quantity)} ${parseFloat(item.unit_price).toFixed(3)} ${parseFloat(item.vat_rate || 0).toFixed(2)}% ${parseFloat(item.total_price).toFixed(3)} `; }); // Company Logo and Header Construction const logoUrl = companySettings.company_logo || ''; const logoImg = logoUrl ? `` : ''; const companyName = companySettings.company_name || 'Accounting System'; const companyAddress = (companySettings.company_address || '').replace(/\n/g, '
'); const companyVat = companySettings.vat_number ? `

VAT: ${companySettings.vat_number}

` : ''; const companyPhone = companySettings.company_phone ? `

Tel: ${companySettings.company_phone}

` : ''; // Quotation Header Construction const quotDate = data.quotation_date; const quotValid = data.valid_until || 'N/A'; const quotNo = 'QUO-' + data.id.toString().padStart(5, '0'); const customerName = data.customer_name || 'Walk-in Customer'; const statusBadge = `${data.status.toUpperCase()}`; content.innerHTML = `
${logoImg}

${companyName}

${companyAddress}

${companyVat} ${companyPhone}

Quotation / عرض سعر

${statusBadge}

No / رقم: ${quotNo}

Date / التاريخ: ${quotDate}

Valid Until / صالح لغاية: ${quotValid}

To / إلى

${customerName}
${itemsHtml}
# Item Description / وصف الصنف Qty / الكمية Unit Price / سعر الوحدة VAT / الضريبة Total / الإجمالي
Subtotal / المجموع الفرعي ${parseFloat(data.total_amount).toFixed(3)}
VAT Amount / مبلغ الضريبة ${parseFloat(data.vat_amount).toFixed(2)}
Grand Total (OMR) / المجموع الكلي (رع) ${parseFloat(data.total_with_vat).toFixed(3)}

Terms & Conditions / الشروط والأحكام:

  • Quotation is valid until the date mentioned above. / عرض السعر صالح لغاية التاريخ المذكور أعلاه.
  • Prices are inclusive of VAT where applicable. / الأسعار تشمل ضريبة القيمة المضافة حيثما ينطبق ذلك.
Authorized Signature / التوقيع المعتمد

Generated by / تم إنشاؤه بواسطة ${companyName}

`; const actionButtons = document.getElementById('quotationActionButtons'); actionButtons.innerHTML = ''; if (data.status === 'pending') { const convertBtn = document.createElement('button'); convertBtn.className = 'btn btn-success me-2'; convertBtn.innerHTML = ' Convert to Invoice'; convertBtn.onclick = function() { if (confirm('Convert this quotation to an invoice?')) { const f = document.createElement('form'); f.method = 'POST'; f.innerHTML = ``; document.body.appendChild(f); f.submit(); } }; actionButtons.appendChild(convertBtn); const editBtn = document.createElement('button'); editBtn.className = 'btn btn-primary'; editBtn.innerHTML = ' Edit'; editBtn.onclick = function() { modal.hide(); const originalEditBtn = document.querySelector(`.edit-quotation-btn[data-id="${data.id}"]`); if (originalEditBtn) originalEditBtn.click(); }; actionButtons.appendChild(editBtn); } modal.show(); if (autoPrint) { setTimeout(() => { window.print(); }, 500); } }; document.querySelectorAll('.view-quotation-btn').forEach(btn => { btn.addEventListener('click', function() { const data = JSON.parse(this.dataset.json); window.viewAndPrintQuotation(data, false); }); });