fix : Wsp fixed printer Race no Web socket etc.....

This commit is contained in:
Sibin Sabu 2025-08-06 12:08:23 +05:30
parent 6df4c49d65
commit 6b8206c3fb
5 changed files with 209 additions and 25 deletions

View File

@ -315,7 +315,7 @@ export class SelectionService {
if (!base.numbers.length || base.value <= 0) return [];
return ['WIN', 'SHP', 'THP'].map(label => {
return ['WIN', 'SHP', 'PLC'].map(label => {
const newRow: SelectionData = {
...base,
label,

View File

@ -38,8 +38,14 @@
</div>
</div>
<footer class="footer">
<!-- <footer class="footer">
<div class="live-data-text">Live Data: </div>
</footer>
</div>
</div> -->
<footer class="footer" [ngStyle]="{ 'background-color': isConnected ? '#d1ffd1' : '#ffcccc' }">
<div class="live-data-text">
Live Data: {{ message || 'Disconnected' }}
</div>
</footer>

View File

@ -1,5 +1,6 @@
import { Component, Input } from '@angular/core';
import { CommonModule } from '@angular/common';
import { WebsocketService } from '../../service/websocket.service'; // adjust path if needed
@Component({
selector: 'app-shared-table',
@ -8,8 +9,28 @@ import { CommonModule } from '@angular/common';
templateUrl: './shared-table.component.html',
styleUrls: ['./shared-table.component.css']
})
// export class SharedTableComponent {
// @Input() summaryRows: any[] = [];
// @Input() rows: any[] = [];
// @Input() totalAmount: string = '';
// }
export class SharedTableComponent {
@Input() summaryRows: any[] = [];
@Input() rows: any[] = [];
@Input() totalAmount: string = '';
message = '';
isConnected = false;
constructor(private websocketService: WebsocketService) {}
ngOnInit() {
this.websocketService.message$.subscribe(msg => {
this.message = msg;
});
this.websocketService.isConnected$.subscribe(status => {
this.isConnected = status;
});
}
}

View File

@ -85,6 +85,9 @@ export class TouchPadMenuComponent implements OnInit, OnDestroy {
private labelRestrictionService: LabelRestrictionService
) {}
selectedRaceNumber: string = '1'; // Default
ngOnInit() {
this.runnerCountSubscription = this.sharedStateService.runnerCount$.subscribe(count => {
this.runnerCount = count || 12;
@ -113,20 +116,36 @@ export class TouchPadMenuComponent implements OnInit, OnDestroy {
});
// --- NEW: Subscribe to race changes ---
this.sharedStateService.selectedRace$.subscribe(() => {
this.setActualRunners();
// If currently in a multi-leg pool, update the numbers for the active leg
if (this.currentPool && this.multiLegLabels.includes(this.selectedLabel || '')) {
this.updateLegRaceDisplay(this.currentPool);
const runnerCount = this.getRunnerCountForLeg(this.multiLegBaseRaceIdx, this.multiLegStage);
this.runnerCount = runnerCount || 12;
this.numbers = Array.from({ length: 30 }, (_, i) => i + 1);
this.numbersFlat = this.numberRows.flat();
this.actualRunners = this.getActualRunnersForCurrentPoolLeg();
} else {
this.setActualRunners();
}
});
// this.sharedStateService.selectedRace$.subscribe(() => {
// this.setActualRunners();
// // If currently in a multi-leg pool, update the numbers for the active leg
// if (this.currentPool && this.multiLegLabels.includes(this.selectedLabel || '')) {
// this.updateLegRaceDisplay(this.currentPool);
// const runnerCount = this.getRunnerCountForLeg(this.multiLegBaseRaceIdx, this.multiLegStage);
// this.runnerCount = runnerCount || 12;
// this.numbers = Array.from({ length: 30 }, (_, i) => i + 1);
// this.numbersFlat = this.numberRows.flat();
// this.actualRunners = this.getActualRunnersForCurrentPoolLeg();
// } else {
// this.setActualRunners();
// }
// });
this.sharedStateService.selectedRace$.subscribe(race => {
this.selectedRaceNumber = String(race || '1');
this.setActualRunners();
if (this.currentPool && this.multiLegLabels.includes(this.selectedLabel || '')) {
this.updateLegRaceDisplay(this.currentPool);
const runnerCount = this.getRunnerCountForLeg(this.multiLegBaseRaceIdx, this.multiLegStage);
this.runnerCount = runnerCount || 12;
this.numbers = Array.from({ length: 30 }, (_, i) => i + 1);
this.numbersFlat = this.numberRows.flat();
this.actualRunners = this.getActualRunnersForCurrentPoolLeg();
} else {
this.setActualRunners();
}
});
}
ngOnDestroy() {
@ -306,7 +325,7 @@ export class TouchPadMenuComponent implements OnInit, OnDestroy {
//----------------------------------ADDED THIS -----------------------------------------------------
if (label === 'WSP') {
const wspLabels = ['WIN', 'SHP', 'THP'];
const wspLabels = ['WIN', 'SHP', 'PLC'];
this.wspTicketStage = 0;
this.selectionService.finalizeCurrentRow();
const currentSelections = this.selectionService.getSelections();
@ -446,7 +465,7 @@ export class TouchPadMenuComponent implements OnInit, OnDestroy {
// ✅ Special logic: If WSP, mirror number to WIN, SHP, and THP
if (this.selectedLabel === 'WSP') {
const labelsToUpdate = ['WIN', 'SHP', 'THP'];
const labelsToUpdate = ['WIN', 'SHP', 'PLC'];
const selections = this.selectionService.getSelections();
const updated = selections.map(sel => {
if (labelsToUpdate.includes(sel.label)) {
@ -496,7 +515,7 @@ export class TouchPadMenuComponent implements OnInit, OnDestroy {
const value = parseFloat(this.padValue) || 0;
if (this.selectedLabel === 'WSP') {
const labels = ['WIN', 'SHP', 'THP'];
const labels = ['WIN', 'SHP', 'PLC'];
const targetLabel = labels[this.wspTicketStage];
const updatedSelections = this.selectionService.getSelections().map(sel => {
@ -616,7 +635,7 @@ export class TouchPadMenuComponent implements OnInit, OnDestroy {
const value = parseFloat(this.padValue) || 0;
if (this.selectedLabel === 'WSP') {
const labels = ['WIN', 'SHP', 'THP'];
const labels = ['WIN', 'SHP', 'PLC'];
const targetLabel = labels[this.wspTicketStage];
const updatedSelections = this.selectionService.getSelections().map(sel => {
@ -691,6 +710,49 @@ export class TouchPadMenuComponent implements OnInit, OnDestroy {
this.resetSelections();
}
//---------Helper Function-----------
getHorseNumbersForSelectedRace(): number[] {
try {
const raceCardDataStr = localStorage.getItem('raceCardData');
console.log('[DEBUG] raceCardDataStr:', raceCardDataStr);
if (!raceCardDataStr) {
console.warn('[DEBUG] No raceCardData found in localStorage');
return [];
}
const raceCardData = JSON.parse(raceCardDataStr);
console.log('[DEBUG] Parsed raceCardData:', raceCardData);
const selectedRaceIdx = parseInt(this.selectedRaceNumber, 10) - 1; // Convert '1' → 0
console.log('[DEBUG] selectedRaceNumber:', this.selectedRaceNumber);
console.log('[DEBUG] selectedRaceIdx:', selectedRaceIdx);
const races = raceCardData.raceVenueRaces?.races || [];
console.log('[DEBUG] races array:', races);
if (races[selectedRaceIdx]) {
console.log('[DEBUG] Horse numbers for selected race:', races[selectedRaceIdx]);
return races[selectedRaceIdx];
} else {
console.warn('[DEBUG] No horses found for selectedRaceIdx:', selectedRaceIdx);
return [];
}
} catch (err) {
console.error('[DEBUG] Error parsing raceCardData:', err);
return [];
}
}
//-------------------PRINT LOGIC----------------------------------------
printTicket() {
const selectionsTotal = this.currentSelections.reduce((sum, sel) => sum + sel.total, 0);
@ -698,7 +760,7 @@ printTicket() {
this.showLimitPopup = true;
return;
}
console.log('[DEBUG] Horse numbers for selected race:', this.getHorseNumbersForSelectedRace());
//--------------------Added Print here
console.log("🖨️ Print ticket clicked");
@ -743,17 +805,34 @@ printTicket() {
const fullYear = now.getFullYear();
const timeStr = now.toTimeString().slice(0, 8).replace(/:/g, '');
const millis = now.getMilliseconds().toString().padStart(3, '0');
const ticketId = `${venue}/${fullYear}${month}${day}/1`;
// const ticketId = `${venue}/${fullYear}${month}${day}/1`;
const ticketId = `${venue}/${fullYear}${month}${day}/${this.selectedRaceNumber}`;
const barcodeId = `1111${day}${month}${year}${timeStr}${millis}`;
// const winLabels = allRows.map(row => {
// const label = row.label.padEnd(10);
// const numbers = row.numbers.join(',').padEnd(15);
// const value = (`*${row.value || 0}`).padEnd(8);
// const total = `Rs ${row.total || 0}`.padStart(8);
// return `${label}${numbers}${value}${total}`;
// }).join('\n');
const winLabels = allRows.map(row => {
let displayNumbers = row.numbers;
// 🔁 If 'F', expand to all horses
if (row.numbers.length === 1 && row.numbers[0] === 'F') {
displayNumbers = this.getHorseNumbersForSelectedRace().map(n => n.toString());
}
const label = row.label.padEnd(10);
const numbers = row.numbers.join(',').padEnd(15);
const numbers = displayNumbers.join(',').padEnd(15);
const value = (`*${row.value || 0}`).padEnd(8);
const total = `Rs ${row.total || 0}`.padStart(8);
return `${label}${numbers}${value}${total}`;
}).join('\n');
// ✅ Print preview
const printData = {
ticketId,
@ -795,17 +874,29 @@ printTicket() {
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
// ---------------------sending data to backend ---------------------------------
fetch('http://192.168.1.12:8083/api/tickets', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
//----------------------------------------ends here --------------------------
.then(response => {
if (!response.ok) {
throw new Error(`Printer error: ${response.status}`);
}
return response.text();
})
.then(result => {
.then(result => {
console.log("✅ Print successful:", result);
this.erase(); // ✅ Clear selections after successful print
})
.catch(error => {
console.error("❌ Print failed:", error);
this.erase(); // ✅ Clear selections after successful print
});

View File

@ -0,0 +1,66 @@
// import { Injectable } from '@angular/core';
// import { Subject } from 'rxjs';
// @Injectable({
// providedIn: 'root'
// })
// export class WebsocketService {
// private socket: WebSocket;
// public message$: Subject<string> = new Subject<string>();
// constructor() {
// // ✅ Connect to your Java WebSocket server at port 8000
// this.socket = new WebSocket('ws://localhost:8000');
// this.socket.onopen = () => {
// console.log('✅ Connected to WebSocket server');
// };
// this.socket.onmessage = (event) => {
// console.log('📩 Received:', event.data);
// this.message$.next(event.data);
// };
// this.socket.onerror = (error) => {
// console.error('❌ WebSocket error:', error);
// };
// this.socket.onclose = () => {
// console.warn('⚠️ WebSocket connection closed');
// };
// }
// }
import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class WebsocketService {
private socket: WebSocket;
public message$: Subject<string> = new Subject<string>();
public isConnected$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor() {
this.socket = new WebSocket('ws://localhost:8000');
this.socket.onopen = () => {
console.log('✅ Connected to WebSocket server');
this.isConnected$.next(true);
};
this.socket.onmessage = (event) => {
console.log('📩 Received:', event.data);
this.message$.next(event.data);
};
this.socket.onerror = (error) => {
console.error('❌ WebSocket error:', error);
};
this.socket.onclose = () => {
console.warn('⚠️ WebSocket connection closed');
this.isConnected$.next(false); // ⛔ disconnected
};
}
}