create branch dev and commit code

This commit is contained in:
thanawat saiyota 2026-06-09 10:50:59 +07:00
parent 3b70cc9fe8
commit ea68fa5cc4
44 changed files with 12421 additions and 214 deletions

View file

@ -0,0 +1,846 @@
<script lang="ts">
import { onMount, onDestroy } from 'svelte';
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { addNotification } from '$lib/core/stores/noti.js';
import Button from '$lib/components/ui/button/button.svelte';
import Input from '$lib/components/ui/input/input.svelte';
import Label from '$lib/components/ui/label/label.svelte';
import * as Card from '$lib/components/ui/card/index.js';
import * as Dialog from '$lib/components/ui/dialog/index.js';
import Badge from '$lib/components/ui/badge/badge.svelte';
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
import { ArrowLeft, Plus, X, Search, RefreshCw } from '@lucide/svelte/icons';
import {
enterRoom,
exitRoom,
sendHeartbeat,
addMenu,
requestListMenu
} from '$lib/core/services/sheetService.js';
import {
existingProductCodes,
loadProductCodesFromCache,
clearProductCodes,
getSheetColumnConfig
} from '$lib/core/stores/sheetStore.js';
import * as adb from '$lib/core/adb/adb';
import { AdbInstance } from '../../../../../state.svelte';
import { recipeFromMachineQuery } from '$lib/core/stores/recipeStore';
// Route params
const country = $page.params.country!;
const catalog = $page.params.catalog!;
const countryCode = country.toLowerCase();
// Country language configuration
const countryLanguageConfig: Record<
string,
{ primary: string; secondary: string; primaryKey: string; secondaryKey: string }
> = {
tha: { primary: 'Thai', secondary: 'English', primaryKey: 'th', secondaryKey: 'en' },
thai: { primary: 'Thai', secondary: 'English', primaryKey: 'th', secondaryKey: 'en' },
mys: { primary: 'Malay', secondary: 'English', primaryKey: 'ms', secondaryKey: 'en' },
myn: { primary: 'Malay', secondary: 'English', primaryKey: 'ms', secondaryKey: 'en' },
idr: { primary: 'Indonesian', secondary: 'English', primaryKey: 'id', secondaryKey: 'en' },
sgp: { primary: 'English', secondary: 'Chinese', primaryKey: 'en', secondaryKey: 'zh' },
sg: { primary: 'English', secondary: 'Chinese', primaryKey: 'en', secondaryKey: 'zh' },
aus: { primary: 'English', secondary: '', primaryKey: 'en', secondaryKey: '' },
gbr: { primary: 'English', secondary: '', primaryKey: 'en', secondaryKey: '' },
ltu: { primary: 'Lithuanian', secondary: 'English', primaryKey: 'lt', secondaryKey: 'en' },
lva: { primary: 'Latvian', secondary: 'English', primaryKey: 'lv', secondaryKey: 'en' },
est: { primary: 'Estonian', secondary: 'English', primaryKey: 'et', secondaryKey: 'en' },
rou: { primary: 'Romanian', secondary: 'English', primaryKey: 'ro', secondaryKey: 'en' },
hkg: { primary: 'Cantonese', secondary: 'English', primaryKey: 'zh', secondaryKey: 'en' },
uae_dubai: { primary: 'Arabic', secondary: 'English', primaryKey: 'ar', secondaryKey: 'en' },
dubai: { primary: 'Arabic', secondary: 'English', primaryKey: 'ar', secondaryKey: 'en' }
};
const defaultLangConfig = {
primary: 'Primary',
secondary: 'English',
primaryKey: 'en',
secondaryKey: ''
};
const langConfig = countryLanguageConfig[countryCode] || defaultLangConfig;
// State
let saving = $state(false);
let lockTimeout = $state(30);
let timeoutInterval: ReturnType<typeof setInterval>;
let roomReleased = false;
// Form state - single menu item
let formData = $state({
name_primary: '',
name_secondary: '',
desc_primary: '',
desc_secondary: '',
image: '',
position: '',
categories: '',
// Additional data
notes: ''
});
// Product code state
let productCodes = $state<{ hot: string; cold: string; blend: string }>({
hot: '',
cold: '',
blend: ''
});
// Derive existing codes from store
const existingCodeSet = $derived($existingProductCodes);
// Get temp type from product code
function getTempFromCode(code: string): 'hot' | 'cold' | 'blend' | null {
const parts = code.split('-');
if (parts.length < 3) return null;
const tempCode = parts[2];
if (tempCode === '01') return 'hot';
if (tempCode === '02') return 'cold';
if (tempCode === '03') return 'blend';
return null;
}
// Load product codes from all sources
async function loadAvailableProductCodes() {
loadingCodes = true;
const codes: AvailableProductCode[] = [];
const seenCodes = new Set<string>();
const serverCodes = new Set<string>(); // Track server codes to identify new machine codes
try {
// 1. Load from server (existingProductCodes store)
for (const code of $existingProductCodes) {
const temp = getTempFromCode(code);
if (temp && !seenCodes.has(code)) {
seenCodes.add(code);
serverCodes.add(code);
codes.push({ code, source: 'server', temp });
}
}
// 2. Load from staged menus (localStorage)
try {
const stored = localStorage.getItem(stagedMenuStorageKey);
const stagedMenus = stored ? JSON.parse(stored) : [];
for (const menu of stagedMenus) {
const code = menu?.productCode;
const temp = getTempFromCode(code);
if (code && temp && !seenCodes.has(code)) {
seenCodes.add(code);
codes.push({
code,
name: menu.name || menu.otherName,
source: 'staged',
temp
});
}
}
} catch (e) {
console.error('Failed to load staged menus:', e);
}
// 3. Load from machine recipes (via recipeFromMachineQuery store)
const machineQuery = $recipeFromMachineQuery;
if (machineQuery?.recipe) {
for (const [code, recipe] of Object.entries(machineQuery.recipe)) {
const temp = getTempFromCode(code);
if (temp && !seenCodes.has(code)) {
seenCodes.add(code);
// Mark as new if not in server codes
const isNew = !serverCodes.has(code);
codes.push({
code,
name: (recipe as any)?.name || (recipe as any)?.otherName,
source: 'machine',
temp,
isNew
});
}
}
}
// Sort: new items first, then by code
codes.sort((a, b) => {
// New items first
if (a.isNew && !b.isNew) return -1;
if (!a.isNew && b.isNew) return 1;
// Then by code
return a.code.localeCompare(b.code);
});
availableProductCodes = codes;
} finally {
loadingCodes = false;
}
}
// Filter codes by current popup type and search query
const filteredCodes = $derived(() => {
let filtered = availableProductCodes.filter((c) => c.temp === codePopupType);
if (codeSearchQuery.trim()) {
const query = codeSearchQuery.toLowerCase().trim();
filtered = filtered.filter(
(c) => c.code.toLowerCase().includes(query) || c.name?.toLowerCase().includes(query)
);
}
// Maintain sort: new items first, then by code
return [...filtered].sort((a, b) => {
if (a.isNew && !b.isNew) return -1;
if (!a.isNew && b.isNew) return 1;
return a.code.localeCompare(b.code);
});
});
// Get source label
function getSourceLabel(source: ProductCodeSource): string {
switch (source) {
case 'server':
return 'Server';
case 'staged':
return 'Draft';
case 'machine':
return 'Machine';
}
}
// Get source badge variant
function getSourceVariant(source: ProductCodeSource): 'default' | 'secondary' | 'outline' {
switch (source) {
case 'server':
return 'default';
case 'staged':
return 'secondary';
case 'machine':
return 'outline';
}
}
// Popup state
let codePopupOpen = $state(false);
let codePopupType = $state<'hot' | 'cold' | 'blend'>('hot');
let codeSearchQuery = $state('');
let loadingCodes = $state(false);
// Available product codes from different sources
type ProductCodeSource = 'server' | 'staged' | 'machine';
type AvailableProductCode = {
code: string;
name?: string;
source: ProductCodeSource;
temp: 'hot' | 'cold' | 'blend';
isNew?: boolean; // true if from machine but not in server
};
let availableProductCodes = $state<AvailableProductCode[]>([]);
// Staged menus storage key (same as create-menu page)
const stagedMenuStorageKey = 'brew.create-menu.drafts.v1';
const tempLabels = {
hot: 'Hot',
cold: 'Cold',
blend: 'Blend'
};
const lockHeartbeatIntervalMs = 10000;
// Open popup for specific temperature type
function openCodePopup(type: 'hot' | 'cold' | 'blend') {
codePopupType = type;
codeSearchQuery = '';
codePopupOpen = true;
}
// Select a product code from the list
function selectCode(code: string) {
productCodes = {
...productCodes,
[codePopupType]: code
};
codePopupOpen = false;
}
// Clear a specific code
function clearCode(type: 'hot' | 'cold' | 'blend') {
productCodes = {
...productCodes,
[type]: ''
};
}
function getCatalogDisplayName(catalogName: string): string {
const match = catalogName.match(/page_catalog_group_(\w+)\.skt/);
return match ? match[1].charAt(0).toUpperCase() + match[1].slice(1) : catalogName;
}
function buildAddContent() {
// Build cells array according to backend format (20 columns).
// Names/descriptions (indices 2-5) are filled below per-country so each
// language lands in its correct sheet column.
const cells = [
'', // 0
'', // 1
'', // 2 - name -> col 4 (Thai/local primary slot)
'', // 3 - name -> col 3 (English slot)
'', // 4 - desc -> col 4
'', // 5 - desc -> col 3
productCodes.hot || '-', // 6 - Hot product code
productCodes.cold || '-', // 7 - Cold product code
productCodes.blend || '-', // 8 - Blend product code
formData.image || '', // 9 - Image filename
'-', // 10
'-', // 11
'-', // 12
formData.position || '', // 13 - Position
'-', // 14
'-', // 15
'-', // 16
'-', // 17
formData.categories || '', // 18 - Categories (comma-separated)
'' // 19
];
// lang_name/lang_desc map to sheet columns 5, 6, 7, 8 respectively.
const lang_name = ['-', '-', '-', '-'];
const lang_desc = ['-', '-', '-', '-'];
// Backend slot mapping (see taobin_sheet/main.py handle_add_menu):
// col 3 <- cells[3], col 4 <- cells[2]
// col 5 <- lang_name[0] ... col 8 <- lang_name[3]
function setNameForColumn(col: number, value: string) {
if (col === 3) cells[3] = value;
else if (col === 4) cells[2] = value;
else if (col >= 5 && col <= 8) lang_name[col - 5] = value || '-';
}
function setDescForColumn(col: number, value: string) {
if (col === 3) cells[5] = value;
else if (col === 4) cells[4] = value;
else if (col >= 5 && col <= 8) lang_desc[col - 5] = value || '-';
}
// Resolve which sheet column each language occupies for this country.
const columnConfig = getSheetColumnConfig(countryCode);
const languageColumns = columnConfig.language; // { en: 3, th: 4, lt: 5, ... }
const enColumn = languageColumns.en ?? 3;
const primaryColumn = languageColumns[columnConfig.primaryLanguage] ?? 4;
if (columnConfig.primaryLanguage === 'en') {
// Single-language (English) machine: primary field is English -> col 3.
setNameForColumn(enColumn, formData.name_primary);
setDescForColumn(enColumn, formData.desc_primary);
} else {
// English is the secondary field -> col 3.
setNameForColumn(enColumn, formData.name_secondary);
setDescForColumn(enColumn, formData.desc_secondary);
// Local primary language -> its configured column.
setNameForColumn(primaryColumn, formData.name_primary);
setDescForColumn(primaryColumn, formData.desc_primary);
// Hong Kong has two primary columns (Mandarin Simplified + Traditional);
// fill both from the single primary input.
if (languageColumns.zh_hans != null && languageColumns.zh_hant != null) {
setNameForColumn(languageColumns.zh_hans, formData.name_primary);
setDescForColumn(languageColumns.zh_hans, formData.desc_primary);
setNameForColumn(languageColumns.zh_hant, formData.name_primary);
setDescForColumn(languageColumns.zh_hant, formData.desc_primary);
}
}
const payload = { lang_name, lang_desc };
return [{ cells, payload }];
}
function validateForm(): string | null {
if (!formData.name_primary && !formData.name_secondary) {
return `Please enter at least ${langConfig.primary} or ${langConfig.secondary} name`;
}
if (!productCodes.hot && !productCodes.cold && !productCodes.blend) {
return 'Please add at least one product code';
}
return null;
}
function resetForm() {
formData = {
name_primary: '',
name_secondary: '',
desc_primary: '',
desc_secondary: '',
image: '',
position: '',
categories: '',
notes: ''
};
productCodes = { hot: '', cold: '', blend: '' };
}
function releaseRoom() {
if (roomReleased) return;
roomReleased = true;
exitRoom(country, catalog);
}
async function handleSave() {
const validationError = validateForm();
if (validationError) {
addNotification(`WARN:${validationError}`);
return;
}
saving = true;
try {
const content = buildAddContent();
const sent = addMenu(country, catalog, content);
if (!sent) {
throw new Error('WebSocket not connected. Cannot add menu.');
}
addNotification('INFO:Menu added successfully');
resetForm();
// Mark that a new menu was just added (edit page will detect and highlight it)
try {
const key = `sheet.newlyAdded.${country}.${catalog}`;
sessionStorage.setItem(key, JSON.stringify({ timestamp: Date.now(), pending: true }));
} catch (e) {
console.warn('Failed to store newly added marker:', e);
}
// Go back to edit page after successful add
setTimeout(() => {
goto(`/sheet/edit/${country}/${catalog}`);
}, 1000);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : 'Unknown error';
addNotification(`ERR:${errorMsg}`);
} finally {
saving = false;
}
}
async function handleCancel() {
releaseRoom();
clearInterval(timeoutInterval);
goto(`/sheet/edit/${country}/${catalog}`);
}
// Track previous size to detect changes
let previousCodeCount = $state(0);
// Re-load available product codes when existingProductCodes store changes
$effect(() => {
const currentSize = $existingProductCodes.size;
if (currentSize > 0 && currentSize !== previousCodeCount) {
previousCodeCount = currentSize;
console.log('[Add] existingProductCodes updated, reloading available codes:', currentSize);
loadAvailableProductCodes();
}
});
onMount(async () => {
// Clear old product codes and load from cache for this country
clearProductCodes();
loadProductCodesFromCache(countryCode);
// Get boxid from connected machine if available
let boxid: string | undefined;
if (adb.getAdbInstance()) {
try {
boxid = (await adb.pull('/sdcard/coffeevending/.bid')) || undefined;
} catch (e) {
console.warn('Failed to get boxid from machine:', e);
}
}
requestListMenu(country, boxid);
// Load available product codes from all sources
await loadAvailableProductCodes();
// Enter room to get lock
const entered = enterRoom(country, catalog);
if (entered) {
addNotification(`INFO:Entered ${getCatalogDisplayName(catalog)} for adding menu`);
// Keep the room alive
timeoutInterval = setInterval(() => {
sendHeartbeat(country, catalog);
lockTimeout = 30;
}, lockHeartbeatIntervalMs);
} else {
addNotification('ERR:WebSocket not connected');
goto(`/sheet/overview/${country}`);
}
});
onDestroy(() => {
clearInterval(timeoutInterval);
releaseRoom();
});
</script>
<!-- Wrapper -->
<div class="flex min-h-screen flex-col">
<!-- Header -->
<div class="sticky top-0 z-10 border-b bg-background">
<div class="flex items-center justify-between px-8 py-4">
<div class="flex items-center gap-4">
<Button variant="ghost" size="sm" onclick={handleCancel}>
<ArrowLeft class="mr-2 h-4 w-4" />
Back
</Button>
<div>
<h1 class="text-2xl font-bold">
Add Menu: {getCatalogDisplayName(catalog)}
</h1>
<p class="text-sm text-muted-foreground">
{country.toUpperCase()}{catalog}
</p>
</div>
</div>
<div class="flex items-center gap-4">
<Badge variant={lockTimeout > 10 ? 'default' : 'destructive'}>
Lock: {lockTimeout}s
</Badge>
<Button variant="outline" onclick={handleCancel} disabled={saving}>
<X class="mr-2 h-4 w-4" />
Cancel
</Button>
<Button onclick={handleSave} disabled={saving}>
{#if saving}
<Spinner class="mr-2 h-4 w-4" />
{:else}
<Plus class="mr-2 h-4 w-4" />
{/if}
Add Menu
</Button>
</div>
</div>
</div>
<!-- Content -->
<div class="flex-1 overflow-y-auto p-8">
<div class="mx-auto max-w-4xl space-y-6">
<!-- Basic Info -->
<Card.Root>
<Card.Header>
<Card.Title class="flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10">
<span class="text-sm font-bold text-primary">1</span>
</div>
Basic Information
</Card.Title>
<Card.Description>Enter menu name and description</Card.Description>
</Card.Header>
<Card.Content class="space-y-4">
<div class="grid gap-4 md:grid-cols-2">
<div class="space-y-2">
<Label for="name_primary">{langConfig.primary} Name *</Label>
<Input
id="name_primary"
bind:value={formData.name_primary}
placeholder="Menu name in {langConfig.primary}"
class="h-11"
/>
</div>
{#if langConfig.secondary}
<div class="space-y-2">
<Label for="name_secondary">{langConfig.secondary} Name *</Label>
<Input
id="name_secondary"
bind:value={formData.name_secondary}
placeholder="Menu name in {langConfig.secondary}"
class="h-11"
/>
</div>
{/if}
</div>
<div class="grid gap-4 md:grid-cols-2">
<div class="space-y-2">
<Label for="desc_primary">{langConfig.primary} Description</Label>
<textarea
id="desc_primary"
bind:value={formData.desc_primary}
placeholder="Description in {langConfig.primary}"
class="min-h-20 w-full rounded-md border bg-background px-3 py-2 text-sm"
rows="3"
></textarea>
</div>
{#if langConfig.secondary}
<div class="space-y-2">
<Label for="desc_secondary">{langConfig.secondary} Description</Label>
<textarea
id="desc_secondary"
bind:value={formData.desc_secondary}
placeholder="Description in {langConfig.secondary}"
class="min-h-20 w-full rounded-md border bg-background px-3 py-2 text-sm"
rows="3"
></textarea>
</div>
{/if}
</div>
</Card.Content>
</Card.Root>
<!-- Product Codes -->
<Card.Root>
<Card.Header>
<Card.Title class="flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10">
<span class="text-sm font-bold text-primary">2</span>
</div>
Product Codes
</Card.Title>
<Card.Description>
Click on each field to select category and generate code
{#if existingCodeSet.size > 0}
({existingCodeSet.size} existing codes)
{/if}
</Card.Description>
</Card.Header>
<Card.Content>
<div class="grid gap-4 md:grid-cols-3">
<!-- Hot Code -->
<div class="space-y-2">
<Label>Hot Code</Label>
<button
type="button"
onclick={() => openCodePopup('hot')}
class="flex h-11 w-full items-center justify-between rounded-md border bg-background px-3 text-left transition-colors hover:border-orange-500/50 hover:bg-orange-500/5"
>
{#if productCodes.hot}
<span class="font-mono text-sm">{productCodes.hot}</span>
<button
type="button"
onclick={(e) => {
e.stopPropagation();
clearCode('hot');
}}
class="text-muted-foreground hover:text-destructive"
>
<X class="h-4 w-4" />
</button>
{:else}
<span class="text-sm text-muted-foreground">Click to add...</span>
<Plus class="h-4 w-4 text-muted-foreground" />
{/if}
</button>
</div>
<!-- Cold Code -->
<div class="space-y-2">
<Label>Cold Code</Label>
<button
type="button"
onclick={() => openCodePopup('cold')}
class="flex h-11 w-full items-center justify-between rounded-md border bg-background px-3 text-left transition-colors hover:border-blue-500/50 hover:bg-blue-500/5"
>
{#if productCodes.cold}
<span class="font-mono text-sm">{productCodes.cold}</span>
<button
type="button"
onclick={(e) => {
e.stopPropagation();
clearCode('cold');
}}
class="text-muted-foreground hover:text-destructive"
>
<X class="h-4 w-4" />
</button>
{:else}
<span class="text-sm text-muted-foreground">Click to add...</span>
<Plus class="h-4 w-4 text-muted-foreground" />
{/if}
</button>
</div>
<!-- Blend Code -->
<div class="space-y-2">
<Label>Blend Code</Label>
<button
type="button"
onclick={() => openCodePopup('blend')}
class="flex h-11 w-full items-center justify-between rounded-md border bg-background px-3 text-left transition-colors hover:border-purple-500/50 hover:bg-purple-500/5"
>
{#if productCodes.blend}
<span class="font-mono text-sm">{productCodes.blend}</span>
<button
type="button"
onclick={(e) => {
e.stopPropagation();
clearCode('blend');
}}
class="text-muted-foreground hover:text-destructive"
>
<X class="h-4 w-4" />
</button>
{:else}
<span class="text-sm text-muted-foreground">Click to add...</span>
<Plus class="h-4 w-4 text-muted-foreground" />
{/if}
</button>
</div>
</div>
<!-- Code Format Info -->
<!-- <div class="mt-4 rounded-lg border border-muted bg-muted/20 p-3">
<p class="text-xs text-muted-foreground">
<strong>Format:</strong> {countryCodeMap[country] || '??'}-[category]-[temp]-[random] •
Country: {country.toUpperCase()}
01=Hot, 02=Cold, 03=Blend
</p>
</div> -->
</Card.Content>
</Card.Root>
<!-- Image & Categories -->
<Card.Root>
<Card.Header>
<Card.Title class="flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-primary/10">
<span class="text-sm font-bold text-primary">3</span>
</div>
Image & Categories
</Card.Title>
<Card.Description>Set image filename and menu categories</Card.Description>
</Card.Header>
<Card.Content>
<div class="grid gap-4 md:grid-cols-2">
<div class="space-y-2">
<Label for="image">Image Filename</Label>
<Input
id="image"
bind:value={formData.image}
placeholder="bn_hot_america_no.png"
class="font-mono"
/>
</div>
<div class="space-y-2">
<Label for="position">Position</Label>
<Input id="position" bind:value={formData.position} placeholder="posi1" />
</div>
</div>
<div class="mt-4 space-y-2">
<Label for="categories">Categories (comma-separated)</Label>
<Input
id="categories"
bind:value={formData.categories}
placeholder="Coffee,CoffeeNoMilk,ShakeShake"
/>
<!-- <p class="text-xs text-muted-foreground">
Separate multiple categories with commas
</p> -->
</div>
</Card.Content>
</Card.Root>
<!-- Actions -->
<div class="flex justify-end gap-3 pb-8">
<Button variant="outline" size="lg" onclick={handleCancel} disabled={saving}>
<X class="mr-2 h-4 w-4" />
Cancel
</Button>
<Button size="lg" onclick={handleSave} disabled={saving}>
{#if saving}
<Spinner class="mr-2 h-4 w-4" />
{:else}
<Plus class="mr-2 h-4 w-4" />
{/if}
Add Menu
</Button>
</div>
</div>
</div>
</div>
<!-- Product Code Selection Popup -->
<Dialog.Root bind:open={codePopupOpen}>
<Dialog.Content class="max-h-[80vh] sm:max-w-lg">
<Dialog.Header>
<Dialog.Title class="flex items-center gap-2">
Select {tempLabels[codePopupType]} Product Code
</Dialog.Title>
<Dialog.Description>
Choose from existing product codes (Server, Draft, or Machine)
</Dialog.Description>
</Dialog.Header>
<!-- Search and Refresh -->
<div class="mt-4 flex gap-2">
<div class="relative flex-1">
<Search class="absolute top-1/2 left-3 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
type="text"
placeholder="Search by code or name..."
bind:value={codeSearchQuery}
class="pl-9"
/>
</div>
<Button
variant="outline"
size="icon"
onclick={() => loadAvailableProductCodes()}
disabled={loadingCodes}
>
<RefreshCw class="h-4 w-4 {loadingCodes ? 'animate-spin' : ''}" />
</Button>
</div>
<!-- Code List -->
<div class="mt-4 max-h-[400px] space-y-2 overflow-y-auto">
{#if loadingCodes}
<div class="flex items-center justify-center py-8">
<Spinner class="h-6 w-6" />
<span class="ml-2 text-muted-foreground">Loading codes...</span>
</div>
{:else if filteredCodes().length === 0}
<div class="py-8 text-center text-muted-foreground">
{#if codeSearchQuery}
No codes found matching "{codeSearchQuery}"
{:else}
No {tempLabels[codePopupType].toLowerCase()} product codes available
{/if}
</div>
{:else}
{#each filteredCodes() as item}
<button
type="button"
onclick={() => selectCode(item.code)}
class="flex w-full items-center justify-between rounded-lg border bg-card p-3 text-left transition-colors hover:border-primary/50 hover:bg-primary/5 {item.isNew ? 'border-green-500/50 bg-green-500/5' : ''}"
>
<div class="min-w-0 flex-1">
<div class="flex items-center gap-2">
<span class="font-mono text-sm">{item.code}</span>
{#if item.isNew}
<Badge class="bg-green-600 hover:bg-green-600 text-[10px] px-1.5 py-0">NEW</Badge>
{/if}
</div>
{#if item.name}
<div class="truncate text-sm text-muted-foreground">{item.name}</div>
{/if}
</div>
<Badge variant={getSourceVariant(item.source)} class="ml-2 shrink-0">
{getSourceLabel(item.source)}
</Badge>
</button>
{/each}
{/if}
</div>
<div class="mt-4 flex items-center justify-between">
<div class="text-xs text-muted-foreground">
{filteredCodes().length} code{filteredCodes().length !== 1 ? 's' : ''} available
</div>
<Button variant="outline" onclick={() => (codePopupOpen = false)}>Cancel</Button>
</div>
</Dialog.Content>
</Dialog.Root>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,11 @@
import { redirect } from '@sveltejs/kit';
import { referenceFromPage } from '$lib/core/stores/recipeStore';
import { get } from 'svelte/store';
export function load() {
// Set reference so departments page knows to redirect to sheet
referenceFromPage.set('sheet');
// Redirect to departments page to select country
throw redirect(302, '/departments');
}

View file

@ -1,66 +1,149 @@
<script lang="ts">
import Button from '$lib/components/ui/button/button.svelte';
import Input from '$lib/components/ui/input/input.svelte';
import { SearchIcon } from '@lucide/svelte/icons';
import { onDestroy, onMount } from 'svelte';
import {
recipeData,
recipeFromServerQuery,
recipeOverviewData,
referenceFromPage
} from '$lib/core/stores/recipeStore.js';
import { sendCommandRequest, sendMessage } from '$lib/core/handlers/ws_messageSender.js';
import { auth } from '$lib/core/stores/auth.js';
import { onMount, onDestroy } from 'svelte';
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { get } from 'svelte/store';
import { getRecipes } from '$lib/core/client/server.js';
import { departmentStore } from '$lib/core/stores/departments';
import { addNotification } from '$lib/core/stores/noti.js';
import { departmentStore } from '$lib/core/stores/departments.js';
import { referenceFromPage } from '$lib/core/stores/recipeStore.js';
import {
sheetCatalogs,
sheetCatalogsLoading,
type Catalog
} from '$lib/core/stores/sheetStore.js';
import { waitForOpenSocket } from '$lib/core/stores/websocketStore.js';
import { requestCatalogs } from '$lib/core/services/sheetService.js';
let refDepartment: string | undefined = $state();
import Button from '$lib/components/ui/button/button.svelte';
import * as Table from '$lib/components/ui/table/index.js';
import Badge from '$lib/components/ui/badge/badge.svelte';
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
import { RefreshCw } from '@lucide/svelte/icons';
onMount(async () => {
// do load recipe
refDepartment = get(departmentStore);
referenceFromPage.set('overview');
// Get country from route params or department store
let selectedCountry = $state<string>($page.params.country || get(departmentStore) || '');
let catalogs = $derived($sheetCatalogs);
let loading = $derived($sheetCatalogsLoading);
let error = $state<string | null>(null);
sendCommandRequest('sheet', {
country: refDepartment,
param: 'catalogs'
});
onMount(() => {
referenceFromPage.set('sheet');
// await getRecipes();
if (selectedCountry) {
void loadCatalogs();
}
});
// onDestroy(() => {
// unsubRecipeData();
// });
async function loadCatalogs() {
if (!selectedCountry) return;
error = null;
sheetCatalogsLoading.set(true);
sheetCatalogs.set([]);
const socket = await waitForOpenSocket();
if (!socket) {
error = 'WebSocket is still connecting. Please try again.';
sheetCatalogsLoading.set(false);
addNotification('ERR:WebSocket not connected');
return;
}
const sent = requestCatalogs(selectedCountry);
if (!sent) {
error = 'WebSocket not connected. Please try again.';
sheetCatalogsLoading.set(false);
addNotification('ERR:WebSocket not connected');
}
}
function handleEditCatalog(catalog: Catalog) {
if (catalog.status === 'locked') {
addNotification(`WARN:Catalog is locked by ${catalog.locked_by}`);
return;
}
goto(`/sheet/edit/${selectedCountry}/${catalog.catalog}`);
}
</script>
<div class="mx-8 flex">
<!-- header -->
<div class="w-full">
<!-- Header -->
<div class="mb-4 flex items-center justify-between">
<div>
<h1 class="m-8 text-4xl font-bold">Layout overview [ {refDepartment} ]</h1>
<h1 class="m-8 text-4xl font-bold">Sheet Overview</h1>
<p class="mx-8 my-0 text-muted-foreground">
Display menus from the spreadsheet current selected country
Catalogs for {selectedCountry.toUpperCase()}
</p>
</div>
<div class="mx-8 my-4 flex gap-2">
<Button variant="default">+ Create Menu</Button>
<div class="mr-8">
<Button variant="outline" onclick={loadCatalogs} disabled={loading}>
<RefreshCw class="mr-2 h-4 w-4" />
Refresh
</Button>
</div>
</div>
<!-- search bar -->
<!-- <div class="mx-4 my-8 flex w-full items-center justify-center gap-2">
<SearchIcon />
<Input type="text" placeholder="Search by id, product code, name or material" class="" />
</div> -->
<!-- filter -->
<!-- table -->
<!-- <div class="w-full overflow-auto">
<DataTable data={data.recipes} refPage="overview" {columns} />
</div> -->
<!-- Content Area -->
<div class="mx-8">
{#if loading}
<div class="flex h-64 items-center justify-center">
<Spinner class="h-12 w-12" />
<p class="ml-4 text-muted-foreground">
Loading catalogs for {selectedCountry}...
</p>
</div>
{:else if error}
<div class="rounded-md border border-red-200 bg-red-50 p-4">
<p class="text-sm text-red-600">{error}</p>
<Button variant="outline" size="sm" class="mt-2" onclick={loadCatalogs}>
<RefreshCw class="mr-2 h-4 w-4" />
Retry
</Button>
</div>
{:else if catalogs.length === 0}
<div class="flex h-64 items-center justify-center text-muted-foreground">
<p>No catalogs found for {selectedCountry}</p>
</div>
{:else}
<Table.Root>
<Table.Header>
<Table.Row>
<Table.Head>Catalog Name</Table.Head>
<Table.Head>Status</Table.Head>
<Table.Head>Locked By</Table.Head>
<Table.Head>Actions</Table.Head>
</Table.Row>
</Table.Header>
<Table.Body>
{#each catalogs as catalog}
<Table.Row>
<Table.Cell class="font-medium">{catalog.catalog}</Table.Cell>
<Table.Cell>
<Badge
variant={catalog.status === 'free' ? 'default' : 'secondary'}
>
{catalog.status.toUpperCase()}
</Badge>
</Table.Cell>
<Table.Cell class="text-muted-foreground">
{catalog.locked_by || '-'}
</Table.Cell>
<Table.Cell>
<Button
size="sm"
variant={catalog.status === 'free' ? 'default' : 'outline'}
onclick={() => handleEditCatalog(catalog)}
disabled={catalog.status === 'locked'}
>
{catalog.status === 'free' ? 'Edit' : 'Locked'}
</Button>
</Table.Cell>
</Table.Row>
{/each}
</Table.Body>
</Table.Root>
{/if}
</div>
</div>
</div>

View file

@ -0,0 +1,279 @@
<script lang="ts">
import { onMount } from 'svelte';
import { get } from 'svelte/store';
import { page } from '$app/stores';
import { goto } from '$app/navigation';
import { permission as currentPerms } from '$lib/core/stores/permissions.js';
import { addNotification } from '$lib/core/stores/noti.js';
import { departmentStore } from '$lib/core/stores/departments.js';
import {
sheetCatalogs,
sheetCatalogsLoading,
type Catalog
} from '$lib/core/stores/sheetStore.js';
import { waitForOpenSocket } from '$lib/core/stores/websocketStore.js';
import { requestCatalogs } from '$lib/core/services/sheetService.js';
import Button from '$lib/components/ui/button/button.svelte';
import * as Select from '$lib/components/ui/select/index.js';
import * as Card from '$lib/components/ui/card/index.js';
import Badge from '$lib/components/ui/badge/badge.svelte';
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
import { ArrowRight, Lock, RefreshCw, Star } from '@lucide/svelte/icons';
const mainCatalogNames = [
'page_catalog_group_coffee.skt',
'page_catalog_group_tea.skt',
'page_catalog_group_milk.skt',
'page_catalog_group_dessert.skt',
'page_catalog_group_whey.skt',
'page_catalog_group_health.skt',
'page_catalog_group_pepsi_7up.skt',
'page_catalog_group_other_other.skt'
];
const mainCatalogRank = new Map(mainCatalogNames.map((name, index) => [name, index]));
function isMainCatalog(catalogName: string): boolean {
return mainCatalogRank.has(catalogName);
}
function compareCatalogs(a: Catalog, b: Catalog): number {
const rankA = mainCatalogRank.get(a.catalog);
const rankB = mainCatalogRank.get(b.catalog);
if (rankA !== undefined && rankB !== undefined) return rankA - rankB;
if (rankA !== undefined) return -1;
if (rankB !== undefined) return 1;
return 0;
}
// Helper function to extract display name from catalog filename
function getCatalogDisplayName(catalogName: string): string {
const match = catalogName.match(/page_catalog_group_(\w+)\.skt/);
if (match && match[1]) {
return match[1].charAt(0).toUpperCase() + match[1].slice(1);
}
return catalogName;
}
let selectedCountry = $state<string>($page.params.country || '');
let catalogs = $derived($sheetCatalogs);
let sortedCatalogs = $derived([...catalogs].sort(compareCatalogs));
let loading = $derived($sheetCatalogsLoading);
let error = $state<string | null>(null);
let enabledCountries = $state<string[]>([]);
onMount(() => {
// Set department store
if (selectedCountry) {
departmentStore.set(selectedCountry);
}
// Extract enabled countries from permissions
const userPerms = get(currentPerms).filter((x) => x.startsWith('document.write'));
enabledCountries = userPerms.map((x) => x.split('.')[2]);
// Auto-load catalogs for the selected country
if (selectedCountry) {
void loadCatalogs();
}
// Retry permissions after 1 second if empty
if (enabledCountries.length === 0) {
setTimeout(() => {
const retryPerms = get(currentPerms).filter((x) => x.startsWith('document.write'));
enabledCountries = retryPerms.map((x) => x.split('.')[2]);
}, 1000);
}
});
async function loadCatalogs() {
if (!selectedCountry) return;
error = null;
sheetCatalogsLoading.set(true);
sheetCatalogs.set([]);
const socket = await waitForOpenSocket();
if (!socket) {
error = 'WebSocket is still connecting. Please try again.';
sheetCatalogsLoading.set(false);
addNotification('ERR:WebSocket not connected');
return;
}
const sent = requestCatalogs(selectedCountry);
if (!sent) {
error = 'WebSocket not connected. Please try again.';
sheetCatalogsLoading.set(false);
addNotification('ERR:WebSocket not connected');
}
}
function handleEditCatalog(catalog: Catalog) {
if (catalog.status === 'locked') {
addNotification(`WARN:Catalog is locked by ${catalog.locked_by}`);
return;
}
goto(`/sheet/edit/${selectedCountry}/${catalog.catalog}`);
}
</script>
<div
class="min-h-screen bg-background dark:bg-[radial-gradient(circle_at_top_left,rgba(20,184,166,0.10),transparent_30%),linear-gradient(180deg,rgba(15,23,42,0.20),transparent_34%)]"
>
<div class="w-full px-8 py-8">
<div class="mb-8 flex items-start justify-between gap-6">
<div class="min-w-0">
<h1 class="text-4xl leading-tight font-bold tracking-normal">
Sheet Overview [ {selectedCountry.toUpperCase()} ]
</h1>
<p class="mt-7 text-lg text-muted-foreground">
View available catalogs for {selectedCountry.toUpperCase()}
</p>
</div>
<Button
variant="outline"
class="h-12 rounded-lg border-border/80 px-5 font-semibold"
onclick={loadCatalogs}
disabled={loading}
>
{#if loading}
<Spinner class="mr-2 h-4 w-4" />
{:else}
<RefreshCw class="mr-2 h-4 w-4" />
{/if}
Refresh
</Button>
</div>
<div class="mb-7">
{#if enabledCountries.length === 0}
<p class="text-sm text-muted-foreground">
No countries available. Please check your permissions.
</p>
{:else}
<Select.Root
type="single"
value={selectedCountry}
onValueChange={(v) => {
if (v) {
selectedCountry = v;
goto(`/sheet/overview/${v}`);
}
}}
>
<Select.Trigger
class="h-11 w-64 rounded-lg border-border/80 bg-card/70 px-4 font-semibold"
>
{selectedCountry.toUpperCase()}
</Select.Trigger>
<Select.Content>
{#each enabledCountries as country}
<Select.Item value={country}>
{country.toUpperCase()}
</Select.Item>
{/each}
</Select.Content>
</Select.Root>
{/if}
</div>
<div>
{#if loading}
<div class="flex h-64 items-center justify-center rounded-lg border bg-card/50">
<Spinner class="h-12 w-12" />
<p class="ml-4 text-muted-foreground">
Loading catalogs for {selectedCountry}...
</p>
</div>
{:else if error}
<div class="rounded-lg border border-red-300 bg-red-50 p-4 dark:border-red-800 dark:bg-red-950/50">
<p class="text-sm text-red-700 dark:text-red-400">{error}</p>
<Button variant="outline" size="sm" class="mt-2" onclick={loadCatalogs}>
<RefreshCw class="mr-2 h-4 w-4" />
Retry
</Button>
</div>
{:else if sortedCatalogs.length === 0}
<div
class="flex h-64 items-center justify-center rounded-lg border bg-card/50 text-muted-foreground"
>
<p>No catalogs found for {selectedCountry}</p>
</div>
{:else}
<div class="grid grid-cols-1 gap-5 md:grid-cols-2 xl:grid-cols-4">
{#each sortedCatalogs as catalog}
<Card.Root
class="group min-h-[234px] rounded-xl border-border/80 bg-card/80 shadow-sm transition-colors hover:border-border hover:bg-card"
>
<Card.Header class="px-6 pt-7 pb-4">
<div class="flex items-start justify-between gap-3">
<Card.Title class="text-xl font-bold tracking-normal">
{getCatalogDisplayName(catalog.catalog)} group
</Card.Title>
{#if isMainCatalog(catalog.catalog)}
<Badge
variant="secondary"
class="inline-flex shrink-0 items-center gap-1 rounded-full border-yellow-500/30 bg-yellow-500/15 px-2.5 py-1 text-xs text-yellow-700 dark:text-yellow-200"
>
<Star class="h-3 w-3 fill-yellow-500 text-yellow-500 dark:fill-yellow-300 dark:text-yellow-300" />
Main
</Badge>
{/if}
</div>
<!-- <p class="mt-3 truncate text-sm text-muted-foreground">
{catalog.catalog}
</p> -->
</Card.Header>
<Card.Content class="px-6 pb-4">
<div class="mt-3 flex min-h-8 items-center gap-3">
{#if catalog.status === 'free'}
<Badge
class="inline-flex rounded-full bg-green-600 px-3 py-1 text-xs text-white hover:bg-green-600"
>
<span class="mr-2 h-1.5 w-1.5 rounded-full bg-green-200"></span>
Available
</Badge>
<span class="flex items-center gap-2 text-sm text-muted-foreground">
<span class="h-1.5 w-1.5 rounded-full bg-green-500"></span>
Ready to edit
</span>
{:else}
<Badge
variant="secondary"
class="flex items-center gap-1 rounded-full px-3 py-1"
>
<Lock class="h-3 w-3" />
Locked
</Badge>
<span class="truncate text-sm text-muted-foreground">
{catalog.locked_by || 'In use'}
</span>
{/if}
</div>
</Card.Content>
<Card.Footer class="px-6 pt-2 pb-6">
<Button
variant="outline"
disabled={catalog.status === 'locked'}
class="h-11 w-full justify-center rounded-lg border-border/80 bg-background/35 font-semibold transition-colors group-hover:bg-background/55"
onclick={() => handleEditCatalog(catalog)}
>
<span class="flex-1 text-center">
{catalog.status === 'free' ? 'Edit' : 'Locked'}
</span>
{#if catalog.status === 'free'}
<ArrowRight class="h-4 w-4" />
{/if}
</Button>
</Card.Footer>
</Card.Root>
{/each}
</div>
{/if}
</div>
</div>
</div>