Products: create services from the admin
- "New service": from scratch (category, who does it — cleaner, driver, career consultant or docs agent —, fixed price and duration, online, name and description in 5 languages) or as a copy of an existing service (prices, questions, checklist, booking window and question texts copied). Created switched off; delete only without orders; reorder within a category. - "Questions in the order form" builder for fixed-price services: choice, number, text, yes/no, required flag; labels stored as text overrides. - The admin itself now loads text overrides, so new service names show right away; the mini app hides missing optional texts (description, option hints) instead of showing keys. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
0edc6432b7
commit
8866616782
8 files changed
+599
-13
No files matched your search
@@ -116,3 +116,10 @@
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
/* вопрос клиенту в редакторе услуги */
|
||||
.bo-qfield {
|
||||
padding: 12px;
|
||||
border-radius: 16px;
|
||||
background: var(--bo-soft);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createT as createSharedT, formatAmd, formatDateTime, type Locale as SharedLocale } from '@barev/i18n';
|
||||
import { createT as createSharedT, formatAmd, formatDateTime, onTextOverrides, textOverridesVersion, type Locale as SharedLocale } from '@barev/i18n';
|
||||
import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from 'react';
|
||||
|
||||
/** Языки новой админки */
|
||||
@@ -386,6 +386,47 @@ const ru = {
|
||||
'chat.notLinked': 'Рабочий бот не открыт',
|
||||
'chat.details': 'Подробнее',
|
||||
'chat.more': 'Ещё действия',
|
||||
'pr.newService': 'Новая услуга',
|
||||
'pr.newServiceHint': 'С нуля — с фиксированной ценой и вашими вопросами клиенту, или копией готовой услуги.',
|
||||
'pr.fromScratch': 'С нуля',
|
||||
'pr.copyOf': 'Копия готовой',
|
||||
'pr.category': 'Направление',
|
||||
'pr.copyFrom': 'Скопировать услугу',
|
||||
'pr.copyHint': 'Скопируются цены, вопросы клиенту, чек-лист и окно записи — потом поменяете что нужно. Так можно сделать, например, «Генеральную уборку офиса» из клининга.',
|
||||
'pr.who': 'Кто выполняет',
|
||||
'pr.whoHint': 'Определяет, кому система предлагает заказ и какие шаги видит исполнитель. Ремонт и уроки — только копией готовой услуги.',
|
||||
'pr.flowHint.CLEANER': 'выехал → работа → готово, с чек-листом',
|
||||
'pr.flowHint.DRIVER': 'водитель на месте → в пути → завершено',
|
||||
'pr.flowHint.CAREER_CONSULTANT': 'консультант → материалы → встреча → итог',
|
||||
'pr.flowHint.DOCS_AGENT': 'проверка документов → подача → готово',
|
||||
'pr.online': 'Онлайн — без адреса и выезда',
|
||||
'pr.namePh': 'Например: Мойка окон',
|
||||
'pr.create': 'Создать услугу',
|
||||
'pr.createHint': 'Услуга появится выключенной: настройте цену, вопросы и чек-лист, затем включите её в «Запись и отмена» — и она сразу появится в приложении.',
|
||||
'pr.created': 'Услуга создана — осталось настроить и включить',
|
||||
'pr.questions': 'Вопросы клиенту при заказе',
|
||||
'pr.questionsHint': 'Что клиент выбирает или пишет в форме заказа. Ответы видят исполнитель и команда.',
|
||||
'pr.qLabel': 'Вопрос, например «Сколько окон?»',
|
||||
'pr.qType.select': 'выбор варианта',
|
||||
'pr.qType.int': 'число',
|
||||
'pr.qType.text': 'текст',
|
||||
'pr.qType.bool': 'да / нет',
|
||||
'pr.qOption': 'Вариант {n}',
|
||||
'pr.qAddOption': 'вариант',
|
||||
'pr.qFrom': 'от',
|
||||
'pr.qTo': 'до',
|
||||
'pr.qRequired': 'обязательно',
|
||||
'pr.qAdd': 'Вопрос',
|
||||
'pr.qNone': 'Вопросов нет — клиент выберет только время и адрес.',
|
||||
'pr.delete': 'Удалить услугу',
|
||||
'pr.deleteConfirm': 'Удалить услугу? Можно, только если по ней ещё не было заказов — иначе выключите её.',
|
||||
'err.SERVICE_HAS_ORDERS': 'По услуге уже были заказы — удалить нельзя, выключите её в «Запись и отмена».',
|
||||
'err.OPTIONS_REQUIRED': 'У вопроса с выбором нужно минимум 2 варианта.',
|
||||
'err.PARAMS_LOCKED': 'У этой услуги цена зависит от ответов — вопросы меняются программистом.',
|
||||
'audit.bo.products.createService': 'создал(а) услугу',
|
||||
'audit.bo.products.saveParams': 'изменил(а) вопросы услуги',
|
||||
'audit.bo.products.deleteService': 'удалил(а) услугу',
|
||||
'audit.bo.products.moveService': 'изменил(а) порядок услуг',
|
||||
'audit.bo.crm.addTask': 'поставил(а) задачу',
|
||||
'audit.bo.crm.setTaskDone': 'отметил(а) задачу',
|
||||
'audit.bo.crm.removeTask': 'удалил(а) задачу',
|
||||
@@ -1441,6 +1482,47 @@ const en: Dict = {
|
||||
'chat.notLinked': 'Work bot not opened',
|
||||
'chat.details': 'Details',
|
||||
'chat.more': 'More actions',
|
||||
'pr.newService': 'New service',
|
||||
'pr.newServiceHint': 'From scratch with a fixed price and your own questions, or as a copy of an existing service.',
|
||||
'pr.fromScratch': 'From scratch',
|
||||
'pr.copyOf': 'Copy of existing',
|
||||
'pr.category': 'Category',
|
||||
'pr.copyFrom': 'Copy service',
|
||||
'pr.copyHint': 'Prices, questions, checklist and booking window are copied — change what you need. E.g. an “Office deep clean” from cleaning.',
|
||||
'pr.who': 'Who does it',
|
||||
'pr.whoHint': 'Decides who gets the order and which steps the provider sees. Repairs and lessons — only as a copy.',
|
||||
'pr.flowHint.CLEANER': 'on the way → work → done, with a checklist',
|
||||
'pr.flowHint.DRIVER': 'driver arrived → riding → done',
|
||||
'pr.flowHint.CAREER_CONSULTANT': 'consultant → materials → meeting → result',
|
||||
'pr.flowHint.DOCS_AGENT': 'document check → submission → done',
|
||||
'pr.online': 'Online — no address or visit',
|
||||
'pr.namePh': 'E.g. Window cleaning',
|
||||
'pr.create': 'Create service',
|
||||
'pr.createHint': 'The service starts switched off: set price, questions and checklist, then switch it on — it appears in the app right away.',
|
||||
'pr.created': 'Service created — set it up and switch it on',
|
||||
'pr.questions': 'Questions in the order form',
|
||||
'pr.questionsHint': 'What the client picks or types when ordering. The provider and team see the answers.',
|
||||
'pr.qLabel': 'Question, e.g. “How many windows?”',
|
||||
'pr.qType.select': 'choice',
|
||||
'pr.qType.int': 'number',
|
||||
'pr.qType.text': 'text',
|
||||
'pr.qType.bool': 'yes / no',
|
||||
'pr.qOption': 'Option {n}',
|
||||
'pr.qAddOption': 'option',
|
||||
'pr.qFrom': 'from',
|
||||
'pr.qTo': 'to',
|
||||
'pr.qRequired': 'required',
|
||||
'pr.qAdd': 'Question',
|
||||
'pr.qNone': 'No questions — the client picks only time and address.',
|
||||
'pr.delete': 'Delete service',
|
||||
'pr.deleteConfirm': 'Delete the service? Only possible without orders — otherwise switch it off.',
|
||||
'err.SERVICE_HAS_ORDERS': 'The service has orders — switch it off instead.',
|
||||
'err.OPTIONS_REQUIRED': 'A choice question needs at least 2 options.',
|
||||
'err.PARAMS_LOCKED': 'This service’s price depends on the answers — questions are changed by a developer.',
|
||||
'audit.bo.products.createService': 'created a service',
|
||||
'audit.bo.products.saveParams': 'edited service questions',
|
||||
'audit.bo.products.deleteService': 'deleted a service',
|
||||
'audit.bo.products.moveService': 'reordered services',
|
||||
'audit.bo.crm.addTask': 'added a task',
|
||||
'audit.bo.crm.setTaskDone': 'updated a task',
|
||||
'audit.bo.crm.removeTask': 'deleted a task',
|
||||
@@ -2493,6 +2575,47 @@ const hy: Dict = {
|
||||
'chat.notLinked': 'Աշխատանքային բոտը բացված չէ',
|
||||
'chat.details': 'Մանրամասներ',
|
||||
'chat.more': 'Այլ գործողություններ',
|
||||
'pr.newService': 'Նոր ծառայություն',
|
||||
'pr.newServiceHint': 'Զրոյից՝ ֆիքսված գնով, կամ պատրաստի ծառայության պատճենով։',
|
||||
'pr.fromScratch': 'Զրոյից',
|
||||
'pr.copyOf': 'Պատրաստիի պատճեն',
|
||||
'pr.category': 'Ուղղություն',
|
||||
'pr.copyFrom': 'Պատճենել ծառայությունը',
|
||||
'pr.copyHint': 'Կպատճենվեն գները, հարցերը, ստուգացանկը։',
|
||||
'pr.who': 'Ով է կատարում',
|
||||
'pr.whoHint': 'Որոշում է, ում է առաջարկվում պատվերը։',
|
||||
'pr.flowHint.CLEANER': 'ճանապարհին → աշխատանք → պատրաստ',
|
||||
'pr.flowHint.DRIVER': 'վարորդը տեղում → ճանապարհին → ավարտ',
|
||||
'pr.flowHint.CAREER_CONSULTANT': 'խորհրդատու → հանդիպում → արդյունք',
|
||||
'pr.flowHint.DOCS_AGENT': 'ստուգում → ներկայացում → պատրաստ',
|
||||
'pr.online': 'Առցանց՝ առանց հասցեի',
|
||||
'pr.namePh': 'Օրինակ՝ Պատուհանների լվացում',
|
||||
'pr.create': 'Ստեղծել ծառայությունը',
|
||||
'pr.createHint': 'Ծառայությունը կստեղծվի անջատված՝ կարգավորեք և միացրեք։',
|
||||
'pr.created': 'Ծառայությունը ստեղծված է',
|
||||
'pr.questions': 'Հարցեր պատվերի ժամանակ',
|
||||
'pr.questionsHint': 'Ինչ է ընտրում հաճախորդը պատվերի ձևում։',
|
||||
'pr.qLabel': 'Հարց',
|
||||
'pr.qType.select': 'ընտրություն',
|
||||
'pr.qType.int': 'թիվ',
|
||||
'pr.qType.text': 'տեքստ',
|
||||
'pr.qType.bool': 'այո / ոչ',
|
||||
'pr.qOption': 'Տարբերակ {n}',
|
||||
'pr.qAddOption': 'տարբերակ',
|
||||
'pr.qFrom': 'սկսած',
|
||||
'pr.qTo': 'մինչև',
|
||||
'pr.qRequired': 'պարտադիր',
|
||||
'pr.qAdd': 'Հարց',
|
||||
'pr.qNone': 'Հարցեր չկան։',
|
||||
'pr.delete': 'Ջնջել ծառայությունը',
|
||||
'pr.deleteConfirm': 'Ջնջե՞լ ծառայությունը։',
|
||||
'err.SERVICE_HAS_ORDERS': 'Ծառայությունն ունի պատվերներ՝ անջատեք այն։',
|
||||
'err.OPTIONS_REQUIRED': 'Անհրաժեշտ է նվազագույնը 2 տարբերակ։',
|
||||
'err.PARAMS_LOCKED': 'Այս ծառայության հարցերը փոխում է ծրագրավորողը։',
|
||||
'audit.bo.products.createService': 'ստեղծեց ծառայություն',
|
||||
'audit.bo.products.saveParams': 'փոխեց ծառայության հարցերը',
|
||||
'audit.bo.products.deleteService': 'ջնջեց ծառայությունը',
|
||||
'audit.bo.products.moveService': 'փոխեց հերթականությունը',
|
||||
'audit.bo.crm.addTask': 'ավելացրեց առաջադրանք',
|
||||
'audit.bo.crm.setTaskDone': 'նշեց առաջադրանքը',
|
||||
'audit.bo.crm.removeTask': 'ջնջեց առաջադրանքը',
|
||||
@@ -3214,6 +3337,12 @@ export function BoI18nProvider({ children }: { children: ReactNode }) {
|
||||
useEffect(() => {
|
||||
document.documentElement.lang = locale;
|
||||
}, [locale]);
|
||||
// тексты, изменённые в «Продуктах» (названия услуг и т.п.), — перерисовать, когда подгрузились
|
||||
const [textsVersion, setTextsVersion] = useState(textOverridesVersion());
|
||||
useEffect(() => {
|
||||
const off = onTextOverrides(() => setTextsVersion(textOverridesVersion()));
|
||||
return () => void off();
|
||||
}, []);
|
||||
const value = useMemo<Ctx>(() => {
|
||||
const sharedT = createSharedT(locale as SharedLocale);
|
||||
const intl = locale === 'en' ? 'en-GB' : locale === 'hy' ? 'hy-AM' : 'ru-RU';
|
||||
@@ -3237,7 +3366,8 @@ export function BoI18nProvider({ children }: { children: ReactNode }) {
|
||||
dateTime: (d) => formatDateTime(locale as SharedLocale, d, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }),
|
||||
time: (d) => formatDateTime(locale as SharedLocale, d, { hour: '2-digit', minute: '2-digit' }),
|
||||
};
|
||||
}, [locale]);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [locale, textsVersion]);
|
||||
return <I18nCtx.Provider value={value}>{children}</I18nCtx.Provider>;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,12 +4,15 @@ import './chats.css';
|
||||
import './orders.css';
|
||||
import './crm.css';
|
||||
import './admin5.css';
|
||||
import { ApiProvider, ToastProvider } from '@barev/web';
|
||||
import { ApiProvider, loadTextOverrides, ToastProvider } from '@barev/web';
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { App } from './App.tsx';
|
||||
import { BoI18nProvider } from './i18n.tsx';
|
||||
|
||||
// названия услуг и другие тексты, изменённые в «Продуктах»
|
||||
void loadTextOverrides();
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<ApiProvider withCredentials>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { navigate, useLocation, useToast, useTRPC } from '@barev/web';
|
||||
import { loadTextOverrides, navigate, useLocation, useToast, useTRPC } from '@barev/web';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import type { Me } from '../App.tsx';
|
||||
import { errText, useT } from '../i18n.tsx';
|
||||
@@ -36,7 +36,7 @@ export function Products({ me }: { me: Me }) {
|
||||
))}
|
||||
</div>
|
||||
{!canEdit && <p className="bo-hint" style={{ marginBottom: 12 }}>{t('pr.readOnly')}</p>}
|
||||
{tab === 'services' && <Services />}
|
||||
{tab === 'services' && <Services canEdit={canEdit} />}
|
||||
{tab === 'plans' && <Plans canEdit={canEdit} />}
|
||||
{tab === 'promos' && <Promos canEdit={canEdit} />}
|
||||
{tab === 'relocation' && <Relocation canEdit={canEdit} />}
|
||||
@@ -46,13 +46,26 @@ export function Products({ me }: { me: Me }) {
|
||||
|
||||
// ───── услуги ─────
|
||||
|
||||
function Services() {
|
||||
function Services({ canEdit }: { canEdit: boolean }) {
|
||||
const { t, shared, amd } = useT();
|
||||
const trpc = useTRPC();
|
||||
const qc = useQueryClient();
|
||||
const cat = useQuery(trpc.bo.products.catalog.queryOptions());
|
||||
const [creating, setCreating] = useState(false);
|
||||
const move = useMutation(trpc.bo.products.moveService.mutationOptions({ onSuccess: () => qc.invalidateQueries({ queryKey: trpc.bo.products.catalog.queryKey() }) }));
|
||||
if (!cat.data) return <Skeleton h={300} />;
|
||||
return (
|
||||
<div className="bo-col" style={{ gap: 18 }}>
|
||||
{canEdit && (
|
||||
<div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<button type="button" className="bo-btn bo-btn--accent" onClick={() => setCreating(true)}>
|
||||
<I name="plus" size={16} />
|
||||
{t('pr.newService')}
|
||||
</button>
|
||||
<span className="bo-hint">{t('pr.newServiceHint')}</span>
|
||||
</div>
|
||||
)}
|
||||
{creating && <NewServiceDialog catalog={cat.data} onClose={() => setCreating(false)} />}
|
||||
{cat.data.map((c) => (
|
||||
<section key={c.id} className="bo-panel">
|
||||
<div className="bo-panel__head">
|
||||
@@ -62,6 +75,16 @@ function Services() {
|
||||
<ul className="bo-list">
|
||||
{c.services.map((s) => (
|
||||
<li key={s.id} style={{ opacity: s.active ? 1 : 0.55 }}>
|
||||
{canEdit && (
|
||||
<span className="bo-stages__arrows">
|
||||
<button type="button" onClick={() => move.mutate({ id: s.id, dir: -1 })} aria-label="↑">
|
||||
<I name="arrowUp" size={14} />
|
||||
</button>
|
||||
<button type="button" onClick={() => move.mutate({ id: s.id, dir: 1 })} aria-label="↓">
|
||||
<I name="arrowDown" size={14} />
|
||||
</button>
|
||||
</span>
|
||||
)}
|
||||
<a href={`#/products/${s.id}`} className="bo-grow" style={{ color: 'inherit', textDecoration: 'none' }}>
|
||||
<b>{shared(`services.${s.code}.name`)}</b>
|
||||
<span className="bo-small bo-muted" style={{ display: 'block' }}>
|
||||
@@ -136,6 +159,7 @@ export function ServiceEditor({ id, me }: { id: string; me: Me }) {
|
||||
<div className="bo-client-grid">
|
||||
<div className="bo-col">
|
||||
<ContentPanel code={s.code} canEdit={canEdit} extras={s.pricing.kind === 'rooms' ? Object.keys(s.pricing.extras) : []} />
|
||||
{s.pricing.kind === 'fixed' && <ParamsPanel service={s} canEdit={canEdit} />}
|
||||
</div>
|
||||
<div className="bo-col">
|
||||
<SettingsPanel service={s} canEdit={canEdit} />
|
||||
@@ -146,6 +170,7 @@ export function ServiceEditor({ id, me }: { id: string; me: Me }) {
|
||||
<div style={{ marginTop: 16 }}>
|
||||
<PricePanel service={s} canEdit={canEdit} />
|
||||
</div>
|
||||
{canEdit && <DeleteService id={s.id} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -159,6 +184,7 @@ function useSaved() {
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: trpc.bo.products.catalog.queryKey() });
|
||||
qc.invalidateQueries({ queryKey: trpc.bo.products.texts.queryKey() });
|
||||
void loadTextOverrides();
|
||||
toast(t('prv.saved'));
|
||||
},
|
||||
onError: (e: unknown) => toast(errText(t, e), 'error'),
|
||||
@@ -835,3 +861,270 @@ function RelocationDialog({ kind, item, onClose }: { kind: 'STEP' | 'DOC'; item?
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
// ───── новая услуга ─────
|
||||
|
||||
const NEW_ROLES = ['CLEANER', 'DRIVER', 'CAREER_CONSULTANT', 'DOCS_AGENT'] as const;
|
||||
|
||||
function NewServiceDialog({ catalog, onClose }: { catalog: Catalog; onClose: () => void }) {
|
||||
const { t, shared } = useT();
|
||||
const trpc = useTRPC();
|
||||
const qc = useQueryClient();
|
||||
const toast = useToast();
|
||||
const [categoryId, setCategoryId] = useState(catalog[0]?.id ?? '');
|
||||
const [mode, setMode] = useState<'new' | 'copy'>('new');
|
||||
const [copyFromId, setCopyFrom] = useState(catalog[0]?.services[0]?.id ?? '');
|
||||
const [role, setRole] = useState<(typeof NEW_ROLES)[number]>('CLEANER');
|
||||
const [isOnline, setOnline] = useState(false);
|
||||
const [price, setPrice] = useState('10000');
|
||||
const [minutes, setMinutes] = useState('60');
|
||||
const [name, setName] = useState<L5>({ ...EMPTY });
|
||||
const [desc, setDesc] = useState<L5>({ ...EMPTY });
|
||||
const create = useMutation(
|
||||
trpc.bo.products.createService.mutationOptions({
|
||||
onSuccess: async (r) => {
|
||||
await loadTextOverrides();
|
||||
qc.invalidateQueries({ queryKey: trpc.bo.products.catalog.queryKey() });
|
||||
toast(t('pr.created'));
|
||||
onClose();
|
||||
navigate(`/products/${r.id}`);
|
||||
},
|
||||
onError: (e) => toast(errText(t, e), 'error'),
|
||||
}),
|
||||
);
|
||||
const all = catalog.flatMap((c) => c.services);
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
wide
|
||||
onClose={onClose}
|
||||
title={t('pr.newService')}
|
||||
footer={
|
||||
<>
|
||||
<button type="button" className="bo-btn bo-btn--ghost" onClick={onClose}>
|
||||
{t('ui.close')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="bo-btn bo-btn--accent"
|
||||
disabled={!name.ru.trim() || !categoryId || create.isPending}
|
||||
onClick={() =>
|
||||
create.mutate({
|
||||
categoryId,
|
||||
name,
|
||||
description: desc,
|
||||
...(mode === 'copy' ? { copyFromId } : { providerRole: role, isOnline, price: Number(price) || 0, minutes: Math.max(15, Number(minutes) || 60) }),
|
||||
})
|
||||
}
|
||||
>
|
||||
{t('pr.create')}
|
||||
</button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="bo-chtabs">
|
||||
<button type="button" aria-pressed={mode === 'new'} onClick={() => setMode('new')}>
|
||||
{t('pr.fromScratch')}
|
||||
</button>
|
||||
<button type="button" aria-pressed={mode === 'copy'} onClick={() => setMode('copy')}>
|
||||
{t('pr.copyOf')}
|
||||
</button>
|
||||
</div>
|
||||
<Field label={t('pr.category')}>
|
||||
<select className="bo-select" value={categoryId} onChange={(e) => setCategoryId(e.target.value)}>
|
||||
{catalog.map((c) => (
|
||||
<option key={c.id} value={c.id}>
|
||||
{shared(`categories.${c.code}.name`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
{mode === 'copy' ? (
|
||||
<Field label={t('pr.copyFrom')} hint={t('pr.copyHint')}>
|
||||
<select className="bo-select" value={copyFromId} onChange={(e) => setCopyFrom(e.target.value)}>
|
||||
{all.map((x) => (
|
||||
<option key={x.id} value={x.id}>
|
||||
{shared(`services.${x.code}.name`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<span className="bo-label">{t('pr.who')}</span>
|
||||
<div className="bo-roles" style={{ marginTop: 6 }}>
|
||||
{NEW_ROLES.map((r) => (
|
||||
<button key={r} type="button" className="bo-role" aria-pressed={role === r} onClick={() => setRole(r)}>
|
||||
<b>{shared(`roles.${r}`)}</b>
|
||||
<span className="bo-small">{t(`pr.flowHint.${r}`)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<span className="bo-hint">{t('pr.whoHint')}</span>
|
||||
</div>
|
||||
<div className="bo-row2">
|
||||
<Field label={t('pr.fixedPrice')}>
|
||||
<input className="bo-input" inputMode="numeric" value={price} onChange={(e) => setPrice(num(e.target.value))} />
|
||||
</Field>
|
||||
<Field label={t('pr.minutes')}>
|
||||
<input className="bo-input" inputMode="numeric" value={minutes} onChange={(e) => setMinutes(num(e.target.value))} />
|
||||
</Field>
|
||||
</div>
|
||||
<label className="bo-check">
|
||||
<input type="checkbox" checked={isOnline} onChange={(e) => setOnline(e.target.checked)} />
|
||||
{t('pr.online')}
|
||||
</label>
|
||||
</>
|
||||
)}
|
||||
<L5Editor label={t('pr.name')} value={name} defaults={{ ru: t('pr.namePh') }} onChange={setName} />
|
||||
<L5Editor label={t('pr.description')} value={desc} defaults={{}} onChange={setDesc} multiline />
|
||||
<p className="bo-hint">{t('pr.createHint')}</p>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
type QField = { key?: string; type: 'select' | 'int' | 'text' | 'bool'; label: string; required: boolean; options: { key?: string; label: string }[]; min: number; max: number };
|
||||
|
||||
/** Вопросы клиенту при заказе — для услуг с фиксированной ценой */
|
||||
function ParamsPanel({ service: s, canEdit }: { service: Service; canEdit: boolean }) {
|
||||
const { t, shared } = useT();
|
||||
const trpc = useTRPC();
|
||||
const label = (k: string) => {
|
||||
const v = shared(k);
|
||||
return v === k ? '' : v;
|
||||
};
|
||||
const initial = (): QField[] =>
|
||||
s.paramsSchema.fields
|
||||
.filter((f) => f.type !== 'extras')
|
||||
.map((f) => ({
|
||||
key: f.key,
|
||||
type: f.type as QField['type'],
|
||||
label: label(`params.${s.code}.${f.key}.label`) || f.key,
|
||||
required: 'required' in f ? !!f.required : false,
|
||||
options: f.type === 'select' ? f.options.map((o) => ({ key: o, label: label(`params.${s.code}.${f.key}.${o}`) || o })) : [],
|
||||
min: f.type === 'int' ? f.min : 1,
|
||||
max: f.type === 'int' ? f.max : 10,
|
||||
}));
|
||||
const [fields, setFields] = useState<QField[]>(initial);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useEffect(() => setFields(initial()), [s.paramsSchema]);
|
||||
const save = useMutation(trpc.bo.products.saveParams.mutationOptions(useSaved()));
|
||||
const set = (i: number, patch: Partial<QField>) => setFields(fields.map((f, k) => (k === i ? { ...f, ...patch } : f)));
|
||||
return (
|
||||
<section className="bo-panel">
|
||||
<div className="bo-panel__head">
|
||||
<h2 className="bo-h2">{t('pr.questions')}</h2>
|
||||
</div>
|
||||
<p className="bo-hint" style={{ marginBottom: 12 }}>
|
||||
{t('pr.questionsHint')}
|
||||
</p>
|
||||
<div className="bo-col" style={{ gap: 10 }}>
|
||||
{fields.map((f, i) => (
|
||||
<div key={f.key ?? `n${i}`} className="bo-qfield">
|
||||
<div style={{ display: 'flex', gap: 8 }}>
|
||||
<input className="bo-input" disabled={!canEdit} value={f.label} maxLength={120} onChange={(e) => set(i, { label: e.target.value })} placeholder={t('pr.qLabel')} />
|
||||
<select
|
||||
className="bo-select"
|
||||
style={{ width: 160 }}
|
||||
disabled={!canEdit}
|
||||
value={f.type}
|
||||
onChange={(e) => set(i, { type: e.target.value as QField['type'], options: e.target.value === 'select' && f.options.length < 2 ? [{ label: '' }, { label: '' }] : f.options })}
|
||||
>
|
||||
{(['select', 'int', 'text', 'bool'] as const).map((x) => (
|
||||
<option key={x} value={x}>
|
||||
{t(`pr.qType.${x}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{canEdit && (
|
||||
<button type="button" className="bo-iconbtn" onClick={() => setFields(fields.filter((_, k) => k !== i))} aria-label={t('chat.tplDelete')}>
|
||||
<I name="close" size={16} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{f.type === 'select' && (
|
||||
<div className="bo-col" style={{ gap: 6, marginTop: 8, paddingLeft: 12 }}>
|
||||
{f.options.map((o, k) => (
|
||||
<div key={o.key ?? `o${k}`} style={{ display: 'flex', gap: 6 }}>
|
||||
<input
|
||||
className="bo-input"
|
||||
style={{ minHeight: 34, padding: '4px 10px' }}
|
||||
disabled={!canEdit}
|
||||
value={o.label}
|
||||
maxLength={120}
|
||||
placeholder={t('pr.qOption', { n: k + 1 })}
|
||||
onChange={(e) => set(i, { options: f.options.map((x, j) => (j === k ? { ...x, label: e.target.value } : x)) })}
|
||||
/>
|
||||
{canEdit && f.options.length > 2 && (
|
||||
<button type="button" className="bo-iconbtn" onClick={() => set(i, { options: f.options.filter((_, j) => j !== k) })} aria-label={t('chat.tplDelete')}>
|
||||
<I name="close" size={14} />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{canEdit && (
|
||||
<button type="button" className="bo-side__link" style={{ color: 'var(--bc-accent)', padding: 0, alignSelf: 'flex-start' }} onClick={() => set(i, { options: [...f.options, { label: '' }] })}>
|
||||
+ {t('pr.qAddOption')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{f.type === 'int' && (
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 8, alignItems: 'center' }} className="bo-small">
|
||||
{t('pr.qFrom')}
|
||||
<input className="bo-input" style={{ width: 80, minHeight: 34 }} disabled={!canEdit} inputMode="numeric" value={String(f.min)} onChange={(e) => set(i, { min: Number(num(e.target.value)) || 0 })} />
|
||||
{t('pr.qTo')}
|
||||
<input className="bo-input" style={{ width: 80, minHeight: 34 }} disabled={!canEdit} inputMode="numeric" value={String(f.max)} onChange={(e) => set(i, { max: Number(num(e.target.value)) || 1 })} />
|
||||
</div>
|
||||
)}
|
||||
{f.type !== 'bool' && (
|
||||
<label className="bo-check bo-small" style={{ marginTop: 6 }}>
|
||||
<input type="checkbox" disabled={!canEdit} checked={f.required} onChange={(e) => set(i, { required: e.target.checked })} />
|
||||
{t('pr.qRequired')}
|
||||
</label>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{fields.length === 0 && <p className="bo-hint">{t('pr.qNone')}</p>}
|
||||
</div>
|
||||
{canEdit && (
|
||||
<div style={{ display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap' }}>
|
||||
<button type="button" className="bo-btn bo-btn--ghost bo-btn--sm" onClick={() => setFields([...fields, { type: 'select', label: '', required: true, options: [{ label: '' }, { label: '' }], min: 1, max: 10 }])}>
|
||||
<I name="plus" size={16} />
|
||||
{t('pr.qAdd')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="bo-btn bo-btn--sm"
|
||||
disabled={save.isPending || fields.some((f) => !f.label.trim() || (f.type === 'select' && f.options.filter((o) => o.label.trim()).length < 2))}
|
||||
onClick={() => save.mutate({ serviceId: s.id, fields: fields.map((f) => ({ ...f, options: f.type === 'select' ? f.options.filter((o) => o.label.trim()) : [] })) })}
|
||||
>
|
||||
{t('ui.save')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function DeleteService({ id }: { id: string }) {
|
||||
const { t } = useT();
|
||||
const trpc = useTRPC();
|
||||
const qc = useQueryClient();
|
||||
const toast = useToast();
|
||||
const del = useMutation(
|
||||
trpc.bo.products.deleteService.mutationOptions({
|
||||
onSuccess: () => {
|
||||
qc.invalidateQueries({ queryKey: trpc.bo.products.catalog.queryKey() });
|
||||
navigate('/products');
|
||||
},
|
||||
onError: (e) => toast(errText(t, e), 'error'),
|
||||
}),
|
||||
);
|
||||
return (
|
||||
<button type="button" className="bo-side__link" style={{ color: 'var(--bc-danger)', marginTop: 16 }} onClick={() => confirm(t('pr.deleteConfirm')) && del.mutate({ id })}>
|
||||
{t('pr.delete')}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user