Replace the price list with Preiskurant No. 423 of 18.09.2026 and make the import a transactional replace.

- price_from_xlsx.py builds price-services.json from the official xlsx (4188 services, new "10. Чекапы" section)
- seed:price replaces the catalog: matching codes keep their ids and links, missing services are deleted
  (or unpublished when patient bookings reference them), everything in one transaction; --dry-run and --hard

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alexey Novikov
2026-11-11 16:23:02 +03:00
co-authored by Claude Opus 5.5
parent f068628e7e
commit 959e693dcc
3 changed files with 290 additions and 54 deletions
+164 -58
View File
@@ -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,52 +31,7 @@ type PriceRow = {
categoryTitle: string categoryTitle: string
} }
const BATCH = 80 type Category =
async function main() {
const payload = await getPayload({ config })
const file = path.join(path.dirname(fileURLToPath(import.meta.url)), 'price-services.json')
const rows = JSON.parse(fs.readFileSync(file, 'utf8')) as PriceRow[]
const existing = await payload.find({
collection: 'services',
limit: 10000,
depth: 0,
pagination: false,
})
const bySlug = new Set(existing.docs.map((d) => String(d.slug)))
let created = 0
let skipped = 0
for (let i = 0; i < rows.length; i += BATCH) {
const chunk = rows.slice(i, i + BATCH)
await Promise.all(
chunk.map(async (row) => {
if (bySlug.has(row.slug)) {
skipped += 1
return
}
const group =
/несъемное протезирование/i.test(row.group) || row.group.startsWith('9.')
? row.group.startsWith('9.') || /несъемное/i.test(row.group)
? row.group
: row.group
: row.group
const category = /несъемное протезирование/i.test(row.group) ? 'dentistry' : row.category
await payload.create({
collection: 'services',
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' | 'consultation'
| 'diagnostics' | 'diagnostics'
| 'lab' | 'lab'
@@ -69,21 +39,157 @@ async function main() {
| 'surgery' | 'surgery'
| 'stay' | 'stay'
| 'package' | 'package'
| 'dentistry', | 'dentistry'
groupTitle: group,
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, 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})`)
} }
console.log(`Done. created=${created} skipped=${skipped} total=${rows.length}`) async function each<T>(items: T[], label: string, fn: (item: T) => Promise<void>) {
process.exit(0) // 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() {
const file = path.join(path.dirname(fileURLToPath(import.meta.url)), 'price-services.json')
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({
collection: 'services',
limit: 100000,
depth: 0,
pagination: false,
locale: 'ru',
})
const bySlug = new Map(existing.docs.map((d) => [String(d.slug), d]))
const removed = HARD ? existing.docs : existing.docs.filter((d) => !slugs.has(String(d.slug)))
// bookings.service is required: a service with bookings cannot be deleted without breaking them.
const booked = new Set<string>()
if (removed.length) {
const bookings = await payload.find({
collection: 'bookings',
where: { service: { in: removed.map((d) => d.id) } },
depth: 0,
pagination: false,
limit: 100000,
overrideAccess: true,
})
for (const b of bookings.docs) booked.add(String(b.service))
}
if (HARD && booked.size) {
console.error(
`--hard aborted: ${booked.size} services have patient bookings and cannot be deleted. ` +
'Run without --hard (they will be unpublished) or remove those bookings first. Nothing was changed.',
)
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
}
// Translations of renamed services are stale: drop them so other languages fall back to Russian
// 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
+130
View File
@@ -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()