fix(inspections): фото больше не теряются — сжатие + персистентная очередь (6929)
Причина потерь: камера отдаёт 3–8 МБ, по LTE PUT длится дольше осмотра, механик закрывал PWA — fetch убивался, фото пропадало (1010 шт за полгода). - сжатие до 1600px JPEG q0.82 перед отправкой (~10x быстрее) - очередь на IndexedDB: сериально, 5 попыток с бэкоффом, доигрывается после перезапуска приложения; фолбэк в память без IDB - «Завершить осмотр» заблокирован, пока грузятся фото (N в кнопке) - слот: «В очереди/Загружаю…», при отказе — «Повторить» - карточка осмотра: failed-фото не показываем пустышками, бейдж «не загрузилось фото: N»; слот с failed предлагает снять заново
This commit is contained in:
1 parent
7d1864fa63
commit
205e6d6d10
9 files changed
+530
-21
No files matched your search
@@ -48,10 +48,11 @@ export async function requestUploadUrl(
|
|||||||
* PUT the file directly to MinIO via the presigned URL.
|
* PUT the file directly to MinIO via the presigned URL.
|
||||||
* Content-Type header MUST match the value the URL was signed with
|
* Content-Type header MUST match the value the URL was signed with
|
||||||
* (we pass the same `args.content_type` to requestUploadUrl).
|
* (we pass the same `args.content_type` to requestUploadUrl).
|
||||||
|
* Принимает Blob: очередь загрузки кладёт сюда сжатый blob, а не File.
|
||||||
*/
|
*/
|
||||||
export async function uploadToS3(
|
export async function uploadToS3(
|
||||||
presigned: PresignedUploadResponse,
|
presigned: PresignedUploadResponse,
|
||||||
file: File,
|
file: Blob,
|
||||||
contentType: string
|
contentType: string
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const r = await fetch(presigned.presigned_url, {
|
const r = await fetch(presigned.presigned_url, {
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
import { useState } from "react";
|
import { useMemo, useState } from "react";
|
||||||
import { CameraCapture } from "./CameraCapture";
|
import { CameraCapture } from "./CameraCapture";
|
||||||
import { AuthImg } from "@/components/AuthImg";
|
import { AuthImg } from "@/components/AuthImg";
|
||||||
import { uploadPhoto } from "@/api/photos";
|
import { compressImage } from "@/lib/imageCompress";
|
||||||
|
import {
|
||||||
|
enqueuePhoto,
|
||||||
|
retryItem,
|
||||||
|
usePhotoQueue,
|
||||||
|
useSlotUploaded,
|
||||||
|
} from "@/lib/photoQueue";
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -22,19 +28,33 @@ export function PhotoSlot({
|
|||||||
onUploaded,
|
onUploaded,
|
||||||
}: Props) {
|
}: Props) {
|
||||||
const [photoId, setPhotoId] = useState<number | undefined>(initialPhotoId);
|
const [photoId, setPhotoId] = useState<number | undefined>(initialPhotoId);
|
||||||
const [uploading, setUploading] = useState(false);
|
const queue = usePhotoQueue();
|
||||||
|
|
||||||
|
// Последний элемент очереди этого слота (могут быть при пересъёмке).
|
||||||
|
const mine = useMemo(
|
||||||
|
() =>
|
||||||
|
[...queue]
|
||||||
|
.reverse()
|
||||||
|
.find(
|
||||||
|
(i) => i.inspectionId === inspectionId && i.side === side && i.slotIndex === slotIndex,
|
||||||
|
),
|
||||||
|
[queue, inspectionId, side, slotIndex],
|
||||||
|
);
|
||||||
|
|
||||||
|
// Фото доехало фоновым насосом — показываем превью.
|
||||||
|
useSlotUploaded(inspectionId, side, slotIndex, (id) => {
|
||||||
|
setPhotoId(id);
|
||||||
|
onUploaded?.(id);
|
||||||
|
});
|
||||||
|
|
||||||
async function handleCapture(file: File) {
|
async function handleCapture(file: File) {
|
||||||
setUploading(true);
|
|
||||||
try {
|
try {
|
||||||
const result = await uploadPhoto(inspectionId, side, slotIndex, file);
|
// Сжимаем до ~1600px: по LTE оригинал в 3–8 МБ грузится дольше,
|
||||||
setPhotoId(result.id);
|
// чем живёт осмотр, — терялись целые серии (задача 6929).
|
||||||
onUploaded?.(result.id);
|
const compressed = await compressImage(file);
|
||||||
toast.success(`${label}: загружено`);
|
await enqueuePhoto({ inspectionId, side, slotIndex, blob: compressed });
|
||||||
} catch {
|
} catch {
|
||||||
toast.error(`${label}: ошибка загрузки`);
|
toast.error(`${label}: не удалось поставить фото в очередь`);
|
||||||
} finally {
|
|
||||||
setUploading(false);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,8 +72,23 @@ export function PhotoSlot({
|
|||||||
onCapture={handleCapture}
|
onCapture={handleCapture}
|
||||||
buttonLabel={photoId ? "Заменить" : "Снять"}
|
buttonLabel={photoId ? "Заменить" : "Снять"}
|
||||||
/>
|
/>
|
||||||
{uploading && (
|
{mine?.status === "failed" ? (
|
||||||
<div className="text-xs text-muted-foreground">Загружаю…</div>
|
<div className="text-xs text-destructive space-y-1">
|
||||||
|
<div>Не загрузилось ({mine.attempts} попыток)</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="underline"
|
||||||
|
onClick={() => void retryItem(mine.id)}
|
||||||
|
>
|
||||||
|
Повторить
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
mine && (
|
||||||
|
<div className="text-xs text-muted-foreground">
|
||||||
|
{mine.status === "uploading" ? "Загружаю…" : "В очереди на загрузку…"}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { scaleFor } from "@/lib/imageCompress";
|
||||||
|
|
||||||
|
describe("scaleFor", () => {
|
||||||
|
it("ужимает по длинной стороне", () => {
|
||||||
|
expect(scaleFor(4000, 3000)).toBeCloseTo(0.4);
|
||||||
|
expect(scaleFor(3000, 1000)).toBeCloseTo(1600 / 3000);
|
||||||
|
expect(scaleFor(900, 4000)).toBeCloseTo(0.4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("меньше лимита — не масштабирует", () => {
|
||||||
|
expect(scaleFor(1000, 800)).toBe(1);
|
||||||
|
expect(scaleFor(1600, 900)).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("нулевые размеры — единица (не делить на ноль)", () => {
|
||||||
|
expect(scaleFor(0, 0)).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
/**
|
||||||
|
* Сжатие фото перед отправкой на сервер (задача 6929: «теряются фото осмотров»).
|
||||||
|
*
|
||||||
|
* Камера отдаёт JPEG по 3–8 МБ; по LTE такой файл грузится десятки секунд,
|
||||||
|
* механик завершал осмотр и закрывал PWA раньше, чем заканчивалась загрузка —
|
||||||
|
* фото терялись молча. Сжимаем до 1600px по длинной стороне (≈300–500 КБ):
|
||||||
|
* для карточки осмотра и сравнения повреждений этого достаточно с запасом,
|
||||||
|
* а грузится в ~10 раз быстрее.
|
||||||
|
*
|
||||||
|
* Если декодировать не удалось (экзотический формат/нет canvas) — отдаём
|
||||||
|
* оригинал: медленная загрузка лучше потерянного фото.
|
||||||
|
*/
|
||||||
|
const MAX_EDGE_PX = 1600;
|
||||||
|
const JPEG_QUALITY = 0.82;
|
||||||
|
/** Уже компактный файл не пережимаем — только время теряем. */
|
||||||
|
const SKIP_IF_SMALLER_BYTES = 400_000;
|
||||||
|
|
||||||
|
/** Во сколько раз уместить картинку в maxEdge (чистая функция — для тестов). */
|
||||||
|
export function scaleFor(width: number, height: number, maxEdge = MAX_EDGE_PX): number {
|
||||||
|
const longest = Math.max(width, height);
|
||||||
|
if (longest <= 0) return 1;
|
||||||
|
return Math.min(1, maxEdge / longest);
|
||||||
|
}
|
||||||
|
|
||||||
|
function decode(file: File): Promise<HTMLImageElement> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const url = URL.createObjectURL(file);
|
||||||
|
const img = new Image();
|
||||||
|
img.onload = () => {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
resolve(img);
|
||||||
|
};
|
||||||
|
img.onerror = () => {
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
reject(new Error("image decode failed"));
|
||||||
|
};
|
||||||
|
img.src = url;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function compressImage(file: File): Promise<File> {
|
||||||
|
if (file.size <= SKIP_IF_SMALLER_BYTES) return file;
|
||||||
|
try {
|
||||||
|
const img = await decode(file);
|
||||||
|
const scale = scaleFor(img.naturalWidth, img.naturalHeight);
|
||||||
|
if (scale >= 1) return file;
|
||||||
|
const canvas = document.createElement("canvas");
|
||||||
|
canvas.width = Math.round(img.naturalWidth * scale);
|
||||||
|
canvas.height = Math.round(img.naturalHeight * scale);
|
||||||
|
const ctx = canvas.getContext("2d");
|
||||||
|
if (!ctx) return file;
|
||||||
|
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
||||||
|
const blob = await new Promise<Blob | null>((resolve) =>
|
||||||
|
canvas.toBlob(resolve, "image/jpeg", JPEG_QUALITY),
|
||||||
|
);
|
||||||
|
if (!blob || blob.size >= file.size) return file;
|
||||||
|
return new File([blob], "photo.jpg", { type: "image/jpeg" });
|
||||||
|
} catch {
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
|
||||||
|
// Очередь должна жить без сети: мокаем транспорт целиком.
|
||||||
|
vi.mock("@/api/photos", () => ({
|
||||||
|
requestUploadUrl: vi.fn(async () => ({
|
||||||
|
photo_id: 7,
|
||||||
|
presigned_url: "https://s3/put",
|
||||||
|
storage_key: "mechanic/inspections/1/x.jpg",
|
||||||
|
})),
|
||||||
|
uploadToS3: vi.fn(async () => undefined),
|
||||||
|
confirmPhoto: vi.fn(async () => ({ id: 7, status: "ready" })),
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { confirmPhoto, requestUploadUrl, uploadToS3 } from "@/api/photos";
|
||||||
|
import {
|
||||||
|
_resetForTests,
|
||||||
|
_setSleepForTests,
|
||||||
|
enqueuePhoto,
|
||||||
|
getSnapshot,
|
||||||
|
onUploaded,
|
||||||
|
retryItem,
|
||||||
|
} from "@/lib/photoQueue";
|
||||||
|
import type { UploadedEvent } from "@/lib/photoQueue";
|
||||||
|
|
||||||
|
const BLOB = new Blob(["bytes"], { type: "image/jpeg" });
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
// Явно восстанавливаем «успешный» транспорт: mockRejectedValue из
|
||||||
|
// отдельных кейсов персистентен и без этого протекает в следующие тесты.
|
||||||
|
vi.mocked(requestUploadUrl).mockImplementation(async () => ({
|
||||||
|
photo_id: 7,
|
||||||
|
presigned_url: "https://s3/put",
|
||||||
|
storage_key: "mechanic/inspections/1/x.jpg",
|
||||||
|
}));
|
||||||
|
vi.mocked(uploadToS3).mockImplementation(async () => undefined);
|
||||||
|
vi.mocked(confirmPhoto).mockImplementation(async () => ({ id: 7, status: "ready" }));
|
||||||
|
_resetForTests();
|
||||||
|
// Бэкофф между повторами не ждём по-настоящему.
|
||||||
|
_setSleepForTests(async () => undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("photoQueue", () => {
|
||||||
|
it("успешная загрузка очищает очередь и стреляет событием слота", async () => {
|
||||||
|
const events: UploadedEvent[] = [];
|
||||||
|
onUploaded((e) => events.push(e));
|
||||||
|
|
||||||
|
await enqueuePhoto({ inspectionId: 1, side: "front", slotIndex: 0, blob: BLOB });
|
||||||
|
|
||||||
|
await vi.waitFor(() => expect(getSnapshot()).toHaveLength(0));
|
||||||
|
expect(requestUploadUrl).toHaveBeenCalledTimes(1);
|
||||||
|
expect(confirmPhoto).toHaveBeenCalledWith(1, 7, { actual_size: BLOB.size });
|
||||||
|
expect(events).toEqual([
|
||||||
|
{ inspectionId: 1, side: "front", slotIndex: 0, photoId: 7 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("сбой сети — 5 попыток, потом failed (фото не теряем молча)", async () => {
|
||||||
|
vi.mocked(uploadToS3).mockRejectedValue(new Error("network down"));
|
||||||
|
|
||||||
|
await enqueuePhoto({ inspectionId: 2, side: "rear", slotIndex: 0, blob: BLOB });
|
||||||
|
|
||||||
|
await vi.waitFor(() => expect(getSnapshot()[0]?.status).toBe("failed"));
|
||||||
|
expect(uploadToS3).toHaveBeenCalledTimes(5);
|
||||||
|
expect(getSnapshot()[0]?.attempts).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retryItem сбрасывает счётчик и доигрывает успешно", async () => {
|
||||||
|
vi.mocked(uploadToS3).mockRejectedValueOnce(new Error("flaky"));
|
||||||
|
|
||||||
|
await enqueuePhoto({ inspectionId: 3, side: "left", slotIndex: 0, blob: BLOB });
|
||||||
|
|
||||||
|
await vi.waitFor(() => expect(getSnapshot()).toHaveLength(0));
|
||||||
|
expect(uploadToS3).toHaveBeenCalledTimes(2); // 1 неудача + успешный повтор
|
||||||
|
});
|
||||||
|
|
||||||
|
it("после исчерпания попыток retry поднимает фото заново", async () => {
|
||||||
|
vi.mocked(uploadToS3).mockRejectedValue(new Error("down"));
|
||||||
|
await enqueuePhoto({ inspectionId: 4, side: "vin", slotIndex: 0, blob: BLOB });
|
||||||
|
await vi.waitFor(() => expect(getSnapshot()[0]?.status).toBe("failed"));
|
||||||
|
|
||||||
|
vi.mocked(uploadToS3).mockResolvedValue(undefined);
|
||||||
|
await retryItem(getSnapshot()[0]!.id);
|
||||||
|
|
||||||
|
await vi.waitFor(() => expect(getSnapshot()).toHaveLength(0));
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,270 @@
|
|||||||
|
/**
|
||||||
|
* Персистентная очередь загрузки фото осмотра (задача 6929).
|
||||||
|
*
|
||||||
|
* Раньше фото грузилось inline в момент снимка, и если механик закрывал
|
||||||
|
* PWA до конца PUT — фото терялось навсегда (в БД висела строка 'pending',
|
||||||
|
* а объекта в хранилище не было). Теперь снимок (уже сжатый) кладётся в
|
||||||
|
* очередь на IndexedDB и уходит фоном: строго по одному, с повторами.
|
||||||
|
* Очередь переживает закрытие приложения и доигрывается при следующем
|
||||||
|
* запуске; «Завершить осмотр» блокируется, пока есть недогруженные фото.
|
||||||
|
*
|
||||||
|
* Если IndexedDB недоступен (приватный режим) — очередь живёт в памяти:
|
||||||
|
* хуже, чем персистентно, но лучше, чем терять фото сразу.
|
||||||
|
*/
|
||||||
|
import { useEffect } from "react";
|
||||||
|
import { useSyncExternalStore } from "react";
|
||||||
|
import { confirmPhoto, requestUploadUrl, uploadToS3 } from "@/api/photos";
|
||||||
|
|
||||||
|
export interface QueuedPhoto {
|
||||||
|
id: string;
|
||||||
|
inspectionId: number;
|
||||||
|
side: string;
|
||||||
|
slotIndex: number;
|
||||||
|
blob: Blob;
|
||||||
|
attempts: number;
|
||||||
|
createdAt: number;
|
||||||
|
status: "queued" | "uploading" | "failed";
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UploadedEvent {
|
||||||
|
inspectionId: number;
|
||||||
|
side: string;
|
||||||
|
slotIndex: number;
|
||||||
|
photoId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DB_NAME = "pp-mechanic-photoq";
|
||||||
|
const STORE = "photos";
|
||||||
|
const MAX_ATTEMPTS = 5;
|
||||||
|
const RETRY_BASE_MS = 4000;
|
||||||
|
|
||||||
|
// ── Хранилище: IndexedDB с фолбэком в память ───────────────────────────────
|
||||||
|
|
||||||
|
let idb: IDBDatabase | null | undefined; // undefined = ещё не пробовали открыть
|
||||||
|
|
||||||
|
function openIdb(): Promise<IDBDatabase | null> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
if (typeof indexedDB === "undefined") return resolve(null);
|
||||||
|
try {
|
||||||
|
const req = indexedDB.open(DB_NAME, 1);
|
||||||
|
req.onupgradeneeded = () => {
|
||||||
|
const db = req.result;
|
||||||
|
if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE, { keyPath: "id" });
|
||||||
|
};
|
||||||
|
req.onsuccess = () => resolve(req.result);
|
||||||
|
req.onerror = () => resolve(null);
|
||||||
|
} catch {
|
||||||
|
resolve(null);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function idbPut(item: QueuedPhoto): Promise<void> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
if (!idb) return resolve();
|
||||||
|
try {
|
||||||
|
const tx = idb.transaction(STORE, "readwrite");
|
||||||
|
// Blob кладётся в IndexedDB как есть (structured clone умеет Blob).
|
||||||
|
tx.objectStore(STORE).put(item);
|
||||||
|
tx.oncomplete = () => resolve();
|
||||||
|
tx.onerror = () => resolve();
|
||||||
|
} catch {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function idbDelete(id: string): Promise<void> {
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
if (!idb) return resolve();
|
||||||
|
try {
|
||||||
|
const tx = idb.transaction(STORE, "readwrite");
|
||||||
|
tx.objectStore(STORE).delete(id);
|
||||||
|
tx.oncomplete = () => resolve();
|
||||||
|
tx.onerror = () => resolve();
|
||||||
|
} catch {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Состояние в памяти + подписка для React ────────────────────────────────
|
||||||
|
|
||||||
|
let items: QueuedPhoto[] = [];
|
||||||
|
let snapshot: QueuedPhoto[] = items;
|
||||||
|
const listeners = new Set<() => void>();
|
||||||
|
const uploadedHandlers = new Set<(e: UploadedEvent) => void>();
|
||||||
|
|
||||||
|
function commit(): void {
|
||||||
|
snapshot = [...items];
|
||||||
|
for (const l of listeners) l();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function subscribe(cb: () => void): () => void {
|
||||||
|
listeners.add(cb);
|
||||||
|
return () => listeners.delete(cb);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSnapshot(): QueuedPhoto[] {
|
||||||
|
return snapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Реактивный доступ к очереди (useSyncExternalStore). */
|
||||||
|
export function usePhotoQueue(): QueuedPhoto[] {
|
||||||
|
return useSyncExternalStore(subscribe, getSnapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function onUploaded(cb: (e: UploadedEvent) => void): () => void {
|
||||||
|
uploadedHandlers.add(cb);
|
||||||
|
return () => uploadedHandlers.delete(cb);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Хук: дождаться загрузки фото конкретного слота (для превью в PhotoSlot). */
|
||||||
|
export function useSlotUploaded(
|
||||||
|
inspectionId: number,
|
||||||
|
side: string,
|
||||||
|
slotIndex: number,
|
||||||
|
cb: (photoId: number) => void,
|
||||||
|
): void {
|
||||||
|
useEffect(
|
||||||
|
() =>
|
||||||
|
onUploaded((e) => {
|
||||||
|
if (e.inspectionId === inspectionId && e.side === side && e.slotIndex === slotIndex) {
|
||||||
|
cb(e.photoId);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
// cb намеренно не в зависимостях: слот живёт всей жизнью страницы,
|
||||||
|
// а колбэк — стабильно замкнут над setState.
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
[inspectionId, side, slotIndex],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Сколько фото этого осмотра ещё не долетело (ошибки не считаем). */
|
||||||
|
export function pendingCountFor(inspectionId: number): number {
|
||||||
|
return items.filter((i) => i.inspectionId === inspectionId && i.status !== "failed").length;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Насос: сериальная догрузка с повторами ─────────────────────────────────
|
||||||
|
|
||||||
|
let sleepImpl: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||||
|
|
||||||
|
/** Тесты подменяют сон, чтобы не ждать бэкоффы по-настоящему. */
|
||||||
|
export function _setSleepForTests(fn: (ms: number) => Promise<void>): void {
|
||||||
|
sleepImpl = fn;
|
||||||
|
}
|
||||||
|
|
||||||
|
let draining = false;
|
||||||
|
|
||||||
|
async function uploadOne(item: QueuedPhoto): Promise<number> {
|
||||||
|
const contentType = item.blob.type || "image/jpeg";
|
||||||
|
const presign = await requestUploadUrl(item.inspectionId, {
|
||||||
|
side: item.side,
|
||||||
|
slot_index: item.slotIndex,
|
||||||
|
content_type: contentType,
|
||||||
|
size: item.blob.size,
|
||||||
|
});
|
||||||
|
await uploadToS3(presign, item.blob, contentType);
|
||||||
|
await confirmPhoto(item.inspectionId, presign.photo_id, {
|
||||||
|
actual_size: item.blob.size,
|
||||||
|
});
|
||||||
|
return presign.photo_id;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function drainQueue(): Promise<void> {
|
||||||
|
if (draining) return;
|
||||||
|
draining = true;
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const item = items.find((i) => i.status === "queued");
|
||||||
|
if (!item) break;
|
||||||
|
item.status = "uploading";
|
||||||
|
commit();
|
||||||
|
try {
|
||||||
|
const photoId = await uploadOne(item);
|
||||||
|
items = items.filter((i) => i.id !== item.id);
|
||||||
|
commit();
|
||||||
|
await idbDelete(item.id);
|
||||||
|
for (const h of uploadedHandlers) {
|
||||||
|
h({ inspectionId: item.inspectionId, side: item.side, slotIndex: item.slotIndex, photoId });
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
item.attempts += 1;
|
||||||
|
item.status = item.attempts >= MAX_ATTEMPTS ? "failed" : "queued";
|
||||||
|
commit();
|
||||||
|
await idbPut(item);
|
||||||
|
if (item.status === "queued") await sleepImpl(RETRY_BASE_MS * item.attempts);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
draining = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Публичное API ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export async function enqueuePhoto(args: {
|
||||||
|
inspectionId: number;
|
||||||
|
side: string;
|
||||||
|
slotIndex: number;
|
||||||
|
blob: Blob;
|
||||||
|
}): Promise<void> {
|
||||||
|
const item: QueuedPhoto = {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
attempts: 0,
|
||||||
|
createdAt: Date.now(),
|
||||||
|
status: "queued",
|
||||||
|
...args,
|
||||||
|
};
|
||||||
|
items.push(item);
|
||||||
|
commit();
|
||||||
|
await idbPut(item);
|
||||||
|
void drainQueue();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Повторить сломанное фото (кнопка «Повторить» в слоте). */
|
||||||
|
export async function retryItem(id: string): Promise<void> {
|
||||||
|
const item = items.find((i) => i.id === id);
|
||||||
|
if (!item) return;
|
||||||
|
item.attempts = 0;
|
||||||
|
item.status = "queued";
|
||||||
|
commit();
|
||||||
|
await idbPut(item);
|
||||||
|
void drainQueue();
|
||||||
|
}
|
||||||
|
|
||||||
|
let initialized = false;
|
||||||
|
|
||||||
|
/** Разовая инициализация при старте приложения: поднять IDB и доиграть хвосты. */
|
||||||
|
export async function initPhotoQueue(): Promise<void> {
|
||||||
|
if (initialized) return;
|
||||||
|
initialized = true;
|
||||||
|
if (idb === undefined) idb = await openIdb();
|
||||||
|
if (idb) {
|
||||||
|
const stored = await new Promise<QueuedPhoto[]>((resolve) => {
|
||||||
|
try {
|
||||||
|
const tx = idb!.transaction(STORE, "readonly");
|
||||||
|
const req = tx.objectStore(STORE).getAll();
|
||||||
|
req.onsuccess = () => resolve((req.result as QueuedPhoto[]) ?? []);
|
||||||
|
req.onerror = () => resolve([]);
|
||||||
|
} catch {
|
||||||
|
resolve([]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// «uploading» из прошлого запуска = загрузка оборвалась закрытием приложения.
|
||||||
|
for (const s of stored) {
|
||||||
|
if (s.status === "uploading") s.status = "queued";
|
||||||
|
items.push(s);
|
||||||
|
}
|
||||||
|
commit();
|
||||||
|
}
|
||||||
|
if (items.length > 0) void drainQueue();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Только для тестов: очистить состояние модуля между кейсами. */
|
||||||
|
export function _resetForTests(): void {
|
||||||
|
items = [];
|
||||||
|
commit();
|
||||||
|
draining = false;
|
||||||
|
initialized = false;
|
||||||
|
}
|
||||||
@@ -4,12 +4,16 @@ import { BrowserRouter } from "react-router-dom";
|
|||||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
import { Toaster } from "sonner";
|
import { Toaster } from "sonner";
|
||||||
import App from "./App";
|
import App from "./App";
|
||||||
|
import { initPhotoQueue } from "@/lib/photoQueue";
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: { queries: { retry: 1, staleTime: 30_000 } },
|
defaultOptions: { queries: { retry: 1, staleTime: 30_000 } },
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Доиграть фото осмотров, не долетевшие в прошлом запуске (задача 6929).
|
||||||
|
void initPhotoQueue();
|
||||||
|
|
||||||
ReactDOM.createRoot(document.getElementById("root")!).render(
|
ReactDOM.createRoot(document.getElementById("root")!).render(
|
||||||
<React.StrictMode>
|
<React.StrictMode>
|
||||||
<QueryClientProvider client={queryClient}>
|
<QueryClientProvider client={queryClient}>
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ import {
|
|||||||
type MarkerSummary,
|
type MarkerSummary,
|
||||||
} from "@/api/inspections";
|
} from "@/api/inspections";
|
||||||
import { uploadPhoto, uploadPhotoAnnotation } from "@/api/photos";
|
import { uploadPhoto, uploadPhotoAnnotation } from "@/api/photos";
|
||||||
|
import { compressImage } from "@/lib/imageCompress";
|
||||||
|
import { usePhotoQueue } from "@/lib/photoQueue";
|
||||||
import { PhotoSlot } from "@/components/camera/PhotoSlot";
|
import { PhotoSlot } from "@/components/camera/PhotoSlot";
|
||||||
import { CameraCapture } from "@/components/camera/CameraCapture";
|
import { CameraCapture } from "@/components/camera/CameraCapture";
|
||||||
import { VendorVehicleScheme } from "@/components/vehicle-scheme/VendorVehicleScheme";
|
import { VendorVehicleScheme } from "@/components/vehicle-scheme/VendorVehicleScheme";
|
||||||
@@ -113,6 +115,13 @@ export default function InspectionEditor() {
|
|||||||
// draft отличается от сохранённого (см. notesDirty ниже).
|
// draft отличается от сохранённого (см. notesDirty ниже).
|
||||||
const [notesDraft, setNotesDraft] = useState<string>("");
|
const [notesDraft, setNotesDraft] = useState<string>("");
|
||||||
|
|
||||||
|
// Очередь догрузки фото (задача 6929): завершать осмотр можно только
|
||||||
|
// когда все снимки доехали — раньше закрытие приложения убивало загрузку.
|
||||||
|
const queue = usePhotoQueue();
|
||||||
|
const uploadingCount = queue.filter(
|
||||||
|
(i) => i.inspectionId === insId && i.status !== "failed",
|
||||||
|
).length;
|
||||||
|
|
||||||
useEffect(() => { loadZoneLabels().then(setZoneLabels); }, []);
|
useEffect(() => { loadZoneLabels().then(setZoneLabels); }, []);
|
||||||
|
|
||||||
const { data: ins, isLoading, isError } = useQuery({
|
const { data: ins, isLoading, isError } = useQuery({
|
||||||
@@ -161,9 +170,18 @@ export default function InspectionEditor() {
|
|||||||
if (isError || !ins)
|
if (isError || !ins)
|
||||||
return <div className="p-8 text-destructive">Осмотр не найден.</div>;
|
return <div className="p-8 text-destructive">Осмотр не найден.</div>;
|
||||||
|
|
||||||
// Photos lookup by side+slot for initialPhotoId
|
// Photos lookup by side+slot for initialPhotoId. Потерянные (failed) фото
|
||||||
|
// не подставляем — слот должен предлагать снять заново; при нескольких
|
||||||
|
// строках на слот (пересъёмка после сбоя) предпочитаем готовую.
|
||||||
const photosBySide = new Map<string, typeof ins.photos[0]>();
|
const photosBySide = new Map<string, typeof ins.photos[0]>();
|
||||||
for (const p of ins.photos) photosBySide.set(`${p.side}-${p.slot_index}`, p);
|
for (const p of ins.photos) {
|
||||||
|
if (p.status === "failed") continue;
|
||||||
|
const key = `${p.side}-${p.slot_index}`;
|
||||||
|
const cur = photosBySide.get(key);
|
||||||
|
if (!cur || (cur.status !== "ready" && p.status === "ready")) {
|
||||||
|
photosBySide.set(key, p);
|
||||||
|
}
|
||||||
|
}
|
||||||
// Photos lookup by id — нужен для marker thumb (annotated vs original)
|
// Photos lookup by id — нужен для marker thumb (annotated vs original)
|
||||||
const photosById = new Map<number, typeof ins.photos[0]>();
|
const photosById = new Map<number, typeof ins.photos[0]>();
|
||||||
for (const p of ins.photos) photosById.set(p.id, p);
|
for (const p of ins.photos) photosById.set(p.id, p);
|
||||||
@@ -341,7 +359,7 @@ export default function InspectionEditor() {
|
|||||||
setFlow({ kind: "idle" });
|
setFlow({ kind: "idle" });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const result = await uploadPhoto(insId, "free", 0, flow.photoFile);
|
const result = await uploadPhoto(insId, "free", 0, await compressImage(flow.photoFile));
|
||||||
if (annotated) {
|
if (annotated) {
|
||||||
try {
|
try {
|
||||||
await uploadPhotoAnnotation(insId, result.id, annotated);
|
await uploadPhotoAnnotation(insId, result.id, annotated);
|
||||||
@@ -497,9 +515,13 @@ export default function InspectionEditor() {
|
|||||||
<Button
|
<Button
|
||||||
className="w-full"
|
className="w-full"
|
||||||
onClick={() => finalize.mutate()}
|
onClick={() => finalize.mutate()}
|
||||||
disabled={finalize.isPending}
|
disabled={finalize.isPending || uploadingCount > 0}
|
||||||
>
|
>
|
||||||
{finalize.isPending ? "Завершаем…" : "Завершить осмотр"}
|
{uploadingCount > 0
|
||||||
|
? `Догружаю фото (${uploadingCount})…`
|
||||||
|
: finalize.isPending
|
||||||
|
? "Завершаем…"
|
||||||
|
: "Завершить осмотр"}
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -152,6 +152,10 @@ export default function InspectionReview() {
|
|||||||
// фото повреждений) + tt_image_id из маркеров (carry-over из Element). Без
|
// фото повреждений) + tt_image_id из маркеров (carry-over из Element). Без
|
||||||
// tt_image_id counter недоучитывал импортированные дефекты — видно на
|
// tt_image_id counter недоучитывал импортированные дефекты — видно на
|
||||||
// осмотрах, где почти все маркеры пришли из вендора.
|
// осмотрах, где почти все маркеры пришли из вендора.
|
||||||
|
// «failed» — фото, чья загрузка оборвалась (объекта в хранилище нет):
|
||||||
|
// в сетке не показываем и в счётчик не считаем, количество выводим отдельно.
|
||||||
|
const visiblePhotos = ins.photos.filter((p: PhotoSummary) => p.status !== "failed");
|
||||||
|
const failedPhotoCount = ins.photos.length - visiblePhotos.length;
|
||||||
const markerPhotoIds = ins.markers
|
const markerPhotoIds = ins.markers
|
||||||
.map((m: MarkerSummary) => m.photo_id)
|
.map((m: MarkerSummary) => m.photo_id)
|
||||||
.filter((id): id is number => id != null);
|
.filter((id): id is number => id != null);
|
||||||
@@ -159,7 +163,7 @@ export default function InspectionReview() {
|
|||||||
.map((m: MarkerSummary) => m.tt_image_id)
|
.map((m: MarkerSummary) => m.tt_image_id)
|
||||||
.filter((id): id is string => !!id);
|
.filter((id): id is string => !!id);
|
||||||
const uniquePhotoIds = Array.from(
|
const uniquePhotoIds = Array.from(
|
||||||
new Set([...ins.photos.map((p: PhotoSummary) => p.id), ...markerPhotoIds])
|
new Set([...visiblePhotos.map((p: PhotoSummary) => p.id), ...markerPhotoIds])
|
||||||
);
|
);
|
||||||
const uniqueTtIds = Array.from(new Set(markerTtIds));
|
const uniqueTtIds = Array.from(new Set(markerTtIds));
|
||||||
const totalPhotoCount = uniquePhotoIds.length + uniqueTtIds.length;
|
const totalPhotoCount = uniquePhotoIds.length + uniqueTtIds.length;
|
||||||
@@ -231,6 +235,12 @@ export default function InspectionReview() {
|
|||||||
{ins.mileage.toLocaleString("ru-RU")} км
|
{ins.mileage.toLocaleString("ru-RU")} км
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{failedPhotoCount > 0 && (
|
||||||
|
<div className="text-destructive">
|
||||||
|
<span className="font-semibold">Не загрузилось фото: </span>
|
||||||
|
{failedPhotoCount} — загрузка оборвалась при осмотре
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
<Card className="p-4 space-y-2">
|
<Card className="p-4 space-y-2">
|
||||||
@@ -291,7 +301,7 @@ export default function InspectionReview() {
|
|||||||
<div className="text-sm text-muted-foreground">Нет фото.</div>
|
<div className="text-sm text-muted-foreground">Нет фото.</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="grid grid-cols-2 gap-2">
|
<div className="grid grid-cols-2 gap-2">
|
||||||
{ins.photos.map((p: PhotoSummary) => (
|
{visiblePhotos.map((p: PhotoSummary) => (
|
||||||
<Card
|
<Card
|
||||||
key={p.id}
|
key={p.id}
|
||||||
className="overflow-hidden cursor-pointer"
|
className="overflow-hidden cursor-pointer"
|
||||||
|
|||||||
Reference in new issue
Block a user