Files
khb_microservices/packages/khb_common/migrations/024_todo_service.sql
2026-10-29 11:08:54 +03:00

105 lines
5.8 KiB
SQL

-- todo_service: живая копия todo JobTread (поля принадлежат JobTread), надстройка (поля принадлежат сервису),
-- связи (Control), лента событий для агентов, очередь запросов (идемпотентность и повторы записи в JobTread).
-- Поля JobTread; обновляются только из JobTread (вебхуки, опрос) и из ответов на собственные записи сервиса.
create table todo_item (
task_id text primary key,
job_id text,
name text not null,
description text,
assignee_ids text[] not null default '{}',
start_date date,
end_date date,
progress numeric,
is_deleted boolean not null default false,
jt_created_at timestamptz,
last_event_at timestamptz, -- последнее событие JobTread по задаче (для "2 дня нет действий")
synced_at timestamptz not null default now(),
search tsvector generated always as (to_tsvector('simple', coalesce(name, '') || ' ' || coalesce(description, ''))) stored
);
create index todo_item_job_idx on todo_item (job_id) where not is_deleted;
create index todo_item_end_idx on todo_item (end_date) where not is_deleted;
create index todo_item_search_idx on todo_item using gin (search);
create index todo_item_assignee_idx on todo_item using gin (assignee_ids);
-- Поля только сервиса.
create table todo_ext (
task_id text primary key,
kind text not null default 'todo' check (kind in ('todo', 'reminder', 'control')),
review_date date,
keep_confirmed boolean not null default false,
done_flag boolean not null default false, -- Control: исполнитель закрыл ("(выполнено)")
overdue_flag boolean not null default false, -- Control: срок наступил, действий нет ("(просрочено)")
base_name text, -- желаемое название без суффикса статуса
created_by_kind text not null default 'unknown' check (created_by_kind in ('human', 'agent', 'automation', 'unknown')),
created_by text,
review_notified_for date, -- для какого review_date уже создано событие review_due
stale_asked_at timestamptz,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index todo_ext_review_idx on todo_ext (review_date) where review_date is not null;
-- Связи между todo. Сейчас единственный вид - control (замена control_todo).
create table todo_link (
id uuid primary key default gen_random_uuid(),
link_type text not null default 'control' check (link_type in ('control')),
task_id text not null, -- Control todo контролёра
linked_task_id text not null, -- todo исполнителя
controller_person_id uuid not null references person(id),
executor_name text,
control_due date,
status text not null default 'active' check (status in ('active', 'overdue', 'done', 'closed')),
created_at timestamptz not null default now(),
updated_at timestamptz not null default now(),
unique (link_type, task_id)
);
create index todo_link_open_idx on todo_link (status) where status in ('active', 'overdue');
create index todo_link_linked_idx on todo_link (linked_task_id);
-- События для агентов: сервис решает, что произошло; агент решает, что сказать.
create table todo_event (
id bigserial primary key,
created_at timestamptz not null default now(),
event_type text not null, -- control_done, control_overdue, review_due, write_failed, ...
task_id text,
person_id uuid references person(id),
payload jsonb not null default '{}',
delivered_at timestamptz,
delivery_error text
);
create index todo_event_person_idx on todo_event (person_id, id);
create index todo_event_pending_idx on todo_event (id) where delivered_at is null;
-- Запросы на запись в JobTread: идемпотентный ключ и очередь повторов (до 5 минут).
create table todo_request (
id uuid primary key default gen_random_uuid(),
idem_key text unique,
op text not null, -- create / update / delete / control
args jsonb not null,
caller text,
status text not null default 'pending' check (status in ('pending', 'done', 'failed')),
result jsonb,
error text,
attempts int not null default 0,
next_attempt_at timestamptz not null default now(),
deadline timestamptz not null,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
create index todo_request_pending_idx on todo_request (next_attempt_at) where status = 'pending';
-- Состояние приёма из JobTread (курсор опроса событий, регистрация вебхука).
create table todo_sync_state (
key text primary key,
value text,
updated_at timestamptz not null default now()
);
alter table todo_item enable row level security;
alter table todo_ext enable row level security;
alter table todo_link enable row level security;
alter table todo_event enable row level security;
alter table todo_request enable row level security;
alter table todo_sync_state enable row level security;