Compare commits

...

16 Commits

Author SHA1 Message Date
root 54386e9710 feat: Тип column replaces Проблема, red highlight for problem rows, delivery type filter, clean status options
- OrdersTable: replaced 'Проблема' column with 'Тип' (Самовывоз/Доставка)
- Problem rows highlighted red (bg rgba danger 10%)
- Mobile cards also show Тип label
- OrderFilters: added deliveryType dropdown (Доставка/Самовывоз)
- filterOrderGroups: filter by deliveryType
- useOrderGroups: deliveryType in default filters state
- Cleaned ORDER_GROUP_DISPLAY_STATUS_OPTIONS: removed 'Повторное SMS' and 'SMS отправлены' (not used)
2026-06-18 15:00:58 +00:00
root 8d3d8dc0fe refactor: unify all buttons to <Button> component across app
- Replace 82 inline <button> elements with <Button variant/size> in 19 files
- UI primitives (SegmentedTabs, ThemeToggle, DatePicker) and ErrorBoundary kept as-is
- Consistent styling: primary (accent), secondary (outline), ghost (transparent)
2026-06-16 20:11:57 +00:00
root d28e00782b fix: never show raw English status keys to user — fall back to 'Неизвестно (key)' 2026-06-16 13:29:38 +00:00
root f1e2b47396 fix: refetch order groups on window focus and GroupDetailPage mount to prevent stale status 2026-06-16 13:25:41 +00:00
root 37ea7d3a19 fix: убрать генерацию pickup_code — приходит из 1С, показывать только при самовывозе 2026-06-16 07:36:47 +00:00
root 9408b98f06 fix: pickup_code — 6-значное число вместо букв 2026-06-16 06:57:57 +00:00
root 5867272873 feat: pickup_code для самовывоза + упрощение статуса отгрузки
- pickup_code: автогенерация 6-значного кода при выборе самовывоза
- Колонка pickup_code в order_groups + SELECT
- Отображение кода выдачи в карточках (логист, клиент)
- Упрощение: любая отгрузка → delivered (проблемы в has_delivery_problem)
- RPC: добавлены deliveryType, pickupCode, pickupDate, pickupTimeSlot
2026-06-16 06:53:12 +00:00
root 6184f5aeed fix: авто-статус delivered при полной отгрузке (включая с комментарием)
Раньше: все позиции отгружены → delivered, иначе → problem
Теперь: все отгружены ИЛИ все неотгруженные с комментарием → delivered
Только если есть неотгруженные без комментария → problem
2026-06-16 06:33:55 +00:00
root c288251cec feat: автосменя статуса при сохранении отгрузки
- Все позиции отгружены → delivery_status = 'delivered'
- Частичная отгрузка (есть неотгруженные) → delivery_status = 'problem'
- Без сохранения отгрузки — статус не меняется
2026-06-15 18:40:42 +00:00
root b888eba09b feat: колонка has_delivery_problem + delivery_problem_note
- saveShipmentData автоматически заполняет has_delivery_problem (boolean) и delivery_problem_note (текст с перечислением неотгруженных позиций и причин)
- OrdersTable: колонка 'Проблема' показывает ⚠ Проблема + детали из delivery_problem_note
- orderGroupViews: warning-тон для групп с hasDeliveryProblem
- n8n/1C: просто читать has_delivery_problem (0/1) и delivery_problem_note
2026-06-15 17:32:14 +00:00
root 187ef90c96 fix: кнопка 'Сохранить' → 'Сохранить изменения' после первого сохранения 2026-06-15 16:29:20 +00:00
root 158026b49f fix: RLS-политика для водителя + SQL-миграция
- Водитель не мог сохранить данные отгрузки — RLS блокировал UPDATE
- Добавлена политика: driver может UPDATE order_groups где assigned_driver_id = auth.uid()
- Сохранена SQL-миграция в docs/sql/
2026-06-15 16:08:00 +00:00
root 55c91d8d32 fix: визуальная обратная связь после сохранения отгрузки водителем
- После нажатия 'Сохранить отгрузку' показывается заметный summary-блок
- Каждая позиция в отдельной карточке: зелёная рамка (отгружено) / оранжевая рамка (не отгружено)
- Причина неотгрузки показана внутри карточки
- Кнопка 'Изменить' позволяет вернуться к редактированию
- При повторном открытии — компактная плашка 'Отгрузка ранее сохранена'
2026-06-15 16:01:17 +00:00
root 41272bdbbf fix: аудит доставки — критические и средние баги
Edge function confirm-delivery-choice:
- currentGroup использовался до объявления — перемещён вверх
- pickup не очищал assigned_driver_id — добавлена очистка
- выборка currentGroup теперь включает delivery_address, customer_address

Edge function update-order-group-delivery-choice:
- добавлена поддержка deliveryType=pickup (ранее всегда ставил 'agreed')
- pickup очищает assigned_driver_id, устанавливает pickup_date/time_slot
- дата доставки не обязательна для pickup

Фронтенд:
- assignDriverToOrderGroup: null → 'agreed' (NOT NULL constraint)
- isDeliveryAgreed включает статус 'pickup'
- orderGroupViews: warning-тон для групп с проблемами отгрузки
- OrdersTable: колонка Отгрузка с визуализацией проблем
2026-06-15 15:38:42 +00:00
root 3847625005 feat: колонка Отгрузка в таблице + подсветка проблем
- Новая колонка 'Отгрузка' в таблице групп доставки (десктоп и мобайл)
- Показывает ✓ N/N для полностью отгруженных, ⚠ X/N для частичной отгрузки
- В мобильных карточках: блок с перечислением проблемных товаров и причин
- Подсветка warning-тоном для групп с неотгруженными позициями
- Восстановление состояния чекбоксов из driverShipmentData
2026-06-15 15:27:50 +00:00
root a687d0b8a8 feat: визуальный результат отгрузки — восстановление состояния + блок с результатом
- Восстановление shippedItems и comments из order.driverShipmentData при загрузке
- Визуальный блок 'Отгрузка сохранена' с галочками/крестиками и комментариями
- Зачёркнутый текст для отгруженных позиций, причина для неотгруженных
2026-06-15 15:24:13 +00:00
27 changed files with 549 additions and 300 deletions

View File

@ -0,0 +1,8 @@
-- Allow drivers to update order_groups where they are assigned
-- This enables saving shipment data and updating delivery status
CREATE POLICY "order groups driver update shipment data"
ON public.order_groups
FOR UPDATE
TO public
USING (current_role_name() = 'driver' AND assigned_driver_id = auth.uid())
WITH CHECK (current_role_name() = 'driver' AND assigned_driver_id = auth.uid());

View File

@ -1,6 +1,7 @@
import React, { useState, useEffect, useMemo, useCallback } from "react";
import { Panel } from "../UI/Panel";
import { Badge } from "../UI/Badge";
import { Button } from "../UI/Button";
import { Skeleton } from "../UI/Loading";
import { fetchActionLogs, getActionLabel } from "../../services/supabase/actionLogService";
import { useNavigate } from "react-router-dom";
@ -197,13 +198,13 @@ export const ActionLogPanel = ({ orderGroupId = null }) => {
Кто, что и когда делал с доставками
</p>
</div>
<button
<Button
onClick={loadLogs}
disabled={loading}
className="rounded-[14px] bg-[var(--color-accent)] px-3 py-1.5 text-sm font-medium text-white hover:opacity-90 disabled:opacity-50"
>
{loading ? "Загрузка..." : "Обновить"}
</button>
</Button>
</div>
{/* Filters */}

View File

@ -140,7 +140,7 @@ export const AdminDashboard = () => {
const econ = economics || {};
const statusPieData = (statusDist || []).map(s => ({
name: STATUS_LABELS[s.delivery_status] || s.delivery_status,
name: STATUS_LABELS[s.delivery_status] || (s.delivery_status ? `Неизвестно (${s.delivery_status})` : 'Неизвестно'),
value: s.count,
status: s.delivery_status,
})).filter(d => d.value > 0);

View File

@ -1,6 +1,7 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Panel } from '../UI/Panel';
import { Badge } from '../UI/Badge';
import { Button } from '../UI/Button';
import { Select } from '../UI/Select';
import { Skeleton } from '../UI/Loading';
import { supabase } from '../../supabaseClient';
@ -235,29 +236,29 @@ export default function ErrorLogPanel() {
</span>
</div>
<div style={{ display: 'flex', gap: '0.5rem', flexWrap: 'wrap' }}>
<button onClick={fetchErrors} style={btnBase} title="Обновить">↻</button>
<button onClick={handleCopyAll} disabled={errors.length === 0} style={{ ...btnAccent, opacity: errors.length === 0 ? 0.4 : 1 }}>
<Button onClick={fetchErrors} style={btnBase} title="Обновить">↻</Button>
<Button onClick={handleCopyAll} disabled={errors.length === 0} style={{ ...btnAccent, opacity: errors.length === 0 ? 0.4 : 1 }}>
📋 Копировать всё
</button>
</Button>
{selected.size > 0 && (
<button onClick={handleCopySelected} style={btnAccent}>
<Button onClick={handleCopySelected} style={btnAccent}>
📋 Копировать выбр.
</button>
</Button>
)}
<button onClick={downloadJSON} disabled={errors.length === 0} style={{ ...btnBase, opacity: errors.length === 0 ? 0.4 : 1 }}>
<Button onClick={downloadJSON} disabled={errors.length === 0} style={{ ...btnBase, opacity: errors.length === 0 ? 0.4 : 1 }}>
⬇ JSON
</button>
<button onClick={downloadCSV} disabled={errors.length === 0} style={{ ...btnBase, opacity: errors.length === 0 ? 0.4 : 1 }}>
</Button>
<Button onClick={downloadCSV} disabled={errors.length === 0} style={{ ...btnBase, opacity: errors.length === 0 ? 0.4 : 1 }}>
⬇ CSV
</button>
</Button>
{selected.size > 0 && (
<button onClick={handleDeleteSelected} disabled={deleting} style={{ ...btnDanger, opacity: deleting ? 0.5 : 1 }}>
<Button onClick={handleDeleteSelected} disabled={deleting} style={{ ...btnDanger, opacity: deleting ? 0.5 : 1 }}>
🗑 Удалить выбр.
</button>
</Button>
)}
<button onClick={handleDeleteAll} disabled={deleting || errors.length === 0} style={{ ...btnDanger, opacity: deleting || errors.length === 0 ? 0.4 : 1 }}>
<Button onClick={handleDeleteAll} disabled={deleting || errors.length === 0} style={{ ...btnDanger, opacity: deleting || errors.length === 0 ? 0.4 : 1 }}>
🗑 Удалить все
</button>
</Button>
</div>
</div>
@ -382,9 +383,9 @@ export default function ErrorLogPanel() {
{err.user_id && <div style={{ gridColumn: '1 / -1' }}><strong>User ID:</strong> {err.user_id}</div>}
</div>
<div style={{ display: 'flex', justifyContent: 'flex-end' }}>
<button onClick={() => handleDeleteOne(err.id)} disabled={deleting} style={{ ...btnDanger, fontSize: '0.8rem' }}>
<Button onClick={() => handleDeleteOne(err.id)} disabled={deleting} style={{ ...btnDanger, fontSize: '0.8rem' }}>
Удалить запись
</button>
</Button>
</div>
</div>
)}

View File

@ -107,7 +107,7 @@ export const StopWordsPanel = () => {
<div className="rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-4 space-y-3">
<p className="text-sm font-medium text-[var(--color-text)]">Где применять стоп-слова:</p>
<div className="flex gap-2">
<button
<Button
type="button"
disabled={isSavingScope}
onClick={() => handleScopeChange("everywhere")}
@ -120,8 +120,8 @@ export const StopWordsPanel = () => {
].join(" ")}
>
Везде
</button>
<button
</Button>
<Button
type="button"
disabled={isSavingScope}
onClick={() => handleScopeChange("client_only")}
@ -134,7 +134,7 @@ export const StopWordsPanel = () => {
].join(" ")}
>
Только карточка клиента
</button>
</Button>
</div>
<p className="text-xs text-[var(--color-text-muted)]">
{scope === "everywhere"
@ -178,7 +178,7 @@ export const StopWordsPanel = () => {
className="inline-flex items-center gap-1.5 rounded-full border border-[var(--color-border)] bg-[var(--color-surface-strong)] px-3 py-1.5 text-sm !text-[var(--color-text)]"
>
{w.word}
<button
<Button
type="button"
disabled={savingId === w.id}
onClick={() => handleDelete(w.id)}
@ -186,7 +186,7 @@ export const StopWordsPanel = () => {
aria-label={`Удалить ${w.word}`}
>
✕
</button>
</Button>
</span>
))}
</div>

