v1.1.0 upd connections instruct and checkup

This commit is contained in:
2026-09-19 17:36:33 +03:00
parent db9be1a90a
commit e1d567612d
4 changed files with 401 additions and 317 deletions

View File

@ -1,88 +1,45 @@
// lib/common/services/network.service.js // lib/common/services/network.service.js
// //
// Проверка подключения через эндпоинты бэкенда: // Определение сети, в которой находится устройство.
// //
// - /api/is_server — публичный сервер unitprint.ru. // - внутри локальной сети принтера (Wi-Fi UnitPrintLocal)
// Отвечает {"is_server":true} → интернет есть, скан доступен; // домен unitprint.ru резолвится на 192.168.20.1 — локальный сервер печати;
// - local.unitprint.ru/api/is_local — локальный сервер печати. // - из интернета домен отвечает публичным адресом 95.165.135.233.
// Отвечает {"is_local":true} → устройство в Wi-Fi принтера (UnitPrintLocal),
// печать доступна.
// //
// Сайт всегда отдаётся с unitprint.ru, поэтому проверка локалки ходит // Клиент не может сам отличить эти случаи по IP (сертификаты, mixed content),
// на отдельный хост local.unitprint.ru: вне локальной сети принтера // поэтому спрашиваем сам сервер: GET /api/is_local → { "is_local": true|false }.
// он просто недоступен. // Эндпоинт обязан быть на обоих инстансах:
// // локальный → { "is_local": true }
// Скан работает только через интернет, печать — только через локальную сеть. // публичный → { "is_local": false }
export const LOCAL_HOST = 'local.unitprint.ru'; export const DOMAIN = 'unitprint.ru';
export const PUBLIC_IP = '95.165.135.233';
export const LOCAL_IP = '192.168.20.1';
export const LOCAL_WIFI_NAME = 'UnitPrintLocal'; export const LOCAL_WIFI_NAME = 'UnitPrintLocal';
/** /**
* GET с таймаутом, читаем JSON. * Определяет текущий режим сети.
* @returns {Promise<any|null>} null — если хост недоступен или ошибка. * @returns {Promise<'local' | 'internet' | 'offline'>}
* - 'local' → отвечающий сервер — локальный (домен → 192.168.20.1)
* - 'internet' → отвечающий сервер — публичный (домен → 95.165.135.233)
* - 'offline' → сервер вообще не ответил
*/ */
async function getJson(url, timeoutMs = 4000) { export async function detectNetwork(timeoutMs = 6000) {
if (typeof fetch === 'undefined') return null; if (typeof fetch === 'undefined') return 'offline';
const controller = new AbortController(); const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs); const timer = setTimeout(() => controller.abort(), timeoutMs);
try { try {
const res = await fetch(url, { const res = await fetch('/api/is_local', {
method: 'GET',
cache: 'no-store', cache: 'no-store',
signal: controller.signal, signal: controller.signal,
}); });
if (!res.ok) return null; if (!res.ok) return 'offline';
return await res.json(); const data = await res.json();
if (typeof data?.is_local !== 'boolean') return 'offline';
return data.is_local ? 'local' : 'internet';
} catch { } catch {
return null; return 'offline';
} finally { } finally {
clearTimeout(timer); clearTimeout(timer);
} }
} }
/**
* Доступность хоста в режиме 'no-cors': CORS не мешает, важен сам факт ответа.
*/
async function canReach(url, timeoutMs = 4000) {
if (typeof fetch === 'undefined') return false;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
await fetch(url, {
method: 'GET',
mode: 'no-cors',
cache: 'no-store',
signal: controller.signal,
});
return true;
} catch {
return false;
} finally {
clearTimeout(timer);
}
}
/**
* Устройство в локальной сети принтера:
* local.unitprint.ru/api/is_local отвечает {"is_local":true}.
*/
export async function isLocalNetwork() {
const ts = Date.now();
const httpsUrl = `https://${LOCAL_HOST}/api/is_local?ping=${ts}`;
const httpUrl = `http://${LOCAL_HOST}/api/is_local?ping=${ts}`;
const data = (await getJson(httpsUrl, 3000)) ?? (await getJson(httpUrl, 3000));
if (data) return data.is_local === true;
// JSON не читается (CORS / самоподписанный сертификат) —fallback:
// сам факт ответа local.unitprint.ru означает, что мы в локалке.
return canReach(httpsUrl, 3000);
}
/**
* Есть интернет: публичный сервер отвечает на /api/is_server.
*/
export async function isServerReachable() {
const data = await getJson(`/api/is_server?ping=${Date.now()}`, 5000);
return data?.is_server === true;
}

