Compare commits
12
Commits
v1.0.2
...
d39b4275bf
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d39b4275bf | ||
|
|
0b447e67bf | ||
|
|
959e693dcc | ||
|
|
f068628e7e | ||
|
|
1550bccb83 | ||
|
|
2ab7c29576 | ||
|
|
a6a748281f | ||
|
|
4dbfe782f5 | ||
|
|
d6b7723113 | ||
|
|
26ed4e6a22 | ||
|
|
73b43e1f24 | ||
|
|
5274520a33 |
+100
@@ -2,6 +2,98 @@
|
|||||||
|
|
||||||
Формат основан на [Keep a Changelog](https://keepachangelog.com/ru/1.1.0/), версии — [SemVer](https://semver.org/lang/ru/).
|
Формат основан на [Keep a Changelog](https://keepachangelog.com/ru/1.1.0/), версии — [SemVer](https://semver.org/lang/ru/).
|
||||||
|
|
||||||
|
## [1.1.0] — 2026-11-11
|
||||||
|
|
||||||
|
### Прейскурант
|
||||||
|
|
||||||
|
- Прайс заменён на Прейскурант № 423 от 18.09.2026: 4188 услуг (было 4221), из них 568 новых, 600 удалено; добавлен раздел «10. Чекапы» (в каталоге — «Комплексные программы»)
|
||||||
|
- `pnpm seed:price` теперь заменяет каталог целиком: услуги с тем же кодом сохраняют id и связи (врачи, акции, заявки, записи), отсутствующие в прайсе удаляются, а услуги с записями пациентов снимаются с публикации; всё в одной транзакции; режимы `--dry-run` и `--hard`
|
||||||
|
- Скрипт `apps/cms/src/seed/price_from_xlsx.py` собирает `price-services.json` из xlsx-прейскуранта
|
||||||
|
|
||||||
|
### Безопасность
|
||||||
|
|
||||||
|
- Роль пользователя может назначать только администратор: регистрация и редактирование профиля больше не позволяют стать `admin` (первый пользователь новой установки по-прежнему становится администратором)
|
||||||
|
- Подтверждение оплаты СБП (`PUT /api/custom/payments/sbp`) принимается только с HMAC-SHA256 подписью `x-sbp-signature` (`SBP_WEBHOOK_SECRET`) или от администратора; повторный вебхук не создаёт дубли чеков
|
||||||
|
- Чеки, справки и другие файлы пациента приватны: у медиа появилось поле «Владелец», файл видит только владелец и администратор; в кабинете файлы скачиваются через сайт (`/api/cabinet/files/…`)
|
||||||
|
- Загружать медиа может только администратор
|
||||||
|
- Пациент не может менять цену, статус оплаты и подтверждение записи (только отменить её), создавать записи и избранное на чужой аккаунт и выписывать счета
|
||||||
|
|
||||||
|
### CMS: картинки
|
||||||
|
|
||||||
|
- Под каждым полем с фото и файлом (врачи, баннеры, акции, филиалы, новости, галерея, страницы, документы) — большое превью, размер и формат, точка фокуса, путь к файлу на сервере и адрес на сайте с кнопкой «Копировать»
|
||||||
|
- Кнопка «Редактировать изображение» открывает встроенный редактор: обрезка, размер в пикселях, точка фокуса; перед первой обрезкой оригинал сохраняется в `media/originals/`, его можно вернуть кнопкой «Вернуть оригинал»
|
||||||
|
- Старые поля «URL фото» показываются только пока в них есть ссылка: видно превью и где реально лежит файл (`apps/web/public/...` или внешний адрес), кнопка «Перенести в медиатеку» делает фото редактируемым
|
||||||
|
- «Направления»: вместо текстового поля — выбор иконки с превью, подборкой медицинских иконок и поиском по всем иконкам Untitled UI; можно загрузить свою иконку (SVG/PNG)
|
||||||
|
|
||||||
|
### Исправлено
|
||||||
|
|
||||||
|
- Загруженное фото врача имеет приоритет над старой ссылкой и открывается с адреса CMS (раньше относительный адрес не работал на сайте)
|
||||||
|
- Сохранение профиля в личном кабинете (ранее запрос в CMS всегда падал)
|
||||||
|
- Генерация PDF-чека и справки после оплаты (`pdfkit` вынесен из сборки Next.js)
|
||||||
|
|
||||||
|
## [1.0.11] — 2026-09-17
|
||||||
|
|
||||||
|
### Сайт
|
||||||
|
|
||||||
|
- В шапке рядом с логотипом — режим работы и телефоны `+7 (499) 674-07-09` / `122` с иконками в цветах сайта
|
||||||
|
|
||||||
|
## [1.0.10] — 2026-09-17
|
||||||
|
|
||||||
|
### Сайт
|
||||||
|
|
||||||
|
- Личный кабинет больше не показывает чужие демо-записи: без входа разделы пустые, у каждого пациента только свои заявки, документы и счета
|
||||||
|
- После заявки на запись создаётся кабинет (если пациента ещё не было) и на почту уходит письмо со сводкой услуги, стоимостью и полезной информацией
|
||||||
|
- В галерее четыре фото КДЦ МОНИКИ как загруженные файлы, не ссылки
|
||||||
|
|
||||||
|
## [1.0.9] — 2026-09-17
|
||||||
|
|
||||||
|
### Сайт
|
||||||
|
|
||||||
|
- В заявке на запись: обязательные ФИО и e-mail, маска телефона РФ `+7` только из цифр, проверка e-mail (`@` и домен), серые примеры в полях
|
||||||
|
|
||||||
|
## [1.0.8] — 2026-09-17
|
||||||
|
|
||||||
|
### CMS
|
||||||
|
|
||||||
|
- Исправлена сессия входа в админку по HTTP: cookie больше не отбрасывается из‑за Origin/CSRF
|
||||||
|
|
||||||
|
### Сайт
|
||||||
|
|
||||||
|
- Cookie входа в личный кабинет сохраняется на HTTP без флага Secure
|
||||||
|
|
||||||
|
## [1.0.7] — 2026-09-17
|
||||||
|
|
||||||
|
### CMS
|
||||||
|
|
||||||
|
- Вход в админку по HTTP снова сохраняет сессию: Secure-cookie больше не ставится без HTTPS
|
||||||
|
|
||||||
|
## [1.0.6] — 2026-09-17
|
||||||
|
|
||||||
|
### Сайт
|
||||||
|
|
||||||
|
- В разделе «Документы» три публичных файла из шапок: согласие на персональные данные, ИДС на медвмешательство/врачебную тайну/телемед, договор с физическим лицом
|
||||||
|
- Удалён публичный договор «…(2026)»
|
||||||
|
- Онлайн-запись временно без расписания: услуга или врач → филиал → ФИО, e-mail, телефон; после отправки — «Большое спасибо, мы свяжемся и уточним информацию»
|
||||||
|
- Заявки сохраняются в админке (коллекция «Заявки на запись»)
|
||||||
|
|
||||||
|
## [1.0.5] — 2026-09-17
|
||||||
|
|
||||||
|
### Сайт
|
||||||
|
|
||||||
|
- В подвале в разделе «Полезное» добавлены ссылки на главную страницу института и образование
|
||||||
|
|
||||||
|
## [1.0.4] — 2026-09-16
|
||||||
|
|
||||||
|
### Сайт
|
||||||
|
|
||||||
|
- Логотип в подвале выровнен по центру колонки
|
||||||
|
|
||||||
|
## [1.0.3] — 2026-09-16
|
||||||
|
|
||||||
|
### Сайт
|
||||||
|
|
||||||
|
- Обновлён логотип МОНИКИ в шапке и подвале
|
||||||
|
|
||||||
## [1.0.2] — 2026-09-16
|
## [1.0.2] — 2026-09-16
|
||||||
|
|
||||||
### Сайт
|
### Сайт
|
||||||
@@ -37,6 +129,14 @@
|
|||||||
- Docker Compose для локальной БД
|
- Docker Compose для локальной БД
|
||||||
- Секреты и логины в git не входят
|
- Секреты и логины в git не входят
|
||||||
|
|
||||||
|
[1.0.10]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.10
|
||||||
|
[1.0.9]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.9
|
||||||
|
[1.0.8]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.8
|
||||||
|
[1.0.7]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.7
|
||||||
|
[1.0.6]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.6
|
||||||
|
[1.0.5]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.5
|
||||||
|
[1.0.4]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.4
|
||||||
|
[1.0.3]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.3
|
||||||
[1.0.2]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.2
|
[1.0.2]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.2
|
||||||
[1.0.1]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.1
|
[1.0.1]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.1
|
||||||
[1.0.0]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.0
|
[1.0.0]: https://git.myunion.pro/Alex/Moniki_uslugi/src/tag/v1.0.0
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
|
|
||||||
Репозиторий: [Moniki_uslugi](https://git.myunion.pro/Alex/Moniki_uslugi) на [git.myunion.pro](https://git.myunion.pro/).
|
Репозиторий: [Moniki_uslugi](https://git.myunion.pro/Alex/Moniki_uslugi) на [git.myunion.pro](https://git.myunion.pro/).
|
||||||
|
|
||||||
Текущая версия: **v1.0.2** (см. [CHANGELOG.md](CHANGELOG.md)).
|
Текущая версия: **v1.1.0** (см. [CHANGELOG.md](CHANGELOG.md)).
|
||||||
|
|
||||||
## Что внутри
|
## Что внутри
|
||||||
|
|
||||||
@@ -70,6 +70,19 @@ docker compose up -d postgres
|
|||||||
|
|
||||||
Учётные данные для локальной разработки создаёт `pnpm seed`. Они не публикуются в этом README.
|
Учётные данные для локальной разработки создаёт `pnpm seed`. Они не публикуются в этом README.
|
||||||
|
|
||||||
|
## Обновление прейскуранта
|
||||||
|
|
||||||
|
Нужен Python 3 с `openpyxl` (`pip install openpyxl`).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 apps/cms/src/seed/price_from_xlsx.py "/путь/к/Прейскурант.xlsx" # пересобрать price-services.json
|
||||||
|
pnpm seed:price --dry-run # показать, сколько услуг будет удалено / обновлено / создано
|
||||||
|
pnpm seed:price # заменить каталог (связи с врачами, акциями и заявками сохраняются)
|
||||||
|
pnpm seed:i18n # при необходимости — заново заполнить переводы
|
||||||
|
```
|
||||||
|
|
||||||
|
Перед запуском на сервере сделайте резервную копию базы.
|
||||||
|
|
||||||
## Версии
|
## Версии
|
||||||
|
|
||||||
Теги SemVer: `vMAJOR.MINOR.PATCH`. История — в `CHANGELOG.md`.
|
Теги SemVer: `vMAJOR.MINOR.PATCH`. История — в `CHANGELOG.md`.
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ NEXT_PUBLIC_SERVER_URL=http://localhost:3001
|
|||||||
CORS_ORIGINS=http://localhost:3000
|
CORS_ORIGINS=http://localhost:3000
|
||||||
SBP_MERCHANT_ID=
|
SBP_MERCHANT_ID=
|
||||||
SBP_API_KEY=
|
SBP_API_KEY=
|
||||||
|
# Required in production: HMAC-SHA256 secret for the x-sbp-signature header of payment webhooks
|
||||||
SBP_WEBHOOK_SECRET=
|
SBP_WEBHOOK_SECRET=
|
||||||
SMS_PROVIDER_API_KEY=
|
SMS_PROVIDER_API_KEY=
|
||||||
SMS_ENABLED=false
|
SMS_ENABLED=false
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ import type { NextConfig } from 'next'
|
|||||||
const nextConfig: NextConfig = {
|
const nextConfig: NextConfig = {
|
||||||
typescript: { ignoreBuildErrors: true },
|
typescript: { ignoreBuildErrors: true },
|
||||||
eslint: { ignoreDuringBuilds: true },
|
eslint: { ignoreDuringBuilds: true },
|
||||||
|
// pdfkit reads its font metrics (.afm) from disk; bundling it breaks receipt PDF generation.
|
||||||
|
serverExternalPackages: ['pdfkit'],
|
||||||
images: {
|
images: {
|
||||||
remotePatterns: [
|
remotePatterns: [
|
||||||
{ protocol: 'http', hostname: 'localhost' },
|
{ protocol: 'http', hostname: 'localhost' },
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@moniki/cms",
|
"name": "@moniki/cms",
|
||||||
"version": "1.0.2",
|
"version": "1.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
@@ -19,6 +19,7 @@
|
|||||||
"seed:news": "tsx src/seed/import-news.ts",
|
"seed:news": "tsx src/seed/import-news.ts",
|
||||||
"seed:pages": "tsx src/seed/site-pages.ts",
|
"seed:pages": "tsx src/seed/site-pages.ts",
|
||||||
"seed:documents": "tsx src/seed/public-documents.ts",
|
"seed:documents": "tsx src/seed/public-documents.ts",
|
||||||
|
"seed:gallery": "tsx src/seed/gallery-photos.ts",
|
||||||
"seed:i18n": "python3 src/seed/translate_locales.py",
|
"seed:i18n": "python3 src/seed/translate_locales.py",
|
||||||
"lint": "next lint"
|
"lint": "next lint"
|
||||||
},
|
},
|
||||||
@@ -28,6 +29,7 @@
|
|||||||
"@payloadcms/richtext-lexical": "^3.49.1",
|
"@payloadcms/richtext-lexical": "^3.49.1",
|
||||||
"@payloadcms/translations": "^3.49.1",
|
"@payloadcms/translations": "^3.49.1",
|
||||||
"@payloadcms/ui": "^3.49.1",
|
"@payloadcms/ui": "^3.49.1",
|
||||||
|
"@untitledui/icons": "^0.0.19",
|
||||||
"cross-env": "^7.0.3",
|
"cross-env": "^7.0.3",
|
||||||
"dotenv": "^16.5.0",
|
"dotenv": "^16.5.0",
|
||||||
"graphql": "^16.10.0",
|
"graphql": "^16.10.0",
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import configPromise from '@payload-config'
|
||||||
|
import { getPayload } from 'payload'
|
||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { isValidEmailAddress, isValidFullName, isValidRuPhone, normalizeRuPhone } from '@/lib/contact-fields'
|
||||||
|
import { findOrCreatePatient, notifyInquiry } from '@/lib/inquiry-account'
|
||||||
|
|
||||||
|
function asText(value: unknown) {
|
||||||
|
return typeof value === "string" ? value.trim() : ""
|
||||||
|
}
|
||||||
|
|
||||||
|
function asId(value: unknown) {
|
||||||
|
if (typeof value === "number" && Number.isFinite(value)) return value
|
||||||
|
if (typeof value === "string" && value.trim()) {
|
||||||
|
const n = Number(value)
|
||||||
|
return Number.isFinite(n) ? n : value.trim()
|
||||||
|
}
|
||||||
|
return undefined
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
const body = (await req.json().catch(() => ({}))) as Record<string, unknown>
|
||||||
|
const name = asText(body.name).replace(/\s+/g, " ")
|
||||||
|
const email = asText(body.email)
|
||||||
|
const phone = normalizeRuPhone(asText(body.phone))
|
||||||
|
const branch = asId(body.branch)
|
||||||
|
const service = asId(body.service)
|
||||||
|
const doctor = asId(body.doctor)
|
||||||
|
|
||||||
|
if (!isValidFullName(name) || !isValidEmailAddress(email) || !isValidRuPhone(phone) || branch == null || (service == null && doctor == null)) {
|
||||||
|
return NextResponse.json({ error: "invalid" }, { status: 400 })
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const payload = await getPayload({ config: configPromise })
|
||||||
|
let patientId: string | number | undefined
|
||||||
|
let cabinetCreated = false
|
||||||
|
let password: string | undefined
|
||||||
|
try {
|
||||||
|
const account = await findOrCreatePatient(payload, { email, name, phone })
|
||||||
|
patientId = account.id
|
||||||
|
cabinetCreated = account.created
|
||||||
|
password = account.password
|
||||||
|
} catch (error) {
|
||||||
|
payload.logger.error({ err: error }, 'Failed to create patient cabinet from inquiry')
|
||||||
|
}
|
||||||
|
|
||||||
|
const doc = await payload.create({
|
||||||
|
collection: "inquiries",
|
||||||
|
overrideAccess: true,
|
||||||
|
data: {
|
||||||
|
name,
|
||||||
|
email,
|
||||||
|
phone,
|
||||||
|
branch,
|
||||||
|
...(service != null ? { service } : {}),
|
||||||
|
...(doctor != null ? { doctor } : {}),
|
||||||
|
...(patientId != null ? { patient: patientId } : {}),
|
||||||
|
status: "new",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
notifyInquiry(payload, {
|
||||||
|
inquiryId: doc.id,
|
||||||
|
patientName: name,
|
||||||
|
email,
|
||||||
|
phone,
|
||||||
|
cabinetCreated,
|
||||||
|
password,
|
||||||
|
}).catch((error) => {
|
||||||
|
payload.logger.error({ err: error }, 'Failed to send inquiry email')
|
||||||
|
})
|
||||||
|
|
||||||
|
return NextResponse.json({ id: String(doc.id), cabinetCreated })
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : "failed"
|
||||||
|
return NextResponse.json({ error: message }, { status: 400 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import configPromise from '@payload-config'
|
||||||
|
import { getPayload } from 'payload'
|
||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { isAdminUser } from '@/lib/access'
|
||||||
|
import { fetchRemoteFile, resolveLegacyUrl } from '@/lib/legacy-media'
|
||||||
|
|
||||||
|
/** Admin helper: copy a legacy linked image into the media library so it can be edited. */
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
const payload = await getPayload({ config: configPromise })
|
||||||
|
const { user } = await payload.auth({ headers: req.headers })
|
||||||
|
if (!isAdminUser(user)) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
|
|
||||||
|
const body = (await req.json().catch(() => ({}))) as { url?: unknown; alt?: unknown }
|
||||||
|
const resolved = await resolveLegacyUrl(typeof body.url === 'string' ? body.url : '')
|
||||||
|
if (!resolved) return NextResponse.json({ error: 'Некорректная ссылка' }, { status: 400 })
|
||||||
|
const alt = typeof body.alt === 'string' ? body.alt : undefined
|
||||||
|
|
||||||
|
try {
|
||||||
|
let doc
|
||||||
|
if (resolved.remote) {
|
||||||
|
const file = await fetchRemoteFile(resolved.url)
|
||||||
|
doc = await payload.create({ collection: 'media', data: { alt }, file, user, overrideAccess: false })
|
||||||
|
} else {
|
||||||
|
if (!resolved.localPath || !resolved.exists) {
|
||||||
|
return NextResponse.json({ error: `Файл не найден: ${resolved.where}` }, { status: 404 })
|
||||||
|
}
|
||||||
|
doc = await payload.create({
|
||||||
|
collection: 'media',
|
||||||
|
data: { alt },
|
||||||
|
filePath: resolved.localPath,
|
||||||
|
user,
|
||||||
|
overrideAccess: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return NextResponse.json({ doc })
|
||||||
|
} catch (error) {
|
||||||
|
const message = error instanceof Error ? error.message : 'Не удалось перенести файл'
|
||||||
|
return NextResponse.json({ error: message }, { status: 400 })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import configPromise from '@payload-config'
|
||||||
|
import { getPayload } from 'payload'
|
||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { isAdminUser } from '@/lib/access'
|
||||||
|
import { resolveLegacyUrl } from '@/lib/legacy-media'
|
||||||
|
|
||||||
|
/** Admin helper: where does a legacy image link (/hero/x.jpg, https://...) actually live. */
|
||||||
|
export async function GET(req: Request) {
|
||||||
|
const payload = await getPayload({ config: configPromise })
|
||||||
|
const { user } = await payload.auth({ headers: req.headers })
|
||||||
|
if (!isAdminUser(user)) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
|
|
||||||
|
const url = new URL(req.url).searchParams.get('url') || ''
|
||||||
|
const resolved = await resolveLegacyUrl(url)
|
||||||
|
if (!resolved) return NextResponse.json({ error: 'Ссылка должна начинаться с / или http(s)://' }, { status: 400 })
|
||||||
|
return NextResponse.json(resolved)
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import fs from 'node:fs/promises'
|
||||||
|
import path from 'node:path'
|
||||||
|
import configPromise from '@payload-config'
|
||||||
|
import { getPayload } from 'payload'
|
||||||
|
import { NextResponse } from 'next/server'
|
||||||
|
import { isAdminUser } from '@/lib/access'
|
||||||
|
import { fileExists, MEDIA_DIR, ORIGINALS_DIR, safeJoin } from '@/lib/media-paths'
|
||||||
|
|
||||||
|
/** Admin helper: undo crops/resizes by putting back the copy saved before the first edit. */
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
const payload = await getPayload({ config: configPromise })
|
||||||
|
const { user } = await payload.auth({ headers: req.headers })
|
||||||
|
if (!isAdminUser(user)) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
|
|
||||||
|
const body = (await req.json().catch(() => ({}))) as { id?: unknown }
|
||||||
|
const id = typeof body.id === 'string' || typeof body.id === 'number' ? body.id : null
|
||||||
|
if (id == null) return NextResponse.json({ error: 'id required' }, { status: 400 })
|
||||||
|
|
||||||
|
const doc = await payload.findByID({ collection: 'media', id, depth: 0, user, overrideAccess: false })
|
||||||
|
const original = doc.originalFile ? safeJoin(ORIGINALS_DIR, String(doc.originalFile)) : null
|
||||||
|
if (!original || !(await fileExists(original))) {
|
||||||
|
return NextResponse.json({ error: 'Оригинал не сохранён' }, { status: 404 })
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = doc.filename ? safeJoin(MEDIA_DIR, String(doc.filename)) : null
|
||||||
|
if (!current) return NextResponse.json({ error: 'У файла нет имени' }, { status: 400 })
|
||||||
|
// Put the original back under the current name so the public URL stays the same.
|
||||||
|
await fs.copyFile(original, current)
|
||||||
|
|
||||||
|
const updated = await payload.update({
|
||||||
|
collection: 'media',
|
||||||
|
id,
|
||||||
|
data: { originalFile: null },
|
||||||
|
filePath: current,
|
||||||
|
overwriteExistingFiles: true,
|
||||||
|
user,
|
||||||
|
overrideAccess: false,
|
||||||
|
})
|
||||||
|
return NextResponse.json({ doc: updated, restoredFrom: path.basename(original) })
|
||||||
|
}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
import configPromise from '@payload-config'
|
import configPromise from '@payload-config'
|
||||||
import { getPayload } from 'payload'
|
import { getPayload } from 'payload'
|
||||||
import { NextResponse } from 'next/server'
|
import { NextResponse } from 'next/server'
|
||||||
import { createSbpPayment } from '@/lib/sbp'
|
import { createSbpPayment, verifySbpWebhook } from '@/lib/sbp'
|
||||||
|
import { isAdminUser } from '@/lib/access'
|
||||||
import { generateReceiptPdf, generateTaxDeductionPdf } from '@/lib/pdf'
|
import { generateReceiptPdf, generateTaxDeductionPdf } from '@/lib/pdf'
|
||||||
import { sendNotification } from '@/lib/notifications'
|
import { sendNotification } from '@/lib/notifications'
|
||||||
|
|
||||||
@@ -69,8 +70,22 @@ export async function POST(req: Request) {
|
|||||||
/** Mark payment paid (webhook / mock) and generate PDFs. */
|
/** Mark payment paid (webhook / mock) and generate PDFs. */
|
||||||
export async function PUT(req: Request) {
|
export async function PUT(req: Request) {
|
||||||
const payload = await getPayload({ config: configPromise })
|
const payload = await getPayload({ config: configPromise })
|
||||||
const body = await req.json()
|
const rawBody = await req.text()
|
||||||
const { sbpPaymentId } = body
|
|
||||||
|
// Only the acquiring bank (signed webhook) or an administrator may mark a payment as paid.
|
||||||
|
const auth = await payload.auth({ headers: req.headers })
|
||||||
|
const signature = req.headers.get('x-sbp-signature')
|
||||||
|
if (!isAdminUser(auth.user) && !verifySbpWebhook(signature, rawBody)) {
|
||||||
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: { sbpPaymentId?: unknown }
|
||||||
|
try {
|
||||||
|
body = JSON.parse(rawBody || '{}')
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: 'Invalid JSON' }, { status: 400 })
|
||||||
|
}
|
||||||
|
const sbpPaymentId = typeof body.sbpPaymentId === 'string' ? body.sbpPaymentId : ''
|
||||||
if (!sbpPaymentId) {
|
if (!sbpPaymentId) {
|
||||||
return NextResponse.json({ error: 'sbpPaymentId required' }, { status: 400 })
|
return NextResponse.json({ error: 'sbpPaymentId required' }, { status: 400 })
|
||||||
}
|
}
|
||||||
@@ -85,8 +100,13 @@ export async function PUT(req: Request) {
|
|||||||
if (!invoice) {
|
if (!invoice) {
|
||||||
return NextResponse.json({ error: 'Invoice not found' }, { status: 404 })
|
return NextResponse.json({ error: 'Invoice not found' }, { status: 404 })
|
||||||
}
|
}
|
||||||
|
if (invoice.status === 'paid') {
|
||||||
|
// Idempotent: repeated webhooks must not create duplicate receipts.
|
||||||
|
return NextResponse.json({ invoice })
|
||||||
|
}
|
||||||
|
|
||||||
const paidAt = new Date().toISOString()
|
const paidAt = new Date().toISOString()
|
||||||
|
const patientId = typeof invoice.patient === 'object' ? invoice.patient.id : invoice.patient
|
||||||
const booking = typeof invoice.booking === 'object' ? invoice.booking : null
|
const booking = typeof invoice.booking === 'object' ? invoice.booking : null
|
||||||
const patient = typeof invoice.patient === 'object' ? invoice.patient : null
|
const patient = typeof invoice.patient === 'object' ? invoice.patient : null
|
||||||
|
|
||||||
@@ -116,7 +136,7 @@ export async function PUT(req: Request) {
|
|||||||
|
|
||||||
const receiptFile = await payload.create({
|
const receiptFile = await payload.create({
|
||||||
collection: 'media',
|
collection: 'media',
|
||||||
data: { alt: `Чек ${invoice.number}` },
|
data: { alt: `Чек ${invoice.number}`, owner: patientId },
|
||||||
file: {
|
file: {
|
||||||
data: receiptBuf,
|
data: receiptBuf,
|
||||||
mimetype: 'application/pdf',
|
mimetype: 'application/pdf',
|
||||||
@@ -127,7 +147,7 @@ export async function PUT(req: Request) {
|
|||||||
|
|
||||||
const taxFile = await payload.create({
|
const taxFile = await payload.create({
|
||||||
collection: 'media',
|
collection: 'media',
|
||||||
data: { alt: `Справка НВ ${invoice.number}` },
|
data: { alt: `Справка НВ ${invoice.number}`, owner: patientId },
|
||||||
file: {
|
file: {
|
||||||
data: taxBuf,
|
data: taxBuf,
|
||||||
mimetype: 'application/pdf',
|
mimetype: 'application/pdf',
|
||||||
@@ -155,7 +175,6 @@ export async function PUT(req: Request) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
const patientId = typeof invoice.patient === 'object' ? invoice.patient.id : invoice.patient
|
|
||||||
await payload.create({
|
await payload.create({
|
||||||
collection: 'documents',
|
collection: 'documents',
|
||||||
data: {
|
data: {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { CollectionConfig } from 'payload'
|
import type { CollectionConfig } from 'payload'
|
||||||
import { ADMIN_GROUP } from '../admin/groups'
|
import { ADMIN_GROUP } from '../admin/groups'
|
||||||
|
import { adminOnlyField, isAdminUser } from '../lib/access'
|
||||||
|
|
||||||
const BOOKING_HOLD_MS = 24 * 60 * 60 * 1000
|
const BOOKING_HOLD_MS = 24 * 60 * 60 * 1000
|
||||||
|
|
||||||
@@ -27,7 +28,21 @@ export const Bookings: CollectionConfig = {
|
|||||||
},
|
},
|
||||||
hooks: {
|
hooks: {
|
||||||
beforeChange: [
|
beforeChange: [
|
||||||
async ({ data, operation, originalDoc }) => {
|
async ({ data, operation, originalDoc, req }) => {
|
||||||
|
const patientRequest = Boolean(req.user) && !isAdminUser(req.user)
|
||||||
|
if (operation === 'create' && patientRequest) {
|
||||||
|
// Patients book only for themselves and cannot choose the price.
|
||||||
|
data.patient = req.user!.id
|
||||||
|
const serviceId = typeof data.service === 'object' && data.service ? data.service.id : data.service
|
||||||
|
const service = serviceId
|
||||||
|
? await req.payload.findByID({ collection: 'services', id: serviceId, depth: 0, req }).catch(() => null)
|
||||||
|
: null
|
||||||
|
if (!service) throw new Error('Услуга не найдена')
|
||||||
|
data.price = Number((service as { price?: unknown }).price) || 0
|
||||||
|
data.status = 'pending'
|
||||||
|
data.paymentStatus = 'unpaid'
|
||||||
|
}
|
||||||
|
|
||||||
if (operation === 'create') {
|
if (operation === 'create') {
|
||||||
data.status = data.status || 'pending'
|
data.status = data.status || 'pending'
|
||||||
data.holdExpiresAt = new Date(Date.now() + BOOKING_HOLD_MS).toISOString()
|
data.holdExpiresAt = new Date(Date.now() + BOOKING_HOLD_MS).toISOString()
|
||||||
@@ -49,6 +64,7 @@ export const Bookings: CollectionConfig = {
|
|||||||
type: 'relationship',
|
type: 'relationship',
|
||||||
relationTo: 'users',
|
relationTo: 'users',
|
||||||
required: true,
|
required: true,
|
||||||
|
access: { update: adminOnlyField },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'doctor',
|
name: 'doctor',
|
||||||
@@ -75,6 +91,10 @@ export const Bookings: CollectionConfig = {
|
|||||||
type: 'select',
|
type: 'select',
|
||||||
required: true,
|
required: true,
|
||||||
defaultValue: 'pending',
|
defaultValue: 'pending',
|
||||||
|
access: {
|
||||||
|
// Patients may only cancel their booking; other transitions are for staff / payment flow.
|
||||||
|
update: ({ req: { user }, data }) => isAdminUser(user) || data?.status === 'cancelled',
|
||||||
|
},
|
||||||
options: [
|
options: [
|
||||||
{ label: 'Ожидает подтверждения (бронь до 24ч)', value: 'pending' },
|
{ label: 'Ожидает подтверждения (бронь до 24ч)', value: 'pending' },
|
||||||
{ label: 'Подтверждена', value: 'confirmed' },
|
{ label: 'Подтверждена', value: 'confirmed' },
|
||||||
@@ -87,6 +107,7 @@ export const Bookings: CollectionConfig = {
|
|||||||
name: 'paymentStatus',
|
name: 'paymentStatus',
|
||||||
type: 'select',
|
type: 'select',
|
||||||
defaultValue: 'unpaid',
|
defaultValue: 'unpaid',
|
||||||
|
access: { create: adminOnlyField, update: adminOnlyField },
|
||||||
options: [
|
options: [
|
||||||
{ label: 'Не оплачено', value: 'unpaid' },
|
{ label: 'Не оплачено', value: 'unpaid' },
|
||||||
{ label: 'Ожидает оплаты', value: 'pending' },
|
{ label: 'Ожидает оплаты', value: 'pending' },
|
||||||
@@ -95,9 +116,9 @@ export const Bookings: CollectionConfig = {
|
|||||||
{ label: 'Возврат', value: 'refunded' },
|
{ label: 'Возврат', value: 'refunded' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{ name: 'price', type: 'number', required: true },
|
{ name: 'price', type: 'number', required: true, access: { update: adminOnlyField } },
|
||||||
{ name: 'holdExpiresAt', type: 'date', admin: { readOnly: true } },
|
{ name: 'holdExpiresAt', type: 'date', admin: { readOnly: true }, access: { update: adminOnlyField } },
|
||||||
{ name: 'confirmedAt', type: 'date' },
|
{ name: 'confirmedAt', type: 'date', access: { create: adminOnlyField, update: adminOnlyField } },
|
||||||
{ name: 'cancelledAt', type: 'date' },
|
{ name: 'cancelledAt', type: 'date' },
|
||||||
{ name: 'cancelReason', type: 'text' },
|
{ name: 'cancelReason', type: 'text' },
|
||||||
{ name: 'rescheduledFrom', type: 'relationship', relationTo: 'bookings' },
|
{ name: 'rescheduledFrom', type: 'relationship', relationTo: 'bookings' },
|
||||||
@@ -106,6 +127,7 @@ export const Bookings: CollectionConfig = {
|
|||||||
name: 'smsReminderScheduled',
|
name: 'smsReminderScheduled',
|
||||||
type: 'checkbox',
|
type: 'checkbox',
|
||||||
defaultValue: false,
|
defaultValue: false,
|
||||||
|
access: { create: adminOnlyField, update: adminOnlyField },
|
||||||
admin: { description: 'Флаг для будущей SMS-рассылки напоминаний' },
|
admin: { description: 'Флаг для будущей SMS-рассылки напоминаний' },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export const Documents: CollectionConfig = {
|
|||||||
}) as Access,
|
}) as Access,
|
||||||
create: ({ req: { user } }) => user?.role === 'admin',
|
create: ({ req: { user } }) => user?.role === 'admin',
|
||||||
update: ({ req: { user } }) => user?.role === 'admin',
|
update: ({ req: { user } }) => user?.role === 'admin',
|
||||||
|
delete: ({ req: { user } }) => user?.role === 'admin',
|
||||||
},
|
},
|
||||||
fields: [
|
fields: [
|
||||||
{ name: 'title', type: 'text', required: true, localized: true, label: 'Название' },
|
{ name: 'title', type: 'text', required: true, localized: true, label: 'Название' },
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { CollectionConfig } from 'payload'
|
import type { CollectionConfig } from 'payload'
|
||||||
import { ADMIN_GROUP } from '../admin/groups'
|
import { ADMIN_GROUP } from '../admin/groups'
|
||||||
|
import { isAdminUser } from '../lib/access'
|
||||||
|
|
||||||
export const Favorites: CollectionConfig = {
|
export const Favorites: CollectionConfig = {
|
||||||
slug: 'favorites',
|
slug: 'favorites',
|
||||||
@@ -18,6 +19,15 @@ export const Favorites: CollectionConfig = {
|
|||||||
return { patient: { equals: user.id } }
|
return { patient: { equals: user.id } }
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
hooks: {
|
||||||
|
beforeChange: [
|
||||||
|
({ data, req }) => {
|
||||||
|
// A patient can only add favorites to their own account.
|
||||||
|
if (req.user && !isAdminUser(req.user)) data.patient = req.user.id
|
||||||
|
return data
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
fields: [
|
fields: [
|
||||||
{ name: 'patient', type: 'relationship', relationTo: 'users', required: true },
|
{ name: 'patient', type: 'relationship', relationTo: 'users', required: true },
|
||||||
{ name: 'doctor', type: 'relationship', relationTo: 'doctors' },
|
{ name: 'doctor', type: 'relationship', relationTo: 'doctors' },
|
||||||
|
|||||||
@@ -0,0 +1,81 @@
|
|||||||
|
import type { CollectionConfig } from 'payload'
|
||||||
|
import { ADMIN_GROUP } from '../admin/groups'
|
||||||
|
import { isValidEmailAddress, isValidFullName, isValidRuPhone, normalizeRuPhone } from '../lib/contact-fields'
|
||||||
|
|
||||||
|
export const Inquiries: CollectionConfig = {
|
||||||
|
slug: 'inquiries',
|
||||||
|
labels: { singular: 'Заявка на запись', plural: 'Заявки на запись' },
|
||||||
|
admin: {
|
||||||
|
group: ADMIN_GROUP.booking,
|
||||||
|
useAsTitle: 'name',
|
||||||
|
defaultColumns: ['name', 'phone', 'email', 'status', 'createdAt'],
|
||||||
|
description: 'Заявки с сайта без выбора времени. Свяжитесь с пациентом и уточните детали.',
|
||||||
|
},
|
||||||
|
access: {
|
||||||
|
create: () => true,
|
||||||
|
read: ({ req: { user } }) => {
|
||||||
|
if (!user) return false
|
||||||
|
if (user.role === 'admin') return true
|
||||||
|
return { patient: { equals: user.id } }
|
||||||
|
},
|
||||||
|
update: ({ req: { user } }) => user?.role === 'admin',
|
||||||
|
delete: ({ req: { user } }) => user?.role === 'admin',
|
||||||
|
},
|
||||||
|
hooks: {
|
||||||
|
beforeValidate: [
|
||||||
|
({ data }) => {
|
||||||
|
if (!data) return data
|
||||||
|
if (typeof data.name === 'string') data.name = data.name.trim().replace(/\s+/g, ' ')
|
||||||
|
if (typeof data.email === 'string') data.email = data.email.trim()
|
||||||
|
if (typeof data.phone === 'string') {
|
||||||
|
const phone = normalizeRuPhone(data.phone)
|
||||||
|
if (phone) data.phone = phone
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
fields: [
|
||||||
|
{
|
||||||
|
name: 'name',
|
||||||
|
type: 'text',
|
||||||
|
required: true,
|
||||||
|
label: 'ФИО',
|
||||||
|
validate: (value: string | null | undefined) =>
|
||||||
|
isValidFullName(String(value ?? '')) ? true : 'Укажите фамилию и имя буквами',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'email',
|
||||||
|
type: 'email',
|
||||||
|
required: true,
|
||||||
|
label: 'E-mail',
|
||||||
|
validate: (value: string | null | undefined) =>
|
||||||
|
isValidEmailAddress(String(value ?? '')) ? true : 'Укажите e-mail в формате name@domain.ru',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'phone',
|
||||||
|
type: 'text',
|
||||||
|
required: true,
|
||||||
|
label: 'Телефон',
|
||||||
|
validate: (value: string | null | undefined) =>
|
||||||
|
isValidRuPhone(String(value ?? '')) ? true : 'Укажите телефон в формате +7 и 10 цифр',
|
||||||
|
},
|
||||||
|
{ name: 'service', type: 'relationship', relationTo: 'services', label: 'Услуга' },
|
||||||
|
{ name: 'doctor', type: 'relationship', relationTo: 'doctors', label: 'Врач' },
|
||||||
|
{ name: 'branch', type: 'relationship', relationTo: 'branches', required: true, label: 'Филиал' },
|
||||||
|
{ name: 'patient', type: 'relationship', relationTo: 'users', label: 'Пациент' },
|
||||||
|
{
|
||||||
|
name: 'status',
|
||||||
|
type: 'select',
|
||||||
|
required: true,
|
||||||
|
defaultValue: 'new',
|
||||||
|
label: 'Статус',
|
||||||
|
options: [
|
||||||
|
{ label: 'Новая', value: 'new' },
|
||||||
|
{ label: 'В работе', value: 'in_progress' },
|
||||||
|
{ label: 'Закрыта', value: 'done' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
timestamps: true,
|
||||||
|
}
|
||||||
@@ -11,8 +11,10 @@ export const Invoices: CollectionConfig = {
|
|||||||
if (user.role === 'admin') return true
|
if (user.role === 'admin') return true
|
||||||
return { patient: { equals: user.id } }
|
return { patient: { equals: user.id } }
|
||||||
},
|
},
|
||||||
create: ({ req: { user } }) => Boolean(user),
|
// Invoices are issued by the payment route (server-side) or staff only.
|
||||||
|
create: ({ req: { user } }) => user?.role === 'admin',
|
||||||
update: ({ req: { user } }) => user?.role === 'admin',
|
update: ({ req: { user } }) => user?.role === 'admin',
|
||||||
|
delete: ({ req: { user } }) => user?.role === 'admin',
|
||||||
},
|
},
|
||||||
fields: [
|
fields: [
|
||||||
{ name: 'number', type: 'text', required: true, unique: true },
|
{ name: 'number', type: 'text', required: true, unique: true },
|
||||||
|
|||||||
@@ -1,5 +1,11 @@
|
|||||||
import type { CollectionConfig } from 'payload'
|
import fs from 'node:fs/promises'
|
||||||
|
import path from 'node:path'
|
||||||
|
import type { Access, CollectionConfig } from 'payload'
|
||||||
import { ADMIN_GROUP } from '../admin/groups'
|
import { ADMIN_GROUP } from '../admin/groups'
|
||||||
|
import { adminOnlyField, isAdminUser } from '../lib/access'
|
||||||
|
import { fileExists, MEDIA_DIR, ORIGINALS_DIR, safeJoin } from '../lib/media-paths'
|
||||||
|
|
||||||
|
type UploadEdits = { crop?: unknown; heightInPixels?: unknown; widthInPixels?: unknown }
|
||||||
|
|
||||||
export const Media: CollectionConfig = {
|
export const Media: CollectionConfig = {
|
||||||
slug: 'media',
|
slug: 'media',
|
||||||
@@ -7,6 +13,9 @@ export const Media: CollectionConfig = {
|
|||||||
admin: { group: ADMIN_GROUP.content },
|
admin: { group: ADMIN_GROUP.content },
|
||||||
upload: {
|
upload: {
|
||||||
staticDir: 'media',
|
staticDir: 'media',
|
||||||
|
// Built-in image editor: crop, size in pixels and focal point ("Редактировать изображение").
|
||||||
|
crop: true,
|
||||||
|
focalPoint: true,
|
||||||
mimeTypes: [
|
mimeTypes: [
|
||||||
'image/*',
|
'image/*',
|
||||||
'video/mp4',
|
'video/mp4',
|
||||||
@@ -15,10 +24,52 @@ export const Media: CollectionConfig = {
|
|||||||
'application/pdf',
|
'application/pdf',
|
||||||
'application/msword',
|
'application/msword',
|
||||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||||
|
'application/rtf',
|
||||||
|
'text/rtf',
|
||||||
|
'application/x-rtf',
|
||||||
|
'text/richtext',
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
access: {
|
access: {
|
||||||
read: () => true,
|
// Public site assets have no owner. Patient files (receipts, tax certificates, results)
|
||||||
|
// are visible only to their owner and admins — this also guards /api/media/file/<name>.
|
||||||
|
read: (({ req: { user } }) => {
|
||||||
|
if (isAdminUser(user)) return true
|
||||||
|
if (!user) return { owner: { exists: false } }
|
||||||
|
return { or: [{ owner: { exists: false } }, { owner: { equals: user.id } }] }
|
||||||
|
}) as Access,
|
||||||
|
create: ({ req: { user } }) => isAdminUser(user),
|
||||||
|
update: ({ req: { user } }) => isAdminUser(user),
|
||||||
|
delete: ({ req: { user } }) => isAdminUser(user),
|
||||||
|
},
|
||||||
|
hooks: {
|
||||||
|
beforeOperation: [
|
||||||
|
// Payload's crop overwrites the file in place. Before the first crop/resize keep a copy
|
||||||
|
// of the original in media/originals/ so it can be restored.
|
||||||
|
async ({ args, operation, req }) => {
|
||||||
|
const id = (args as { id?: number | string }).id
|
||||||
|
if (operation !== 'update' || id == null) return args
|
||||||
|
const edits = (req.query?.uploadEdits ?? {}) as UploadEdits
|
||||||
|
if (!edits.crop && !edits.heightInPixels && !edits.widthInPixels) return args
|
||||||
|
|
||||||
|
const doc = await req.payload.findByID({
|
||||||
|
collection: 'media',
|
||||||
|
id,
|
||||||
|
depth: 0,
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
})
|
||||||
|
if (!doc?.filename || doc.originalFile) return args
|
||||||
|
|
||||||
|
const source = safeJoin(MEDIA_DIR, doc.filename)
|
||||||
|
if (!source || !(await fileExists(source))) return args
|
||||||
|
await fs.mkdir(ORIGINALS_DIR, { recursive: true })
|
||||||
|
const originalName = `${doc.id}-${doc.filename}`
|
||||||
|
await fs.copyFile(source, path.join(ORIGINALS_DIR, originalName))
|
||||||
|
args.data = { ...(args.data ?? {}), originalFile: originalName }
|
||||||
|
return args
|
||||||
|
},
|
||||||
|
],
|
||||||
},
|
},
|
||||||
fields: [
|
fields: [
|
||||||
{
|
{
|
||||||
@@ -26,5 +77,47 @@ export const Media: CollectionConfig = {
|
|||||||
type: 'text',
|
type: 'text',
|
||||||
localized: true,
|
localized: true,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'owner',
|
||||||
|
type: 'relationship',
|
||||||
|
relationTo: 'users',
|
||||||
|
label: 'Владелец (приватный файл пациента)',
|
||||||
|
admin: {
|
||||||
|
description: 'Если указан пациент, файл доступен только ему и администраторам. Пусто — публичный файл сайта.',
|
||||||
|
},
|
||||||
|
access: {
|
||||||
|
create: adminOnlyField,
|
||||||
|
update: adminOnlyField,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'originalFile',
|
||||||
|
type: 'text',
|
||||||
|
label: 'Оригинал до редактирования',
|
||||||
|
admin: { hidden: true, readOnly: true },
|
||||||
|
access: { read: adminOnlyField, create: adminOnlyField, update: adminOnlyField },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// Absolute path of the file on the CMS server (admins only, never stored).
|
||||||
|
name: 'storagePath',
|
||||||
|
type: 'text',
|
||||||
|
virtual: true,
|
||||||
|
admin: { hidden: true },
|
||||||
|
access: { read: adminOnlyField },
|
||||||
|
hooks: {
|
||||||
|
afterRead: [
|
||||||
|
({ siblingData }) =>
|
||||||
|
typeof siblingData?.filename === 'string' ? safeJoin(MEDIA_DIR, siblingData.filename) : null,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'fileLocation',
|
||||||
|
type: 'ui',
|
||||||
|
admin: {
|
||||||
|
position: 'sidebar',
|
||||||
|
components: { Field: '/components/admin/MediaLocation#MediaLocation' },
|
||||||
|
},
|
||||||
|
},
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,22 @@ export const Specialties: CollectionConfig = {
|
|||||||
{ name: 'title', type: 'text', required: true, localized: true },
|
{ name: 'title', type: 'text', required: true, localized: true },
|
||||||
{ name: 'slug', type: 'text', required: true, unique: true },
|
{ name: 'slug', type: 'text', required: true, unique: true },
|
||||||
{ name: 'description', type: 'textarea', localized: true },
|
{ name: 'description', type: 'textarea', localized: true },
|
||||||
{ name: 'icon', type: 'text', admin: { description: 'Имя иконки Untitled UI' } },
|
{
|
||||||
|
name: 'icon',
|
||||||
|
type: 'text',
|
||||||
|
label: 'Иконка',
|
||||||
|
admin: {
|
||||||
|
description: 'Встроенная иконка (Untitled UI). Если ниже загружена своя картинка, используется она.',
|
||||||
|
components: { Field: '/components/admin/IconPicker#IconPicker' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'iconImage',
|
||||||
|
type: 'upload',
|
||||||
|
relationTo: 'media',
|
||||||
|
label: 'Своя иконка (SVG или PNG)',
|
||||||
|
filterOptions: { mimeType: { contains: 'image' } },
|
||||||
|
},
|
||||||
{ name: 'sortOrder', type: 'number', defaultValue: 0 },
|
{ name: 'sortOrder', type: 'number', defaultValue: 0 },
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import type { CollectionConfig } from 'payload'
|
import type { CollectionConfig } from 'payload'
|
||||||
import { ADMIN_GROUP } from '../admin/groups'
|
import { ADMIN_GROUP } from '../admin/groups'
|
||||||
|
import { isAdminUser } from '../lib/access'
|
||||||
|
|
||||||
export const Users: CollectionConfig = {
|
export const Users: CollectionConfig = {
|
||||||
slug: 'users',
|
slug: 'users',
|
||||||
@@ -8,7 +9,7 @@ export const Users: CollectionConfig = {
|
|||||||
tokenExpiration: 60 * 60 * 24 * 7,
|
tokenExpiration: 60 * 60 * 24 * 7,
|
||||||
cookies: {
|
cookies: {
|
||||||
sameSite: 'Lax',
|
sameSite: 'Lax',
|
||||||
secure: process.env.NODE_ENV === 'production',
|
secure: false,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
admin: {
|
admin: {
|
||||||
@@ -33,6 +34,16 @@ export const Users: CollectionConfig = {
|
|||||||
type: 'select',
|
type: 'select',
|
||||||
required: true,
|
required: true,
|
||||||
defaultValue: 'patient',
|
defaultValue: 'patient',
|
||||||
|
access: {
|
||||||
|
// Only admins may assign roles. The very first account (admin UI "create first user")
|
||||||
|
// is allowed so a fresh install can bootstrap its administrator.
|
||||||
|
create: async ({ req }) => {
|
||||||
|
if (isAdminUser(req.user)) return true
|
||||||
|
const { totalDocs } = await req.payload.count({ collection: 'users', overrideAccess: true })
|
||||||
|
return totalDocs === 0
|
||||||
|
},
|
||||||
|
update: ({ req: { user } }) => isAdminUser(user),
|
||||||
|
},
|
||||||
options: [
|
options: [
|
||||||
{ label: 'Пациент', value: 'patient' },
|
{ label: 'Пациент', value: 'patient' },
|
||||||
{ label: 'Врач', value: 'doctor' },
|
{ label: 'Врач', value: 'doctor' },
|
||||||
|
|||||||
@@ -0,0 +1,116 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import React, { useMemo, useState } from 'react'
|
||||||
|
import type { TextFieldClientComponent } from 'payload'
|
||||||
|
import { FieldDescription, FieldError, FieldLabel, useField } from '@payloadcms/ui'
|
||||||
|
import * as Icons from '@untitledui/icons'
|
||||||
|
import { iconComponentName, iconKebabName, MEDICAL_ICONS, resolveIconName } from '../../lib/icons'
|
||||||
|
|
||||||
|
type IconComponent = React.ComponentType<{ size?: number; className?: string; 'aria-hidden'?: boolean }>
|
||||||
|
const ICONS = Icons as unknown as Record<string, IconComponent>
|
||||||
|
const ALL_NAMES = Object.keys(ICONS)
|
||||||
|
.filter((name) => /^[A-Z]/.test(name) && typeof ICONS[name] !== 'undefined')
|
||||||
|
.sort()
|
||||||
|
|
||||||
|
const tile = (selected: boolean): React.CSSProperties => ({
|
||||||
|
width: 48,
|
||||||
|
height: 48,
|
||||||
|
borderRadius: 10,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
cursor: 'pointer',
|
||||||
|
border: selected ? '2px solid var(--theme-success-500)' : '1px solid var(--theme-elevation-150)',
|
||||||
|
background: selected ? 'var(--theme-success-50)' : 'var(--theme-elevation-0)',
|
||||||
|
color: 'var(--theme-elevation-800)',
|
||||||
|
padding: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
/** Visual icon picker for «Направления»: preview as on the site, curated medical set and search. */
|
||||||
|
export const IconPicker: TextFieldClientComponent = ({ field, path, readOnly }) => {
|
||||||
|
const { value, setValue, errorMessage, showError } = useField<string>({ path })
|
||||||
|
const [query, setQuery] = useState('')
|
||||||
|
const current = resolveIconName(value, ICONS)
|
||||||
|
const Current = current ? ICONS[current] : null
|
||||||
|
|
||||||
|
const results = useMemo(() => {
|
||||||
|
const q = query.trim().toLowerCase().replace(/\s+/g, '-')
|
||||||
|
if (!q) return MEDICAL_ICONS.map((n) => iconComponentName(n)).filter((n) => n in ICONS)
|
||||||
|
return ALL_NAMES.filter((n) => iconKebabName(n).includes(q)).slice(0, 80)
|
||||||
|
}, [query])
|
||||||
|
|
||||||
|
const label = typeof field.label === 'string' ? field.label : 'Иконка'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="field-type text" style={{ marginBottom: 24 }}>
|
||||||
|
<FieldLabel label={label} path={path} />
|
||||||
|
<div style={{ display: 'flex', gap: 20, alignItems: 'flex-start', flexWrap: 'wrap' }}>
|
||||||
|
<div style={{ textAlign: 'center' }}>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
width: 88,
|
||||||
|
height: 88,
|
||||||
|
borderRadius: 16,
|
||||||
|
background: 'var(--theme-elevation-100)',
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
color: 'var(--theme-elevation-900)',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{Current ? <Current size={44} aria-hidden /> : <span style={{ fontSize: 12 }}>нет</span>}
|
||||||
|
</div>
|
||||||
|
<p style={{ fontSize: 11, margin: '6px 0 0', color: 'var(--theme-elevation-500)' }}>
|
||||||
|
{current ? iconKebabName(current) : value ? `«${value}» не найдена` : 'не выбрана'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div style={{ flex: 1, minWidth: 280 }}>
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
placeholder="Поиск по всем иконкам: heart, eye, user…"
|
||||||
|
value={query}
|
||||||
|
disabled={Boolean(readOnly)}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
style={{ marginBottom: 10 }}
|
||||||
|
/>
|
||||||
|
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
|
||||||
|
{results.map((name) => {
|
||||||
|
const Icon = ICONS[name]
|
||||||
|
const kebab = iconKebabName(name)
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={name}
|
||||||
|
type="button"
|
||||||
|
title={kebab}
|
||||||
|
aria-label={kebab}
|
||||||
|
aria-pressed={current === name}
|
||||||
|
disabled={Boolean(readOnly)}
|
||||||
|
onClick={() => setValue(kebab)}
|
||||||
|
style={tile(current === name)}
|
||||||
|
>
|
||||||
|
<Icon size={22} aria-hidden />
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
{!results.length ? (
|
||||||
|
<span style={{ fontSize: 13, color: 'var(--theme-elevation-500)' }}>Ничего не найдено</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
{value ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn--style-secondary btn--size-small"
|
||||||
|
style={{ marginTop: 10 }}
|
||||||
|
disabled={Boolean(readOnly)}
|
||||||
|
onClick={() => setValue('')}
|
||||||
|
>
|
||||||
|
Убрать иконку
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<FieldError message={errorMessage} path={path} showError={showError} />
|
||||||
|
{field.admin?.description ? <FieldDescription description={field.admin.description} path={path} /> : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import React, { useEffect, useState } from 'react'
|
||||||
|
import { toast, useField } from '@payloadcms/ui'
|
||||||
|
import { formatBytes, MediaCard } from './media-ui/MediaCard'
|
||||||
|
|
||||||
|
type Resolved = {
|
||||||
|
url: string
|
||||||
|
previewUrl: string
|
||||||
|
localPath: string | null
|
||||||
|
where: string
|
||||||
|
exists: boolean
|
||||||
|
size: number | null
|
||||||
|
remote: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIME_BY_EXT: Record<string, string> = {
|
||||||
|
jpg: 'image/jpeg',
|
||||||
|
jpeg: 'image/jpeg',
|
||||||
|
png: 'image/png',
|
||||||
|
webp: 'image/webp',
|
||||||
|
gif: 'image/gif',
|
||||||
|
svg: 'image/svg+xml',
|
||||||
|
avif: 'image/avif',
|
||||||
|
mp4: 'video/mp4',
|
||||||
|
webm: 'video/webm',
|
||||||
|
mov: 'video/quicktime',
|
||||||
|
}
|
||||||
|
|
||||||
|
function guessMime(url: string) {
|
||||||
|
const ext = url.split(/[?#]/)[0].split('.').pop()?.toLowerCase() || ''
|
||||||
|
return MIME_BY_EXT[ext] || 'image/jpeg'
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shown under legacy "URL фото" fields: preview of the linked file, where it really lives
|
||||||
|
* (apps/web/public/... or the remote address) and a button that moves it into the media library
|
||||||
|
* so it gets the normal preview and editor.
|
||||||
|
*/
|
||||||
|
export function LegacyUrlPreview({
|
||||||
|
path,
|
||||||
|
field,
|
||||||
|
}: {
|
||||||
|
path: string
|
||||||
|
field?: { admin?: { custom?: { uploadField?: string } } }
|
||||||
|
}) {
|
||||||
|
const { value, setValue } = useField<string>({ path })
|
||||||
|
const uploadName = field?.admin?.custom?.uploadField
|
||||||
|
const uploadPath = uploadName ? path.replace(/[^.]+$/, uploadName) : ''
|
||||||
|
const upload = useField<unknown>({ path: uploadPath || path })
|
||||||
|
const [resolved, setResolved] = useState<Resolved | null>(null)
|
||||||
|
const [error, setError] = useState('')
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const url = (value || '').trim()
|
||||||
|
setResolved(null)
|
||||||
|
setError('')
|
||||||
|
if (!url) return
|
||||||
|
const timer = setTimeout(async () => {
|
||||||
|
const res = await fetch(`/api/custom/media-tools/resolve-url?url=${encodeURIComponent(url)}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
})
|
||||||
|
const data = await res.json().catch(() => ({}))
|
||||||
|
if (res.ok) setResolved(data as Resolved)
|
||||||
|
else setError(data.error || 'Не удалось разобрать ссылку')
|
||||||
|
}, 300)
|
||||||
|
return () => clearTimeout(timer)
|
||||||
|
}, [value])
|
||||||
|
|
||||||
|
if (!value) return null
|
||||||
|
if (error) return <p style={{ fontSize: 12, color: 'var(--theme-error-500)' }}>{error}</p>
|
||||||
|
if (!resolved) return null
|
||||||
|
|
||||||
|
const where = resolved.remote ? 'Внешняя ссылка' : resolved.exists ? 'Где лежит файл' : 'Файл не найден'
|
||||||
|
|
||||||
|
return (
|
||||||
|
<MediaCard
|
||||||
|
info={{
|
||||||
|
previewUrl: resolved.exists ? resolved.previewUrl : null,
|
||||||
|
publicUrl: resolved.previewUrl,
|
||||||
|
storagePath: null,
|
||||||
|
mimeType: guessMime(resolved.url),
|
||||||
|
filesize: resolved.size,
|
||||||
|
}}
|
||||||
|
actions={
|
||||||
|
uploadPath ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn--style-primary btn--size-small"
|
||||||
|
style={{ margin: 0 }}
|
||||||
|
disabled={busy || (!resolved.remote && !resolved.exists)}
|
||||||
|
onClick={async () => {
|
||||||
|
setBusy(true)
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/custom/media-tools/import-url', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'include',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ url: resolved.url }),
|
||||||
|
})
|
||||||
|
const data = await res.json().catch(() => ({}))
|
||||||
|
if (!res.ok) throw new Error(data.error || 'Не удалось перенести файл')
|
||||||
|
upload.setValue(data.doc.id)
|
||||||
|
setValue('')
|
||||||
|
toast.success('Файл перенесён в медиатеку. Сохраните документ.')
|
||||||
|
} catch (e) {
|
||||||
|
toast.error(e instanceof Error ? e.message : 'Ошибка')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Перенести в медиатеку
|
||||||
|
</button>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
notice={
|
||||||
|
<div style={{ marginTop: 10, display: 'grid', gap: 4, fontSize: 12 }}>
|
||||||
|
<span style={{ color: 'var(--theme-elevation-500)' }}>{where}</span>
|
||||||
|
<code style={{ wordBreak: 'break-all' }}>
|
||||||
|
{resolved.remote ? resolved.url : resolved.localPath || resolved.where}
|
||||||
|
</code>
|
||||||
|
{resolved.size ? <span style={{ color: 'var(--theme-elevation-500)' }}>{formatBytes(resolved.size)}</span> : null}
|
||||||
|
<span style={{ color: 'var(--theme-elevation-500)' }}>
|
||||||
|
Это старая ссылка на файл. Чтобы обрезать фото или поменять точку фокуса, перенесите его в медиатеку.
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import React, { useCallback, useEffect, useState } from 'react'
|
||||||
|
import { toast, useDocumentInfo } from '@payloadcms/ui'
|
||||||
|
import { CopyRow, fetchMediaDoc, mediaInfo, restoreOriginal, type MediaDoc } from './media-ui/MediaCard'
|
||||||
|
|
||||||
|
/** Sidebar of a media file: exact file location, public address and "restore original". */
|
||||||
|
export function MediaLocation() {
|
||||||
|
const { id, lastUpdateTime } = useDocumentInfo() as { id?: number | string; lastUpdateTime?: number }
|
||||||
|
const [doc, setDoc] = useState<MediaDoc | null>(null)
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
if (id == null) return setDoc(null)
|
||||||
|
setDoc(await fetchMediaDoc(id))
|
||||||
|
}, [id])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load, lastUpdateTime])
|
||||||
|
|
||||||
|
if (!doc) return null
|
||||||
|
const info = mediaInfo(doc)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={{ display: 'grid', gap: 10, marginBottom: 24 }}>
|
||||||
|
{info.storagePath ? <CopyRow title="Где лежит файл" value={info.storagePath} /> : null}
|
||||||
|
{info.publicUrl ? <CopyRow title="Адрес на сайте" value={info.publicUrl} /> : null}
|
||||||
|
{info.originalPath ? (
|
||||||
|
<>
|
||||||
|
<CopyRow title="Оригинал до редактирования" value={info.originalPath} />
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn--style-secondary btn--size-small"
|
||||||
|
style={{ margin: 0 }}
|
||||||
|
disabled={busy}
|
||||||
|
onClick={async () => {
|
||||||
|
setBusy(true)
|
||||||
|
try {
|
||||||
|
await restoreOriginal(doc.id)
|
||||||
|
toast.success('Оригинал восстановлен, обновите страницу')
|
||||||
|
await load()
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : 'Ошибка')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Вернуть оригинал
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import React, { useCallback, useEffect, useState } from 'react'
|
||||||
|
import { toast, useDocumentDrawer, useField } from '@payloadcms/ui'
|
||||||
|
import { fetchMediaDoc, MediaCard, mediaInfo, restoreOriginal, type MediaDoc } from './media-ui/MediaCard'
|
||||||
|
|
||||||
|
function relationId(value: unknown): number | string | null {
|
||||||
|
if (value == null || value === '') return null
|
||||||
|
if (typeof value === 'object') {
|
||||||
|
const id = (value as { id?: unknown; value?: unknown }).id ?? (value as { value?: unknown }).value
|
||||||
|
return typeof id === 'string' || typeof id === 'number' ? id : null
|
||||||
|
}
|
||||||
|
return typeof value === 'string' || typeof value === 'number' ? value : null
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shown under every upload field: large preview, where the file lives on the server,
|
||||||
|
* its public address, and quick access to the image editor (crop / size / focal point).
|
||||||
|
*/
|
||||||
|
export function MediaPreview({ path }: { path: string }) {
|
||||||
|
const { value } = useField<unknown>({ path })
|
||||||
|
const id = relationId(value)
|
||||||
|
const [doc, setDoc] = useState<MediaDoc | null>(null)
|
||||||
|
const [busy, setBusy] = useState(false)
|
||||||
|
|
||||||
|
const load = useCallback(async () => {
|
||||||
|
if (id == null) return setDoc(null)
|
||||||
|
setDoc(await fetchMediaDoc(id))
|
||||||
|
}, [id])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
void load()
|
||||||
|
}, [load])
|
||||||
|
|
||||||
|
const [EditDrawer, , { openDrawer }] = useDocumentDrawer({
|
||||||
|
collectionSlug: 'media',
|
||||||
|
id: id == null ? undefined : Number(id),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (id == null || !doc) return null
|
||||||
|
const info = mediaInfo(doc)
|
||||||
|
const isImage = Boolean(doc.mimeType?.startsWith('image/'))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<MediaCard
|
||||||
|
info={info}
|
||||||
|
actions={
|
||||||
|
<>
|
||||||
|
<button type="button" className="btn btn--style-primary btn--size-small" style={{ margin: 0 }} onClick={openDrawer}>
|
||||||
|
{isImage ? 'Редактировать изображение' : 'Открыть файл'}
|
||||||
|
</button>
|
||||||
|
{doc.originalFile ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn--style-secondary btn--size-small"
|
||||||
|
style={{ margin: 0 }}
|
||||||
|
disabled={busy}
|
||||||
|
onClick={async () => {
|
||||||
|
setBusy(true)
|
||||||
|
try {
|
||||||
|
await restoreOriginal(doc.id)
|
||||||
|
toast.success('Оригинал восстановлен')
|
||||||
|
await load()
|
||||||
|
} catch (error) {
|
||||||
|
toast.error(error instanceof Error ? error.message : 'Ошибка')
|
||||||
|
} finally {
|
||||||
|
setBusy(false)
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Вернуть оригинал
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
notice={
|
||||||
|
isImage ? (
|
||||||
|
<p style={{ margin: '10px 0 0', fontSize: 12, color: 'var(--theme-elevation-500)' }}>
|
||||||
|
В редакторе нажмите «Редактировать изображение»: кадрирование, размер в пикселях и точка фокуса.
|
||||||
|
Оригинал сохраняется перед первой обрезкой.
|
||||||
|
</p>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
<EditDrawer onSave={() => void load()} />
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
'use client'
|
||||||
|
|
||||||
|
import React, { useState } from 'react'
|
||||||
|
|
||||||
|
export type MediaInfo = {
|
||||||
|
previewUrl?: string | null
|
||||||
|
publicUrl?: string | null
|
||||||
|
storagePath?: string | null
|
||||||
|
originalPath?: string | null
|
||||||
|
mimeType?: string | null
|
||||||
|
width?: number | null
|
||||||
|
height?: number | null
|
||||||
|
filesize?: number | null
|
||||||
|
focalX?: number | null
|
||||||
|
focalY?: number | null
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatBytes(bytes?: number | null) {
|
||||||
|
if (!bytes) return ''
|
||||||
|
if (bytes < 1024) return `${bytes} Б`
|
||||||
|
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} КБ`
|
||||||
|
return `${(bytes / 1024 / 1024).toFixed(1)} МБ`
|
||||||
|
}
|
||||||
|
|
||||||
|
const box: React.CSSProperties = {
|
||||||
|
border: '1px solid var(--theme-elevation-150)',
|
||||||
|
borderRadius: 8,
|
||||||
|
padding: 12,
|
||||||
|
marginTop: 8,
|
||||||
|
background: 'var(--theme-elevation-0)',
|
||||||
|
}
|
||||||
|
|
||||||
|
const pathRow: React.CSSProperties = {
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
gap: 8,
|
||||||
|
fontFamily: 'var(--font-mono, monospace)',
|
||||||
|
fontSize: 12,
|
||||||
|
background: 'var(--theme-elevation-50)',
|
||||||
|
borderRadius: 4,
|
||||||
|
padding: '6px 8px',
|
||||||
|
wordBreak: 'break-all',
|
||||||
|
}
|
||||||
|
|
||||||
|
const label: React.CSSProperties = { fontSize: 12, color: 'var(--theme-elevation-500)', margin: '0 0 4px' }
|
||||||
|
|
||||||
|
export function CopyRow({ title, value }: { title: string; value: string }) {
|
||||||
|
const [copied, setCopied] = useState(false)
|
||||||
|
return (
|
||||||
|
<div>
|
||||||
|
<p style={label}>{title}</p>
|
||||||
|
<div style={pathRow}>
|
||||||
|
<span style={{ flex: 1 }}>{value}</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn--style-secondary btn--size-small"
|
||||||
|
style={{ margin: 0, flexShrink: 0 }}
|
||||||
|
onClick={() => {
|
||||||
|
navigator.clipboard?.writeText(value).then(() => {
|
||||||
|
setCopied(true)
|
||||||
|
setTimeout(() => setCopied(false), 1500)
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{copied ? 'Скопировано' : 'Копировать'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Large preview with focal point, file facts and exact file locations. */
|
||||||
|
export function MediaCard({
|
||||||
|
info,
|
||||||
|
actions,
|
||||||
|
notice,
|
||||||
|
}: {
|
||||||
|
info: MediaInfo
|
||||||
|
actions?: React.ReactNode
|
||||||
|
notice?: React.ReactNode
|
||||||
|
}) {
|
||||||
|
const isImage = Boolean(info.mimeType?.startsWith('image/'))
|
||||||
|
const isVideo = Boolean(info.mimeType?.startsWith('video/'))
|
||||||
|
const facts = [
|
||||||
|
info.width && info.height ? `${info.width} × ${info.height}` : '',
|
||||||
|
info.mimeType ? info.mimeType.split('/')[1]?.toUpperCase() : '',
|
||||||
|
formatBytes(info.filesize),
|
||||||
|
].filter(Boolean)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div style={box}>
|
||||||
|
<div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'flex-start' }}>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: 'relative',
|
||||||
|
width: 220,
|
||||||
|
maxWidth: '100%',
|
||||||
|
borderRadius: 6,
|
||||||
|
overflow: 'hidden',
|
||||||
|
background: 'var(--theme-elevation-100)',
|
||||||
|
minHeight: 120,
|
||||||
|
display: 'flex',
|
||||||
|
alignItems: 'center',
|
||||||
|
justifyContent: 'center',
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{info.previewUrl && isImage ? (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
<img src={info.previewUrl} alt="" style={{ display: 'block', width: '100%', height: 'auto' }} />
|
||||||
|
) : info.previewUrl && isVideo ? (
|
||||||
|
<video src={info.previewUrl} controls preload="metadata" style={{ display: 'block', width: '100%' }} />
|
||||||
|
) : (
|
||||||
|
<span style={{ fontSize: 13, color: 'var(--theme-elevation-500)', padding: 16 }}>
|
||||||
|
{info.mimeType ? `Файл ${info.mimeType}` : 'Нет превью'}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{isImage && info.focalX != null && info.focalY != null ? (
|
||||||
|
<span
|
||||||
|
title="Точка фокуса"
|
||||||
|
style={{
|
||||||
|
position: 'absolute',
|
||||||
|
left: `${info.focalX}%`,
|
||||||
|
top: `${info.focalY}%`,
|
||||||
|
width: 14,
|
||||||
|
height: 14,
|
||||||
|
marginLeft: -7,
|
||||||
|
marginTop: -7,
|
||||||
|
borderRadius: '50%',
|
||||||
|
border: '2px solid #fff',
|
||||||
|
boxShadow: '0 0 0 1px rgba(0,0,0,.5)',
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
<div style={{ flex: 1, minWidth: 260, display: 'grid', gap: 10 }}>
|
||||||
|
{facts.length ? (
|
||||||
|
<p style={{ margin: 0, fontSize: 13, color: 'var(--theme-elevation-700)' }}>{facts.join(' · ')}</p>
|
||||||
|
) : null}
|
||||||
|
{info.storagePath ? <CopyRow title="Где лежит файл" value={info.storagePath} /> : null}
|
||||||
|
{info.publicUrl ? <CopyRow title="Адрес на сайте" value={info.publicUrl} /> : null}
|
||||||
|
{info.originalPath ? <CopyRow title="Оригинал до редактирования" value={info.originalPath} /> : null}
|
||||||
|
{actions ? <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>{actions}</div> : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{notice}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MediaDoc = {
|
||||||
|
id: number | string
|
||||||
|
url?: string | null
|
||||||
|
filename?: string | null
|
||||||
|
mimeType?: string | null
|
||||||
|
width?: number | null
|
||||||
|
height?: number | null
|
||||||
|
filesize?: number | null
|
||||||
|
focalX?: number | null
|
||||||
|
focalY?: number | null
|
||||||
|
storagePath?: string | null
|
||||||
|
originalFile?: string | null
|
||||||
|
updatedAt?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fetchMediaDoc(id: number | string): Promise<MediaDoc | null> {
|
||||||
|
const res = await fetch(`/api/media/${encodeURIComponent(String(id))}?depth=0`, {
|
||||||
|
credentials: 'include',
|
||||||
|
cache: 'no-store',
|
||||||
|
})
|
||||||
|
if (!res.ok) return null
|
||||||
|
return (await res.json()) as MediaDoc
|
||||||
|
}
|
||||||
|
|
||||||
|
export function mediaInfo(doc: MediaDoc): MediaInfo {
|
||||||
|
const bust = doc.updatedAt ? `?v=${encodeURIComponent(doc.updatedAt)}` : ''
|
||||||
|
const origin = typeof window !== 'undefined' ? window.location.origin : ''
|
||||||
|
const storagePath = doc.storagePath || null
|
||||||
|
return {
|
||||||
|
previewUrl: doc.url ? `${doc.url}${bust}` : null,
|
||||||
|
publicUrl: doc.url ? (doc.url.startsWith('http') ? doc.url : `${origin}${doc.url}`) : null,
|
||||||
|
storagePath,
|
||||||
|
originalPath:
|
||||||
|
doc.originalFile && storagePath
|
||||||
|
? storagePath.replace(/[^/\\]+$/, `originals/${doc.originalFile}`)
|
||||||
|
: null,
|
||||||
|
mimeType: doc.mimeType,
|
||||||
|
width: doc.width,
|
||||||
|
height: doc.height,
|
||||||
|
filesize: doc.filesize,
|
||||||
|
focalX: doc.focalX,
|
||||||
|
focalY: doc.focalY,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function restoreOriginal(id: number | string) {
|
||||||
|
const res = await fetch('/api/custom/media-tools/restore-original', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'include',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ id }),
|
||||||
|
})
|
||||||
|
const data = await res.json().catch(() => ({}))
|
||||||
|
if (!res.ok) throw new Error(data.error || 'Не удалось восстановить оригинал')
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import type { FieldAccess, PayloadRequest } from 'payload'
|
||||||
|
|
||||||
|
export function isAdminUser(user: PayloadRequest['user'] | null | undefined): boolean {
|
||||||
|
return (user as { role?: string } | null | undefined)?.role === 'admin'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Field can be written only by admins (or by trusted server code via overrideAccess). */
|
||||||
|
export const adminOnlyField: FieldAccess = ({ req: { user } }) => isAdminUser(user)
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[A-Za-z0-9-]{2,}$/
|
||||||
|
|
||||||
|
export function isValidFullName(value: string) {
|
||||||
|
const name = value.trim().replace(/\s+/g, " ")
|
||||||
|
if (name.length < 3) return false
|
||||||
|
const parts = name.split(" ").filter(Boolean)
|
||||||
|
if (parts.length < 2) return false
|
||||||
|
return /^[\p{L}][\p{L}\s'-]*$/u.test(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isValidEmailAddress(value: string) {
|
||||||
|
return EMAIL_RE.test(value.trim())
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeRuPhone(value: string) {
|
||||||
|
let digits = value.replace(/\D/g, "")
|
||||||
|
if (digits.startsWith("8")) digits = `7${digits.slice(1)}`
|
||||||
|
if (!digits.startsWith("7")) digits = `7${digits}`
|
||||||
|
digits = digits.slice(0, 11)
|
||||||
|
return digits.length === 11 ? `+${digits}` : ""
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isValidRuPhone(value: string) {
|
||||||
|
return /^\+7\d{10}$/.test(normalizeRuPhone(value))
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { sql } from '@payloadcms/db-postgres'
|
||||||
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
|
type DrizzleAdapter = {
|
||||||
|
drizzle: { execute: (query: unknown) => Promise<unknown> }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function exec(payload: Payload, query: unknown) {
|
||||||
|
const adapter = payload.db as DrizzleAdapter
|
||||||
|
await adapter.drizzle.execute(query)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function ensureInquiriesSchema(payload: Payload) {
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
DO $$ BEGIN
|
||||||
|
CREATE TYPE enum_inquiries_status AS ENUM ('new', 'in_progress', 'done');
|
||||||
|
EXCEPTION
|
||||||
|
WHEN duplicate_object THEN NULL;
|
||||||
|
END $$
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
CREATE TABLE IF NOT EXISTS inquiries (
|
||||||
|
id serial PRIMARY KEY,
|
||||||
|
name character varying NOT NULL,
|
||||||
|
email character varying NOT NULL,
|
||||||
|
phone character varying NOT NULL,
|
||||||
|
service_id integer,
|
||||||
|
doctor_id integer,
|
||||||
|
branch_id integer NOT NULL,
|
||||||
|
status enum_inquiries_status DEFAULT 'new' NOT NULL,
|
||||||
|
updated_at timestamp(3) with time zone DEFAULT now() NOT NULL,
|
||||||
|
created_at timestamp(3) with time zone DEFAULT now() NOT NULL
|
||||||
|
)
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
ALTER TABLE inquiries
|
||||||
|
ADD COLUMN IF NOT EXISTS patient_id integer
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
CREATE INDEX IF NOT EXISTS inquiries_patient_idx ON inquiries (patient_id)
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
ALTER TABLE payload_locked_documents_rels
|
||||||
|
ADD COLUMN IF NOT EXISTS inquiries_id integer
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
CREATE INDEX IF NOT EXISTS payload_locked_documents_rels_inquiries_id_idx
|
||||||
|
ON payload_locked_documents_rels (inquiries_id)
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE payload_locked_documents_rels
|
||||||
|
ADD CONSTRAINT payload_locked_documents_rels_inquiries_fk
|
||||||
|
FOREIGN KEY (inquiries_id) REFERENCES inquiries(id) ON DELETE CASCADE;
|
||||||
|
EXCEPTION WHEN duplicate_object THEN NULL;
|
||||||
|
END $$
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { sql } from '@payloadcms/db-postgres'
|
||||||
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
|
type DrizzleAdapter = {
|
||||||
|
drizzle: { execute: (query: unknown) => Promise<unknown> }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function exec(payload: Payload, query: unknown) {
|
||||||
|
const adapter = payload.db as DrizzleAdapter
|
||||||
|
await adapter.drizzle.execute(query)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adds media.owner_id (private patient files) and marks existing receipts/tax PDFs as private. */
|
||||||
|
export async function ensureMediaSchema(payload: Payload) {
|
||||||
|
// Copy of the file kept before the first crop/resize in the admin image editor.
|
||||||
|
await exec(payload, sql`ALTER TABLE media ADD COLUMN IF NOT EXISTS original_file character varying`)
|
||||||
|
|
||||||
|
// «Направления»: custom uploaded icon next to the built-in icon name.
|
||||||
|
await exec(payload, sql`ALTER TABLE specialties ADD COLUMN IF NOT EXISTS icon_image_id integer`)
|
||||||
|
await exec(payload, sql`CREATE INDEX IF NOT EXISTS specialties_icon_image_idx ON specialties (icon_image_id)`)
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE specialties
|
||||||
|
ADD CONSTRAINT specialties_icon_image_id_media_id_fk
|
||||||
|
FOREIGN KEY (icon_image_id) REFERENCES media(id) ON DELETE SET NULL;
|
||||||
|
EXCEPTION
|
||||||
|
WHEN duplicate_object THEN NULL;
|
||||||
|
END $$
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
|
||||||
|
await exec(payload, sql`ALTER TABLE media ADD COLUMN IF NOT EXISTS owner_id integer`)
|
||||||
|
await exec(payload, sql`CREATE INDEX IF NOT EXISTS media_owner_idx ON media (owner_id)`)
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
DO $$ BEGIN
|
||||||
|
ALTER TABLE media
|
||||||
|
ADD CONSTRAINT media_owner_id_users_id_fk
|
||||||
|
FOREIGN KEY (owner_id) REFERENCES users(id) ON DELETE SET NULL;
|
||||||
|
EXCEPTION
|
||||||
|
WHEN duplicate_object THEN NULL;
|
||||||
|
END $$
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
|
||||||
|
// Backfill: files attached to patient documents belong to that patient.
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
UPDATE media m
|
||||||
|
SET owner_id = d.patient_id
|
||||||
|
FROM documents d
|
||||||
|
WHERE d.file_id = m.id
|
||||||
|
AND d.patient_id IS NOT NULL
|
||||||
|
AND COALESCE(d.is_public, false) = false
|
||||||
|
AND m.owner_id IS NULL
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
// Backfill: receipts / tax certificates referenced by invoices.
|
||||||
|
await exec(
|
||||||
|
payload,
|
||||||
|
sql`
|
||||||
|
UPDATE media m
|
||||||
|
SET owner_id = i.patient_id
|
||||||
|
FROM invoices i
|
||||||
|
WHERE (i.receipt_pdf_id = m.id OR i.tax_deduction_pdf_id = m.id)
|
||||||
|
AND i.patient_id IS NOT NULL
|
||||||
|
AND m.owner_id IS NULL
|
||||||
|
`,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
/**
|
||||||
|
* Specialty icons: names are kebab-case Untitled UI icon names ("activity-heart", "beaker-01").
|
||||||
|
* Both the CMS picker and the site resolve stored values with resolveIconName().
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Curated medical icons shown first in the CMS picker. */
|
||||||
|
export const MEDICAL_ICONS = [
|
||||||
|
'medical-cross',
|
||||||
|
'medical-circle',
|
||||||
|
'medical-square',
|
||||||
|
'heart',
|
||||||
|
'heart-rounded',
|
||||||
|
'activity-heart',
|
||||||
|
'activity',
|
||||||
|
'heart-hand',
|
||||||
|
'scan',
|
||||||
|
'microscope',
|
||||||
|
'beaker-01',
|
||||||
|
'beaker-02',
|
||||||
|
'thermometer-01',
|
||||||
|
'droplets-01',
|
||||||
|
'virus',
|
||||||
|
'eye',
|
||||||
|
'atom-01',
|
||||||
|
'cpu-chip-01',
|
||||||
|
'zap',
|
||||||
|
'shield-plus',
|
||||||
|
'file-heart-01',
|
||||||
|
'clipboard-check',
|
||||||
|
'user-01',
|
||||||
|
'users-01',
|
||||||
|
'hand',
|
||||||
|
'stars-01',
|
||||||
|
] as const
|
||||||
|
|
||||||
|
/** Old values from seeds / manual input that are not exact icon names. */
|
||||||
|
const ALIASES: Record<string, string> = {
|
||||||
|
flash: 'zap',
|
||||||
|
beaker: 'beaker-01',
|
||||||
|
'cpu-chip': 'cpu-chip-01',
|
||||||
|
flask: 'beaker-01',
|
||||||
|
stethoscope: 'medical-cross',
|
||||||
|
brain: 'cpu-chip-01',
|
||||||
|
thermometer: 'thermometer-01',
|
||||||
|
user: 'user-01',
|
||||||
|
users: 'users-01',
|
||||||
|
}
|
||||||
|
|
||||||
|
export function iconComponentName(kebab: string) {
|
||||||
|
return kebab
|
||||||
|
.split('-')
|
||||||
|
.filter(Boolean)
|
||||||
|
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
||||||
|
.join('')
|
||||||
|
}
|
||||||
|
|
||||||
|
export function iconKebabName(componentName: string) {
|
||||||
|
return componentName
|
||||||
|
.replace(/([a-z])([A-Z0-9])/g, '$1-$2')
|
||||||
|
.replace(/([0-9])([A-Z])/g, '$1-$2')
|
||||||
|
.toLowerCase()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns the component name for a stored icon value, or null if it doesn't exist. */
|
||||||
|
export function resolveIconName(value: string | null | undefined, available: Record<string, unknown>) {
|
||||||
|
const raw = (value || '').trim().toLowerCase()
|
||||||
|
if (!raw) return null
|
||||||
|
for (const candidate of [raw, ALIASES[raw], `${raw}-01`]) {
|
||||||
|
if (!candidate) continue
|
||||||
|
const name = iconComponentName(candidate)
|
||||||
|
if (name in available) return name
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import { randomBytes } from 'crypto'
|
||||||
|
import type { Payload } from 'payload'
|
||||||
|
import { buildInquiryEmail } from './inquiry-email'
|
||||||
|
import { sendNotification } from './notifications'
|
||||||
|
|
||||||
|
function siteUrl() {
|
||||||
|
return (process.env.CORS_ORIGINS || 'http://localhost:3000').split(',')[0]?.trim() || 'http://localhost:3000'
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateCabinetPassword() {
|
||||||
|
const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789'
|
||||||
|
const bytes = randomBytes(10)
|
||||||
|
let out = 'Mk-'
|
||||||
|
for (const byte of bytes) out += alphabet[byte % alphabet.length]
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
function relRecord(value: unknown): Record<string, unknown> | null {
|
||||||
|
return value && typeof value === 'object' ? (value as Record<string, unknown>) : null
|
||||||
|
}
|
||||||
|
|
||||||
|
function relText(value: unknown, key: string) {
|
||||||
|
const rec = relRecord(value)
|
||||||
|
const raw = rec?.[key]
|
||||||
|
return typeof raw === 'string' ? raw.trim() : ''
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function findOrCreatePatient(
|
||||||
|
payload: Payload,
|
||||||
|
input: { email: string; name: string; phone: string },
|
||||||
|
): Promise<{ id: string | number; created: boolean; password?: string }> {
|
||||||
|
const email = input.email.trim().toLowerCase()
|
||||||
|
const existing = await payload.find({
|
||||||
|
collection: 'users',
|
||||||
|
where: { email: { equals: email } },
|
||||||
|
limit: 1,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
if (existing.docs[0]) {
|
||||||
|
const user = existing.docs[0]
|
||||||
|
if (!user.phone && input.phone) {
|
||||||
|
await payload.update({
|
||||||
|
collection: 'users',
|
||||||
|
id: user.id,
|
||||||
|
overrideAccess: true,
|
||||||
|
data: { phone: input.phone },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return { id: user.id, created: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
const password = generateCabinetPassword()
|
||||||
|
const created = await payload.create({
|
||||||
|
collection: 'users',
|
||||||
|
overrideAccess: true,
|
||||||
|
data: {
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
fullName: input.name,
|
||||||
|
phone: input.phone,
|
||||||
|
role: 'patient',
|
||||||
|
emailOptIn: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return { id: created.id, created: true, password }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function notifyInquiry(
|
||||||
|
payload: Payload,
|
||||||
|
input: {
|
||||||
|
inquiryId: string | number
|
||||||
|
patientName: string
|
||||||
|
email: string
|
||||||
|
phone: string
|
||||||
|
cabinetCreated: boolean
|
||||||
|
password?: string
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const inquiry = await payload.findByID({
|
||||||
|
collection: 'inquiries',
|
||||||
|
id: input.inquiryId,
|
||||||
|
depth: 2,
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
const message = buildInquiryEmail({
|
||||||
|
patientName: input.patientName,
|
||||||
|
email: input.email,
|
||||||
|
phone: input.phone,
|
||||||
|
serviceTitle: relText(inquiry.service, 'title').replace(/^\d+(?:\.\d+)*\.?\s+/, '').trim(),
|
||||||
|
servicePrice: Number(relRecord(inquiry.service)?.price) || undefined,
|
||||||
|
doctorName: relText(inquiry.doctor, 'fullName'),
|
||||||
|
branchName: relText(inquiry.branch, 'name'),
|
||||||
|
branchAddress: relText(inquiry.branch, 'address'),
|
||||||
|
cabinetCreated: input.cabinetCreated,
|
||||||
|
password: input.password,
|
||||||
|
loginUrl: `${siteUrl()}/ru/login`,
|
||||||
|
})
|
||||||
|
await sendNotification(payload, {
|
||||||
|
channel: 'email',
|
||||||
|
to: input.email,
|
||||||
|
subject: message.subject,
|
||||||
|
body: message.text,
|
||||||
|
html: message.html,
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
function escapeHtml(text: string) {
|
||||||
|
return text
|
||||||
|
.replace(/&/g, '&')
|
||||||
|
.replace(/</g, '<')
|
||||||
|
.replace(/>/g, '>')
|
||||||
|
.replace(/"/g, '"')
|
||||||
|
}
|
||||||
|
|
||||||
|
function row(label: string, value: string) {
|
||||||
|
if (!value.trim()) return ''
|
||||||
|
return `<tr>
|
||||||
|
<td style="padding:8px 0;color:#64748b;font-size:14px;width:40%;vertical-align:top;">${escapeHtml(label)}</td>
|
||||||
|
<td style="padding:8px 0;color:#0f172a;font-size:14px;font-weight:600;">${escapeHtml(value)}</td>
|
||||||
|
</tr>`
|
||||||
|
}
|
||||||
|
|
||||||
|
export type InquiryEmailInput = {
|
||||||
|
patientName: string
|
||||||
|
email: string
|
||||||
|
phone: string
|
||||||
|
serviceTitle?: string
|
||||||
|
servicePrice?: number
|
||||||
|
doctorName?: string
|
||||||
|
branchName?: string
|
||||||
|
branchAddress?: string
|
||||||
|
cabinetCreated: boolean
|
||||||
|
password?: string
|
||||||
|
loginUrl: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatPrice(amount?: number) {
|
||||||
|
if (amount == null || !Number.isFinite(amount) || amount <= 0) return ''
|
||||||
|
return new Intl.NumberFormat('ru-RU', {
|
||||||
|
style: 'currency',
|
||||||
|
currency: 'RUB',
|
||||||
|
maximumFractionDigits: 0,
|
||||||
|
}).format(amount)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildInquiryEmail(input: InquiryEmailInput) {
|
||||||
|
const firstName = input.patientName.trim().split(/\s+/)[1] || input.patientName.trim()
|
||||||
|
const price = formatPrice(input.servicePrice)
|
||||||
|
const subject = input.cabinetCreated
|
||||||
|
? 'Личный кабинет и заявка на запись — МОНИКИ'
|
||||||
|
: 'Ваша заявка на запись принята — МОНИКИ'
|
||||||
|
|
||||||
|
const cabinetBlock = input.cabinetCreated
|
||||||
|
? `
|
||||||
|
<div style="margin:24px 0;padding:20px;border-radius:16px;background:#eef6fb;border:1px solid #cfe3f2;">
|
||||||
|
<p style="margin:0 0 8px;font-size:16px;font-weight:700;color:#163a56;">Для вас создан личный кабинет</p>
|
||||||
|
<p style="margin:0 0 16px;font-size:14px;line-height:1.55;color:#334155;">
|
||||||
|
В кабинете будут ваши заявки, документы и счета. Войти можно по почте, которую вы указали в заявке.
|
||||||
|
</p>
|
||||||
|
<table role="presentation" width="100%" cellspacing="0" cellpadding="0">
|
||||||
|
${row('Логин', input.email)}
|
||||||
|
${input.password ? row('Пароль', input.password) : ''}
|
||||||
|
</table>
|
||||||
|
<p style="margin:16px 0 0;">
|
||||||
|
<a href="${escapeHtml(input.loginUrl)}" style="display:inline-block;background:#1b4b73;color:#ffffff;text-decoration:none;padding:12px 20px;border-radius:999px;font-size:14px;font-weight:700;">
|
||||||
|
Войти в личный кабинет
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
</div>`
|
||||||
|
: `
|
||||||
|
<p style="margin:0 0 20px;font-size:14px;line-height:1.55;color:#334155;">
|
||||||
|
Заявка сохранена в вашем личном кабинете. Войти можно по адресу
|
||||||
|
<a href="${escapeHtml(input.loginUrl)}" style="color:#1b4b73;font-weight:700;">${escapeHtml(input.loginUrl)}</a>.
|
||||||
|
</p>`
|
||||||
|
|
||||||
|
const html = `<!doctype html>
|
||||||
|
<html lang="ru">
|
||||||
|
<body style="margin:0;padding:0;background:#f4f7fb;font-family:'Segoe UI',Arial,sans-serif;">
|
||||||
|
<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#f4f7fb;padding:24px 12px;">
|
||||||
|
<tr>
|
||||||
|
<td align="center">
|
||||||
|
<table role="presentation" width="640" cellspacing="0" cellpadding="0" style="max-width:640px;width:100%;background:#ffffff;border-radius:20px;overflow:hidden;box-shadow:0 10px 30px rgba(15,23,42,0.06);">
|
||||||
|
<tr>
|
||||||
|
<td style="background:linear-gradient(135deg,#163a56,#1b4b73);padding:28px 32px;color:#ffffff;">
|
||||||
|
<p style="margin:0;font-size:12px;letter-spacing:.12em;text-transform:uppercase;opacity:.8;">КДЦ МОНИКИ</p>
|
||||||
|
<h1 style="margin:8px 0 0;font-size:24px;line-height:1.3;">Заявка принята</h1>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
<tr>
|
||||||
|
<td style="padding:32px;">
|
||||||
|
<p style="margin:0 0 16px;font-size:16px;color:#0f172a;">Здравствуйте, ${escapeHtml(firstName)}!</p>
|
||||||
|
<p style="margin:0 0 20px;font-size:15px;line-height:1.6;color:#334155;">
|
||||||
|
Спасибо, что выбрали платные медицинские услуги КДЦ МОНИКИ им. М. Ф. Владимирского.
|
||||||
|
Мы получили вашу заявку и свяжемся с вами, чтобы уточнить удобную дату и время.
|
||||||
|
</p>
|
||||||
|
<div style="padding:4px 20px 8px;border-radius:16px;background:#f8fafc;border:1px solid #e2e8f0;">
|
||||||
|
<p style="margin:16px 0 4px;font-size:13px;font-weight:700;letter-spacing:.04em;text-transform:uppercase;color:#1b4b73;">Сводка заявки</p>
|
||||||
|
<table role="presentation" width="100%" cellspacing="0" cellpadding="0">
|
||||||
|
${row('Пациент', input.patientName)}
|
||||||
|
${row('Услуга', input.serviceTitle || '')}
|
||||||
|
${row('Стоимость', price)}
|
||||||
|
${row('Врач', input.doctorName || '')}
|
||||||
|
${row('Филиал', input.branchName || '')}
|
||||||
|
${row('Адрес', input.branchAddress || '')}
|
||||||
|
${row('Телефон для связи', input.phone)}
|
||||||
|
${row('E-mail', input.email)}
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
${cabinetBlock}
|
||||||
|
<div style="margin-top:8px;padding:20px;border-radius:16px;background:#fff8ef;border:1px solid #f1e0c3;">
|
||||||
|
<p style="margin:0 0 10px;font-size:16px;font-weight:700;color:#9a6700;">Полезная информация</p>
|
||||||
|
<ul style="margin:0;padding-left:18px;color:#57534e;font-size:14px;line-height:1.65;">
|
||||||
|
<li>Возьмите паспорт. Если есть полис ОМС или результаты обследований — их тоже полезно иметь при себе.</li>
|
||||||
|
<li>Приходите за 10–15 минут до приёма, чтобы оформить документы на стойке регистрации.</li>
|
||||||
|
<li>Точное время визита подтвердит администратор: +7 (499) 674-07-09 или 122.</li>
|
||||||
|
<li>Основной филиал: ул. Щепкина, 61/2, метро «Проспект Мира».</li>
|
||||||
|
<li>Если планы изменятся, напишите нам или позвоните — заявку можно уточнить или перенести.</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
<p style="margin:24px 0 0;font-size:13px;line-height:1.6;color:#64748b;">
|
||||||
|
С заботой о вашем здоровье,<br>
|
||||||
|
<strong style="color:#163a56;">КДЦ МОНИКИ</strong><br>
|
||||||
|
Платные медицинские услуги
|
||||||
|
</p>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
</table>
|
||||||
|
</body>
|
||||||
|
</html>`
|
||||||
|
|
||||||
|
const textLines = [
|
||||||
|
`Здравствуйте, ${firstName}!`,
|
||||||
|
'',
|
||||||
|
'Мы получили вашу заявку на запись в КДЦ МОНИКИ и свяжемся с вами, чтобы уточнить дату и время.',
|
||||||
|
'',
|
||||||
|
input.serviceTitle ? `Услуга: ${input.serviceTitle}` : '',
|
||||||
|
price ? `Стоимость: ${price}` : '',
|
||||||
|
input.doctorName ? `Врач: ${input.doctorName}` : '',
|
||||||
|
input.branchName ? `Филиал: ${input.branchName}` : '',
|
||||||
|
input.branchAddress ? `Адрес: ${input.branchAddress}` : '',
|
||||||
|
`Телефон: ${input.phone}`,
|
||||||
|
`E-mail: ${input.email}`,
|
||||||
|
'',
|
||||||
|
input.cabinetCreated
|
||||||
|
? `Для вас создан личный кабинет.\nЛогин: ${input.email}\nПароль: ${input.password || ''}\nВход: ${input.loginUrl}`
|
||||||
|
: `Личный кабинет: ${input.loginUrl}`,
|
||||||
|
'',
|
||||||
|
'Возьмите паспорт, приходите за 10–15 минут. Телефон: +7 (499) 674-07-09, 122.',
|
||||||
|
].filter(Boolean)
|
||||||
|
|
||||||
|
return { subject, html, text: textLines.join('\n') }
|
||||||
|
}
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import fs from 'node:fs/promises'
|
||||||
|
import path from 'node:path'
|
||||||
|
import { fileExists, MEDIA_DIR, safeJoin, siteOrigin, WEB_PUBLIC_DIR } from './media-paths'
|
||||||
|
|
||||||
|
export type ResolvedLegacyUrl = {
|
||||||
|
url: string
|
||||||
|
/** Where the browser can load a preview from. */
|
||||||
|
previewUrl: string
|
||||||
|
/** Absolute file path on the server, if the link points to a local file. */
|
||||||
|
localPath: string | null
|
||||||
|
/** Human-readable location, e.g. "apps/web/public/hero/building.jpg". */
|
||||||
|
where: string
|
||||||
|
exists: boolean
|
||||||
|
size: number | null
|
||||||
|
remote: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
const MEDIA_FILE_PREFIX = '/api/media/file/'
|
||||||
|
|
||||||
|
export async function resolveLegacyUrl(raw: string): Promise<ResolvedLegacyUrl | null> {
|
||||||
|
const url = raw.trim()
|
||||||
|
if (!url) return null
|
||||||
|
|
||||||
|
if (/^https?:\/\//i.test(url)) {
|
||||||
|
return { url, previewUrl: url, localPath: null, where: url, exists: true, size: null, remote: true }
|
||||||
|
}
|
||||||
|
if (!url.startsWith('/')) return null
|
||||||
|
|
||||||
|
const clean = decodeURIComponent(url.split(/[?#]/)[0])
|
||||||
|
let localPath: string | null
|
||||||
|
let previewUrl: string
|
||||||
|
if (clean.startsWith(MEDIA_FILE_PREFIX)) {
|
||||||
|
localPath = safeJoin(MEDIA_DIR, clean.slice(MEDIA_FILE_PREFIX.length))
|
||||||
|
previewUrl = url
|
||||||
|
} else {
|
||||||
|
localPath = safeJoin(WEB_PUBLIC_DIR, clean)
|
||||||
|
previewUrl = `${siteOrigin()}${url}`
|
||||||
|
}
|
||||||
|
const exists = localPath ? await fileExists(localPath) : false
|
||||||
|
const size = exists && localPath ? (await fs.stat(localPath)).size : null
|
||||||
|
return {
|
||||||
|
url,
|
||||||
|
previewUrl,
|
||||||
|
localPath,
|
||||||
|
where: localPath ? path.relative(path.resolve(process.cwd(), '..', '..'), localPath) : url,
|
||||||
|
exists,
|
||||||
|
size,
|
||||||
|
remote: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const MAX_REMOTE_BYTES = 50 * 1024 * 1024
|
||||||
|
|
||||||
|
export async function fetchRemoteFile(url: string) {
|
||||||
|
const res = await fetch(url, { signal: AbortSignal.timeout(20000), redirect: 'follow' })
|
||||||
|
if (!res.ok) throw new Error(`Не удалось скачать файл (${res.status})`)
|
||||||
|
const mimetype = (res.headers.get('content-type') || '').split(';')[0].trim()
|
||||||
|
if (!/^(image|video)\//.test(mimetype)) throw new Error('По ссылке не картинка и не видео')
|
||||||
|
const length = Number(res.headers.get('content-length') || 0)
|
||||||
|
if (length > MAX_REMOTE_BYTES) throw new Error('Файл больше 50 МБ')
|
||||||
|
const data = Buffer.from(await res.arrayBuffer())
|
||||||
|
if (data.length > MAX_REMOTE_BYTES) throw new Error('Файл больше 50 МБ')
|
||||||
|
const name = decodeURIComponent(new URL(url).pathname.split('/').pop() || 'image') || 'image'
|
||||||
|
return { data, mimetype, name, size: data.length }
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import type { CollectionConfig, Field, GlobalConfig } from 'payload'
|
||||||
|
|
||||||
|
const MEDIA_PREVIEW = '/components/admin/MediaPreview#MediaPreview'
|
||||||
|
const LEGACY_URL_PREVIEW = '/components/admin/LegacyUrlPreview#LegacyUrlPreview'
|
||||||
|
|
||||||
|
/** Legacy link fields whose upload sibling is not simply the name without "Url". */
|
||||||
|
const LEGACY_SIBLING_OVERRIDES: Record<string, string> = { imageUrl: 'cover' }
|
||||||
|
|
||||||
|
type AnyField = Field & {
|
||||||
|
name?: string
|
||||||
|
type: string
|
||||||
|
relationTo?: string | string[]
|
||||||
|
fields?: Field[]
|
||||||
|
tabs?: Array<{ fields: Field[] }>
|
||||||
|
blocks?: Array<{ fields: Field[] }>
|
||||||
|
admin?: Record<string, unknown> & {
|
||||||
|
components?: Record<string, unknown>
|
||||||
|
custom?: Record<string, unknown>
|
||||||
|
condition?: (data: unknown, siblingData: Record<string, unknown>, ctx: unknown) => boolean
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function enhanceList(fields: Field[]) {
|
||||||
|
const list = fields as AnyField[]
|
||||||
|
const uploads = new Set(
|
||||||
|
list.filter((f) => f.type === 'upload' && f.relationTo === 'media' && f.name).map((f) => f.name as string),
|
||||||
|
)
|
||||||
|
|
||||||
|
for (const field of list) {
|
||||||
|
if (field.type === 'upload' && field.relationTo === 'media') {
|
||||||
|
const components = (field.admin?.components ?? {}) as Record<string, unknown>
|
||||||
|
const after = Array.isArray(components.afterInput) ? components.afterInput : []
|
||||||
|
field.admin = {
|
||||||
|
...(field.admin ?? {}),
|
||||||
|
components: { ...components, afterInput: [...after, MEDIA_PREVIEW] },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (field.type === 'text' && field.name?.endsWith('Url')) {
|
||||||
|
const base = field.name.slice(0, -3)
|
||||||
|
const sibling = uploads.has(base)
|
||||||
|
? base
|
||||||
|
: LEGACY_SIBLING_OVERRIDES[field.name] && uploads.has(LEGACY_SIBLING_OVERRIDES[field.name])
|
||||||
|
? LEGACY_SIBLING_OVERRIDES[field.name]
|
||||||
|
: null
|
||||||
|
if (sibling) {
|
||||||
|
const name = field.name
|
||||||
|
const prevCondition = field.admin?.condition
|
||||||
|
const components = (field.admin?.components ?? {}) as Record<string, unknown>
|
||||||
|
const after = Array.isArray(components.afterInput) ? components.afterInput : []
|
||||||
|
field.admin = {
|
||||||
|
...(field.admin ?? {}),
|
||||||
|
description: 'Старая ссылка на файл. Новое фото загружайте в поле выше; эту ссылку можно перенести в медиатеку.',
|
||||||
|
custom: { ...(field.admin?.custom ?? {}), uploadField: sibling },
|
||||||
|
components: { ...components, afterInput: [...after, LEGACY_URL_PREVIEW] },
|
||||||
|
// One image control per picture: the legacy link is only shown while it still holds a value.
|
||||||
|
condition: (data, siblingData, ctx) =>
|
||||||
|
Boolean(siblingData?.[name]) && (prevCondition ? prevCondition(data, siblingData, ctx) : true),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(field.fields)) enhanceList(field.fields)
|
||||||
|
if (Array.isArray(field.tabs)) field.tabs.forEach((tab) => enhanceList(tab.fields))
|
||||||
|
if (Array.isArray(field.blocks)) field.blocks.forEach((block) => enhanceList(block.fields))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adds the media preview / file location UI to every image field of the given configs. */
|
||||||
|
export function withMediaPreviews<T extends CollectionConfig | GlobalConfig>(configs: T[]): T[] {
|
||||||
|
for (const config of configs) enhanceList(config.fields)
|
||||||
|
return configs
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import fs from 'node:fs/promises'
|
||||||
|
import path from 'node:path'
|
||||||
|
|
||||||
|
/** Payload resolves the relative upload staticDir ('media') against the process working directory. */
|
||||||
|
export const MEDIA_DIR = path.resolve(process.cwd(), 'media')
|
||||||
|
export const ORIGINALS_DIR = path.join(MEDIA_DIR, 'originals')
|
||||||
|
|
||||||
|
/** Public folder of the site app, where legacy image links like /hero/building.jpg live. */
|
||||||
|
export const WEB_PUBLIC_DIR = path.resolve(
|
||||||
|
process.env.WEB_PUBLIC_DIR || path.join(process.cwd(), '..', 'web', 'public'),
|
||||||
|
)
|
||||||
|
|
||||||
|
export function siteOrigin() {
|
||||||
|
return (process.env.CORS_ORIGINS || 'http://localhost:3000').split(',')[0]?.trim() || 'http://localhost:3000'
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Joins a user-supplied relative path to a base dir, refusing anything that escapes it. */
|
||||||
|
export function safeJoin(base: string, relative: string): string | null {
|
||||||
|
const resolved = path.resolve(base, '.' + path.posix.normalize('/' + relative.replace(/\\/g, '/')))
|
||||||
|
return resolved === base || resolved.startsWith(base + path.sep) ? resolved : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function fileExists(p: string) {
|
||||||
|
try {
|
||||||
|
return (await fs.stat(p)).isFile()
|
||||||
|
} catch {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ export type NotifyInput = {
|
|||||||
to: string
|
to: string
|
||||||
subject: string
|
subject: string
|
||||||
body: string
|
body: string
|
||||||
|
html?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
function escapeHtml(text: string) {
|
function escapeHtml(text: string) {
|
||||||
@@ -36,7 +37,7 @@ export async function sendNotification(
|
|||||||
const result = await payload.sendEmail({
|
const result = await payload.sendEmail({
|
||||||
to: input.to,
|
to: input.to,
|
||||||
subject: input.subject,
|
subject: input.subject,
|
||||||
html: `<p>${escapeHtml(input.body)}</p>`,
|
html: input.html || `<p>${escapeHtml(input.body)}</p>`,
|
||||||
text: input.body,
|
text: input.body,
|
||||||
})
|
})
|
||||||
if (result && typeof result === 'object' && 'skipped' in result && result.skipped) {
|
if (result && typeof result === 'object' && 'skipped' in result && result.skipped) {
|
||||||
|
|||||||
+13
-2
@@ -1,3 +1,5 @@
|
|||||||
|
import { createHmac, timingSafeEqual } from 'crypto'
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SBP (СБП) acquiring adapter.
|
* SBP (СБП) acquiring adapter.
|
||||||
* Provider credentials come from env; real bank API can be plugged in later.
|
* Provider credentials come from env; real bank API can be plugged in later.
|
||||||
@@ -36,9 +38,18 @@ export async function createSbpPayment(
|
|||||||
throw new Error('SBP provider integration: set adapter implementation for your bank')
|
throw new Error('SBP provider integration: set adapter implementation for your bank')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies the payment webhook signature: hex HMAC-SHA256 of the raw body with SBP_WEBHOOK_SECRET.
|
||||||
|
* Adjust the header/algorithm to the acquiring bank's spec when the real provider is connected.
|
||||||
|
* Without a secret, unsigned calls are accepted only outside production (local mock payments).
|
||||||
|
*/
|
||||||
export function verifySbpWebhook(signature: string | null, rawBody: string): boolean {
|
export function verifySbpWebhook(signature: string | null, rawBody: string): boolean {
|
||||||
const secret = process.env.SBP_WEBHOOK_SECRET
|
const secret = process.env.SBP_WEBHOOK_SECRET
|
||||||
if (!secret) return process.env.NODE_ENV !== 'production'
|
if (!secret) return process.env.NODE_ENV !== 'production'
|
||||||
// Replace with HMAC verification from your acquiring docs
|
if (!signature) return false
|
||||||
return Boolean(signature && rawBody)
|
const expected = createHmac('sha256', secret).update(rawBody, 'utf8').digest('hex')
|
||||||
|
const given = signature.trim().toLowerCase().replace(/^sha256=/, '')
|
||||||
|
const a = Buffer.from(expected, 'utf8')
|
||||||
|
const b = Buffer.from(given, 'utf8')
|
||||||
|
return a.length === b.length && timingSafeEqual(a, b)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ import { Documents } from './collections/Documents'
|
|||||||
import { Favorites } from './collections/Favorites'
|
import { Favorites } from './collections/Favorites'
|
||||||
import { Notifications } from './collections/Notifications'
|
import { Notifications } from './collections/Notifications'
|
||||||
import { Invoices } from './collections/Invoices'
|
import { Invoices } from './collections/Invoices'
|
||||||
|
import { Inquiries } from './collections/Inquiries'
|
||||||
import { Settings } from './globals/Settings'
|
import { Settings } from './globals/Settings'
|
||||||
import { settingsResendAdapter } from './lib/email'
|
import { settingsResendAdapter } from './lib/email'
|
||||||
import { ensureSettingsSchema } from './lib/ensure-settings-schema'
|
import { ensureSettingsSchema } from './lib/ensure-settings-schema'
|
||||||
@@ -31,6 +32,9 @@ import { ensurePagesSchema } from './lib/ensure-pages-schema'
|
|||||||
import { ensureDocumentsSchema } from './lib/ensure-documents-schema'
|
import { ensureDocumentsSchema } from './lib/ensure-documents-schema'
|
||||||
import { ensureServicesSchema } from './lib/ensure-services-schema'
|
import { ensureServicesSchema } from './lib/ensure-services-schema'
|
||||||
import { ensureBannersSchema } from './lib/ensure-banners-schema'
|
import { ensureBannersSchema } from './lib/ensure-banners-schema'
|
||||||
|
import { ensureInquiriesSchema } from './lib/ensure-inquiries-schema'
|
||||||
|
import { ensureMediaSchema } from './lib/ensure-media-schema'
|
||||||
|
import { withMediaPreviews } from './lib/media-fields'
|
||||||
|
|
||||||
const filename = fileURLToPath(import.meta.url)
|
const filename = fileURLToPath(import.meta.url)
|
||||||
const dirname = path.dirname(filename)
|
const dirname = path.dirname(filename)
|
||||||
@@ -52,13 +56,14 @@ export default buildConfig({
|
|||||||
titleSuffix: ' — МОНИКИ Платные услуги',
|
titleSuffix: ' — МОНИКИ Платные услуги',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
collections: [
|
collections: withMediaPreviews([
|
||||||
Branches,
|
Branches,
|
||||||
Specialties,
|
Specialties,
|
||||||
Doctors,
|
Doctors,
|
||||||
Services,
|
Services,
|
||||||
Schedules,
|
Schedules,
|
||||||
Bookings,
|
Bookings,
|
||||||
|
Inquiries,
|
||||||
Invoices,
|
Invoices,
|
||||||
Reviews,
|
Reviews,
|
||||||
Pages,
|
Pages,
|
||||||
@@ -71,8 +76,8 @@ export default buildConfig({
|
|||||||
Documents,
|
Documents,
|
||||||
Favorites,
|
Favorites,
|
||||||
Notifications,
|
Notifications,
|
||||||
],
|
]),
|
||||||
globals: [Settings],
|
globals: withMediaPreviews([Settings]),
|
||||||
email: settingsResendAdapter,
|
email: settingsResendAdapter,
|
||||||
onInit: async (payload) => {
|
onInit: async (payload) => {
|
||||||
await ensureSettingsSchema(payload)
|
await ensureSettingsSchema(payload)
|
||||||
@@ -80,6 +85,8 @@ export default buildConfig({
|
|||||||
await ensureDocumentsSchema(payload)
|
await ensureDocumentsSchema(payload)
|
||||||
await ensureServicesSchema(payload)
|
await ensureServicesSchema(payload)
|
||||||
await ensureBannersSchema(payload)
|
await ensureBannersSchema(payload)
|
||||||
|
await ensureInquiriesSchema(payload)
|
||||||
|
await ensureMediaSchema(payload)
|
||||||
try {
|
try {
|
||||||
const { seedSitePages } = await import('./seed/site-pages')
|
const { seedSitePages } = await import('./seed/site-pages')
|
||||||
await seedSitePages(payload)
|
await seedSitePages(payload)
|
||||||
@@ -92,6 +99,12 @@ export default buildConfig({
|
|||||||
} catch (err) {
|
} catch (err) {
|
||||||
payload.logger.error({ err }, 'Failed to seed public documents')
|
payload.logger.error({ err }, 'Failed to seed public documents')
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
const { seedGalleryPhotos } = await import('./seed/gallery-photos')
|
||||||
|
await seedGalleryPhotos(payload)
|
||||||
|
} catch (err) {
|
||||||
|
payload.logger.error({ err }, 'Failed to seed gallery photos')
|
||||||
|
}
|
||||||
},
|
},
|
||||||
editor: lexicalEditor(),
|
editor: lexicalEditor(),
|
||||||
i18n: {
|
i18n: {
|
||||||
@@ -110,7 +123,8 @@ export default buildConfig({
|
|||||||
}),
|
}),
|
||||||
sharp,
|
sharp,
|
||||||
cors: allowedOrigins,
|
cors: allowedOrigins,
|
||||||
csrf: allowedOrigins,
|
// Empty list: do not drop the session cookie when Origin is missing or atypical (HTTP IP:port admin).
|
||||||
|
csrf: [],
|
||||||
localization: {
|
localization: {
|
||||||
locales: [
|
locales: [
|
||||||
{ code: 'ru', label: 'Русский' },
|
{ code: 'ru', label: 'Русский' },
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 493 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 397 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 535 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 125 KiB |
@@ -0,0 +1,110 @@
|
|||||||
|
import 'dotenv/config'
|
||||||
|
import fs from 'fs'
|
||||||
|
import path from 'path'
|
||||||
|
import { fileURLToPath } from 'url'
|
||||||
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
|
export const GALLERY_PHOTOS = [
|
||||||
|
{
|
||||||
|
filename: 'photo-6.jpg',
|
||||||
|
mime: 'image/jpeg',
|
||||||
|
title: 'Ресепшен КДЦ МОНИКИ',
|
||||||
|
alt: 'Стойка регистрации КДЦ МОНИКИ',
|
||||||
|
sortOrder: 10,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
filename: 'photo69.jpeg',
|
||||||
|
mime: 'image/jpeg',
|
||||||
|
title: 'Администратор на ресепшене',
|
||||||
|
alt: 'Администратор КДЦ МОНИКИ за стойкой регистрации',
|
||||||
|
sortOrder: 20,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
filename: 'photo68.jpg',
|
||||||
|
mime: 'image/jpeg',
|
||||||
|
title: 'Зона ожидания',
|
||||||
|
alt: 'Зал ожидания отделения платных медицинских услуг КДЦ МОНИКИ',
|
||||||
|
sortOrder: 30,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
filename: 'photo-9.jpg',
|
||||||
|
mime: 'image/jpeg',
|
||||||
|
title: 'Стойка регистрации',
|
||||||
|
alt: 'Интерьер стойки регистрации КДЦ МОНИКИ',
|
||||||
|
sortOrder: 40,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
function filePath(filename: string) {
|
||||||
|
const here = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const bundled = path.join(here, 'files', 'gallery', filename)
|
||||||
|
return fs.existsSync(bundled) ? bundled : null
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function seedGalleryPhotos(payload: Payload) {
|
||||||
|
for (const item of GALLERY_PHOTOS) {
|
||||||
|
const source = filePath(item.filename)
|
||||||
|
if (!source) {
|
||||||
|
payload.logger.warn(`Gallery photo not found: ${item.filename}`)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
const already = await payload.find({
|
||||||
|
collection: 'gallery',
|
||||||
|
where: { title: { equals: item.title } },
|
||||||
|
locale: 'ru',
|
||||||
|
limit: 1,
|
||||||
|
})
|
||||||
|
if (already.docs.length) continue
|
||||||
|
|
||||||
|
const existingMedia = await payload.find({
|
||||||
|
collection: 'media',
|
||||||
|
where: { filename: { equals: item.filename } },
|
||||||
|
limit: 1,
|
||||||
|
})
|
||||||
|
|
||||||
|
let mediaId = existingMedia.docs[0]?.id
|
||||||
|
if (!mediaId) {
|
||||||
|
const buf = fs.readFileSync(source)
|
||||||
|
const media = await payload.create({
|
||||||
|
collection: 'media',
|
||||||
|
locale: 'ru',
|
||||||
|
data: { alt: item.alt },
|
||||||
|
file: {
|
||||||
|
data: buf,
|
||||||
|
mimetype: item.mime,
|
||||||
|
name: item.filename,
|
||||||
|
size: buf.length,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
mediaId = media.id
|
||||||
|
}
|
||||||
|
|
||||||
|
await payload.create({
|
||||||
|
collection: 'gallery',
|
||||||
|
locale: 'ru',
|
||||||
|
data: {
|
||||||
|
title: item.title,
|
||||||
|
image: mediaId,
|
||||||
|
category: 'clinic',
|
||||||
|
sortOrder: item.sortOrder,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
payload.logger.info(`Seeded gallery photo ${item.filename}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const { getPayload } = await import('payload')
|
||||||
|
const config = (await import('../payload.config')).default
|
||||||
|
const payload = await getPayload({ config })
|
||||||
|
await seedGalleryPhotos(payload)
|
||||||
|
process.exit(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1]?.includes('gallery-photos')) {
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error(err)
|
||||||
|
process.exit(1)
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -1,7 +1,22 @@
|
|||||||
|
/**
|
||||||
|
* Replace the services catalog with price-services.json (build it with price_from_xlsx.py).
|
||||||
|
*
|
||||||
|
* pnpm seed:price — replace: the catalog becomes exactly the new price list.
|
||||||
|
* Services whose code (slug) is still in the list keep their id,
|
||||||
|
* so links from doctors, promotions, inquiries and bookings survive;
|
||||||
|
* services missing from the list are deleted, new ones are created.
|
||||||
|
* A removed service that patient bookings still point to is unpublished
|
||||||
|
* instead (hidden from the site, booking history kept).
|
||||||
|
* pnpm seed:price --hard — delete every service first, then create the whole list from scratch
|
||||||
|
* (all links to services are lost; refuses to run while bookings exist).
|
||||||
|
* All changes run in one database transaction: on any error nothing is changed.
|
||||||
|
* pnpm seed:price --dry-run — only print what would change.
|
||||||
|
*/
|
||||||
import 'dotenv/config'
|
import 'dotenv/config'
|
||||||
import fs from 'node:fs'
|
import fs from 'node:fs'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
import { fileURLToPath } from 'node:url'
|
import { fileURLToPath } from 'node:url'
|
||||||
|
import { sql } from '@payloadcms/db-postgres'
|
||||||
import { getPayload } from 'payload'
|
import { getPayload } from 'payload'
|
||||||
import config from '../payload.config'
|
import config from '../payload.config'
|
||||||
|
|
||||||
@@ -16,74 +31,165 @@ type PriceRow = {
|
|||||||
categoryTitle: string
|
categoryTitle: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const BATCH = 80
|
type Category =
|
||||||
|
| 'consultation'
|
||||||
|
| 'diagnostics'
|
||||||
|
| 'lab'
|
||||||
|
| 'procedure'
|
||||||
|
| 'surgery'
|
||||||
|
| 'stay'
|
||||||
|
| 'package'
|
||||||
|
| 'dentistry'
|
||||||
|
|
||||||
|
const args = new Set(process.argv.slice(2))
|
||||||
|
const HARD = args.has('--hard')
|
||||||
|
const DRY_RUN = args.has('--dry-run')
|
||||||
|
|
||||||
|
function serviceData(row: PriceRow) {
|
||||||
|
return {
|
||||||
|
title: row.title,
|
||||||
|
slug: row.slug,
|
||||||
|
code: row.code || null,
|
||||||
|
nmuCode: row.nmu || null,
|
||||||
|
description: `${row.categoryTitle}. ${row.group}. Код услуги ${row.code || '—'}.`,
|
||||||
|
price: row.price,
|
||||||
|
currency: 'RUB',
|
||||||
|
category: row.category as Category,
|
||||||
|
groupTitle: row.group,
|
||||||
|
isPublished: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function each<T>(items: T[], label: string, fn: (item: T) => Promise<void>) {
|
||||||
|
// Sequential on purpose: all writes share one transaction (one connection).
|
||||||
|
for (let i = 0; i < items.length; i++) {
|
||||||
|
await fn(items[i])
|
||||||
|
if ((i + 1) % 500 === 0 || i + 1 === items.length) console.log(`${label} ${i + 1}/${items.length}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
const payload = await getPayload({ config })
|
|
||||||
const file = path.join(path.dirname(fileURLToPath(import.meta.url)), 'price-services.json')
|
const file = path.join(path.dirname(fileURLToPath(import.meta.url)), 'price-services.json')
|
||||||
const rows = JSON.parse(fs.readFileSync(file, 'utf8')) as PriceRow[]
|
const rows = JSON.parse(fs.readFileSync(file, 'utf8')) as PriceRow[]
|
||||||
|
const slugs = new Set(rows.map((r) => r.slug))
|
||||||
|
if (slugs.size !== rows.length) throw new Error('price-services.json has duplicate slugs')
|
||||||
|
if (rows.length < 100) throw new Error(`Refusing to import a suspiciously small price list (${rows.length} rows)`)
|
||||||
|
|
||||||
|
const payload = await getPayload({ config })
|
||||||
const existing = await payload.find({
|
const existing = await payload.find({
|
||||||
collection: 'services',
|
collection: 'services',
|
||||||
limit: 10000,
|
limit: 100000,
|
||||||
depth: 0,
|
depth: 0,
|
||||||
pagination: false,
|
pagination: false,
|
||||||
|
locale: 'ru',
|
||||||
})
|
})
|
||||||
const bySlug = new Set(existing.docs.map((d) => String(d.slug)))
|
const bySlug = new Map(existing.docs.map((d) => [String(d.slug), d]))
|
||||||
|
|
||||||
let created = 0
|
const removed = HARD ? existing.docs : existing.docs.filter((d) => !slugs.has(String(d.slug)))
|
||||||
let skipped = 0
|
|
||||||
|
|
||||||
for (let i = 0; i < rows.length; i += BATCH) {
|
// bookings.service is required: a service with bookings cannot be deleted without breaking them.
|
||||||
const chunk = rows.slice(i, i + BATCH)
|
const booked = new Set<string>()
|
||||||
await Promise.all(
|
if (removed.length) {
|
||||||
chunk.map(async (row) => {
|
const bookings = await payload.find({
|
||||||
if (bySlug.has(row.slug)) {
|
collection: 'bookings',
|
||||||
skipped += 1
|
where: { service: { in: removed.map((d) => d.id) } },
|
||||||
return
|
depth: 0,
|
||||||
}
|
pagination: false,
|
||||||
const group =
|
limit: 100000,
|
||||||
/несъемное протезирование/i.test(row.group) || row.group.startsWith('9.')
|
overrideAccess: true,
|
||||||
? row.group.startsWith('9.') || /несъемное/i.test(row.group)
|
})
|
||||||
? row.group
|
for (const b of bookings.docs) booked.add(String(b.service))
|
||||||
: row.group
|
}
|
||||||
: row.group
|
if (HARD && booked.size) {
|
||||||
const category = /несъемное протезирование/i.test(row.group) ? 'dentistry' : row.category
|
console.error(
|
||||||
await payload.create({
|
`--hard aborted: ${booked.size} services have patient bookings and cannot be deleted. ` +
|
||||||
collection: 'services',
|
'Run without --hard (they will be unpublished) or remove those bookings first. Nothing was changed.',
|
||||||
locale: 'ru',
|
|
||||||
draft: false,
|
|
||||||
data: {
|
|
||||||
title: row.title,
|
|
||||||
slug: row.slug,
|
|
||||||
code: row.code || undefined,
|
|
||||||
nmuCode: row.nmu || undefined,
|
|
||||||
description: `${row.categoryTitle}. ${group}. Код услуги ${row.code || '—'}.`,
|
|
||||||
price: row.price,
|
|
||||||
currency: 'RUB',
|
|
||||||
category: category as
|
|
||||||
| 'consultation'
|
|
||||||
| 'diagnostics'
|
|
||||||
| 'lab'
|
|
||||||
| 'procedure'
|
|
||||||
| 'surgery'
|
|
||||||
| 'stay'
|
|
||||||
| 'package'
|
|
||||||
| 'dentistry',
|
|
||||||
groupTitle: group,
|
|
||||||
isPublished: true,
|
|
||||||
isPopular: false,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
bySlug.add(row.slug)
|
|
||||||
created += 1
|
|
||||||
}),
|
|
||||||
)
|
)
|
||||||
console.log(`imported ${Math.min(i + BATCH, rows.length)}/${rows.length} (created ${created}, skipped ${skipped})`)
|
process.exit(1)
|
||||||
|
}
|
||||||
|
const toDelete = removed.filter((d) => !booked.has(String(d.id)))
|
||||||
|
const toUnpublish = removed.filter((d) => booked.has(String(d.id)))
|
||||||
|
const toUpdate = HARD ? [] : rows.filter((r) => bySlug.has(r.slug))
|
||||||
|
const toCreate = HARD ? rows : rows.filter((r) => !bySlug.has(r.slug))
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`Mode: ${HARD ? 'hard (delete all, recreate)' : 'replace (keep ids of matching codes)'}${DRY_RUN ? ', dry run' : ''}`,
|
||||||
|
)
|
||||||
|
console.log(
|
||||||
|
`Current services: ${existing.docs.length}. New price list: ${rows.length}. ` +
|
||||||
|
`Delete: ${toDelete.length}, unpublish (has bookings): ${toUnpublish.length}, ` +
|
||||||
|
`update: ${toUpdate.length}, create: ${toCreate.length}.`,
|
||||||
|
)
|
||||||
|
if (DRY_RUN) process.exit(0)
|
||||||
|
|
||||||
|
const transactionID = await payload.db.beginTransaction()
|
||||||
|
const req = { transactionID } as Parameters<typeof payload.update>[0]['req']
|
||||||
|
const retranslate: Array<string | number> = []
|
||||||
|
try {
|
||||||
|
await each(toDelete, 'deleted', async (doc) => {
|
||||||
|
await payload.delete({ collection: 'services', id: doc.id, overrideAccess: true, req })
|
||||||
|
})
|
||||||
|
await each(toUnpublish, 'unpublished', async (doc) => {
|
||||||
|
await payload.update({
|
||||||
|
collection: 'services',
|
||||||
|
id: doc.id,
|
||||||
|
locale: 'ru',
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
data: { isPublished: false },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
await each(toUpdate, 'updated', async (row) => {
|
||||||
|
const doc = bySlug.get(row.slug)!
|
||||||
|
if (doc.title !== row.title || doc.groupTitle !== row.group) retranslate.push(doc.id)
|
||||||
|
await payload.update({
|
||||||
|
collection: 'services',
|
||||||
|
id: doc.id,
|
||||||
|
locale: 'ru',
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
data: serviceData(row),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
await each(toCreate, 'created', async (row) => {
|
||||||
|
await payload.create({
|
||||||
|
collection: 'services',
|
||||||
|
locale: 'ru',
|
||||||
|
overrideAccess: true,
|
||||||
|
req,
|
||||||
|
data: { ...serviceData(row), isPopular: false },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
if (transactionID) await payload.db.commitTransaction(transactionID)
|
||||||
|
} catch (err) {
|
||||||
|
if (transactionID) await payload.db.rollbackTransaction(transactionID)
|
||||||
|
console.error('Import failed, all changes rolled back. Nothing was changed.')
|
||||||
|
throw err
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Done. created=${created} skipped=${skipped} total=${rows.length}`)
|
// Translations of renamed services are stale: drop them so other languages fall back to Russian
|
||||||
process.exit(0)
|
// until `pnpm seed:i18n` is run again. Idempotent, safe to repeat.
|
||||||
|
const db = payload.db as unknown as { drizzle: { execute: (q: unknown) => Promise<unknown> } }
|
||||||
|
for (let i = 0; i < retranslate.length; i += 500) {
|
||||||
|
const ids = retranslate.slice(i, i + 500).map(Number)
|
||||||
|
await db.drizzle.execute(
|
||||||
|
sql`DELETE FROM services_locales WHERE _locale <> 'ru' AND _parent_id IN (${sql.join(
|
||||||
|
ids.map((id) => sql`${id}`),
|
||||||
|
sql`, `,
|
||||||
|
)})`,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
const { totalDocs } = await payload.count({
|
||||||
|
collection: 'services',
|
||||||
|
where: { isPublished: { equals: true } },
|
||||||
|
overrideAccess: true,
|
||||||
|
})
|
||||||
|
console.log(
|
||||||
|
`Done. deleted=${toDelete.length} unpublished=${toUnpublish.length} updated=${toUpdate.length} ` +
|
||||||
|
`created=${toCreate.length} retranslate=${retranslate.length} published=${totalDocs}`,
|
||||||
|
)
|
||||||
|
process.exit(totalDocs === rows.length ? 0 : 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch((err) => {
|
main().catch((err) => {
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,130 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Convert the official price list (Прейскурант, .xlsx) into price-services.json.
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python3 apps/cms/src/seed/price_from_xlsx.py "/path/to/Прейскурант.xlsx"
|
||||||
|
|
||||||
|
Sheet layout (first sheet): A = код НМУ, B = код услуги, C = наименование, D = стоимость.
|
||||||
|
- A row with only column C filled is a heading. Numbered headings ("2.3 Компьютерная томография")
|
||||||
|
become the service group; unnumbered sub-headings and footnotes are not groups.
|
||||||
|
- The site category comes from the top-level section number (1 — консультации, 2 — диагностика ...).
|
||||||
|
Section numbers never go backwards, so "3. Несъемное протезирование" inside section 9 stays dentistry.
|
||||||
|
- Duplicate service codes get a "-2", "-3" ... slug suffix (same convention as the previous import).
|
||||||
|
|
||||||
|
Requires openpyxl (pip install openpyxl).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from collections import Counter
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
|
||||||
|
SECTION_CATEGORY = {
|
||||||
|
1: "consultation",
|
||||||
|
2: "diagnostics",
|
||||||
|
3: "lab",
|
||||||
|
4: "procedure",
|
||||||
|
5: "surgery",
|
||||||
|
6: "stay",
|
||||||
|
7: "package",
|
||||||
|
9: "dentistry",
|
||||||
|
10: "package", # Чекапы — комплексные программы
|
||||||
|
}
|
||||||
|
CATEGORY_TITLE = {
|
||||||
|
"consultation": "Приёмы и консультации",
|
||||||
|
"diagnostics": "Инструментальные исследования",
|
||||||
|
"lab": "Лабораторные исследования",
|
||||||
|
"procedure": "Манипуляции и процедуры",
|
||||||
|
"surgery": "Операции",
|
||||||
|
"stay": "Пребывание и размещение",
|
||||||
|
"package": "Комплексные программы",
|
||||||
|
"dentistry": "Стоматология",
|
||||||
|
}
|
||||||
|
|
||||||
|
NUMBERED = re.compile(r"^(\d+)(?:\.\d+)*\.?\s+\S")
|
||||||
|
NOT_A_GROUP = re.compile(r"степень риска", re.IGNORECASE)
|
||||||
|
|
||||||
|
|
||||||
|
def clean(value) -> str:
|
||||||
|
if value is None:
|
||||||
|
return ""
|
||||||
|
if isinstance(value, float) and value.is_integer():
|
||||||
|
value = int(value)
|
||||||
|
return re.sub(r"\s+", " ", str(value)).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def empty(value) -> bool:
|
||||||
|
return clean(value) == ""
|
||||||
|
|
||||||
|
|
||||||
|
def convert(xlsx: Path) -> tuple[list[dict], list[str]]:
|
||||||
|
ws = openpyxl.load_workbook(xlsx, data_only=True, read_only=True).worksheets[0]
|
||||||
|
rows: list[dict] = []
|
||||||
|
warnings: list[str] = []
|
||||||
|
section = 0
|
||||||
|
group = ""
|
||||||
|
slug_counts: Counter[str] = Counter()
|
||||||
|
|
||||||
|
for idx, raw in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2):
|
||||||
|
a, b, c, d = (list(raw) + [None] * 4)[:4]
|
||||||
|
if all(empty(v) for v in (a, b, c, d)):
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Heading row: only the name column is filled.
|
||||||
|
if empty(a) and empty(b) and empty(d) and not empty(c):
|
||||||
|
heading = clean(c)
|
||||||
|
m = NUMBERED.match(heading)
|
||||||
|
if m and not NOT_A_GROUP.search(heading):
|
||||||
|
top = int(m.group(1))
|
||||||
|
if top > section and top in SECTION_CATEGORY:
|
||||||
|
section = top
|
||||||
|
group = heading
|
||||||
|
continue
|
||||||
|
|
||||||
|
if empty(b) or empty(d):
|
||||||
|
warnings.append(f"row {idx}: skipped (no code or price): {clean(a)} | {clean(b)} | {clean(c)} | {clean(d)}")
|
||||||
|
continue
|
||||||
|
if not isinstance(d, (int, float)):
|
||||||
|
warnings.append(f"row {idx}: skipped (price is not a number): {clean(d)}")
|
||||||
|
continue
|
||||||
|
if not group or section not in SECTION_CATEGORY:
|
||||||
|
warnings.append(f"row {idx}: skipped (no group yet): {clean(c)}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
code = clean(b)
|
||||||
|
slug_counts[code] += 1
|
||||||
|
slug = f"s-{code}" if slug_counts[code] == 1 else f"s-{code}-{slug_counts[code]}"
|
||||||
|
category = SECTION_CATEGORY[section]
|
||||||
|
rows.append(
|
||||||
|
{
|
||||||
|
"slug": slug,
|
||||||
|
"nmu": clean(a),
|
||||||
|
"code": code,
|
||||||
|
"title": clean(c),
|
||||||
|
"price": float(d),
|
||||||
|
"group": group,
|
||||||
|
"category": category,
|
||||||
|
"categoryTitle": CATEGORY_TITLE[category],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return rows, warnings
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
if len(sys.argv) != 2:
|
||||||
|
sys.exit(__doc__)
|
||||||
|
rows, warnings = convert(Path(sys.argv[1]))
|
||||||
|
out = Path(__file__).with_name("price-services.json")
|
||||||
|
out.write_text(json.dumps(rows, ensure_ascii=False), encoding="utf-8")
|
||||||
|
for w in warnings:
|
||||||
|
print("WARN", w, file=sys.stderr)
|
||||||
|
by_cat = Counter(r["category"] for r in rows)
|
||||||
|
print(f"Wrote {len(rows)} services to {out.name}: " + ", ".join(f"{k}={v}" for k, v in by_cat.items()))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -4,80 +4,111 @@ import path from 'path'
|
|||||||
import { fileURLToPath } from 'url'
|
import { fileURLToPath } from 'url'
|
||||||
import type { Payload } from 'payload'
|
import type { Payload } from 'payload'
|
||||||
|
|
||||||
export const PUBLIC_CONTRACT_FILENAME = 'Dogovor-platnie-2026.docx'
|
const DOCX_MIME = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|
||||||
export const PUBLIC_CONTRACT_TITLE = 'Договор на оказание платных медицинских услуг (2026)'
|
const RTF_MIME = 'application/rtf'
|
||||||
const CONTRACT_MIME =
|
|
||||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
|
|
||||||
|
|
||||||
function contractPath() {
|
export const PUBLIC_DOCUMENTS = [
|
||||||
|
{
|
||||||
|
filename: 'Soglasie-personalnye-dannye.rtf',
|
||||||
|
title: 'Согласие пациента на обработку персональных данных',
|
||||||
|
mime: RTF_MIME,
|
||||||
|
type: 'other' as const,
|
||||||
|
issuedAt: '2026-07-15T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
filename: 'IDS-meditsinskoe-vmeshatelstvo.docx',
|
||||||
|
title:
|
||||||
|
'Информированное добровольное согласие пациента (законного представителя пациента) на медицинское вмешательство, предоставление сведений, составляющих врачебную тайну, и консультацию врача-специалиста с применением телемедицинских технологий',
|
||||||
|
mime: DOCX_MIME,
|
||||||
|
type: 'other' as const,
|
||||||
|
issuedAt: '2026-09-01T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
filename: 'Dogovor-platnye-uslugi-fiz-litso.docx',
|
||||||
|
title: 'Договор на оказание платных медицинских услуг (с физическим лицом)',
|
||||||
|
mime: DOCX_MIME,
|
||||||
|
type: 'contract' as const,
|
||||||
|
issuedAt: '2026-06-30T00:00:00.000Z',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const OLD_CONTRACT_FILENAME = 'Dogovor-platnie-2026.docx'
|
||||||
|
|
||||||
|
function filePath(filename: string) {
|
||||||
const here = path.dirname(fileURLToPath(import.meta.url))
|
const here = path.dirname(fileURLToPath(import.meta.url))
|
||||||
const bundled = path.join(here, 'files', PUBLIC_CONTRACT_FILENAME)
|
const bundled = path.join(here, 'files', filename)
|
||||||
if (fs.existsSync(bundled)) return bundled
|
if (fs.existsSync(bundled)) return bundled
|
||||||
const icloud = path.join(
|
|
||||||
process.env.HOME || '',
|
|
||||||
'Library/Mobile Documents/com~apple~CloudDocs/Downloads icloud',
|
|
||||||
PUBLIC_CONTRACT_FILENAME,
|
|
||||||
)
|
|
||||||
if (fs.existsSync(icloud)) return icloud
|
|
||||||
return null
|
return null
|
||||||
}
|
}
|
||||||
|
|
||||||
function copyToWebPublic(source: string) {
|
function copyToWebPublic(source: string, filename: string) {
|
||||||
const here = path.dirname(fileURLToPath(import.meta.url))
|
const here = path.dirname(fileURLToPath(import.meta.url))
|
||||||
const dest = path.resolve(here, '../../../web/public/documents', PUBLIC_CONTRACT_FILENAME)
|
const dest = path.resolve(here, '../../../web/public/documents', filename)
|
||||||
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
fs.mkdirSync(path.dirname(dest), { recursive: true })
|
||||||
fs.copyFileSync(source, dest)
|
fs.copyFileSync(source, dest)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function seedPublicDocuments(payload: Payload) {
|
export async function seedPublicDocuments(payload: Payload) {
|
||||||
const filePath = contractPath()
|
|
||||||
if (!filePath) {
|
|
||||||
payload.logger.warn('Public contract file not found, skip seed')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
copyToWebPublic(filePath)
|
|
||||||
|
|
||||||
const existing = await payload.find({
|
const existing = await payload.find({
|
||||||
collection: 'documents',
|
collection: 'documents',
|
||||||
where: {
|
where: { isPublic: { equals: true } },
|
||||||
and: [{ isPublic: { equals: true } }, { type: { equals: 'contract' } }],
|
limit: 100,
|
||||||
},
|
|
||||||
limit: 50,
|
|
||||||
depth: 1,
|
depth: 1,
|
||||||
})
|
})
|
||||||
|
|
||||||
const already = existing.docs.some((doc) => {
|
for (const doc of existing.docs) {
|
||||||
const file = typeof doc.file === 'object' && doc.file ? doc.file : null
|
const file = typeof doc.file === 'object' && doc.file ? doc.file : null
|
||||||
const filename = file && 'filename' in file ? String(file.filename || '') : ''
|
const filename = file && 'filename' in file ? String(file.filename || '') : ''
|
||||||
return filename === PUBLIC_CONTRACT_FILENAME || String(doc.title || '').includes('платных медицинских услуг')
|
const title = String(doc.title || '')
|
||||||
})
|
const stale =
|
||||||
if (already) return
|
filename === OLD_CONTRACT_FILENAME || title.includes('(2026)') || title.includes('платных медицинских услуг (2026)')
|
||||||
|
if (!stale) continue
|
||||||
|
await payload.delete({ collection: 'documents', id: doc.id })
|
||||||
|
payload.logger.info(`Removed public document ${title}`)
|
||||||
|
}
|
||||||
|
|
||||||
const buf = fs.readFileSync(filePath)
|
for (const item of PUBLIC_DOCUMENTS) {
|
||||||
const media = await payload.create({
|
const source = filePath(item.filename)
|
||||||
collection: 'media',
|
if (!source) {
|
||||||
data: { alt: PUBLIC_CONTRACT_TITLE },
|
payload.logger.warn(`Public document file not found: ${item.filename}`)
|
||||||
file: {
|
continue
|
||||||
data: buf,
|
}
|
||||||
mimetype: CONTRACT_MIME,
|
copyToWebPublic(source, item.filename)
|
||||||
name: PUBLIC_CONTRACT_FILENAME,
|
|
||||||
size: buf.length,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
await payload.create({
|
const already = await payload.find({
|
||||||
collection: 'documents',
|
collection: 'documents',
|
||||||
locale: 'ru',
|
where: {
|
||||||
data: {
|
and: [{ isPublic: { equals: true } }, { title: { equals: item.title } }],
|
||||||
title: PUBLIC_CONTRACT_TITLE,
|
},
|
||||||
type: 'contract',
|
limit: 1,
|
||||||
isPublic: true,
|
})
|
||||||
file: media.id,
|
if (already.docs.length) continue
|
||||||
issuedAt: '2026-01-01T00:00:00.000Z',
|
|
||||||
},
|
const buf = fs.readFileSync(source)
|
||||||
})
|
const media = await payload.create({
|
||||||
payload.logger.info(`Seeded public document ${PUBLIC_CONTRACT_FILENAME}`)
|
collection: 'media',
|
||||||
|
data: { alt: item.title },
|
||||||
|
file: {
|
||||||
|
data: buf,
|
||||||
|
mimetype: item.mime,
|
||||||
|
name: item.filename,
|
||||||
|
size: buf.length,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
await payload.create({
|
||||||
|
collection: 'documents',
|
||||||
|
locale: 'ru',
|
||||||
|
data: {
|
||||||
|
title: item.title,
|
||||||
|
type: item.type,
|
||||||
|
isPublic: true,
|
||||||
|
file: media.id,
|
||||||
|
issuedAt: item.issuedAt,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
payload.logger.info(`Seeded public document ${item.filename}`)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function main() {
|
async function main() {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@moniki/web",
|
"name": "@moniki/web",
|
||||||
"version": "1.0.2",
|
"version": "1.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev -p 3000",
|
"dev": "next dev -p 3000",
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
Before Width: | Height: | Size: 130 KiB After Width: | Height: | Size: 11 KiB |
@@ -1,3 +1,5 @@
|
|||||||
|
import { getMyDocuments } from "@/lib/api";
|
||||||
|
import { formatDate } from "@/lib/utils";
|
||||||
import { getTranslations, setRequestLocale } from "next-intl/server";
|
import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||||
|
|
||||||
export default async function CabinetDocumentsPage({
|
export default async function CabinetDocumentsPage({
|
||||||
@@ -8,11 +10,27 @@ export default async function CabinetDocumentsPage({
|
|||||||
const { locale } = await params;
|
const { locale } = await params;
|
||||||
setRequestLocale(locale);
|
setRequestLocale(locale);
|
||||||
const t = await getTranslations("cabinet");
|
const t = await getTranslations("cabinet");
|
||||||
|
const documents = await getMyDocuments();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<h2 className="mb-4 text-xl font-semibold">{t("documents")}</h2>
|
<h2 className="mb-4 text-xl font-semibold">{t("documents")}</h2>
|
||||||
<p className="text-[var(--text-muted)]">{t("emptyDocuments")}</p>
|
{documents.length === 0 ? (
|
||||||
|
<p className="text-[var(--text-muted)]">{t("emptyDocuments")}</p>
|
||||||
|
) : (
|
||||||
|
<ul className="space-y-3">
|
||||||
|
{documents.map((doc) => (
|
||||||
|
<li key={doc.id} className="rounded-[12px] border border-[var(--border)] bg-white px-4 py-3">
|
||||||
|
<a href={doc.href} className="font-semibold text-[var(--brand-700)]" target="_blank" rel="noreferrer">
|
||||||
|
{doc.title}
|
||||||
|
</a>
|
||||||
|
{doc.issuedAt ? (
|
||||||
|
<p className="mt-1 text-sm text-[var(--text-muted)]">{formatDate(doc.issuedAt, locale)}</p>
|
||||||
|
) : null}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Card } from "@/components/ui/Card";
|
import { Card } from "@/components/ui/Card";
|
||||||
import { getMyBookings } from "@/lib/api";
|
import { getMyInvoices } from "@/lib/api";
|
||||||
import { formatPrice } from "@/lib/utils";
|
import { formatDate, formatPrice } from "@/lib/utils";
|
||||||
import { getTranslations, setRequestLocale } from "next-intl/server";
|
import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||||
|
|
||||||
export default async function CabinetInvoicesPage({
|
export default async function CabinetInvoicesPage({
|
||||||
@@ -11,24 +11,27 @@ export default async function CabinetInvoicesPage({
|
|||||||
const { locale } = await params;
|
const { locale } = await params;
|
||||||
setRequestLocale(locale);
|
setRequestLocale(locale);
|
||||||
const t = await getTranslations("cabinet");
|
const t = await getTranslations("cabinet");
|
||||||
const bookings = await getMyBookings();
|
const invoices = await getMyInvoices();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<h2 className="mb-4 text-xl font-semibold">{t("invoices")}</h2>
|
<h2 className="mb-4 text-xl font-semibold">{t("invoices")}</h2>
|
||||||
{bookings.length === 0 ? (
|
{invoices.length === 0 ? (
|
||||||
<p className="text-[var(--text-muted)]">{t("emptyInvoices")}</p>
|
<p className="text-[var(--text-muted)]">{t("emptyInvoices")}</p>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{bookings.map((b) => (
|
{invoices.map((invoice) => (
|
||||||
<Card key={b.id} className="flex items-center justify-between gap-4">
|
<Card key={invoice.id} className="flex items-center justify-between gap-4">
|
||||||
<div>
|
<div>
|
||||||
<p className="font-semibold">{b.serviceTitle}</p>
|
<p className="font-semibold">{invoice.title}</p>
|
||||||
<p className="text-sm text-[var(--text-muted)]">{b.datetime}</p>
|
<p className="text-sm text-[var(--text-muted)]">
|
||||||
|
{invoice.number}
|
||||||
|
{invoice.datetime ? ` · ${formatDate(invoice.datetime, locale)}` : ""}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<p className="font-bold text-[var(--brand-700)]">{formatPrice(b.price, locale)}</p>
|
<p className="font-bold text-[var(--brand-700)]">{formatPrice(invoice.amount, locale)}</p>
|
||||||
<p className="text-xs text-[var(--neutral-500)]">{b.paid ? t("paid") : t("unpaid")}</p>
|
<p className="text-xs text-[var(--neutral-500)]">{invoice.paid ? t("paid") : t("unpaid")}</p>
|
||||||
</div>
|
</div>
|
||||||
</Card>
|
</Card>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { CabinetNav } from "@/components/cabinet/CabinetNav";
|
import { CabinetNav } from "@/components/cabinet/CabinetNav";
|
||||||
import { namedPageMetadata } from "@/lib/page-metadata";
|
import { namedPageMetadata } from "@/lib/page-metadata";
|
||||||
|
import { me } from "@/lib/api";
|
||||||
|
import { Link } from "@/i18n/routing";
|
||||||
import { getTranslations, setRequestLocale } from "next-intl/server";
|
import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
@@ -22,6 +24,20 @@ export default async function CabinetLayout({
|
|||||||
const { locale } = await params;
|
const { locale } = await params;
|
||||||
setRequestLocale(locale);
|
setRequestLocale(locale);
|
||||||
const t = await getTranslations("cabinet");
|
const t = await getTranslations("cabinet");
|
||||||
|
const auth = await getTranslations("auth");
|
||||||
|
const user = await me();
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return (
|
||||||
|
<div className="mx-auto max-w-xl px-4 py-12 sm:px-6">
|
||||||
|
<h1 className="text-3xl font-bold text-[var(--neutral-900)]">{t("title")}</h1>
|
||||||
|
<p className="mt-4 text-[var(--text-muted)]">{t("loginHint")}</p>
|
||||||
|
<Link href="/login" className="mt-4 inline-block font-semibold text-[var(--brand-700)]">
|
||||||
|
{auth("login")}
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mx-auto max-w-6xl px-4 py-12 sm:px-6">
|
<div className="mx-auto max-w-6xl px-4 py-12 sm:px-6">
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ export default async function GalleryPage({
|
|||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img src={item.image} alt={item.title} className="mx-auto block w-full object-cover object-center" />
|
<img src={item.image} alt={item.title} className="mx-auto block w-full object-cover object-center" />
|
||||||
<figcaption className="bg-white px-3 py-2 text-sm text-[var(--neutral-600)]">
|
<figcaption className="bg-white px-3 py-2 text-sm text-[var(--neutral-600)]">
|
||||||
{item.title} · {item.category}
|
{item.title}
|
||||||
</figcaption>
|
</figcaption>
|
||||||
</figure>
|
</figure>
|
||||||
))}
|
))}
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { ScrollToTop } from "@/components/layout/ScrollToTop";
|
|||||||
import { ThemeProvider } from "@/components/layout/ThemeProvider";
|
import { ThemeProvider } from "@/components/layout/ThemeProvider";
|
||||||
import { CookieBanner } from "@/components/legal/CookieBanner";
|
import { CookieBanner } from "@/components/legal/CookieBanner";
|
||||||
import { A11Y_BOOTSTRAP } from "@/lib/a11y";
|
import { A11Y_BOOTSTRAP } from "@/lib/a11y";
|
||||||
|
import { APP_VERSION } from "@/lib/version";
|
||||||
import { THEME_BOOTSTRAP } from "@/lib/theme";
|
import { THEME_BOOTSTRAP } from "@/lib/theme";
|
||||||
import { routing, type Locale } from "@/i18n/routing";
|
import { routing, type Locale } from "@/i18n/routing";
|
||||||
import { Manrope } from "next/font/google";
|
import { Manrope } from "next/font/google";
|
||||||
@@ -40,8 +41,8 @@ export async function generateMetadata({
|
|||||||
},
|
},
|
||||||
description: t("fullName"),
|
description: t("fullName"),
|
||||||
icons: {
|
icons: {
|
||||||
icon: "/logo.png",
|
icon: `/logo.png?v=${APP_VERSION}`,
|
||||||
apple: "/logo.png",
|
apple: `/logo.png?v=${APP_VERSION}`,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,24 +19,11 @@ export async function POST(request: Request) {
|
|||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
sameSite: "lax",
|
sameSite: "lax",
|
||||||
path: "/",
|
path: "/",
|
||||||
secure: process.env.NODE_ENV === "production",
|
secure: false,
|
||||||
maxAge: 60 * 60 * 24 * 7,
|
maxAge: 60 * 60 * 24 * 7,
|
||||||
});
|
});
|
||||||
return response;
|
return response;
|
||||||
} catch {
|
} catch {
|
||||||
// Demo login fallback when CMS is down
|
|
||||||
if (body.email && body.password) {
|
|
||||||
const response = NextResponse.json({
|
|
||||||
user: { id: "demo", email: body.email, name: "Пациент" },
|
|
||||||
});
|
|
||||||
response.cookies.set(AUTH_COOKIE, "demo-token", {
|
|
||||||
httpOnly: true,
|
|
||||||
sameSite: "lax",
|
|
||||||
path: "/",
|
|
||||||
maxAge: 60 * 60 * 24 * 7,
|
|
||||||
});
|
|
||||||
return response;
|
|
||||||
}
|
|
||||||
return NextResponse.json({ message: "Login failed" }, { status: 500 });
|
return NextResponse.json({ message: "Login failed" }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,13 +5,7 @@ import { NextResponse } from "next/server";
|
|||||||
export async function GET() {
|
export async function GET() {
|
||||||
const store = await cookies();
|
const store = await cookies();
|
||||||
const token = store.get(AUTH_COOKIE)?.value;
|
const token = store.get(AUTH_COOKIE)?.value;
|
||||||
if (!token) return NextResponse.json({ user: null }, { status: 401 });
|
if (!token || token === "demo-token") return NextResponse.json({ user: null }, { status: 401 });
|
||||||
|
|
||||||
if (token === "demo-token") {
|
|
||||||
return NextResponse.json({
|
|
||||||
user: { id: "demo", email: "patient@example.com", name: "Пациент", phone: "+7" },
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${CMS_URL}/api/users/me`, {
|
const res = await fetch(`${CMS_URL}/api/users/me`, {
|
||||||
@@ -21,34 +15,49 @@ export async function GET() {
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
return NextResponse.json(data, { status: res.status });
|
return NextResponse.json(data, { status: res.status });
|
||||||
} catch {
|
} catch {
|
||||||
return NextResponse.json({
|
return NextResponse.json({ user: null }, { status: 401 });
|
||||||
user: { id: "demo", email: "patient@example.com", name: "Пациент" },
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function PATCH(request: Request) {
|
export async function PATCH(request: Request) {
|
||||||
const store = await cookies();
|
const store = await cookies();
|
||||||
const token = store.get(AUTH_COOKIE)?.value;
|
const token = store.get(AUTH_COOKIE)?.value;
|
||||||
if (!token) return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
|
if (!token || token === "demo-token") return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
|
||||||
|
|
||||||
const body = await request.json();
|
const body = ((await request.json().catch(() => ({}))) ?? {}) as Record<string, unknown>;
|
||||||
if (token === "demo-token") {
|
// Whitelist profile fields: never forward role, email, password or other account internals.
|
||||||
return NextResponse.json({ user: { id: "demo", ...body } });
|
const payload: Record<string, unknown> = {};
|
||||||
}
|
const fullName = body.fullName ?? body.name;
|
||||||
|
if (typeof fullName === "string") payload.fullName = fullName;
|
||||||
|
if (typeof body.phone === "string") payload.phone = body.phone;
|
||||||
|
if (typeof body.birthDate === "string" || body.birthDate === null) payload.birthDate = body.birthDate;
|
||||||
|
if (typeof body.locale === "string") payload.locale = body.locale;
|
||||||
|
if (typeof body.smsOptIn === "boolean") payload.smsOptIn = body.smsOptIn;
|
||||||
|
if (typeof body.emailOptIn === "boolean") payload.emailOptIn = body.emailOptIn;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`${CMS_URL}/api/users/me`, {
|
// Payload has no PATCH /users/me: resolve the current user id, then update by id.
|
||||||
|
const meRes = await fetch(`${CMS_URL}/api/users/me`, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
const me = (await meRes.json().catch(() => ({}))) as { user?: { id?: string | number } | null };
|
||||||
|
const userId = me.user?.id;
|
||||||
|
if (!meRes.ok || userId == null) {
|
||||||
|
return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`${CMS_URL}/api/users/${encodeURIComponent(String(userId))}`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
"Content-Type": "application/json",
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
return NextResponse.json(data, { status: res.status });
|
return NextResponse.json(data, { status: res.status });
|
||||||
} catch {
|
} catch {
|
||||||
return NextResponse.json({ user: { id: "demo", ...body } });
|
return NextResponse.json({ message: "Update failed" }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,44 +4,44 @@ import { NextResponse } from "next/server";
|
|||||||
export async function POST(request: Request) {
|
export async function POST(request: Request) {
|
||||||
const body = await request.json();
|
const body = await request.json();
|
||||||
try {
|
try {
|
||||||
|
const payload = {
|
||||||
|
email: body.email,
|
||||||
|
password: body.password,
|
||||||
|
fullName: body.fullName || body.name,
|
||||||
|
phone: body.phone,
|
||||||
|
role: "patient",
|
||||||
|
};
|
||||||
const res = await fetch(`${CMS_URL}/api/users`, {
|
const res = await fetch(`${CMS_URL}/api/users`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify(body),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
return NextResponse.json(data, { status: res.status });
|
return NextResponse.json(data, { status: res.status });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Auto-login after register
|
|
||||||
const loginRes = await fetch(`${CMS_URL}/api/users/login`, {
|
const loginRes = await fetch(`${CMS_URL}/api/users/login`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ email: body.email, password: body.password }),
|
body: JSON.stringify({ email: body.email, password: body.password }),
|
||||||
});
|
});
|
||||||
const loginData = await loginRes.json().catch(() => ({}));
|
const loginData = await loginRes.json().catch(() => ({}));
|
||||||
const token = loginData.token || data.token || "demo-token";
|
const token = loginData.token || data.token;
|
||||||
|
if (!token) {
|
||||||
|
return NextResponse.json({ message: "Register succeeded but login failed" }, { status: 500 });
|
||||||
|
}
|
||||||
|
|
||||||
const response = NextResponse.json({ user: data.doc || data.user || { email: body.email } });
|
const response = NextResponse.json({ user: data.doc || data.user || { email: body.email } });
|
||||||
response.cookies.set(AUTH_COOKIE, token, {
|
response.cookies.set(AUTH_COOKIE, token, {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
sameSite: "lax",
|
sameSite: "lax",
|
||||||
path: "/",
|
path: "/",
|
||||||
secure: process.env.NODE_ENV === "production",
|
secure: false,
|
||||||
maxAge: 60 * 60 * 24 * 7,
|
maxAge: 60 * 60 * 24 * 7,
|
||||||
});
|
});
|
||||||
return response;
|
return response;
|
||||||
} catch {
|
} catch {
|
||||||
const response = NextResponse.json({
|
return NextResponse.json({ message: "Register failed" }, { status: 500 });
|
||||||
user: { id: "demo", email: body.email, name: body.name },
|
|
||||||
});
|
|
||||||
response.cookies.set(AUTH_COOKIE, "demo-token", {
|
|
||||||
httpOnly: true,
|
|
||||||
sameSite: "lax",
|
|
||||||
path: "/",
|
|
||||||
maxAge: 60 * 60 * 24 * 7,
|
|
||||||
});
|
|
||||||
return response;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { CMS_URL, getAuthToken } from "@/lib/api";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
type Params = { params: Promise<{ filename: string }> };
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Streams a private patient file from the CMS using the patient's session token.
|
||||||
|
* The CMS media access rules decide whether this patient may read the file.
|
||||||
|
*/
|
||||||
|
export async function GET(_request: Request, { params }: Params) {
|
||||||
|
const { filename } = await params;
|
||||||
|
if (!filename || filename.includes("/") || filename.includes("..")) {
|
||||||
|
return NextResponse.json({ error: "invalid" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = await getAuthToken();
|
||||||
|
if (!token || token === "demo-token") {
|
||||||
|
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await fetch(`${CMS_URL}/api/media/file/${encodeURIComponent(filename)}`, {
|
||||||
|
headers: { Authorization: `Bearer ${token}` },
|
||||||
|
cache: "no-store",
|
||||||
|
}).catch(() => null);
|
||||||
|
|
||||||
|
if (!res || !res.ok || !res.body) {
|
||||||
|
return NextResponse.json({ error: "Not found" }, { status: res?.status === 403 ? 403 : 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const headers = new Headers();
|
||||||
|
headers.set("Content-Type", res.headers.get("Content-Type") || "application/octet-stream");
|
||||||
|
const length = res.headers.get("Content-Length");
|
||||||
|
if (length) headers.set("Content-Length", length);
|
||||||
|
headers.set("Content-Disposition", `inline; filename*=UTF-8''${encodeURIComponent(filename)}`);
|
||||||
|
headers.set("Cache-Control", "private, no-store");
|
||||||
|
return new NextResponse(res.body, { status: 200, headers });
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { createInquiry } from "@/lib/api";
|
||||||
|
import {
|
||||||
|
isValidEmailAddress,
|
||||||
|
isValidFullName,
|
||||||
|
isValidRuPhone,
|
||||||
|
normalizeRuPhone,
|
||||||
|
} from "@/lib/contact-fields";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
function asText(value: unknown) {
|
||||||
|
return typeof value === "string" ? value.trim() : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
const body = (await request.json()) as Record<string, unknown>;
|
||||||
|
const name = asText(body.name ?? body.patientName).replace(/\s+/g, " ");
|
||||||
|
const email = asText(body.email);
|
||||||
|
const phone = normalizeRuPhone(asText(body.phone));
|
||||||
|
const branchId = asText(body.branchId);
|
||||||
|
const serviceId = asText(body.serviceId) || undefined;
|
||||||
|
const doctorId = asText(body.doctorId) || undefined;
|
||||||
|
|
||||||
|
if (!isValidFullName(name) || !isValidEmailAddress(email) || !isValidRuPhone(phone) || !branchId || (!serviceId && !doctorId)) {
|
||||||
|
return NextResponse.json({ error: "invalid" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const inquiry = await createInquiry({
|
||||||
|
name,
|
||||||
|
email,
|
||||||
|
phone,
|
||||||
|
branchId,
|
||||||
|
serviceId,
|
||||||
|
doctorId,
|
||||||
|
});
|
||||||
|
return NextResponse.json(inquiry);
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json({ error: "unavailable" }, { status: 503 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,14 @@ import { Button } from "@/components/ui/Button";
|
|||||||
import { Card } from "@/components/ui/Card";
|
import { Card } from "@/components/ui/Card";
|
||||||
import { Input } from "@/components/ui/Input";
|
import { Input } from "@/components/ui/Input";
|
||||||
import { Select } from "@/components/ui/Select";
|
import { Select } from "@/components/ui/Select";
|
||||||
import type { Branch, Doctor, Service, Slot } from "@/lib/demo-data";
|
import type { Branch, Doctor, Service } from "@/lib/demo-data";
|
||||||
|
import {
|
||||||
|
formatRuPhone,
|
||||||
|
isValidEmailAddress,
|
||||||
|
isValidFullName,
|
||||||
|
isValidRuPhone,
|
||||||
|
normalizeRuPhone,
|
||||||
|
} from "@/lib/contact-fields";
|
||||||
import { matchesQuery } from "@/lib/search";
|
import { matchesQuery } from "@/lib/search";
|
||||||
import { cn, formatPrice, stripPriceListIndex } from "@/lib/utils";
|
import { cn, formatPrice, stripPriceListIndex } from "@/lib/utils";
|
||||||
import { useTranslations, useLocale } from "next-intl";
|
import { useTranslations, useLocale } from "next-intl";
|
||||||
@@ -21,7 +28,6 @@ type Props = {
|
|||||||
const steps = [
|
const steps = [
|
||||||
{ id: "service", labelKey: "stepService" },
|
{ id: "service", labelKey: "stepService" },
|
||||||
{ id: "branch", labelKey: "stepBranch" },
|
{ id: "branch", labelKey: "stepBranch" },
|
||||||
{ id: "slot", labelKey: "stepSlot" },
|
|
||||||
{ id: "confirm", labelKey: "stepConfirm" },
|
{ id: "confirm", labelKey: "stepConfirm" },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
@@ -40,11 +46,10 @@ export function BookingWizard({
|
|||||||
const [services, setServices] = useState<Service[]>([]);
|
const [services, setServices] = useState<Service[]>([]);
|
||||||
const [serviceQuery, setServiceQuery] = useState("");
|
const [serviceQuery, setServiceQuery] = useState("");
|
||||||
const [branchId, setBranchId] = useState(initialBranchId || "");
|
const [branchId, setBranchId] = useState(initialBranchId || "");
|
||||||
const [date, setDate] = useState(() => new Date().toISOString().slice(0, 10));
|
|
||||||
const [slots, setSlots] = useState<Slot[]>([]);
|
|
||||||
const [slotId, setSlotId] = useState("");
|
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
const [phone, setPhone] = useState("");
|
const [phone, setPhone] = useState("");
|
||||||
|
const [fieldErrors, setFieldErrors] = useState<{ name?: string; email?: string; phone?: string }>({});
|
||||||
const [done, setDone] = useState(false);
|
const [done, setDone] = useState(false);
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [pending, startTransition] = useTransition();
|
const [pending, startTransition] = useTransition();
|
||||||
@@ -61,7 +66,6 @@ export function BookingWizard({
|
|||||||
const service = services.find((s) => s.id === serviceId);
|
const service = services.find((s) => s.id === serviceId);
|
||||||
const doctor = doctors.find((d) => d.id === doctorId);
|
const doctor = doctors.find((d) => d.id === doctorId);
|
||||||
const branch = branches.find((b) => b.id === branchId);
|
const branch = branches.find((b) => b.id === branchId);
|
||||||
const slot = slots.find((s) => s.id === slotId);
|
|
||||||
|
|
||||||
const visibleServices = useMemo(() => {
|
const visibleServices = useMemo(() => {
|
||||||
const list = !serviceQuery.trim()
|
const list = !serviceQuery.trim()
|
||||||
@@ -81,54 +85,49 @@ export function BookingWizard({
|
|||||||
return doctors.filter((d) => d.services.includes(serviceId));
|
return doctors.filter((d) => d.services.includes(serviceId));
|
||||||
}, [doctors, serviceId]);
|
}, [doctors, serviceId]);
|
||||||
|
|
||||||
async function loadSlots(nextDate: string, nextBranch: string) {
|
function contactErrors() {
|
||||||
const params = new URLSearchParams({
|
const next: { name?: string; email?: string; phone?: string } = {};
|
||||||
date: nextDate,
|
if (!name.trim()) next.name = t("nameRequired");
|
||||||
branchId: nextBranch,
|
else if (!isValidFullName(name)) next.name = t("nameInvalid");
|
||||||
});
|
if (!email.trim()) next.email = t("emailRequired");
|
||||||
if (doctorId) params.set("doctorId", doctorId);
|
else if (!isValidEmailAddress(email)) next.email = t("emailInvalid");
|
||||||
if (serviceId) params.set("serviceId", serviceId);
|
if (!isValidRuPhone(phone)) next.phone = t("phoneInvalid");
|
||||||
const res = await fetch(`/api/slots?${params}`);
|
return next;
|
||||||
const data = (await res.json()) as Slot[];
|
|
||||||
setSlots(data);
|
|
||||||
setSlotId("");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function canNext() {
|
function canNext() {
|
||||||
if (step === 0) return Boolean(serviceId || doctorId);
|
if (step === 0) return Boolean(serviceId || doctorId);
|
||||||
if (step === 1) return Boolean(branchId);
|
if (step === 1) return Boolean(branchId);
|
||||||
if (step === 2) return Boolean(slotId);
|
return true;
|
||||||
return Boolean(name && phone);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async function onNext() {
|
async function onNext() {
|
||||||
setError("");
|
setError("");
|
||||||
if (step === 1 && branchId) {
|
|
||||||
await loadSlots(date, branchId);
|
|
||||||
}
|
|
||||||
if (step < steps.length - 1) {
|
if (step < steps.length - 1) {
|
||||||
setStep((s) => s + 1);
|
setStep((s) => s + 1);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const nextErrors = contactErrors();
|
||||||
|
setFieldErrors(nextErrors);
|
||||||
|
if (Object.keys(nextErrors).length) return;
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
try {
|
try {
|
||||||
const res = await fetch("/api/bookings", {
|
const res = await fetch("/api/inquiries", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
serviceId: serviceId || undefined,
|
serviceId: serviceId || undefined,
|
||||||
doctorId: doctorId || undefined,
|
doctorId: doctorId || undefined,
|
||||||
branchId,
|
branchId,
|
||||||
slotId,
|
name: name.trim().replace(/\s+/g, " "),
|
||||||
datetime: slot?.start,
|
email: email.trim(),
|
||||||
patientName: name,
|
phone: normalizeRuPhone(phone),
|
||||||
phone,
|
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
if (!res.ok) throw new Error("fail");
|
if (!res.ok) throw new Error("fail");
|
||||||
setDone(true);
|
setDone(true);
|
||||||
} catch {
|
} catch {
|
||||||
setError(t("confirm"));
|
setError(t("error"));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -177,7 +176,7 @@ export function BookingWizard({
|
|||||||
<button
|
<button
|
||||||
key={s.id}
|
key={s.id}
|
||||||
type="button"
|
type="button"
|
||||||
onClick={() => setServiceId(s.id)}
|
onClick={() => setServiceId(s.id === serviceId ? "" : s.id)}
|
||||||
className={cn(
|
className={cn(
|
||||||
"flex w-full items-center justify-between gap-3 border-b border-[var(--border)] px-3 py-2 text-left text-sm last:border-b-0",
|
"flex w-full items-center justify-between gap-3 border-b border-[var(--border)] px-3 py-2 text-left text-sm last:border-b-0",
|
||||||
serviceId === s.id
|
serviceId === s.id
|
||||||
@@ -233,53 +232,6 @@ export function BookingWizard({
|
|||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{step === 2 ? (
|
{step === 2 ? (
|
||||||
<>
|
|
||||||
<Input
|
|
||||||
type="date"
|
|
||||||
label={t("selectDate")}
|
|
||||||
value={date}
|
|
||||||
onChange={async (e) => {
|
|
||||||
const v = e.target.value;
|
|
||||||
setDate(v);
|
|
||||||
if (branchId) await loadSlots(v, branchId);
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div>
|
|
||||||
<p className="mb-2 text-sm font-medium text-[var(--neutral-700)]">{t("selectTime")}</p>
|
|
||||||
{slots.filter((s) => s.available).length === 0 ? (
|
|
||||||
<p className="text-sm text-[var(--text-muted)]">{t("noSlots")}</p>
|
|
||||||
) : (
|
|
||||||
<div className="flex flex-wrap gap-2">
|
|
||||||
{slots
|
|
||||||
.filter((s) => s.available)
|
|
||||||
.map((s) => {
|
|
||||||
const label = new Date(s.start).toLocaleTimeString([], {
|
|
||||||
hour: "2-digit",
|
|
||||||
minute: "2-digit",
|
|
||||||
});
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
key={s.id}
|
|
||||||
type="button"
|
|
||||||
onClick={() => setSlotId(s.id)}
|
|
||||||
className={cn(
|
|
||||||
"rounded-[10px] border px-3 py-2 text-sm font-medium",
|
|
||||||
slotId === s.id
|
|
||||||
? "border-[var(--brand-500)] bg-[var(--brand-600)] text-white"
|
|
||||||
: "border-[var(--border)] hover:border-[var(--brand-300)]",
|
|
||||||
)}
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</>
|
|
||||||
) : null}
|
|
||||||
|
|
||||||
{step === 3 ? (
|
|
||||||
<>
|
<>
|
||||||
<div className="rounded-[10px] bg-[var(--neutral-50)] p-4 text-sm">
|
<div className="rounded-[10px] bg-[var(--neutral-50)] p-4 text-sm">
|
||||||
<p className="font-semibold">{t("summary")}</p>
|
<p className="font-semibold">{t("summary")}</p>
|
||||||
@@ -287,12 +239,55 @@ export function BookingWizard({
|
|||||||
{service ? <li>{stripPriceListIndex(service.title)}</li> : null}
|
{service ? <li>{stripPriceListIndex(service.title)}</li> : null}
|
||||||
{doctor ? <li>{doctor.name}</li> : null}
|
{doctor ? <li>{doctor.name}</li> : null}
|
||||||
{branch ? <li>{branch.name}</li> : null}
|
{branch ? <li>{branch.name}</li> : null}
|
||||||
{slot ? <li>{new Date(slot.start).toLocaleString()}</li> : null}
|
|
||||||
{service ? <li>{formatPrice(service.price, locale)}</li> : null}
|
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
<Input label={t("patientName")} value={name} onChange={(e) => setName(e.target.value)} required />
|
<Input
|
||||||
<Input label={t("phone")} value={phone} onChange={(e) => setPhone(e.target.value)} required />
|
label={t("patientName")}
|
||||||
|
placeholder={t("namePlaceholder")}
|
||||||
|
value={name}
|
||||||
|
autoComplete="name"
|
||||||
|
error={fieldErrors.name}
|
||||||
|
onChange={(e) => {
|
||||||
|
setName(e.target.value);
|
||||||
|
setFieldErrors((prev) => ({ ...prev, name: undefined }));
|
||||||
|
}}
|
||||||
|
onBlur={() => setFieldErrors((prev) => ({ ...prev, name: contactErrors().name }))}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
type="email"
|
||||||
|
inputMode="email"
|
||||||
|
label={t("email")}
|
||||||
|
placeholder={t("emailPlaceholder")}
|
||||||
|
value={email}
|
||||||
|
autoComplete="email"
|
||||||
|
error={fieldErrors.email}
|
||||||
|
onChange={(e) => {
|
||||||
|
setEmail(e.target.value);
|
||||||
|
setFieldErrors((prev) => ({ ...prev, email: undefined }));
|
||||||
|
}}
|
||||||
|
onBlur={() => setFieldErrors((prev) => ({ ...prev, email: contactErrors().email }))}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
type="tel"
|
||||||
|
inputMode="numeric"
|
||||||
|
label={t("phone")}
|
||||||
|
placeholder={t("phonePlaceholder")}
|
||||||
|
value={phone}
|
||||||
|
autoComplete="tel"
|
||||||
|
error={fieldErrors.phone}
|
||||||
|
onChange={(e) => {
|
||||||
|
setPhone(formatRuPhone(e.target.value));
|
||||||
|
setFieldErrors((prev) => ({ ...prev, phone: undefined }));
|
||||||
|
}}
|
||||||
|
onBlur={() => setFieldErrors((prev) => ({ ...prev, phone: contactErrors().phone }))}
|
||||||
|
onFocus={() => {
|
||||||
|
if (!phone.trim() || phone.trim() === "+") setPhone("+7");
|
||||||
|
}}
|
||||||
|
maxLength={16}
|
||||||
|
required
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
|||||||
@@ -95,15 +95,20 @@ export function BookingActions({ booking }: { booking: Booking }) {
|
|||||||
<p className="mt-1 text-sm text-[var(--text-muted)]">{booking.doctorName}</p>
|
<p className="mt-1 text-sm text-[var(--text-muted)]">{booking.doctorName}</p>
|
||||||
<p className="text-sm text-[var(--text-muted)]">{booking.branchName}</p>
|
<p className="text-sm text-[var(--text-muted)]">{booking.branchName}</p>
|
||||||
<p className="mt-2 text-sm font-medium">{formatDate(booking.datetime, locale)}</p>
|
<p className="mt-2 text-sm font-medium">{formatDate(booking.datetime, locale)}</p>
|
||||||
|
{booking.source === "inquiry" ? (
|
||||||
|
<p className="mt-2 text-sm text-[var(--text-muted)]">{t("requestPending")}</p>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-right">
|
<div className="text-right">
|
||||||
<p className="text-sm font-semibold text-[var(--brand-700)]">{statusLabel}</p>
|
<p className="text-sm font-semibold text-[var(--brand-700)]">{statusLabel}</p>
|
||||||
<p className="mt-1 text-sm">{formatPrice(booking.price, locale)}</p>
|
{booking.price ? <p className="mt-1 text-sm">{formatPrice(booking.price, locale)}</p> : null}
|
||||||
<p className="text-xs text-[var(--neutral-500)]">{paid ? t("paid") : t("unpaid")}</p>
|
{booking.source === "inquiry" ? null : (
|
||||||
|
<p className="text-xs text-[var(--neutral-500)]">{paid ? t("paid") : t("unpaid")}</p>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{status === "upcoming" ? (
|
{status === "upcoming" && booking.source !== "inquiry" ? (
|
||||||
<div className="mt-4 flex flex-wrap gap-2">
|
<div className="mt-4 flex flex-wrap gap-2">
|
||||||
{!paid ? (
|
{!paid ? (
|
||||||
<Button size="sm" onClick={pay} disabled={pending}>
|
<Button size="sm" onClick={pay} disabled={pending}>
|
||||||
@@ -161,7 +166,7 @@ export function BookingActions({ booking }: { booking: Booking }) {
|
|||||||
|
|
||||||
{reviewDone ? <p className="mt-3 text-sm text-[var(--success)]">{tr("thanks")}</p> : null}
|
{reviewDone ? <p className="mt-3 text-sm text-[var(--success)]">{tr("thanks")}</p> : null}
|
||||||
|
|
||||||
{status === "upcoming" ? (
|
{status === "upcoming" && booking.source !== "inquiry" ? (
|
||||||
<p className="mt-3 text-xs text-[var(--neutral-500)]">
|
<p className="mt-3 text-xs text-[var(--neutral-500)]">
|
||||||
<Link href="/booking" className="underline">
|
<Link href="/booking" className="underline">
|
||||||
{t("reschedule")}
|
{t("reschedule")}
|
||||||
|
|||||||
@@ -29,6 +29,11 @@ const linkKeys = [
|
|||||||
{ href: "/gallery" as const, key: "gallery" },
|
{ href: "/gallery" as const, key: "gallery" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const extraUsefulLinks = [
|
||||||
|
{ href: "https://www.monikiweb.ru/", key: "instituteHome" as const },
|
||||||
|
{ href: "https://edu.monikiweb.ru/", key: "education" as const },
|
||||||
|
];
|
||||||
|
|
||||||
function telHref(phone: string) {
|
function telHref(phone: string) {
|
||||||
const value = phone.replace(/[^\d+]/g, "");
|
const value = phone.replace(/[^\d+]/g, "");
|
||||||
return value ? `tel:${value}` : undefined;
|
return value ? `tel:${value}` : undefined;
|
||||||
@@ -71,7 +76,11 @@ export async function Footer() {
|
|||||||
<footer className="mt-auto border-t border-[var(--border)] bg-[var(--surface)]">
|
<footer className="mt-auto border-t border-[var(--border)] bg-[var(--surface)]">
|
||||||
<div className="mx-auto grid max-w-6xl gap-10 px-4 py-12 sm:px-6 md:grid-cols-2 lg:grid-cols-5">
|
<div className="mx-auto grid max-w-6xl gap-10 px-4 py-12 sm:px-6 md:grid-cols-2 lg:grid-cols-5">
|
||||||
<div>
|
<div>
|
||||||
<Logo imgClassName="h-16 w-16" showTagline={false} />
|
<Logo
|
||||||
|
className="w-full justify-center"
|
||||||
|
imgClassName="h-20 w-auto max-h-none sm:h-24"
|
||||||
|
showTagline={false}
|
||||||
|
/>
|
||||||
<p className="mt-2 text-sm leading-relaxed text-[var(--text-muted)]">{footer("about")}</p>
|
<p className="mt-2 text-sm leading-relaxed text-[var(--text-muted)]">{footer("about")}</p>
|
||||||
<p className="mt-4 text-sm text-[var(--neutral-700)]">{hero("address")}</p>
|
<p className="mt-4 text-sm text-[var(--neutral-700)]">{hero("address")}</p>
|
||||||
<p className="mt-1 text-sm font-semibold text-[var(--brand-700)]">
|
<p className="mt-1 text-sm font-semibold text-[var(--brand-700)]">
|
||||||
@@ -143,6 +152,18 @@ export async function Footer() {
|
|||||||
</p>
|
</p>
|
||||||
<nav aria-label={footer("useful")}>
|
<nav aria-label={footer("useful")}>
|
||||||
<ul className="mt-3 space-y-2">
|
<ul className="mt-3 space-y-2">
|
||||||
|
{extraUsefulLinks.map((item) => (
|
||||||
|
<li key={item.href}>
|
||||||
|
<a
|
||||||
|
href={item.href}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="text-sm text-[var(--neutral-700)] hover:text-[var(--brand-700)]"
|
||||||
|
>
|
||||||
|
{footer(item.key)}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
{usefulLinks.map((page) => (
|
{usefulLinks.map((page) => (
|
||||||
<li key={page.slug}>
|
<li key={page.slug}>
|
||||||
<Link
|
<Link
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { HeaderContacts } from "@/components/layout/HeaderContacts";
|
||||||
import { HeaderTools } from "@/components/layout/HeaderTools";
|
import { HeaderTools } from "@/components/layout/HeaderTools";
|
||||||
import { LocaleSwitcher } from "@/components/layout/LocaleSwitcher";
|
import { LocaleSwitcher } from "@/components/layout/LocaleSwitcher";
|
||||||
import { Logo } from "@/components/layout/Logo";
|
import { Logo } from "@/components/layout/Logo";
|
||||||
@@ -37,18 +38,20 @@ export function Header() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="sticky top-0 z-50 border-b border-[var(--border)] bg-[var(--surface)]">
|
<header className="sticky top-0 z-50 border-b border-[var(--border)] bg-[var(--surface)]">
|
||||||
<div className="mx-auto flex h-[var(--header-h)] max-w-7xl items-center gap-3 px-4 sm:px-6">
|
<div className="mx-auto flex h-[var(--header-h)] w-full max-w-[1600px] items-center gap-3 px-4 sm:px-6">
|
||||||
<Logo tagline={meta("tagline")} className="min-w-0 shrink-0" />
|
<Logo tagline={meta("tagline")} className="min-w-0 shrink-0" />
|
||||||
|
<span className="hidden h-10 w-px shrink-0 bg-[var(--border)] xl:block" aria-hidden />
|
||||||
|
<HeaderContacts className="hidden xl:flex" />
|
||||||
|
|
||||||
<nav
|
<nav
|
||||||
className="hidden min-w-0 flex-1 items-center justify-end gap-0 lg:flex"
|
className="hidden min-w-0 flex-1 items-center justify-end overflow-hidden lg:flex"
|
||||||
aria-label={a11y("mainNav")}
|
aria-label={a11y("mainNav")}
|
||||||
>
|
>
|
||||||
{links.map((l) => (
|
{links.map((l) => (
|
||||||
<Link
|
<Link
|
||||||
key={l.href}
|
key={l.href}
|
||||||
href={l.href}
|
href={l.href}
|
||||||
className="whitespace-nowrap rounded-lg px-2.5 py-2 text-base font-medium text-[var(--neutral-700)] transition hover:bg-[var(--brand-50)] hover:text-[var(--brand-700)]"
|
className="whitespace-nowrap rounded-lg px-2 py-2 text-[15px] font-medium text-[var(--neutral-700)] transition hover:bg-[var(--brand-50)] hover:text-[var(--brand-700)]"
|
||||||
>
|
>
|
||||||
{t(l.key)}
|
{t(l.key)}
|
||||||
</Link>
|
</Link>
|
||||||
@@ -109,6 +112,7 @@ export function Header() {
|
|||||||
<Button size="sm">{t("cabinet")}</Button>
|
<Button size="sm">{t("cabinet")}</Button>
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
<HeaderContacts stacked className="mt-4 border-t border-[var(--border)] pt-4 lg:hidden" />
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|||||||
@@ -0,0 +1,77 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import { Clock, Phone01 } from "@untitledui/icons";
|
||||||
|
import { useTranslations } from "next-intl";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
function IconWell({ children }: { children: ReactNode }) {
|
||||||
|
return (
|
||||||
|
<span className="flex h-8 w-8 shrink-0 items-center justify-center rounded-[10px] bg-[var(--brand-50)] text-[var(--brand-700)]">
|
||||||
|
{children}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function HeaderContacts({
|
||||||
|
className,
|
||||||
|
stacked = false,
|
||||||
|
}: {
|
||||||
|
className?: string;
|
||||||
|
stacked?: boolean;
|
||||||
|
}) {
|
||||||
|
const t = useTranslations("header");
|
||||||
|
const hero = useTranslations("hero");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
stacked ? "flex flex-col items-stretch gap-3" : "flex min-w-0 items-center gap-3",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"min-w-0 items-center gap-2.5",
|
||||||
|
stacked ? "flex" : "hidden min-[1480px]:flex",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<IconWell>
|
||||||
|
<Clock size={16} aria-hidden />
|
||||||
|
</IconWell>
|
||||||
|
<p className="min-w-0 leading-snug">
|
||||||
|
<span className="sr-only">{t("hoursLabel")}. </span>
|
||||||
|
<span className="block text-[13px] font-semibold tracking-tight text-[var(--brand-700)]">
|
||||||
|
{t("hoursWeekdays")}
|
||||||
|
</span>
|
||||||
|
<span className="block text-[12px] text-[var(--neutral-500)]">{t("hoursWeekend")}</span>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{!stacked ? (
|
||||||
|
<span className="hidden h-8 w-px shrink-0 bg-[var(--border)] min-[1480px]:block" aria-hidden />
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<div className={cn("min-w-0 items-center gap-2.5", stacked ? "flex" : "hidden xl:flex")}>
|
||||||
|
<IconWell>
|
||||||
|
<Phone01 size={16} aria-hidden />
|
||||||
|
</IconWell>
|
||||||
|
<p className="min-w-0 leading-snug">
|
||||||
|
<span className="sr-only">{t("phoneLabel")}. </span>
|
||||||
|
<a
|
||||||
|
href="tel:+74996740709"
|
||||||
|
className="block text-[13px] font-semibold tracking-tight text-[var(--brand-700)] transition hover:text-[var(--brand-800)]"
|
||||||
|
>
|
||||||
|
{hero("phone")}
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href="tel:122"
|
||||||
|
className="block text-[12px] font-medium text-[var(--neutral-500)] transition hover:text-[var(--brand-700)]"
|
||||||
|
>
|
||||||
|
{hero("phoneAlt")}
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { Link } from "@/i18n/routing";
|
import { Link } from "@/i18n/routing";
|
||||||
|
import { APP_VERSION } from "@/lib/version";
|
||||||
import { cn } from "@/lib/utils";
|
import { cn } from "@/lib/utils";
|
||||||
|
|
||||||
export function Logo({
|
export function Logo({
|
||||||
@@ -16,9 +17,9 @@ export function Logo({
|
|||||||
<Link href="/" className={cn("group flex items-center gap-2.5", className)}>
|
<Link href="/" className={cn("group flex items-center gap-2.5", className)}>
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img
|
<img
|
||||||
src="/logo.png"
|
src={`/logo.png?v=${APP_VERSION}`}
|
||||||
alt="МОНИКИ"
|
alt="МОНИКИ"
|
||||||
className={cn("h-12 w-12 shrink-0 rounded-full object-contain", imgClassName)}
|
className={cn("h-12 w-auto max-h-14 shrink-0 object-contain sm:h-14", imgClassName)}
|
||||||
/>
|
/>
|
||||||
{showTagline && tagline ? (
|
{showTagline && tagline ? (
|
||||||
<span className="hidden max-w-[7.5rem] text-[11px] leading-tight text-[var(--neutral-500)] xl:block">
|
<span className="hidden max-w-[7.5rem] text-[11px] leading-tight text-[var(--neutral-500)] xl:block">
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { Card } from "@/components/ui/Card";
|
import { Card } from "@/components/ui/Card";
|
||||||
import {
|
import {
|
||||||
FALLBACK_PUBLIC_CONTRACT_HREF,
|
FALLBACK_PUBLIC_DOCUMENTS,
|
||||||
getPublicDocuments,
|
getPublicDocuments,
|
||||||
type PublicDocument,
|
type PublicDocument,
|
||||||
} from "@/lib/api";
|
} from "@/lib/api";
|
||||||
@@ -19,16 +19,7 @@ function fileLabel(item: PublicDocument) {
|
|||||||
export async function PublicDocumentsList({ locale }: { locale: string }) {
|
export async function PublicDocumentsList({ locale }: { locale: string }) {
|
||||||
const t = await getTranslations("legal.documentsPage");
|
const t = await getTranslations("legal.documentsPage");
|
||||||
const docs = await getPublicDocuments(locale);
|
const docs = await getPublicDocuments(locale);
|
||||||
const items: PublicDocument[] = docs.length
|
const items: PublicDocument[] = docs.length ? docs : FALLBACK_PUBLIC_DOCUMENTS;
|
||||||
? docs
|
|
||||||
: [
|
|
||||||
{
|
|
||||||
id: 0,
|
|
||||||
title: t("contractTitle"),
|
|
||||||
href: FALLBACK_PUBLIC_CONTRACT_HREF,
|
|
||||||
filename: "Dogovor-platnie-2026.docx",
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ul className="space-y-4">
|
<ul className="space-y-4">
|
||||||
|
|||||||
+243
-27
@@ -1,7 +1,6 @@
|
|||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
import {
|
import {
|
||||||
demoBanners,
|
demoBanners,
|
||||||
demoBookings,
|
|
||||||
demoBranches,
|
demoBranches,
|
||||||
demoDoctors,
|
demoDoctors,
|
||||||
demoGallery,
|
demoGallery,
|
||||||
@@ -46,15 +45,15 @@ function withLocale(query: URLSearchParams, locale?: string | null) {
|
|||||||
return query;
|
return query;
|
||||||
}
|
}
|
||||||
|
|
||||||
type FetchOptions = RequestInit & { token?: string | null; fallback?: unknown };
|
type FetchOptions = RequestInit & { token?: string | null; fallback?: unknown; timeoutMs?: number };
|
||||||
|
|
||||||
async function cmsFetch<T>(path: string, options: FetchOptions = {}): Promise<T> {
|
async function cmsFetch<T>(path: string, options: FetchOptions = {}): Promise<T> {
|
||||||
const { token, fallback, ...init } = options;
|
const { token, fallback, timeoutMs, ...init } = options;
|
||||||
const headers = new Headers(init.headers);
|
const headers = new Headers(init.headers);
|
||||||
headers.set("Content-Type", "application/json");
|
headers.set("Content-Type", "application/json");
|
||||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||||
|
|
||||||
const timeout = AbortSignal.timeout(5000);
|
const timeout = AbortSignal.timeout(timeoutMs ?? 5000);
|
||||||
const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -170,6 +169,83 @@ function asText(value: unknown): string {
|
|||||||
return "";
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isPatientToken(token: string | null): token is string {
|
||||||
|
return Boolean(token) && token !== "demo-token";
|
||||||
|
}
|
||||||
|
|
||||||
|
function relRecord(value: unknown): Record<string, unknown> | null {
|
||||||
|
return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapInquiryBooking(raw: Record<string, unknown>): Booking {
|
||||||
|
const service = relRecord(raw.service);
|
||||||
|
const doctor = relRecord(raw.doctor);
|
||||||
|
const branch = relRecord(raw.branch);
|
||||||
|
return {
|
||||||
|
id: `inquiry-${raw.id}`,
|
||||||
|
serviceTitle: stripPriceListIndex(asText(service?.title)) || (doctor ? "Приём врача" : "Заявка на запись"),
|
||||||
|
doctorName: asText(doctor?.fullName) || "—",
|
||||||
|
branchName: asText(branch?.name),
|
||||||
|
datetime: asText(raw.createdAt),
|
||||||
|
status: asText(raw.status) === "done" ? "completed" : "upcoming",
|
||||||
|
price: Number(service?.price) || 0,
|
||||||
|
paid: false,
|
||||||
|
source: "inquiry",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapCmsBooking(raw: Record<string, unknown>): Booking {
|
||||||
|
const service = relRecord(raw.service);
|
||||||
|
const doctor = relRecord(raw.doctor);
|
||||||
|
const branch = relRecord(raw.branch);
|
||||||
|
const statusRaw = asText(raw.status);
|
||||||
|
const status: Booking["status"] =
|
||||||
|
statusRaw === "completed" ? "completed" : statusRaw === "cancelled" || statusRaw === "expired" ? "cancelled" : "upcoming";
|
||||||
|
return {
|
||||||
|
id: String(raw.id ?? ""),
|
||||||
|
serviceTitle: stripPriceListIndex(asText(service?.title)) || "Услуга",
|
||||||
|
doctorName: asText(doctor?.fullName) || "—",
|
||||||
|
branchName: asText(branch?.name),
|
||||||
|
datetime: asText(raw.startsAt) || asText(raw.createdAt),
|
||||||
|
status,
|
||||||
|
price: Number(raw.price) || Number(service?.price) || 0,
|
||||||
|
paid: asText(raw.paymentStatus) === "paid",
|
||||||
|
source: "booking",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapFavorite(raw: Record<string, unknown>): Service | Doctor | null {
|
||||||
|
const doctor = relRecord(raw.doctor);
|
||||||
|
if (doctor) {
|
||||||
|
return {
|
||||||
|
id: String(doctor.id ?? raw.id ?? ""),
|
||||||
|
slug: asText(doctor.slug),
|
||||||
|
name: asText(doctor.fullName) || asText(doctor.name),
|
||||||
|
specialty: asText(doctor.specialty) || asText(doctor.position),
|
||||||
|
experienceYears: Number(doctor.experienceYears) || 0,
|
||||||
|
photo: mediaSrc(doctor.photo),
|
||||||
|
bio: asText(doctor.bio),
|
||||||
|
rating: Number(doctor.rating) || 0,
|
||||||
|
reviewsCount: Number(doctor.reviewsCount) || 0,
|
||||||
|
services: [],
|
||||||
|
branchIds: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const service = relRecord(raw.service);
|
||||||
|
if (service) {
|
||||||
|
return {
|
||||||
|
id: String(service.id ?? raw.id ?? ""),
|
||||||
|
slug: asText(service.slug),
|
||||||
|
title: asText(service.title),
|
||||||
|
category: asText(service.groupTitle) || asText(service.category),
|
||||||
|
price: Number(service.price) || 0,
|
||||||
|
durationMin: Number(service.durationMin) || 0,
|
||||||
|
description: asText(service.description),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
function mapIds(value: unknown): string[] {
|
function mapIds(value: unknown): string[] {
|
||||||
if (!Array.isArray(value)) return [];
|
if (!Array.isArray(value)) return [];
|
||||||
return value.map((item) => {
|
return value.map((item) => {
|
||||||
@@ -190,13 +266,9 @@ function mapDoctor(raw: Record<string, unknown>): Doctor {
|
|||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(" ")
|
.join(" ")
|
||||||
: "";
|
: "";
|
||||||
const mediaUrl =
|
// An uploaded photo (media library) wins over the legacy photoUrl link.
|
||||||
typeof raw.photo === "string"
|
const mediaUrl = raw.photo && typeof raw.photo === "object" ? mediaSrc(raw.photo) : "";
|
||||||
? raw.photo
|
const photoUrl = mediaUrl || resolveAssetUrl(asText(raw.photoUrl));
|
||||||
: raw.photo && typeof raw.photo === "object"
|
|
||||||
? asText((raw.photo as Record<string, unknown>).url)
|
|
||||||
: "";
|
|
||||||
const photoUrl = asText(raw.photoUrl) || mediaUrl;
|
|
||||||
const photoPending = Boolean(raw.photoPending) || !photoUrl;
|
const photoPending = Boolean(raw.photoPending) || !photoUrl;
|
||||||
const name = asText(raw.name) || asText(raw.fullName);
|
const name = asText(raw.name) || asText(raw.fullName);
|
||||||
|
|
||||||
@@ -664,10 +736,24 @@ export async function getNewsBySlug(slug: string, locale = "ru"): Promise<NewsIt
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function getGallery(locale = "ru"): Promise<GalleryItem[]> {
|
export async function getGallery(locale = "ru"): Promise<GalleryItem[]> {
|
||||||
const query = withLocale(new URLSearchParams({ limit: "100", depth: "1" }), locale);
|
const query = withLocale(new URLSearchParams({ limit: "100", depth: "1", sort: "sortOrder" }), locale);
|
||||||
return cmsFetch<GalleryItem[]>(`/api/gallery?${query}`, { fallback: demoGallery }).then((data) =>
|
try {
|
||||||
unwrapList(data as PayloadList<GalleryItem> | GalleryItem[]),
|
const data = await cmsFetch<PayloadList<Record<string, unknown>>>(`/api/gallery?${query}`, {
|
||||||
);
|
cache: "no-store",
|
||||||
|
});
|
||||||
|
const items = unwrapList(data)
|
||||||
|
.map((raw) => ({
|
||||||
|
id: String(raw.id ?? ""),
|
||||||
|
title: asText(raw.title),
|
||||||
|
image: mediaSrc(raw.image),
|
||||||
|
category: asText(raw.category),
|
||||||
|
}))
|
||||||
|
.filter((item) => item.id && item.image);
|
||||||
|
if (items.length) return items;
|
||||||
|
} catch {
|
||||||
|
// fall through to demo
|
||||||
|
}
|
||||||
|
return demoGallery;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getReviews(
|
export async function getReviews(
|
||||||
@@ -767,6 +853,31 @@ export async function createBooking(payload: {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function createInquiry(payload: {
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
phone: string;
|
||||||
|
branchId: string;
|
||||||
|
serviceId?: string;
|
||||||
|
doctorId?: string;
|
||||||
|
}): Promise<{ id: string }> {
|
||||||
|
const data: Record<string, unknown> = {
|
||||||
|
name: payload.name,
|
||||||
|
email: payload.email,
|
||||||
|
phone: payload.phone,
|
||||||
|
branch: Number(payload.branchId) || payload.branchId,
|
||||||
|
status: "new",
|
||||||
|
};
|
||||||
|
if (payload.serviceId) data.service = Number(payload.serviceId) || payload.serviceId;
|
||||||
|
if (payload.doctorId) data.doctor = Number(payload.doctorId) || payload.doctorId;
|
||||||
|
return cmsFetch(`/api/custom/inquiries`, {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
cache: "no-store",
|
||||||
|
timeoutMs: 30000,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export async function cancelBooking(id: string): Promise<void> {
|
export async function cancelBooking(id: string): Promise<void> {
|
||||||
const token = await getAuthToken();
|
const token = await getAuthToken();
|
||||||
await cmsFetch(`/api/bookings/${id}`, {
|
await cmsFetch(`/api/bookings/${id}`, {
|
||||||
@@ -827,11 +938,16 @@ export async function createReview(payload: {
|
|||||||
|
|
||||||
export async function getFavorites(): Promise<(Service | Doctor)[]> {
|
export async function getFavorites(): Promise<(Service | Doctor)[]> {
|
||||||
const token = await getAuthToken();
|
const token = await getAuthToken();
|
||||||
return cmsFetch(`/api/favorites`, {
|
if (!isPatientToken(token)) return [];
|
||||||
|
return cmsFetch(`/api/favorites?depth=1&limit=50`, {
|
||||||
token,
|
token,
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
fallback: [],
|
fallback: { docs: [] },
|
||||||
}).then((data) => unwrapList(data as PayloadList<Service | Doctor> | (Service | Doctor)[]));
|
}).then((data) =>
|
||||||
|
unwrapList(data as PayloadList<Record<string, unknown>> | Record<string, unknown>[])
|
||||||
|
.map(mapFavorite)
|
||||||
|
.filter((item): item is Service | Doctor => Boolean(item)),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function addFavorite(payload: {
|
export async function addFavorite(payload: {
|
||||||
@@ -860,11 +976,80 @@ export async function removeFavorite(id: string): Promise<void> {
|
|||||||
|
|
||||||
export async function getMyBookings(): Promise<Booking[]> {
|
export async function getMyBookings(): Promise<Booking[]> {
|
||||||
const token = await getAuthToken();
|
const token = await getAuthToken();
|
||||||
return cmsFetch<Booking[]>(`/api/bookings?mine=true`, {
|
if (!isPatientToken(token)) return [];
|
||||||
token,
|
const [inquiries, bookings] = await Promise.all([
|
||||||
cache: "no-store",
|
cmsFetch<PayloadList<Record<string, unknown>>>(`/api/inquiries?limit=50&depth=2&sort=-createdAt`, {
|
||||||
fallback: demoBookings,
|
token,
|
||||||
}).then((data) => unwrapList(data as PayloadList<Booking> | Booking[]));
|
cache: "no-store",
|
||||||
|
fallback: { docs: [] },
|
||||||
|
}).catch(() => ({ docs: [] })),
|
||||||
|
cmsFetch<PayloadList<Record<string, unknown>>>(`/api/bookings?limit=50&depth=2&sort=-startsAt`, {
|
||||||
|
token,
|
||||||
|
cache: "no-store",
|
||||||
|
fallback: { docs: [] },
|
||||||
|
}).catch(() => ({ docs: [] })),
|
||||||
|
]);
|
||||||
|
return [
|
||||||
|
...unwrapList(inquiries).map(mapInquiryBooking),
|
||||||
|
...unwrapList(bookings).map(mapCmsBooking),
|
||||||
|
].sort((a, b) => Date.parse(b.datetime) - Date.parse(a.datetime));
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CabinetDocument = {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
href: string;
|
||||||
|
issuedAt?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getMyDocuments(): Promise<CabinetDocument[]> {
|
||||||
|
const token = await getAuthToken();
|
||||||
|
if (!isPatientToken(token)) return [];
|
||||||
|
const data = await cmsFetch<PayloadList<Record<string, unknown>>>(
|
||||||
|
`/api/documents?depth=1&limit=50&sort=-issuedAt&where[isPublic][equals]=false`,
|
||||||
|
{ token, cache: "no-store", fallback: { docs: [] } },
|
||||||
|
).catch(() => ({ docs: [] as Record<string, unknown>[] }));
|
||||||
|
return unwrapList(data)
|
||||||
|
.map((raw) => {
|
||||||
|
const file = raw.file && typeof raw.file === "object" ? (raw.file as Record<string, unknown>) : null;
|
||||||
|
// Patient files are private in the CMS: download them through the site with the session token.
|
||||||
|
const filename = asText(file?.filename);
|
||||||
|
const href = filename ? `/api/cabinet/files/${encodeURIComponent(filename)}` : mediaSrc(file);
|
||||||
|
const title = asText(raw.title);
|
||||||
|
if (!title || !href) return null;
|
||||||
|
return { id: String(raw.id ?? ""), title, href, issuedAt: asText(raw.issuedAt) || undefined };
|
||||||
|
})
|
||||||
|
.filter((item): item is CabinetDocument => Boolean(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
export type CabinetInvoice = {
|
||||||
|
id: string;
|
||||||
|
number: string;
|
||||||
|
title: string;
|
||||||
|
amount: number;
|
||||||
|
paid: boolean;
|
||||||
|
datetime: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function getMyInvoices(): Promise<CabinetInvoice[]> {
|
||||||
|
const token = await getAuthToken();
|
||||||
|
if (!isPatientToken(token)) return [];
|
||||||
|
const data = await cmsFetch<PayloadList<Record<string, unknown>>>(
|
||||||
|
`/api/invoices?depth=2&limit=50&sort=-createdAt`,
|
||||||
|
{ token, cache: "no-store", fallback: { docs: [] } },
|
||||||
|
).catch(() => ({ docs: [] as Record<string, unknown>[] }));
|
||||||
|
return unwrapList(data).map((raw) => {
|
||||||
|
const booking = relRecord(raw.booking);
|
||||||
|
const service = booking ? relRecord(booking.service) : null;
|
||||||
|
return {
|
||||||
|
id: String(raw.id ?? ""),
|
||||||
|
number: asText(raw.number) || String(raw.id ?? ""),
|
||||||
|
title: asText(service?.title) || asText(raw.number) || "Счёт",
|
||||||
|
amount: Number(raw.amount) || 0,
|
||||||
|
paid: asText(raw.status) === "paid",
|
||||||
|
datetime: asText(raw.paidAt) || asText(raw.createdAt),
|
||||||
|
};
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function me(): Promise<{
|
export async function me(): Promise<{
|
||||||
@@ -874,13 +1059,22 @@ export async function me(): Promise<{
|
|||||||
phone?: string;
|
phone?: string;
|
||||||
} | null> {
|
} | null> {
|
||||||
const token = await getAuthToken();
|
const token = await getAuthToken();
|
||||||
if (!token) return null;
|
if (!isPatientToken(token)) return null;
|
||||||
try {
|
try {
|
||||||
return await cmsFetch(`/api/users/me`, {
|
const data = await cmsFetch<Record<string, unknown>>(`/api/users/me`, {
|
||||||
token,
|
token,
|
||||||
cache: "no-store",
|
cache: "no-store",
|
||||||
fallback: { id: "demo", email: "patient@example.com", name: "Пациент", phone: "+7" },
|
|
||||||
});
|
});
|
||||||
|
const user = relRecord(data.user) || data;
|
||||||
|
const email = asText(user.email);
|
||||||
|
const id = user.id != null ? String(user.id) : "";
|
||||||
|
if (!email || !id || id === "demo") return null;
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
email,
|
||||||
|
name: asText(user.fullName) || asText(user.name) || undefined,
|
||||||
|
phone: asText(user.phone) || undefined,
|
||||||
|
};
|
||||||
} catch {
|
} catch {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -1059,7 +1253,29 @@ export type PublicDocument = {
|
|||||||
issuedAt?: string;
|
issuedAt?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const FALLBACK_PUBLIC_CONTRACT_HREF = "/documents/Dogovor-platnie-2026.docx";
|
export const FALLBACK_PUBLIC_DOCUMENTS: PublicDocument[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
title: "Согласие пациента на обработку персональных данных",
|
||||||
|
href: "/documents/Soglasie-personalnye-dannye.rtf",
|
||||||
|
filename: "Soglasie-personalnye-dannye.rtf",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
title:
|
||||||
|
"Информированное добровольное согласие пациента (законного представителя пациента) на медицинское вмешательство, предоставление сведений, составляющих врачебную тайну, и консультацию врача-специалиста с применением телемедицинских технологий",
|
||||||
|
href: "/documents/IDS-meditsinskoe-vmeshatelstvo.docx",
|
||||||
|
filename: "IDS-meditsinskoe-vmeshatelstvo.docx",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 3,
|
||||||
|
title: "Договор на оказание платных медицинских услуг (с физическим лицом)",
|
||||||
|
href: "/documents/Dogovor-platnye-uslugi-fiz-litso.docx",
|
||||||
|
filename: "Dogovor-platnye-uslugi-fiz-litso.docx",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
export const FALLBACK_PUBLIC_CONTRACT_HREF = FALLBACK_PUBLIC_DOCUMENTS[2].href;
|
||||||
|
|
||||||
export async function getPublicDocuments(locale = "ru"): Promise<PublicDocument[]> {
|
export async function getPublicDocuments(locale = "ru"): Promise<PublicDocument[]> {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[A-Za-z0-9-]{2,}$/
|
||||||
|
|
||||||
|
export function isValidFullName(value: string) {
|
||||||
|
const name = value.trim().replace(/\s+/g, " ")
|
||||||
|
if (name.length < 3) return false
|
||||||
|
const parts = name.split(" ").filter(Boolean)
|
||||||
|
if (parts.length < 2) return false
|
||||||
|
return /^[\p{L}][\p{L}\s'-]*$/u.test(name)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isValidEmailAddress(value: string) {
|
||||||
|
const email = value.trim()
|
||||||
|
return EMAIL_RE.test(email)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function ruPhoneDigits(value: string) {
|
||||||
|
let digits = value.replace(/\D/g, "")
|
||||||
|
if (digits.startsWith("8")) digits = `7${digits.slice(1)}`
|
||||||
|
if (!digits.startsWith("7")) digits = `7${digits}`
|
||||||
|
return digits.slice(0, 11)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatRuPhone(value: string) {
|
||||||
|
const digits = ruPhoneDigits(value)
|
||||||
|
const local = digits.slice(1)
|
||||||
|
let formatted = "+7"
|
||||||
|
if (local.length > 0) formatted += ` ${local.slice(0, 3)}`
|
||||||
|
if (local.length > 3) formatted += ` ${local.slice(3, 6)}`
|
||||||
|
if (local.length > 6) formatted += ` ${local.slice(6, 8)}`
|
||||||
|
if (local.length > 8) formatted += ` ${local.slice(8, 10)}`
|
||||||
|
return formatted
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeRuPhone(value: string) {
|
||||||
|
const digits = ruPhoneDigits(value)
|
||||||
|
return digits.length === 11 ? `+${digits}` : ""
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isValidRuPhone(value: string) {
|
||||||
|
return /^\+7\d{10}$/.test(normalizeRuPhone(value))
|
||||||
|
}
|
||||||
@@ -131,6 +131,7 @@ export type Booking = {
|
|||||||
status: "upcoming" | "completed" | "cancelled";
|
status: "upcoming" | "completed" | "cancelled";
|
||||||
price: number;
|
price: number;
|
||||||
paid: boolean;
|
paid: boolean;
|
||||||
|
source?: "inquiry" | "booking";
|
||||||
};
|
};
|
||||||
|
|
||||||
export const demoServices: Service[] = [
|
export const demoServices: Service[] = [
|
||||||
|
|||||||
@@ -20,6 +20,12 @@
|
|||||||
"menu": "Меню",
|
"menu": "Меню",
|
||||||
"close": "Закрыць"
|
"close": "Закрыць"
|
||||||
},
|
},
|
||||||
|
"header": {
|
||||||
|
"hoursLabel": "Рэжым працы",
|
||||||
|
"hoursWeekdays": "Пн–Сб 08:00–20:00",
|
||||||
|
"hoursWeekend": "Нд 09:00–16:00",
|
||||||
|
"phoneLabel": "Тэлефон"
|
||||||
|
},
|
||||||
"a11y": {
|
"a11y": {
|
||||||
"open": "Спецыяльныя магчымасці",
|
"open": "Спецыяльныя магчымасці",
|
||||||
"title": "Налады даступнасці",
|
"title": "Налады даступнасці",
|
||||||
@@ -119,26 +125,36 @@
|
|||||||
},
|
},
|
||||||
"booking": {
|
"booking": {
|
||||||
"title": "Анлайн-запіс",
|
"title": "Анлайн-запіс",
|
||||||
"subtitle": "Абярыце паслугу ці ўрача, філіял і зручны час",
|
"subtitle": "Абярыце паслугу ці ўрача, філіял і пакіньце кантакты — мы звяжамся з вамі",
|
||||||
"stepService": "Паслуга / ўрач",
|
"stepService": "Паслуга / ўрач",
|
||||||
"stepBranch": "Філіял",
|
"stepBranch": "Філіял",
|
||||||
"stepSlot": "Дата і час",
|
"stepSlot": "Дата і час",
|
||||||
"stepConfirm": "Пацверджанне",
|
"stepConfirm": "Кантакты",
|
||||||
"selectService": "Абярыце паслугу",
|
"selectService": "Абярыце паслугу",
|
||||||
"selectDoctor": "Абярыце ўрача (неабавязкова)",
|
"selectDoctor": "Абярыце ўрача",
|
||||||
"selectBranch": "Абярыце філіял",
|
"selectBranch": "Абярыце філіял",
|
||||||
"selectDate": "Дата",
|
"selectDate": "Дата",
|
||||||
"selectTime": "Даступны час",
|
"selectTime": "Даступны час",
|
||||||
"noSlots": "Няма свабодных слотаў на гэтую дату",
|
"noSlots": "Няма свабодных слотаў на гэтую дату",
|
||||||
"confirm": "Пацвердзіць запіс",
|
"confirm": "Адправіць заяўку",
|
||||||
"success": "Запіс створаны",
|
"success": "Вялікі дзякуй!",
|
||||||
"successHint": "Мы дашлём напамін на email. Кіраваць запісам можна ў асабістым кабінеце.",
|
"successHint": "Мы абавязкова звяжамся з вамі ў бліжэйшы час і ўдакладнім усю інфармацыю.",
|
||||||
|
"error": "Не ўдалося адправіць заяўку. Патэлефануйце нам або паспрабуйце яшчэ раз.",
|
||||||
"next": "Далей",
|
"next": "Далей",
|
||||||
"back": "Назад",
|
"back": "Назад",
|
||||||
"patientName": "ПІБ",
|
"patientName": "ПІБ",
|
||||||
|
"email": "E-mail",
|
||||||
"phone": "Тэлефон",
|
"phone": "Тэлефон",
|
||||||
"summary": "Зводка запісу",
|
"summary": "Зводка заяўкі",
|
||||||
"searchService": "Знайдзіце паслугу па назве або кодзе"
|
"searchService": "Знайдзіце паслугу па назве або кодзе",
|
||||||
|
"namePlaceholder": "Іваноў Іван Іванавіч",
|
||||||
|
"emailPlaceholder": "ivan.ivanov@mail.ru",
|
||||||
|
"phonePlaceholder": "+7 900 123 45 67",
|
||||||
|
"nameRequired": "Укажыце ПІБ",
|
||||||
|
"nameInvalid": "Укажыце прозвішча і імя літарамі",
|
||||||
|
"emailRequired": "Укажыце e-mail",
|
||||||
|
"emailInvalid": "Укажыце e-mail у фармаце name@domain.ru",
|
||||||
|
"phoneInvalid": "Укажыце тэлефон у фармаце +7 і 10 лічбаў"
|
||||||
},
|
},
|
||||||
"branches": {
|
"branches": {
|
||||||
"title": "Філіялы",
|
"title": "Філіялы",
|
||||||
@@ -226,6 +242,8 @@
|
|||||||
"emptyFavorites": "Абранае пустое",
|
"emptyFavorites": "Абранае пустое",
|
||||||
"emptyDocuments": "Дакументаў пакуль няма",
|
"emptyDocuments": "Дакументаў пакуль няма",
|
||||||
"emptyInvoices": "Рахункаў пакуль няма",
|
"emptyInvoices": "Рахункаў пакуль няма",
|
||||||
|
"loginHint": "Увайдзіце ў асабісты кабінет, каб убачыць свае запісы, дакументы і рахункі.",
|
||||||
|
"requestPending": "Заяўка прынята. Мы звяжамся з вамі, каб удакладніць дату і час.",
|
||||||
"save": "Захаваць",
|
"save": "Захаваць",
|
||||||
"saved": "Захавана"
|
"saved": "Захавана"
|
||||||
},
|
},
|
||||||
@@ -236,8 +254,8 @@
|
|||||||
"doctorsSubtitle": "Урачы з вялікім клінічным досведам",
|
"doctorsSubtitle": "Урачы з вялікім клінічным досведам",
|
||||||
"allDoctors": "Усе ўрачы",
|
"allDoctors": "Усе ўрачы",
|
||||||
"allReviews": "Усе водгукі",
|
"allReviews": "Усе водгукі",
|
||||||
"ctaTitle": "Запішыцеся на зручны час",
|
"ctaTitle": "Пакіньце заяўку на прыём",
|
||||||
"ctaSubtitle": "Анлайн-запіс 24/7, напаміны і аплата праз СБП",
|
"ctaSubtitle": "Абярыце паслугу ці ўрача — мы звяжамся з вамі і ўдакладнім дэталі",
|
||||||
"branchesTitle": "Нашы адрасы",
|
"branchesTitle": "Нашы адрасы",
|
||||||
"branchesSubtitle": "Дзве зручныя лакацыі для прыёму",
|
"branchesSubtitle": "Дзве зручныя лакацыі для прыёму",
|
||||||
"newsTitle": "Навіны клінікі",
|
"newsTitle": "Навіны клінікі",
|
||||||
@@ -312,7 +330,7 @@
|
|||||||
"subtitle": "Дагаворы і іншыя файлы для пацыентаў платных паслуг.",
|
"subtitle": "Дагаворы і іншыя файлы для пацыентаў платных паслуг.",
|
||||||
"intro": "Спампуйце актуальныя дакументы па платных медыцынскіх паслугах МОНІКІ.",
|
"intro": "Спампуйце актуальныя дакументы па платных медыцынскіх паслугах МОНІКІ.",
|
||||||
"download": "Спампаваць",
|
"download": "Спампаваць",
|
||||||
"contractTitle": "Дагавор на аказанне платных медыцынскіх паслуг (2026)"
|
"contractTitle": "Дагавор на аказанне платных медыцынскіх паслуг (з фізічнай асобай)"
|
||||||
},
|
},
|
||||||
"discounts": {
|
"discounts": {
|
||||||
"title": "Зніжкі і льготы",
|
"title": "Зніжкі і льготы",
|
||||||
@@ -362,6 +380,8 @@
|
|||||||
"links": "Раздзелы",
|
"links": "Раздзелы",
|
||||||
"organization": "Арганізацыя",
|
"organization": "Арганізацыя",
|
||||||
"useful": "Карыснае",
|
"useful": "Карыснае",
|
||||||
|
"instituteHome": "Галоўная старонка інстытута",
|
||||||
|
"education": "Адукацыя",
|
||||||
"social": "Мы ў сацсетках",
|
"social": "Мы ў сацсетках",
|
||||||
"rights": "© МОНІКІ. Усе правы абаронены.",
|
"rights": "© МОНІКІ. Усе правы абаронены.",
|
||||||
"version": "Версія сайта v{version}",
|
"version": "Версія сайта v{version}",
|
||||||
|
|||||||
@@ -20,6 +20,12 @@
|
|||||||
"menu": "Menu",
|
"menu": "Menu",
|
||||||
"close": "Close"
|
"close": "Close"
|
||||||
},
|
},
|
||||||
|
"header": {
|
||||||
|
"hoursLabel": "Opening hours",
|
||||||
|
"hoursWeekdays": "Mon–Sat 08:00–20:00",
|
||||||
|
"hoursWeekend": "Sun 09:00–16:00",
|
||||||
|
"phoneLabel": "Phone"
|
||||||
|
},
|
||||||
"a11y": {
|
"a11y": {
|
||||||
"open": "Accessibility",
|
"open": "Accessibility",
|
||||||
"title": "Accessibility settings",
|
"title": "Accessibility settings",
|
||||||
@@ -119,26 +125,36 @@
|
|||||||
},
|
},
|
||||||
"booking": {
|
"booking": {
|
||||||
"title": "Online booking",
|
"title": "Online booking",
|
||||||
"subtitle": "Choose a service or doctor, branch, and time slot",
|
"subtitle": "Choose a service or doctor and a branch, then leave your contacts — we will call you back",
|
||||||
"stepService": "Service / doctor",
|
"stepService": "Service / doctor",
|
||||||
"stepBranch": "Branch",
|
"stepBranch": "Branch",
|
||||||
"stepSlot": "Date & time",
|
"stepSlot": "Date & time",
|
||||||
"stepConfirm": "Confirm",
|
"stepConfirm": "Contacts",
|
||||||
"selectService": "Select a service",
|
"selectService": "Select a service",
|
||||||
"selectDoctor": "Select a doctor (optional)",
|
"selectDoctor": "Select a doctor",
|
||||||
"selectBranch": "Select a branch",
|
"selectBranch": "Select a branch",
|
||||||
"selectDate": "Date",
|
"selectDate": "Date",
|
||||||
"selectTime": "Available times",
|
"selectTime": "Available times",
|
||||||
"noSlots": "No slots available for this date",
|
"noSlots": "No slots available for this date",
|
||||||
"confirm": "Confirm booking",
|
"confirm": "Send request",
|
||||||
"success": "Booking created",
|
"success": "Thank you!",
|
||||||
"successHint": "We will email a reminder. Manage bookings in your account.",
|
"successHint": "We will contact you shortly and confirm all the details.",
|
||||||
|
"error": "Could not send the request. Please call us or try again.",
|
||||||
"next": "Next",
|
"next": "Next",
|
||||||
"back": "Back",
|
"back": "Back",
|
||||||
"patientName": "Full name",
|
"patientName": "Full name",
|
||||||
|
"email": "E-mail",
|
||||||
"phone": "Phone",
|
"phone": "Phone",
|
||||||
"summary": "Booking summary",
|
"summary": "Request summary",
|
||||||
"searchService": "Find a service by name or code"
|
"searchService": "Find a service by name or code",
|
||||||
|
"namePlaceholder": "Ivanov Ivan Ivanovich",
|
||||||
|
"emailPlaceholder": "ivan.ivanov@mail.ru",
|
||||||
|
"phonePlaceholder": "+7 900 123 45 67",
|
||||||
|
"nameRequired": "Enter your full name",
|
||||||
|
"nameInvalid": "Enter last name and first name in letters",
|
||||||
|
"emailRequired": "Enter your e-mail",
|
||||||
|
"emailInvalid": "Enter an e-mail like name@domain.ru",
|
||||||
|
"phoneInvalid": "Enter a phone number as +7 and 10 digits"
|
||||||
},
|
},
|
||||||
"branches": {
|
"branches": {
|
||||||
"title": "Branches",
|
"title": "Branches",
|
||||||
@@ -226,6 +242,8 @@
|
|||||||
"emptyFavorites": "No favorites yet",
|
"emptyFavorites": "No favorites yet",
|
||||||
"emptyDocuments": "No documents yet",
|
"emptyDocuments": "No documents yet",
|
||||||
"emptyInvoices": "No invoices yet",
|
"emptyInvoices": "No invoices yet",
|
||||||
|
"loginHint": "Sign in to see your bookings, documents and invoices. Each patient has a personal account.",
|
||||||
|
"requestPending": "Your request was received. We will contact you to confirm the date and time.",
|
||||||
"save": "Save",
|
"save": "Save",
|
||||||
"saved": "Saved"
|
"saved": "Saved"
|
||||||
},
|
},
|
||||||
@@ -236,8 +254,8 @@
|
|||||||
"doctorsSubtitle": "Doctors with extensive clinical experience",
|
"doctorsSubtitle": "Doctors with extensive clinical experience",
|
||||||
"allDoctors": "All doctors",
|
"allDoctors": "All doctors",
|
||||||
"allReviews": "All reviews",
|
"allReviews": "All reviews",
|
||||||
"ctaTitle": "Book a convenient time",
|
"ctaTitle": "Leave a booking request",
|
||||||
"ctaSubtitle": "Online booking 24/7, reminders, and SBP payments",
|
"ctaSubtitle": "Choose a service or doctor — we will contact you to confirm the details",
|
||||||
"branchesTitle": "Our locations",
|
"branchesTitle": "Our locations",
|
||||||
"branchesSubtitle": "Two convenient campuses for appointments",
|
"branchesSubtitle": "Two convenient campuses for appointments",
|
||||||
"newsTitle": "Clinic news",
|
"newsTitle": "Clinic news",
|
||||||
@@ -312,7 +330,7 @@
|
|||||||
"subtitle": "Contracts and other files for paid-service patients.",
|
"subtitle": "Contracts and other files for paid-service patients.",
|
||||||
"intro": "Download current documents for paid medical services at MONIKI.",
|
"intro": "Download current documents for paid medical services at MONIKI.",
|
||||||
"download": "Download",
|
"download": "Download",
|
||||||
"contractTitle": "Paid medical services contract (2026)"
|
"contractTitle": "Paid medical services contract (with an individual)"
|
||||||
},
|
},
|
||||||
"discounts": {
|
"discounts": {
|
||||||
"title": "Discounts and benefits",
|
"title": "Discounts and benefits",
|
||||||
@@ -362,6 +380,8 @@
|
|||||||
"links": "Sections",
|
"links": "Sections",
|
||||||
"organization": "Organization",
|
"organization": "Organization",
|
||||||
"useful": "Useful",
|
"useful": "Useful",
|
||||||
|
"instituteHome": "Institute homepage",
|
||||||
|
"education": "Education",
|
||||||
"social": "Social media",
|
"social": "Social media",
|
||||||
"rights": "© MONIKI. All rights reserved.",
|
"rights": "© MONIKI. All rights reserved.",
|
||||||
"version": "Site version v{version}",
|
"version": "Site version v{version}",
|
||||||
|
|||||||
@@ -20,6 +20,12 @@
|
|||||||
"menu": "Меню",
|
"menu": "Меню",
|
||||||
"close": "Жабуу"
|
"close": "Жабуу"
|
||||||
},
|
},
|
||||||
|
"header": {
|
||||||
|
"hoursLabel": "Иш убактысы",
|
||||||
|
"hoursWeekdays": "Дш–Иш 08:00–20:00",
|
||||||
|
"hoursWeekend": "Жк 09:00–16:00",
|
||||||
|
"phoneLabel": "Телефон"
|
||||||
|
},
|
||||||
"a11y": {
|
"a11y": {
|
||||||
"open": "Атайын мүмкүнчүлүктөр",
|
"open": "Атайын мүмкүнчүлүктөр",
|
||||||
"title": "Жеткиликтүүлүк жөндөөлөрү",
|
"title": "Жеткиликтүүлүк жөндөөлөрү",
|
||||||
@@ -119,26 +125,36 @@
|
|||||||
},
|
},
|
||||||
"booking": {
|
"booking": {
|
||||||
"title": "Онлайн жазылуу",
|
"title": "Онлайн жазылуу",
|
||||||
"subtitle": "Кызмат же дарыгерди, филиалды жана ыңгайлуу убакытты тандаңыз",
|
"subtitle": "Кызмат же дарыгерди жана филиалды тандап, байланышыңызды калтырыңыз — биз сиз менен байланышабыз",
|
||||||
"stepService": "Кызмат / дарыгер",
|
"stepService": "Кызмат / дарыгер",
|
||||||
"stepBranch": "Филиал",
|
"stepBranch": "Филиал",
|
||||||
"stepSlot": "Дата жана убакыт",
|
"stepSlot": "Дата жана убакыт",
|
||||||
"stepConfirm": "Ырастоо",
|
"stepConfirm": "Байланыш",
|
||||||
"selectService": "Кызматты тандаңыз",
|
"selectService": "Кызматты тандаңыз",
|
||||||
"selectDoctor": "Дарыгерди тандаңыз (милдеттүү эмес)",
|
"selectDoctor": "Дарыгерди тандаңыз",
|
||||||
"selectBranch": "Филиалды тандаңыз",
|
"selectBranch": "Филиалды тандаңыз",
|
||||||
"selectDate": "Дата",
|
"selectDate": "Дата",
|
||||||
"selectTime": "Жеткиликтүү убакыт",
|
"selectTime": "Жеткиликтүү убакыт",
|
||||||
"noSlots": "Бул датага бош слот жок",
|
"noSlots": "Бул датага бош слот жок",
|
||||||
"confirm": "Жазылууну ырастоо",
|
"confirm": "Өтүнмө жөнөтүү",
|
||||||
"success": "Жазылуу түзүлдү",
|
"success": "Чоң рахмат!",
|
||||||
"successHint": "Эскертүүнү emailге жөнөтөбүз. Жазылууну жеке кабинеттен башкарыңыз.",
|
"successHint": "Биз жакын арада сиз менен байланышып, бардык маалыматты тактайбыз.",
|
||||||
|
"error": "Өтүнмө жөнөтүлгөн жок. Бизге чалыңыз же кайра аракет кылыңыз.",
|
||||||
"next": "Андан ары",
|
"next": "Андан ары",
|
||||||
"back": "Артка",
|
"back": "Артка",
|
||||||
"patientName": "Аты-жөнү",
|
"patientName": "Аты-жөнү",
|
||||||
|
"email": "E-mail",
|
||||||
"phone": "Телефон",
|
"phone": "Телефон",
|
||||||
"summary": "Жазылуу жыйынтыгы",
|
"summary": "Өтүнмөнүн жыйынтыгы",
|
||||||
"searchService": "Кызматты аталышы же коду боюнча табыңыз"
|
"searchService": "Кызматты аталышы же коду боюнча табыңыз",
|
||||||
|
"namePlaceholder": "Иванов Иван Иванович",
|
||||||
|
"emailPlaceholder": "ivan.ivanov@mail.ru",
|
||||||
|
"phonePlaceholder": "+7 900 123 45 67",
|
||||||
|
"nameRequired": "Аты-жөнүңүздү жазыңыз",
|
||||||
|
"nameInvalid": "Фамилия жана атын тамгалар менен жазыңыз",
|
||||||
|
"emailRequired": "E-mail жазыңыз",
|
||||||
|
"emailInvalid": "E-mailди name@domain.ru форматында жазыңыз",
|
||||||
|
"phoneInvalid": "Телефонду +7 жана 10 сан форматында жазыңыз"
|
||||||
},
|
},
|
||||||
"branches": {
|
"branches": {
|
||||||
"title": "Филиалдар",
|
"title": "Филиалдар",
|
||||||
@@ -226,6 +242,8 @@
|
|||||||
"emptyFavorites": "Тандалмалар бош",
|
"emptyFavorites": "Тандалмалар бош",
|
||||||
"emptyDocuments": "Азырынча документ жок",
|
"emptyDocuments": "Азырынча документ жок",
|
||||||
"emptyInvoices": "Азырынча эсеп жок",
|
"emptyInvoices": "Азырынча эсеп жок",
|
||||||
|
"loginHint": "Жазууларыңызды, документтерди жана эсептерди көрүү үчүн жеке кабинетке кириңиз.",
|
||||||
|
"requestPending": "Өтүнмө кабыл алынды. Биз дата менен убакытты тактоо үчүн байланышабыз.",
|
||||||
"save": "Сактоо",
|
"save": "Сактоо",
|
||||||
"saved": "Сакталды"
|
"saved": "Сакталды"
|
||||||
},
|
},
|
||||||
@@ -236,8 +254,8 @@
|
|||||||
"doctorsSubtitle": "Чоң клиникалык тажрыйбалуу дарыгерлер",
|
"doctorsSubtitle": "Чоң клиникалык тажрыйбалуу дарыгерлер",
|
||||||
"allDoctors": "Бардык дарыгерлер",
|
"allDoctors": "Бардык дарыгерлер",
|
||||||
"allReviews": "Бардык пикирлер",
|
"allReviews": "Бардык пикирлер",
|
||||||
"ctaTitle": "Ыңгайлуу убакытка жазылыңыз",
|
"ctaTitle": "Кабыл алуу өтүнмөсүн калтырыңыз",
|
||||||
"ctaSubtitle": "Онлайн жазылуу 24/7, эскертүүлөр жана СБП төлөмү",
|
"ctaSubtitle": "Кызмат же дарыгерди тандаңыз — биз сиз менен байланышып, деталдарды тактайбыз",
|
||||||
"branchesTitle": "Биздин даректер",
|
"branchesTitle": "Биздин даректер",
|
||||||
"branchesSubtitle": "Кабыл алуу үчүн эки ыңгайлуу жайгашкан жер",
|
"branchesSubtitle": "Кабыл алуу үчүн эки ыңгайлуу жайгашкан жер",
|
||||||
"newsTitle": "Клиника жаңылыктары",
|
"newsTitle": "Клиника жаңылыктары",
|
||||||
@@ -312,7 +330,7 @@
|
|||||||
"subtitle": "Акылуу кызматтардын бейтаптары үчүн келишимдер жана башка файлдар.",
|
"subtitle": "Акылуу кызматтардын бейтаптары үчүн келишимдер жана башка файлдар.",
|
||||||
"intro": "МОНИКИнин акылуу медициналык кызматтары боюнча актуалдуу документтерди жүктөп алыңыз.",
|
"intro": "МОНИКИнин акылуу медициналык кызматтары боюнча актуалдуу документтерди жүктөп алыңыз.",
|
||||||
"download": "Жүктөө",
|
"download": "Жүктөө",
|
||||||
"contractTitle": "Акылуу медициналык кызматтарды көрсөтүү келишими (2026)"
|
"contractTitle": "Акылуу медициналык кызматтарды көрсөтүү келишими (жеке жак менен)"
|
||||||
},
|
},
|
||||||
"discounts": {
|
"discounts": {
|
||||||
"title": "Арзандатуулар жана жеңилдиктер",
|
"title": "Арзандатуулар жана жеңилдиктер",
|
||||||
@@ -362,6 +380,8 @@
|
|||||||
"links": "Бөлүмдөр",
|
"links": "Бөлүмдөр",
|
||||||
"organization": "Уюм",
|
"organization": "Уюм",
|
||||||
"useful": "Пайдалуу",
|
"useful": "Пайдалуу",
|
||||||
|
"instituteHome": "Институттун башкы бети",
|
||||||
|
"education": "Билим берүү",
|
||||||
"social": "Соцтармактарда",
|
"social": "Соцтармактарда",
|
||||||
"rights": "© МОНИКИ. Бардык укуктар корголгон.",
|
"rights": "© МОНИКИ. Бардык укуктар корголгон.",
|
||||||
"version": "Сайттын версиясы v{version}",
|
"version": "Сайттын версиясы v{version}",
|
||||||
|
|||||||
@@ -20,6 +20,12 @@
|
|||||||
"menu": "Меню",
|
"menu": "Меню",
|
||||||
"close": "Закрыть"
|
"close": "Закрыть"
|
||||||
},
|
},
|
||||||
|
"header": {
|
||||||
|
"hoursLabel": "Режим работы",
|
||||||
|
"hoursWeekdays": "Пн–Сб 08:00–20:00",
|
||||||
|
"hoursWeekend": "Вс 09:00–16:00",
|
||||||
|
"phoneLabel": "Телефон"
|
||||||
|
},
|
||||||
"a11y": {
|
"a11y": {
|
||||||
"open": "Специальные возможности",
|
"open": "Специальные возможности",
|
||||||
"title": "Настройки доступности",
|
"title": "Настройки доступности",
|
||||||
@@ -119,26 +125,36 @@
|
|||||||
},
|
},
|
||||||
"booking": {
|
"booking": {
|
||||||
"title": "Онлайн-запись",
|
"title": "Онлайн-запись",
|
||||||
"subtitle": "Выберите услугу или врача, филиал и удобное время",
|
"subtitle": "Выберите услугу или врача, филиал и оставьте контакты — мы свяжемся с вами",
|
||||||
"stepService": "Услуга / врач",
|
"stepService": "Услуга / врач",
|
||||||
"stepBranch": "Филиал",
|
"stepBranch": "Филиал",
|
||||||
"stepSlot": "Дата и время",
|
"stepSlot": "Дата и время",
|
||||||
"stepConfirm": "Подтверждение",
|
"stepConfirm": "Контакты",
|
||||||
"selectService": "Выберите услугу",
|
"selectService": "Выберите услугу",
|
||||||
"searchService": "Найдите услугу по названию или коду",
|
"searchService": "Найдите услугу по названию или коду",
|
||||||
"selectDoctor": "Выберите врача (необязательно)",
|
"selectDoctor": "Выберите врача",
|
||||||
"selectBranch": "Выберите филиал",
|
"selectBranch": "Выберите филиал",
|
||||||
"selectDate": "Дата",
|
"selectDate": "Дата",
|
||||||
"selectTime": "Доступное время",
|
"selectTime": "Доступное время",
|
||||||
"noSlots": "Нет свободных слотов на эту дату",
|
"noSlots": "Нет свободных слотов на эту дату",
|
||||||
"confirm": "Подтвердить запись",
|
"confirm": "Отправить заявку",
|
||||||
"success": "Запись создана",
|
"success": "Большое спасибо!",
|
||||||
"successHint": "Мы отправим напоминание на email. Управлять записью можно в личном кабинете.",
|
"successHint": "Мы обязательно свяжемся с вами в ближайшее время и уточним всю информацию.",
|
||||||
|
"error": "Не удалось отправить заявку. Позвоните нам или попробуйте ещё раз.",
|
||||||
"next": "Далее",
|
"next": "Далее",
|
||||||
"back": "Назад",
|
"back": "Назад",
|
||||||
"patientName": "ФИО",
|
"patientName": "ФИО",
|
||||||
|
"email": "E-mail",
|
||||||
"phone": "Телефон",
|
"phone": "Телефон",
|
||||||
"summary": "Сводка записи"
|
"summary": "Сводка заявки",
|
||||||
|
"namePlaceholder": "Иванов Иван Иванович",
|
||||||
|
"emailPlaceholder": "ivan.ivanov@mail.ru",
|
||||||
|
"phonePlaceholder": "+7 900 123 45 67",
|
||||||
|
"nameRequired": "Укажите ФИО",
|
||||||
|
"nameInvalid": "Укажите фамилию и имя буквами",
|
||||||
|
"emailRequired": "Укажите e-mail",
|
||||||
|
"emailInvalid": "Укажите e-mail в формате name@domain.ru",
|
||||||
|
"phoneInvalid": "Укажите телефон в формате +7 и 10 цифр"
|
||||||
},
|
},
|
||||||
"branches": {
|
"branches": {
|
||||||
"title": "Филиалы",
|
"title": "Филиалы",
|
||||||
@@ -226,6 +242,8 @@
|
|||||||
"emptyFavorites": "Избранное пусто",
|
"emptyFavorites": "Избранное пусто",
|
||||||
"emptyDocuments": "Документов пока нет",
|
"emptyDocuments": "Документов пока нет",
|
||||||
"emptyInvoices": "Счетов пока нет",
|
"emptyInvoices": "Счетов пока нет",
|
||||||
|
"loginHint": "Войдите в личный кабинет, чтобы увидеть свои записи, документы и счета. У каждого пациента свой кабинет.",
|
||||||
|
"requestPending": "Заявка принята. Мы свяжемся с вами, чтобы уточнить дату и время визита.",
|
||||||
"save": "Сохранить",
|
"save": "Сохранить",
|
||||||
"saved": "Сохранено"
|
"saved": "Сохранено"
|
||||||
},
|
},
|
||||||
@@ -236,8 +254,8 @@
|
|||||||
"doctorsSubtitle": "Врачи с большим клиническим опытом",
|
"doctorsSubtitle": "Врачи с большим клиническим опытом",
|
||||||
"allDoctors": "Все врачи",
|
"allDoctors": "Все врачи",
|
||||||
"allReviews": "Все отзывы",
|
"allReviews": "Все отзывы",
|
||||||
"ctaTitle": "Запишитесь на удобное время",
|
"ctaTitle": "Оставьте заявку на приём",
|
||||||
"ctaSubtitle": "Онлайн-запись 24/7, напоминания и оплата через СБП",
|
"ctaSubtitle": "Выберите услугу или врача — мы свяжемся с вами и уточним детали",
|
||||||
"branchesTitle": "Наши адреса",
|
"branchesTitle": "Наши адреса",
|
||||||
"branchesSubtitle": "Два удобных локации для приёма",
|
"branchesSubtitle": "Два удобных локации для приёма",
|
||||||
"newsTitle": "Новости клиники",
|
"newsTitle": "Новости клиники",
|
||||||
@@ -312,7 +330,7 @@
|
|||||||
"subtitle": "Договоры и другие файлы для пациентов платных услуг.",
|
"subtitle": "Договоры и другие файлы для пациентов платных услуг.",
|
||||||
"intro": "Скачайте актуальные документы по платным медицинским услугам МОНИКИ.",
|
"intro": "Скачайте актуальные документы по платным медицинским услугам МОНИКИ.",
|
||||||
"download": "Скачать",
|
"download": "Скачать",
|
||||||
"contractTitle": "Договор на оказание платных медицинских услуг (2026)"
|
"contractTitle": "Договор на оказание платных медицинских услуг (с физическим лицом)"
|
||||||
},
|
},
|
||||||
"discounts": {
|
"discounts": {
|
||||||
"title": "Скидки и льготы",
|
"title": "Скидки и льготы",
|
||||||
@@ -362,6 +380,8 @@
|
|||||||
"links": "Разделы",
|
"links": "Разделы",
|
||||||
"organization": "Организация",
|
"organization": "Организация",
|
||||||
"useful": "Полезное",
|
"useful": "Полезное",
|
||||||
|
"instituteHome": "Главная страница института",
|
||||||
|
"education": "Образование",
|
||||||
"social": "Мы в соцсетях",
|
"social": "Мы в соцсетях",
|
||||||
"rights": "© МОНИКИ. Все права защищены.",
|
"rights": "© МОНИКИ. Все права защищены.",
|
||||||
"version": "Версия сайта v{version}",
|
"version": "Версия сайта v{version}",
|
||||||
|
|||||||
@@ -20,6 +20,12 @@
|
|||||||
"menu": "Меню",
|
"menu": "Меню",
|
||||||
"close": "Пӯшидан"
|
"close": "Пӯшидан"
|
||||||
},
|
},
|
||||||
|
"header": {
|
||||||
|
"hoursLabel": "Соатҳои кор",
|
||||||
|
"hoursWeekdays": "Дш–Шб 08:00–20:00",
|
||||||
|
"hoursWeekend": "Як 09:00–16:00",
|
||||||
|
"phoneLabel": "Телефон"
|
||||||
|
},
|
||||||
"a11y": {
|
"a11y": {
|
||||||
"open": "Имкониятҳои махсус",
|
"open": "Имкониятҳои махсус",
|
||||||
"title": "Танзимоти дастрасӣ",
|
"title": "Танзимоти дастрасӣ",
|
||||||
@@ -119,26 +125,36 @@
|
|||||||
},
|
},
|
||||||
"booking": {
|
"booking": {
|
||||||
"title": "Сабти онлайн",
|
"title": "Сабти онлайн",
|
||||||
"subtitle": "Хизмат ё духтур, филиал ва вақти қулайро интихоб кунед",
|
"subtitle": "Хизмат ё духтур ва филиалро интихоб кунед ва тамос гузоред — мо бо шумо тамос мегирем",
|
||||||
"stepService": "Хизмат / духтур",
|
"stepService": "Хизмат / духтур",
|
||||||
"stepBranch": "Филиал",
|
"stepBranch": "Филиал",
|
||||||
"stepSlot": "Сана ва вақт",
|
"stepSlot": "Сана ва вақт",
|
||||||
"stepConfirm": "Тасдиқ",
|
"stepConfirm": "Тамос",
|
||||||
"selectService": "Хизматро интихоб кунед",
|
"selectService": "Хизматро интихоб кунед",
|
||||||
"selectDoctor": "Духтурро интихоб кунед (ихтиёрӣ)",
|
"selectDoctor": "Духтурро интихоб кунед",
|
||||||
"selectBranch": "Филиалро интихоб кунед",
|
"selectBranch": "Филиалро интихоб кунед",
|
||||||
"selectDate": "Сана",
|
"selectDate": "Сана",
|
||||||
"selectTime": "Вақтҳои дастрас",
|
"selectTime": "Вақтҳои дастрас",
|
||||||
"noSlots": "Барои ин сана слот нест",
|
"noSlots": "Барои ин сана слот нест",
|
||||||
"confirm": "Сабтро тасдиқ кунед",
|
"confirm": "Фиристодани дархост",
|
||||||
"success": "Сабт эҷод шуд",
|
"success": "Ташаккури зиёд!",
|
||||||
"successHint": "Ёдраскунӣ ба email мефиристем. Сабтро дар кабинети шахсӣ идора кунед.",
|
"successHint": "Мо ҳатман дар наздиктарин вақт бо шумо тамос мегирем ва тамоми маълумотро дақиқ мекунем.",
|
||||||
|
"error": "Дархост фиристода нашуд. Ба мо занг занед ё бори дигар кӯшиш кунед.",
|
||||||
"next": "Минбаъд",
|
"next": "Минбаъд",
|
||||||
"back": "Бозгашт",
|
"back": "Бозгашт",
|
||||||
"patientName": "Ному насаб",
|
"patientName": "Ному насаб",
|
||||||
|
"email": "E-mail",
|
||||||
"phone": "Телефон",
|
"phone": "Телефон",
|
||||||
"summary": "Хулосаи сабт",
|
"summary": "Хулосаи дархост",
|
||||||
"searchService": "Хизматро бо ном ё рамз ҷустуҷӯ кунед"
|
"searchService": "Хизматро бо ном ё рамз ҷустуҷӯ кунед",
|
||||||
|
"namePlaceholder": "Иванов Иван Иванович",
|
||||||
|
"emailPlaceholder": "ivan.ivanov@mail.ru",
|
||||||
|
"phonePlaceholder": "+7 900 123 45 67",
|
||||||
|
"nameRequired": "Ному насабро нависед",
|
||||||
|
"nameInvalid": "Насаб ва номро бо ҳарфҳо нависед",
|
||||||
|
"emailRequired": "E-mail-ро нависед",
|
||||||
|
"emailInvalid": "E-mail-ро дар шакли name@domain.ru нависед",
|
||||||
|
"phoneInvalid": "Телефонро дар шакли +7 ва 10 рақам нависед"
|
||||||
},
|
},
|
||||||
"branches": {
|
"branches": {
|
||||||
"title": "Филиалҳо",
|
"title": "Филиалҳо",
|
||||||
@@ -226,6 +242,8 @@
|
|||||||
"emptyFavorites": "Дӯстдоштаҳо холӣ",
|
"emptyFavorites": "Дӯстдоштаҳо холӣ",
|
||||||
"emptyDocuments": "Ҳанӯз ҳуҷҷат нест",
|
"emptyDocuments": "Ҳанӯз ҳуҷҷат нест",
|
||||||
"emptyInvoices": "Ҳанӯз ҳисоб нест",
|
"emptyInvoices": "Ҳанӯз ҳисоб нест",
|
||||||
|
"loginHint": "Ба кабинети шахсӣ ворид шавед, то дархостҳо, ҳуҷҷатҳо ва ҳисобҳои худро бубинед.",
|
||||||
|
"requestPending": "Дархост қабул шуд. Мо барои дақиқ кардани сана ва вақт бо шумо тамос мегирем.",
|
||||||
"save": "Нигоҳ доштан",
|
"save": "Нигоҳ доштан",
|
||||||
"saved": "Нигоҳ дошта шуд"
|
"saved": "Нигоҳ дошта шуд"
|
||||||
},
|
},
|
||||||
@@ -236,8 +254,8 @@
|
|||||||
"doctorsSubtitle": "Духтурон бо таҷрибаи зиёди клиникӣ",
|
"doctorsSubtitle": "Духтурон бо таҷрибаи зиёди клиникӣ",
|
||||||
"allDoctors": "Ҳамаи духтурон",
|
"allDoctors": "Ҳамаи духтурон",
|
||||||
"allReviews": "Ҳамаи шарҳҳо",
|
"allReviews": "Ҳамаи шарҳҳо",
|
||||||
"ctaTitle": "Ба вақти қулай сабт кунед",
|
"ctaTitle": "Дархости қабулро гузоред",
|
||||||
"ctaSubtitle": "Сабти онлайн 24/7, ёдраскунӣ ва пардохти СБП",
|
"ctaSubtitle": "Хизмат ё духтурро интихоб кунед — мо бо шумо тамос гирифта ҷузъиётро дақиқ мекунем",
|
||||||
"branchesTitle": "Суроғаҳои мо",
|
"branchesTitle": "Суроғаҳои мо",
|
||||||
"branchesSubtitle": "Ду макони қулай барои қабул",
|
"branchesSubtitle": "Ду макони қулай барои қабул",
|
||||||
"newsTitle": "Хабарҳои клиника",
|
"newsTitle": "Хабарҳои клиника",
|
||||||
@@ -312,7 +330,7 @@
|
|||||||
"subtitle": "Шартномаҳо ва дигар файлҳо барои беморони хизматрасонии пулакӣ.",
|
"subtitle": "Шартномаҳо ва дигар файлҳо барои беморони хизматрасонии пулакӣ.",
|
||||||
"intro": "Ҳуҷҷатҳои актуалии хизматрасонии тиббии пулакии МОНИКИ-ро боргирӣ кунед.",
|
"intro": "Ҳуҷҷатҳои актуалии хизматрасонии тиббии пулакии МОНИКИ-ро боргирӣ кунед.",
|
||||||
"download": "Боргирӣ",
|
"download": "Боргирӣ",
|
||||||
"contractTitle": "Шартнома дар бораи расонидани хизматрасонии тиббии пулакӣ (2026)"
|
"contractTitle": "Шартнома дар бораи расонидани хизматрасонии тиббии пулакӣ (бо шахси воқеӣ)"
|
||||||
},
|
},
|
||||||
"discounts": {
|
"discounts": {
|
||||||
"title": "Тахфиф ва имтиёзҳо",
|
"title": "Тахфиф ва имтиёзҳо",
|
||||||
@@ -362,6 +380,8 @@
|
|||||||
"links": "Бохшҳо",
|
"links": "Бохшҳо",
|
||||||
"organization": "Ташкилот",
|
"organization": "Ташкилот",
|
||||||
"useful": "Фоиданок",
|
"useful": "Фоиданок",
|
||||||
|
"instituteHome": "Саҳифаи асосии институт",
|
||||||
|
"education": "Таҳсилот",
|
||||||
"social": "Мо дар шабакаҳои иҷтимоӣ",
|
"social": "Мо дар шабакаҳои иҷтимоӣ",
|
||||||
"rights": "© МОНИКИ. Ҳамаи ҳуқуқҳо ҳифз шудаанд.",
|
"rights": "© МОНИКИ. Ҳамаи ҳуқуқҳо ҳифз шудаанд.",
|
||||||
"version": "Версияи сайт v{version}",
|
"version": "Версияи сайт v{version}",
|
||||||
|
|||||||
@@ -20,6 +20,12 @@
|
|||||||
"menu": "菜单",
|
"menu": "菜单",
|
||||||
"close": "关闭"
|
"close": "关闭"
|
||||||
},
|
},
|
||||||
|
"header": {
|
||||||
|
"hoursLabel": "工作时间",
|
||||||
|
"hoursWeekdays": "周一至周六 08:00–20:00",
|
||||||
|
"hoursWeekend": "周日 09:00–16:00",
|
||||||
|
"phoneLabel": "电话"
|
||||||
|
},
|
||||||
"a11y": {
|
"a11y": {
|
||||||
"open": "无障碍",
|
"open": "无障碍",
|
||||||
"title": "无障碍设置",
|
"title": "无障碍设置",
|
||||||
@@ -119,26 +125,36 @@
|
|||||||
},
|
},
|
||||||
"booking": {
|
"booking": {
|
||||||
"title": "在线预约",
|
"title": "在线预约",
|
||||||
"subtitle": "选择服务或医生、分院和合适时间",
|
"subtitle": "选择服务或医生、分院并留下联系方式,我们会与您联系",
|
||||||
"stepService": "服务 / 医生",
|
"stepService": "服务 / 医生",
|
||||||
"stepBranch": "分院",
|
"stepBranch": "分院",
|
||||||
"stepSlot": "日期与时间",
|
"stepSlot": "日期与时间",
|
||||||
"stepConfirm": "确认",
|
"stepConfirm": "联系方式",
|
||||||
"selectService": "选择服务",
|
"selectService": "选择服务",
|
||||||
"selectDoctor": "选择医生(可选)",
|
"selectDoctor": "选择医生",
|
||||||
"selectBranch": "选择分院",
|
"selectBranch": "选择分院",
|
||||||
"selectDate": "日期",
|
"selectDate": "日期",
|
||||||
"selectTime": "可预约时间",
|
"selectTime": "可预约时间",
|
||||||
"noSlots": "该日期暂无空档",
|
"noSlots": "该日期暂无空档",
|
||||||
"confirm": "确认预约",
|
"confirm": "提交申请",
|
||||||
"success": "预约已创建",
|
"success": "非常感谢!",
|
||||||
"successHint": "我们将发送邮件提醒。可在个人中心管理预约。",
|
"successHint": "我们会尽快与您联系并确认全部信息。",
|
||||||
|
"error": "申请未能发送。请致电我们或稍后重试。",
|
||||||
"next": "下一步",
|
"next": "下一步",
|
||||||
"back": "返回",
|
"back": "返回",
|
||||||
"patientName": "姓名",
|
"patientName": "姓名",
|
||||||
|
"email": "E-mail",
|
||||||
"phone": "电话",
|
"phone": "电话",
|
||||||
"summary": "预约摘要",
|
"summary": "申请摘要",
|
||||||
"searchService": "按名称或编码查找服务"
|
"searchService": "按名称或编码查找服务",
|
||||||
|
"namePlaceholder": "Ivanov Ivan Ivanovich",
|
||||||
|
"emailPlaceholder": "ivan.ivanov@mail.ru",
|
||||||
|
"phonePlaceholder": "+7 900 123 45 67",
|
||||||
|
"nameRequired": "请填写姓名",
|
||||||
|
"nameInvalid": "请用字母填写姓和名",
|
||||||
|
"emailRequired": "请填写电子邮箱",
|
||||||
|
"emailInvalid": "请填写 name@domain.ru 格式的邮箱",
|
||||||
|
"phoneInvalid": "请填写 +7 加 10 位数字的电话"
|
||||||
},
|
},
|
||||||
"branches": {
|
"branches": {
|
||||||
"title": "分院",
|
"title": "分院",
|
||||||
@@ -226,6 +242,8 @@
|
|||||||
"emptyFavorites": "暂无收藏",
|
"emptyFavorites": "暂无收藏",
|
||||||
"emptyDocuments": "暂无文件",
|
"emptyDocuments": "暂无文件",
|
||||||
"emptyInvoices": "暂无账单",
|
"emptyInvoices": "暂无账单",
|
||||||
|
"loginHint": "请登录个人账户查看您的预约、文件和账单。每位患者都有独立账户。",
|
||||||
|
"requestPending": "申请已受理。我们会联系您确认就诊日期和时间。",
|
||||||
"save": "保存",
|
"save": "保存",
|
||||||
"saved": "已保存"
|
"saved": "已保存"
|
||||||
},
|
},
|
||||||
@@ -236,8 +254,8 @@
|
|||||||
"doctorsSubtitle": "拥有丰富临床经验的医生",
|
"doctorsSubtitle": "拥有丰富临床经验的医生",
|
||||||
"allDoctors": "全部医生",
|
"allDoctors": "全部医生",
|
||||||
"allReviews": "全部评价",
|
"allReviews": "全部评价",
|
||||||
"ctaTitle": "预约合适时间",
|
"ctaTitle": "提交就诊申请",
|
||||||
"ctaSubtitle": "全天候在线预约、提醒与 SBP 支付",
|
"ctaSubtitle": "选择服务或医生,我们会与您联系并确认细节",
|
||||||
"branchesTitle": "我们的地址",
|
"branchesTitle": "我们的地址",
|
||||||
"branchesSubtitle": "两个便捷就诊地点",
|
"branchesSubtitle": "两个便捷就诊地点",
|
||||||
"newsTitle": "医院新闻",
|
"newsTitle": "医院新闻",
|
||||||
@@ -312,7 +330,7 @@
|
|||||||
"subtitle": "付费服务患者可下载的合同及其他文件。",
|
"subtitle": "付费服务患者可下载的合同及其他文件。",
|
||||||
"intro": "下载莫尼基付费医疗服务的现行文件。",
|
"intro": "下载莫尼基付费医疗服务的现行文件。",
|
||||||
"download": "下载",
|
"download": "下载",
|
||||||
"contractTitle": "付费医疗服务合同(2026)"
|
"contractTitle": "付费医疗服务合同(自然人)"
|
||||||
},
|
},
|
||||||
"discounts": {
|
"discounts": {
|
||||||
"title": "折扣与优惠",
|
"title": "折扣与优惠",
|
||||||
@@ -362,6 +380,8 @@
|
|||||||
"links": "栏目",
|
"links": "栏目",
|
||||||
"organization": "机构信息",
|
"organization": "机构信息",
|
||||||
"useful": "实用信息",
|
"useful": "实用信息",
|
||||||
|
"instituteHome": "研究所主页",
|
||||||
|
"education": "教育",
|
||||||
"social": "社交媒体",
|
"social": "社交媒体",
|
||||||
"rights": "© МОНИКИ。保留所有权利。",
|
"rights": "© МОНИКИ。保留所有权利。",
|
||||||
"version": "网站版本 v{version}",
|
"version": "网站版本 v{version}",
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "moniki-platnye-uslugi",
|
"name": "moniki-platnye-uslugi",
|
||||||
"version": "1.0.2",
|
"version": "1.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "pnpm -r --parallel dev",
|
"dev": "pnpm -r --parallel dev",
|
||||||
|
|||||||
Generated
+3
@@ -25,6 +25,9 @@ importers:
|
|||||||
'@payloadcms/ui':
|
'@payloadcms/ui':
|
||||||
specifier: ^3.49.1
|
specifier: ^3.49.1
|
||||||
version: 3.89.0(@types/react@19.3.0)(monaco-editor@0.56.0)(next@15.3.9(react-dom@19.1.0(react@19.1.0))(react@19.1.0)(sass@1.77.4))(payload@3.89.0(graphql@16.14.2)(typescript@5.9.3))(react-dom@19.1.0(react@19.1.0))(react@19.1.0)(typescript@5.9.3)
|
version: 3.89.0(@types/react@19.3.0)(monaco-editor@0.56.0)(next@15.3.9(react-dom@19.1.0(react@19.1.0))(react@19.1.0)(sass@1.77.4))(payload@3.89.0(graphql@16.14.2)(typescript@5.9.3))(react-dom@19.1.0(react@19.1.0))(react@19.1.0)(typescript@5.9.3)
|
||||||
|
'@untitledui/icons':
|
||||||
|
specifier: ^0.0.19
|
||||||
|
version: 0.0.19(react@19.1.0)
|
||||||
cross-env:
|
cross-env:
|
||||||
specifier: ^7.0.3
|
specifier: ^7.0.3
|
||||||
version: 7.0.3
|
version: 7.0.3
|
||||||
|
|||||||
Reference in New Issue
Block a user