feat : Payout in gui half done means error handling is there

This commit is contained in:
Sibin Sabu 2025-09-15 16:45:54 +05:30
parent 5984f9d036
commit ba40f4dd52
3 changed files with 230 additions and 158 deletions

View File

@ -187,7 +187,7 @@ export class NavbarComponent implements OnInit, OnDestroy {
this.subscription = interval(5000)
.pipe(
switchMap(() => {
return this.http.get('http://localhost:8080/abs/latest').pipe(
return this.http.get('http://localhost:8087/abs/latest').pipe(
catchError((err) => {
this.liveStatusOk = false;
return of(null);

View File

@ -62,6 +62,7 @@
[(ngModel)]="payoutTicketNo"
/>
</div>
<div class="warning-message" *ngIf="payoutWarning">{{ payoutWarning }}</div>
<div class="modal-footer">
<button class="cancel-btn" (click)="closePayoutPopup()">CANCEL</button>

View File

@ -67,125 +67,6 @@ export class SidebarComponent {
cancelWarning: string = ''; // For showing inline warnings
// async printTicketCancel() {
// const enteredTicketNo = this.ticketNo?.trim();
// console.log('[STEP 1] Entered Ticket No:', enteredTicketNo);
// this.cancelWarning = '';
// const localTicketsStr = localStorage.getItem('canceltickets');
// if (!localTicketsStr) {
// console.error('[STEP 2] No localTickets found in localStorage.');
// this.cancelWarning = '❌ No ticket history found.';
// return;
// }
// let localTickets;
// try {
// localTickets = JSON.parse(localTicketsStr);
// } catch (e) {
// console.error('[STEP 3] Error parsing localTickets:', e);
// this.cancelWarning = '❌ Error reading stored tickets.';
// return;
// }
// if (!Array.isArray(localTickets) || localTickets.length === 0) {
// console.warn('[STEP 4] localTickets is empty.');
// this.cancelWarning = '❌ No tickets available to verify.';
// return;
// }
// const lastTicket = localTickets[localTickets.length - 1];
// console.log('[STEP 5] Last Ticket:', lastTicket);
// if (!lastTicket || !lastTicket.barcodeId) {
// console.warn('[STEP 6] Last ticket missing barcodeId.');
// this.cancelWarning = '❌ Invalid stored ticket.';
// return;
// }
// const storedBarcode = lastTicket.barcodeId.trim();
// console.log('[STEP 7] Stored Barcode ID:', storedBarcode);
// if (enteredTicketNo === storedBarcode) {
// console.log('[✅ MATCH] Ticket No matches barcode. Proceeding to cancel...');
// try {
// // 🔗 Call cancel API first
// const cancelReq = {
// ticketNo: lastTicket.barcodeId,
// btId: lastTicket.btId || "0485", // <-- put correct btId here
// usrId: lastTicket.usrId || "341" // <-- put correct usrId here
// };
// console.log("📡 Sending cancel request:", cancelReq);
// const response = await fetch("http://localhost:8085/cancel/ticket", {
// method: "POST",
// headers: { "Content-Type": "application/json" },
// body: JSON.stringify(cancelReq)
// });
// const data = await response.json();
// console.log("📩 Cancel API Response:", data);
// if (!data.ok) {
// console.error("❌ Cancel failed:", data.error);
// this.cancelWarning = `❌ Cancel failed: ${data.error}`;
// return;
// }
// // ✅ Cancel succeeded
// // Clear the input so it wont show until next ticket is issued
// this.ticketNo = ''; // <-- THIS LINE CLEARS THE INPUT
// const cancelTicketData = {
// type: 'CANCEL_TICKET',
// ticketId: lastTicket.ticketId || '',
// barcodeId: lastTicket.barcodeId,
// cancelDate: new Date().toLocaleString(),
// totalAmount: lastTicket.totalAmount || 0
// };
// // 🔍 Console Preview
// console.log('🧾 [CANCEL TICKET LAYOUT]');
// console.log(`
// ========================================
// ⚠️ TICKET CANCELLED ⚠️
// ----------------------------------------
// Ticket ID : ${cancelTicketData.ticketId}
// Barcode ID : ${cancelTicketData.barcodeId}
// Cancelled At : ${cancelTicketData.cancelDate}
// Original Total: ₹${cancelTicketData.totalAmount}
// ========================================
// `);
// // 🖨️ Send to printer server
// fetch('http://localhost:9100/print', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify(cancelTicketData)
// })
// .then(r => r.text())
// .then(result => {
// console.log("✅ Cancel ticket print successful:", result);
// })
// .catch(error => {
// console.error("❌ Cancel ticket print failed:", error);
// });
// this.closeCancelPopup();
// } catch (e) {
// console.error("❌ Cancel API call failed:", e);
// this.cancelWarning = '❌ Cancel API call failed. Please try again.';
// }
// } else {
// console.warn('[❌ MISMATCH] Entered Ticket No does NOT match last stored barcode.');
// this.cancelWarning = '❌ Invalid ticket number. Please check and try again.';
// }
// }
// //--------------------------------COMPLETED THE CANCEL PRINT ---------------------------------------
//--------------------------------------- UPDATED CANCEL PRINT -------------------------------------------
@ -345,65 +226,253 @@ Original Total: ₹${cancelTicketData.totalAmount}
//--------------------------------------------PRINT PAYOUT TICKET -----------------------------------------------------------------
payoutWarning = ''; // show GUI message when payout response is not as expected
printPayoutTicket() {
console.log("🖨️ Print ticket clicked");
// alert(`Printing Payout Ticket No: ${this.payoutTicketNo}`);
const TicketNumber = this.payoutTicketNo;
// async printPayoutTicket() {
// console.log("🖨️ Print payout clicked");
// const ticketNo = this.payoutTicketNo?.toString().trim();
// if (!ticketNo) {
// console.warn("⚠️ No payout ticket number set.");
// return;
// }
// const userName = localStorage.getItem('userName') || 'Unknown';
// // Prepare request payload (same as your curl)
// const apiPayload = {
// ticketNo: ticketNo,
// voucherNo: "",
// memAcctNum: "",
// memAcctCardCode: "",
// moneyTyp: "C",
// btId: "0485", // replace with dynamic btId if needed
// usrId: "341" // replace with dynamic usrId if needed
// };
// console.log("📡 Sending payout API request:", apiPayload);
// try {
// const apiUrl = "http://localhost:8086/payout/ticket?debug=1";
// const resp = await fetch(apiUrl, {
// method: "POST",
// headers: { "Content-Type": "application/json" },
// body: JSON.stringify(apiPayload)
// });
// if (!resp.ok) {
// console.error("❌ Payout API HTTP error:", resp.status, resp.statusText);
// return;
// }
// const json = await resp.json();
// console.log("📩 Payout API response JSON:", json);
// // ✅ Save only the response (no request) to localStorage
// try {
// localStorage.setItem("payout", JSON.stringify(json));
// console.log("[localStorage] saved payout response only");
// } catch (e) {
// console.warn("⚠️ Failed to save payout to localStorage:", e);
// }
// if (!json.ok) {
// console.error("❌ Payout API returned ok: false -", json.error || json);
// return;
// }
// // ✅ Load the payout response from localStorage
// let payoutResp: any = null;
// try {
// const stored = localStorage.getItem("payout");
// if (stored) payoutResp = JSON.parse(stored);
// } catch (e) {
// console.warn("⚠️ Failed to parse stored payout:", e);
// }
// // Default dividend fallback
// let dividend = "0";
// if (payoutResp && payoutResp.data && typeof payoutResp.data.cashAmount !== "undefined") {
// dividend = String(payoutResp.data.cashAmount);
// }
// // Success: proceed to build print payload
// const backendData = json.data || {};
// const printData = {
// type: 'payout',
// ticketNumber: ticketNo,
// printedBy: userName,
// dividend: dividend,
// backend: backendData
// };
// const layoutPreview = `
// -------------------------------
// 🎉 PAYOUT TICKET 🎉
// -------------------------------
// Ticket No : ${printData.ticketNumber}
// Dividend : ${printData.dividend}
// Printed By : ${printData.printedBy}
// Backend Amt : ${backendData.cashAmount ?? 'N/A'}
// User Name : ${backendData.userName ?? 'N/A'}
// Date : ${new Date().toLocaleString()}
// -------------------------------
// 💸 Thank you for playing 💸
// -------------------------------
// `;
// console.log("[🧾 PAYOUT LAYOUT PREVIEW]");
// console.log(layoutPreview);
// try {
// const printResp = await fetch('http://localhost:9100/print', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify(printData)
// });
// if (!printResp.ok) throw new Error(`Printer HTTP ${printResp.status}`);
// const printResult = await printResp.text();
// console.log("✅ Payout print successful:", printResult);
// } catch (printErr) {
// console.error("❌ Payout print failed:", printErr);
// }
// this.closePayoutPopup();
// } catch (err) {
// console.error("❌ Payout API call failed:", err);
// }
// }
async printPayoutTicket() {
console.log("🖨️ Print payout clicked");
this.payoutWarning = '';
const ticketNo = this.payoutTicketNo?.toString().trim();
if (!ticketNo) {
console.warn("⚠️ No payout ticket number set.");
this.payoutWarning = '❌ No payout ticket number set.';
return;
}
const userName = localStorage.getItem('userName') || 'Unknown';
const printData = {
TicketNumber: TicketNumber,
printedBy: userName,
Dividend: '10'
// Prepare request payload
const apiPayload = {
ticketNo: ticketNo,
voucherNo: "",
memAcctNum: "",
memAcctCardCode: "",
moneyTyp: "C",
btId: "0485", // replace with dynamic btId if needed
usrId: "341" // replace with dynamic usrId if needed
};
// 🧾 Log the formatted ticket layout before printing
const layoutPreview = `
console.log("📡 Sending payout API request:", apiPayload);
try {
const apiUrl = "http://localhost:8086/payout/ticket?debug=1";
const resp = await fetch(apiUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(apiPayload)
});
if (!resp.ok) {
console.error("❌ Payout API HTTP error:", resp.status, resp.statusText);
this.payoutWarning = `❌ Payout API HTTP ${resp.status}`;
return;
}
const json = await resp.json();
console.log("📩 Payout API response JSON:", json);
// Save only the response (no request) to localStorage
try {
localStorage.setItem("payout", JSON.stringify(json));
console.log("[localStorage] saved payout response only");
} catch (e) {
console.warn("⚠️ Failed to save payout to localStorage:", e);
}
// If API returned ok:false -> show message and stop
if (!json.ok) {
console.error("❌ Payout API returned ok: false -", json.error || json);
this.payoutWarning = `❌ Payout failed: ${json.error ?? 'server error'}`;
return;
}
// Accept either shape:
// - json.data.cashAmount (nested)
// - json.cashAmount (flat)
const nestedCash = json.data && typeof json.data.cashAmount !== 'undefined' ? json.data.cashAmount : undefined;
const flatCash = typeof json.cashAmount !== 'undefined' ? json.cashAmount : undefined;
// If neither contains cashAmount, show GUI message and abort print
if (typeof nestedCash === 'undefined' && typeof flatCash === 'undefined') {
console.warn("Payout response missing cashAmount in both expected places. Ask user to retry.");
this.payoutWarning = '⚠️ Payout incomplete — server not responding correctly. Please try again.';
return;
}
// Use whichever exists (prefer nested)
const cashAmount = (typeof nestedCash !== 'undefined') ? nestedCash : flatCash;
const dividend = String(cashAmount ?? 0);
// Proceed to print using the resolved dividend and preserve backend data for printer if needed
const backendData = json.data ? json.data : { ...json }; // if flat, put fields at top-level into backendData
const printData = {
type: 'payout',
ticketNumber: ticketNo,
printedBy: userName,
dividend: dividend,
backend: backendData
};
const layoutPreview = `
-------------------------------
🎉 PAYOUT TICKET 🎉
-------------------------------
Ticket No : ${printData.TicketNumber}
Dividend : ${printData.Dividend}
Ticket No : ${printData.ticketNumber}
Dividend : ${printData.dividend}
Printed By : ${printData.printedBy}
Backend Amt : ${backendData.cashAmount ?? 'N/A'}
User Name : ${backendData.userName ?? 'N/A'}
Date : ${new Date().toLocaleString()}
-------------------------------
💸 Thank you for playing 💸
-------------------------------
`;
console.log("[🧾 TICKET LAYOUT PREVIEW]");
console.log(layoutPreview);
console.log("[🧾 PAYOUT LAYOUT PREVIEW]");
console.log(layoutPreview);
// 🖨️ Send the print request to 9100
const payload = {
type: 'payout',
ticketNumber: printData.TicketNumber,
printedBy: printData.printedBy,
dividend: printData.Dividend
};
try {
const printResp = await fetch('http://localhost:9100/print', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(printData)
});
fetch('http://localhost:9100/print', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
.then(response => {
if (!response.ok) throw new Error(`Printer error: ${response.status}`);
return response.text();
})
.then(result => {
console.log("✅ Print successful:", result);
})
.catch(error => {
console.error("❌ Print failed:", error);
});
if (!printResp.ok) throw new Error(`Printer HTTP ${printResp.status}`);
const printResult = await printResp.text();
console.log("✅ Payout print successful:", printResult);
} catch (printErr) {
console.error("❌ Payout print failed:", printErr);
this.payoutWarning = '❌ Print failed. Check printer server.';
}
this.closePayoutPopup();
// close payout modal only after successful print (or you can still close even if print failed)
this.closePayoutPopup();
} catch (err) {
console.error("❌ Payout API call failed:", err);
this.payoutWarning = '❌ Payout API call failed. Please try again.';
}
}
openDepositPopup() {
this.depositClick.emit();
this.showDeposit = true;
@ -417,6 +486,7 @@ Date : ${new Date().toLocaleString()}
this.depositWarning = '';
}
//----------------------------PRINT PAYOUT TICKET ENDS -------------------------------------------------------
@ -658,3 +728,4 @@ objectKeys = Object.keys;
}
}