View File

@ -1,76 +1,119 @@
<!-- lib/common/ui/NetworkGate.svelte -->
<!-- <!--
lib/common/ui/NetworkGate.svelte Экран-блокиратор: не пускает дальше, пока устройство не окажется в нужной сети.
Экран-блокиратор: не пускает дальше, пока устройство не окажется в нужной сети.
mode: mode:
- 'need-internet' — нужен интернет (/api/is_server отвечает true). Используется в скане. - 'need-internet' — нужен интернет (домен → 95.165.135.233). Используется в скане.
- 'need-local' — нужна локальная сеть принтера (local.unitprint.ru/api/is_local отвечает true). Перед печатью. - 'need-local' — нужна локальная сеть принтера (домен → 192.168.20.1). Перед печатью.
Сам опрашивает подключение; как только оно появилось — показывает «Подключено» и вызывает onReady().
Как только сеть появилась — показывает «Подключено» и вызывает onReady().
--> -->
<script> <script>
import { onMount } from 'svelte'; import { onMount } from 'svelte';
import { isLocalNetwork, isServerReachable, LOCAL_WIFI_NAME } from '$lib/common/services/network.service.js'; import { detectNetwork, LOCAL_WIFI_NAME } from '$lib/common/services/network.service.js';
let { let {
/** 'need-internet' | 'need-local' */ /** 'need-internet' | 'need-local' */
mode, mode,
onReady = () => {}, onReady = () => {},
onBack = () => {}, onBack = () => {},
pollMs = 3000, pollMs = 2000,
} = $props(); } = $props();
let success = $state(false); /** 'checking' — первая проверка, 'waiting' — ждём сеть, 'success' — сеть появилась */
let busy = false; let status = $state('checking');
let finished = false; let copySuccess = $state(false);
let timer = null;
const isLocalMode = $derived(mode === 'need-local'); let busy = false;
let finished = false;
let timer = null;
async function check() { const isLocalMode = $derived(mode === 'need-local');
if (busy || finished) return;
busy = true; async function check() {
if (busy || finished) return;
busy = true;
try {
const net = await detectNetwork();
const ok = isLocalMode ? net === 'local' : net === 'internet';
if (ok) {
finished = true;
status = 'success';
stopPoll();
setTimeout(() => onReady?.(), 900);
} else if (status === 'checking') {
status = 'waiting';
startPoll();
}
} finally {
busy = false;
}
}
function startPoll() {
stopPoll();
timer = setInterval(check, pollMs);
}
function stopPoll() {
if (timer) clearInterval(timer);
timer = null;
}
onMount(() => {
check();
const onVis = () => {
if (document.visibilityState === 'visible') check();
};
document.addEventListener('visibilitychange', onVis);
return () => {
document.removeEventListener('visibilitychange', onVis);
stopPoll();
};
});
async function copyWifiName() {
let success = false;
if (navigator.clipboard && window.isSecureContext) {
try { try {
const ok = isLocalMode ? await isLocalNetwork() : await isServerReachable(); await navigator.clipboard.writeText(LOCAL_WIFI_NAME);
if (ok) { success = true;
finished = true; } catch (err) {
success = true; console.warn('Clipboard API failed:', err);
stopPoll();
setTimeout(() => onReady?.(), 900);
}
} finally {
busy = false;
} }
} }
if (!success) {
function startPoll() { try {
stopPoll(); const textArea = document.createElement('textarea');
timer = setInterval(check, pollMs); textArea.value = LOCAL_WIFI_NAME;
textArea.style.position = 'fixed';
textArea.style.left = '-9999px';
textArea.style.opacity = '0';
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
const deprecated = /** @type {any} */ (document).execCommand;
if (deprecated && deprecated.call(document, 'copy')) success = true;
document.body.removeChild(textArea);
} catch (err) {
console.error('Fallback copy failed:', err);
}
} }
function stopPoll() { if (success) {
if (timer) clearInterval(timer); copySuccess = true;
timer = null; setTimeout(() => (copySuccess = false), 2000);
} }
}
onMount(() => {
check();
startPoll();
const onVis = () => {
if (document.visibilityState === 'visible') check();
};
document.addEventListener('visibilitychange', onVis);
return () => {
document.removeEventListener('visibilitychange', onVis);
stopPoll();
};
});
</script> </script>
<div class="gate-container"> <div class="gate-container">
<header class="gate-header"> <header class="gate-header">
<button type="button" class="back-btn" onclick={() => onBack?.()}>←</button> <button type="button" class="back-btn" onclick={() => onBack?.()}>←</button>
<h1>{isLocalMode ? 'Подключение к принтеру' : 'Нет интернета'}</h1>
</header> </header>
<main class="gate-content"> <main class="gate-content">
{#if success} {#if status === 'success'}
<div class="state-block"> <div class="state-block">
<div class="success-icon"> <div class="success-icon">
<svg width="42" height="42" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"></polyline></svg> <svg width="42" height="42" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"></polyline></svg>
@ -98,29 +141,41 @@ mode:
<div class="gate-info"> <div class="gate-info">
{#if isLocalMode} {#if isLocalMode}
<h2>Подключитесь к принтеру</h2> <h2>Нет связи с принтером</h2>
<p>Печать доступна только в локальной сети принтера. Подключите устройство к сети:</p> <p>Печать доступна только в локальной сети принтера. Подключите устройство к сети:</p>
{:else} {:else}
<h2>Необходимо подключение к интернету</h2> <h2>Необходимо подключение к интернету</h2>
<p>Сканирование доступно только онлайн</p> <p>Убедитесь, что вы отключены от локальной сети Wi-Fi принтера.</p>
{/if} {/if}
</div> </div>
{#if isLocalMode} <div class="steps">
<div class="steps-card"> {#if isLocalMode}
<div class="step"> <div class="step">
<span class="step-num">1</span> <span class="step-num">1</span>
<span class="step-body"> <div class="step-body">
<span class="step-text">Подключитесь к Wi-Fi</span> <span class="step-text">Подключитесь к Wi-Fi</span>
<span class="wifi-name"> <div class="wifi-chip-row">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <span class="wifi-chip">
<path d="M5 12.55a11 11 0 0 1 14.08 0"></path> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path> <path d="M5 12.55a11 11 0 0 1 14.08 0"></path>
<line x1="12" y1="20" x2="12.01" y2="20"></line> <path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path>
</svg> <line x1="12" y1="20" x2="12.01" y2="20"></line>
{LOCAL_WIFI_NAME} </svg>
</span> {LOCAL_WIFI_NAME}
</span> </span>
<button
type="button"
class="copy-btn"
class:success={copySuccess}
onclick={copyWifiName}
title={copySuccess ? 'Скопировано' : 'Скопировать название сети'}
aria-label={copySuccess ? 'Скопировано' : 'Скопировать название сети'}
>
{copySuccess ? '✓' : '📋'}
</button>
</div>
</div>
</div> </div>
<div class="step"> <div class="step">
<span class="step-num">2</span> <span class="step-num">2</span>
@ -130,166 +185,254 @@ mode:
<span class="step-num">3</span> <span class="step-num">3</span>
<span class="step-text">Отключите VPN</span> <span class="step-text">Отключите VPN</span>
</div> </div>
</div> {:else}
{/if} <div class="step">
<span class="step-num">1</span>
<span class="step-text">Отключитесь от сети <strong>{LOCAL_WIFI_NAME}</strong></span>
</div>
<div class="step">
<span class="step-num">2</span>
<span class="step-text">Включите мобильный интернет или подключитесь к другому Wi-Fi</span>
</div>
{/if}
</div>
<div class="waiting-row"> <div class="waiting-row">
<div class="spinner small"></div> <div class="spinner small"></div>
<span>Ожидание подключения…</span> <span>
{#if status === 'checking'}
Проверка подключения…
{:else if isLocalMode}
Ожидание подключения к принтеру…
{:else}
Ожидание интернета…
{/if}
</span>
</div> </div>
<p class="auto-hint">Как только подключение появится — продолжим автоматически</p>
<button type="button" class="retry-btn" onclick={check}>Проверить снова</button>
{/if} {/if}
</main> </main>
</div> </div>
<style> <style>
.gate-container { .gate-container {
width: 100%; width: 100%;
min-height: 100dvh; min-height: 100dvh;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
background: radial-gradient(120% 60% at 50% -10%, rgba(99, 102, 241, 0.18) 0%, transparent 60%); background: radial-gradient(120% 60% at 50% -10%, rgba(99, 102, 241, 0.18) 0%, transparent 60%);
font-family: system-ui, -apple-system, sans-serif; font-family: system-ui, -apple-system, sans-serif;
color: #f5f7fa; color: #f5f7fa;
} }
.gate-header { .gate-header {
padding: 24px 20px 8px; padding: 24px 20px 8px;
display: flex; display: flex;
align-items: center; align-items: center;
} position: relative;
.back-btn { }
background: none; .back-btn {
border: none; background: none;
color: #6366f1; border: none;
font-size: 15px; color: #6366f1;
font-weight: 600; font-size: 15px;
cursor: pointer; font-weight: 600;
padding: 8px 4px; cursor: pointer;
min-height: 44px; padding: 8px 4px;
touch-action: manipulation; margin-right: auto;
-webkit-tap-highlight-color: transparent; min-height: 44px;
} touch-action: manipulation;
.gate-content { -webkit-tap-highlight-color: transparent;
flex: 1; }
width: 100%; .gate-header h1 {
max-width: 520px; margin: 0;
margin: 0 auto; font-size: 28px;
box-sizing: border-box; font-weight: 700;
padding: 28px 20px 40px; position: absolute;
display: flex; left: 50%;
flex-direction: column; transform: translateX(-50%);
align-items: center; white-space: nowrap;
gap: 22px; }
} .gate-content {
/* ── состояние success ── */ flex: 1;
.state-block { width: 100%;
flex: 1; max-width: 520px;
display: flex; margin: 0 auto;
flex-direction: column; box-sizing: border-box;
align-items: center; padding: 28px 20px 40px;
justify-content: center; display: flex;
gap: 14px; flex-direction: column;
text-align: center; align-items: center;
padding: 40px 0; gap: 22px;
} }
.state-title { margin: 0; font-size: 19px; font-weight: 700; color: #f5f7fa; }
.state-title.ok { color: #4ade80; } .state-block {
.state-sub { margin: 0; font-size: 14px; color: #8b93a1; } flex: 1;
.success-icon { display: flex;
width: 88px; flex-direction: column;
height: 88px; align-items: center;
border-radius: 50%; justify-content: center;
display: grid; gap: 14px;
place-items: center; text-align: center;
background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%); padding: 40px 0;
box-shadow: 0 16px 38px -12px rgba(34, 197, 94, 0.55); }
color: #fff; .state-title { margin: 0; font-size: 19px; font-weight: 700; color: #f5f7fa; }
animation: pop-in 0.4s cubic-bezier(0.34, 1.56, 0.64, 1); .state-title.ok { color: #4ade80; }
} .state-sub { margin: 0; font-size: 14px; color: #8b93a1; }
@keyframes pop-in { .success-icon {
from { transform: scale(0.5); opacity: 0; } width: 88px;
to { transform: scale(1); opacity: 1; } height: 88px;
} border-radius: 50%;
/* ── состояние ожидания ── */ display: grid;
.icon-wrap { place-items: center;
width: 92px; background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
height: 92px; box-shadow: 0 16px 38px -12px rgba(34, 197, 94, 0.55);
border-radius: 28px; color: #fff;
display: grid; animation: pop-in 0.4s cubic-bezier(0.34, 1.56, 0.64, 1);
place-items: center; }
color: #fff; @keyframes pop-in {
margin-top: 6px; from { transform: scale(0.5); opacity: 0; }
} to { transform: scale(1); opacity: 1; }
.icon-wrap.local { }
background: linear-gradient(135deg, #5b8cff 0%, #38c6ff 100%);
box-shadow: 0 16px 38px -12px rgba(72, 150, 255, 0.55); .icon-wrap {
} width: 92px;
.icon-wrap.internet { height: 92px;
background: linear-gradient(135deg, #34d399 0%, #2dd4bf 100%); border-radius: 28px;
box-shadow: 0 16px 38px -12px rgba(52, 211, 153, 0.55); display: grid;
} place-items: center;
.gate-info { text-align: center; display: flex; flex-direction: column; gap: 8px; } color: #fff;
.gate-info h2 { margin: 0; font-size: 21px; font-weight: 700; letter-spacing: -0.01em; } margin-top: 6px;
.gate-info p { margin: 0; font-size: 14px; line-height: 1.5; color: #9ca3af; } }
/* ── единый блок шагов ── */ .icon-wrap.local {
.steps-card { background: linear-gradient(135deg, #5b8cff 0%, #38c6ff 100%);
width: 100%; box-shadow: 0 16px 38px -12px rgba(72, 150, 255, 0.55);
display: flex; }
flex-direction: column; .icon-wrap.internet {
gap: 12px; background: linear-gradient(135deg, #34d399 0%, #2dd4bf 100%);
padding: 14px 16px; box-shadow: 0 16px 38px -12px rgba(52, 211, 153, 0.55);
border-radius: 16px; }
background: rgba(255, 255, 255, 0.05); .gate-info { text-align: center; display: flex; flex-direction: column; gap: 8px; }
border: 1px solid rgba(255, 255, 255, 0.08); .gate-info h2 { margin: 0; font-size: 21px; font-weight: 700; letter-spacing: -0.01em; }
text-align: left; .gate-info p { margin: 0; font-size: 14px; line-height: 1.5; color: #9ca3af; }
}
.step { display: flex; align-items: center; gap: 14px; } .steps { width: 100%; display: flex; flex-direction: column; gap: 10px; }
.step-num { .step {
width: 26px; display: flex;
height: 26px; align-items: center;
border-radius: 50%; gap: 14px;
flex-shrink: 0; padding: 14px 16px;
display: flex; border-radius: 16px;
align-items: center; background: rgba(255, 255, 255, 0.05);
justify-content: center; border: 1px solid rgba(255, 255, 255, 0.08);
background: rgba(99, 102, 241, 0.18); text-align: left;
border: 1px solid rgba(99, 102, 241, 0.4); }
color: #a5b4fc; .step-num {
font-size: 13px; width: 26px;
font-weight: 700; height: 26px;
} border-radius: 50%;
.step-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; } flex-shrink: 0;
.step-text { font-size: 15px; line-height: 1.45; color: #e5e9f0; } display: flex;
/* имя Wi-Fi без рамки, просто иконка + текст */ align-items: center;
.wifi-name { justify-content: center;
display: inline-flex; background: rgba(99, 102, 241, 0.18);
align-items: center; border: 1px solid rgba(99, 102, 241, 0.4);
gap: 8px; color: #a5b4fc;
color: #7db4ff; font-size: 13px;
font-size: 15px; font-weight: 700;
font-weight: 700; }
letter-spacing: 0.01em; .step-text { font-size: 15px; line-height: 1.45; color: #e5e9f0; }
} .step-text strong { color: #fff; }
.wifi-name svg { flex-shrink: 0; } .step-body { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 10px; }
/* ── ожидание ── */
.waiting-row { .wifi-chip-row { display: flex; align-items: center; gap: 10px; }
display: flex; .wifi-chip {
align-items: center; flex: 1;
gap: 10px; min-width: 0;
margin-top: 4px; display: flex;
color: #8b93a1; align-items: center;
font-size: 14px; justify-content: center;
font-weight: 600; gap: 8px;
} padding: 12px 14px;
/* ── спиннер ── */ border-radius: 12px;
.spinner { background: rgba(91, 140, 255, 0.14);
border-radius: 50%; border: 1px solid rgba(91, 140, 255, 0.45);
border: 3px solid rgba(255, 255, 255, 0.12); color: #fff;
border-top-color: #6366f1; font-size: 16px;
animation: gate-spin 0.8s linear infinite; font-weight: 700;
} letter-spacing: 0.01em;
.spinner.small { width: 18px; height: 18px; border-width: 2px; } overflow: hidden;
@keyframes gate-spin { to { transform: rotate(360deg); } } text-overflow: ellipsis;
@media (max-width: 380px) { white-space: nowrap;
.gate-info h2 { font-size: 19px; } }
} .wifi-chip svg { flex-shrink: 0; color: #7db4ff; }
.copy-btn {
width: 46px;
height: 46px;
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(99, 102, 241, 0.2);
border: 1px solid rgba(99, 102, 241, 0.4);
border-radius: 12px;
color: #fff;
font-size: 20px;
cursor: pointer;
transition: all 0.2s ease;
padding: 0;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
}
.copy-btn:hover { background: rgba(99, 102, 241, 0.35); border-color: #6366f1; }
.copy-btn:active { transform: scale(0.95); }
.copy-btn.success { background: rgba(34, 197, 94, 0.25); border-color: rgba(34, 197, 94, 0.5); }
.waiting-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 4px;
color: #8b93a1;
font-size: 14px;
font-weight: 600;
}
.auto-hint {
margin: -12px 0 0;
text-align: center;
color: rgba(139, 147, 161, 0.6);
font-size: 12px;
line-height: 1.4;
}
.retry-btn {
width: 100%;
padding: 16px 24px;
border-radius: 16px;
border: 1px solid rgba(255, 255, 255, 0.14);
background: rgba(255, 255, 255, 0.06);
color: #f5f7fa;
font-size: 16px;
font-weight: 700;
cursor: pointer;
transition: background 0.2s ease, border-color 0.2s ease;
touch-action: manipulation;
-webkit-tap-highlight-color: transparent;
}
.retry-btn:hover { background: rgba(255, 255, 255, 0.1); border-color: rgba(255, 255, 255, 0.24); }
.spinner {
border-radius: 50%;
border: 3px solid rgba(255, 255, 255, 0.12);
border-top-color: #6366f1;
animation: gate-spin 0.8s linear infinite;
}
.spinner.big { width: 46px; height: 46px; }
.spinner.small { width: 18px; height: 18px; border-width: 2px; }
@keyframes gate-spin { to { transform: rotate(360deg); } }
@media (max-width: 380px) {
.gate-header h1 { font-size: 22px; }
.gate-info h2 { font-size: 19px; }
}
</style> </style>

View File

@ -205,5 +205,5 @@
<div class="version"> <div class="version">
<span>v{backendVersion}</span> <span>v{backendVersion}</span>
<span>v1.0.9</span> <span>v1.1.0</span>
</div> </div>

View File

@ -7,7 +7,6 @@
import PaymentPage from '$lib/common/ui/PaymentPage.svelte'; import PaymentPage from '$lib/common/ui/PaymentPage.svelte';
import { plFiles, plCopies } from '$lib/common/utils/pricing.util.js'; import { plFiles, plCopies } from '$lib/common/utils/pricing.util.js';
import NetworkGate from '$lib/common/ui/NetworkGate.svelte'; import NetworkGate from '$lib/common/ui/NetworkGate.svelte';
import { isLocalNetwork } from '$lib/common/services/network.service.js';
let { onBack = () => {} } = $props(); let { onBack = () => {} } = $props();
const store = createPrintStore(); const store = createPrintStore();
@ -38,32 +37,27 @@
/* ── Проверка сети перед отправкой печати ── /* ── Проверка сети перед отправкой печати ──
* Печать работает только в локальной сети принтера (домен → 192.168.20.1). * Печать работает только в локальной сети принтера (домен → 192.168.20.1).
* Если «Я оплатил(а)» нажата не в той сети — показываем экран подключения * Гейт открывается мгновенно по нажатию «Я оплатил(а)» и сам внутри себя
* и автоматически отправляем печать, как только сеть появится. * делает первую проверку: если мы уже в локалке — короткая зелёная вспышка
* и печать ушла; если нет — инструкции и авто-проход при появлении сети.
*/ */
/** @type {null | 'checking' | 'blocked'} */ /** true → показываем экран подключения к принтеру */
let printNetGate = $state(null); let printNetGate = $state(false);
async function handleConfirmPayment() { function handleConfirmPayment() {
if (printNetGate === 'checking') return; // Гейт сам проверит сеть: если уже локальная — сразу пропустит и напечатает,
printNetGate = 'checking'; // если нет — покажет инструкции и будет ждать появления сети.
const net = await isLocalNetwork(); printNetGate = true;
if (net === 'local') {
printNetGate = null;
store.submitPrint();
} else {
printNetGate = 'blocked';
}
} }
function handleGateReady() { function handleGateReady() {
// сеть принтера появилась — пропускаем пользователя и сразу печатаем // сеть принтера появилась — пропускаем пользователя и сразу печатаем
printNetGate = null; printNetGate = false;
store.submitPrint(); store.submitPrint();
} }
function handleGateBack() { function handleGateBack() {
printNetGate = null; // возврат к странице оплаты printNetGate = false; // возврат к странице оплаты
} }
</script> </script>
@ -71,15 +65,8 @@
<!-- Страница прогресса печати (после оплаты) --> <!-- Страница прогресса печати (после оплаты) -->
<PrintProgress {store} onBack={onBack} /> <PrintProgress {store} onBack={onBack} />
{:else if store.showPayment} {:else if store.showPayment}
{#if printNetGate === 'blocked'} {#if printNetGate}
<NetworkGate mode="need-local" onReady={handleGateReady} onBack={handleGateBack} /> <NetworkGate mode="need-local" onReady={handleGateReady} onBack={handleGateBack} />
{:else if printNetGate === 'checking'}
<div class="page-container">
<div class="net-checking">
<div class="net-spinner"></div>
<p>Проверка подключения…</p>
</div>
</div>
{:else} {:else}
<PaymentPage <PaymentPage
totalPrice={store.totalPrice} totalPrice={store.totalPrice}
@ -142,9 +129,6 @@
{/if} {/if}
<style> <style>
.net-checking { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 18px; padding: 40px 20px; color: #8b93a1; font-size: 15px; font-weight: 600; text-align: center; }
.net-spinner { width: 42px; height: 42px; border-radius: 50%; border: 3px solid rgba(255,255,255,0.12); border-top-color: #6366f1; animation: net-spin 0.8s linear infinite; }
@keyframes net-spin { to { transform: rotate(360deg); } }
.page-container { width: 100%; min-height: 100dvh; display: flex; flex-direction: column; background: radial-gradient(120% 60% at 50% -10%, rgba(99,102,241,0.18) 0%, transparent 60%); font-family: system-ui, -apple-system, sans-serif; color: #f5f7fa; } .page-container { width: 100%; min-height: 100dvh; display: flex; flex-direction: column; background: radial-gradient(120% 60% at 50% -10%, rgba(99,102,241,0.18) 0%, transparent 60%); font-family: system-ui, -apple-system, sans-serif; color: #f5f7fa; }
.header { padding: 24px 20px 8px; display: flex; align-items: center; position: relative; } .header { padding: 24px 20px 8px; display: flex; align-items: center; position: relative; }
.back-btn { background: none; border: none; color: #6366f1; font-size: 15px; font-weight: 600; cursor: pointer; padding: 8px 4px; margin-right: auto; min-height: 44px; } .back-btn { background: none; border: none; color: #6366f1; font-size: 15px; font-weight: 600; cursor: pointer; padding: 8px 4px; margin-right: auto; min-height: 44px; }