add: New Gen Price & Gen PriceSlot
This commit is contained in:
parent
c6b528d5eb
commit
be0dfb7f63
5 changed files with 361 additions and 11 deletions
246
src/lib/components/gen-price-panel.svelte
Normal file
246
src/lib/components/gen-price-panel.svelte
Normal file
|
|
@ -0,0 +1,246 @@
|
|||
<script lang="ts">
|
||||
import { logger } from '$lib/core/utils/logger';
|
||||
import { addNotification } from '$lib/core/stores/noti.js';
|
||||
import Button from '$lib/components/ui/button/button.svelte';
|
||||
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
|
||||
import Progress from '$lib/components/ui/progress/progress.svelte';
|
||||
import * as Dialog from '$lib/components/ui/dialog/index.js';
|
||||
import { Cog, Upload, RotateCcw } from '@lucide/svelte/icons';
|
||||
|
||||
import * as adb from '$lib/core/adb/adb';
|
||||
import {
|
||||
genLayoutBatch,
|
||||
resetGenLayoutBatch
|
||||
} from '$lib/core/stores/genLayoutStore.js';
|
||||
import { requestGenPrice, requestGenPriceSlot } from '$lib/core/services/sheetService.js';
|
||||
|
||||
// Reusable "Gen Price" / "Gen PriceSlot" panel: triggers gen-service, receives
|
||||
// the streamed profile JSON via the shared genLayoutBatch store, pushes the
|
||||
// files to the machine over ADB, then offers an app restart.
|
||||
let { country, mode }: { country: string; mode: 'price' | 'priceslot' } = $props();
|
||||
|
||||
const sourceDir = '/sdcard/coffeevending';
|
||||
const label = mode === 'price' ? 'Gen Price' : 'Gen PriceSlot';
|
||||
const expectedRef = mode === 'price' ? 'gen-price' : 'gen-priceslot';
|
||||
|
||||
let status = $derived($genLayoutBatch.status);
|
||||
let files = $derived($genLayoutBatch.files);
|
||||
// Only reflect progress for our own kind (the store is shared across pages).
|
||||
let isOurs = $derived($genLayoutBatch.ref === expectedRef);
|
||||
let busy = $derived(isOurs && (status === 'generating' || status === 'receiving'));
|
||||
|
||||
let pushing = $state(false);
|
||||
let pushProgress = $state({ current: 0, total: 0 });
|
||||
let restartOpen = $state(false);
|
||||
let restarting = $state(false);
|
||||
|
||||
function machineConnected(): boolean {
|
||||
return Boolean(adb.getAdbInstance());
|
||||
}
|
||||
|
||||
function startGen() {
|
||||
if (!machineConnected()) {
|
||||
addNotification('ERR:Machine not connected. Cannot push files to Android.');
|
||||
return;
|
||||
}
|
||||
resetGenLayoutBatch();
|
||||
const sent = mode === 'price' ? requestGenPrice(country) : requestGenPriceSlot(country);
|
||||
if (!sent) {
|
||||
addNotification('ERR:WebSocket not connected');
|
||||
}
|
||||
}
|
||||
|
||||
// Web-gen produces "_web" profile variants in the recipe repo (so the canonical
|
||||
// master is never overwritten). Map them to the machine's ACTIVE profile name:
|
||||
// - drop the "_web" marker, and
|
||||
// - for master files replace "master" -> "1" and drop any leading dot.
|
||||
// profile_master_web.json -> /sdcard/coffeevending/profile/profile_1.json
|
||||
// profile_AUS_master_web.json -> /sdcard/coffeevending/profile/profile_AUS_1.json
|
||||
// price/profile_<T>_slot_<N>_web.json -> .../profile/price/profile_<T>_slot_<N>.json
|
||||
// Slots are detected by a "/price/" segment.
|
||||
function toMachinePath(genFilePath: string): string {
|
||||
const isSlot = genFilePath.includes('/price/');
|
||||
let filename = (genFilePath.split('/').pop() || '').replace('_web', '');
|
||||
if (!isSlot) {
|
||||
filename = filename.replace('master', '1');
|
||||
if (filename.startsWith('.')) filename = filename.slice(1);
|
||||
}
|
||||
return isSlot
|
||||
? `${sourceDir}/profile/price/${filename}`
|
||||
: `${sourceDir}/profile/${filename}`;
|
||||
}
|
||||
|
||||
async function pushAll() {
|
||||
if (!machineConnected()) {
|
||||
addNotification('ERR:Machine not connected');
|
||||
return;
|
||||
}
|
||||
const list = $genLayoutBatch.files;
|
||||
if (list.length === 0) {
|
||||
addNotification('WARN:No files to push');
|
||||
return;
|
||||
}
|
||||
|
||||
pushing = true;
|
||||
pushProgress = { current: 0, total: list.length };
|
||||
try {
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const file = list[i];
|
||||
const androidPath = toMachinePath(file.file);
|
||||
const parentDir = androidPath.slice(0, androidPath.lastIndexOf('/'));
|
||||
await adb.executeCmd(`mkdir -p "${parentDir}"`);
|
||||
await adb.push(androidPath, file.content);
|
||||
pushProgress = { current: i + 1, total: list.length };
|
||||
logger.info(`[${label}] Pushed ${i + 1}/${list.length}: ${androidPath}`);
|
||||
}
|
||||
addNotification(`INFO:Pushed ${list.length} ${mode} file(s) to Android`);
|
||||
restartOpen = true;
|
||||
} catch (error) {
|
||||
logger.error(`[${label}] Push error:`, error);
|
||||
addNotification(`ERR:Failed to push files: ${error}`);
|
||||
} finally {
|
||||
pushing = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmRestart() {
|
||||
if (!machineConnected()) {
|
||||
addNotification('ERR:Machine not connected');
|
||||
return;
|
||||
}
|
||||
restarting = true;
|
||||
try {
|
||||
// A price change only takes effect after a FULL device reboot (restarting
|
||||
// just the XMLEngine app is not enough for new profile prices).
|
||||
addNotification('INFO:Rebooting machine to apply new prices...');
|
||||
await adb.executeCmd('reboot');
|
||||
addNotification('INFO:Reboot command sent');
|
||||
restartOpen = false;
|
||||
} catch (error) {
|
||||
logger.error(`[${label}] Reboot error:`, error);
|
||||
addNotification(`ERR:Failed to reboot machine: ${error}`);
|
||||
} finally {
|
||||
restarting = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="rounded-lg border bg-muted/30 p-4">
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h4 class="font-semibold">{label}</h4>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
Generate and push {mode === 'price' ? 'price' : 'price-slot'} profile files to Machine
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<Button variant="outline" onclick={startGen} disabled={busy || pushing}>
|
||||
{#if busy}
|
||||
<Spinner class="mr-2 h-4 w-4" />
|
||||
{status === 'generating' ? 'Generating...' : 'Receiving...'}
|
||||
{:else}
|
||||
<Cog class="mr-2 h-4 w-4" />
|
||||
{label}
|
||||
{/if}
|
||||
</Button>
|
||||
|
||||
{#if isOurs && status === 'complete' && files.length > 0}
|
||||
<Button variant="default" onclick={pushAll} disabled={pushing || !machineConnected()}>
|
||||
{#if pushing}
|
||||
<Spinner class="mr-2 h-4 w-4" />
|
||||
Pushing {pushProgress.current}/{pushProgress.total}...
|
||||
{:else}
|
||||
<Upload class="mr-2 h-4 w-4" />
|
||||
Push All ({files.length} files)
|
||||
{/if}
|
||||
</Button>
|
||||
{/if}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
onclick={() => (restartOpen = true)}
|
||||
disabled={pushing || restarting || !machineConnected()}
|
||||
>
|
||||
{#if restarting}
|
||||
<Spinner class="mr-2 h-4 w-4" />
|
||||
Rebooting...
|
||||
{:else}
|
||||
<RotateCcw class="mr-2 h-4 w-4" />
|
||||
Reboot Machine
|
||||
{/if}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if isOurs && status === 'receiving'}
|
||||
<div class="mt-4 space-y-2">
|
||||
<Progress
|
||||
value={$genLayoutBatch.total_files > 0
|
||||
? (files.length / $genLayoutBatch.total_files) * 100
|
||||
: 0}
|
||||
max={100}
|
||||
class="h-2"
|
||||
/>
|
||||
<p class="text-center text-xs text-muted-foreground">
|
||||
Receiving files: {files.length} / {$genLayoutBatch.total_files}
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if pushing}
|
||||
<div class="mt-4 space-y-2">
|
||||
<Progress
|
||||
value={pushProgress.total > 0 ? (pushProgress.current / pushProgress.total) * 100 : 0}
|
||||
max={100}
|
||||
class="h-2"
|
||||
/>
|
||||
<p class="text-center text-xs text-muted-foreground">
|
||||
Pushing to Android: {pushProgress.current} / {pushProgress.total}
|
||||
</p>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if isOurs && status === 'complete' && files.length > 0}
|
||||
<div class="mt-4">
|
||||
<p class="mb-2 text-sm font-medium">Generated {files.length} file(s):</p>
|
||||
<div class="max-h-32 overflow-y-auto rounded border bg-background p-2">
|
||||
{#each files as file}
|
||||
<div class="truncate font-mono text-xs text-muted-foreground">
|
||||
{file.file.split('/').pop()}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
{#if isOurs && status === 'error'}
|
||||
<div class="mt-4 rounded border border-red-200 bg-red-50 p-3">
|
||||
<p class="text-sm text-red-600">{$genLayoutBatch.error}</p>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
<Dialog.Root bind:open={restartOpen}>
|
||||
<Dialog.Content class="sm:max-w-md">
|
||||
<Dialog.Header>
|
||||
<Dialog.Title>Reboot Machine?</Dialog.Title>
|
||||
<Dialog.Description>
|
||||
New {mode} prices only take effect after a full device reboot. The machine
|
||||
will restart — this takes a few minutes.
|
||||
</Dialog.Description>
|
||||
</Dialog.Header>
|
||||
<div class="flex justify-end gap-3">
|
||||
<Button variant="outline" onclick={() => (restartOpen = false)} disabled={restarting}>
|
||||
Later
|
||||
</Button>
|
||||
<Button onclick={confirmRestart} disabled={restarting}>
|
||||
{#if restarting}
|
||||
<Spinner class="mr-2 h-4 w-4" />
|
||||
{:else}
|
||||
<RotateCcw class="mr-2 h-4 w-4" />
|
||||
{/if}
|
||||
Reboot Now
|
||||
</Button>
|
||||
</div>
|
||||
</Dialog.Content>
|
||||
</Dialog.Root>
|
||||
|
|
@ -261,14 +261,23 @@ const handlers: Record<string, (payload: any) => void> = {
|
|||
// Handle gen-service responses
|
||||
if (from === 'gen-service') {
|
||||
switch (level) {
|
||||
case 'batch_start':
|
||||
case 'batch_start': {
|
||||
const genRef = p.ref ?? 'gen-layout';
|
||||
handleGenLayoutBatchStart({
|
||||
batch_id: p.batch_id,
|
||||
total_files: p.total_files,
|
||||
total_size_bytes: p.total_size_bytes
|
||||
total_size_bytes: p.total_size_bytes,
|
||||
ref: genRef
|
||||
});
|
||||
addNotification(`INFO:Gen Layout started (${p.total_files} files)`);
|
||||
const genLabel =
|
||||
genRef === 'gen-price'
|
||||
? 'Gen Price'
|
||||
: genRef === 'gen-priceslot'
|
||||
? 'Gen PriceSlot'
|
||||
: 'Gen Layout';
|
||||
addNotification(`INFO:${genLabel} started (${p.total_files} files)`);
|
||||
break;
|
||||
}
|
||||
case 'file':
|
||||
handleGenLayoutFile({
|
||||
batch_id: p.batch_id,
|
||||
|
|
@ -287,11 +296,11 @@ const handlers: Record<string, (payload: any) => void> = {
|
|||
batch_id: p.batch_id,
|
||||
total_files: p.total_files
|
||||
});
|
||||
addNotification('INFO:Gen Layout complete');
|
||||
addNotification('INFO:Generation complete');
|
||||
break;
|
||||
case 'ERROR':
|
||||
handleGenLayoutError(msg);
|
||||
addNotification(`ERR:Gen Layout error: ${msg}`);
|
||||
addNotification(`ERR:Generation error: ${msg}`);
|
||||
break;
|
||||
default:
|
||||
logger.info('[GenService] Received:', level, msg);
|
||||
|
|
|
|||
|
|
@ -325,7 +325,7 @@ export async function requestGenLayout(country: string): Promise<boolean> {
|
|||
};
|
||||
}
|
||||
|
||||
setGenLayoutGenerating();
|
||||
setGenLayoutGenerating('gen-layout');
|
||||
|
||||
logger.info('[sheetService] Sending gen-layout request for country:', country);
|
||||
|
||||
|
|
@ -344,6 +344,79 @@ export async function requestGenLayout(country: string): Promise<boolean> {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger gen-service to (re)generate the machine price profile from Grist.
|
||||
* Backend: taobin_admin app.py `gen-price` branch -> gen_price_supra.gen_price.
|
||||
* Produces profile_<C>_master.json, commits to recipe-repo, streams files back
|
||||
* (ref='gen-price') for the frontend to push to the machine.
|
||||
*/
|
||||
export async function requestGenPrice(country: string): Promise<boolean> {
|
||||
const curr_user = get(auth);
|
||||
|
||||
let user_info: any = {};
|
||||
if (curr_user) {
|
||||
user_info = {
|
||||
displayName: curr_user.displayName,
|
||||
email: curr_user.email,
|
||||
uid: curr_user.uid
|
||||
};
|
||||
}
|
||||
|
||||
setGenLayoutGenerating('gen-price');
|
||||
|
||||
logger.info('[sheetService] Sending gen-price request for country:', country);
|
||||
|
||||
return await sendMessage({
|
||||
type: 'command',
|
||||
payload: {
|
||||
user_info,
|
||||
srv_name: 'gen-service',
|
||||
values: {
|
||||
file_layout: 'sheet',
|
||||
file_desc: 'sheet',
|
||||
country: country,
|
||||
param: 'gen-price-supra_app'
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Trigger gen-service to (re)generate the per-slot price profiles from Grist.
|
||||
* Backend: taobin_admin app.py `gen-priceslot` branch -> gen_price_supra.gen_priceslot.
|
||||
* Produces profile_<C>_slot_<N>.json (ref='gen-priceslot').
|
||||
*/
|
||||
export async function requestGenPriceSlot(country: string): Promise<boolean> {
|
||||
const curr_user = get(auth);
|
||||
|
||||
let user_info: any = {};
|
||||
if (curr_user) {
|
||||
user_info = {
|
||||
displayName: curr_user.displayName,
|
||||
email: curr_user.email,
|
||||
uid: curr_user.uid
|
||||
};
|
||||
}
|
||||
|
||||
setGenLayoutGenerating('gen-priceslot');
|
||||
|
||||
logger.info('[sheetService] Sending gen-priceslot request for country:', country);
|
||||
|
||||
return await sendMessage({
|
||||
type: 'command',
|
||||
payload: {
|
||||
user_info,
|
||||
srv_name: 'gen-service',
|
||||
values: {
|
||||
file_layout: 'sheet',
|
||||
file_desc: 'sheet',
|
||||
country: country,
|
||||
param: 'gen-priceslot-supra_app'
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Request price data from sheet for specific product codes
|
||||
* NOTE: Can only send once per type (price). Use hasSheetPriceBeenSent to check.
|
||||
|
|
|
|||
|
|
@ -7,12 +7,20 @@ export interface GenLayoutFile {
|
|||
file_index: number;
|
||||
}
|
||||
|
||||
// Kind of gen-service batch. Distinguishes which files were generated so the
|
||||
// push logic can map them to the correct machine path.
|
||||
// gen-layout -> layout files under taobin_project/
|
||||
// gen-price -> profile_<C>_master.json -> /sdcard/coffeevending/profile/
|
||||
// gen-priceslot -> profile_<C>_slot_<N>.json -> .../price/
|
||||
export type GenKind = 'gen-layout' | 'gen-price' | 'gen-priceslot';
|
||||
|
||||
export interface GenLayoutBatch {
|
||||
batch_id: string;
|
||||
total_files: number;
|
||||
total_size_bytes: number;
|
||||
status: 'idle' | 'generating' | 'receiving' | 'complete' | 'error';
|
||||
files: GenLayoutFile[];
|
||||
ref: GenKind;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
|
|
@ -29,7 +37,8 @@ const initialState: GenLayoutBatch = {
|
|||
total_files: 0,
|
||||
total_size_bytes: 0,
|
||||
status: 'idle',
|
||||
files: []
|
||||
files: [],
|
||||
ref: 'gen-layout'
|
||||
};
|
||||
|
||||
export const genLayoutBatch = writable<GenLayoutBatch>(initialState);
|
||||
|
|
@ -52,15 +61,17 @@ export function handleGenLayoutBatchStart(payload: {
|
|||
batch_id: string;
|
||||
total_files: number;
|
||||
total_size_bytes: number;
|
||||
ref?: GenKind;
|
||||
}) {
|
||||
genLayoutBatch.set({
|
||||
batch_id: payload.batch_id,
|
||||
total_files: payload.total_files,
|
||||
total_size_bytes: payload.total_size_bytes,
|
||||
status: 'receiving',
|
||||
files: []
|
||||
files: [],
|
||||
ref: payload.ref ?? get(genLayoutBatch).ref ?? 'gen-layout'
|
||||
});
|
||||
logger.info('[GenLayout] Batch started:', payload.batch_id, 'total files:', payload.total_files);
|
||||
logger.info('[GenLayout] Batch started:', payload.batch_id, 'ref:', payload.ref, 'total files:', payload.total_files);
|
||||
}
|
||||
|
||||
export function handleGenLayoutFile(payload: {
|
||||
|
|
@ -79,7 +90,10 @@ export function handleGenLayoutFile(payload: {
|
|||
|
||||
if (payload.is_chunked) {
|
||||
const fileIndex = payload.file_index;
|
||||
const partIndex = payload.part_index ?? 0;
|
||||
// Backend sends part_index 1-based (1..N); normalize to 0-based so it
|
||||
// matches the 0..totalParts-1 assembly loop below. Without this, part 1
|
||||
// was stored empty and the last chunk was dropped (files > 1MB corrupted).
|
||||
const partIndex = (payload.part_index ?? 1) - 1;
|
||||
const totalParts = payload.total_parts ?? 1;
|
||||
|
||||
// Get or create tracker for this file
|
||||
|
|
@ -242,9 +256,10 @@ export function resetGenLayoutBatch() {
|
|||
chunkedFiles.clear();
|
||||
}
|
||||
|
||||
export function setGenLayoutGenerating() {
|
||||
export function setGenLayoutGenerating(ref: GenKind = 'gen-layout') {
|
||||
genLayoutBatch.update((batch) => ({
|
||||
...batch,
|
||||
ref,
|
||||
status: 'generating'
|
||||
}));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@
|
|||
import * as Table from '$lib/components/ui/table/index.js';
|
||||
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
|
||||
import { Plus, RefreshCw, Save } from '@lucide/svelte/icons';
|
||||
import GenPricePanel from '$lib/components/gen-price-panel.svelte';
|
||||
|
||||
let selectedCountry = $state<string>($page.params.country || get(departmentStore) || '');
|
||||
let search = $state('');
|
||||
|
|
@ -211,6 +212,12 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{#if selectedCountry}
|
||||
<div class="mb-5">
|
||||
<GenPricePanel country={selectedCountry} mode="price" />
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div
|
||||
class="mb-5 grid gap-3 rounded-xl border bg-card/60 p-4 lg:grid-cols-[1fr_180px_180px_140px_auto]"
|
||||
>
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue