acc_invoices: внутренние проекты (acc_internal_projects), описание, ссылка для оплаты, «Файла Invoice пока нет», строки необязательны, ждёт автор по умолчанию
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -42,6 +42,24 @@ d("acc_invoices: API платёжного процесса (временная
|
||||
expect((await call("emp", "GET", "me")).body.is_staff).toBe(false);
|
||||
});
|
||||
|
||||
it("создание: ждёт автор по умолчанию, строки необязательны, внутренний проект, «файла пока нет»", async () => {
|
||||
const ip = (await db.pool.query("select id from acc_internal_projects where name = 'ИТ KHBuild'")).rows[0].id as string;
|
||||
const c = await call("emp", "POST", "invoices", { vendor_name: "Linode", amount: 50, internal_project_id: ip, no_invoice_file: true, description: "хостинг", pay_link: "https://pay.example.com/x" });
|
||||
expect(c.status).toBe(201);
|
||||
const d = (await call("emp", "GET", `invoices/${c.body.id}`)).body;
|
||||
expect(d.invoice.target_employee).toBe(ids.emp);
|
||||
expect(d.invoice.project_name).toBe("ИТ KHBuild");
|
||||
expect(d.details).toHaveLength(1);
|
||||
expect(d.details[0]).toMatchObject({ virtual: true, amount: 50, description: "хостинг" });
|
||||
// без файла, но с отметкой «файла Invoice пока нет» отправить можно
|
||||
expect((await call("emp", "POST", `invoices/${c.body.id}/submit`)).status).toBe(200);
|
||||
// без отметки и без файла - нельзя
|
||||
const c2 = await call("emp", "POST", "invoices", { vendor_name: "Linode", amount: 50 });
|
||||
const bad = await call("emp", "POST", `invoices/${c2.body.id}/submit`);
|
||||
expect(bad.status).toBe(422);
|
||||
expect(bad.body.problems.join()).toMatch(/файл/);
|
||||
});
|
||||
|
||||
it("полный путь: черновик -> строки -> отправка -> проверки -> согласование -> «в банк» -> отмена отметки", async () => {
|
||||
const c = await call("emp", "POST", "invoices", { vendor_name: "ACME", invoice_number: "A-1", amount: 100, invoice_url: "https://drive.google.com/file/d/x/view" });
|
||||
expect(c.status).toBe(201);
|
||||
|
||||
@@ -35,6 +35,10 @@ const FIELD_SCHEMA = z
|
||||
invoice_date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable(),
|
||||
amount: money,
|
||||
project_customer_id: nullableStr,
|
||||
internal_project_id: uuid.nullable(),
|
||||
description: z.string().trim().max(4000).nullable(),
|
||||
pay_link: z.string().trim().url().max(2000).nullable(),
|
||||
no_invoice_file: z.boolean(),
|
||||
jt_job_id: nullableStr,
|
||||
contract_id: uuid.nullable(),
|
||||
target_employee: uuid.nullable(),
|
||||
@@ -136,7 +140,9 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
|
||||
const a = await need(req);
|
||||
const row = await load(a, req.params.id, reply);
|
||||
if (!row) return;
|
||||
const lines = await getDetails(pool, row.id);
|
||||
const real = await getDetails(pool, row.id);
|
||||
// строки не заданы: считаем одной строкой на всю сумму инвойса (в БД не пишется)
|
||||
const lines = real.length ? real : [{ id: "virtual", virtual: true, line_no: 1, description: row.description ?? null, quantity: null, unit_price: null, amount: row.amount, category_qbo_id: null, category_name: null, contract_detail_id: null }];
|
||||
return {
|
||||
invoice: decorate(row, a),
|
||||
details: lines,
|
||||
@@ -148,17 +154,18 @@ export function buildApi(deps: ApiDeps): FastifyInstance {
|
||||
/* ------------------------------------------------------------- создание */
|
||||
app.post("/api/invoices", async (req, reply) => {
|
||||
const a = await need(req);
|
||||
const body = FIELD_SCHEMA.pick({ vendor_name: true, vendor_qbo_id: true, invoice_number: true, invoice_date: true, amount: true, project_customer_id: true, jt_job_id: true, contract_id: true, target_employee: true, need_employee_refund: true, invoice_url: true, payment_url: true, pay_method: true })
|
||||
const body = FIELD_SCHEMA.pick({ vendor_name: true, vendor_qbo_id: true, invoice_number: true, invoice_date: true, amount: true, project_customer_id: true, internal_project_id: true, description: true, pay_link: true, no_invoice_file: true, jt_job_id: true, contract_id: true, target_employee: true, need_employee_refund: true, invoice_url: true, payment_url: true, pay_method: true })
|
||||
.extend({ vendor_name: z.string().trim().min(1).max(300), amount: money.default(0) })
|
||||
.parse(req.body ?? {});
|
||||
const row = (
|
||||
await pool.query(
|
||||
`insert into acc_invoices (id, vendor_name, vendor_qbo_id, invoice_number, invoice_date, amount, project_customer_id, jt_job_id, contract_id,
|
||||
target_employee, need_employee_refund, invoice_url, payment_url, pay_method, is_draft, author, stage)
|
||||
values (gen_random_uuid(), $1, $2, $3, coalesce($4::date, current_date), $5, $6, $7, $8, $9, coalesce($10, false), $11, $12, $13, true, $14, 'checking')
|
||||
target_employee, need_employee_refund, invoice_url, payment_url, pay_method, is_draft, author, stage, internal_project_id, description, pay_link, no_invoice_file)
|
||||
values (gen_random_uuid(), $1, $2, $3, coalesce($4::date, current_date), $5, $6, $7, $8, $9, coalesce($10, false), $11, $12, $13, true, $14, 'checking', $15, $16, $17, coalesce($18, false))
|
||||
returning id`,
|
||||
[body.vendor_name, body.vendor_qbo_id ?? null, body.invoice_number ?? null, body.invoice_date ?? null, body.amount, body.project_customer_id ?? null, body.jt_job_id ?? null, body.contract_id ?? null,
|
||||
body.target_employee ?? a.personId, body.need_employee_refund ?? null, body.invoice_url ?? null, body.payment_url ?? null, body.pay_method ?? null, a.personId],
|
||||
body.target_employee ?? a.personId, body.need_employee_refund ?? null, body.invoice_url ?? null, body.payment_url ?? null, body.pay_method ?? null, a.personId,
|
||||
body.project_customer_id ? null : (body.internal_project_id ?? null), body.description ?? null, body.pay_link ?? null, body.no_invoice_file ?? null],
|
||||
)
|
||||
).rows[0];
|
||||
return reply.code(201).send({ id: row.id });
|
||||
|
||||
@@ -7,12 +7,12 @@ type Q = Pick<Pool, "query">;
|
||||
const LIST_SQL = `
|
||||
select i.id, i.invoice_number, i.vendor_name, i.vendor_qbo_id, i.invoice_date::text as invoice_date, i.amount::float8 as amount,
|
||||
i.project_customer_id, i.jt_job_id, i.contract_id, i.pay_method,
|
||||
i.is_draft, i.cancelled, i.is_approved, i.llm_result, i.manual_result, i.invoice_url, i.payment_url,
|
||||
i.internal_project_id, i.description, i.pay_link, i.no_invoice_file, i.is_draft, i.cancelled, i.is_approved, i.llm_result, i.manual_result, i.invoice_url, i.payment_url,
|
||||
i.sent_to_bank, i.qbo_txn_id, i.paid_on::text as paid_on, i.is_paid_manual, i.paid_manual_at, i.review_date::text as review_date,
|
||||
i.need_employee_refund, i.is_employee_refunded, i.author, i.target_employee, i.created_at, i.updated_at,
|
||||
(select display_name from person where id = i.author) as author_name,
|
||||
(select display_name from person where id = i.target_employee) as target_name,
|
||||
(select c.display_name from qbo_customer c where c.id = i.project_customer_id limit 1) as project_name,
|
||||
coalesce((select c.display_name from qbo_customer c where c.id = i.project_customer_id limit 1), (select ip.name from acc_internal_projects ip where ip.id = i.internal_project_id)) as project_name,
|
||||
(select sum(d.amount)::float8 from acc_invoices_details d where d.invoice_id = i.id) as details_sum,
|
||||
(select count(*)::int from acc_invoices o where o.id <> i.id and not o.cancelled and o.vendor_name = i.vendor_name
|
||||
and coalesce(o.invoice_number, '') <> '' and o.invoice_number = i.invoice_number and o.amount = i.amount) as duplicates,
|
||||
@@ -28,6 +28,9 @@ export interface ListItem extends InvoiceRow {
|
||||
vendor_qbo_id: string | null;
|
||||
invoice_date: string | null;
|
||||
project_customer_id: string | null;
|
||||
internal_project_id: string | null;
|
||||
description: string | null;
|
||||
pay_link: string | null;
|
||||
jt_job_id: string | null;
|
||||
contract_id: string | null;
|
||||
pay_method: string | null;
|
||||
@@ -109,6 +112,7 @@ export async function recomputeApproved(db: Q, invoiceId: string): Promise<boole
|
||||
|
||||
export const LOOKUP = {
|
||||
projects: `select id, display_name as name from qbo_customer where is_job and active order by display_name`,
|
||||
internal_projects: `select id, name from acc_internal_projects order by sort, name`,
|
||||
vendors: `select id, display_name as name from qbo_vendor where active order by display_name`,
|
||||
people: `select id, display_name as name from person where is_active order by display_name`,
|
||||
categories: `select id, coalesce(fully_qualified_name, name) as name from qbo_account where active and classification in ('Expense','Revenue') order by 2`,
|
||||
|
||||
@@ -18,6 +18,7 @@ export interface InvoiceRow {
|
||||
/** когда сотрудник поставил отметку «оплачен» */
|
||||
paid_manual_at: Date | string | null;
|
||||
qbo_txn_id?: string | null;
|
||||
no_invoice_file?: boolean;
|
||||
review_date: string | null;
|
||||
amount: number;
|
||||
author: string | null;
|
||||
@@ -73,7 +74,7 @@ export function errorsOf(r: InvoiceRow, now: Date, bankConfirmHours: number): st
|
||||
const e: string[] = [];
|
||||
if (r.is_draft) return e; // у черновика ошибок процесса нет
|
||||
if (!r.cancelled) {
|
||||
if (!r.invoice_url && !r.paid_on) e.push("Нет файла инвойса (ссылки на Drive)");
|
||||
if (!r.invoice_url && !r.paid_on && !r.no_invoice_file) e.push("Нет файла инвойса (ссылки на Drive)");
|
||||
if (r.llm_result && !isOk(r.llm_result)) e.push(`Проверка агента: ${r.llm_result}`);
|
||||
if (r.manual_result && !isOk(r.manual_result)) e.push(`Проверка сотрудника: ${r.manual_result}`);
|
||||
if (r.approves_rejected > 0) e.push("Согласование отклонено");
|
||||
@@ -146,12 +147,12 @@ export const canView = (w: Who, r: Pick<InvoiceRow, "author" | "target_employee"
|
||||
/** Поля, которые можно менять при is_draft = false (остальное - только после возврата в черновик). */
|
||||
export const LIVE_FIELDS = {
|
||||
/** сотрудники бухгалтерии */
|
||||
staff: ["contract_id", "invoice_url", "payment_url", "is_paid_manual", "target_employee", "need_employee_refund", "is_employee_refunded", "review_date", "manual_result", "project_customer_id", "jt_job_id", "pay_method"],
|
||||
staff: ["contract_id", "invoice_url", "payment_url", "is_paid_manual", "target_employee", "need_employee_refund", "is_employee_refunded", "review_date", "manual_result", "project_customer_id", "internal_project_id", "jt_job_id", "pay_method", "pay_link", "description", "no_invoice_file"],
|
||||
/** инициатор: только неплатёжные характеристики */
|
||||
owner: ["target_employee"],
|
||||
} as const;
|
||||
/** Поля черновика. */
|
||||
export const DRAFT_FIELDS = ["vendor_name", "vendor_qbo_id", "invoice_number", "invoice_date", "amount", "project_customer_id", "jt_job_id", "contract_id", "target_employee", "need_employee_refund", "invoice_url", "payment_url", "pay_method", "review_date"] as const;
|
||||
export const DRAFT_FIELDS = ["vendor_name", "vendor_qbo_id", "invoice_number", "invoice_date", "amount", "project_customer_id", "jt_job_id", "contract_id", "target_employee", "need_employee_refund", "invoice_url", "payment_url", "pay_method", "review_date", "internal_project_id", "description", "pay_link", "no_invoice_file"] as const;
|
||||
|
||||
export type Allowed = { ok: true } | { ok: false; status: 400 | 403 | 409; error: string };
|
||||
const no = (status: 400 | 403 | 409, error: string): Allowed => ({ ok: false, status, error });
|
||||
@@ -202,12 +203,12 @@ export function canCancel(w: Who, r: Pick<InvoiceRow, "author" | "target_employe
|
||||
}
|
||||
|
||||
/** Проверка перед отправкой черновика в платёжный процесс. Возвращает список недостающего. */
|
||||
export function submitProblems(r: { vendor_name: string | null; amount: number | null; invoice_date: string | null; invoice_url: string | null }, detailsSum: number | null): string[] {
|
||||
export function submitProblems(r: { vendor_name: string | null; amount: number | null; invoice_date: string | null; invoice_url: string | null; no_invoice_file?: boolean }, detailsSum: number | null): string[] {
|
||||
const p: string[] = [];
|
||||
if (!r.vendor_name?.trim()) p.push("не указан вендор");
|
||||
if (!(r.amount && r.amount > 0)) p.push("сумма должна быть больше нуля");
|
||||
if (!r.invoice_date) p.push("не указана дата инвойса");
|
||||
if (!r.invoice_url) p.push("не приложен файл инвойса");
|
||||
if (!r.invoice_url && !r.no_invoice_file) p.push("не приложен файл инвойса (если его пока нет, отметьте «Файла Invoice пока нет.»)");
|
||||
if (detailsSum !== null && r.amount !== null && Math.abs(detailsSum - r.amount) > 0.005) p.push("сумма строк не равна сумме инвойса");
|
||||
return p;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user