feat: implement direct database-driven KDS status tracking and frontend UI for table order monitoring

This commit is contained in:
2026-05-24 17:05:03 +02:00
parent 0396190927
commit 58fae2f0e6
9 changed files with 1400 additions and 1027 deletions

12
ai.txt
View File

@@ -2,16 +2,7 @@ Idea aplikacj.
W restauracji na kazdym stoliku będize naklejka z inwydidualnym kodem QR.
Klient bedzie mógł zeskanować kod QR i wejść do aplikacji.
W aplikacji na ten moment chciałbym opracować następujące funkcję:
- podgląd aktualnych dać i napojów nabitych na tym stoliku wraz z ich stanem realizacji.
Będziemy to wiedizeć dzięki odpytywaniu ekranów KDS, które są umieszczone na kuchni.
Ideą jest to, aby każdy klient mógł sprawdzić, czy jego zamówione dania jeszcze są w toku czy są już zrealizowane i zaraz kelner dostarczy je do stolika.
Obecnie aplikacja podsłuchuje service workera tych ekranów z dostaje jsony, któe potem interpretuje. Ale jest to zawodny proces.
Chciałbym przenieść sposób pozyskiwania danych na odczyt (tylko wodczyt) danych z bazy danych.
Potrzebuję pomocy w tym aby odpowiednio zinterpretować dane w bazie.
Znam już jej strukturę oraz wiem co, i w ktorej tabeli bazy się znajduje.
Dane do bazy danych Microsoft SQL
$serverName = '192.168.20.20';
@@ -938,9 +929,6 @@ Pozycje danego rachunku znajdują się w tabeli: dbo.NGastroDTRachunekPozycja
"order_reason": "timestamp\/rowversion"
},
Chciałbym abyśmy zaczeli korzystać z bazy danych do oczytu aktualnych zamówień KDS dla danego stolika. Przeanalizuj to co Ci dałem. Nigdy nie zgaduj żadnych nazw. Jeśli potrzebujemy naze tabeli, jej schemat lub inne dane - poprośmnie o nie a ja je dostarcze.
Mam tez procedury, które znalazłem na bazie. Nie jestem pewien czy one nam pomogą - ale może będą przydatne.
CREATE PROCEDURE [dbo].[PV_WSKDSGetBill]
@cGetRequestTemplate bit = 0,

122
append_css.js Normal file
View File

@@ -0,0 +1,122 @@
const fs = require('fs');
const css = `
/* Wariant 2: Uciekająca Kura */
.anim-run {
position: relative;
width: 100px;
height: 40px;
overflow: hidden;
display: flex;
align-items: center;
}
.anim-run .chicken {
position: absolute;
font-size: 24px;
animation: runLeft 3s infinite linear;
}
.anim-run .chef {
position: absolute;
font-size: 28px;
animation: runLeftChef 3s infinite linear;
}
@keyframes runLeft {
0% { transform: translateX(100px); }
100% { transform: translateX(-40px); }
}
@keyframes runLeftChef {
0% { transform: translateX(140px); }
100% { transform: translateX(0px); }
}
/* Wariant 3: Kura w garnku */
.anim-pot {
position: relative;
width: 40px;
height: 40px;
display: flex;
align-items: flex-end;
justify-content: center;
}
.anim-pot .pot-emoji {
font-size: 32px;
z-index: 2;
}
.anim-pot .chicken-head {
position: absolute;
font-size: 24px;
bottom: 10px;
z-index: 1;
animation: peekaboo 4s infinite ease-in-out;
}
@keyframes peekaboo {
0%, 100%, 80% { transform: translateY(15px); opacity: 0; }
30%, 50% { transform: translateY(0px); opacity: 1; }
}
/* Wariant 4: Latająca pizza */
.anim-pizza {
position: relative;
width: 50px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.anim-pizza .chef-pizza {
font-size: 28px;
z-index: 1;
}
.anim-pizza .pizza-emoji {
position: absolute;
font-size: 20px;
top: 0;
right: 0;
z-index: 2;
animation: spinPizza 2s infinite ease-in-out;
}
@keyframes spinPizza {
0%, 100% { transform: translateY(0) rotate(0deg); }
50% { transform: translateY(-15px) rotate(360deg); }
}
/* Wariant 5: Nerwowa świnka */
.anim-pig {
position: relative;
width: 60px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.anim-pig .pig-emoji {
font-size: 28px;
animation: nervous 0.2s infinite;
}
.anim-pig .sweat-emoji {
position: absolute;
font-size: 16px;
top: 0;
right: 15px;
animation: sweatDrop 1s infinite;
}
.anim-pig .knife-emoji {
position: absolute;
font-size: 20px;
right: -10px;
animation: knifeStab 2s infinite ease-in-out;
}
@keyframes nervous {
0%, 100% { transform: translateX(0); }
50% { transform: translateX(2px); }
}
@keyframes sweatDrop {
0% { transform: translateY(0); opacity: 1; }
100% { transform: translateY(10px); opacity: 0; }
}
@keyframes knifeStab {
0%, 100% { transform: translateX(10px); opacity: 0; }
50% { transform: translateX(0px); opacity: 1; }
}
`;
fs.appendFileSync('public/assets/css/stolik2_api.css', css);
console.log("Appended CSS");