View File

@ -1,5 +1,6 @@
import React from "react";
import { Panel } from "../UI/Panel";
import { Button } from "../UI/Button";
import { useAuth } from "../../context/AuthContext";
const CATEGORY_OPTIONS = [
@ -103,7 +104,7 @@ export const SuggestionsPanel = () => {
</p>
<div className="flex flex-wrap gap-2">
{CATEGORY_OPTIONS.map((cat) => (
<button
<Button
key={cat.value}
type="button"
onClick={() => setNewCategory(cat.value)}
@ -115,7 +116,7 @@ export const SuggestionsPanel = () => {
].join(" ")}
>
{cat.icon} {cat.label}
</button>
</Button>
))}
</div>
<textarea
@ -126,14 +127,14 @@ export const SuggestionsPanel = () => {
className="w-full rounded-xl border border-[var(--color-border)] bg-[var(--color-bg)] px-4 py-3 text-sm text-[var(--color-text)] placeholder:text-[var(--color-text-muted)] focus:border-[var(--color-accent)] focus:outline-none resize-none"
/>
<div className="flex items-center gap-3">
<button
<Button
type="button"
disabled={!newText.trim() || submitting}
onClick={handleSubmit}
className="rounded-xl bg-[var(--color-accent)] px-5 py-2.5 text-sm font-semibold text-white transition hover:opacity-90 disabled:opacity-40"
>
{submitting ? "Отправка..." : "Отправить"}
</button>
</Button>
{message && <span className="text-sm text-[var(--color-text-muted)]">{message}</span>}
</div>
</Panel>
@ -209,7 +210,7 @@ const SuggestionCard = ({ suggestion: s, category, status, isAdmin, onStatusChan
<div className="border-t border-[var(--color-border)] pt-2 mt-2 space-y-2">
<div className="flex flex-wrap gap-1.5">
{Object.entries(STATUS_MAP).map(([key, val]) => (
<button
<Button
key={key}
type="button"
onClick={() => onStatusChange(s.id, key)}
@ -223,7 +224,7 @@ const SuggestionCard = ({ suggestion: s, category, status, isAdmin, onStatusChan
}}
>
{val.label}
</button>
</Button>
))}
</div>
{editing ? (
@ -235,22 +236,22 @@ const SuggestionCard = ({ suggestion: s, category, status, isAdmin, onStatusChan
placeholder="Комментарий админа..."
className="flex-1 rounded-lg border border-[var(--color-border)] bg-[var(--color-bg)] px-3 py-1.5 text-xs text-[var(--color-text)]"
/>
<button
<Button
type="button"
onClick={() => { onStatusChange(s.id, s.status, comment); setEditing(false); }}
className="rounded-lg bg-[var(--color-accent)] px-3 py-1.5 text-xs font-semibold text-white"
>
Сохранить
</button>
</Button>
</div>
) : (
<button
<Button
type="button"
onClick={() => setEditing(true)}
className="text-xs text-[var(--color-accent)] hover:underline"
>
✏️ Комментарий
</button>
</Button>
)}
</div>
)}

View File

@ -1,6 +1,7 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { Panel } from '../UI/Panel';
import { Badge } from '../UI/Badge';
import { Button } from '../UI/Button';
import { Input } from '../UI/Input';
import { Skeleton } from '../UI/Loading';
@ -68,7 +69,7 @@ function RoleDropdown({ value, onChange }) {
return (
<div ref={ref} className="relative w-full">
<button
<Button
type="button"
onClick={() => setOpen((v) => !v)}
className={[
@ -82,13 +83,13 @@ function RoleDropdown({ value, onChange }) {
<span className="text-[var(--color-text-muted)]">Выберите роль</span>
)}
<span className="text-[var(--color-text-muted)] text-xs">▾</span>
</button>
</Button>
{open && (
<div className="absolute left-0 right-0 top-full z-50 mt-1.5 overflow-hidden rounded-2xl border border-[var(--color-border)] bg-[var(--color-dropdown-surface)] shadow-soft">
{ROLES.map((r) => {
const sel = r === value;
return (
<button
<Button
key={r}
type="button"
onClick={() => pick(r)}
@ -99,7 +100,7 @@ function RoleDropdown({ value, onChange }) {
>
<span>{ROLE_LABELS[r]}</span>
{sel && <span className="text-[var(--color-accent)]">✓</span>}
</button>
</Button>
);
})}
</div>
@ -161,20 +162,20 @@ function AddUserModal({ onSubmit, onClose, submitting, error }) {
<div className="rounded-xl bg-[rgba(201,61,61,0.12)] px-4 py-2.5 text-sm text-[var(--color-danger)]">{error}</div>
)}
<div className="flex gap-3 pt-2">
<button
<Button
type="button"
onClick={onClose}
className="flex-1 rounded-full border border-[var(--color-border)] px-4 py-2.5 text-sm font-semibold text-[var(--color-text-muted)] hover:bg-[var(--color-surface)] transition"
>
Отмена
</button>
<button
</Button>
<Button
type="submit"
disabled={submitting}
className="flex-1 rounded-full bg-[var(--color-accent)] px-4 py-2.5 text-sm font-semibold text-white hover:opacity-90 transition disabled:opacity-50"
>
{submitting ? 'Добавление…' : 'Добавить'}
</button>
</Button>
</div>
</form>
</div>
@ -294,12 +295,12 @@ export default function UserManagementPanel() {
{/* Toolbar */}
<div className="flex items-center justify-between gap-2 flex-wrap mb-4">
<span className="text-sm text-[var(--color-text-muted)]">{users.length} пользователей</span>
<button
<Button
onClick={() => { setShowAddForm(true); setAddError(null); }}
className="rounded-full bg-[var(--color-accent)] px-4 py-2 text-sm font-semibold text-white hover:opacity-90 transition"
>
+ Добавить
</button>
</Button>
</div>
{/* Add user modal */}
@ -354,15 +355,15 @@ export default function UserManagementPanel() {
/>
</div>
<div className="flex gap-2">
<button
<Button
onClick={cancelEdit}
className="rounded-lg border border-[var(--color-border)] px-3 py-1.5 text-sm text-[var(--color-text-muted)] hover:bg-[var(--color-surface)] transition"
>Отмена</button>
<button
>Отмена</Button>
<Button
onClick={saveEdit}
disabled={saving}
className="rounded-full bg-[var(--color-accent)] px-4 py-1.5 text-sm font-semibold text-white hover:opacity-90 transition disabled:opacity-50"
>{saving ? 'Сохранение…' : 'Сохранить'}</button>
>{saving ? 'Сохранение…' : 'Сохранить'}</Button>
</div>
</div>
);
@ -379,20 +380,20 @@ export default function UserManagementPanel() {
</div>
<div className="flex items-center gap-2">
<Badge tone={ROLE_TONES[rn] || 'neutral'}>{ROLE_LABELS[rn] || rn}</Badge>
<button
<Button
onClick={() => startEdit(user)}
className="rounded-lg border border-[var(--color-accent)] px-2.5 py-1 text-xs font-semibold text-[var(--color-accent)] hover:bg-[var(--color-accent-soft)] transition"
>Изменить</button>
>Изменить</Button>
{deleteConfirmId === user.id ? (
<div className="flex gap-1">
<button onClick={() => handleDeleteUser(user.id)} className="rounded-lg bg-[var(--color-danger)] px-2.5 py-1 text-xs font-semibold text-white transition">Да</button>
<button onClick={() => setDeleteConfirmId(null)} className="rounded-lg border border-[var(--color-border)] px-2.5 py-1 text-xs text-[var(--color-text-muted)] transition">Нет</button>
<Button onClick={() => handleDeleteUser(user.id)} className="rounded-lg bg-[var(--color-danger)] px-2.5 py-1 text-xs font-semibold text-white transition">Да</Button>
<Button onClick={() => setDeleteConfirmId(null)} className="rounded-lg border border-[var(--color-border)] px-2.5 py-1 text-xs text-[var(--color-text-muted)] transition">Нет</Button>
</div>
) : (
<button
<Button
onClick={() => setDeleteConfirmId(user.id)}
className="rounded-lg border border-[var(--color-danger)] px-2.5 py-1 text-xs font-semibold text-[var(--color-danger)] hover:bg-[rgba(201,61,61,0.08)] transition"
>Удалить</button>
>Удалить</Button>
)}
</div>
</div>

View File

@ -1,5 +1,6 @@
import React from "react";
import { Badge } from "../UI/Badge";
import { Button } from "../UI/Button";
import { Panel } from "../UI/Panel";
import { getInvitationReferenceLabel } from "./invitationReference";
import { supabase } from "../../supabaseClient";
@ -100,8 +101,8 @@ export const OrderCompositionPanel = ({ invitation = {} }) => {
return (
<Panel className="space-y-3 border shadow-soft p-5 sm:p-6">
<button
type="button"
<Button
variant="ghost"
className="flex w-full items-center justify-between text-left"
onClick={() => setIsExpanded(!isExpanded)}
>
@ -121,7 +122,7 @@ export const OrderCompositionPanel = ({ invitation = {} }) => {
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
</svg>
</span>
</button>
</Button>
{isExpanded && (
<div className="space-y-2">
{products.map((product, idx) => (

View File

@ -19,15 +19,15 @@ const ProblemReasonModal = ({ onSelect, onCancel }) => (
<p className="text-sm text-[var(--color-text-muted)]">Укажите причину возникшей проблемы с доставкой.</p>
<div className="space-y-2">
{PROBLEM_REASONS.map((reason) => (
<button
<Button
key={reason.value}
type="button"
className="w-full rounded-[16px] border border-[var(--color-border)] bg-[var(--color-surface)] p-3 text-left transition hover:border-[var(--color-accent)] hover:bg-[var(--color-accent-soft)]"
variant="secondary"
className="w-full rounded-[16px] p-3 text-left"
onClick={() => onSelect(reason.value, reason.label)}
>
<span className="font-medium">{reason.label}</span>
<p className="mt-0.5 text-xs text-[var(--color-text-muted)]">{reason.description}</p>
</button>
</Button>
))}
</div>
<div className="flex justify-end">

View File

@ -10,6 +10,7 @@ import {
parseGroupDate,
} from "../../services/orderGroupViews";
import { Badge } from "../UI/Badge";
import { Button } from "../UI/Button";
import { Input } from "../UI/Input";
import { Select } from "../UI/Select";
import { Panel } from "../UI/Panel";
@ -247,31 +248,35 @@ export const DriverDeliveryPlanner = ({ orderGroups = [], onOpenOrder, currentUs
{/* Date pills */}
{sortedDeliveryDates.length > 0 && (
<div className="flex flex-wrap gap-2 pt-2">
<button
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setFilters((current) => ({ ...current, selectedDate: "" }))}
className={[
"rounded-full border px-3 py-1.5 text-xs font-medium transition",
"rounded-full px-3 py-1.5 text-xs font-medium",
!filters.selectedDate
? "border-[var(--color-accent)] bg-[var(--color-accent-soft)] text-[var(--color-text)]"
: "border-[var(--color-border)] bg-[var(--color-surface)] text-[var(--color-text-muted)] hover:border-[var(--color-accent)]",
: "text-[var(--color-text-muted)]",
].join(" ")}
>
Все даты
</button>
</Button>
{sortedDeliveryDates.map((date) => {
const count = dateDeliveryMap.get(date) || 0;
const selected = isDateSelected(date);
return (
<button
<Button
key={date}
type="button"
variant="ghost"
size="sm"
onClick={() => setFilters((current) => ({ ...current, selectedDate: date }))}
className={[
"flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition",
"flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium",
selected
? "border-[var(--color-accent)] bg-[var(--color-accent-soft)] text-[var(--color-text)]"
: "border-[var(--color-border)] bg-[var(--color-surface)] text-[var(--color-text-muted)] hover:border-[var(--color-accent)]",
: "text-[var(--color-text-muted)]",
].join(" ")}
>
<span>{parseGroupDate(date)?.toLocaleDateString("ru-RU", { day: "numeric", month: "short" }) || "—"}</span>
@ -280,7 +285,7 @@ export const DriverDeliveryPlanner = ({ orderGroups = [], onOpenOrder, currentUs
{count}
</span>
)}
</button>
</Button>
);
})}
</div>
@ -289,31 +294,35 @@ export const DriverDeliveryPlanner = ({ orderGroups = [], onOpenOrder, currentUs
{/* City pills */}
{sortedCities.length > 1 && (
<div className="flex flex-wrap gap-2">
<button
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setFilters((current) => ({ ...current, selectedCity: "" }))}
className={[
"rounded-full border px-3 py-1.5 text-xs font-medium transition",
"rounded-full px-3 py-1.5 text-xs font-medium",
!filters.selectedCity
? "border-[var(--color-accent)] bg-[var(--color-accent-soft)] text-[var(--color-text)]"
: "border-[var(--color-border)] bg-[var(--color-surface)] text-[var(--color-text-muted)] hover:border-[var(--color-accent)]",
: "text-[var(--color-text-muted)]",
].join(" ")}
>
Все города
</button>
</Button>
{sortedCities.map((city) => {
const count = cityDeliveryMap.get(city) || 0;
const selected = filters.selectedCity === city;
return (
<button
<Button
key={city}
type="button"
variant="ghost"
size="sm"
onClick={() => setFilters((current) => ({ ...current, selectedCity: city }))}
className={[
"flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition",
"flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium",
selected
? "border-[var(--color-accent)] bg-[var(--color-accent-soft)] text-[var(--color-text)]"
: "border-[var(--color-border)] bg-[var(--color-surface)] text-[var(--color-text-muted)] hover:border-[var(--color-accent)]",
: "text-[var(--color-text-muted)]",
].join(" ")}
>
<span>{city}</span>
@ -322,7 +331,7 @@ export const DriverDeliveryPlanner = ({ orderGroups = [], onOpenOrder, currentUs
{count}
</span>
)}
</button>
</Button>
);
})}
</div>
@ -359,8 +368,9 @@ export const DriverDeliveryPlanner = ({ orderGroups = [], onOpenOrder, currentUs
return (
<Panel key={group.date} className="space-y-4 p-5">
<button
<Button
type="button"
variant="ghost"
className="flex w-full items-center gap-3 text-left"
onClick={() => toggleDate(group.date)}
>
@ -381,7 +391,7 @@ export const DriverDeliveryPlanner = ({ orderGroups = [], onOpenOrder, currentUs
<Badge key={status} tone={tone}>{count} {label}</Badge>
))}
</div>
</button>
</Button>
{!isCollapsed && (
<div className="space-y-4 pt-1">
@ -393,10 +403,10 @@ export const DriverDeliveryPlanner = ({ orderGroups = [], onOpenOrder, currentUs
</div>
<div className="grid gap-3">
{items.map((item) => (
<button
<Button
key={item.id}
type="button"
className="rounded-[24px] border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-4 text-left transition hover:bg-[var(--color-accent-soft)]"
variant="secondary"
className="rounded-[24px] p-4 text-left"
onClick={() => onOpenOrder?.(item.id)}
>
<div className="flex flex-wrap items-start justify-between gap-3">
@ -414,7 +424,7 @@ export const DriverDeliveryPlanner = ({ orderGroups = [], onOpenOrder, currentUs
<div className="mt-3 text-sm text-[var(--color-text-muted)]">
{item.deliveryAddress || item.delivery_address || "Адрес не указан"}
</div>
</button>
</Button>
))}
</div>
</div>

View File

@ -92,6 +92,8 @@ const parseOrderItems = (order) => {
export const DriverShipmentPanel = ({ order, onShipmentChange, onSaveShipment, isSavingShipment }) => {
const [stopWords, setStopWords] = React.useState([]);
const [scopeActive, setScopeActive] = React.useState(true);
const [savedShipment, setSavedShipment] = React.useState([]);
const [justSaved, setJustSaved] = React.useState(false);
React.useEffect(() => {
if (!supabase) return;
@ -109,10 +111,46 @@ export const DriverShipmentPanel = ({ order, onShipmentChange, onSaveShipment, i
if (!stopWords.length || !scopeActive) return allItems;
return allItems.filter((item) => !matchesStopWord(item.name, stopWords));
}, [allItems, stopWords, scopeActive]);
const [shippedItems, setShippedItems] = React.useState(new Set());
const [comments, setComments] = React.useState({});
// Restore previously saved shipment data from order
const initialShippedIds = React.useMemo(() => {
const saved = order?.driverShipmentData;
if (!Array.isArray(saved) || saved.length === 0) return new Set();
const ids = new Set();
for (const item of saved) {
if (item.shipped && item.id) ids.add(item.id);
}
return ids;
}, [order?.driverShipmentData]);
const initialComments = React.useMemo(() => {
const saved = order?.driverShipmentData;
if (!Array.isArray(saved) || saved.length === 0) return {};
const map = {};
for (const item of saved) {
if (!item.shipped && item.id && item.comment) map[item.id] = item.comment;
}
return map;
}, [order?.driverShipmentData]);
const [shippedItems, setShippedItems] = React.useState(initialShippedIds);
const [comments, setComments] = React.useState(initialComments);
const [commentInput, setCommentInput] = React.useState("");
// Sync state when order data changes (e.g. after save)
React.useEffect(() => {
setShippedItems(initialShippedIds);
setComments(initialComments);
}, [initialShippedIds, initialComments]);
// Track last saved shipment data for visual display
React.useEffect(() => {
const saved = order?.driverShipmentData;
if (Array.isArray(saved) && saved.length > 0) {
setSavedShipment(saved);
}
}, [order?.driverShipmentData]);
const toggleItem = (itemId) => {
setShippedItems((prev) => {
const next = new Set(prev);
@ -265,17 +303,22 @@ export const DriverShipmentPanel = ({ order, onShipmentChange, onSaveShipment, i
{onSaveShipment && items.length > 0 && (
<div className="flex items-center gap-3">
<Button
onClick={() => onSaveShipment(items.map((item) => ({
id: item.id,
name: item.name,
quantity: item.quantity,
unit: item.unit,
shipped: shippedItems.has(item.id),
comment: shippedItems.has(item.id) ? "" : (comments[item.id] || ""),
})))}
onClick={() => {
const data = items.map((item) => ({
id: item.id,
name: item.name,
quantity: item.quantity,
unit: item.unit,
shipped: shippedItems.has(item.id),
comment: shippedItems.has(item.id) ? "" : (comments[item.id] || ""),
}));
setSavedShipment(data);
setJustSaved(true);
onSaveShipment(data);
}}
disabled={isSavingShipment || shippedCount === 0}
>
{isSavingShipment ? "Сохраняем..." : "Сохранить отгрузку"}
{isSavingShipment ? "Сохраняем..." : justSaved ? "Сохранить изменения" : "Сохранить"}
</Button>
{shippedCount > 0 && shippedCount < items.length && (
<span className="text-xs text-[var(--color-text-muted)]">
@ -284,6 +327,66 @@ export const DriverShipmentPanel = ({ order, onShipmentChange, onSaveShipment, i
)}
</div>
)}
{/* Saved shipment summary — show prominently after save */}
{justSaved && savedShipment.length > 0 && (
<div className="rounded-xl border-2 border-[var(--color-accent)] bg-[var(--color-accent-soft)] p-4 text-sm">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<span className="text-xl">✅</span>
<strong className="text-[var(--color-accent)]">
Отгрузка сохранена: {savedShipment.filter((i) => i.shipped).length} из {savedShipment.length}
</strong>
</div>
<Button variant="ghost" size="sm" onClick={() => setJustSaved(false)}>
Изменить
</Button>
</div>
<div className="space-y-2">
{savedShipment.map((item) => (
<div
key={item.id}
className={[
"rounded-lg px-3 py-2",
item.shipped
? "bg-[var(--color-surface-strong)] border border-[var(--color-accent)]"
: "bg-[var(--color-warning-soft)] border border-[var(--color-warning)]",
].join(" ")}
>
<div className="flex items-center gap-2">
<span className={item.shipped ? "text-[var(--color-accent)]" : "text-[var(--color-warning)]"}>
{item.shipped ? "✓" : "✗"}
</span>
<span className={item.shipped ? "text-[var(--color-text-muted)] line-through" : "text-[var(--color-text)] font-medium"}>
{item.name}{item.quantity ? ` — ${item.quantity}${item.unit ? ` ${item.unit}` : ""}` : ""}
</span>
</div>
{!item.shipped && item.comment && (
<div className="mt-1 ml-6 text-xs text-[var(--color-warning)]">
Причина: {item.comment}
</div>
)}
</div>
))}
</div>
</div>
)}
{/* Restore saved state on load (when not justSaved) */}
{!justSaved && savedShipment.length > 0 && (
<div className="rounded-xl border border-[var(--color-accent)] bg-[var(--color-accent-soft)] px-3 py-2 text-xs text-[var(--color-accent)]">
✅ Отгрузка ранее сохранена: {savedShipment.filter((i) => i.shipped).length}/{savedShipment.length} позиций
<Button
type="button"
variant="ghost"
size="sm"
className="underline text-[var(--color-text-muted)]"
onClick={() => setJustSaved(true)}
>
Показать
</Button>
</div>
)}
</Panel>
);
};

View File

@ -7,6 +7,7 @@ import {
ORDER_GROUP_DISPLAY_STATUS_OPTIONS,
} from "../../services/orderGroupViews";
import { Badge } from "../UI/Badge";
import { Button } from "../UI/Button";
import { Panel } from "../UI/Panel";
import { SkeletonPage } from "../UI/Loading";
import { OrderFilters } from "../orders/OrderFilters";
@ -113,9 +114,9 @@ export const LogisticsReadinessBoard = ({ orderGroups = [], onSelectSet, statusO
return (
<Panel key={statusValue} className="overflow-hidden p-0">
<button
type="button"
className="flex w-full items-center justify-between px-5 py-3 text-left transition hover:bg-[var(--color-accent-soft)]"
<Button
variant="ghost"
className="flex w-full items-center justify-between px-5 py-3 text-left"
onClick={() => {
setCollapsedSections((prev) => {
const next = new Set(prev);
@ -142,16 +143,16 @@ export const LogisticsReadinessBoard = ({ orderGroups = [], onSelectSet, statusO
>
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
</svg>
</button>
</Button>
{!isCollapsed && (
<div className="overflow-x-auto">
<TableHeader />
{groups.map((group) => (
<button
<Button
key={group.id}
type="button"
className={`grid ${COLS} gap-0 w-full border-t border-[var(--color-border)] text-left transition hover:bg-[var(--color-accent-soft)]`}
variant="ghost"
className={`grid ${COLS} gap-0 w-full border-t border-[var(--color-border)] text-left`}
onClick={() => { if (onSelectSet) onSelectSet(group.id); }}
>
<div className="px-4 py-2.5">
@ -176,7 +177,7 @@ export const LogisticsReadinessBoard = ({ orderGroups = [], onSelectSet, statusO
<div className="px-4 py-2.5 text-sm text-[var(--color-text-muted)]">
{formatDateTime(group.updatedAt)}
</div>
</button>
</Button>
))}
</div>
)}

View File

@ -47,7 +47,7 @@ export function NotificationBell({ notifications, unreadCount, onMarkAsRead, onM
return (
<div className="relative" ref={bellRef}>
<button
<Button
className="relative flex h-9 w-9 items-center justify-center rounded-full transition hover:bg-[var(--color-surface-strong)]"
onClick={() => setIsOpen(!isOpen)}
aria-label={`Уведомления${unreadCount > 0 ? ` (${unreadCount})` : ""}`}
@ -58,7 +58,7 @@ export function NotificationBell({ notifications, unreadCount, onMarkAsRead, onM
{unreadCount > 99 ? "99+" : unreadCount}
</span>
)}
</button>
</Button>
{isOpen && (
<div className="absolute right-0 top-full z-50 mt-2 w-80 sm:w-96">
@ -67,29 +67,29 @@ export function NotificationBell({ notifications, unreadCount, onMarkAsRead, onM
<h3 className="text-sm font-semibold">Уведомления</h3>
<div className="flex items-center gap-1">
{unreadCount > 0 && (
<button
<Button
className="rounded p-1 text-xs text-[var(--color-accent)] hover:bg-[var(--color-surface-strong)]"
onClick={onMarkAllAsRead}
title="Прочитать все"
>
<CheckCheck className="h-4 w-4" />
</button>
</Button>
)}
{onOpenSettings && (
<button
<Button
className="rounded p-1 text-xs text-[var(--color-text-muted)] hover:bg-[var(--color-surface-strong)]"
onClick={() => { onOpenSettings(); setIsOpen(false); }}
title="Настройки"
>
<Settings className="h-4 w-4" />
</button>
</Button>
)}
<button
<Button
className="rounded p-1 text-xs text-[var(--color-text-muted)] hover:bg-[var(--color-surface-strong)]"
onClick={() => setIsOpen(false)}
>
<X className="h-4 w-4" />
</button>
</Button>
</div>
</div>

View File

@ -2,6 +2,7 @@ import React from "react";
import { useNotificationPreferences } from "../../hooks/useNotifications";
import { usePushNotifications } from "../../hooks/usePushNotifications";
import { Panel } from "../UI/Panel";
import { Button } from "../UI/Button";
import { Bell, Settings } from "../UI/Icons";
import { Skeleton } from "../UI/Loading";
@ -27,12 +28,12 @@ export function NotificationSettings({ userId, userRole, onBack }) {
<div className="space-y-4">
<div className="flex items-center gap-3">
{onBack && (
<button
<Button
className="rounded p-1 text-[var(--color-text-muted)] hover:bg-[var(--color-surface-strong)]"
onClick={onBack}
>
← Назад
</button>
</Button>
)}
<h2 className="text-lg font-semibold">Настройки уведомлений</h2>
</div>
@ -67,12 +68,12 @@ export function NotificationSettings({ userId, userRole, onBack }) {
<div className="space-y-4">
<div className="flex items-center gap-3">
{onBack && (
<button
<Button
className="rounded p-1 text-[var(--color-text-muted)] hover:bg-[var(--color-surface-strong)]"
onClick={onBack}
>
← Назад
</button>
</Button>
)}
<h2 className="text-lg font-semibold">Настройки уведомлений</h2>
</div>
@ -94,7 +95,7 @@ export function NotificationSettings({ userId, userRole, onBack }) {
</div>
</div>
{isSupported && (
<button
<Button
className={`relative h-6 w-11 rounded-full transition-colors ${
isSubscribed ? "bg-[var(--color-accent)]" : "bg-[var(--color-border)]"
}`}
@ -106,7 +107,7 @@ export function NotificationSettings({ userId, userRole, onBack }) {
isSubscribed ? "translate-x-5" : "translate-x-0"
}`}
/>
</button>
</Button>
)}
</div>
</Panel>
@ -124,7 +125,7 @@ export function NotificationSettings({ userId, userRole, onBack }) {
<p className="text-sm font-medium">{label}</p>
<p className="text-xs text-[var(--color-text-muted)]">{description}</p>
</div>
<button
<Button
className={`relative mt-0.5 h-6 w-11 shrink-0 rounded-full transition-colors ${
prefs[key] ? "bg-[var(--color-accent)]" : "bg-[var(--color-border)]"
}`}
@ -136,7 +137,7 @@ export function NotificationSettings({ userId, userRole, onBack }) {
prefs[key] ? "translate-x-5" : "translate-x-0"
}`}
/>
</button>
</Button>
</label>
))}
</div>

View File

@ -1,4 +1,5 @@
import React from "react";
import { Button } from "../UI/Button";
const WEEK_DAY_LABELS = ["ПН", "ВТ", "СР", "ЧТ", "ПТ", "СБ", "ВС"];
@ -58,8 +59,8 @@ const CalendarWidget = ({
return (
<div className={layoutClassName}>
<div className={calendarClassName}>
<button
type="button"
<Button
variant="ghost"
aria-label={label}
aria-expanded={isCalendarOpen}
className="flex min-h-[54px] w-full items-center justify-between rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] px-4 text-left text-sm font-medium !text-[var(--color-text)] transition hover:border-[var(--color-accent)] focus:border-[var(--color-accent)] focus:outline-none"
@ -67,7 +68,7 @@ const CalendarWidget = ({
>
<span>{selectedDate ? formatDateForDisplay(selectedDate) : "Выберите дату"}</span>
<span aria-hidden="true" className="text-[var(--color-text-muted)]">▾</span>
</button>
</Button>
{isCalendarOpen ? (
<div className="rounded-[20px] border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-3 shadow-lg absolute left-0 top-full z-50 mt-2 w-[300px]">
<div className="flex items-center justify-between gap-3">
@ -83,23 +84,23 @@ const CalendarWidget = ({
</h4>
</div>
<div className="flex items-center gap-2">
<button
type="button"
<Button
variant="ghost"
disabled={!canGoBack}
aria-label="Предыдущий месяц"
className="flex h-9 w-9 items-center justify-center rounded-full border border-[var(--color-border)] text-sm text-[var(--color-text-muted)] transition hover:border-[var(--color-accent)] hover:!text-[var(--color-text)] disabled:cursor-not-allowed disabled:opacity-40"
onClick={() => setCurrentMonth((month) => new Date(month.getFullYear(), month.getMonth() - 1, 1))}
>
‹
</button>
<button
type="button"
</Button>
<Button
variant="ghost"
aria-label="Следующий месяц"
className="flex h-9 w-9 items-center justify-center rounded-full border border-[var(--color-border)] text-sm text-[var(--color-text-muted)] transition hover:border-[var(--color-accent)] hover:!text-[var(--color-text)]"
onClick={() => setCurrentMonth((month) => new Date(month.getFullYear(), month.getMonth() + 1, 1))}
>
›
</button>
</Button>
</div>
</div>
<div className="mt-4 grid grid-cols-7 gap-1 text-center text-[10px] font-semibold uppercase text-[var(--color-text-muted)]">
@ -123,9 +124,9 @@ const CalendarWidget = ({
const dayNumber = String(day.getDate()).padStart(2, "0");
return (
<button
<Button
key={dateKey}
type="button"
variant="ghost"
disabled={isDisabled}
title={isWeekend ? "Выходной, доставки нет" : isSelectable ? "Можно выбрать" : "Недоступно"}
className={[
@ -150,7 +151,7 @@ const CalendarWidget = ({
className="absolute inset-x-2 top-1/2 h-px -rotate-12 bg-[var(--color-text-muted)] opacity-70"
/>
) : null}
</button>
</Button>
);
})}
</div>
@ -162,9 +163,9 @@ const CalendarWidget = ({
</div>
<div className={timeClassName}>
{timeOptions.map((option) => (
<button
<Button
key={option}
type="button"
variant="ghost"
aria-pressed={selectedTime === option}
className={[
"min-h-[54px] rounded-2xl border px-4 text-left text-sm font-medium transition",
@ -175,7 +176,7 @@ const CalendarWidget = ({
onClick={() => onTimeChange(option)}
>
{option}
</button>
</Button>
))}
</div>
</div>

View File

@ -67,8 +67,8 @@ const ConfirmModal = ({ open, title, message, onConfirm, onCancel }) => {
{title && <h3 className="text-lg font-semibold">{title}</h3>}
{message && <p className="mt-2 text-sm text-[var(--color-text-muted)]">{message}</p>}
<div className="mt-5 flex justify-end gap-3">
<button type="button" className="rounded-xl border border-[var(--color-border)] px-4 py-2 text-sm font-medium text-[var(--color-text-muted)] hover:bg-[var(--color-surface)]" onClick={onCancel}>Отмена</button>
<button type="button" className="rounded-xl bg-[var(--color-accent)] px-4 py-2 text-sm font-medium text-white hover:opacity-90" onClick={onConfirm}>Подтвердить</button>
<Button variant="secondary" onClick={onCancel}>Отмена</Button>
<Button variant="primary" onClick={onConfirm}>Подтвердить</Button>
</div>
</div>
</div>
@ -84,13 +84,14 @@ const CollapsibleChips = ({ label, items }) => {
if (!Array.isArray(items) || items.length === 0) return null;
return (
<span className="inline">
<button
type="button"
<Button
variant="ghost"
size="sm"
className="ml-1 cursor-pointer rounded-full bg-[var(--color-surface)] px-2 py-0.5 text-xs font-medium text-[var(--color-text-muted)] transition hover:bg-[var(--color-accent-soft)] hover:text-[var(--color-accent)]"
onClick={() => setOpen(!open)}
>
{label} {open ? "▲" : "▼"}
</button>
</Button>
{open && (
<span className="ml-1 inline-flex flex-wrap gap-1">
{items.map((item, idx) => (
@ -342,8 +343,8 @@ const CollapsibleOrderComposition = ({ order }) => {
return (
<div className="space-y-3">
<button
type="button"
<Button
variant="ghost"
className="flex w-full items-center justify-between text-left"
onClick={() => setIsExpanded(!isExpanded)}
>
@ -365,7 +366,7 @@ const CollapsibleOrderComposition = ({ order }) => {
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
</svg>
</span>
</button>
</Button>
{isExpanded && (
<div className="space-y-3">
{!orders.length ? (
@ -516,15 +517,15 @@ const ProblemReasonModal = ({ onSelect, onCancel }) => (
<p className="text-sm text-[var(--color-text-muted)]">Укажите причину возникшей проблемы с доставкой.</p>
<div className="space-y-2">
{PROBLEM_REASONS.map((reason) => (
<button
<Button
key={reason.value}
type="button"
className="w-full rounded-[16px] border border-[var(--color-border)] bg-[var(--color-surface)] p-3 text-left transition hover:border-[var(--color-accent)] hover:bg-[var(--color-accent-soft)]"
variant="secondary"
className="w-full rounded-[16px] p-3 text-left"
onClick={() => onSelect(reason.value, reason.label)}
>
<span className="font-medium">{reason.label}</span>
<p className="mt-0.5 text-xs text-[var(--color-text-muted)]">{reason.description}</p>
</button>
</Button>
))}
</div>
<div className="flex justify-end">
@ -635,7 +636,7 @@ export const OrderDetailPanel = ({
);
}
const isDeliveryAgreed = ["agreed", "driver_assigned", "loaded", "on_route", "delivered", "picked_up"].includes(order.deliveryStatus || order.delivery_status);
const isDeliveryAgreed = ["agreed", "driver_assigned", "loaded", "on_route", "delivered", "picked_up", "pickup"].includes(order.deliveryStatus || order.delivery_status);
const isPickupOrder = order.deliveryType === "pickup" || order.deliveryStatus === "pickup" || order.delivery_status === "pickup";
// Show "agreed" banner only when selected tab matches the already-agreed type
const agreedTypeMatchesTab = isDeliveryAgreed && !isEditingDate && (
@ -863,6 +864,12 @@ export const OrderDetailPanel = ({
<p className="text-xs text-[var(--color-text-muted)]">{isPickupOrder ? "Статус самовывоза" : "Статус доставки"}</p>
<p className="font-medium !text-[var(--color-text)]">{getOrderGroupDeliveryStatusLabel(order.deliveryStatus || order.delivery_status)}</p>
</div>
{(order.pickupCode || order.pickup_code) && (order.deliveryType === "pickup" || order.delivery_type === "pickup") ? (
<div>
<p className="text-xs text-[var(--color-text-muted)]">Код выдачи</p>
<p className="text-2xl font-bold tracking-[0.3em] text-[var(--color-accent)]">{order.pickupCode || order.pickup_code}</p>
</div>
) : null}
</div>
</Panel>
@ -878,28 +885,20 @@ export const OrderDetailPanel = ({
</div>
{/* Delivery type tabs */}
<div className="flex gap-2 rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] p-1">
<button
type="button"
className={`flex-1 rounded-xl px-3 py-2 text-sm font-semibold transition ${
deliveryType === "delivery"
? "bg-[var(--color-accent)] text-white"
: "text-[var(--color-text-muted)] hover:text-[var(--color-text)]"
}`}
<Button
variant={deliveryType === "delivery" ? "primary" : "ghost"}
className="flex-1 rounded-xl px-3 py-2 text-sm font-semibold"
onClick={() => { setDeliveryType("delivery"); setFormMessage(""); }}
>
🚚 Доставка
</button>
<button
type="button"
className={`flex-1 rounded-xl px-3 py-2 text-sm font-semibold transition ${
deliveryType === "pickup"
? "bg-[var(--color-accent)] text-white"
: "text-[var(--color-text-muted)] hover:text-[var(--color-text)]"
}`}
</Button>
<Button
variant={deliveryType === "pickup" ? "primary" : "ghost"}
className="flex-1 rounded-xl px-3 py-2 text-sm font-semibold"
onClick={() => { setDeliveryType("pickup"); setFormMessage(""); }}
>
🏪 Самовывоз
</button>
</Button>
</div>
{deliveryType === "pickup" && (
<div className="rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] p-3 text-sm text-[var(--color-text-muted)]">
@ -1087,14 +1086,11 @@ export const OrderDetailPanel = ({
return statusOptions.map((statusOption) => {
const isSelected = pendingStatus?.value === statusOption.value;
const isDeliveredBtn = statusOption.value === "delivered";
const deliveryBlocked = isDeliveredBtn && shipmentState && !shipmentState.canMarkDelivered;
return (
<Button
key={statusOption.value}
variant={isSelected ? "primary" : "secondary"}
disabled={deliveryBlocked}
title={deliveryBlocked ? "Сначала отметьте все позиции как отгруженные" : undefined}
disabled={isSavingStatusChange}
onClick={() => {
if (statusOption.value === "problem") {
setProblemReason("selecting");
@ -1104,11 +1100,6 @@ export const OrderDetailPanel = ({
}}
>
{statusOption.label}
{isDeliveredBtn && shipmentState && !shipmentState.canMarkDelivered ? (
<span className="ml-1.5 text-xs text-[var(--color-text-muted)]">
({shipmentState.shipped}/{shipmentState.total})
</span>
) : null}
</Button>
);
});
@ -1120,7 +1111,6 @@ export const OrderDetailPanel = ({
variant="primary"
disabled={isSavingStatusChange}
onClick={() => {
if (pendingStatus.value === "delivered" && shipmentState && !shipmentState.canMarkDelivered) return;
onChangeDeliveryStatus({
orderGroupId: order.id,
status: pendingStatus.value,

View File

@ -1,4 +1,5 @@
import React from "react";
import { Button } from "../UI/Button";
import { Input } from "../UI/Input";
import { Panel } from "../UI/Panel";
import { DatePicker } from "../UI/DatePicker";
@ -41,12 +42,11 @@ export const OrderFilters = ({ filters, setFilters, statusOptions = [], cities =
{/* Row 1: Status + City + Search */}
<div className="grid gap-3 md:grid-cols-[minmax(12rem,0.7fr)_minmax(0,0.5fr)_minmax(0,1.6fr)] md:items-end">
<div ref={statusMenuRef} className="relative flex min-w-0 flex-col gap-2">
<button
type="button"
<Button
variant="ghost"
aria-haspopup="listbox"
aria-expanded={isStatusOpen}
className={[
"flex h-[46px] w-full items-center justify-between rounded-2xl border px-4 text-left text-sm transition",
className={["flex h-[46px] w-full items-center justify-between rounded-2xl border px-4 text-left text-sm transition",
isStatusOpen
? "border-[var(--color-accent)] bg-[var(--color-accent-soft)] text-[var(--color-text)]"
: "border-[var(--color-border)] bg-[var(--color-surface)] text-[var(--color-text)] hover:border-[var(--color-accent)]",
@ -55,7 +55,7 @@ export const OrderFilters = ({ filters, setFilters, statusOptions = [], cities =
>
<span className="min-w-0 flex-1 truncate">{selectedStatusLabel}</span>
<span aria-hidden="true" className="ml-3 text-[var(--color-text-muted)]">▾</span>
</button>
</Button>
{isStatusOpen ? (
<div
@ -65,13 +65,12 @@ export const OrderFilters = ({ filters, setFilters, statusOptions = [], cities =
{statusOptions.map((option) => {
const isSelected = option.value === statusValue;
return (
<button
<Button
key={option.value}
type="button"
variant="ghost"
role="option"
aria-selected={isSelected}
className={[
"flex w-full items-center justify-between px-4 py-3 text-left text-sm transition",
className={["flex w-full items-center justify-between px-4 py-3 text-left text-sm transition",
isSelected
? "bg-[var(--color-accent-soft)] text-[var(--color-text)]"
: "text-[var(--color-text)] hover:bg-[var(--color-surface-strong)]",
@ -86,7 +85,7 @@ export const OrderFilters = ({ filters, setFilters, statusOptions = [], cities =
{option.count || 0}
</span>
{isSelected ? <span className="ml-3 text-[var(--color-accent)]">✓</span> : null}
</button>
</Button>
);
})}
</div>
@ -106,6 +105,16 @@ export const OrderFilters = ({ filters, setFilters, statusOptions = [], cities =
</select>
)}
<select
value={filters.deliveryType || ""}
onChange={(e) => updateFilter("deliveryType", e.target.value)}
className="h-[46px] rounded-2xl border border-[var(--color-border)] bg-[var(--color-surface)] px-4 text-sm outline-none focus:border-[var(--color-accent)]"
>
<option value="">Тип получения</option>
<option value="delivery">Доставка</option>
<option value="pickup">Самовывоз</option>
</select>
<Input
className="h-[46px] py-0"
placeholder="Поиск по группе, клиенту или телефону"
@ -131,13 +140,13 @@ export const OrderFilters = ({ filters, setFilters, statusOptions = [], cities =
className="min-w-[140px] flex-1 md:max-w-[200px]"
/>
{hasDateFilter && (
<button
type="button"
<Button
variant="ghost"
onClick={clearDateFilter}
className="mb-0.5 flex h-[46px] items-center gap-1.5 rounded-2xl border border-[var(--color-danger)] px-4 text-sm font-semibold text-[var(--color-danger)] hover:bg-[rgba(201,61,61,0.08)] transition"
className="mb-0.5 h-[46px] gap-1.5 rounded-2xl border border-[var(--color-danger)] px-4 text-sm font-semibold text-[var(--color-danger)] hover:bg-[rgba(201,61,61,0.08)]"
>
✕ Сбросить
</button>
</Button>
)}
</div>
</div>

View File

@ -107,15 +107,15 @@ export const OrdersCalendarView = ({ orders, onOpenOrder }) => {
</div>
<div className="space-y-2">
{dayOrders.map((order) => (
<button
<Button
key={order.id}
type="button"
variant="ghost"
className="w-full rounded-[16px] px-3 py-3 text-left text-sm"
onClick={() => onOpenOrder(order.id)}
className="w-full rounded-[16px] bg-[var(--color-surface)] px-3 py-3 text-left text-sm hover:bg-[var(--color-accent-soft)]"
>
<div className="font-medium">{order.orderNumber}</div>
<div className="mt-1 text-xs text-[var(--color-text-muted)]">{order.customer.name}</div>
</button>
</Button>
))}
</div>
</div>
@ -157,17 +157,17 @@ export const OrdersCalendarView = ({ orders, onOpenOrder }) => {
<div className="space-y-2">
{dayOrders.slice(0, 2).map((order) => (
<button
<Button
key={order.id}
type="button"
variant="ghost"
className="w-full rounded-[16px] px-3 py-2 text-left text-sm"
onClick={() => onOpenOrder(order.id)}
className="w-full rounded-[16px] bg-[var(--color-surface)] px-3 py-2 text-left text-sm hover:bg-[var(--color-accent-soft)]"
>
<div className="font-medium">{order.orderNumber}</div>
<div className="mt-1 text-xs text-[var(--color-text-muted)]">
{order.customer.name}
</div>
</button>
</Button>
))}
{dayOrders.length > 2 ? (
<div className="px-1 text-xs text-[var(--color-text-muted)]">

View File

@ -1,5 +1,6 @@
import { formatDateTime } from "../../utils/formatters";
import { Badge } from "../UI/Badge";
import { Button } from "../UI/Button";
import { Panel } from "../UI/Panel";
import { SkeletonTable } from "../UI/Loading";
import { OrderFilters } from "./OrderFilters";
@ -17,6 +18,14 @@ const fmtDate = (d) => {
return `${day}.${m}.${y}`;
};
const getShipmentIssues = (group) => {
const data = group?.driverShipmentData;
if (!Array.isArray(data) || data.length === 0) return null;
const unshipped = data.filter((i) => !i.shipped);
if (unshipped.length === 0) return null;
return unshipped;
};
const buildGroupSummary = (group) => {
const orderCountLabel = `${group.ordersCount || 0} ${group.ordersCount === 1 ? "заказ" : group.ordersCount < 5 ? "заказа" : "заказов"}`;
const parts = [orderCountLabel];
@ -45,6 +54,12 @@ const renderOrderNumbers = (group) => {
return `${visible.join(", ")} +${remaining}`;
};
const getDeliveryTypeLabel = (deliveryType) => {
if (deliveryType === "pickup") return "Самовывоз";
if (deliveryType === "delivery") return "Доставка";
return "—";
};
const renderMobileOrderNumbers = (group) => {
const numbers = group.allBillNumbers || group.orderNumbers;
if (!Array.isArray(numbers) || !numbers.length) {
@ -102,37 +117,56 @@ export const OrdersTable = ({
Группы не найдены. Попробуйте изменить поиск или статус.
</div>
) : null}
{orderGroups.map((group) => (
<button
key={group.id}
type="button"
onClick={() => onOpenOrder(group.id)}
className={[
"w-full rounded-[22px] border border-[var(--color-border)] bg-[var(--color-surface-strong)] p-4 text-left transition",
selectedOrderGroupId === group.id ? "bg-[var(--color-accent-soft)]" : "",
].join(" ")}
>
<div className="space-y-1">
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-start gap-3">
<div className="min-w-0 truncate font-medium">
{group.displayTitle || group.customerName || group.groupKey}
</div>
<Badge className="self-start" tone={getOrderGroupStatusTone(group)}>
{getOrderGroupDisplayStatusLabel(group)}
</Badge>
</div>
<div className="text-sm text-[var(--color-text-muted)]">
{group.displaySubtitle || [group.customerPhone, group.customerDate].filter(Boolean).join(" · ")}
</div>
</div>
{orderGroups.map((group) => {
const hasProblem = group.hasDeliveryProblem;
const baseClass = "w-full rounded-[22px] border text-left transition";
const selectedClass = selectedOrderGroupId === group.id
? "border-[var(--color-accent)] bg-[var(--color-accent-soft)]"
: hasProblem
? "border-[var(--color-danger)] bg-[rgba(201,61,61,0.1)]"
: "border-[var(--color-border)] bg-[var(--color-surface-strong)]";
<div className="mt-3 text-sm text-[var(--color-text-muted)]">{buildGroupSummary(group)}</div>
<div className="mt-2 text-sm text-[var(--color-text-muted)]">{renderMobileOrderNumbers(group)}</div>
<div className="mt-3 text-xs text-[var(--color-text-muted)]">
{formatDateTime(group.updatedAt)}
</div>
</button>
))}
return (
<Button
key={group.id}
variant="ghost"
onClick={() => onOpenOrder(group.id)}
className={[baseClass, selectedClass].join(" ")}
>
<div className="space-y-1">
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-start gap-3">
<div className="min-w-0 truncate font-medium">
{group.displayTitle || group.customerName || group.groupKey}
</div>
<Badge className="self-start" tone={getOrderGroupStatusTone(group)}>
{getOrderGroupDisplayStatusLabel(group)}
</Badge>
</div>
<div className="text-sm text-[var(--color-text-muted)]">
{group.displaySubtitle || [group.customerPhone, group.customerDate].filter(Boolean).join(" · ")}
</div>
</div>
<div className="mt-3 text-sm text-[var(--color-text-muted)]">{buildGroupSummary(group)}</div>
<div className="mt-2 text-sm text-[var(--color-text-muted)]">{renderMobileOrderNumbers(group)}</div>
<div className="mt-2 text-sm text-[var(--color-text-muted)]">Тип: {getDeliveryTypeLabel(group.deliveryType)}</div>
{group.hasDeliveryProblem && (
<div className="mt-2 rounded-lg border border-[var(--color-warning)] bg-[var(--color-warning-soft)] px-2 py-1 text-xs">
<span className="font-medium text-[var(--color-warning)]">⚠ Проблема с доставкой</span>
{group.deliveryProblemNote && (
<div className="mt-0.5 text-[var(--color-text-muted)]">{group.deliveryProblemNote}</div>
)}
</div>
)}
{!group.hasDeliveryProblem && Array.isArray(group?.driverShipmentData) && group.driverShipmentData.length > 0 && (
<div className="mt-2 text-xs text-[var(--color-accent)]">✓ Доставка без проблем</div>
)}
<div className="mt-3 text-xs text-[var(--color-text-muted)]">
{formatDateTime(group.updatedAt)}
</div>
</Button>
);
})}
</div>
<div className="hidden overflow-x-auto md:block">
@ -142,21 +176,30 @@ export const OrdersTable = ({
</div>
) : (
<div>
<div className="grid grid-cols-[minmax(180px,2.5fr)_minmax(100px,1.2fr)_minmax(100px,1fr)_minmax(80px,1fr)_minmax(120px,1.2fr)_minmax(130px,1.2fr)] gap-0 border-b border-[var(--color-border)] bg-[var(--color-surface-strong)] text-xs uppercase tracking-[0.16em] text-[var(--color-text-muted)]">
<div className="grid grid-cols-[minmax(180px,2.5fr)_minmax(100px,1.2fr)_minmax(100px,1fr)_minmax(80px,1fr)_minmax(120px,1.2fr)_minmax(80px,0.8fr)_minmax(130px,1.2fr)] gap-0 border-b border-[var(--color-border)] bg-[var(--color-surface-strong)] text-xs uppercase tracking-[0.16em] text-[var(--color-text-muted)]">
<div className="px-5 py-4 font-medium">Группа / Клиент</div>
<div className="px-5 py-4 font-medium">Счёта</div>
<div className="px-5 py-4 font-medium">Статус</div>
<div className="px-5 py-4 font-medium">Водитель</div>
<div className="px-5 py-4 font-medium">Дата доставки</div>
<div className="px-5 py-4 font-medium">Тип</div>
<div className="px-5 py-4 font-medium">Обновлён</div>
</div>
{orderGroups.map((group) => (
<button
key={group.id}
type="button"
className={`grid grid-cols-[minmax(180px,2.5fr)_minmax(100px,1.2fr)_minmax(100px,1fr)_minmax(80px,1fr)_minmax(120px,1.2fr)_minmax(130px,1.2fr)] gap-0 w-full border-t border-[var(--color-border)] text-left transition hover:bg-[var(--color-accent-soft)] ${selectedOrderGroupId === group.id ? "bg-[var(--color-accent-soft)]" : ""}`}
onClick={() => onOpenOrder(group.id)}
>
{orderGroups.map((group) => {
const hasProblem = group.hasDeliveryProblem;
const rowClassName = `grid grid-cols-[minmax(180px,2.5fr)_minmax(100px,1.2fr)_minmax(100px,1fr)_minmax(80px,1fr)_minmax(120px,1.2fr)_minmax(80px,0.8fr)_minmax(130px,1.2fr)] gap-0 w-full border-t border-[var(--color-border)] text-left transition ${
hasProblem
? "bg-[rgba(201,61,61,0.1)] hover:bg-[rgba(201,61,61,0.15)]"
: "hover:bg-[var(--color-accent-soft)]"
} ${selectedOrderGroupId === group.id ? "bg-[var(--color-accent-soft)]" : ""}`;
return (
<Button
key={group.id}
variant="ghost"
className={rowClassName}
onClick={() => onOpenOrder(group.id)}
>
<div className="px-5 py-4">
<div className="font-medium">{group.displayTitle || group.customerName || group.groupKey}</div>
<div className="mt-1 text-sm text-[var(--color-text-muted)]">
@ -180,12 +223,16 @@ export const OrdersTable = ({
<span className="text-[var(--color-text-muted)]">—</span>
)}
</div>
<div className="px-5 py-4 text-sm">
{getDeliveryTypeLabel(group.deliveryType)}
</div>
<div className="px-5 py-4 text-sm text-[var(--color-text-muted)]">
{formatDateTime(group.updatedAt)}
</div>
</button>
))}
</div>
</Button>
);
})}
</div>
)}
</div>
</Panel>

View File

@ -14,6 +14,7 @@ export const useOrderGroups = () => {
const [filters, setFilters] = React.useState({
query: "",
displayStatus: "all",
deliveryType: "",
});
const [selectedOrderGroupId, setSelectedOrderGroupId] = React.useState(null);
const [isLoading, setIsLoading] = React.useState(true);
@ -22,38 +23,49 @@ export const useOrderGroups = () => {
const [isSavingDriverAssignment, setIsSavingDriverAssignment] = React.useState(false);
const [isSavingStatusChange, setIsSavingStatusChange] = React.useState(false);
const loadLiveData = React.useCallback(async (showLoading = true) => {
if (showLoading) {
setIsLoading(true);
}
setLoadError("");
const groupsResult = await fetchOrderGroups();
if (!groupsResult) {
return;
}
if (groupsResult.error) {
setLoadError(groupsResult.error?.message || "Не удалось загрузить группы доставки");
setOrderGroups([]);
setIsLoading(false);
return;
}
setOrderGroups(groupsResult.data || []);
setIsLoading(false);
}, []);
// Initial load
React.useEffect(() => {
let cancelled = false;
const loadLiveData = async () => {
/* Demo mode removed — always use Supabase */
const doLoad = async () => {
setIsLoading(true);
setLoadError("");
const groupsResult = await fetchOrderGroups();
if (cancelled) {
return;
}
if (groupsResult.error) {
setLoadError(groupsResult.error?.message || "Не удалось загрузить группы доставки");
setOrderGroups([]);
setIsLoading(false);
return;
}
setOrderGroups(groupsResult.data || []);
setIsLoading(false);
await loadLiveData(true);
if (cancelled) return;
};
doLoad();
return () => { cancelled = true; };
}, [loadLiveData]);
loadLiveData();
return () => {
cancelled = true;
// Refetch on window focus to keep data fresh across tabs/pages
React.useEffect(() => {
const handleFocus = () => {
loadLiveData(false); // silent refetch, no loading spinner
};
}, []);
window.addEventListener("focus", handleFocus);
return () => window.removeEventListener("focus", handleFocus);
}, [loadLiveData]);
React.useEffect(() => {
if (!orderGroups.length) {
@ -238,5 +250,6 @@ export const useOrderGroups = () => {
isSavingStatusChange,
isLoading,
loadError,
refetch: loadLiveData,
};
};

View File

@ -57,7 +57,7 @@ export const AppShell = ({
<div className="space-y-1">
{navItems.map((item) => (
<button
<Button
key={item.key}
className={[
"flex w-full items-center justify-between rounded-[18px] px-3 py-3 text-left text-sm transition",
@ -70,7 +70,7 @@ export const AppShell = ({
>
<span className="font-medium">{item.label}</span>
{item.badge ? <Badge tone="accent">{item.badge}</Badge> : null}
</button>
</Button>
))}
</div>
@ -129,7 +129,7 @@ export const AppShell = ({
<div className="sticky inset-x-0 top-0 z-40 -mx-3 -mt-4 border-b border-[var(--color-border)] bg-[var(--color-surface)] px-3 py-2 backdrop-blur xl:hidden sm:-mx-4 md:-mx-6">
<div className="flex gap-1 overflow-x-auto" style={{ WebkitOverflowScrolling: 'touch', scrollbarWidth: 'none' }}>
{navItems.map((item) => (
<button
<Button
key={item.key}
className={[
"flex flex-shrink-0 items-center gap-1.5 rounded-[14px] px-3 py-2 text-sm transition",
@ -144,7 +144,7 @@ export const AppShell = ({
{item.badge ? (
<Badge tone={activeSection === item.key ? "neutral" : "accent"}>{item.badge}</Badge>
) : null}
</button>
</Button>
))}
</div>
</div>

View File

@ -7,6 +7,7 @@ import { OrderCompositionPanel } from "../components/client/OrderCompositionPane
import { getInvitationReferenceLabel } from "../components/client/invitationReference";
import { DeliveryStateNotice } from "../components/client/DeliveryStateNotice";
import { Panel } from "../components/UI/Panel";
import { Button } from "../components/UI/Button";
import { Skeleton } from "../components/UI/Loading";
import { formatDeliveryDate } from "../components/client/deliveryDateFormatting";
import {
@ -378,6 +379,13 @@ export const ClientDeliveryPage = () => {
<p className="text-sm leading-6 text-[var(--color-text-muted)]">
Статус: {invitation?.deliveryType === "pickup" ? "самовывоз" : "доставка"} уже согласован. При повторном открытии этой ссылки будет показан тот же выбор.
</p>
{(invitation?.pickupCode || invitation?.pickup_code) ? (
<div className="mt-3 rounded-2xl border-2 border-[var(--color-accent)] bg-[var(--color-accent-soft)] p-4 text-center">
<p className="text-xs uppercase tracking-[0.2em] text-[var(--color-text-muted)]">Код выдачи</p>
<p className="mt-1 text-3xl font-bold tracking-[0.4em] text-[var(--color-accent)]">{invitation.pickupCode || invitation.pickup_code}</p>
<p className="mt-2 text-xs text-[var(--color-text-muted)]">Покажите этот код при получении заказа</p>
</div>
) : null}
</Panel>
) : null}
@ -385,7 +393,7 @@ export const ClientDeliveryPage = () => {
<>
{/* Tab switcher */}
<div className="flex gap-2 rounded-[28px] border border-[var(--color-border)] bg-[var(--color-surface)] p-1">
<button
<Button
type="button"
className={`flex-1 rounded-[24px] px-4 py-2.5 text-sm font-semibold transition ${
activeTab === TAB_DELIVERY
@ -400,8 +408,8 @@ export const ClientDeliveryPage = () => {
}}
>
🚚 Доставка
</button>
<button
</Button>
<Button
type="button"
className={`flex-1 rounded-[24px] px-4 py-2.5 text-sm font-semibold transition ${
activeTab === TAB_PICKUP
@ -416,7 +424,7 @@ export const ClientDeliveryPage = () => {
}}
>
🏪 Самовывоз
</button>
</Button>
</div>
{activeTab === TAB_DELIVERY && !invitation?.deliveryAddress && !invitation?.customerAddress && (

View File

@ -37,6 +37,7 @@ export const GroupDetailPage = () => {
changeDeliveryStatus,
saveShipmentData,
isLoading,
refetch,
} = useOrderGroups();
// ── Drivers ────────────────────────────────────────────────────────────────
@ -48,6 +49,11 @@ export const GroupDetailPage = () => {
}
}, [groupId, setSelectedOrderGroupId]);
// Refetch data when navigating to this page to ensure fresh status
React.useEffect(() => {
refetch(false); // silent refetch, no loading spinner
}, [refetch]);
React.useEffect(() => {
let cancelled = false;
const load = async () => {

View File

@ -141,7 +141,7 @@ export const isOrderGroupAgreedForDelivery = (group) => {
};
export const getOrderGroupDeliveryStatusLabel = (status) =>
DELIVERY_GROUP_STATUS_LABELS[status] || status || "Неизвестно";
DELIVERY_GROUP_STATUS_LABELS[status] || (status ? `Неизвестно (${status})` : "Неизвестно");
export const getOrderGroupDisplayStatusLabel = (group) => {
const deliveryStatus = group?.deliveryStatus || group?.delivery_status;
@ -305,6 +305,11 @@ export const filterOrderGroups = (groups, filters = {}) => {
}
}
const deliveryTypeFilter = (filters.deliveryType || "").trim().toLowerCase();
if (deliveryTypeFilter && group.deliveryType !== deliveryTypeFilter) {
return false;
}
if (!query) {
return true;
}
@ -333,13 +338,11 @@ export const ORDER_GROUP_DISPLAY_STATUS_OPTIONS = [
{ value: "delivery:paid_storage", label: DELIVERY_GROUP_STATUS_LABELS.paid_storage },
{ value: "delivery:cancelled", label: DELIVERY_GROUP_STATUS_LABELS.cancelled },
{ value: "status:manual_required", label: "Требует ручной обработки" },
{ value: "status:second_sms_sent", label: "Повторное SMS" },
{ value: "status:sms_sent", label: "SMS отправлены" },
{ value: "status:ready_for_notification", label: "Готово к уведомлению" },
];
export const getOrderGroupStatusLabel = (status) =>
ORDER_GROUP_STATUS_LABELS[status] || status || "Неизвестно";
ORDER_GROUP_STATUS_LABELS[status] || (status ? `Неизвестно (${status})` : "Неизвестно");
export const getOrderGroupDeliveryStatusTone = (status) => {
switch (status) {
@ -461,6 +464,9 @@ export const buildOrderGroupBuckets = (groups) => {
export const getOrderGroupStatusTone = (group) => {
const deliveryStatus = group?.deliveryStatus || group?.delivery_status;
// Highlight groups with delivery problems
if (group?.hasDeliveryProblem) return "warning";
if (deliveryStatus && deliveryStatus !== "pending_confirmation") {
return getOrderGroupDeliveryStatusTone(deliveryStatus);
}

View File

@ -221,6 +221,9 @@ export const mapOrderGroupRowToDeliveryGroup = (row) => {
pickupDate: row.pickup_date || null,
pickupTimeSlot: row.pickup_time_slot || null,
driverShipmentData: row.driver_shipment_data || null,
hasDeliveryProblem: row.has_delivery_problem || false,
deliveryProblemNote: row.delivery_problem_note || null,
pickupCode: row.pickup_code || null,
syncedTo1cAt: row.synced_to_1c_at || null,
deliveryHalfDay: getOrderGroupDeliveryHalfDay({
deliveryHalfDay: rawDeliveryHalfDay,
@ -262,7 +265,7 @@ export const mapOrderGroupRowToDeliveryGroup = (row) => {
};
};
const ORDER_GROUP_SELECT_FIELDS = `id, group_key, order_numbers, status, delivery_status, sms_sent_at, created_at, updated_at, created_from_exchange_at, source_key, customer_name, customer_phone, customer_phone_normalized, customer_date, orders_total, orders_ready, orders_not_ready, source_orders, order_list, order_list_structured, delivery_invitation_id, delivery_link, notification_status, sms_attempts, first_sms_sent_at, second_sms_sent_at, last_sms_error, next_notification_check_at, delivery_date, delivery_time, delivery_address, customer_address, delivery_date_source, manual_confirmation_at, paid_storage_at, assigned_driver_id, assigned_driver:users!order_groups_assigned_driver_id_fkey(id, name), driver_shipment_data, delivery_type, pickup_date, pickup_time_slot, synced_to_1c_at`;
const ORDER_GROUP_SELECT_FIELDS = `id, group_key, order_numbers, status, delivery_status, sms_sent_at, created_at, updated_at, created_from_exchange_at, source_key, customer_name, customer_phone, customer_phone_normalized, customer_date, orders_total, orders_ready, orders_not_ready, source_orders, order_list, order_list_structured, delivery_invitation_id, delivery_link, notification_status, sms_attempts, first_sms_sent_at, second_sms_sent_at, last_sms_error, next_notification_check_at, delivery_date, delivery_time, delivery_address, customer_address, delivery_date_source, manual_confirmation_at, paid_storage_at, assigned_driver_id, assigned_driver:users!order_groups_assigned_driver_id_fkey(id, name), driver_shipment_data, delivery_type, pickup_date, pickup_time_slot, has_delivery_problem, delivery_problem_note, pickup_code, synced_to_1c_at`;
export const updateOrderGroupDeliveryChoice = async ({
orderGroupId,
@ -350,7 +353,7 @@ export const assignDriverToOrderGroup = async ({
const ADVANCED_STATUSES = ["loaded", "on_route", "delivered", "picked_up"];
const newStatus = driverId
? (ADVANCED_STATUSES.includes(currentStatus) ? undefined : "driver_assigned")
: null; // removing driver → reset to pending
: "agreed"; // removing driver → revert to agreed (NOT null — would violate NOT NULL constraint)
const updates = {
assigned_driver_id: driverId || null,
...(newStatus !== undefined && { delivery_status: newStatus }),
@ -391,13 +394,28 @@ export const assignDriverToOrderGroup = async ({
export const saveShipmentData = async ({ orderGroupId, shipmentData }) => {
return safeSupabaseCall(async () => {
const client = requireSupabase();
const hasAnyShipped = shipmentData.some((i) => i.shipped);
const hasProblem = shipmentData.some((i) => !i.shipped);
const problemNote = hasProblem
? shipmentData.filter((i) => !i.shipped).map((i) => `${i.name}${i.quantity ? ` (${i.quantity}${i.unit ? ` ${i.unit}` : ""})` : ""}${i.comment ? ` — ${i.comment}` : ""}`).join("; ")
: null;
// Any shipment data saved = delivered status. Problems go into has_delivery_problem/delivery_problem_note columns.
const newDeliveryStatus = hasAnyShipped ? "delivered" : undefined;
const updatePayload = {
driver_shipment_data: shipmentData,
has_delivery_problem: hasProblem,
delivery_problem_note: problemNote,
updated_at: new Date().toISOString(),
};
if (newDeliveryStatus) {
updatePayload.delivery_status = newDeliveryStatus;
}
const { error: updateError } = await client
.from("order_groups")
.update({
driver_shipment_data: shipmentData,
updated_at: new Date().toISOString(),
})
.update(updatePayload)
.eq("id", orderGroupId);
if (updateError) throw updateError;

View File

@ -138,6 +138,17 @@ Deno.serve(async (request) => {
const deliveryType = body.deliveryType || "delivery";
if (invitation.order_group_id) {
const { data: currentGroup, error: groupError } = await supabase
.from("order_groups")
.select("id, delivery_status, delivery_address, customer_address")
.eq("id", invitation.order_group_id)
.single();
if (groupError) {
throw groupError;
}
// When user switches from pickup to delivery but has no address → requires_address
const hasAddress = invitation.delivery_address?.trim() || currentGroup?.delivery_address?.trim() || currentGroup?.customer_address?.trim();
const effectiveDeliveryStatus = deliveryType === "pickup"
@ -146,17 +157,6 @@ Deno.serve(async (request) => {
? "agreed"
: "requires_address";
if (invitation.order_group_id) {
const { data: currentGroup, error: groupError } = await supabase
.from("order_groups")
.select("id, delivery_status")
.eq("id", invitation.order_group_id)
.single();
if (groupError) {
throw groupError;
}
if (!isActiveInvitationState(invitation.state) || currentGroup.delivery_status !== "pending_confirmation") {
return jsonResponse(
{
@ -208,6 +208,8 @@ Deno.serve(async (request) => {
if (deliveryType === "pickup") {
groupUpdateData.pickup_date = body.pickupDate || requestedSlot.deliveryDate || null;
groupUpdateData.pickup_time_slot = body.pickupTimeSlot || requestedSlot.deliveryTime || null;
// Pickup orders don't need a driver — clear assignment
groupUpdateData.assigned_driver_id = null;
}
const { error: groupUpdateError } = await supabase
@ -256,6 +258,7 @@ Deno.serve(async (request) => {
ok: true,
orderGroupId: invitation.order_group_id,
deliveryStatus: effectiveDeliveryStatus,
pickupCode: groupUpdateData.pickup_code || null,
},
200,
corsHeaders,

View File

@ -23,6 +23,9 @@ type UpdateDeliveryChoiceBody = {
orderGroupId?: string;
deliveryDate?: string;
deliveryTime?: string;
deliveryType?: string;
pickupDate?: string;
pickupTimeSlot?: string;
};
const isValidDate = (value: string) => /^\d{4}-\d{2}-\d{2}$/.test(value);
@ -111,12 +114,14 @@ Deno.serve(async (request) => {
const orderGroupId = String(body.orderGroupId || "").trim();
const deliveryDate = String(body.deliveryDate || "").trim();
const deliveryTime = normalizeDeliveryTime(String(body.deliveryTime || "").trim());
const deliveryType = String(body.deliveryType || "delivery").trim();
if (!orderGroupId) {
return jsonResponse({ ok: false, error: "orderGroupId is required" }, 400, corsHeaders);
}
if (!isAllowedDeliveryDate(deliveryDate)) {
// Pickup orders don't require a delivery date — allow skipping date validation
if (deliveryType !== "pickup" && !isAllowedDeliveryDate(deliveryDate)) {
return jsonResponse({ ok: false, error: "Выберите будущий будний день доставки" }, 400, corsHeaders);
}
@ -147,7 +152,7 @@ Deno.serve(async (request) => {
const { data: currentGroup, error: currentGroupError } = await supabase
.from("order_groups")
.select("id, delivery_status, delivery_invitation_id")
.select("id, delivery_status, delivery_invitation_id, pickup_code")
.eq("id", orderGroupId)
.single();
@ -155,15 +160,29 @@ Deno.serve(async (request) => {
throw currentGroupError;
}
const effectiveDeliveryStatus = deliveryType === "pickup" ? "pickup" : "agreed";
const updateData: Record<string, unknown> = {
delivery_status: effectiveDeliveryStatus,
delivery_date: deliveryDate || null,
delivery_time: deliveryTime || null,
delivery_type: deliveryType,
notification_status: "confirmed",
updated_at: new Date().toISOString(),
};
if (deliveryType === "pickup") {
updateData.pickup_date = body.pickupDate || deliveryDate || null;
updateData.pickup_time_slot = body.pickupTimeSlot || deliveryTime || null;
updateData.assigned_driver_id = null;
} else {
updateData.pickup_date = null;
updateData.pickup_time_slot = null;
}
const { data: group, error: groupUpdateError } = await supabase
.from("order_groups")
.update({
delivery_status: "agreed",
delivery_date: deliveryDate,
delivery_time: deliveryTime,
notification_status: "confirmed",
updated_at: new Date().toISOString(),
})
.update(updateData)
.eq("id", orderGroupId)
.select("*")
.single();
@ -198,7 +217,8 @@ Deno.serve(async (request) => {
actor_user_id: actor.userId,
actor_role: actor.role,
old_delivery_status: currentGroup.delivery_status || null,
new_delivery_status: "agreed",
new_delivery_status: effectiveDeliveryStatus,
delivery_type: deliveryType,
delivery_date: deliveryDate,
delivery_time: deliveryTime,
},