fix : added print and proper enter logic to wsp

This commit is contained in:
karthik 2025-08-14 13:05:25 +05:30
parent 554fdffa23
commit 200360cb68
2 changed files with 126 additions and 70 deletions

View File

@ -147,8 +147,6 @@ export class MiddleSectionComponent implements OnInit, OnDestroy {
} }
} }
parseWinLabelsToRows(winLabels: string, fallbackTotal?: number): SelectionData[] { parseWinLabelsToRows(winLabels: string, fallbackTotal?: number): SelectionData[] {
return (winLabels.split('\n') as string[]) return (winLabels.split('\n') as string[])
.map(line => { .map(line => {
@ -188,11 +186,9 @@ parseWinLabelsToRows(winLabels: string, fallbackTotal?: number): SelectionData[]
} }
//-------------------------------------------------REPEAT PRINT LOGIC ----------------------------------------------- //-----------------------REPEAT PRINT LOGIC ----------------------------------
printRepeat() {
console.log('🖨️ [DEBUG] Printing ticket...');
printRepeat() {
console.log('🖨️ [DEBUG] Printing ticket...');
const userName = localStorage.getItem('userName') || 'Unknown'; const userName = localStorage.getItem('userName') || 'Unknown';
@ -207,15 +203,15 @@ printRepeat() {
const millis = String(now.getMilliseconds()).padStart(3, '0'); const millis = String(now.getMilliseconds()).padStart(3, '0');
const barcodeId = `1111${day}${month}${year}${timeStr}${millis}`; const barcodeId = `1111${day}${month}${year}${timeStr}${millis}`;
const printableRows = this.filledRows const printableRows = this.filledRows
.filter(row => row.label && row.numbers.length > 0 && row.total > 0) .filter(row => row.label && row.numbers.length > 0 && row.total > 0)
.map(row => { .map(row => {
const horses = Array.isArray(row.numbers) ? row.numbers.join(',') : row.numbers; const horses = Array.isArray(row.numbers) ? row.numbers.join(',') : row.numbers;
return `${row.label.padEnd(6)} ${horses.padEnd(15)} * ${String(row.value).padEnd(3)}${row.total}`; return `${row.label.padEnd(6)} ${horses.padEnd(15)} * ${String(row.value).padEnd(3)}${row.total}`;
}) })
.join('\n'); .join('\n');
const ticketContent = ` const ticketContent = `
BTC Race Ticket BTC Race Ticket
${printableRows} ${printableRows}
@ -223,31 +219,59 @@ Barcode ID : ${barcodeId}
Printed by : ${userName} Printed by : ${userName}
Date : ${now.toLocaleString()}`; Date : ${now.toLocaleString()}`;
console.log('%c\n' + ticketContent, 'font-family: monospace; color: green'); console.log('%c\n' + ticketContent, 'font-family: monospace; color: green');
const payload = { // ✅ Send to print server
type: 'repeat', const payload = {
type: 'repeat',
printedBy: userName, printedBy: userName,
barcodeId, // send barcode separately barcodeId, // send barcode separately
content: ticketContent, content: ticketContent,
timestamp: now.toLocaleString() timestamp: now.toLocaleString()
}; };
fetch('http://localhost:9100/print', { fetch('http://localhost:9100/print', {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload) body: JSON.stringify(payload)
}) })
.then(response => { .then(response => {
if (!response.ok) throw new Error(`Printer error: ${response.status}`); if (!response.ok) throw new Error(`Printer error: ${response.status}`);
return response.text(); return response.text();
}) })
.then(result => { .then(result => {
console.log("✅ Repeat ticket print successful:", result); console.log("✅ Repeat ticket print successful:", result);
}) })
.catch(error => { .catch(error => {
console.error("❌ Repeat ticket print failed:", error); console.error("❌ Repeat ticket print failed:", error);
}); });
// --- Update localStorage for transaction summary like normal print ---
// 1. Increment printClickCount
let clickCount = Number(localStorage.getItem('printClickCount') || '0');
clickCount += 1;
localStorage.setItem('printClickCount', clickCount.toString());
// 2. Add a new ticket entry to localTickets (type: 'ticket', totalAmount)
try {
const existingTicketsStr = localStorage.getItem('localTickets');
const existingTickets = existingTicketsStr ? JSON.parse(existingTicketsStr) : [];
// Calculate totalAmount for this repeat print
const totalAmount = this.filledRows
.filter(row => row.label && row.numbers.length > 0 && row.total > 0)
.reduce((sum, row) => sum + (row.total || 0), 0);
const ticketEntry = {
type: 'ticket',
printedBy: userName,
totalAmount,
content: ticketContent,
};
existingTickets.push(ticketEntry);
localStorage.setItem('localTickets', JSON.stringify(existingTickets));
} catch (error) {
console.error('❌ Failed to update localTickets for repeat print:', error);
}
// Hide Confirm and Print buttons before clearing selections // Hide Confirm and Print buttons before clearing selections
this.showConfirmButton = false; this.showConfirmButton = false;
@ -261,8 +285,6 @@ Date : ${now.toLocaleString()}`;
//------------------------------PRINT REPEAT ENDED HERE-----------------------------------------------------S //------------------------------PRINT REPEAT ENDED HERE-----------------------------------------------------S
erase() { erase() {
this.selectionService.clearSelections(); this.selectionService.clearSelections();
this.resetSelections(); this.resetSelections();

View File

@ -586,43 +586,59 @@ if (this.twoGroupLabels.includes(this.selectedLabel || '')) {
} }
onPadEnter() { onPadEnter() {
// Disable Enter if maxRowsReached if (this.maxRowsReached) return;
if (this.maxRowsReached) return;
if (!this.canPrint) { if (!this.canPrint) {
this.print();
}
const value = parseFloat(this.padValue) || 0;
if (this.selectedLabel === 'WSP') {
const labels = ['WIN', 'SHP', 'PLC'];
const targetLabel = labels[this.wspTicketStage];
const updatedSelections = this.selectionService.getSelections().map(sel => {
if (sel.label === targetLabel && JSON.stringify(sel.numbers) === JSON.stringify(this.selectedNumbers)) {
return {
...sel,
value,
total: value * (sel.numbers?.length || 0) * 10
};
}
return sel;
});
this.selectionService.setSelections(updatedSelections);
// Move to next stage
this.wspTicketStage = (this.wspTicketStage + 1) % 3;
this.padValue = '';
this.updateCanPrint();
return;
}
// ✅ Default path: finalize row and reset input
this.print(); this.print();
} }
const value = parseFloat(this.padValue) || 0;
if (this.selectedLabel === 'WSP') {
const labels = ['WIN', 'SHP', 'PLC'];
const targetLabel = labels[this.wspTicketStage];
const selections = this.selectionService.getSelections();
// Find the current WSP row to ensure numbers are synchronized
const currentWSPRow = selections.find(sel => sel.label === targetLabel);
if (currentWSPRow) {
this.selectedNumbers = [...currentWSPRow.numbers]; // Synchronize selectedNumbers
}
const updatedSelections = selections.map(sel => {
if (sel.label === targetLabel) {
const total = value * (sel.numbers?.length || 0) * 10;
return {
...sel,
value,
total
};
}
return sel;
});
this.selectionService.setSelections(updatedSelections);
// Only increment stage if not at the last stage (PLC)
if (this.wspTicketStage < 2) {
this.wspTicketStage++;
// Update selectedNumbers for the next stage
const nextLabel = labels[this.wspTicketStage];
const nextWSPRow = updatedSelections.find(sel => sel.label === nextLabel);
if (nextWSPRow) {
this.selectedNumbers = [...nextWSPRow.numbers];
}
}
this.padValue = '';
this.updateCanPrint();
return;
}
this.print();
}
onShashEnter() { onShashEnter() {
if (this.selectedLabel === 'TAN' && this.isBoxed) { if (this.selectedLabel === 'TAN' && this.isBoxed) {
return; return;
@ -841,6 +857,24 @@ enterPadVal(key: string) {
// At least one valid row in finalized selections or current row // At least one valid row in finalized selections or current row
const selections = this.selectionService.getSelections(); const selections = this.selectionService.getSelections();
const currentRow = this.selectionService.getCurrentRow(); const currentRow = this.selectionService.getCurrentRow();
if (this.selectedLabel === 'WSP') {
// For WSP, require all three rows (WIN, SHP, PLC) to have valid numbers and values >= 1
const wspLabels = ['WIN', 'SHP', 'PLC'];
const wspSelections = selections.filter(sel => wspLabels.includes(sel.label));
// Check if we are at the last stage (PLC) and all rows are valid
const allWSPRowsValid = wspSelections.length === 3 && wspSelections.every(row =>
row.label &&
row.numbers &&
row.numbers.length > 0 &&
row.value >= 1 &&
row.total > 0
);
return this.wspTicketStage === 2 && allWSPRowsValid;
}
// For non-WSP, keep existing logic: any valid row enables printing
const hasValidRow = selections.some( const hasValidRow = selections.some(
row => !!row.label && !!row.numbers && row.numbers.length > 0 && row.value > 0 && row.total > 0 row => !!row.label && !!row.numbers && row.numbers.length > 0 && row.value > 0 && row.total > 0
) || ( ) || (