408 lines
17 KiB
JavaScript
408 lines
17 KiB
JavaScript
frappe.ui.form.on("Sales Invoice", {
|
|
refresh(frm) {
|
|
frm.clear_custom_buttons();
|
|
|
|
if (frm.doc.docstatus !== 1) return;
|
|
if (!frm.doc.customer) return;
|
|
|
|
if (frm.doc.outstanding_amount <= 0) {
|
|
frm.dashboard.add_indicator("Paid", "green");
|
|
return;
|
|
}
|
|
|
|
frm.dashboard.add_indicator("Unpaid", "red");
|
|
|
|
frm.add_custom_button("Run Payment", () => {
|
|
run_payment_flow(frm);
|
|
}, "Actions");
|
|
}
|
|
});
|
|
|
|
|
|
function run_payment_flow(frm) {
|
|
frm.disable_save();
|
|
|
|
frappe.call({
|
|
method: "ns_app.api.payments.check_autopay",
|
|
args: { customer: frm.doc.customer },
|
|
callback(r) {
|
|
frm.enable_save();
|
|
if (!r.message) return;
|
|
|
|
if (r.message.autopay_enabled && r.message.autopay_id) {
|
|
run_autopay(frm);
|
|
} else {
|
|
open_manual_payment_form(frm);
|
|
}
|
|
}
|
|
});
|
|
}
|
|
|
|
|
|
function run_autopay(frm) {
|
|
frappe.confirm(
|
|
`Run AutoPay for ${format_currency(frm.doc.outstanding_amount)}?`,
|
|
() => {
|
|
frm.remove_custom_button("Run Payment");
|
|
frm.add_custom_button("Processing...", () => {}, null).prop("disabled", true);
|
|
|
|
frappe.call({
|
|
method: "ns_app.api.payments.run_autopay_payment",
|
|
args: { invoice: frm.doc.name },
|
|
freeze: true,
|
|
freeze_message: "Processing payment...",
|
|
callback(r) {
|
|
if (!r.message) {
|
|
show_payment_failed(frm, "No response from payment processor");
|
|
return;
|
|
}
|
|
if (r.message.success) {
|
|
frm.remove_custom_button("Run Payment");
|
|
frm.add_custom_button("Paid ✓", () => {}).prop("disabled", true);
|
|
frappe.show_alert({
|
|
message: `Payment of ${format_currency(frm.doc.outstanding_amount)} received`,
|
|
indicator: "green"
|
|
});
|
|
frm.reload_doc();
|
|
} else {
|
|
show_payment_failed(frm, r.message.error || "Payment declined");
|
|
}
|
|
}
|
|
});
|
|
},
|
|
() => {}
|
|
);
|
|
}
|
|
|
|
|
|
function show_payment_failed(frm, message) {
|
|
frm.remove_custom_button("Processing...");
|
|
frm.add_custom_button("Retry Payment", () => run_payment_flow(frm));
|
|
frappe.msgprint({ title: "Payment Failed", indicator: "red", message });
|
|
}
|
|
|
|
|
|
function open_manual_payment_form(frm) {
|
|
const uid = Date.now();
|
|
window.ns_payment_processing = false;
|
|
|
|
let all_invoices = [];
|
|
let selected = new Set();
|
|
|
|
const dialog = new frappe.ui.Dialog({
|
|
title: "Secure Payment",
|
|
size: "large",
|
|
fields: [
|
|
{
|
|
fieldtype: "HTML",
|
|
fieldname: "payment_form",
|
|
options: `
|
|
<div style="padding:20px;">
|
|
<div>
|
|
<label>First Name</label>
|
|
<input type="text" id="first_name_${uid}" class="form-control"/>
|
|
</div>
|
|
<div class="mt-2">
|
|
<label>Last Name</label>
|
|
<input type="text" id="last_name_${uid}" class="form-control"/>
|
|
</div>
|
|
<div class="mt-2">
|
|
<label>Company (Optional)</label>
|
|
<input type="text" id="company_${uid}" class="form-control"/>
|
|
</div>
|
|
<div class="mt-2">
|
|
<label>Billing ZIP</label>
|
|
<input type="text" id="billing_zip_${uid}" class="form-control"/>
|
|
</div>
|
|
<div class="mt-3">
|
|
<label style="font-weight:bold;">
|
|
<input type="checkbox" id="save_autopay_${uid}"/>
|
|
Save for Auto Pay
|
|
</label>
|
|
</div>
|
|
<div class="mt-3" style="border-top:1px solid #eee; padding-top:12px;">
|
|
<label style="font-weight:bold;">
|
|
<input type="checkbox" id="multi_invoice_${uid}"/>
|
|
Pay Additional Invoices
|
|
</label>
|
|
</div>
|
|
<div id="invoice_table_wrap_${uid}" style="display:none; margin-top:12px;">
|
|
<div id="invoice_table_loading_${uid}" style="color:#888; font-size:13px;">
|
|
Loading invoices...
|
|
</div>
|
|
<table id="invoice_table_${uid}" class="table table-bordered table-sm"
|
|
style="display:none; font-size:13px;">
|
|
<thead style="background:#f5f5f5;">
|
|
<tr>
|
|
<th style="width:36px;">
|
|
<input type="checkbox" id="select_all_${uid}" title="Select all"/>
|
|
</th>
|
|
<th>Invoice #</th>
|
|
<th>Date</th>
|
|
<th>Customer</th>
|
|
<th style="text-align:right;">Amount Due</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody id="invoice_tbody_${uid}"></tbody>
|
|
<tfoot>
|
|
<tr>
|
|
<td colspan="4" style="text-align:right; font-weight:bold;">
|
|
Selected Total
|
|
</td>
|
|
<td style="text-align:right; font-weight:bold;"
|
|
id="selected_total_${uid}">
|
|
${format_currency(frm.doc.outstanding_amount)}
|
|
</td>
|
|
</tr>
|
|
</tfoot>
|
|
</table>
|
|
</div>
|
|
<div id="cc_number_${uid}" class="mt-3"></div>
|
|
<div id="cc_exp_${uid}" class="mt-2"></div>
|
|
<div id="cc_cvv_${uid}" class="mt-2"></div>
|
|
<button id="pay_btn_${uid}" class="btn btn-primary mt-4">
|
|
Pay ${format_currency(frm.doc.outstanding_amount)}
|
|
</button>
|
|
</div>`
|
|
}
|
|
],
|
|
primary_action_label: "Close",
|
|
primary_action() { dialog.hide(); }
|
|
});
|
|
|
|
dialog.show();
|
|
|
|
// ── Cleanup on close ─────────────────────────────────────────────────────
|
|
dialog.$wrapper.on("hidden.bs.modal", function () {
|
|
document.querySelectorAll(".modal-backdrop").forEach(el => el.remove());
|
|
document.body.classList.remove("modal-open");
|
|
document.body.style.overflow = "";
|
|
dialog.$wrapper.remove();
|
|
window.ns_payment_processing = false;
|
|
if (window.CollectJS) { try { delete window.CollectJS; } catch(e) {} }
|
|
});
|
|
|
|
// ── Prefill billing fields ────────────────────────────────────────────────
|
|
setTimeout(() => {
|
|
const parts = (frm.doc.customer_name || "").trim().split(" ");
|
|
const set = (id, val) => { const el = document.getElementById(id); if (el) el.value = val; };
|
|
set(`first_name_${uid}`, parts[0] || "");
|
|
set(`last_name_${uid}`, parts.slice(1).join(" ") || "");
|
|
set(`company_${uid}`, frm.doc.customer || "");
|
|
set(`billing_zip_${uid}`, frm.doc.billing_zip || frm.doc.pincode || "");
|
|
}, 50);
|
|
|
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
function get_selected_total() {
|
|
return all_invoices
|
|
.filter(inv => selected.has(inv.name))
|
|
.reduce((sum, inv) => sum + inv.outstanding_amount, 0);
|
|
}
|
|
|
|
function update_pay_button() {
|
|
const total = selected.size > 0 ? get_selected_total() : frm.doc.outstanding_amount;
|
|
const btn = document.getElementById(`pay_btn_${uid}`);
|
|
if (btn && !btn.disabled) btn.innerText = `Pay ${format_currency(total)}`;
|
|
const totalEl = document.getElementById(`selected_total_${uid}`);
|
|
if (totalEl) totalEl.innerText = format_currency(total);
|
|
}
|
|
|
|
function render_invoice_table(invoices) {
|
|
all_invoices = invoices;
|
|
|
|
const tbody = document.getElementById(`invoice_tbody_${uid}`);
|
|
const table = document.getElementById(`invoice_table_${uid}`);
|
|
const loading = document.getElementById(`invoice_table_loading_${uid}`);
|
|
|
|
if (!tbody) return;
|
|
|
|
tbody.innerHTML = "";
|
|
selected.clear();
|
|
|
|
invoices.forEach(inv => {
|
|
if (inv.name === frm.doc.name) selected.add(inv.name);
|
|
|
|
const tr = document.createElement("tr");
|
|
tr.setAttribute("data-invoice", inv.name);
|
|
tr.innerHTML = `
|
|
<td style="text-align:center;">
|
|
<input type="checkbox"
|
|
class="inv-check-${uid}"
|
|
data-name="${inv.name}"
|
|
${inv.name === frm.doc.name ? "checked" : ""}/>
|
|
</td>
|
|
<td><a href="/app/sales-invoice/${inv.name}" target="_blank">${inv.name}</a></td>
|
|
<td>${frappe.datetime.str_to_user(inv.posting_date)}</td>
|
|
<td>${inv.customer_name || frm.doc.customer_name}</td>
|
|
<td style="text-align:right;">${format_currency(inv.outstanding_amount)}</td>
|
|
`;
|
|
tbody.appendChild(tr);
|
|
});
|
|
|
|
// Row checkbox events — use delegation on tbody
|
|
$(tbody).on("change", `.inv-check-${uid}`, function () {
|
|
if (this.checked) selected.add(this.dataset.name);
|
|
else selected.delete(this.dataset.name);
|
|
update_pay_button();
|
|
|
|
const all = tbody.querySelectorAll(`.inv-check-${uid}`);
|
|
const selectAll = document.getElementById(`select_all_${uid}`);
|
|
if (selectAll) selectAll.checked = [...all].every(c => c.checked);
|
|
});
|
|
|
|
// Select-all
|
|
$(dialog.$wrapper).on("change", `#select_all_${uid}`, function () {
|
|
tbody.querySelectorAll(`.inv-check-${uid}`).forEach(cb => {
|
|
cb.checked = this.checked;
|
|
if (this.checked) selected.add(cb.dataset.name);
|
|
else selected.delete(cb.dataset.name);
|
|
});
|
|
update_pay_button();
|
|
});
|
|
|
|
loading.style.display = "none";
|
|
table.style.display = "";
|
|
update_pay_button();
|
|
}
|
|
|
|
// ── Multi-invoice checkbox — delegated, no setTimeout needed ─────────────
|
|
dialog.$wrapper.on("change", `#multi_invoice_${uid}`, function () {
|
|
const tableWrap = document.getElementById(`invoice_table_wrap_${uid}`);
|
|
if (!tableWrap) return;
|
|
|
|
if (!this.checked) {
|
|
tableWrap.style.display = "none";
|
|
selected.clear();
|
|
update_pay_button();
|
|
return;
|
|
}
|
|
|
|
tableWrap.style.display = "";
|
|
|
|
if (all_invoices.length > 0) {
|
|
render_invoice_table(all_invoices);
|
|
return;
|
|
}
|
|
|
|
frappe.call({
|
|
method: "ns_app.api.payments.get_unpaid_invoices",
|
|
args: { customer: frm.doc.customer },
|
|
callback(r) {
|
|
if (r.message && r.message.length) {
|
|
render_invoice_table(r.message);
|
|
} else {
|
|
const loading = document.getElementById(`invoice_table_loading_${uid}`);
|
|
if (loading) loading.innerText = "No other unpaid invoices found.";
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
// ── CollectJS ─────────────────────────────────────────────────────────────
|
|
function loadCollectJS(callback) {
|
|
const existing = document.querySelector('script[src*="Collect.js"]');
|
|
if (existing) existing.remove();
|
|
if (window.CollectJS) { try { delete window.CollectJS; } catch(e) {} }
|
|
|
|
const script = document.createElement("script");
|
|
script.src = "https://secure.nmi.com/token/Collect.js";
|
|
script.setAttribute("data-tokenization-key", "HKx4XR-G549wT-8bZ2YJ-3kbG28");
|
|
script.onload = () => { console.log("CollectJS loaded"); callback(); };
|
|
document.body.appendChild(script);
|
|
}
|
|
|
|
loadCollectJS(() => {
|
|
setTimeout(() => {
|
|
CollectJS.configure({
|
|
variant: "inline",
|
|
styleSniffer: true,
|
|
fields: {
|
|
ccnumber: { selector: `#cc_number_${uid}`, placeholder: "Card Number" },
|
|
ccexp: { selector: `#cc_exp_${uid}`, placeholder: "MM / YY" },
|
|
cvv: { selector: `#cc_cvv_${uid}`, placeholder: "CVV" }
|
|
},
|
|
callback(response) {
|
|
if (window.ns_payment_processing) return;
|
|
window.ns_payment_processing = true;
|
|
|
|
if (!response.token) {
|
|
window.ns_payment_processing = false;
|
|
frappe.msgprint("Payment failed to tokenize");
|
|
return;
|
|
}
|
|
|
|
const get = id => document.getElementById(`${id}_${uid}`)?.value?.trim();
|
|
const saveCb = document.getElementById(`save_autopay_${uid}`);
|
|
const multiCb = document.getElementById(`multi_invoice_${uid}`);
|
|
|
|
const invoice_names = (multiCb?.checked && selected.size > 0)
|
|
? [...selected]
|
|
: [frm.doc.name];
|
|
|
|
const payBtn = document.getElementById(`pay_btn_${uid}`);
|
|
if (payBtn) { payBtn.disabled = true; payBtn.innerText = "Processing..."; }
|
|
|
|
run_token_payment(frm, response.token, dialog, {
|
|
first_name: get("first_name"),
|
|
last_name: get("last_name"),
|
|
company: get("company"),
|
|
billing_zip: get("billing_zip"),
|
|
save_autopay: saveCb?.checked ? 1 : 0,
|
|
invoice_names
|
|
});
|
|
}
|
|
});
|
|
|
|
const btn = document.getElementById(`pay_btn_${uid}`);
|
|
if (!btn) { console.error("Pay button not found"); return; }
|
|
|
|
btn.onclick = function () {
|
|
if (window.ns_payment_processing) return;
|
|
btn.disabled = true;
|
|
btn.innerText = "Processing...";
|
|
frappe.show_alert({ message: "Processing payment...", indicator: "blue" });
|
|
CollectJS.startPaymentRequest();
|
|
};
|
|
}, 300);
|
|
});
|
|
}
|
|
|
|
|
|
function run_token_payment(frm, token, dialog, extra_data = {}) {
|
|
frappe.call({
|
|
method: "ns_app.api.payments.run_token_payment",
|
|
args: {
|
|
invoice: frm.doc.name,
|
|
invoice_names: extra_data.invoice_names || [frm.doc.name],
|
|
token,
|
|
first_name: extra_data.first_name,
|
|
last_name: extra_data.last_name,
|
|
company: extra_data.company,
|
|
billing_zip: extra_data.billing_zip,
|
|
save_autopay: extra_data.save_autopay || 0
|
|
},
|
|
freeze: true,
|
|
freeze_message: "Processing payment...",
|
|
callback(r) {
|
|
if (r.message?.success) {
|
|
frappe.show_alert({
|
|
message: extra_data.save_autopay && r.message.vault_id
|
|
? `Payment successful + AutoPay enabled (${r.message.vault_id})`
|
|
: "Payment successful",
|
|
indicator: "green"
|
|
});
|
|
window.ns_payment_processing = false;
|
|
dialog.hide();
|
|
frm.reload_doc();
|
|
} else {
|
|
window.ns_payment_processing = false;
|
|
frappe.msgprint(r.message?.error || "Payment failed");
|
|
const payBtn = document.querySelector('[id^="pay_btn_"]');
|
|
if (payBtn) {
|
|
payBtn.disabled = false;
|
|
payBtn.innerText = `Pay ${format_currency(frm.doc.outstanding_amount)}`;
|
|
}
|
|
}
|
|
}
|
|
});
|
|
} |