Raleigh Dermatology — Service Record
-- ════════════════════════════════════════════════════════════ -- 09 RALEIGH DERMATOLOGY: INVENTORY, MAINTENANCE, SECTIONS, MESSAGES -- Run once in the Supabase SQL Editor. Safe to re-run. -- -- This file includes everything from 06 and 08, so it works whether -- or not those were ever run. Nothing is deleted. Franklin Farm is -- unchanged, and get_property_record() is not touched. -- -- Adds: -- * supplies: monitor level, on-order flag, order note, count detail, -- counted date, photos, section -- * office_messages: chat and item comments (office <-> team) -- * get_office_record() client page read (access code) -- * post_office_message() client page write (access code) -- * Nov 1, 2026 Janitor's Closet counts (only items not already listed) -- ════════════════════════════════════════════════════════════ -- 1. Record type (from 06) ──────────────────────────────────── alter table properties add column if not exists record_type text not null default 'estate'; alter table properties drop constraint if exists properties_record_type_check; alter table properties add constraint properties_record_type_check check (record_type in ('estate','office')); update properties set record_type = 'office', status_badge = coalesce(status_badge, 'Service active'), footer_note = coalesce(footer_note, 'Scope of service: routine cleaning. Sharps, regulated medical waste, and blood or body-fluid spills remain with the practice''s clinical staff.'), updated_at = now() where id = '4e1e9db0-a6f1-41d6-9a64-4f618be02d25'; -- 2. Supplies (from 06) plus inventory fields ───────────────── create table if not exists supplies ( id uuid primary key default gen_random_uuid(), property_id uuid not null references properties(id) on delete cascade, item_name text not null, category text, stored_at text, unit text, on_hand numeric not null default 0, min_level numeric not null default 0, supplied_by text, created_at timestamptz not null default now(), updated_at timestamptz not null default now() ); create index if not exists idx_supplies_property on supplies(property_id); alter table supplies add column if not exists monitor_level numeric; -- "Monitor" at or below this alter table supplies add column if not exists on_order boolean not null default false; alter table supplies add column if not exists order_note text; -- e.g. "Ordered Nov 1" alter table supplies add column if not exists count_detail text; -- e.g. "+ 23 loose rolls" alter table supplies add column if not exists counted_at date; alter table supplies add column if not exists photos text[] not null default '{}'; alter table supplies add column if not exists sort_order int not null default 0; -- 3. Notes (from 06) ────────────────────────────────────────── create table if not exists property_notes ( id uuid primary key default gen_random_uuid(), property_id uuid not null references properties(id) on delete cascade, note_text text not null, created_at timestamptz not null default now() ); create index if not exists idx_property_notes_property on property_notes(property_id); -- 4. Sections (from 08) ─────────────────────────────────────── create table if not exists sections ( id uuid primary key default gen_random_uuid(), property_id uuid not null references properties(id) on delete cascade, section_number int not null, name text not null, area text, rooms text[] not null default '{}', last_cleaned date, note text, created_at timestamptz not null default now(), updated_at timestamptz not null default now(), unique (property_id, section_number) ); create index if not exists idx_sections_property on sections(property_id); alter table records add column if not exists section_id uuid references sections(id) on delete set null; alter table supplies add column if not exists section_id uuid references sections(id) on delete set null; insert into sections (property_id, section_number, name, area, rooms) values ('4e1e9db0-a6f1-41d6-9a64-4f618be02d25', 1, 'Section 1', 'Northwest', array[ 'Medical Waiting Room','Medical Front Desk','Cosmetic Waiting Room','Cosmetic Front Desk', 'Cosmetic Rooms (2)','Supply Closet','UV Room','Patient Bathrooms (2)','Room 7','Room 8']), ('4e1e9db0-a6f1-41d6-9a64-4f618be02d25', 2, 'Section 2', 'Northeast', array[ 'Mohs Waiting Room','Offices (2)','IT Office','Employee Restroom','Room 1','Room 2','Room 3','Middle Lab','Big Lab']), ('4e1e9db0-a6f1-41d6-9a64-4f618be02d25', 3, 'Section 3', 'Southeast', array[ 'Room 4','Room 5','Room 6','Room 9','Room 10','Room 12','Room 13','Room 14','Room 15','Room 16', 'Provider Offices (3)','Staff Kitchen','Back Exit Hallway','Cosmetic Rooms (2)']), ('4e1e9db0-a6f1-41d6-9a64-4f618be02d25', 4, 'Section 4', 'Southwest', array[ 'Cosmetic Room','Patient Bathroom','Laundry','Staff Bathroom','Room 11','Offices (2)','Procedure Room','Desk']) on conflict (property_id, section_number) do nothing; -- 5. Messages and comments ──────────────────────────────────── -- target_type null = general chat message -- target_type set = comment on a supply, concern, or section create table if not exists office_messages ( id uuid primary key default gen_random_uuid(), property_id uuid not null references properties(id) on delete cascade, author_role text not null check (author_role in ('office','team')), author_name text not null, body text not null check (char_length(body) between 1 and 2000), target_type text check (target_type in ('supply','concern','section')), target_id uuid, read_at timestamptz, -- when the team read an office message created_at timestamptz not null default now() ); create index if not exists idx_office_messages_property on office_messages(property_id, created_at); -- 6. Access: org members manage everything; clients only through the functions alter table supplies enable row level security; alter table property_notes enable row level security; alter table sections enable row level security; alter table office_messages enable row level security; grant select, insert, update, delete on supplies, property_notes, sections, office_messages to authenticated; do $$ declare t text; begin foreach t in array array['supplies','property_notes','sections','office_messages'] loop execute format('drop policy if exists "org members manage %1$s" on %1$I', t); execute format($p$create policy "org members manage %1$s" on %1$I for all using (property_id in (select id from properties where org_id in (select org_id from memberships where user_id = auth.uid()))) with check (property_id in (select id from properties where org_id in (select org_id from memberships where user_id = auth.uid())))$p$, t); end loop; end $$; -- 7. Client read ────────────────────────────────────────────── create or replace function get_office_record(p_property_id text, p_access_code text) returns jsonb language plpgsql security definer set search_path = public, extensions set row_security = off as $$ declare v properties%rowtype; begin select * into v from properties where id::text = p_property_id and record_type = 'office'; if not found or p_access_code is null or crypt(p_access_code, v.access_code_hash) <> v.access_code_hash then return jsonb_build_object('ok', false); end if; return jsonb_build_object( 'ok', true, 'property', jsonb_build_object( 'name', v.property_name, 'address', v.address_line, 'badge', v.status_badge, 'lastVisitLabel', v.last_walk_label, 'lastVisit', v.last_walk_value, 'nextVisit', v.next_scheduled, 'steward', v.steward_of_record, 'scope', v.footer_note ), 'supplies', ( select coalesce(jsonb_agg(jsonb_build_object( 'id', sp.id, 'item', sp.item_name, 'category', sp.category, 'storedAt', sp.stored_at, 'unit', sp.unit, 'onHand', sp.on_hand, 'detail', sp.count_detail, 'orderAt', sp.min_level, 'monitorAt', sp.monitor_level, 'orderNote', sp.order_note, 'sectionId', sp.section_id, 'photos', sp.photos, 'counted', to_char(coalesce(sp.counted_at, sp.updated_at::date), 'Mon DD, YYYY'), 'countedIso', coalesce(sp.counted_at, sp.updated_at::date), 'status', case when sp.on_order then 'ordered' when sp.on_hand <= sp.min_level then 'order' when sp.monitor_level is not null and sp.on_hand <= sp.monitor_level then 'monitor' else 'stocked' end ) order by sp.stored_at nulls last, sp.sort_order, sp.item_name), '[]'::jsonb) from supplies sp where sp.property_id = v.id ), 'concerns', ( select coalesce(jsonb_agg(jsonb_build_object( 'id', r.id, 'ref', r.display_id, 'title', r.title, 'band', r.band, 'status', r.status, 'location', r.location, 'sectionId', r.section_id, 'owner', r.owner, 'action', r.action_required, 'found', to_char(coalesce(r.found_date, r.created_at::date), 'Mon DD, YYYY'), 'notes', ( select coalesce(jsonb_agg(jsonb_build_object( 'date', n.note_date, 'text', n.note_text, 'images', coalesce(n.images, '{}') ) order by n.created_at), '[]'::jsonb) from record_notes n where n.record_id = r.id ) ) order by r.created_at desc), '[]'::jsonb) from records r where r.property_id = v.id ), 'sections', ( select coalesce(jsonb_agg(jsonb_build_object( 'id', s.id, 'number', s.section_number, 'name', s.name, 'area', s.area, 'rooms', s.rooms, 'note', s.note, 'lastCleaned', to_char(s.last_cleaned, 'Dy, Mon DD') ) order by s.section_number), '[]'::jsonb) from sections s where s.property_id = v.id ), 'messages', ( select coalesce(jsonb_agg(jsonb_build_object( 'id', m.id, 'role', m.author_role, 'name', m.author_name, 'body', m.body, 'targetType', m.target_type, 'targetId', m.target_id, 'at', to_char(m.created_at at time zone 'America/New_York', 'Mon DD, HH12:MI AM') ) order by m.created_at), '[]'::jsonb) from (select * from office_messages where property_id = v.id order by created_at desc limit 300) m ), 'generated', to_char(now() at time zone 'America/New_York', 'Mon DD, YYYY "at" HH12:MI AM') ); end; $$; -- 8. Client write: message or comment ───────────────────────── create or replace function post_office_message( p_property_id text, p_access_code text, p_name text, p_body text, p_target_type text default null, p_target_id uuid default null) returns jsonb language plpgsql security definer set search_path = public, extensions set row_security = off as $$ declare v properties%rowtype; v_name text := left(btrim(coalesce(p_name, '')), 80); v_body text := left(btrim(coalesce(p_body, '')), 2000); v_id uuid; begin select * into v from properties where id::text = p_property_id and record_type = 'office'; if not found or p_access_code is null or crypt(p_access_code, v.access_code_hash) <> v.access_code_hash then return jsonb_build_object('ok', false, 'error', 'code'); end if; if v_name = '' or v_body = '' then return jsonb_build_object('ok', false, 'error', 'empty'); end if; if p_target_type is not null and p_target_type not in ('supply','concern','section') then return jsonb_build_object('ok', false, 'error', 'target'); end if; if p_target_type = 'supply' and not exists (select 1 from supplies where id = p_target_id and property_id = v.id) or p_target_type = 'concern' and not exists (select 1 from records where id = p_target_id and property_id = v.id) or p_target_type = 'section' and not exists (select 1 from sections where id = p_target_id and property_id = v.id) then return jsonb_build_object('ok', false, 'error', 'target'); end if; if (select count(*) from office_messages where property_id = v.id and author_role = 'office' and created_at > now() - interval '10 minutes') >= 30 then return jsonb_build_object('ok', false, 'error', 'rate'); end if; insert into office_messages (property_id, author_role, author_name, body, target_type, target_id) values (v.id, 'office', v_name, v_body, p_target_type, case when p_target_type is null then null else p_target_id end) returning id into v_id; return jsonb_build_object('ok', true, 'id', v_id); end; $$; revoke all on function get_office_record(text, text) from public; revoke all on function post_office_message(text, text, text, text, text, uuid) from public; grant execute on function get_office_record(text, text) to anon, authenticated; grant execute on function post_office_message(text, text, text, text, text, uuid) to anon, authenticated; -- 9. Janitor's Closet counts, Nov 1, 2026 ───────────────────── -- Order / Monitor levels are starting points. Change them in the steward app. insert into supplies (property_id, item_name, category, stored_at, unit, on_hand, count_detail, min_level, monitor_level, on_order, order_note, counted_at, sort_order) select '4e1e9db0-a6f1-41d6-9a64-4f618be02d25', x.item, x.cat, 'Janitor''s Closet', x.unit, x.qty, x.detail, x.order_at, x.monitor_at, x.on_order, x.note, date '2026-11-01', x.ord from (values ('Toilet paper', 'Paper', 'rolls', 127, null::text, 24, 48, false, null::text, 1), ('Paper towels', 'Paper', 'rolls', 10, null, 4, 6, false, null, 2), ('Flat paper towels', 'Paper', 'packs', 55, null, 10, 20, false, null, 3), ('Small clear trash bags', 'Liners', 'cases', 5, '+ 23 loose rolls', 1, 2, false, null, 4), ('Large black kitchen bags', 'Liners', 'rolls', 3.5, null, 2, 4, false, null, 5), ('13-gal white bags', 'Liners', 'rolls', 6, null, 2, 4, true, 'Just ordered', 6), ('Large clear medical bags (40-44 gal)','Liners', 'rolls', 0.5, null, 1, 2, false, null, 7), ('Disinfectant wipes', 'Disinfect', 'containers', 1, null, 1, 2, false, null, 8) ) as x(item, cat, unit, qty, detail, order_at, monitor_at, on_order, note, ord) where not exists ( select 1 from supplies s where s.property_id = '4e1e9db0-a6f1-41d6-9a64-4f618be02d25' and lower(s.item_name) = lower(x.item) ); -- Confirm select item_name, on_hand, unit, case when on_order then 'Already ordered' when on_hand <= min_level then 'Order needed' when monitor_level is not null and on_hand <= monitor_level then 'Monitor' else 'Stocked' end as status from supplies where property_id = '4e1e9db0-a6f1-41d6-9a64-4f618be02d25' order by sort_order, item_name;