Lock down access control and add image previews, file locations and cropping to the CMS.
Security: - only admins can assign user roles; profile updates are whitelisted - SBP payment confirmation requires an HMAC-signed webhook or an admin, and is idempotent - patient receipts and documents are private media owned by the patient, downloaded via the site - patients cannot change booking price or payment status, forge invoices or write for other accounts CMS images: - every upload field shows a large preview, focal point, server file path and public URL - crop/resize keeps the original in media/originals with a "restore original" action - legacy image URL fields show where the file really lives and can be moved into the media library - specialties get a visual icon picker (Untitled UI) and an optional custom icon upload Fixes: saving the cabinet profile, receipt PDF generation, uploaded doctor photos on the site. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
959e693dcc
commit
0b447e67bf
@@ -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' },
|
||||||
|
|||||||
@@ -29,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,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-рассылки напоминаний' },
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -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' },
|
||||||
|
|||||||
@@ -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',
|
||||||
@@ -22,7 +31,45 @@ export const Media: CollectionConfig = {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
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: [
|
||||||
{
|
{
|
||||||
@@ -30,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',
|
||||||
@@ -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,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,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
|
||||||
|
}
|
||||||
|
}
|
||||||
+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)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,6 +33,8 @@ 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 { 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)
|
||||||
@@ -54,7 +56,7 @@ export default buildConfig({
|
|||||||
titleSuffix: ' — МОНИКИ Платные услуги',
|
titleSuffix: ' — МОНИКИ Платные услуги',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
collections: [
|
collections: withMediaPreviews([
|
||||||
Branches,
|
Branches,
|
||||||
Specialties,
|
Specialties,
|
||||||
Doctors,
|
Doctors,
|
||||||
@@ -74,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)
|
||||||
@@ -84,6 +86,7 @@ export default buildConfig({
|
|||||||
await ensureServicesSchema(payload)
|
await ensureServicesSchema(payload)
|
||||||
await ensureBannersSchema(payload)
|
await ensureBannersSchema(payload)
|
||||||
await ensureInquiriesSchema(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)
|
||||||
|
|||||||
@@ -24,15 +24,30 @@ export async function PATCH(request: Request) {
|
|||||||
const token = store.get(AUTH_COOKIE)?.value;
|
const token = store.get(AUTH_COOKIE)?.value;
|
||||||
if (!token || token === "demo-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>;
|
||||||
const payload = {
|
// Whitelist profile fields: never forward role, email, password or other account internals.
|
||||||
...body,
|
const payload: Record<string, unknown> = {};
|
||||||
fullName: body.fullName || body.name,
|
const fullName = body.fullName ?? body.name;
|
||||||
};
|
if (typeof fullName === "string") payload.fullName = fullName;
|
||||||
delete payload.name;
|
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}`,
|
||||||
|
|||||||
@@ -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 });
|
||||||
|
}
|
||||||
@@ -266,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);
|
||||||
|
|
||||||
@@ -1016,7 +1012,9 @@ export async function getMyDocuments(): Promise<CabinetDocument[]> {
|
|||||||
return unwrapList(data)
|
return unwrapList(data)
|
||||||
.map((raw) => {
|
.map((raw) => {
|
||||||
const file = raw.file && typeof raw.file === "object" ? (raw.file as Record<string, unknown>) : null;
|
const file = raw.file && typeof raw.file === "object" ? (raw.file as Record<string, unknown>) : null;
|
||||||
const href = mediaSrc(file);
|
// 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);
|
const title = asText(raw.title);
|
||||||
if (!title || !href) return null;
|
if (!title || !href) return null;
|
||||||
return { id: String(raw.id ?? ""), title, href, issuedAt: asText(raw.issuedAt) || undefined };
|
return { id: String(raw.id ?? ""), title, href, issuedAt: asText(raw.issuedAt) || undefined };
|
||||||
|
|||||||
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