add more documents format support

This commit is contained in:
2026-09-15 08:46:16 +03:00
parent 5608a800dc
commit a44ff63353
4 changed files with 615 additions and 487 deletions

View File

@ -3,12 +3,23 @@
/** /**
* Определение типа файла * Определение типа файла
* @param {File} file * @param {File} file
* @returns {'image' | 'pdf' | 'other'} * @returns {'image' | 'pdf' | 'office' | 'other'}
*/ */
export function detectFileType(file) { export function detectFileType(file) {
if (!file) return 'other'; if (!file) return 'other';
if (file.type.startsWith('image/')) return 'image'; if (file.type.startsWith('image/')) return 'image';
if (file.type === 'application/pdf') return 'pdf'; if (file.type === 'application/pdf') return 'pdf';
// Офисные документы — определяем по расширению,
// т.к. MIME может быть пустым или некорректным
const ext = (file.name || '').toLowerCase().split('.').pop() || '';
const officeExts = [
'doc', 'docx', 'odt', // текст
'xls', 'xlsx', 'ods', // таблицы
'ppt', 'pptx', 'odp', // презентации (на всякий случай)
];
if (officeExts.includes(ext)) return 'office';
return 'other'; return 'other';
} }

View File

@ -73,7 +73,15 @@
plCopies={plCopies} plCopies={plCopies}
/> />
<input type="file" bind:this={fileInput} accept="image/*,.pdf" multiple onchange={handleFileSelect} hidden /> <!-- ✅ Расширенный accept -->
<input
type="file"
bind:this={fileInput}
accept="image/*,.pdf,.doc,.docx,.odt,.xls,.xlsx,.ods,.ppt,.pptx,.odp"
multiple
onchange={handleFileSelect}
hidden
/>
</div> </div>
{/if} {/if}

View File

