Merge branch 'dev' into 'master'
feat: new test mode for video See merge request Pakin/supra-app!9
This commit is contained in:
commit
984865943b
7 changed files with 563 additions and 15 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
|
// Handle gen-service responses
|
||||||
if (from === 'gen-service') {
|
if (from === 'gen-service') {
|
||||||
switch (level) {
|
switch (level) {
|
||||||
case 'batch_start':
|
case 'batch_start': {
|
||||||
|
const genRef = p.ref ?? 'gen-layout';
|
||||||
handleGenLayoutBatchStart({
|
handleGenLayoutBatchStart({
|
||||||
batch_id: p.batch_id,
|
batch_id: p.batch_id,
|
||||||
total_files: p.total_files,
|
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;
|
break;
|
||||||
|
}
|
||||||
case 'file':
|
case 'file':
|
||||||
handleGenLayoutFile({
|
handleGenLayoutFile({
|
||||||
batch_id: p.batch_id,
|
batch_id: p.batch_id,
|
||||||
|
|
@ -287,11 +296,11 @@ const handlers: Record<string, (payload: any) => void> = {
|
||||||
batch_id: p.batch_id,
|
batch_id: p.batch_id,
|
||||||
total_files: p.total_files
|
total_files: p.total_files
|
||||||
});
|
});
|
||||||
addNotification('INFO:Gen Layout complete');
|
addNotification('INFO:Generation complete');
|
||||||
break;
|
break;
|
||||||
case 'ERROR':
|
case 'ERROR':
|
||||||
handleGenLayoutError(msg);
|
handleGenLayoutError(msg);
|
||||||
addNotification(`ERR:Gen Layout error: ${msg}`);
|
addNotification(`ERR:Generation error: ${msg}`);
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
logger.info('[GenService] Received:', level, msg);
|
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);
|
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
|
* Request price data from sheet for specific product codes
|
||||||
* NOTE: Can only send once per type (price). Use hasSheetPriceBeenSent to check.
|
* NOTE: Can only send once per type (price). Use hasSheetPriceBeenSent to check.
|
||||||
|
|
|
||||||
|
|
@ -7,12 +7,20 @@ export interface GenLayoutFile {
|
||||||
file_index: number;
|
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 {
|
export interface GenLayoutBatch {
|
||||||
batch_id: string;
|
batch_id: string;
|
||||||
total_files: number;
|
total_files: number;
|
||||||
total_size_bytes: number;
|
total_size_bytes: number;
|
||||||
status: 'idle' | 'generating' | 'receiving' | 'complete' | 'error';
|
status: 'idle' | 'generating' | 'receiving' | 'complete' | 'error';
|
||||||
files: GenLayoutFile[];
|
files: GenLayoutFile[];
|
||||||
|
ref: GenKind;
|
||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -29,7 +37,8 @@ const initialState: GenLayoutBatch = {
|
||||||
total_files: 0,
|
total_files: 0,
|
||||||
total_size_bytes: 0,
|
total_size_bytes: 0,
|
||||||
status: 'idle',
|
status: 'idle',
|
||||||
files: []
|
files: [],
|
||||||
|
ref: 'gen-layout'
|
||||||
};
|
};
|
||||||
|
|
||||||
export const genLayoutBatch = writable<GenLayoutBatch>(initialState);
|
export const genLayoutBatch = writable<GenLayoutBatch>(initialState);
|
||||||
|
|
@ -52,15 +61,17 @@ export function handleGenLayoutBatchStart(payload: {
|
||||||
batch_id: string;
|
batch_id: string;
|
||||||
total_files: number;
|
total_files: number;
|
||||||
total_size_bytes: number;
|
total_size_bytes: number;
|
||||||
|
ref?: GenKind;
|
||||||
}) {
|
}) {
|
||||||
genLayoutBatch.set({
|
genLayoutBatch.set({
|
||||||
batch_id: payload.batch_id,
|
batch_id: payload.batch_id,
|
||||||
total_files: payload.total_files,
|
total_files: payload.total_files,
|
||||||
total_size_bytes: payload.total_size_bytes,
|
total_size_bytes: payload.total_size_bytes,
|
||||||
status: 'receiving',
|
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: {
|
export function handleGenLayoutFile(payload: {
|
||||||
|
|
@ -79,7 +90,10 @@ export function handleGenLayoutFile(payload: {
|
||||||
|
|
||||||
if (payload.is_chunked) {
|
if (payload.is_chunked) {
|
||||||
const fileIndex = payload.file_index;
|
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;
|
const totalParts = payload.total_parts ?? 1;
|
||||||
|
|
||||||
// Get or create tracker for this file
|
// Get or create tracker for this file
|
||||||
|
|
@ -242,9 +256,10 @@ export function resetGenLayoutBatch() {
|
||||||
chunkedFiles.clear();
|
chunkedFiles.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setGenLayoutGenerating() {
|
export function setGenLayoutGenerating(ref: GenKind = 'gen-layout') {
|
||||||
genLayoutBatch.update((batch) => ({
|
genLayoutBatch.update((batch) => ({
|
||||||
...batch,
|
...batch,
|
||||||
|
ref,
|
||||||
status: 'generating'
|
status: 'generating'
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -24,6 +24,7 @@
|
||||||
import * as Table from '$lib/components/ui/table/index.js';
|
import * as Table from '$lib/components/ui/table/index.js';
|
||||||
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
|
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
|
||||||
import { Plus, RefreshCw, Save } from '@lucide/svelte/icons';
|
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 selectedCountry = $state<string>($page.params.country || get(departmentStore) || '');
|
||||||
let search = $state('');
|
let search = $state('');
|
||||||
|
|
@ -211,6 +212,12 @@
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{#if selectedCountry}
|
||||||
|
<div class="mb-5">
|
||||||
|
<GenPricePanel country={selectedCountry} mode="price" />
|
||||||
|
</div>
|
||||||
|
{/if}
|
||||||
|
|
||||||
<div
|
<div
|
||||||
class="mb-5 grid gap-3 rounded-xl border bg-card/60 p-4 lg:grid-cols-[1fr_180px_180px_140px_auto]"
|
class="mb-5 grid gap-3 rounded-xl border bg-card/60 p-4 lg:grid-cols-[1fr_180px_180px_140px_auto]"
|
||||||
>
|
>
|
||||||
|
|
|
||||||
|
|
@ -10,6 +10,7 @@
|
||||||
import Badge from '$lib/components/ui/badge/badge.svelte';
|
import Badge from '$lib/components/ui/badge/badge.svelte';
|
||||||
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
|
import Spinner from '$lib/components/ui/spinner/spinner.svelte';
|
||||||
import Progress from '$lib/components/ui/progress/progress.svelte';
|
import Progress from '$lib/components/ui/progress/progress.svelte';
|
||||||
|
import { Checkbox } from '$lib/components/ui/checkbox/index.js';
|
||||||
import {
|
import {
|
||||||
Upload,
|
Upload,
|
||||||
X,
|
X,
|
||||||
|
|
@ -22,7 +23,8 @@
|
||||||
CalendarDays,
|
CalendarDays,
|
||||||
Clock,
|
Clock,
|
||||||
ChevronDown,
|
ChevronDown,
|
||||||
ImageIcon
|
ImageIcon,
|
||||||
|
FlaskConical
|
||||||
} from '@lucide/svelte/icons';
|
} from '@lucide/svelte/icons';
|
||||||
import * as adb from '$lib/core/adb/adb';
|
import * as adb from '$lib/core/adb/adb';
|
||||||
import { env } from '$env/dynamic/public';
|
import { env } from '$env/dynamic/public';
|
||||||
|
|
@ -32,6 +34,7 @@
|
||||||
const CREATE_ENDPOINT = '/api/video-mainpage';
|
const CREATE_ENDPOINT = '/api/video-mainpage';
|
||||||
const LIST_ENDPOINT = '/api/video-mainpage/list';
|
const LIST_ENDPOINT = '/api/video-mainpage/list';
|
||||||
const UPDATE_ENDPOINT = '/api/video-mainpage/update';
|
const UPDATE_ENDPOINT = '/api/video-mainpage/update';
|
||||||
|
const TESTMODE_ENDPOINT = '/api/video-mainpage/testmode';
|
||||||
const MACHINE_PROJECT_DIR = '/sdcard/coffeevending/taobin_project';
|
const MACHINE_PROJECT_DIR = '/sdcard/coffeevending/taobin_project';
|
||||||
const GET_IMAGE = env.PUBLIC_GET_IMAGE;
|
const GET_IMAGE = env.PUBLIC_GET_IMAGE;
|
||||||
const DURATION_TRIM = 4; // brewing play seconds = video length − 4
|
const DURATION_TRIM = 4; // brewing play seconds = video length − 4
|
||||||
|
|
@ -103,6 +106,26 @@
|
||||||
let pushProgress = $state({ percent: 0, name: '', active: false });
|
let pushProgress = $state({ percent: 0, name: '', active: false });
|
||||||
let isAdbConnected = $derived(Boolean(AdbInstance.instance));
|
let isAdbConnected = $derived(Boolean(AdbInstance.instance));
|
||||||
|
|
||||||
|
// ── test mode (machine-local date/time override) ─────────────────────────
|
||||||
|
// '' = unset (leave that clock field on the real value).
|
||||||
|
let testMonth = $state('');
|
||||||
|
let testDay = $state('');
|
||||||
|
let testHour = $state('');
|
||||||
|
let testMinute = $state('');
|
||||||
|
let testEnabled = $state(true); // emits `Var TestMode = 1` so the gate fires
|
||||||
|
let applyingTest = $state(false);
|
||||||
|
const hasTestValues = $derived(
|
||||||
|
[testMonth, testDay, testHour, testMinute].some((v) => v !== '')
|
||||||
|
);
|
||||||
|
|
||||||
|
// Dropdown options. Hour/minute are zero-padded for display; the value is the
|
||||||
|
// plain number string (the backend parses it with int()).
|
||||||
|
const MONTH_OPTS = Array.from({ length: 12 }, (_, i) => String(i + 1));
|
||||||
|
const DAY_OPTS = Array.from({ length: 31 }, (_, i) => String(i + 1));
|
||||||
|
const HOUR_OPTS = Array.from({ length: 24 }, (_, i) => String(i));
|
||||||
|
const MINUTE_OPTS = Array.from({ length: 60 }, (_, i) => String(i));
|
||||||
|
const pad2 = (s: string) => s.padStart(2, '0');
|
||||||
|
|
||||||
// ── list ────────────────────────────────────────────────────────────────
|
// ── list ────────────────────────────────────────────────────────────────
|
||||||
let managed = $state<ManagedVideo[]>([]);
|
let managed = $state<ManagedVideo[]>([]);
|
||||||
let readonlyList = $state<ReadonlyVideo[]>([]);
|
let readonlyList = $state<ReadonlyVideo[]>([]);
|
||||||
|
|
@ -286,6 +309,49 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Inject (or, when `clear`, remove) the TestMode date/time override in the
|
||||||
|
// header of the web scripts and push them to the connected machine over ADB.
|
||||||
|
// Never touches git/FTP — this override is machine-local by design.
|
||||||
|
async function applyTestMode(clear = false) {
|
||||||
|
if (!AdbInstance.instance) return addNotification('ERR:Connect a machine first');
|
||||||
|
const body = clear
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
enabled: testEnabled,
|
||||||
|
month: testMonth,
|
||||||
|
day: testDay,
|
||||||
|
hour: testHour,
|
||||||
|
minute: testMinute
|
||||||
|
};
|
||||||
|
applyingTest = true;
|
||||||
|
pushProgress = { percent: 0, name: '', active: true };
|
||||||
|
try {
|
||||||
|
const res = await fetch(`${TESTMODE_ENDPOINT}?country=${encodeURIComponent(country)}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
});
|
||||||
|
const result = await res.json().catch(() => ({}));
|
||||||
|
if (!res.ok) throw new Error(result?.message || result?.detail || 'Test-mode apply failed');
|
||||||
|
await pushScripts(result?.content?.scripts ?? []);
|
||||||
|
if (result?.cleared) {
|
||||||
|
testMonth = testDay = testHour = testMinute = '';
|
||||||
|
testEnabled = false;
|
||||||
|
addNotification(`INFO:Test mode cleared on machine (${country})`);
|
||||||
|
} else {
|
||||||
|
const o = result?.override ?? {};
|
||||||
|
addNotification(
|
||||||
|
`INFO:Test mode pushed to machine — ${o.month ?? '–'}/${o.day ?? '–'} ${o.hour ?? '–'}:${o.minute ?? '–'} (${country})`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
addNotification(`ERR:${error instanceof Error ? error.message : 'Test-mode failed'}`);
|
||||||
|
} finally {
|
||||||
|
applyingTest = false;
|
||||||
|
pushProgress = { percent: 0, name: '', active: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function handleSubmit() {
|
async function handleSubmit() {
|
||||||
const user = $auth;
|
const user = $auth;
|
||||||
if (!user) return addNotification('ERR:Not logged in');
|
if (!user) return addNotification('ERR:Not logged in');
|
||||||
|
|
@ -336,9 +402,15 @@
|
||||||
);
|
);
|
||||||
await pushScripts(result?.content?.scripts ?? []);
|
await pushScripts(result?.content?.scripts ?? []);
|
||||||
|
|
||||||
if (result?.sftp?.error)
|
if (result?.duplicate) {
|
||||||
addNotification(`WARN:Uploaded but FTP sync failed: ${result.sftp.error}`);
|
addNotification(
|
||||||
addNotification(`INFO:Added "${name.trim()}" as brewing_adv${result.n} (${country})`);
|
`WARN:"${name.trim()}" already exists as brewing_adv${result.n} — pushed to machine, no duplicate created`
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
if (result?.sftp?.error)
|
||||||
|
addNotification(`WARN:Uploaded but FTP sync failed: ${result.sftp.error}`);
|
||||||
|
addNotification(`INFO:Added "${name.trim()}" as brewing_adv${result.n} (${country})`);
|
||||||
|
}
|
||||||
clearMain();
|
clearMain();
|
||||||
clearBrewing();
|
clearBrewing();
|
||||||
clearBrewingTxt();
|
clearBrewingTxt();
|
||||||
|
|
@ -709,6 +781,100 @@
|
||||||
</Card.Footer>
|
</Card.Footer>
|
||||||
</Card.Root>
|
</Card.Root>
|
||||||
|
|
||||||
|
<!-- Test mode (machine-local date/time override) -->
|
||||||
|
<Card.Root class="overflow-hidden shadow-sm">
|
||||||
|
<Card.Header>
|
||||||
|
<Card.Title class="flex items-center gap-2 text-lg">
|
||||||
|
<FlaskConical class="h-5 w-5 text-muted-foreground" /> Test mode
|
||||||
|
</Card.Title>
|
||||||
|
<Card.Description>
|
||||||
|
Override the machine clock (<code class="font-mono">AdvSystem*</code>) to preview
|
||||||
|
date-gated videos. Gated by <code class="font-mono">TestMode = 1</code> and pushed to
|
||||||
|
the connected machine only — never committed or synced. Fill only what you need.
|
||||||
|
</Card.Description>
|
||||||
|
</Card.Header>
|
||||||
|
<Card.Content class="space-y-4">
|
||||||
|
<div class="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label class="text-xs">Month</Label>
|
||||||
|
<Select.Root type="single" bind:value={testMonth}>
|
||||||
|
<Select.Trigger class="w-full">{testMonth || '—'}</Select.Trigger>
|
||||||
|
<Select.Content class="max-h-60">
|
||||||
|
<Select.Item value="">—</Select.Item>
|
||||||
|
{#each MONTH_OPTS as m}
|
||||||
|
<Select.Item value={m}>{m}</Select.Item>
|
||||||
|
{/each}
|
||||||
|
</Select.Content>
|
||||||
|
</Select.Root>
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label class="text-xs">Day</Label>
|
||||||
|
<Select.Root type="single" bind:value={testDay}>
|
||||||
|
<Select.Trigger class="w-full">{testDay || '—'}</Select.Trigger>
|
||||||
|
<Select.Content class="max-h-60">
|
||||||
|
<Select.Item value="">—</Select.Item>
|
||||||
|
{#each DAY_OPTS as d}
|
||||||
|
<Select.Item value={d}>{d}</Select.Item>
|
||||||
|
{/each}
|
||||||
|
</Select.Content>
|
||||||
|
</Select.Root>
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label class="text-xs">Hour</Label>
|
||||||
|
<Select.Root type="single" bind:value={testHour}>
|
||||||
|
<Select.Trigger class="w-full">{testHour === '' ? '—' : pad2(testHour)}</Select.Trigger>
|
||||||
|
<Select.Content class="max-h-60">
|
||||||
|
<Select.Item value="">—</Select.Item>
|
||||||
|
{#each HOUR_OPTS as h}
|
||||||
|
<Select.Item value={h}>{pad2(h)}</Select.Item>
|
||||||
|
{/each}
|
||||||
|
</Select.Content>
|
||||||
|
</Select.Root>
|
||||||
|
</div>
|
||||||
|
<div class="space-y-1.5">
|
||||||
|
<Label class="text-xs">Minute</Label>
|
||||||
|
<Select.Root type="single" bind:value={testMinute}>
|
||||||
|
<Select.Trigger class="w-full"
|
||||||
|
>{testMinute === '' ? '—' : pad2(testMinute)}</Select.Trigger
|
||||||
|
>
|
||||||
|
<Select.Content class="max-h-60">
|
||||||
|
<Select.Item value="">—</Select.Item>
|
||||||
|
{#each MINUTE_OPTS as mi}
|
||||||
|
<Select.Item value={mi}>{pad2(mi)}</Select.Item>
|
||||||
|
{/each}
|
||||||
|
</Select.Content>
|
||||||
|
</Select.Root>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label class="flex w-fit items-center gap-2 text-sm">
|
||||||
|
<Checkbox bind:checked={testEnabled} />
|
||||||
|
Enable test mode <code class="font-mono text-xs">(Var TestMode = 1)</code>
|
||||||
|
</label>
|
||||||
|
<div class="flex flex-wrap items-center gap-2">
|
||||||
|
<Button
|
||||||
|
onclick={() => applyTestMode(false)}
|
||||||
|
disabled={applyingTest || !isAdbConnected || (!hasTestValues && !testEnabled)}
|
||||||
|
>
|
||||||
|
{#if applyingTest}
|
||||||
|
<Spinner class="mr-2 h-4 w-4" />Applying...
|
||||||
|
{:else}
|
||||||
|
<MonitorPlay class="mr-2 h-4 w-4" />Apply to machine
|
||||||
|
{/if}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
onclick={() => applyTestMode(true)}
|
||||||
|
disabled={applyingTest || !isAdbConnected}
|
||||||
|
>
|
||||||
|
Clear override
|
||||||
|
</Button>
|
||||||
|
{#if !isAdbConnected}
|
||||||
|
<span class="text-xs text-muted-foreground">Connect a machine to apply.</span>
|
||||||
|
{/if}
|
||||||
|
</div>
|
||||||
|
</Card.Content>
|
||||||
|
</Card.Root>
|
||||||
|
|
||||||
<!-- Existing -->
|
<!-- Existing -->
|
||||||
<div class="space-y-3">
|
<div class="space-y-3">
|
||||||
<div class="flex items-center justify-between">
|
<div class="flex items-center justify-between">
|
||||||
|
|
|
||||||
32
src/routes/api/video-mainpage/testmode/+server.ts
Normal file
32
src/routes/api/video-mainpage/testmode/+server.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
||||||
|
import { json, error } from '@sveltejs/kit';
|
||||||
|
import type { RequestHandler } from './$types';
|
||||||
|
import { env } from '$env/dynamic/public';
|
||||||
|
|
||||||
|
const API_BASE = env.PUBLIC_POST_IMAGE;
|
||||||
|
|
||||||
|
// Return the country's web video scripts with a TestMode date/time override
|
||||||
|
// injected (or removed). The caller pushes the result to a machine over ADB —
|
||||||
|
// nothing is committed or synced. POST because the Kong route is POST-only.
|
||||||
|
export const POST: RequestHandler = async ({ url, request }) => {
|
||||||
|
try {
|
||||||
|
const country = (url.searchParams.get('country') || 'tha').toLowerCase();
|
||||||
|
const body = await request.json().catch(() => ({}));
|
||||||
|
const response = await fetch(
|
||||||
|
`${API_BASE}/video/mainpage/testmode/${encodeURIComponent(country)}`,
|
||||||
|
{
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(body)
|
||||||
|
}
|
||||||
|
);
|
||||||
|
if (!response.ok) {
|
||||||
|
const e = await response.json().catch(() => ({ detail: response.statusText }));
|
||||||
|
throw error(response.status, e.detail || 'Test-mode apply failed');
|
||||||
|
}
|
||||||
|
return json(await response.json());
|
||||||
|
} catch (err) {
|
||||||
|
console.error('[Video MainPage TestMode Proxy] Error:', err);
|
||||||
|
if (err && typeof err === 'object' && 'status' in err) throw err;
|
||||||
|
throw error(500, err instanceof Error ? err.message : 'Internal server error');
|
||||||
|
}
|
||||||
|
};
|
||||||
Loading…
Add table
Add a link
Reference in a new issue