24
extract.js Normal file
View File

@@ -0,0 +1,24 @@
const fs = require('fs');
const html = fs.readFileSync('public/stolik2_api.html', 'utf8');
// Match first style and script tags
const cssMatch = html.match(/<style>([\s\S]*?)<\/style>/);
const jsMatch = html.match(/<script>([\s\S]*?)<\/script>/);
if(cssMatch) {
fs.writeFileSync('public/assets/css/stolik2_api.css', cssMatch[1].trim());
}
if(jsMatch) {
fs.writeFileSync('public/assets/js/stolik2_api.js', jsMatch[1].trim());
}
let newHtml = html;
if(cssMatch) {
newHtml = newHtml.replace(/<style>[\s\S]*?<\/style>/, '<link rel="stylesheet" href="assets/css/stolik2_api.css">');
}
if(jsMatch) {
newHtml = newHtml.replace(/<script>[\s\S]*?<\/script>/, '<script src="assets/js/stolik2_api.js"></script>');
}
fs.writeFileSync('public/stolik2_api.html', newHtml);
console.log("Extraction complete.");

View File

@@ -0,0 +1,628 @@
:root {
--primary: #e2b07e; /* Ciepłe złoto/miedź */
--bg: #0f0f11;
--surface: #1c1c1f;
--surface-light: #2c2c2e;
--text-main: #ffffff;
--text-muted: #9a9a9e;
--success: #4ade80;
--accent: #f59e0b;
--radius: 20px;
}
* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
body {
margin: 0;
font-family: 'Plus Jakarta Sans', sans-serif;
background-color: var(--bg);
color: var(--text-main);
line-height: 1.6;
overflow-x: hidden;
}
/* --- LOADER SCREEN --- */
#loadingScreen {
position: fixed;
inset: 0;
z-index: 100;
background: var(--bg);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px;
text-align: center;
transition: opacity 0.5s ease, visibility 0.5s;
}
.loader-icon {
width: 80px;
height: 80px;
border: 3px solid var(--surface-light);
border-top: 3px solid var(--primary);
border-radius: 50%;
animation: spin 1s cubic-bezier(0.4, 0, 0.2, 1) infinite;
margin-bottom: 24px;
}
.loader-text h2 {
font-family: 'Playfair Display', serif;
margin: 0 0 8px;
color: var(--primary);
}
.loader-msg { color: var(--text-muted); font-size: 14px; min-height: 20px; }
/* --- MAIN LAYOUT --- */
.container {
max-width: 500px;
margin: 0 auto;
padding: 24px 16px 100px;
}
header {
text-align: center;
margin-bottom: 32px;
padding-top: 20px;
}
.logo-text {
font-family: 'Playfair Display', serif;
font-size: 28px;
margin: 0;
background: linear-gradient(to right, #fff, var(--primary));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.table-badge {
display: inline-block;
background: var(--surface-light);
padding: 6px 16px;
border-radius: 99px;
font-size: 13px;
font-weight: 600;
margin-top: 8px;
color: var(--primary);
border: 1px solid rgba(226, 176, 126, 0.2);
}
/* --- STATUS CARD --- */
.status-card {
background: var(--surface);
border-radius: var(--radius);
padding: 24px;
margin-bottom: 24px;
position: relative;
overflow: hidden;
box-shadow: 0 20px 40px rgba(0,0,0,0.4);
border: 1px solid rgba(255,255,255,0.05);
}
.status-header {
display: flex;
justify-content: space-between;
align-items: flex-start;
margin-bottom: 20px;
}
.status-title {
font-size: 14px;
text-transform: uppercase;
letter-spacing: 1px;
color: var(--text-muted);
display: block;
margin-bottom: 4px;
}
.status-value {
font-size: 22px;
font-weight: 700;
color: var(--text-main);
}
.progress-container {
height: 8px;
background: var(--surface-light);
border-radius: 10px;
margin: 15px 0;
overflow: hidden;
}
.progress-bar {
height: 100%;
width: 0%;
background: linear-gradient(90deg, var(--primary), var(--accent));
box-shadow: 0 0 15px rgba(226, 176, 126, 0.4);
transition: width 1s cubic-bezier(0.4, 0, 0.2, 1);
}
/* --- ITEMS LIST --- */
.items-container h3 {
font-size: 18px;
margin: 0 0 16px 8px;
}
.item-card {
background: var(--surface);
margin-bottom: 12px;
padding: 16px;
border-radius: 16px;
display: flex;
justify-content: space-between;
align-items: center;
transition: transform 0.2s;
border-left: 4px solid var(--surface-light);
}
.item-card.ready { border-left-color: var(--success); }
.item-card.archived { opacity: 0.82; }
.history-section { margin-top: 26px; }
.history-note {
font-size: 12px;
color: var(--text-muted);
margin: 0 0 12px 8px;
line-height: 1.45;
}
.item-info { display: flex; flex-direction: column; }
.item-name { font-weight: 600; font-size: 16px; }
.item-meta { font-size: 12px; color: var(--text-muted); }
.item-qty {
background: var(--surface-light);
padding: 6px 12px;
border-radius: 10px;
font-weight: 700;
color: var(--primary);
}
/* --- EMPTY STATE --- */
.empty-state {
text-align: center;
padding: 40px 20px;
}
.empty-icon { font-size: 48px; margin-bottom: 16px; opacity: 0.5; }
/* --- ANIMATIONS --- */
@keyframes spin { to { transform: rotate(360deg); } }
.hidden { opacity: 0; visibility: hidden; pointer-events: none; display: none; }
.meta-footer {
font-size: 11px;
color: var(--text-muted);
margin-top: 20px;
text-align: center;
}
/* --- ACTION CARD --- */
.action-card {
background: var(--surface);
border-radius: var(--radius);
padding: 16px;
margin-bottom: 20px;
text-align: center;
box-shadow: 0 10px 30px rgba(0,0,0,0.3);
border: 1px solid rgba(255,255,255,0.05);
position: relative;
overflow: hidden;
}
.action-card h3 {
font-size: 15px;
margin: 0 0 12px;
text-transform: uppercase;
letter-spacing: 1px;
color: var(--text-muted);
}
.action-buttons {
display: flex;
flex-direction: row;
gap: 10px;
}
.btn {
font-family: inherit;
font-size: 15px;
font-weight: 600;
padding: 14px 20px;
border-radius: 12px;
border: none;
cursor: pointer;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
width: 100%;
display: flex;
justify-content: center;
align-items: center;
gap: 8px;
}
.action-btn {
flex-direction: column;
font-size: 13px;
line-height: 1.3;
padding: 14px 8px;
gap: 6px;
flex: 1;
}
.action-btn span {
font-size: 24px;
}
.btn-primary {
background: linear-gradient(135deg, var(--primary), var(--accent));
color: var(--bg);
box-shadow: 0 4px 15px rgba(226, 176, 126, 0.3);
}
.btn-primary:active {
transform: scale(0.98);
}
.btn-secondary {
background: var(--surface-light);
color: var(--primary);
border: 1px solid rgba(226, 176, 126, 0.2);
}
.btn-secondary:active {
transform: scale(0.98);
}
/* --- MODAL DIALOG --- */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(15, 15, 17, 0.85);
backdrop-filter: blur(8px);
z-index: 200;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
opacity: 0;
visibility: hidden;
transition: opacity 0.3s ease, visibility 0.3s;
}
.modal-overlay.active {
opacity: 1;
visibility: visible;
}
.modal-content {
background: var(--surface);
width: 100%;
max-width: 400px;
border-radius: 24px;
padding: 24px;
box-shadow: 0 20px 50px rgba(0,0,0,0.5);
border: 1px solid rgba(255,255,255,0.1);
transform: translateY(20px) scale(0.95);
transition: transform 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
.modal-overlay.active .modal-content {
transform: translateY(0) scale(1);
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
}
.modal-header h3 {
margin: 0;
font-size: 20px;
color: var(--primary);
font-family: 'Playfair Display', serif;
}
.close-btn {
background: transparent;
color: var(--text-muted);
border: none;
font-size: 28px;
cursor: pointer;
padding: 0;
line-height: 1;
transition: color 0.2s;
}
.close-btn:hover {
color: var(--text-main);
}
.step {
display: none;
animation: fadeInStep 0.4s ease forwards;
}
.step.active {
display: block;
}
@keyframes fadeInStep {
from { opacity: 0; transform: translateX(10px); }
to { opacity: 1; transform: translateX(0); }
}
.option-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-bottom: 24px;
}
.option-card {
background: var(--surface-light);
border: 1px solid rgba(226, 176, 126, 0.1);
border-radius: 16px;
padding: 20px;
text-align: center;
cursor: pointer;
transition: all 0.2s ease;
}
.option-card:hover {
background: rgba(226, 176, 126, 0.15);
transform: translateY(-2px);
}
.option-icon {
font-size: 32px;
margin-bottom: 8px;
display: block;
}
.option-label {
font-weight: 600;
font-size: 14px;
color: var(--text-main);
}
.input-group {
margin-bottom: 20px;
}
.input-label {
display: block;
font-size: 13px;
color: var(--text-muted);
margin-bottom: 8px;
}
.input-field {
width: 100%;
background: var(--bg);
border: 1px solid var(--surface-light);
color: var(--text-main);
padding: 14px;
border-radius: 12px;
font-family: inherit;
font-size: 16px;
transition: border-color 0.2s;
}
.input-field:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 2px rgba(226, 176, 126, 0.2);
}
.company-details {
background: var(--bg);
padding: 16px;
border-radius: 12px;
margin-bottom: 24px;
border: 1px solid var(--surface-light);
}
.company-input {
width: 100%;
background: transparent;
border: 1px solid transparent;
color: var(--text-main);
font-family: inherit;
font-size: 15px;
padding: 8px;
border-radius: 8px;
transition: all 0.2s;
}
.company-input:not([readonly]) {
border-color: var(--surface-light);
background: var(--surface-light);
}
.company-input:not([readonly]):focus {
outline: none;
border-color: var(--primary);
}
.company-input.muted {
color: var(--text-muted);
font-size: 13px;
}
/* --- TOAST --- */
.toast {
position: fixed;
bottom: 30px;
left: 50%;
transform: translateX(-50%) translateY(100px);
background: linear-gradient(135deg, var(--success), #22c55e);
color: var(--bg);
padding: 14px 28px;
border-radius: 30px;
font-weight: 700;
font-size: 15px;
box-shadow: 0 10px 30px rgba(74, 222, 128, 0.3);
opacity: 0;
transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55);
z-index: 300;
display: flex;
align-items: center;
gap: 10px;
}
.toast.active {
transform: translateX(-50%) translateY(0);
opacity: 1;
}
/* --- KITCHEN ANIMATION --- */
.kitchen-anim {
position: relative;
width: 40px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.pan-emoji {
font-size: 30px;
z-index: 2;
animation: panToss 1.5s infinite ease-in-out;
transform-origin: 70% 70%;
}
.fire-emoji {
position: absolute;
bottom: -5px;
left: 5px;
font-size: 24px;
z-index: 1;
animation: fireFlicker 0.4s infinite alternate;
}
@keyframes panToss {
0%, 100% { transform: rotate(0deg) translateY(0); }
50% { transform: rotate(-20deg) translateY(-8px); }
}
@keyframes fireFlicker {
0% { transform: scale(1) rotate(-3deg); opacity: 0.8; filter: drop-shadow(0 0 5px var(--accent)); }
100% { transform: scale(1.1) rotate(3deg); opacity: 1; filter: drop-shadow(0 0 10px var(--accent)); }
}
/* Wariant 2: Uciekająca Kura */
.anim-run {
position: relative;
width: 100px;
height: 40px;
overflow: hidden;
display: flex;
align-items: center;
}
.anim-run .chicken {
position: absolute;
font-size: 24px;
animation: runLeft 3s infinite linear;
}
.anim-run .chef {
position: absolute;
font-size: 28px;
animation: runLeftChef 3s infinite linear;
}
@keyframes runLeft {
0% { transform: translateX(100px); }
100% { transform: translateX(-40px); }
}
@keyframes runLeftChef {
0% { transform: translateX(140px); }
100% { transform: translateX(0px); }
}
/* Wariant 3: Kura w garnku */
.anim-pot {
position: relative;
width: 40px;
height: 40px;
display: flex;
align-items: flex-end;
justify-content: center;
}
.anim-pot .pot-emoji {
font-size: 32px;
z-index: 2;
}
.anim-pot .chicken-head {
position: absolute;
font-size: 24px;
bottom: 10px;
z-index: 1;
animation: peekaboo 4s infinite ease-in-out;
}
@keyframes peekaboo {
0%, 100%, 80% { transform: translateY(15px); opacity: 0; }
30%, 50% { transform: translateY(0px); opacity: 1; }
}
/* Wariant 4: Latająca pizza */
.anim-pizza {
position: relative;
width: 50px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.anim-pizza .chef-pizza {
font-size: 28px;
z-index: 1;
}
.anim-pizza .pizza-emoji {
position: absolute;
font-size: 20px;
top: 0;
right: 0;
z-index: 2;
animation: spinPizza 2s infinite ease-in-out;
}
@keyframes spinPizza {
0%, 100% { transform: translateY(0) rotate(0deg); }
50% { transform: translateY(-15px) rotate(360deg); }
}
/* Wariant 5: Nerwowa świnka */
.anim-pig {
position: relative;
width: 60px;
height: 40px;
display: flex;
align-items: center;
justify-content: center;
}
.anim-pig .pig-emoji {
font-size: 28px;
animation: nervous 0.2s infinite;
}
.anim-pig .sweat-emoji {
position: absolute;
font-size: 16px;
top: 0;
right: 15px;
animation: sweatDrop 1s infinite;
}
.anim-pig .knife-emoji {
position: absolute;
font-size: 20px;
right: -10px;
animation: knifeStab 2s infinite ease-in-out;
}
@keyframes nervous {
0%, 100% { transform: translateX(0); }
50% { transform: translateX(2px); }
}
@keyframes sweatDrop {
0% { transform: translateY(0); opacity: 1; }
100% { transform: translateY(10px); opacity: 0; }
}
@keyframes knifeStab {
0%, 100% { transform: translateX(10px); opacity: 0; }
50% { transform: translateX(0px); opacity: 1; }
}

View File

@@ -0,0 +1,543 @@
window.kitchenAnimations = [
`<div class="kitchen-anim"><div class="fire-emoji">🔥</div><div class="pan-emoji">🍳</div></div>`,
`<div class="anim-run"><div class="chicken">🐓</div><div class="chef">👨‍🍳</div></div>`,
`<div class="anim-pot"><div class="chicken-head">🐓</div><div class="pot-emoji">🍲</div></div>`,
`<div class="anim-pizza"><div class="chef-pizza">👨‍🍳</div><div class="pizza-emoji">🍕</div></div>`,
`<div class="anim-pig"><div class="pig-emoji">🐷</div><div class="sweat-emoji">💦</div><div class="knife-emoji">🍴</div></div>`
];
window.selectedAnimationHtml = null;
const params = new URLSearchParams(location.search);
let tableParam = (params.get("table") || "").trim();
// Jeśli brak numeru stolika w URL zapytaj użytkownika
if (!tableParam) {
const input = prompt("Podaj numer stolika:");
const trimmed = (input || "").trim();
if (trimmed) {
const newUrl = new URL(location.href);
newUrl.searchParams.set("table", trimmed);
location.replace(newUrl.toString());
}
}
// UI Elements
const loadingScreen = document.getElementById("loadingScreen");
const loaderMsg = document.getElementById("loaderMsg");
const tableLabel = document.getElementById("tableLabel");
const prepStatus = document.getElementById("prepStatus");
const progressBar = document.getElementById("progressBar");
const statusMeta = document.getElementById("statusMeta");
const itemsList = document.getElementById("itemsList");
const emptyState = document.getElementById("emptyState");
const metaFooter = document.getElementById("metaFooter");
const statusIcon = document.getElementById("statusIcon");
const storageKey = `stolik2_state_${(tableParam || "unknown").toLowerCase()}`;
const historyKey = "stolik2_global_history";
const historySection = document.getElementById("historySection");
const historyList = document.getElementById("historyList");
const SIX_MONTHS_MS = 180 * 24 * 60 * 60 * 1000;
const HOT_WINDOW_MS = 5 * 60 * 60 * 1000;
// Dynamic Loader Messages
const LOADER_MIN_MS = 10_000;
const loadStartTime = Date.now();
const msgs = ["Rozgrzewamy piece...", "Szef kuchni sprawdza składniki...", "Łączenie z sercem restauracji...", "Prawie gotowe..."];
let msgIdx = 0;
const msgInterval = setInterval(() => {
msgIdx = (msgIdx + 1) % msgs.length;
loaderMsg.textContent = msgs[msgIdx];
}, 4000);
// Initial State
if (tableParam) {
tableLabel.textContent = `Stolik ${tableParam}`;
}
function hideLoader() {
const elapsed = Date.now() - loadStartTime;
const remaining = Math.max(0, LOADER_MIN_MS - elapsed);
setTimeout(() => {
loadingScreen.classList.add("hidden");
clearInterval(msgInterval);
}, remaining);
}
function updateUI(bills) {
// Hide loader after minimum display time
hideLoader();
const allArticles = bills.flatMap(b => Array.isArray(b?.Articles) ? b.Articles : []);
const items = mergeWithPersistedItems(allArticles);
renderGlobalHistory();
if (items.length === 0) {
showEmptyState();
return;
}
renderItems(items);
updateStatus(bills, items);
}
function detectTableCandidates(bill) {
const remark = String(bill?.Remark || "");
const description = String(bill?.Description || "").trim();
// 1) klasyczny format: "STOLIK 9", "STOLIK 11A"
const stolikMatch = remark.match(/STOLIK\s*([0-9A-Z]+)/i);
const fromRemark = stolikMatch ? stolikMatch[1].toLowerCase() : "";
// 2) czasem numer bywa w samym Description
const fromDescription = description.toLowerCase();
return { fromRemark, fromDescription, remark: remark.toLowerCase() };
}
function showEmptyState() {
emptyState.classList.remove("hidden");
itemsList.innerHTML = "";
prepStatus.textContent = "Brak aktywnych zamówień";
statusIcon.textContent = "🍃";
progressBar.style.width = "0%";
statusMeta.textContent = "Zapraszamy do złożenia zamówienia u kelnera.";
// Historia może istnieć nawet gdy brak bieżących pozycji
renderGlobalHistory();
}
function normalizeArticleName(rawName) {
const name = String(rawName || "Pozycja");
// Usuwa gramatury typu: "300G", "250 G", "500/200/150G".
const withoutWeight = name.replace(
/\b\d+(?:[.,]\d+)?(?:\s*\/\s*\d+(?:[.,]\d+)?)*\s*[gG]\b/g,
""
);
return withoutWeight
.replace(/\s{2,}/g, " ")
.replace(/\s+([,.;:!?])/g, "$1")
.trim() || "Pozycja";
}
function loadPersistedItems() {
try {
const raw = localStorage.getItem(storageKey);
if (!raw) return [];
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function savePersistedItems(items) {
try {
localStorage.setItem(storageKey, JSON.stringify(items));
} catch {
// brak miejsca/tryb prywatny
}
}
function loadGlobalHistory() {
try {
const raw = localStorage.getItem(historyKey);
if (!raw) return [];
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function saveGlobalHistory(entries) {
const now = Date.now();
const cleaned = entries
.filter((e) => e && e.name && Number.isFinite(e.archivedAt))
.filter((e) => (now - e.archivedAt) <= SIX_MONTHS_MS);
try {
localStorage.setItem(historyKey, JSON.stringify(cleaned));
} catch {
// ignore storage errors
}
}
function addItemsToGlobalHistory(items, sourceTable) {
if (!items.length) return;
const now = Date.now();
const existing = loadGlobalHistory();
// zapobiegamy dokładnym duplikatom (ta sama nazwa + qty + stół blisko czasu)
const dedupWindowMs = 2 * 60 * 1000;
const toAdd = items.filter((item) => {
return !existing.some((h) =>
h.name === item.name &&
Number(h.qty) === Number(item.qty) &&
String(h.sourceTable || "") === String(sourceTable || "") &&
Math.abs((h.archivedAt || 0) - now) <= dedupWindowMs
);
}).map((item) => ({
name: item.name,
qty: item.qty,
sourceTable: sourceTable || "?",
archivedAt: now
}));
if (!toAdd.length) return;
saveGlobalHistory([...existing, ...toAdd]);
}
function renderGlobalHistory() {
const now = Date.now();
const history = loadGlobalHistory()
.filter((e) => (now - (e.archivedAt || 0)) <= SIX_MONTHS_MS)
.sort((a, b) => (b.archivedAt || 0) - (a.archivedAt || 0));
saveGlobalHistory(history);
if (!history.length) {
historySection.classList.add("hidden");
historyList.innerHTML = "";
return;
}
historySection.classList.remove("hidden");
historyList.innerHTML = "";
history.forEach((entry) => {
const dt = new Date(entry.archivedAt || Date.now());
const div = document.createElement("div");
div.className = "item-card archived ready";
div.innerHTML = `
<div class="item-info">
<span class="item-name">${entry.name}</span>
<span class="item-meta">Stolik ${entry.sourceTable || "?"}${dt.toLocaleDateString("pl-PL")} ${dt.toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'})}</span>
</div>
<div class="item-qty">x${entry.qty}</div>
`;
historyList.appendChild(div);
});
}
function mergeWithPersistedItems(articles) {
const current = new Map();
articles.forEach(a => {
const name = normalizeArticleName(a.Name);
const todo = parseFloat(String(a.QuantityToDo || a.QuantitySet || "0").replace(",","."));
const done = parseFloat(String(a.QuantityDone || "0").replace(",","."));
if (!current.has(name)) {
current.set(name, { name, qty: 0, done: 0, present: true, completedByDisappear: false });
}
const curr = current.get(name);
curr.qty += Number.isFinite(todo) ? todo : 0;
curr.done += Number.isFinite(done) ? done : 0;
});
const persisted = loadPersistedItems();
const persistedMap = new Map(persisted.map(i => [i.name, i]));
const merged = [];
// Aktualnie obecne pozycje z WS
current.forEach((item) => {
merged.push({
...item,
present: true,
completedByDisappear: false,
updatedAt: Date.now()
});
});
// Pozycje, które były wcześniej, ale zniknęły z WS -> zostają jako gotowe
persistedMap.forEach((oldItem, name) => {
if (current.has(name)) return;
const qty = Number.isFinite(oldItem?.qty) ? oldItem.qty : 0;
const archivedAt = Number.isFinite(oldItem?.archivedAt) ? oldItem.archivedAt : Date.now();
const shouldMoveToGlobal = (Date.now() - archivedAt) > HOT_WINDOW_MS;
if (shouldMoveToGlobal) {
addItemsToGlobalHistory([{ name, qty }], tableParam);
return;
}
merged.push({
name,
qty,
done: qty,
present: false,
completedByDisappear: true,
archivedAt,
updatedAt: Date.now()
});
});
// Aktywne na górze, gotowe (zniknięte) na dole
merged.sort((a, b) => {
if (a.present !== b.present) return a.present ? -1 : 1;
return a.name.localeCompare(b.name, "pl");
});
savePersistedItems(merged);
return merged;
}
function renderItems(items) {
emptyState.classList.add("hidden");
itemsList.innerHTML = "";
items.forEach((item) => {
const isReady = item.done >= item.qty && item.qty > 0;
const div = document.createElement("div");
div.className = `item-card ${isReady ? 'ready' : ''} ${item.present ? '' : 'archived'}`;
let meta = "🔥 W przygotowaniu";
if (isReady && item.completedByDisappear) {
meta = "✅ Gotowe (zrealizowane)";
} else if (isReady) {
meta = "✅ Gotowe";
}
div.innerHTML = `
<div class="item-info">
<span class="item-name">${item.name}</span>
<span class="item-meta">${meta}</span>
</div>
<div class="item-qty">x${item.qty}</div>
`;
itemsList.appendChild(div);
});
renderGlobalHistory();
}
function updateStatus(bills, items) {
let total = 0;
let done = 0;
items.forEach(i => {
total += Number.isFinite(i.qty) ? i.qty : 0;
done += Number.isFinite(i.done) ? i.done : 0;
});
const pct = total > 0 ? (done / total) * 100 : 0;
progressBar.style.width = `${pct}%`;
if (pct >= 100) {
prepStatus.textContent = "Gotowe do podania!";
statusIcon.innerHTML = "😋";
statusMeta.textContent = "Wszystkie Twoje dania opuściły już kuchnię.";
} else if (pct > 0) {
prepStatus.textContent = "Częściowo gotowe";
statusIcon.innerHTML = "🍳";
statusMeta.textContent = "Pierwsze pyszności już na Ciebie czekają!";
} else {
prepStatus.textContent = "W przygotowaniu";
if (!window.selectedAnimationHtml) {
window.selectedAnimationHtml = window.kitchenAnimations[Math.floor(Math.random() * window.kitchenAnimations.length)];
}
statusIcon.innerHTML = window.selectedAnimationHtml;
statusMeta.textContent = "Twoje zamówienie jest właśnie tworzone przez naszych kucharzy.";
}
// Footer meta
const newest = [...bills].sort((a,b) => new Date(b?.Date || 0) - new Date(a?.Date || 0))[0];
const time = newest?.Date
? new Date(newest.Date).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})
: "--:--";
metaFooter.textContent = `Zamówienie złożone o godzinie ${time} • Stolik ${tableParam}`;
}
// API Fetch Logic
async function fetchOrders() {
try {
const response = await fetch('../api_kds.php');
const result = await response.json();
if (result.status === 'success') {
if (!tableParam) {
updateUI([]);
return;
}
const myTable = tableParam.toLowerCase();
// Filtrowanie pozycji dla wybranego stolika
const matches = result.data.filter(item => {
const stolikNazwa = (item.NazwaStolika || '').toLowerCase();
const stolikId = (item.StolikID || '').toLowerCase();
// Sprawdzamy czy nazwa stolika z bazy zawiera numer szukany (np. O-61) lub czy ID się zgadza
return stolikNazwa === myTable || stolikId === myTable || stolikNazwa.includes(myTable);
});
// Grupowanie składników w główne dania, żeby klient widział "Pierogi" a nie "Opakowanie"
const groups = {};
matches.forEach(item => {
const groupId = item.GrupaZestawuID || item.PozycjaID;
if (!groups[groupId]) {
groups[groupId] = {
Name: item.NazwaZestawu || item.NazwaTowaru,
QuantitySet: item.GrupaZestawuID ? 1 : parseFloat(item.Ilosc)
};
}
});
const transformedArticles = Object.values(groups);
// Najnowszy czas dodania (do pokazania w stopce)
const latestDate = matches.length > 0
? matches.sort((a,b) => new Date(b.DataDodania) - new Date(a.DataDodania))[0].DataDodania
: null;
// Przekazanie do dotychczasowej logiki aktualizującej UI (w odpowiednim formacie)
updateUI([{
Articles: transformedArticles,
Date: latestDate
}]);
} else {
loaderMsg.textContent = "Błąd API: " + result.message;
}
} catch (err) {
loaderMsg.textContent = "Problem z połączeniem. Próbujemy ponownie...";
}
}
fetchOrders();
setInterval(fetchOrders, 3000);
// --- CALL WAITER LOGIC ---
let billState = { payment: '', doc: '', nip: '', company: null };
function showToast(msg) {
const t = document.getElementById("toastMsg");
document.getElementById("toastText").textContent = msg;
t.classList.remove("active");
void t.offsetWidth; // trigger reflow
t.classList.add("active");
setTimeout(() => t.classList.remove("active"), 3500);
}
function sendApiSimulated(actionName, details) {
console.log(`[SYMULACJA API] Akcja: ${actionName}`, details);
// Przykładowe wysłanie docelowo:
// if (window.socket && window.socket.readyState === WebSocket.OPEN) {
// window.socket.send(JSON.stringify({ action: "sendUpstream", payload: { type: actionName, table: tableParam, ...details } }));
// }
}
window.callWaiter = function(type) {
if (type === 'order') {
sendApiSimulated("CallWaiter_Order", { table: tableParam });
showToast("Kelner wkrótce do Ciebie podejdzie!");
}
};
window.openBillDialog = function() {
billState = { payment: '', doc: '', nip: '', company: null };
document.getElementById("billModal").classList.add("active");
goToStep("stepPayment");
};
window.closeBillDialog = function() {
document.getElementById("billModal").classList.remove("active");
};
window.goToStep = function(stepId) {
document.querySelectorAll(".step").forEach(s => s.classList.remove("active"));
document.getElementById(stepId).classList.add("active");
};
window.selectPayment = function(method) {
billState.payment = method;
goToStep("stepDocument");
};
window.selectDocument = function(docType) {
billState.doc = docType;
if (docType === 'paragon') {
closeBillDialog();
sendApiSimulated("CallWaiter_Bill", { table: tableParam, payment: billState.payment, doc: 'paragon' });
showToast("Kelner przyniesie paragon do opłacenia!");
} else {
goToStep("stepNIP");
document.getElementById("nipInput").value = '';
setTimeout(() => document.getElementById("nipInput").focus(), 100);
}
};
window.fetchGUS = function() {
const nip = document.getElementById("nipInput").value.replace(/[\s-]/g, '');
if (nip.length < 10) {
alert("Wprowadź poprawny numer NIP.");
return;
}
const btn = document.getElementById("btnGUS");
btn.textContent = "Szukam...";
btn.disabled = true;
// Symulacja pobrania z GUS
setTimeout(() => {
btn.textContent = "Pobierz z GUS";
btn.disabled = false;
billState.nip = nip;
billState.company = {
name: "Przykładowa Firma Sp. z o.o.",
address: "ul. Gastronomiczna 12/4, 00-120 Warszawa",
nip: nip
};
document.getElementById("cmpName").value = billState.company.name;
document.getElementById("cmpAddress").value = billState.company.address;
document.getElementById("cmpNip").value = "NIP: " + billState.company.nip;
// reset do readonly
document.getElementById("cmpName").readOnly = true;
document.getElementById("cmpAddress").readOnly = true;
document.getElementById("btnEditCompany").textContent = "Popraw ręcznie";
goToStep("stepVerify");
}, 1200);
};
window.editCompanyData = function() {
const n = document.getElementById("cmpName");
const a = document.getElementById("cmpAddress");
const btn = document.getElementById("btnEditCompany");
if (n.readOnly) {
n.readOnly = false;
a.readOnly = false;
n.focus();
btn.textContent = "Zakończ edycję";
} else {
n.readOnly = true;
a.readOnly = true;
btn.textContent = "Popraw ręcznie";
}
};
window.confirmInvoice = function() {
billState.company.name = document.getElementById("cmpName").value;
billState.company.address = document.getElementById("cmpAddress").value;
closeBillDialog();
sendApiSimulated("CallWaiter_Bill", {
table: tableParam,
payment: billState.payment,
doc: 'faktura',
nip: billState.nip,
company: billState.company
});
showToast("Dziękujemy! Prośba o fakturę została wysłana.");
};
// Fallback: If no data after 25s, show empty state anyway
setTimeout(() => {
if (!loadingScreen.classList.contains("hidden")) {
updateUI([]);
}
}, 25000);

File diff suppressed because it is too large Load Diff

31
schema.php Normal file
View File

@@ -0,0 +1,31 @@
<?php
$serverName = '192.168.20.20';
$connectionOptions = ['Database' => 'Gastro', 'Uid' => 'sa', 'PWD' => 'karczma!@#26', 'CharacterSet' => 'UTF-8'];
$conn = sqlsrv_connect($serverName, $connectionOptions);
if (!$conn) {
die(print_r(sqlsrv_errors(), true));
}
$tsql = "
SELECT TABLE_NAME, COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%KDS%'
OR COLUMN_NAME LIKE '%Druk%'
OR COLUMN_NAME LIKE '%Kierun%'
OR COLUMN_NAME LIKE '%Stanowisk%'
OR COLUMN_NAME LIKE '%Ekran%'
OR COLUMN_NAME LIKE '%Wydruk%'
";
$stmt = sqlsrv_query($conn, $tsql);
if (!$stmt) {
die(print_r(sqlsrv_errors(), true));
}
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
// Only care about related tables like NGastroTowar, NGastroDTRachunekPozycja, etc.
if (strpos($row['TABLE_NAME'], 'NGastro') === 0) {
echo $row['TABLE_NAME'] . " -> " . $row['COLUMN_NAME'] . "\n";
}
}

17
schema_bills.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
$serverName = '192.168.20.20';
$connectionOptions = ['Database' => 'Gastro', 'Uid' => 'sa', 'PWD' => 'karczma!@#26', 'CharacterSet' => 'UTF-8'];
$conn = sqlsrv_connect($serverName, $connectionOptions);
$tables = ['NGastroDTRachunek', 'NGastroDTRachunekPozycja', 'NGastroKonfiguracjaDrukowaniaZamowien'];
foreach ($tables as $table) {
echo "--- $table ---\n";
$tsql = "SELECT COLUMN_NAME, DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '$table'";
$stmt = sqlsrv_query($conn, $tsql);
$cols = [];
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$cols[] = $row['COLUMN_NAME'] . " (" . $row['DATA_TYPE'] . ")";
}
echo implode(", ", $cols) . "\n\n";
}

33
test_bills.php Normal file
View File

@@ -0,0 +1,33 @@
<?php
$serverName = '192.168.20.20';
$connectionOptions = ['Database' => 'Gastro', 'Uid' => 'sa', 'PWD' => 'karczma!@#26', 'CharacterSet' => 'UTF-8'];
$conn = sqlsrv_connect($serverName, $connectionOptions);
$tsql = "
SELECT
r.ID as RachunekID,
r.Numer as RachunekNumer,
r.Opis,
r.DataZamkniecia,
r.Status,
r.FlgRozliczony,
COUNT(rp.ID) as PozycjeCount,
SUM(rp._c_Wartosc) as SumaWartosc
FROM dbo.NGastroDTRachunek r
LEFT JOIN dbo.NGastroDTRachunekPozycja rp ON rp.DTRachunekID = r.ID
WHERE CAST(r.DataOtwarcia as DATE) = CAST(GETDATE() as DATE)
GROUP BY r.ID, r.Numer, r.Opis, r.DataZamkniecia, r.Status, r.FlgRozliczony
ORDER BY r.Numer DESC
";
$stmt = sqlsrv_query($conn, $tsql);
if (!$stmt) die(print_r(sqlsrv_errors(), true));
$bills = [];
$count = 0;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
if ($count++ < 10) {
print_r($row);
}
}
echo "\nTotal active items: $count\n";