@ -16,9 +16,7 @@
/** @type {'button' | 'icon-button' | 'counter' | 'toggle-group' | 'file-card' | 'upload-zone' | 'footer'} */ /** @type {'button' | 'icon-button' | 'counter' | 'toggle-group' | 'file-card' | 'upload-zone' | 'footer'} */
let { as, ...props } = $props(); let { as, ...props } = $props();
// локально на экземпляр карточки файла
let formatOpen = $state(false); let formatOpen = $state(false);
$effect(() => { $effect(() => {
if (!props.file?.expanded) formatOpen = false; if (!props.file?.expanded) formatOpen = false;
}); });
@ -33,6 +31,11 @@
if (!file.format || file.format === 'Авто') return `Авто (${file.autoFormat ?? 'A4'})`; if (!file.format || file.format === 'Авто') return `Авто (${file.autoFormat ?? 'A4'})`;
return file.format; return file.format;
} }
/** Является ли файл офисным документом */
function isOffice(file) {
return file?.fileType === 'office';
}
</script> </script>
{#if as === 'button'} {#if as === 'button'}
@ -83,18 +86,63 @@
<section class="file-card" class:expanded={file.expanded}> <section class="file-card" class:expanded={file.expanded}>
<div class="file-row" onclick={() => props.onToggle?.(file.id)}> <div class="file-row" onclick={() => props.onToggle?.(file.id)}>
<span class="chevron">{file.expanded ? '▼' : '►'}</span> <span class="chevron">{file.expanded ? '▼' : '►'}</span>
<!-- Бейдж типа файла -->
{#if isOffice(file)}
<span class="type-badge">
{file.file.name.split('.').pop()?.toUpperCase() ?? 'DOC'}
</span>
{/if}
<span class="file-name" title={file.file.name}>{file.file.name}</span> <span class="file-name" title={file.file.name}>{file.file.name}</span>
<span class="file-row-actions" onclick={(e) => e.stopPropagation()}> <span class="file-row-actions" onclick={(e) => e.stopPropagation()}>
{#if file.previewUrl} <!-- Превью только для image/pdf -->
{#if file.previewUrl && !isOffice(file)}
<svelte:self as="icon-button" onclick={() => props.onPreview?.(file)} title="Предпросмотр">🔍</svelte:self> <svelte:self as="icon-button" onclick={() => props.onPreview?.(file)} title="Предпросмотр">🔍</svelte:self>
{/if} {/if}
<svelte:self as="icon-button" variant="danger" onclick={() => props.onRemove?.(file.id)} title="Удалить"></svelte:self> <svelte:self as="icon-button" variant="danger" onclick={() => props.onRemove?.(file.id)} title="Удалить"></svelte:self>
</span> </span>
</div> </div>
{#if file.expanded} {#if file.expanded}
<div class="file-options"> <div class="file-options">
<!-- 1. Кнопки с настройками -->
<!-- 2. Переключатели — сразу под кнопками настроек --> {#if isOffice(file)}
<!-- ═══ Офисный документ: упрощённые настройки ═══ -->
<p class="office-hint">
Документ будет распечатан как есть — конвертация выполняется на сервере.
</p>
<div class="duo-group">
<div class="duo-row">
<ToggleOption
label="Печать"
options={SIDES_OPTIONS}
value={file.sides ?? 'Односторонняя'}
onchange={(v) => props.onUpdate?.(file.id, { sides: v })}
/>
<ToggleOption
label="Цветность"
options={COLOR_LABELS}
value={COLOR_LABELS[Math.max(0, COLOR_MODES.findIndex((c) => c.id === file.colorMode))]}
onchange={(v, i) => props.onUpdate?.(file.id, { colorMode: COLOR_MODES[i]?.id })}
/>
</div>
</div>
<div class="slider-options">
<SliderOption
label="Качество"
options={QUALITY_LABELS}
hint="Качество печати: влияет на расход тонера и время прогрева."
value={QUALITIES[file.qualityIndex]?.label ?? QUALITY_LABELS[1] ?? QUALITY_LABELS[0]}
onchange={(v) => props.onUpdate?.(file.id, { qualityIndex: QUALITY_LABELS.indexOf(v) })}
/>
</div>
{:else}
<!-- ═══ Image / PDF: полные настройки ═══ -->
<div class="duo-group"> <div class="duo-group">
<div class="duo-row"> <div class="duo-row">
<GearOption value={pagesText(file)} onclick={() => props.onPageSelect?.(file)} /> <GearOption value={pagesText(file)} onclick={() => props.onPageSelect?.(file)} />
@ -116,7 +164,6 @@
</div> </div>
</div> </div>
<!-- 3. Ползунки — ниже -->
<div class="slider-options"> <div class="slider-options">
<SliderOption <SliderOption
label="Качество" label="Качество"
@ -133,8 +180,9 @@
onchange={(v) => props.onUpdate?.(file.id, { dpi: v })} onchange={(v) => props.onUpdate?.(file.id, { dpi: v })}
/> />
</div> </div>
{/if}
<!-- 4. Количество — в конце --> <!-- Количество копий — для всех типов -->
<div class="copies-row"> <div class="copies-row">
<label class="option-title compact">Кол-во:</label> <label class="option-title compact">Кол-во:</label>
<svelte:self <svelte:self
@ -147,6 +195,8 @@
</div> </div>
</div> </div>
<!-- FormatPicker только для image/pdf -->
{#if !isOffice(file)}
<FormatPicker <FormatPicker
bind:open={formatOpen} bind:open={formatOpen}
options={FORMAT_OPTIONS} options={FORMAT_OPTIONS}
@ -154,6 +204,7 @@
onselect={(v) => props.onUpdate?.(file.id, { format: v })} onselect={(v) => props.onUpdate?.(file.id, { format: v })}
/> />
{/if} {/if}
{/if}
</section> </section>
{:else if as === 'upload-zone'} {:else if as === 'upload-zone'}
@ -227,4 +278,31 @@
.price-summary { display: flex; justify-content: space-between; align-items: baseline; width: 100%; } .price-summary { display: flex; justify-content: space-between; align-items: baseline; width: 100%; }
.summary-itogo { font-size: 30px; font-weight: 700; color: #8b93a1; } .summary-itogo { font-size: 30px; font-weight: 700; color: #8b93a1; }
.summary-price { font-size: 38px; font-weight: 800; color: #fff; } .summary-price { font-size: 38px; font-weight: 800; color: #fff; }
/* ── Бейдж типа файла (DOC, XLS, ODT…) ── */
.type-badge {
flex-shrink: 0;
padding: 3px 7px;
border-radius: 6px;
background: rgba(99, 102, 241, 0.2);
border: 1px solid rgba(99, 102, 241, 0.35);
color: #a5b4fc;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.04em;
line-height: 1.2;
user-select: none;
}
/* ── Подсказка для офисных файлов ── */
.office-hint {
margin: 0;
padding: 10px 12px;
border-radius: 10px;
background: rgba(251, 191, 36, 0.08);
border: 1px solid rgba(251, 191, 36, 0.2);
color: #d4a94e;
font-size: 13px;
line-height: 1.5;
}
</style> </style>

View File

@ -1,25 +1,30 @@
// lib/pages/print/store.svelte.js // lib/pages/print/store.svelte.js
import { onDestroy, tick } from 'svelte'; import { onDestroy, tick } from 'svelte';
import { getPricePerPage } from '$lib/common/utils/pricing.util.js'; import { getPricePerPage } from '$lib/common/utils/pricing.util.js';
import { detectFileType, pagesLabel as _pagesLabel } from '$lib/common/utils/file.util.js'; import { detectFileType, pagesLabel as _pagesLabel } from '$lib/common/utils/file.util.js';
import { loadPdfDocument, renderPageToImage } from '$lib/common/services/pdf.service.js'; import { loadPdfDocument, renderPageToImage } from '$lib/common/services/pdf.service.js';
/** /**
* @typedef {{ id: number, file: File, previewUrl: string | null, fileType: 'image' | 'pdf' | 'other', expanded: boolean, format: 'A4' | 'A5', colorMode: 'bw' | 'color', qualityIndex: number, copies: number, totalPages: number, selectedPages: Set<number>, pdfDoc: any }} FileEntry * @typedef {{
* id: number, file: File, previewUrl: string | null,
* fileType: 'image' | 'pdf' | 'office' | 'other',
* expanded: boolean, format: string, colorMode: string,
* qualityIndex: number, copies: number, sides: string,
* dpi: string, totalPages: number,
* selectedPages: Set<number>, pdfDoc: any
* }} FileEntry
*/ */
export function createPrintStore() { export function createPrintStore() {
let files = $state(/** @type {FileEntry[]} */ ([])); let files = $state(/** @type {FileEntry[]} */ ([]));
let activeFile = $state(/** @type {FileEntry | null} */ (null)); let activeFile = $state(/** @type {FileEntry | null} */ (null));
let viewMode = $state(/** @type {'gallery' | 'preview'} */ ('gallery')); let viewMode = $state(/** @type {'gallery' | 'preview'} */ ('gallery'));
let showPayment = $state(false); let showPayment = $state(false);
let isPrinting = $state(false); let isPrinting = $state(false);
let galleryThumbnails = $state([]); let galleryThumbnails = $state([]);
let galleryLoading = $state(false); let galleryLoading = $state(false);
let previewPagesCache = $state({}); let previewPagesCache = $state({});
let isPreviewRendering = $state(false); let isPreviewRendering = $state(false);
let uid = 0; let uid = 0;
const totalPrice = $derived( const totalPrice = $derived(
@ -57,27 +62,38 @@ export function createPrintStore() {
async function addFiles(fileList) { async function addFiles(fileList) {
if (!fileList || fileList.length === 0) return; if (!fileList || fileList.length === 0) return;
const newFiles = []; const newFiles = [];
for (let i = 0; i < fileList.length; i++) { for (let i = 0; i < fileList.length; i++) {
const file = fileList[i]; const file = fileList[i];
const fType = detectFileType(file); const fType = detectFileType(file);
const isOffice = fType === 'office';
newFiles.push({ newFiles.push({
id: ++uid, id: ++uid,
file, file,
previewUrl: URL.createObjectURL(file), // Для офисных файлов превью не создаём
previewUrl: isOffice ? null : URL.createObjectURL(file),
fileType: fType, fileType: fType,
expanded: false, expanded: false,
format: 'A4', format: 'Авто',
colorMode: 'bw', colorMode: 'bw',
qualityIndex: 1, qualityIndex: 1,
copies: 1, copies: 1,
totalPages: fType === 'image' ? 1 : 0, sides: 'Односторонняя',
selectedPages: fType === 'image' ? new Set([1]) : new Set(), dpi: 'Авто',
// Для офисных файлов: 1 «страница» для расчёта цены,
// реальное кол-во определит CUPS
totalPages: (fType === 'image' || isOffice) ? 1 : 0,
selectedPages: (fType === 'image' || isOffice) ? new Set([1]) : new Set(),
pdfDoc: null pdfDoc: null
}); });
} }
files = [...files, ...newFiles]; files = [...files, ...newFiles];
for (const entry of newFiles) { for (const entry of newFiles) {
if (entry.fileType === 'pdf') ensurePdfLoaded(entry); if (entry.fileType === 'pdf') ensurePdfLoaded(entry);
// office и image — ничего дополнительно не загружаем
} }
} }
@ -123,6 +139,7 @@ export function createPrintStore() {
previewPagesCache = {}; previewPagesCache = {};
galleryThumbnails = []; galleryThumbnails = [];
await tick(); await tick();
if (entry.fileType === 'pdf') { if (entry.fileType === 'pdf') {
const pdf = await ensurePdfLoaded(entry); const pdf = await ensurePdfLoaded(entry);
if (pdf && entry.totalPages > 0) { if (pdf && entry.totalPages > 0) {
@ -181,20 +198,35 @@ export function createPrintStore() {
async function submitPrint() { async function submitPrint() {
if (files.length === 0 || isPrinting) return; if (files.length === 0 || isPrinting) return;
isPrinting = true; isPrinting = true;
const formData = new FormData(); const formData = new FormData();
for (const f of files) { for (const f of files) {
formData.append('files', f.file, f.file.name); formData.append('files', f.file, f.file.name);
// Для офисных файлов всегда отправляем все страницы —
// CUPS сам разберётся
const pagesValue =
f.fileType === 'office'
? 'all'
: f.selectedPages && f.selectedPages.size > 0
? Array.from(f.selectedPages).sort((a, b) => a - b).join(',')
: 'all';
formData.append( formData.append(
'settings', 'settings',
JSON.stringify({ JSON.stringify({
filename: f.file.name, filename: f.file.name,
pages: f.selectedPages ? Array.from(f.selectedPages).sort((a, b) => a - b).join(',') : 'all', pages: pagesValue,
copies: f.copies, copies: f.copies,
colorMode: f.colorMode, colorMode: f.colorMode,
format: f.format format: f.fileType === 'office' ? 'auto' : f.format,
sides: f.sides ?? 'Односторонняя',
quality: f.qualityIndex,
dpi: f.dpi ?? 'Авто'
}) })
); );
} }
try { try {
const res = await fetch('/api/print', { method: 'POST', body: formData }); const res = await fetch('/api/print', { method: 'POST', body: formData });
const text = await res.text(); const text = await res.text();
@ -223,7 +255,6 @@ export function createPrintStore() {
get galleryLoading() { return galleryLoading; }, get galleryLoading() { return galleryLoading; },
get previewPagesCache() { return previewPagesCache; }, get previewPagesCache() { return previewPagesCache; },
get isPreviewRendering() { return isPreviewRendering; }, get isPreviewRendering() { return isPreviewRendering; },
addFiles, addFiles,
removeFile, removeFile,
toggleExpand, toggleExpand,