create table incoming_emails
(
    id                      bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default now()             not null,
    incoming_email_id       uuid                     default gen_random_uuid() not null
        constraint incoming_emails_smtp_email_attachment_id_key
            unique,
    recipient               text,
    sender                  text,
    subject                 text,
    body_plain              text,
    body_html               text,
    filename                text,
    file_url                text,
    alias_mail_recipient    text,
    attachments             json,
    time                    numeric,
    is_fwd                  boolean                  default false,
    author_name             text,
    return_path             text,
    delivered_to            text,
    received                text,
    dkim_signature          text,
    x_google_dkim_signature text,
    x_gm_message_state      text,
    x_gm_gg                 text,
    x_google_smtp_source    text,
    x_received              text,
    mime_version            text,
    date                    text,
    "from"                  text,
    x_gm_features           text,
    message_id              text
        unique,
    content_type            text,
    x_uid                   text,
    status                  text,
    "to"                    text,
    company_id              uuid
        references companies (company_id)
);

alter table incoming_emails
    owner to postgres;

grant select, update, usage on sequence incoming_emails_id_seq to anon;

grant select, update, usage on sequence incoming_emails_id_seq to authenticated;

grant select, update, usage on sequence incoming_emails_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on incoming_emails to anon;

grant delete, insert, references, select, trigger, truncate, update on incoming_emails to authenticated;

grant delete, insert, references, select, trigger, truncate, update on incoming_emails to service_role;

create table monitors
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()             not null,
    monitor_id            uuid                     default gen_random_uuid() not null
        unique,
    maintenance           boolean                  default false,
    status                text,
    enabled               boolean                  default false,
    last_checked_at       numeric                  default '0'::numeric,
    average_response_time numeric                  default '0'::numeric,
    uptime                numeric                  default '0'::numeric,
    organization_id       text,
    url                   text
        unique,
    method                text                     default 'GET'::text,
    expected_http_code    numeric                  default '200'::numeric,
    interval_seconds      numeric                  default '60'::numeric,
    domain                text,
    fallback_strategy     text,
    fallback_webhook      text,
    body_payload          json,
    favicon               text,
    drilldown_url         text,
    group_id              text,
    lookback_days         numeric                  default '90'::numeric,
    has_uptime_chart      boolean                  default true,
    chart_key             text,
    expected_json_body    json,
    name                  text,
    public                boolean                  default false
);

alter table monitors
    owner to postgres;

grant select, update, usage on sequence monitors_id_seq to anon;

grant select, update, usage on sequence monitors_id_seq to authenticated;

grant select, update, usage on sequence monitors_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on monitors to anon;

grant delete, insert, references, select, trigger, truncate, update on monitors to authenticated;

grant delete, insert, references, select, trigger, truncate, update on monitors to service_role;

create table monitor_logs
(
    id                       bigint generated by default as identity
        primary key,
    created_at               timestamp with time zone default now() not null,
    monitor_id               uuid                     default gen_random_uuid(),
    time                     numeric,
    received_http_code       numeric,
    received_json_response   json,
    url                      text,
    expected_http_code       numeric,
    method                   text,
    domain                   text,
    organization_id          text,
    response_time_ms         numeric,
    headers                  json,
    meta_og_title            text,
    meta_og_image            text,
    success                  boolean,
    meta_description         text,
    meta_og_author           text,
    meta_og_url              text,
    meta_og_description      text,
    meta_og_type             text,
    meta_og_locale           text,
    meta_twitter_card        text,
    meta_twitter_title       text,
    meta_twitter_description text,
    meta_twitter_creator     text,
    title                    text
);

alter table monitor_logs
    owner to postgres;

grant select, update, usage on sequence monitor_logs_id_seq to anon;

grant select, update, usage on sequence monitor_logs_id_seq to authenticated;

grant select, update, usage on sequence monitor_logs_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on monitor_logs to anon;

grant delete, insert, references, select, trigger, truncate, update on monitor_logs to authenticated;

grant delete, insert, references, select, trigger, truncate, update on monitor_logs to service_role;

create table company_usage
(
    id                              bigint generated by default as identity
        primary key,
    created_at                      timestamp with time zone default now() not null,
    company_id                      uuid
        references companies (company_id),
    ponto_accounts_connected        numeric                  default '0'::numeric,
    drive_storage_used_bytes        numeric                  default '0'::numeric,
    drive_storage_bytes_limit       numeric                  default '35000000000'::numeric,
    ponto_accounts_connected_limit  numeric                  default '10'::numeric,
    receipts_scanned                numeric                  default '0'::numeric,
    receipts_scanned_limit          numeric                  default '1000'::numeric,
    sales_invoice_created           numeric                  default '0'::numeric,
    sales_invoice_created_limit     numeric                  default '500'::numeric,
    sales_invoice_emails_sent       numeric                  default '0'::numeric,
    sales_invoice_emails_sent_limit numeric                  default '100'::numeric,
    quotes_made                     numeric                  default '0'::numeric,
    quotes_made_limit               numeric                  default '100'::numeric,
    quotes_sent_email               numeric                  default '0'::numeric,
    quotes_sent_email_limit         numeric                  default '100'::numeric,
    transactions                    numeric                  default '0'::numeric,
    transactions_limit              numeric                  default '100000'::numeric,
    reconciliations                 numeric                  default '0'::numeric,
    reconciliations_limit           numeric                  default '10000'::numeric,
    company_usage_id                uuid                     default gen_random_uuid()
        unique
);

alter table company_usage
    owner to postgres;

grant select, update, usage on sequence company_usage_id_seq to anon;

grant select, update, usage on sequence company_usage_id_seq to authenticated;

grant select, update, usage on sequence company_usage_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on company_usage to anon;

grant delete, insert, references, select, trigger, truncate, update on company_usage to authenticated;

grant delete, insert, references, select, trigger, truncate, update on company_usage to service_role;

create table yuki_raw_transactions
(
    merchant    text,
    date        text,
    description text,
    debit       text,
    credit      text
);

alter table yuki_raw_transactions
    owner to postgres;

grant delete, insert, references, select, trigger, truncate, update on yuki_raw_transactions to anon;

grant delete, insert, references, select, trigger, truncate, update on yuki_raw_transactions to authenticated;

grant delete, insert, references, select, trigger, truncate, update on yuki_raw_transactions to service_role;

create table job_types
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default now() not null,
    name              text,
    job_type_id       uuid                     default gen_random_uuid(),
    concurency_weight bigint
);

alter table job_types
    owner to postgres;

grant select, update, usage on sequence job_types_id_seq to anon;

grant select, update, usage on sequence job_types_id_seq to authenticated;

grant select, update, usage on sequence job_types_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on job_types to anon;

grant delete, insert, references, select, trigger, truncate, update on job_types to authenticated;

grant delete, insert, references, select, trigger, truncate, update on job_types to service_role;

create table quote_line_items
(
    id             bigint generated by default as identity
        primary key,
    line_item_id   uuid                     default gen_random_uuid(),
    quote_id       uuid,
    product_id     uuid,
    price_id       uuid,
    quantity       numeric,
    unit_price     numeric,
    tax_rate       numeric,
    tax_inclusive  boolean                  default true,
    product_name   text,
    subtotal       numeric,
    total          numeric,
    subtotal_fmt   text,
    total_fmt      text,
    unit_price_fmt text,
    created_at     timestamp with time zone default now() not null
);

alter table quote_line_items
    owner to postgres;

grant delete, insert, references, select, trigger, truncate, update on quote_line_items to anon;

grant delete, insert, references, select, trigger, truncate, update on quote_line_items to authenticated;

grant delete, insert, references, select, trigger, truncate, update on quote_line_items to service_role;

create table quote_settings
(
    id                                        bigint generated by default as identity
        primary key,
    default_currency                          text,
    created_at                                timestamp with time zone default now() not null,
    quote_prefix                              text,
    expiry_days                               bigint                   default '30'::bigint,
    company_id                                uuid                                   not null,
    default_note                              text,
    default_footer                            text,
    starting_number                           numeric                  default '1'::numeric,
    year_format                               text                     default 'show'::text,
    quote_setting_id                          uuid                     default gen_random_uuid(),
    hosted_quote_page                         boolean                  default true,
    retry_schedule_one_time_quote_max_retries numeric                  default '3'::numeric,
    quote_finalization_grace_period_minutes   numeric                  default '60'::numeric
);

alter table quote_settings
    owner to postgres;

grant select, update, usage on sequence quote_settings_id_seq to anon;

grant select, update, usage on sequence quote_settings_id_seq to authenticated;

grant select, update, usage on sequence quote_settings_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on quote_settings to anon;

grant delete, insert, references, select, trigger, truncate, update on quote_settings to authenticated;

grant delete, insert, references, select, trigger, truncate, update on quote_settings to service_role;

create table aurora_config
(
    id                         bigint generated by default as identity
        primary key,
    created_at                 timestamp with time zone default now() not null,
    enable_paddle_ocr_engine   boolean                  default false,
    enable_tesseract_engine    boolean                  default false,
    enable_ocrspace_engine     boolean                  default false,
    datacenter_ocr_space       numeric                  default '2'::numeric,
    aurora_config_id           uuid                     default gen_random_uuid()
        unique,
    document_hashing_algorithm text,
    document_hashing_template  text
);

alter table aurora_config
    owner to postgres;

grant select, update, usage on sequence aurora_config_id_seq to anon;

grant select, update, usage on sequence aurora_config_id_seq to authenticated;

grant select, update, usage on sequence aurora_config_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on aurora_config to anon;

grant delete, insert, references, select, trigger, truncate, update on aurora_config to authenticated;

grant delete, insert, references, select, trigger, truncate, update on aurora_config to service_role;

create table aurora_requests
(
    id                                      bigint generated by default as identity
        constraint aurora_ocr_requests_pkey
            primary key,
    created_at                              timestamp with time zone default now() not null,
    engine                                  text,
    status                                  text,
    success                                 boolean                  default false,
    message                                 text,
    ocr_backend_response_time_ms            numeric                  default '0'::numeric,
    is_errored_on_processing                boolean                  default false,
    error_message                           text,
    error_details                           text,
    parsed_text                             text,
    text_orientation                        numeric                  default '0'::numeric,
    searchable_pdf_url                      text,
    file_parse_exit_code                    numeric                  default '0'::numeric,
    aurora_ocr_request_id                   uuid                     default gen_random_uuid()
        constraint aurora_ocr_requests_aurora_ocr_request_id_key
            unique,
    aurora_api_response_time_ms             numeric                  default '0'::numeric,
    aurora_post_processing_response_time_ms numeric                  default '0'::numeric,
    aurora_pre_processing_response_time_ms  numeric                  default '0'::numeric,
    user_id                                 text
        references users (user_id),
    company_id                              uuid
        references companies (company_id),
    file_url                                text,
    engine_version                          text,
    aurora_version                          text,
    time                                    numeric                  default '0'::numeric,
    hash                                    text                                   not null,
    aurora_request_id                       uuid                                   not null
        unique,
    json                                    json,
    document_type                           text,
    document_json                           json,
    score                                   numeric                  default '0'::numeric,
    keys_identified                         numeric                  default '0'::numeric,
    items_y_axis_angle_tilts                json,
    aurora_y_tilt_calc_processing_time      numeric                  default '0'::numeric,
    avg_y_axis_global_tilt                  numeric,
    y_axis_group_margin                     numeric,
    enable_upscaler                         boolean                  default false,
    line_item_parser_model                  text,
    line_item_parsing_processing_time       numeric,
    document_organic_model_json             json,
    document_parser_model_json              json,
    document_organic_model_keys             numeric,
    line_item_organic_model                 text                     default 'aurora-v0.1.0'::text,
    line_item_organic_processing_time       numeric,
    line_item_parser_response               json,
    document_openrouter_json                json,
    document_parser_model_keys              numeric,
    line_items_json                         json,
    request_id_masked                       uuid
        unique
);

alter table aurora_requests
    owner to postgres;

grant delete, insert, references, select, trigger, truncate, update on aurora_requests to anon;

grant delete, insert, references, select, trigger, truncate, update on aurora_requests to authenticated;

grant delete, insert, references, select, trigger, truncate, update on aurora_requests to service_role;

create table aurora_keys
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()             not null,
    aurora_key_id         uuid                     default gen_random_uuid() not null
        unique,
    key                   text,
    description           text,
    document_type         text,
    global_key            text
        constraint aurora_keys_doc_key_key
            unique,
    type                  text,
    only_alphanumeric     boolean                  default false,
    is_currency           boolean                  default false,
    force_uppercase_value boolean                  default false
);

alter table aurora_keys
    owner to postgres;

grant select, update, usage on sequence aurora_keys_id_seq to anon;

grant select, update, usage on sequence aurora_keys_id_seq to authenticated;

grant select, update, usage on sequence aurora_keys_id_seq to service_role;

create table aurora_parser_rules
(
    id                             bigint generated by default as identity
        primary key,
    created_at                     timestamp with time zone default now() not null,
    document_type                  text                     default 'receipt'::text,
    global                         boolean                  default true,
    value                          text,
    pointer                        text                     default 'grouped_lines'::text,
    key                            text
        references aurora_keys (global_key),
    enabled                        boolean                  default true,
    aurora_parser_rule_id          uuid                     default gen_random_uuid()
        unique,
    country_code                   text                     default 'NL'::text,
    parsing_strategy               text                     default 'partial_match'::text,
    function_call                  text,
    regex                          text,
    char_limit                     numeric,
    has_also_contain_numbers       boolean                  default false,
    include_entire_line_when_match boolean                  default true,
    is_case_sensitive              boolean                  default false,
    include_value_on_match         boolean                  default false,
    infinite_x_lookback_range      boolean                  default false,
    infinite_y_lookback_range      boolean                  default false,
    y_scope_max_one_value_down     boolean                  default false,
    y_look_back_range_margin       numeric,
    key_priority                   numeric                  default '0'::numeric,
    template_value                 text,
    is_currency_value              numeric
);

alter table aurora_parser_rules
    owner to postgres;

grant select, update, usage on sequence aurora_parser_rules_id_seq to anon;

grant select, update, usage on sequence aurora_parser_rules_id_seq to authenticated;

grant select, update, usage on sequence aurora_parser_rules_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on aurora_parser_rules to anon;

grant delete, insert, references, select, trigger, truncate, update on aurora_parser_rules to authenticated;

grant delete, insert, references, select, trigger, truncate, update on aurora_parser_rules to service_role;

grant delete, insert, references, select, trigger, truncate, update on aurora_keys to anon;

grant delete, insert, references, select, trigger, truncate, update on aurora_keys to authenticated;

grant delete, insert, references, select, trigger, truncate, update on aurora_keys to service_role;

create table aurora_language_support
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default now() not null,
    country_code  text,
    status        text,
    language      text,
    note          text,
    language_code text,
    supported     boolean                  default false,
    stable        boolean                  default false
);

alter table aurora_language_support
    owner to postgres;

grant select, update, usage on sequence aurora_language_support_id_seq to anon;

grant select, update, usage on sequence aurora_language_support_id_seq to authenticated;

grant select, update, usage on sequence aurora_language_support_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on aurora_language_support to anon;

grant delete, insert, references, select, trigger, truncate, update on aurora_language_support to authenticated;

grant delete, insert, references, select, trigger, truncate, update on aurora_language_support to service_role;

create table aurora_line_items
(
    id                       bigint generated by default as identity
        primary key,
    created_at               timestamp with time zone default now() not null,
    name                     text,
    quantity                 numeric                  default '1'::numeric,
    price                    numeric,
    price_unit               numeric,
    currency                 text                     default 'EUR'::text,
    ledger_code_value        text,
    ledger_code_ref          text,
    merchant_name            text,
    country_code             text                     default 'NL'::text,
    ledger_code_long         text,
    vat_rate                 numeric                  default '21'::numeric,
    line_item_hash           text
        unique,
    details                  json,
    origin_aurora_request_id uuid,
    is_under_your_earnings   boolean                  default false,
    verified                 boolean                  default false
);

alter table aurora_line_items
    owner to postgres;

grant select, update, usage on sequence aurora_line_items_id_seq to anon;

grant select, update, usage on sequence aurora_line_items_id_seq to authenticated;

grant select, update, usage on sequence aurora_line_items_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on aurora_line_items to anon;

grant delete, insert, references, select, trigger, truncate, update on aurora_line_items to authenticated;

grant delete, insert, references, select, trigger, truncate, update on aurora_line_items to service_role;

create table feature_flags
(
    id          bigint generated by default as identity
        primary key,
    created_at  timestamp with time zone default now() not null,
    user_id     text
        references users (user_id),
    name        text,
    description text,
    enabled     boolean                  default false,
    flag        text
);

alter table feature_flags
    owner to postgres;

grant select, update, usage on sequence feature_flags_id_seq to anon;

grant select, update, usage on sequence feature_flags_id_seq to authenticated;

grant select, update, usage on sequence feature_flags_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on feature_flags to anon;

grant delete, insert, references, select, trigger, truncate, update on feature_flags to authenticated;

grant delete, insert, references, select, trigger, truncate, update on feature_flags to service_role;

create table contact_persons
(
    id                                                              bigint generated by default as identity,
    contact_id                                                      uuid                     default gen_random_uuid() not null
        primary key,
    name                                                            text,
    phone                                                           text,
    email                                                           text,
    note                                                            text,
    customer_id                                                     uuid                                               not null,
    created_at                                                      timestamp with time zone default now()             not null,
    identification_json                                             json,
    identification_url                                              text,
    title                                                           text,
    date_of_birth                                                   text,
    home_address_country_code                                       text,
    home_address_address                                            text,
    home_address_apartment_unit_other                               text,
    home_address_postal_code                                        text,
    home_address_city                                               text,
    stake_percentage                                                numeric                  default '0'::numeric,
    is_member_of_governing_board                                    boolean                  default false,
    is_executive_or_senior_manager_with_significant_management_resp boolean                  default false,
    owns_more_than_25_percent                                       boolean                  default false,
    legal_first_name                                                text,
    legal_last_name                                                 text,
    contact_number                                                  text,
    salutation                                                      text,
    initials                                                        text,
    first_names                                                     text,
    infix                                                           text,
    gender                                                          text                     default 'male'::text
);

alter table contact_persons
    owner to postgres;

grant select, update, usage on sequence contact_persons_id_seq to anon;

grant select, update, usage on sequence contact_persons_id_seq to authenticated;

grant select, update, usage on sequence contact_persons_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on contact_persons to anon;

grant delete, insert, references, select, trigger, truncate, update on contact_persons to authenticated;

grant delete, insert, references, select, trigger, truncate, update on contact_persons to service_role;

create table customer_types
(
    id               bigint generated by default as identity,
    customer_type_id uuid                     default gen_random_uuid() not null,
    name             text,
    company_id       uuid
        references companies (company_id),
    created_at       timestamp with time zone default now()             not null,
    description      text,
    primary key (id, customer_type_id)
);

alter table customer_types
    owner to postgres;

grant select, update, usage on sequence customer_types_id_seq to anon;

grant select, update, usage on sequence customer_types_id_seq to authenticated;

grant select, update, usage on sequence customer_types_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on customer_types to anon;

grant delete, insert, references, select, trigger, truncate, update on customer_types to authenticated;

grant delete, insert, references, select, trigger, truncate, update on customer_types to service_role;

create table aurora_merchants
(
    id                           bigint generated by default as identity
        primary key,
    created_at                   timestamp with time zone default now() not null,
    name                         text,
    aurora_merchant_id           uuid                     default gen_random_uuid()
        unique,
    total_documents_in_foundry   numeric                  default '0'::numeric,
    avg_y_axis_tilt_group_margin numeric                  default '11'::numeric,
    country_code                 text,
    company_number               text,
    vat_id                       text,
    avatar                       text,
    updated_at                   numeric,
    score                        numeric,
    most_common_document_type    text                     default 'receipt'::text,
    website                      text,
    metadata                     json,
    email                        text,
    company_number_ref           text,
    company_entity               text,
    address_line_1               text,
    address_line_2               text,
    postal_code                  text,
    house_number                 text,
    state                        text,
    language                     text                     default 'en'::text,
    province                     text,
    company_nature               text
);

alter table aurora_merchants
    owner to postgres;

grant select, update, usage on sequence aurora_merchants_id_seq to anon;

grant select, update, usage on sequence aurora_merchants_id_seq to authenticated;

grant select, update, usage on sequence aurora_merchants_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on aurora_merchants to anon;

grant delete, insert, references, select, trigger, truncate, update on aurora_merchants to authenticated;

grant delete, insert, references, select, trigger, truncate, update on aurora_merchants to service_role;

create table aurora_logs
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default now() not null,
    aurora_log_id uuid                     default gen_random_uuid()
        unique,
    status        text,
    http_code     numeric,
    ocr_engine    text,
    file_url      text,
    message       text,
    request_id    text
);

alter table aurora_logs
    owner to postgres;

grant select, update, usage on sequence aurora_logs_id_seq to anon;

grant select, update, usage on sequence aurora_logs_id_seq to authenticated;

grant select, update, usage on sequence aurora_logs_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on aurora_logs to anon;

grant delete, insert, references, select, trigger, truncate, update on aurora_logs to authenticated;

grant delete, insert, references, select, trigger, truncate, update on aurora_logs to service_role;

create table frontend_config
(
    id                              bigint generated by default as identity
        primary key,
    created_at                      timestamp with time zone default now()             not null,
    frontend_config_id              uuid                     default gen_random_uuid() not null
        unique,
    current_status_in_status_banner text                     default 'maintenance'::text,
    disable_status_banner           boolean                  default true
);

alter table frontend_config
    owner to postgres;

grant select, update, usage on sequence frontend_config_id_seq to anon;

grant select, update, usage on sequence frontend_config_id_seq to authenticated;

grant select, update, usage on sequence frontend_config_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on frontend_config to anon;

grant delete, insert, references, select, trigger, truncate, update on frontend_config to authenticated;

grant delete, insert, references, select, trigger, truncate, update on frontend_config to service_role;

create table openrouter_api_requests
(
    id                       bigint generated by default as identity
        primary key,
    created_at               timestamp with time zone default now() not null,
    generation_id            text
        unique,
    cost_total               numeric,
    cost_web_search          numeric,
    cost_cache               numeric,
    cost_file_processing     numeric,
    tokens_prompt            numeric,
    tokens_completion        numeric,
    tokens_reasoning         numeric,
    model_permaslug          text,
    provider_name            text,
    variant                  text,
    cancelled                boolean,
    streamed                 boolean,
    finish_reason_raw        text,
    finish_reason_normalized text,
    generation_time_ms       numeric,
    time_to_first_token_ms   numeric,
    app_name                 text,
    api_key_name             text
);

alter table openrouter_api_requests
    owner to postgres;

grant select, update, usage on sequence openrouter_api_requests_id_seq to anon;

grant select, update, usage on sequence openrouter_api_requests_id_seq to authenticated;

grant select, update, usage on sequence openrouter_api_requests_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on openrouter_api_requests to anon;

grant delete, insert, references, select, trigger, truncate, update on openrouter_api_requests to authenticated;

grant delete, insert, references, select, trigger, truncate, update on openrouter_api_requests to service_role;

create table company_roles
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default now()             not null,
    company_role_id uuid                     default gen_random_uuid() not null
        unique,
    title           text,
    description     text,
    global          boolean                  default false,
    enabled         boolean                  default false,
    translation_key text
);

comment on table company_roles is 'Contains company roles and their underlying possible permissions';

alter table company_roles
    owner to postgres;

grant select, update, usage on sequence company_roles_id_seq to anon;

grant select, update, usage on sequence company_roles_id_seq to authenticated;

grant select, update, usage on sequence company_roles_id_seq to service_role;

create table company_members
(
    id                                                              bigint generated by default as identity
        primary key,
    created_at                                                      timestamp with time zone default now()             not null,
    job_title                                                       text,
    user_id                                                         text
        references users (user_id),
    date_of_birth                                                   text,
    home_address_country                                            text,
    home_address_address                                            text,
    home_address_apartment_unit_other                               text,
    home_address_postal_code                                        text,
    home_address_city                                               text,
    stake_percentage                                                numeric                  default '0'::numeric,
    is_member_of_governing_board                                    boolean                  default false,
    is_executive_or_senior_manager_with_significant_management_resp boolean                  default false,
    owns_more_than_25_percent                                       boolean                  default false,
    legal_first_name                                                text,
    legal_last_name                                                 text,
    company_id                                                      uuid
        references companies (company_id),
    is_owner                                                        boolean                  default false,
    alias                                                           text,
    added_by_user_id                                                text
        references users (user_id),
    invite_code_used                                                text
        references company_invite_codes (invite_code),
    status                                                          text                     default 'pending'::text,
    active                                                          boolean                  default false,
    last_seen_at                                                    numeric                  default '0'::numeric,
    joined_at                                                       numeric                  default '0'::numeric,
    email                                                           text,
    name                                                            text,
    idempotency_key                                                 uuid                     default gen_random_uuid()
        unique,
    department                                                      text,
    company_member_id                                               uuid                     default gen_random_uuid() not null
        unique,
    invite_email_sent_at                                            numeric,
    invite_email_sent                                               boolean                  default false,
    temp_password                                                   text,
    temp_password_reset                                             boolean                  default false,
    team                                                            text,
    invite_url                                                      text,
    added_by_name                                                   text,
    added_by_location                                               text,
    added_by_ipv4                                                   text,
    added_by_email                                                  text,
    role_id                                                         uuid
        references company_roles (company_role_id),
    access_group_id                                                 uuid
        references access_groups (access_group_id),
    masked_company_member_id                                        text
        unique,
    confirmation_email_sent                                         boolean                  default false,
    confirmation_email_sent_at                                      numeric,
    hide_on_webapp                                                  boolean                  default false,
    invited_at                                                      numeric,
    display_name                                                    text,
    auth_index                                                      numeric                  default '1'::numeric
);

alter table company_members
    owner to postgres;

grant select, update, usage on sequence company_members_id_seq to anon;

grant select, update, usage on sequence company_members_id_seq to authenticated;

grant select, update, usage on sequence company_members_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on company_members to anon;

grant delete, insert, references, select, trigger, truncate, update on company_members to authenticated;

grant delete, insert, references, select, trigger, truncate, update on company_members to service_role;

grant delete, insert, references, select, trigger, truncate, update on company_roles to anon;

grant delete, insert, references, select, trigger, truncate, update on company_roles to authenticated;

grant delete, insert, references, select, trigger, truncate, update on company_roles to service_role;

create table event_log_api
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default now() not null,
    object        text                     default 'request'::text,
    request_id    uuid                     default gen_random_uuid(),
    user_id       text,
    company_id    text,
    body          json,
    query_string  text,
    headers       json,
    method        text,
    path          text,
    http_code     numeric,
    ipv4          text,
    user_agent    text,
    time          numeric,
    host          text,
    server        text                     default 'xylex.cloud'::text,
    cached        boolean                  default false,
    response_time numeric,
    cache_key     text
);

alter table event_log_api
    owner to postgres;

grant select, update, usage on sequence event_log_api_id_seq to anon;

grant select, update, usage on sequence event_log_api_id_seq to authenticated;

grant select, update, usage on sequence event_log_api_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on event_log_api to anon;

grant delete, insert, references, select, trigger, truncate, update on event_log_api to authenticated;

grant delete, insert, references, select, trigger, truncate, update on event_log_api to service_role;

create table sidebar_items
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default now() not null,
    href            text,
    label           text,
    translation_key text,
    index           numeric,
    icon            text,
    category        text,
    enabled         boolean                  default false,
    is_submenu      boolean                  default false
);

alter table sidebar_items
    owner to postgres;

grant select, update, usage on sequence sidebar_items_id_seq to anon;

grant select, update, usage on sequence sidebar_items_id_seq to authenticated;

grant select, update, usage on sequence sidebar_items_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on sidebar_items to anon;

grant delete, insert, references, select, trigger, truncate, update on sidebar_items to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sidebar_items to service_role;

create table documents_v2
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()             not null,
    document_id           uuid                     default gen_random_uuid() not null
        unique,
    file_id               uuid,
    file_url              text,
    company_id            uuid
        references companies (company_id),
    merchant_id           uuid
        references merchants (merchant_id),
    bank_account_id       uuid
        references banking_accounts (banking_account_id),
    aurora_record_id      uuid,
    aurora_request_id     uuid
        references aurora_requests (request_id_masked),
    currency              text                     default 'EUR'::text,
    document_type         text                     default 'RECEIPT'::text,
    document_date         text,
    receipt_number        text,
    customer_info         json,
    merchant_info         json,
    earnings_details      json,
    items                 json,
    vat_details           json,
    totals_details        json,
    system_checks         json,
    reconciled            boolean                  default false,
    updated_at            numeric,
    invoice_number        text,
    misc                  json,
    payment_details       json,
    total                 numeric,
    amount_due            numeric,
    subtotal              numeric,
    tax_amount            numeric,
    total_paid            numeric,
    booked                boolean                  default false,
    order_id              text,
    debtor_number         text,
    payment_term          text,
    merchant_name         text,
    test_mode             boolean                  default false,
    document_date_unix    numeric,
    dedup_hash            text,
    dedup_serialized      text,
    merchant_country_code text,
    reconciliation_id     uuid,
    customer_name         text
);

alter table documents_v2
    owner to postgres;

grant select, update, usage on sequence documents_v2_id_seq to anon;

grant select, update, usage on sequence documents_v2_id_seq to authenticated;

grant select, update, usage on sequence documents_v2_id_seq to service_role;

create index documents_v2_company_id_invoice_number_idx
    on documents_v2 (company_id, invoice_number);

create index documents_v2_company_id_order_id_idx
    on documents_v2 (company_id, order_id);

create index documents_v2_company_id_currency_idx
    on documents_v2 (company_id, currency);

create index documents_v2_company_id_merchant_id_idx
    on documents_v2 (company_id, merchant_id);

create index documents_v2_company_id_customer_name_idx
    on documents_v2 (company_id, customer_name);

create index documents_v2_company_id_total_idx
    on documents_v2 (company_id, total);

create index documents_v2_company_id_document_date_unix_idx
    on documents_v2 (company_id, document_date_unix);

create index documents_v2_company_id_total_currency_idx
    on documents_v2 (company_id, total, currency);

create index documents_v2_company_id_currency_merchant_id_idx
    on documents_v2 (company_id, currency, merchant_id);

create index documents_v2_company_id_currency_customer_name_idx
    on documents_v2 (company_id, currency, customer_name);

create index idx_documents_v2_reconciled
    on documents_v2 (company_id, reconciled, document_id);

create index ix_doc_company_unrec
    on documents_v2 (company_id, document_id)
    where (reconciled IS NOT TRUE);

create index ix_doc_company_invoice
    on documents_v2 (company_id, invoice_number)
    where ((invoice_number <> ''::text) AND (reconciled IS NOT TRUE));

create index ix_doc_company_order_id
    on documents_v2 (company_id, order_id)
    where ((order_id <> ''::text) AND (reconciled IS NOT TRUE));

create index ix_doc_company_currency_merchant
    on documents_v2 (company_id, currency, merchant_id)
    where (reconciled IS NOT TRUE);

create index ix_doc_company_currency_customer
    on documents_v2 (company_id, currency, customer_name)
    where (reconciled IS NOT TRUE);

create index brin_doc_company_date
    on documents_v2 using brin (company_id, document_date_unix);

create index ix_docs_company_currency_total
    on documents_v2 (company_id, currency, total);

create index docs_company_currency_total_date_idx
    on documents_v2 (company_id, currency, total, document_date_unix)
    where (reconciled IS NOT TRUE);

grant delete, insert, references, select, trigger, truncate, update on documents_v2 to anon;

grant delete, insert, references, select, trigger, truncate, update on documents_v2 to authenticated;

grant delete, insert, references, select, trigger, truncate, update on documents_v2 to service_role;

create table microsoft_calendar_events
(
    id                          bigint generated by default as identity
        primary key,
    created_at                  timestamp with time zone default now() not null,
    microsoft_user_id           text,
    microsoft_event_id          text                                   not null
        unique,
    microsoft_calendar_event_id uuid                     default gen_random_uuid(),
    subject                     text,
    body_preview                text,
    body                        json,
    start_time                  numeric,
    end_time                    numeric,
    location                    json,
    attendees                   json,
    organizer                   json,
    company_id                  uuid
        references companies (company_id)
);

alter table microsoft_calendar_events
    owner to postgres;

grant select, update, usage on sequence microsoft_calendar_events_id_seq to anon;

grant select, update, usage on sequence microsoft_calendar_events_id_seq to authenticated;

grant select, update, usage on sequence microsoft_calendar_events_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on microsoft_calendar_events to anon;

grant delete, insert, references, select, trigger, truncate, update on microsoft_calendar_events to authenticated;

grant delete, insert, references, select, trigger, truncate, update on microsoft_calendar_events to service_role;

create table customer_jurisdictions
(
    id                       bigint generated by default as identity
        primary key,
    created_at               timestamp with time zone default now() not null,
    customer_jurisdiction_id uuid                     default gen_random_uuid()
        unique,
    name                     text,
    country_code             text                     default 'NL'::text,
    company_id               uuid
        references companies (company_id),
    global                   boolean                  default true,
    enabled                  boolean                  default true,
    description              text,
    updated_at               numeric,
    color                    text
);

alter table customer_jurisdictions
    owner to postgres;

grant select, update, usage on sequence customer_jurisdictions_id_seq to anon;

grant select, update, usage on sequence customer_jurisdictions_id_seq to authenticated;

grant select, update, usage on sequence customer_jurisdictions_id_seq to service_role;

create table customers
(
    id                               bigint generated by default as identity
        unique,
    customer_id                      uuid      default gen_random_uuid() not null
        constraint customers_pkey1
            primary key,
    company_number                   text,
    vat_id                           text,
    note                             text,
    street_address                   text,
    address_line_2                   text,
    city                             text,
    state_province_region            text,
    postal_code                      text,
    country                          text      default 'NL'::text,
    email                            text,
    size                             text,
    customer_type_id                 text,
    phone                            text,
    website                          text,
    legal_form                       text,
    owner                            text,
    vat_return_frequency             text      default 'quarterly'::text,
    icp_return_frequency             text      default 'monthly'::text,
    cash_management                  text      default 'no_cash'::text,
    subject_to_vat                   boolean   default true,
    created_at                       timestamp default now(),
    name                             text,
    main_contact_id                  uuid,
    company_id                       uuid                                not null
        constraint customers_company_id_fkey1
            references companies (company_id),
    domain                           text,
    administration                   text,
    contract_start_date              numeric,
    accounting_start_date            numeric,
    closing_enabled                  boolean   default false,
    self_booking                     boolean   default false,
    global_company_id                uuid,
    customer_jurisdiction            text,
    account_manager                  text,
    archive_hash                     text
        constraint customers_archive_descriptor_key
            unique,
    customer_jurisdiction_id         uuid
        references customer_jurisdictions (customer_jurisdiction_id),
    status                           text      default 'ACTIVE'::text,
    allow_self_accounting            boolean   default false,
    companies                        numeric   default '1'::numeric,
    users                            numeric   default '1'::numeric,
    workflow                         numeric   default '0'::numeric,
    tickets                          numeric   default '0'::numeric,
    questions                        numeric   default '0'::numeric,
    is_overdue                       boolean   default false,
    data_provider                    text      default 'NATIVE'::text,
    portal                           text,
    data_provider_reference_id       text,
    signed_gdpr_document             boolean   default false,
    archived_at                      numeric,
    inactive_on                      numeric,
    last_seen_at                     numeric,
    bundle                           text,
    accountant_id                    text,
    accountant_name                  text,
    accountant_is_partner_backoffice boolean   default false,
    currencies                       json,
    default_currency                 json,
    domain_wildcard_email            text,
    internal_email_support           text,
    internal_phone_number            text,
    internal_email_administration    text,
    supported_languages              json,
    is_partner_domain                text,
    subject_to_reverse_vat_charge    boolean   default false,
    avatar                           text,
    metadata                         json,
    company_country_number           text
        unique,
    payment_method_invoice           text,
    person_number_ref                text,
    person_number                    text,
    birth_day                        text,
    salutations                      text,
    payment_term_invoice             text,
    label                            text,
    language_invoice_and_quote       text,
    last_name                        text,
    street                           text,
    first_name                       text,
    description                      text,
    reverse_charged                  boolean   default false
);

alter table customers
    owner to postgres;

create table invoices
(
    id                              bigint generated by default as identity,
    recipient_name                  text,
    recipient_email                 text,
    invoice_nr                      text,
    recipient_postal_code           text,
    recipient_phone                 text,
    recipient_first_name            text,
    recipient_last_name             text,
    recipient_address               text,
    recipient_country               text,
    due_date                        numeric                                            not null,
    created_at                      timestamp with time zone default now()             not null,
    currency                        text                     default 'EUR'::text,
    contact                         uuid
        references contacts (contact_id)
            on delete set default,
    status                          text,
    recipient_company               text,
    recipient_company_id            uuid
        references companies (company_id),
    invoice_id                      uuid                     default gen_random_uuid() not null
        unique,
    paid                            boolean                  default false,
    author_name                     text,
    link_tos                        text,
    link_privacy_policy             text,
    memo                            text,
    author_email                    text,
    author_postal_code              text,
    author_phone                    text,
    author_first_name               text,
    author_last_name                text,
    author_address                  text,
    author_country                  text,
    author_company_id               text,
    author_vat_id                   text,
    author_tax_id                   text,
    author_kvk                      text,
    recipient_kvk                   text,
    recipient_tax_id                text,
    recipient_vat_id                text,
    amount                          numeric(8, 2)            default '0'::numeric,
    amount_paid                     numeric                  default '0'::numeric,
    amount_remaining                numeric                  default '0'::numeric,
    paid_at                         numeric                  default '0'::numeric,
    payment_method                  text,
    number_format                   text                     default 'nl-NL'::text,
    email_sent                      boolean                  default false,
    email_id                        uuid,
    email_sent_at                   numeric,
    times_opened                    numeric,
    times_opened_unique             numeric,
    company_logo                    text,
    company_logo_href               text,
    discount_code                   text,
    discount_total                  numeric                  default '0'::numeric,
    discount                        boolean                  default false,
    shipping_rate                   boolean                  default false,
    shipping_total                  numeric                  default '0'::numeric,
    send_as_email                   boolean                  default false,
    subscription                    boolean                  default false,
    subscription_id                 text,
    relation_hash                   text,
    scheduled_email_send_at         numeric,
    descriptor_global               text,
    descriptor_relation             text,
    number_global                   numeric,
    number_relation                 numeric,
    url                             text,
    brand_color                     text,
    pdf_generated                   boolean                  default false,
    pdf_url                         text,
    reverse_charged                 boolean                  default false,
    invoice_template_id             uuid                     default gen_random_uuid(),
    custom_fields                   json,
    tax_id_type_recipient           text,
    tax_id_type_author              text,
    descriptor_project              text,
    views                           numeric                  default '0'::numeric,
    revenue                         numeric                  default '0'::numeric,
    sales                           numeric                  default '0'::numeric,
    note                            text,
    url_link_deactivated            boolean                  default false,
    total_fmt                       text,
    subtotal_fmt                    text,
    tax_total_fmt                   text,
    has_payment_callback            boolean                  default false,
    payment_method_count            numeric                  default '1'::numeric,
    invoice_age_days_past_due       numeric                  default '0'::numeric,
    payment_methods                 jsonb,
    creator_ip_address              text,
    author_tax_country              text,
    recipient_tax_country           text,
    issue_date                      numeric,
    payment_method_ids              text,
    footer                          text,
    slug                            text
        unique,
    subtotal                        numeric,
    tax_amount                      numeric,
    total                           numeric,
    idempotency_key                 uuid                     default gen_random_uuid(),
    payment_method_configuration_id uuid,
    language                        text                     default 'en'::text,
    amount_paid_fmt                 text,
    amount_remaining_fmt            text,
    tax_rate                        numeric                  default '21'::numeric,
    time_creation                   numeric                  default '0'::numeric,
    recipient_billing_street        text,
    recipient_shipping_street       text,
    recipient_billing_house_number  text,
    recipient_shipping_house_number text,
    recipient_billing_country       text,
    recipient_shipping_country      text,
    recipient_shipping_province     text,
    recipient_shipping_city         text,
    tax_exempt                      boolean                  default false,
    tax_inclusive                   boolean                  default false,
    receipt_url                     text,
    awaiting_archival               boolean                  default false,
    reconciliation_id               uuid,
    quote_id                        text,
    customer                        uuid
        references customers,
    global_company_id               uuid,
    amount_due_fmt                  text,
    ref_identifier                  text
        constraint invoices_ref_invoice_identifier_key
            unique,
    ref_provider                    text,
    total_incl_vat                  numeric,
    primary key (id, invoice_id)
);

alter table invoices
    owner to postgres;

grant select, update, usage on sequence invoices_id_seq to anon;

grant select, update, usage on sequence invoices_id_seq to authenticated;

grant select, update, usage on sequence invoices_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on invoices to anon;

grant delete, insert, references, select, trigger, truncate, update on invoices to authenticated;

grant delete, insert, references, select, trigger, truncate, update on invoices to service_role;

create table mollie_payment_links
(
    id                     bigint generated by default as identity
        primary key,
    created_at             timestamp with time zone default now()             not null,
    mollie_account_id      uuid
        references mollie_accounts (mollie_account_id),
    mollie_payment_link_id uuid                     default gen_random_uuid() not null
        unique,
    label                  text,
    description            text,
    url                    text,
    status                 text                     default 'pending'::text,
    allowed_methods        json,
    amount_value           text,
    amount_currency        text,
    archived               boolean                  default false,
    expires_at             text,
    payment_link_id        text
        unique,
    mode                   text,
    paid_at                numeric,
    profile_id             text,
    redirect_url           text,
    resource               text                     default 'payment-link'::text,
    reusable               boolean                  default false,
    sequence_type          text                     default 'oneoff'::text,
    webhook_url            text,
    payment_link           text,
    self_link              text,
    invoice_id             uuid
        references invoices (invoice_id),
    link_payment           text,
    link_self              text
);

alter table mollie_payment_links
    owner to postgres;

grant select, update, usage on sequence mollie_payment_links_id_seq to anon;

grant select, update, usage on sequence mollie_payment_links_id_seq to authenticated;

grant select, update, usage on sequence mollie_payment_links_id_seq to service_role;

create index idx_mollie_payment_links_invoice
    on mollie_payment_links (invoice_id);

grant delete, insert, references, select, trigger, truncate, update on mollie_payment_links to anon;

grant delete, insert, references, select, trigger, truncate, update on mollie_payment_links to authenticated;

grant delete, insert, references, select, trigger, truncate, update on mollie_payment_links to service_role;

create table tickets
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default now()             not null,
    title           text,
    description     text,
    creator_userid  uuid                                               not null,
    assignee_userid uuid,
    priority        text,
    status          text,
    company_id      uuid,
    ticket_id       uuid                     default gen_random_uuid() not null
        unique,
    ticket_number   numeric,
    due_date        timestamp with time zone,
    closed_at       numeric,
    close_reason    text,
    closed          boolean                  default false,
    closed_user_id  text
        references users (user_id),
    customer_id     uuid
        references customers
);

comment on table tickets is 'tickets for suitsconnect';

alter table tickets
    owner to postgres;

grant select, update, usage on sequence tickets_id_seq to anon;

grant select, update, usage on sequence tickets_id_seq to authenticated;

grant select, update, usage on sequence tickets_id_seq to service_role;

create trigger tickets_notify
    after insert or update or delete
    on tickets
    for each row
execute procedure notify_tickets();

grant delete, insert, references, select, trigger, truncate, update on tickets to anon;

grant delete, insert, references, select, trigger, truncate, update on tickets to authenticated;

grant delete, insert, references, select, trigger, truncate, update on tickets to service_role;

create table quotes
(
    id                              bigint generated by default as identity,
    recipient_name                  text,
    recipient_email                 text,
    invoice_nr                      text,
    recipient_postal_code           text,
    recipient_phone                 text,
    recipient_first_name            text,
    recipient_last_name             text,
    recipient_address               text,
    recipient_country               text,
    created_at                      timestamp with time zone default now()             not null,
    currency                        text                     default 'EUR'::text,
    contact                         uuid
        references contacts (contact_id)
            on delete set default,
    status                          text,
    recipient_company               text,
    recipient_company_id            uuid
        references companies (company_id),
    quote_id                        uuid                     default gen_random_uuid() not null
        constraint quotes_invoice_id_key
            unique,
    paid                            boolean                  default false,
    author_name                     text,
    link_tos                        text,
    link_privacy_policy             text,
    memo                            text,
    author_email                    text,
    author_postal_code              text,
    author_phone                    text,
    author_first_name               text,
    author_last_name                text,
    author_address                  text,
    author_country                  text,
    author_company_id               text,
    author_vat_id                   text,
    author_tax_id                   text,
    author_kvk                      text,
    recipient_kvk                   text,
    recipient_tax_id                text,
    recipient_vat_id                text,
    amount                          numeric                  default '0'::numeric,
    amount_paid                     numeric                  default '0'::numeric,
    amount_remaining                numeric                  default '0'::numeric,
    paid_at                         numeric                  default '0'::numeric,
    payment_method                  text,
    number_format                   text                     default 'nl-NL'::text,
    email_sent                      boolean                  default false,
    email_id                        uuid,
    email_sent_at                   numeric,
    times_opened                    numeric,
    times_opened_unique             numeric,
    company_logo                    text,
    company_logo_href               text,
    discount_code                   text,
    discount_total                  numeric                  default '0'::numeric,
    discount                        boolean                  default false,
    shipping_rate                   boolean                  default false,
    shipping_total                  numeric                  default '0'::numeric,
    send_as_email                   boolean                  default false,
    subscription                    boolean                  default false,
    subscription_id                 text,
    relation_hash                   text,
    scheduled_email_send_at         numeric,
    descriptor_global               text,
    descriptor_relation             text,
    number_global                   numeric,
    number_relation                 numeric,
    url                             text,
    brand_color                     text,
    pdf_generated                   boolean                  default false,
    pdf_url                         text,
    reverse_charged                 boolean                  default false,
    invoice_template_id             uuid                     default gen_random_uuid(),
    custom_fields                   json,
    tax_id_type_recipient           text,
    tax_id_type_author              text,
    descriptor_project              text,
    views                           numeric                  default '0'::numeric,
    revenue                         numeric                  default '0'::numeric,
    sales                           numeric                  default '0'::numeric,
    note                            text,
    url_link_deactivated            boolean                  default false,
    total_fmt                       text,
    subtotal_fmt                    text,
    tax_total_fmt                   text,
    has_payment_callback            boolean                  default false,
    payment_method_count            numeric                  default '1'::numeric,
    invoice_age_days_past_due       numeric                  default '0'::numeric,
    payment_methods                 jsonb,
    creator_ip_address              text,
    author_tax_country              text,
    recipient_tax_country           text,
    issue_date                      numeric,
    payment_method_ids              text,
    footer                          text,
    slug                            text
        unique,
    subtotal                        numeric,
    tax_amount                      numeric,
    total                           numeric,
    idempotency_key                 uuid                     default gen_random_uuid(),
    payment_method_configuration_id uuid,
    language                        text                     default 'en'::text,
    amount_paid_fmt                 text,
    amount_remaining_fmt            text,
    tax_rate                        numeric                  default '21'::numeric,
    time_creation                   numeric                  default '0'::numeric,
    recipient_billing_street        text,
    recipient_shipping_street       text,
    recipient_billing_house_number  text,
    recipient_shipping_house_number text,
    recipient_billing_country       text,
    recipient_shipping_country      text,
    recipient_shipping_province     text,
    recipient_shipping_city         text,
    expiry_date                     numeric,
    quote_nr                        text                                               not null,
    signature                       text,
    signer_name                     text,
    signer_email                    text,
    signed_date                     numeric,
    view_key                        text,
    signer_ip                       text,
    customer                        uuid
        references customers,
    global_company_id               uuid,
    awaiting_archival               boolean                  default false,
    primary key (id, quote_id)
);

alter table quotes
    owner to postgres;

grant select, update, usage on sequence quotes_id_seq to anon;

grant select, update, usage on sequence quotes_id_seq to authenticated;

grant select, update, usage on sequence quotes_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on quotes to anon;

grant delete, insert, references, select, trigger, truncate, update on quotes to authenticated;

grant delete, insert, references, select, trigger, truncate, update on quotes to service_role;

create table ticket_chats
(
    chat_id              uuid                     default uuid_generate_v4() not null
        primary key,
    user1_id             uuid                                                not null
        constraint fk_user1
            references auth.users
            on delete cascade,
    user2_id             uuid
        constraint fk_user2
            references auth.users
            on delete cascade,
    created_at           timestamp with time zone default now()              not null,
    last_message_at      timestamp with time zone,
    last_message_preview text,
    ticket_id            uuid                                                not null
        unique
        references tickets (ticket_id),
    constraint unique_user_pair
        unique (user1_id, user2_id),
    constraint ordered_user_ids_nullable
        check ((user2_id IS NULL) OR ((user2_id IS NOT NULL) AND (user1_id < user2_id)))
);

comment on column ticket_chats.user2_id is 'Nullable to support unassigned tickets. When null, only user1_id participates until someone is assigned.';

comment on constraint ordered_user_ids_nullable on ticket_chats is 'Ensures user1_id < user2_id when both exist, allows null user2_id for unassigned tickets.';

alter table ticket_chats
    owner to postgres;

create index idx_ticket_chats_user2
    on ticket_chats (user2_id)
    where (user2_id IS NOT NULL);

create policy ticket_chats_insert on ticket_chats
    as permissive
    for insert
    with check ((auth.uid() = user1_id) OR ((user2_id IS NOT NULL) AND (auth.uid() = user2_id)));

create policy ticket_chats_select on ticket_chats
    as permissive
    for select
    using ((auth.uid() = user1_id) OR ((user2_id IS NOT NULL) AND (auth.uid() = user2_id)));

grant delete, insert, references, select, trigger, truncate, update on ticket_chats to anon;

grant delete, insert, references, select, trigger, truncate, update on ticket_chats to authenticated;

grant delete, insert, references, select, trigger, truncate, update on ticket_chats to service_role;

create table ticket_messages
(
    message_id          uuid                     default uuid_generate_v4() not null,
    chat_id             uuid                                                not null
        constraint fk_chat
            references ticket_chats
            on delete cascade,
    sender_id           uuid                                                not null
        constraint fk_sender
            references auth.users
            on delete cascade,
    text                text                                                not null,
    created_at          timestamp with time zone default now()              not null,
    reply_to_message_id uuid,
    time                numeric,
    attachments         json,
    deleted             boolean                  default false,
    message_updated_at  bigint,
    id                  bigint generated by default as identity
        primary key
);

alter table ticket_messages
    owner to postgres;

grant select, update, usage on sequence ticket_messages_id_seq to anon;

grant select, update, usage on sequence ticket_messages_id_seq to authenticated;

grant select, update, usage on sequence ticket_messages_id_seq to service_role;

create trigger trigger_update_ticket_chat_last_message
    after insert
    on ticket_messages
    for each row
execute procedure update_ticket_chat_last_message();

create policy ticket_messages_insert on ticket_messages
    as permissive
    for insert
    with check ((auth.uid() = sender_id) AND (auth.uid() IN (SELECT ticket_chats.user1_id
                                                             FROM ticket_chats
                                                             WHERE (ticket_chats.chat_id = ticket_messages.chat_id)
                                                             UNION
                                                             SELECT ticket_chats.user2_id
                                                             FROM ticket_chats
                                                             WHERE ((ticket_chats.chat_id = ticket_messages.chat_id) AND
                                                                    (ticket_chats.user2_id IS NOT NULL)))));

create policy ticket_messages_select on ticket_messages
    as permissive
    for select
    using (auth.uid() IN (SELECT ticket_chats.user1_id
                          FROM ticket_chats
                          WHERE (ticket_chats.chat_id = ticket_messages.chat_id)
                          UNION
                          SELECT ticket_chats.user2_id
                          FROM ticket_chats
                          WHERE ((ticket_chats.chat_id = ticket_messages.chat_id) AND
                                 (ticket_chats.user2_id IS NOT NULL))));

grant delete, insert, references, select, trigger, truncate, update on ticket_messages to anon;

grant delete, insert, references, select, trigger, truncate, update on ticket_messages to authenticated;

grant delete, insert, references, select, trigger, truncate, update on ticket_messages to service_role;

grant delete, insert, references, select, trigger, truncate, update on customers to anon;

grant delete, insert, references, select, trigger, truncate, update on customers to authenticated;

grant delete, insert, references, select, trigger, truncate, update on customers to service_role;

create table ticket_todos
(
    id                bigint generated by default as identity
        constraint ticket_todos_duplicate_pkey
            primary key,
    created_at        timestamp with time zone default now()             not null,
    updated_at        timestamp with time zone default now()             not null,
    title             text                                               not null,
    description       text,
    status            text                                               not null,
    created_by        uuid                                               not null
        constraint ticket_todos_duplicate_created_by_fkey
            references auth.users
            on delete cascade,
    assigned_to       uuid
        constraint ticket_todos_duplicate_assigned_to_fkey
            references auth.users
            on delete set null,
    due_date          timestamp with time zone,
    priority          integer                  default 1,
    todo_id           uuid                     default gen_random_uuid() not null
        unique,
    ticket_id         uuid                     default gen_random_uuid() not null
        constraint ticket_todos_duplicate_ticket_id_fkey
            references tickets (ticket_id),
    completed_user_id text
        references users (user_id),
    completed_at      numeric
);

comment on table ticket_todos is 'This is a duplicate of ticket_todos';

comment on column ticket_todos.priority is 'Priority level: 1=low, 2=medium, 3=high, 4=urgent';

alter table ticket_todos
    owner to postgres;

create index ticket_todos_duplicate_assigned_to_idx
    on ticket_todos (assigned_to);

create index ticket_todos_duplicate_due_date_idx
    on ticket_todos (due_date);

create index ticket_todos_duplicate_status_idx
    on ticket_todos (status);

grant delete, insert, references, select, trigger, truncate, update on ticket_todos to anon;

grant delete, insert, references, select, trigger, truncate, update on ticket_todos to authenticated;

grant delete, insert, references, select, trigger, truncate, update on ticket_todos to service_role;

grant delete, insert, references, select, trigger, truncate, update on customer_jurisdictions to anon;

grant delete, insert, references, select, trigger, truncate, update on customer_jurisdictions to authenticated;

grant delete, insert, references, select, trigger, truncate, update on customer_jurisdictions to service_role;

create table xbp_commits
(
    id                      text not null
        primary key,
    created_at              text,
    sender_id               text,
    sender_name             text,
    commit_id               text,
    repository_id           text,
    message                 text,
    repository_name         text,
    ref                     text,
    before                  text,
    after                   text,
    updated_at              text,
    pushed_at               text,
    size                    text,
    pusher_name             text,
    pusher_email            text,
    sender_avatar_url       text,
    compare_url             text,
    commits                 text,
    head_commit_id          text,
    head_commit_message     text,
    head_commit_timestamp   text,
    head_commit_url         text,
    head_commit_author_name text,
    head_commit_email       text,
    head_commit_username    text,
    committer_name          text,
    committer_email         text,
    committer_username      text,
    modified                text,
    repository_url          text
);

alter table xbp_commits
    owner to postgres;

grant delete, insert, references, select, trigger, truncate, update on xbp_commits to anon;

grant delete, insert, references, select, trigger, truncate, update on xbp_commits to authenticated;

grant delete, insert, references, select, trigger, truncate, update on xbp_commits to service_role;

create table xbp_deliveries
(
    id                                     bigint generated by default as identity
        primary key,
    created_at                             timestamp with time zone default now() not null,
    method                                 text,
    content_type                           text,
    user_agent                             text,
    x_github_delivery                      text,
    x_github_event                         text,
    x_github_hook_id                       text,
    x_github_hook_installation_target_id   text,
    x_github_hook_installation_target_type text,
    payload                                json,
    message                                text,
    time                                   numeric,
    repository_name                        text,
    repository_id                          text,
    sender_id                              text,
    request                                text                     default '/api/xbp/webhook'::text,
    status                                 numeric                  default '200'::numeric,
    host                                   text                     default 'xylex.cloud'::text,
    repository_url                         text
);

alter table xbp_deliveries
    owner to postgres;

grant select, update, usage on sequence xbp_deliveries_id_seq to anon;

grant select, update, usage on sequence xbp_deliveries_id_seq to authenticated;

grant select, update, usage on sequence xbp_deliveries_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on xbp_deliveries to anon;

grant delete, insert, references, select, trigger, truncate, update on xbp_deliveries to authenticated;

grant delete, insert, references, select, trigger, truncate, update on xbp_deliveries to service_role;

create table customer_activity
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()             not null,
    customer_id           uuid
        references customers,
    message               text,
    action                text,
    attachments           json,
    user_id               text
        references users (user_id),
    time                  numeric,
    company_id            uuid
        references companies (company_id),
    deletable             boolean                  default false,
    contact_person_scoped boolean                  default false,
    contact_person_id     uuid
        references contact_persons,
    avatar                text,
    display_name          text,
    customer_activity_id  uuid                     default gen_random_uuid() not null
        unique
);

alter table customer_activity
    owner to postgres;

grant select, update, usage on sequence customer_activity_id_seq to anon;

grant select, update, usage on sequence customer_activity_id_seq to authenticated;

grant select, update, usage on sequence customer_activity_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on customer_activity to anon;

grant delete, insert, references, select, trigger, truncate, update on customer_activity to authenticated;

grant delete, insert, references, select, trigger, truncate, update on customer_activity to service_role;

create table api_keys
(
    id           bigint generated by default as identity
        primary key,
    created_at   timestamp with time zone default now() not null,
    user_id      text
        references users (user_id),
    company_id   uuid
        references companies (company_id),
    key          text,
    secret       text,
    generated_at numeric,
    title        text,
    exp_at       numeric,
    system       boolean                  default false,
    last_used_at numeric,
    enabled      boolean                  default false
);

alter table api_keys
    owner to postgres;

grant select, update, usage on sequence api_keys_id_seq to anon;

grant select, update, usage on sequence api_keys_id_seq to authenticated;

grant select, update, usage on sequence api_keys_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on api_keys to anon;

grant delete, insert, references, select, trigger, truncate, update on api_keys to authenticated;

grant delete, insert, references, select, trigger, truncate, update on api_keys to service_role;

create table ticket_activity
(
    id                 bigint generated by default as identity
        primary key,
    created_at         timestamp with time zone default now()             not null,
    ticket_activity_id uuid                     default gen_random_uuid() not null
        unique,
    action             text,
    title              text,
    message            text,
    attachments        json,
    ticket_id          uuid
        references tickets (ticket_id),
    customer_id        uuid
        references customers,
    time               numeric,
    user_id            text
        references users (user_id)
);

alter table ticket_activity
    owner to postgres;

grant select, update, usage on sequence ticket_activity_id_seq to anon;

grant select, update, usage on sequence ticket_activity_id_seq to authenticated;

grant select, update, usage on sequence ticket_activity_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on ticket_activity to anon;

grant delete, insert, references, select, trigger, truncate, update on ticket_activity to authenticated;

grant delete, insert, references, select, trigger, truncate, update on ticket_activity to service_role;

create table customer_settings
(
    id         bigint generated by default as identity
        primary key,
    created_at timestamp with time zone default now() not null,
    company_id uuid
        references companies (company_id)
);

alter table customer_settings
    owner to postgres;

grant select, update, usage on sequence customer_settings_id_seq to anon;

grant select, update, usage on sequence customer_settings_id_seq to authenticated;

grant select, update, usage on sequence customer_settings_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on customer_settings to anon;

grant delete, insert, references, select, trigger, truncate, update on customer_settings to authenticated;

grant delete, insert, references, select, trigger, truncate, update on customer_settings to service_role;

create table reconciliation_ledger_processing_rules
(
    id                                       bigint generated by default as identity
        primary key,
    created_at                               timestamp with time zone default now()             not null,
    reconciliation_ledger_processing_rule_id uuid                     default gen_random_uuid() not null
        constraint reconciliation_ledger_process_reconciliation_ledger_process_key
            unique,
    iban                                     text,
    iban_counterparty                        text,
    name_counterparty                        text,
    account_holder_name                      text,
    account_holder_name_counterparty         text,
    country_code                             text                     default 'NL'::text,
    global                                   boolean                  default false,
    on_credits                               boolean                  default false,
    on_debits                                boolean                  default false,
    ledger_version                           text,
    ledger_code                              text,
    ledger_code_name                         text,
    enabled                                  boolean                  default false,
    auto_book                                boolean                  default false
);

alter table reconciliation_ledger_processing_rules
    owner to postgres;

grant select, update, usage on sequence reconciliation_ledger_processing_rules_id_seq to anon;

grant select, update, usage on sequence reconciliation_ledger_processing_rules_id_seq to authenticated;

grant select, update, usage on sequence reconciliation_ledger_processing_rules_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on reconciliation_ledger_processing_rules to anon;

grant delete, insert, references, select, trigger, truncate, update on reconciliation_ledger_processing_rules to authenticated;

grant delete, insert, references, select, trigger, truncate, update on reconciliation_ledger_processing_rules to service_role;

create table transaction_activity
(
    id                      bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default now()             not null,
    message                 text,
    action                  text,
    attachments             json,
    user_id                 text
        references users (user_id),
    time                    numeric,
    company_id              uuid,
    deletable               boolean                  default false,
    avatar                  text,
    display_name            text,
    transaction_id          uuid
        references transactions,
    system                  boolean                  default false,
    transaction_activity_id uuid                     default gen_random_uuid() not null
        unique
);

comment on table transaction_activity is 'This is a duplicate of customer_activity';

alter table transaction_activity
    owner to postgres;

grant select, update, usage on sequence transaction_activity_id_seq to anon;

grant select, update, usage on sequence transaction_activity_id_seq to authenticated;

grant select, update, usage on sequence transaction_activity_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on transaction_activity to anon;

grant delete, insert, references, select, trigger, truncate, update on transaction_activity to authenticated;

grant delete, insert, references, select, trigger, truncate, update on transaction_activity to service_role;

create table aurora_document_types
(
    id                      bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default now()             not null,
    name                    text
        unique,
    supported               boolean                  default false,
    status                  text                     default 'untested'::text,
    aurora_document_type_id uuid                     default gen_random_uuid() not null
        unique,
    global_cases            numeric                  default '0'::numeric,
    country_code            text                     default 'EN'::text,
    updated_at              bigint                   default (EXTRACT(epoch FROM now()))::bigint
);

alter table aurora_document_types
    owner to postgres;

grant select, update, usage on sequence aurora_document_types_id_seq to anon;

grant select, update, usage on sequence aurora_document_types_id_seq to authenticated;

grant select, update, usage on sequence aurora_document_types_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on aurora_document_types to anon;

grant delete, insert, references, select, trigger, truncate, update on aurora_document_types to authenticated;

grant delete, insert, references, select, trigger, truncate, update on aurora_document_types to service_role;

create table reconciliations_staging
(
    id                        bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default now()             not null,
    verified                  boolean                  default false,
    booked                    boolean                  default false,
    archived                  boolean                  default false,
    flagged                   boolean                  default false,
    reconciliation_staging_id uuid                     default gen_random_uuid() not null
        unique,
    reconciliation_id         uuid                                               not null
        references reconciliations (reconciliation_id)
            on delete cascade,
    company_id                uuid                                               not null
);

alter table reconciliations_staging
    owner to postgres;

grant select, update, usage on sequence reconciliations_staging_id_seq to anon;

grant select, update, usage on sequence reconciliations_staging_id_seq to authenticated;

grant select, update, usage on sequence reconciliations_staging_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_staging to anon;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_staging to authenticated;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_staging to service_role;

create table pm_deployments
(
    id                     bigint generated by default as identity
        constraint pm2_deployments_pkey
            primary key,
    created_at             timestamp with time zone default now() not null,
    project_id             text,
    deployment_id          text                                   not null
        unique,
    status                 text,
    pm_id                  numeric,
    pid                    numeric,
    commit_id              text,
    repository_url         text,
    commit_comment         text,
    time                   numeric,
    commit_author_username text,
    xbp_command            text,
    sha                    text,
    repository_name        text,
    sha_short              text,
    organization_name      text,
    project_name           text,
    github_username        text,
    repository_owner       text
);

alter table pm_deployments
    owner to postgres;

grant select, update, usage on sequence pm_deployments_id_seq to anon;

grant select, update, usage on sequence pm_deployments_id_seq to authenticated;

grant select, update, usage on sequence pm_deployments_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on pm_deployments to anon;

grant delete, insert, references, select, trigger, truncate, update on pm_deployments to authenticated;

grant delete, insert, references, select, trigger, truncate, update on pm_deployments to service_role;



alter table pm_postgrest
    owner to postgres;

grant select, update, usage on sequence pm_postgrest_id_seq to anon;

grant select, update, usage on sequence pm_postgrest_id_seq to authenticated;

grant select, update, usage on sequence pm_postgrest_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on pm_postgrest to anon;

grant delete, insert, references, select, trigger, truncate, update on pm_postgrest to authenticated;

grant delete, insert, references, select, trigger, truncate, update on pm_postgrest to service_role;

create table athena_queries
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default now()             not null,
    driver          text                     default 'athena'::text,
    db_client       text                     default 'postgres'::text,
    query           text,
    params          json,
    athena_query_id uuid                     default gen_random_uuid() not null
        unique,
    author          text
        references users (user_id),
    title           text,
    description     text,
    updated_at      numeric,
    path            text
);

alter table athena_queries
    owner to postgres;

grant select, update, usage on sequence athena_queries_id_seq to anon;

grant select, update, usage on sequence athena_queries_id_seq to authenticated;

grant select, update, usage on sequence athena_queries_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on athena_queries to anon;

grant delete, insert, references, select, trigger, truncate, update on athena_queries to authenticated;

grant delete, insert, references, select, trigger, truncate, update on athena_queries to service_role;

create table yuki_users
(
    id                         bigint generated by default as identity
        constraint yuki_portal_domain_users_pkey
            primary key,
    created_at                 timestamp with time zone default now()             not null,
    yuki_portal_domain_user_id uuid                     default gen_random_uuid() not null
        constraint yuki_portal_domain_users_yuki_portal_domain_user_id_key
            unique,
    yuki_id                    text                                               not null
        unique,
    site_id                    text,
    name                       text,
    login                      text,
    domain                     text,
    last_login                 text,
    imported_at                numeric,
    importer_email             text,
    importer_yuki_csrf_token   text,
    company_id                 uuid
        constraint yuki_portal_domain_users_company_id_fkey
            references companies (company_id),
    yuki_user_id               uuid                     default gen_random_uuid() not null
        unique
);

alter table yuki_users
    owner to postgres;

grant delete, insert, references, select, trigger, truncate, update on yuki_users to anon;

grant delete, insert, references, select, trigger, truncate, update on yuki_users to authenticated;

grant delete, insert, references, select, trigger, truncate, update on yuki_users to service_role;

create table yuki_credentials
(
    id                  bigint generated by default as identity
        primary key,
    created_at          timestamp with time zone default now()             not null,
    company_id          uuid
        references companies (company_id),
    user_id             text
        references users (user_id),
    yuki_csrf_token     text,
    user_agent          text,
    cookie              text,
    yuki_auth_2         text,
    yuki_session        text,
    yuki_email          text,
    yuki_device_cookie  text,
    yuki_auth           text,
    yuki_user_id        text,
    yuki_portal_id      text,
    yuki_device_id      text,
    yuki_distinct_id    text,
    yuki_credentials_id uuid                     default gen_random_uuid() not null
        unique
);

alter table yuki_credentials
    owner to postgres;

grant select, update, usage on sequence yuki_credentials_id_seq to anon;

grant select, update, usage on sequence yuki_credentials_id_seq to authenticated;

grant select, update, usage on sequence yuki_credentials_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on yuki_credentials to anon;

grant delete, insert, references, select, trigger, truncate, update on yuki_credentials to authenticated;

grant delete, insert, references, select, trigger, truncate, update on yuki_credentials to service_role;

create table yuki_domains
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()             not null,
    yuki_domain_id        uuid                     default gen_random_uuid() not null
        unique,
    status_id             integer,
    domain                text,
    created               date,
    status                text,
    companies             integer,
    workflow              integer,
    questions             integer,
    bobyparent            integer,
    bundle                text,
    trial                 boolean,
    signed_gdpr_document  boolean,
    allow_self_accounting integer,
    users                 integer,
    archived_on           timestamp with time zone,
    inactive_on           date,
    is_overdue            integer,
    portal                text
);

alter table yuki_domains
    owner to postgres;

grant select, update, usage on sequence yuki_domains_id_seq to anon;

grant select, update, usage on sequence yuki_domains_id_seq to authenticated;

grant select, update, usage on sequence yuki_domains_id_seq to service_role;

create unique index yuki_domains_domain_key
    on yuki_domains (domain);

grant delete, insert, references, select, trigger, truncate, update on yuki_domains to anon;

grant delete, insert, references, select, trigger, truncate, update on yuki_domains to authenticated;

grant delete, insert, references, select, trigger, truncate, update on yuki_domains to service_role;

create table api_codes
(
    id          bigint generated by default as identity
        primary key,
    created_at  timestamp with time zone default now()             not null,
    api_code_id uuid                     default gen_random_uuid() not null
        unique,
    code        text
        unique,
    success     boolean                  default false,
    description text,
    http_code   text,
    resource    text,
    service     text
);

alter table api_codes
    owner to postgres;

grant select, update, usage on sequence api_codes_id_seq to anon;

grant select, update, usage on sequence api_codes_id_seq to authenticated;

grant select, update, usage on sequence api_codes_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on api_codes to anon;

grant delete, insert, references, select, trigger, truncate, update on api_codes to authenticated;

grant delete, insert, references, select, trigger, truncate, update on api_codes to service_role;

create table connect_client_status
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default now() not null,
    user_id           text                                   not null
        unique
        references users (user_id),
    chat_id           uuid,
    last_active       bigint,
    ticket_id         text,
    task_id           text,
    user_status_id    uuid,
    app_in_background boolean
);

alter table connect_client_status
    owner to postgres;

grant select, update, usage on sequence connect_client_status_id_seq to anon;

grant select, update, usage on sequence connect_client_status_id_seq to authenticated;

grant select, update, usage on sequence connect_client_status_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on connect_client_status to anon;

grant delete, insert, references, select, trigger, truncate, update on connect_client_status to authenticated;

grant delete, insert, references, select, trigger, truncate, update on connect_client_status to service_role;

create table chat_subscriptions
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default now()             not null,
    subscription_id uuid                     default gen_random_uuid() not null,
    user_id         text                                               not null,
    ticket_id       text,
    chat_id         uuid                                               not null,
    task_id         text
);

alter table chat_subscriptions
    owner to postgres;

grant select, update, usage on sequence chat_subscriptions_id_seq to anon;

grant select, update, usage on sequence chat_subscriptions_id_seq to authenticated;

grant select, update, usage on sequence chat_subscriptions_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on chat_subscriptions to anon;

grant delete, insert, references, select, trigger, truncate, update on chat_subscriptions to authenticated;

grant delete, insert, references, select, trigger, truncate, update on chat_subscriptions to service_role;

create table link_meta_preview_cache
(
    id                         bigint generated by default as identity
        primary key,
    created_at                 timestamp with time zone default now()             not null,
    link_meta_preview_cache_id uuid                     default gen_random_uuid() not null
        unique,
    url                        text                                               not null
        unique,
    title                      text,
    description                text,
    content_type               text,
    media_type                 text,
    images                     json,
    videos                     json,
    audios                     json,
    domain                     text,
    updated_at                 numeric
);

alter table link_meta_preview_cache
    owner to postgres;

grant select, update, usage on sequence link_meta_preview_cache_id_seq to anon;

grant select, update, usage on sequence link_meta_preview_cache_id_seq to authenticated;

grant select, update, usage on sequence link_meta_preview_cache_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on link_meta_preview_cache to anon;

grant delete, insert, references, select, trigger, truncate, update on link_meta_preview_cache to authenticated;

grant delete, insert, references, select, trigger, truncate, update on link_meta_preview_cache to service_role;

create table api_registry
(
    id                            bigint generated by default as identity
        primary key,
    created_at                    timestamp with time zone default now()             not null,
    url                           text,
    method                        text                     default 'POST'::text,
    content_type                  text                     default 'application/json'::text,
    accept_encoding               text                     default 'gzip, deflate, br, zstd'::text,
    cache_control                 text                     default 'no-cache'::text,
    requires_auth_cookie          boolean                  default false,
    cookie                        text,
    user_agent                    text                     default ' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36'::text,
    required_headers              json                     default '[]'::json,
    requires_authorization_cookie boolean                  default false,
    "authorization"               text,
    domain                        text,
    path                          text                     default '/'::text,
    description                   text,
    expected_http_code            numeric                  default '200'::numeric,
    average_response_time         numeric,
    example_response_json         json,
    response_map_idempotency_key  text,
    response_map_error_message    text,
    response_map_data             text,
    example_request_payload       json,
    api_registry_id               uuid                     default gen_random_uuid() not null
        unique,
    api_slug                      text
        unique
);

alter table api_registry
    owner to postgres;

grant select, update, usage on sequence api_registry_id_seq to anon;

grant select, update, usage on sequence api_registry_id_seq to authenticated;

grant select, update, usage on sequence api_registry_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on api_registry to anon;

grant delete, insert, references, select, trigger, truncate, update on api_registry to authenticated;

grant delete, insert, references, select, trigger, truncate, update on api_registry to service_role;

create table pm_athena_router
(
    id         bigint generated by default as identity
        primary key,
    created_at timestamp with time zone default now() not null,
    host       text,
    athena_url text
);

alter table pm_athena_router
    owner to postgres;

grant select, update, usage on sequence pm_athena_router_id_seq to anon;

grant select, update, usage on sequence pm_athena_router_id_seq to authenticated;

grant select, update, usage on sequence pm_athena_router_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on pm_athena_router to anon;

grant delete, insert, references, select, trigger, truncate, update on pm_athena_router to authenticated;

grant delete, insert, references, select, trigger, truncate, update on pm_athena_router to service_role;

create table admin_config
(
    id                             bigint generated by default as identity
        primary key,
    created_at                     timestamp with time zone default now()             not null,
    admin_config_id                uuid                     default gen_random_uuid() not null
        unique,
    enable_notification_generation boolean                  default true
);

alter table admin_config
    owner to postgres;

grant select, update, usage on sequence admin_config_id_seq to anon;

grant select, update, usage on sequence admin_config_id_seq to authenticated;

grant select, update, usage on sequence admin_config_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on admin_config to anon;

grant delete, insert, references, select, trigger, truncate, update on admin_config to authenticated;

grant delete, insert, references, select, trigger, truncate, update on admin_config to service_role;

create table notification_logs
(
    id                   bigint generated by default as identity
        primary key,
    created_at           timestamp with time zone default now()             not null,
    status               text                                               not null,
    action               text                                               not null,
    resource_type        text                                               not null,
    resource_ref         text,
    notification_log_id  uuid                     default gen_random_uuid() not null,
    company_id           uuid,
    user_id              text,
    notification_type_id bigint
        constraint fk_notification_type
            references notification_types,
    message              text
);

alter table notification_logs
    owner to postgres;

grant select, update, usage on sequence notification_logs_id_seq to anon;

grant select, update, usage on sequence notification_logs_id_seq to authenticated;

grant select, update, usage on sequence notification_logs_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on notification_logs to anon;

grant delete, insert, references, select, trigger, truncate, update on notification_logs to authenticated;

grant delete, insert, references, select, trigger, truncate, update on notification_logs to service_role;

create table pm_projects
(
    id                    bigint generated by default as identity
        constraint pm2_projects_pkey
            primary key,
    created_at            timestamp with time zone default now()             not null,
    project_id            text                                               not null
        unique,
    project_name          text                                               not null
        unique,
    domain                text                                               not null
        unique,
    status                text,
    last_update           numeric,
    pid                   numeric,
    username              text,
    unique_id             text
        unique,
    args                  json,
    port                  numeric,
    process_name          text,
    uptime                numeric,
    deployed_at           numeric,
    pm_id                 numeric,
    memory                numeric,
    cpu                   numeric,
    pm_out_log_path       text,
    pm_err_log_path       text,
    pm_pid_path           text,
    repository_url        text,
    current_commit_id     text,
    icon_url              text,
    project_url           text,
    website_url           text,
    prod_branch           text,
    dev_branch            text,
    bucket_id             text,
    bucket_name           text,
    build_dir             text,
    pm_app_name           text,
    framework             text,
    organization_id       text,
    xbp_command           text,
    deploy_key            uuid                     default gen_random_uuid(),
    repository_name       text,
    auto_deploy           boolean                  default false,
    global_api_key        text,
    global_secret_token   text,
    health_check_endpoint text,
    pm_project_id         uuid                     default gen_random_uuid() not null
        unique
);

alter table pm_projects
    owner to postgres;

grant select, update, usage on sequence pm_projects_id_seq to anon;

grant select, update, usage on sequence pm_projects_id_seq to authenticated;

grant select, update, usage on sequence pm_projects_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on pm_projects to anon;

grant delete, insert, references, select, trigger, truncate, update on pm_projects to authenticated;

grant delete, insert, references, select, trigger, truncate, update on pm_projects to service_role;

create table reconciliations_match_scores
(
    reconciliation_id              uuid                                               not null
        references reconciliations (reconciliation_id)
            on delete cascade,
    confidence                     numeric,
    numerator                      numeric,
    total_weight                   numeric,
    date_match                     boolean,
    invoice_match                  boolean,
    order_match                    boolean,
    merchant_match                 boolean,
    amount_match                   boolean,
    currency_match                 boolean,
    date_weight                    numeric,
    invoice_weight                 numeric,
    order_weight                   numeric,
    merchant_weight                numeric,
    amount_weight                  numeric,
    currency_weight                numeric,
    date_score                     numeric,
    invoice_score                  numeric,
    order_score                    numeric,
    merchant_score                 numeric,
    amount_score                   numeric,
    currency_score                 numeric,
    created_at                     timestamp with time zone default now(),
    customer_match                 boolean,
    customer_weight                numeric,
    customer_score                 numeric,
    id                             bigint generated by default as identity
        primary key,
    reconciliations_match_score_id uuid                     default gen_random_uuid() not null
        unique,
    company_id                     uuid
        references companies (company_id)
);

alter table reconciliations_match_scores
    owner to postgres;

grant select, update, usage on sequence reconciliations_match_scores_id_seq to anon;

grant select, update, usage on sequence reconciliations_match_scores_id_seq to authenticated;

grant select, update, usage on sequence reconciliations_match_scores_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_match_scores to anon;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_match_scores to authenticated;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_match_scores to service_role;

create table reconciliations_weight_registry
(
    id                              bigint generated by default as identity
        constraint reconciliation_weight_registry_pkey
            primary key,
    company_id                      uuid,
    merchant_id                     text,
    weight_key                      text                                               not null
        constraint reconciliations_weight_registry_weight_key_check
            check (weight_key = ANY
                   (ARRAY ['date'::text, 'invoice_number'::text, 'order_number'::text, 'merchant_id'::text, 'amount_total'::text, 'currency'::text, 'customer_name'::text])),
    weight_value                    numeric                                            not null,
    active                          boolean                  default true              not null,
    created_at                      timestamp with time zone default now()             not null,
    reconciliations_weight_registry uuid                     default gen_random_uuid() not null
        constraint reconciliations_weight_regist_reconciliations_weight_regist_key
            unique,
    constraint reconciliation_weight_registr_company_id_merchant_id_weight_key
        unique (company_id, merchant_id, weight_key)
);

alter table reconciliations_weight_registry
    owner to postgres;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_weight_registry to anon;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_weight_registry to authenticated;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_weight_registry to service_role;

create table tax_id_registry
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default now() not null,
    country_code      country_code                           not null,
    name              text,
    name_localized    text,
    tax_id_descriptor text,
    description       text,
    example           text,
    regex             text,
    tax_id_ref_name   text,
    placeholder       text
);

alter table tax_id_registry
    owner to postgres;

grant select, update, usage on sequence tax_id_registry_id_seq to anon;

grant select, update, usage on sequence tax_id_registry_id_seq to authenticated;

grant select, update, usage on sequence tax_id_registry_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on tax_id_registry to anon;

grant delete, insert, references, select, trigger, truncate, update on tax_id_registry to authenticated;

grant delete, insert, references, select, trigger, truncate, update on tax_id_registry to service_role;

create table jortt_inbox
(
    id                      bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default now()             not null,
    jortt_inbox_id          uuid                     default gen_random_uuid() not null
        unique,
    suitsbooks_company_id   uuid
        references companies (company_id),
    conversation_data       json,
    entity_type             text,
    jort_organization_id    text,
    aggregate_id            text,
    sequence_number         numeric,
    description             text,
    source                  text,
    file_type               text,
    file_size               numeric,
    expense_id              text,
    file_signature          text,
    thumbnail_400_file_id   text,
    thumbnail_1200_file_id  text,
    thumbnail_2000_file_id  text,
    metadata                json,
    updated_at              timestamp,
    thumbnail_400_url       text,
    thumbnail_1200_url      text,
    original_url            text,
    full_count              text,
    search_record           json,
    receipt_value_record    json,
    note_records            json,
    expense_record          text,
    imported_and_normalized boolean                  default false,
    suitsbooks_document_id  uuid,
    suitsbooks_file_id      uuid,
    jortt_id                numeric
);

alter table jortt_inbox
    owner to postgres;

grant select, update, usage on sequence jortt_inbox_id_seq to anon;

grant select, update, usage on sequence jortt_inbox_id_seq to authenticated;

grant select, update, usage on sequence jortt_inbox_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on jortt_inbox to anon;

grant delete, insert, references, select, trigger, truncate, update on jortt_inbox to authenticated;

grant delete, insert, references, select, trigger, truncate, update on jortt_inbox to service_role;

create table jortt_credentials
(
    id                  bigint generated by default as identity
        primary key,
    created_at          timestamp with time zone default now()             not null,
    jortt_credential_id uuid                     default gen_random_uuid() not null
        unique,
    company_id          uuid
        references companies (company_id),
    x_csrf_token        text,
    jortt_session_token text,
    exp_at              numeric,
    inbox_api           boolean                  default false
);

alter table jortt_credentials
    owner to postgres;

grant select, update, usage on sequence jortt_credentials_id_seq to anon;

grant select, update, usage on sequence jortt_credentials_id_seq to authenticated;

grant select, update, usage on sequence jortt_credentials_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on jortt_credentials to anon;

grant delete, insert, references, select, trigger, truncate, update on jortt_credentials to authenticated;

grant delete, insert, references, select, trigger, truncate, update on jortt_credentials to service_role;

create table jortt_transactions
(
    id                           bigint generated by default as identity
        primary key,
    created_at                   timestamp with time zone default now()             not null,
    company_id                   uuid
        references companies (company_id),
    conversation_data            json,
    entity_type                  text,
    jort_tx_id                   numeric,
    jortt_transaction_id         uuid                     default gen_random_uuid() not null
        unique,
    aggregate_id                 text,
    sequence_number              numeric,
    bank_transaction_id          text,
    jortt_organization_id        text,
    bookable_id                  text,
    bank_account_iban            text,
    bank_account                 text,
    contra_account               text,
    contra_account_iban          text,
    contra_account_owner         text,
    amount                       numeric,
    description                  text,
    payment_type                 text,
    date                         text,
    bank                         text,
    skip_for_manual_matching     boolean                  default false,
    bank_account_id              text,
    ledger_account_id            text,
    match_info                   text,
    ignore_in_bookkeeping        boolean                  default false,
    provider_bank_transaction_id text,
    bank_data_provider           text,
    original_bank_transaction_id text,
    value_date                   text,
    bank_account_nickname        text,
    full_count                   text,
    due_amount                   numeric,
    amount_side                  text,
    href                         text
);

alter table jortt_transactions
    owner to postgres;

grant select, update, usage on sequence jortt_transactions_id_seq to anon;

grant select, update, usage on sequence jortt_transactions_id_seq to authenticated;

grant select, update, usage on sequence jortt_transactions_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on jortt_transactions to anon;

grant delete, insert, references, select, trigger, truncate, update on jortt_transactions to authenticated;

grant delete, insert, references, select, trigger, truncate, update on jortt_transactions to service_role;

create table admin_db_credentials
(
    id                     bigint generated by default as identity
        primary key,
    created_at             timestamp with time zone default now()             not null,
    admin_db_credential_id uuid                     default gen_random_uuid() not null
        unique,
    host                   text,
    connection_type        text                     default 'postgres'::text,
    password               text,
    default_db             text,
    ssl_enabled            boolean                  default false,
    "user"                 text,
    port                   numeric,
    name                   text,
    environment            text,
    backup_command         text,
    anon_key               text,
    service_key            text,
    public_url             text
);

alter table admin_db_credentials
    owner to postgres;

grant select, update, usage on sequence admin_db_credentials_id_seq to anon;

grant select, update, usage on sequence admin_db_credentials_id_seq to authenticated;

grant select, update, usage on sequence admin_db_credentials_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on admin_db_credentials to anon;

grant delete, insert, references, select, trigger, truncate, update on admin_db_credentials to authenticated;

grant delete, insert, references, select, trigger, truncate, update on admin_db_credentials to service_role;

create table ponto_logs
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default now()             not null,
    time          numeric,
    webhook_id    uuid                     default gen_random_uuid(),
    message       text,
    status        text,
    resource      text,
    error         text,
    http_code     text,
    path          text,
    route         text,
    user_id       text
        references users (user_id),
    account_id    uuid
        references ponto_account,
    ponto_log_id  uuid                     default gen_random_uuid() not null
        unique,
    level         text,
    file          text,
    action        text,
    api_code      text,
    refresh_token text
);

alter table ponto_logs
    owner to postgres;

grant select, update, usage on sequence ponto_logs_id_seq to anon;

grant select, update, usage on sequence ponto_logs_id_seq to authenticated;

grant select, update, usage on sequence ponto_logs_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on ponto_logs to anon;

grant delete, insert, references, select, trigger, truncate, update on ponto_logs to authenticated;

grant delete, insert, references, select, trigger, truncate, update on ponto_logs to service_role;

create table reconciliations_logs
(
    id                    bigint                   default nextval('reconciliations_log_id_seq'::regclass) not null
        constraint reconciliations_log_pkey
            primary key,
    reconciliation_log_id uuid                     default gen_random_uuid()                               not null,
    created_at            timestamp with time zone default now()                                           not null,
    run_id                uuid                                                                             not null,
    function_version      text                                                                             not null,
    action                text                                                                             not null,
    target                text,
    status                text                                                                             not null,
    message               text,
    company_id            uuid,
    transaction_id        uuid,
    document_id           uuid,
    reconciliation_id     uuid,
    rows_affected         integer,
    confidence            numeric,
    step_ms               bigint,
    processing_ms         bigint,
    context               jsonb
);

alter table reconciliations_logs
    owner to postgres;

create unique index reconciliations_log_reconciliations_log_id_idx
    on reconciliations_logs (reconciliation_log_id);

create index reconciliations_log_run_id_idx
    on reconciliations_logs (run_id);

create index reconciliations_log_created_at_idx
    on reconciliations_logs (created_at);

create index reconciliations_log_action_status_created_at_idx
    on reconciliations_logs (action, status, created_at);

create index reconciliations_log_company_id_transaction_id_idx
    on reconciliations_logs (company_id, transaction_id);

create index reconciliations_log_reconciliation_id_idx
    on reconciliations_logs (reconciliation_id);

create index reconciliations_log_document_id_idx
    on reconciliations_logs (document_id);

create index idx_reconlog_run_created
    on reconciliations_logs (run_id, created_at);

create index idx_reconlog_company
    on reconciliations_logs (company_id);

create index idx_reconlog_tx
    on reconciliations_logs (transaction_id);

create index idx_reconlog_doc
    on reconciliations_logs (document_id);

create index idx_reconlog_reconciliation
    on reconciliations_logs (reconciliation_id);

create index ix_reconlog_run_created
    on reconciliations_logs (run_id asc, created_at desc);

create index ix_reconlog_company_created
    on reconciliations_logs (company_id asc, created_at desc);

create index ix_reconlog_action_created
    on reconciliations_logs (action asc, created_at desc);

create index ix_reconlog_created
    on reconciliations_logs (created_at desc);

grant delete, insert, references, select, trigger, truncate, update on reconciliations_logs to anon;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_logs to authenticated;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_logs to service_role;

create table reconciliations_activity
(
    id             bigserial
        primary key,
    activity_id    uuid                     default gen_random_uuid() not null,
    created_at     timestamp with time zone default now()             not null,
    run_id         uuid                                               not null,
    company_id     uuid,
    transaction_id uuid,
    document_id    uuid,
    action         text                                               not null,
    reason         text,
    details        jsonb,
    time           numeric
);

alter table reconciliations_activity
    owner to postgres;

grant select, update, usage on sequence reconciliations_activity_id_seq to anon;

grant select, update, usage on sequence reconciliations_activity_id_seq to authenticated;

grant select, update, usage on sequence reconciliations_activity_id_seq to service_role;

create unique index ux_reconciliations_activity_activity_id
    on reconciliations_activity (activity_id);

create index ix_reconciliations_activity_run_id
    on reconciliations_activity (run_id);

create index ix_reconciliations_activity_tx
    on reconciliations_activity (transaction_id);

create index ix_reconciliations_activity_doc
    on reconciliations_activity (document_id);

create index ix_reconciliations_activity_company
    on reconciliations_activity (company_id);

create index ix_reconciliations_activity_action
    on reconciliations_activity (action);

grant delete, insert, references, select, trigger, truncate, update on reconciliations_activity to anon;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_activity to authenticated;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_activity to service_role;

create table nl_companies
(
    id                        bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default now(),
    kvk_number                bigint
        unique,
    name                      text,
    postal_code               text,
    active                    boolean,
    street                    text,
    area                      text,
    longitude                 double precision,
    latitude                  double precision,
    vat_id                    text,
    rsin                      text,
    establishment_number      bigint,
    rights_form               text,
    province                  text,
    municipality              text,
    standard_business_layout  text,
    rights_form_code          text,
    establishment             boolean,
    house_number              bigint,
    neighborhood              text,
    country                   text,
    activities                jsonb,
    city                      text,
    main_activity             text,
    main_activity_description text,
    main_sbi_code             bigint
);

alter table nl_companies
    owner to postgres;

grant select, update, usage on sequence nl_companies_id_seq to anon;

grant select, update, usage on sequence nl_companies_id_seq to authenticated;

grant select, update, usage on sequence nl_companies_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on nl_companies to anon;

grant delete, insert, references, select, trigger, truncate, update on nl_companies to authenticated;

grant delete, insert, references, select, trigger, truncate, update on nl_companies to service_role;

create table reconciliations_config
(
    id                       bigint generated by default as identity
        primary key,
    created_at               timestamp with time zone default now()         not null,
    reconciliation_config_id uuid                     default gen_random_uuid(),
    amount_tolerance         numeric,
    allow_doc_duplicates     boolean                  default false         not null,
    log_activity             boolean                  default false         not null,
    date_window_days         numeric                  default '1'::numeric  not null,
    min_confidence           numeric                  default 0.5           not null,
    use_pair_cache           boolean                  default false         not null,
    auto_reconcile           boolean                  default false         not null,
    auto_reconcile_min_pct   numeric                  default '90'::numeric not null
);

alter table reconciliations_config
    owner to postgres;

grant select, update, usage on sequence reconciliations_config_id_seq to anon;

grant select, update, usage on sequence reconciliations_config_id_seq to authenticated;

grant select, update, usage on sequence reconciliations_config_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_config to anon;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_config to authenticated;

grant delete, insert, references, select, trigger, truncate, update on reconciliations_config to service_role;

create table jortt_invoices
(
    id                                             bigint generated by default as identity
        primary key,
    created_at                                     timestamp with time zone default now()             not null,
    entity_type                                    text,
    jortt_invoice_id                               uuid                     default gen_random_uuid() not null
        unique,
    jortt_id                                       numeric
        unique,
    aggregate_id                                   text
        unique,
    jortt_organization_id                          text,
    sequence_number                                numeric,
    bookable_id                                    text,
    invoice_number                                 text,
    invoice_date                                   text,
    invoice_due_date                               text,
    invoice_currency                               text,
    invoice_total                                  numeric,
    invoice_total_incl_vat                         numeric,
    invoice_status                                 text,
    invoice_date_sent                              text,
    send_method                                    text,
    recipient_company_name                         text,
    recipient_attn                                 text,
    recipient_address_street                       text,
    recipient_address_city                         text,
    recipient_address_postal_code                  text,
    recipient_address_country_code                 text,
    recipient_address_country_name                 text,
    recipient_in_eu                                boolean                  default false,
    recipient_reference                            text,
    recipient_email_salutation                     text,
    creditor_company_name                          text,
    creditor_address_street                        text,
    creditor_address_city                          text,
    creditor_address_postal_code                   text,
    creditor_address_country_code                  text,
    creditor_address_country_name                  text,
    creditor_phonenumber                           text,
    creditor_coc_number                            text,
    creditor_vat_number                            text,
    creditor_bank_account_number                   text,
    creditor_bank_information_in_the_name_of       text,
    creditor_iban                                  text,
    creditor_vat_type                              text,
    creditor_bic                                   text,
    mail_data_from                                 text,
    mail_data_to                                   text,
    mail_data_cc_addresses                         json,
    mail_data_subject                              text,
    mail_data_body                                 text,
    attachment_ids                                 json,
    updated_at                                     timestamp with time zone,
    recipient_aggregate_id                         text,
    mail_data_bcc                                  text,
    invoice_reference                              text,
    logo_id                                        text,
    background_file_id                             text,
    invoice_delivery_period                        text,
    invoice_delivery_period_end                    text,
    creditor_company_name_line_2                   text,
    creditor_profession                            text,
    creditor_healthcare_data_bignummer             text,
    creditor_healthcare_data_agb_zorgverlenerscode text,
    creditor_healthcare_data_agb_praktijkcode      text,
    recipient_extra_information                    text,
    credited_invoice_id                            text,
    recipient_vat_shifted                          boolean                  default false,
    recipient_vat_number                           text,
    remarks                                        text,
    introduction                                   text,
    invoice_marked_free_of_vat                     boolean                  default false,
    language                                       text,
    net_amounts                                    boolean                  default false,
    credit_case_id                                 text,
    invoice_description                            text,
    is_periodic                                    boolean                  default false,
    periodic_invoice_id                            text,
    number_of_reminders_sent                       numeric                  default '0'::numeric,
    last_reminded_at                               timestamp with time zone,
    payment_method                                 text,
    payment_method_details                         text,
    tradename_id                                   text,
    labelable_id                                   text,
    creditor_website                               text,
    apply_eu_vat_july_2021_rule                    boolean                  default false,
    sold_via_platform                              boolean                  default false,
    recipient_is_private                           boolean                  default false,
    type                                           text,
    possible_actions                               json,
    view_status                                    text,
    show_invoice_status_text                       text,
    due_amount                                     numeric,
    href                                           text,
    payment_term                                   numeric,
    days_late                                      numeric,
    invoice_date_for_view                          text,
    get_recipient                                  json,
    url_to_download                                text,
    url_to_print                                   text,
    amount_side                                    text,
    ledger_account_side                            text,
    vat_country                                    text,
    violates_closed_year                           boolean                  default false,
    payment_details                                text,
    company_details                                text,
    footer                                         text,
    free_bottom_text                               text,
    send_every                                     text,
    missing_information                            text,
    has_invalid_vat_percentage                     text,
    payment_link                                   text,
    max_reference_length                           numeric,
    can_send                                       boolean                  default false,
    note_records                                   json,
    label_records                                  json,
    customer_record                                json,
    company_id                                     uuid
        references companies (company_id),
    importer_user_id                               text
        references users (user_id),
    customer_id                                    uuid
        references customers,
    promoted_to_native_invoice                     boolean                  default false,
    file_url                                       text,
    document_id                                    uuid
        references documents_v2 (document_id),
    invoice_id                                     uuid
        references invoices (invoice_id)
);

alter table jortt_invoices
    owner to postgres;

grant select, update, usage on sequence jortt_invoices_id_seq to anon;

grant select, update, usage on sequence jortt_invoices_id_seq to authenticated;

grant select, update, usage on sequence jortt_invoices_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on jortt_invoices to anon;

grant delete, insert, references, select, trigger, truncate, update on jortt_invoices to authenticated;

grant delete, insert, references, select, trigger, truncate, update on jortt_invoices to service_role;

create table reconciliation_activity
(
    id                bigint                   default nextval('reconciliations_activity_id_seq'::regclass) not null
        primary key,
    activity_id       uuid                     default gen_random_uuid()                                    not null,
    created_at        timestamp with time zone default now()                                                not null,
    run_id            uuid                                                                                  not null,
    company_id        uuid,
    transaction_id    uuid,
    document_id       uuid,
    action            text                                                                                  not null,
    reason            text,
    details           jsonb,
    time              numeric,
    reconciliation_id uuid                                                                                  not null
        unique
        references reconciliations (reconciliation_id)
            on delete cascade
);

comment on table reconciliation_activity is 'reconciliation_activity - for matched reconciliations';

alter table reconciliation_activity
    owner to postgres;

create unique index reconciliation_activity_activity_id_idx
    on reconciliation_activity (activity_id);

create index reconciliation_activity_run_id_idx
    on reconciliation_activity (run_id);

create index reconciliation_activity_transaction_id_idx
    on reconciliation_activity (transaction_id);

create index reconciliation_activity_document_id_idx
    on reconciliation_activity (document_id);

create index reconciliation_activity_company_id_idx
    on reconciliation_activity (company_id);

create index reconciliation_activity_action_idx
    on reconciliation_activity (action);

grant delete, insert, references, select, trigger, truncate, update on reconciliation_activity to anon;

grant delete, insert, references, select, trigger, truncate, update on reconciliation_activity to authenticated;

grant delete, insert, references, select, trigger, truncate, update on reconciliation_activity to service_role;

create table global_merchants_registry
(
    id                     bigint generated by default as identity
        primary key,
    created_at             timestamp with time zone default now() not null,
    name                   text                                   not null
        unique,
    icon                   text,
    merchant_id            uuid                     default gen_random_uuid()
        unique,
    email                  text,
    website                text,
    description            text,
    billing_postal_code    text,
    billing_address_line_1 text,
    billing_address_line_2 text,
    billing_city           text,
    billing_state          text,
    billing_province       text,
    vat_id                 text,
    company_number         text,
    company_number_type    text,
    phone_number           text,
    language               text,
    industry               text,
    slug                   text
        unique,
    enabled                boolean                  default true,
    public                 boolean                  default true,
    verified               boolean                  default false,
    country_code           text
);

alter table global_merchants_registry
    owner to postgres;

grant select, update, usage on sequence global_merchants_registry_id_seq to anon;

grant select, update, usage on sequence global_merchants_registry_id_seq to authenticated;

grant select, update, usage on sequence global_merchants_registry_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on global_merchants_registry to anon;

grant delete, insert, references, select, trigger, truncate, update on global_merchants_registry to authenticated;

grant delete, insert, references, select, trigger, truncate, update on global_merchants_registry to service_role;

create table merchant_ibans
(
    id               bigint generated by default as identity
        primary key,
    created_at       timestamp with time zone default now()             not null,
    merchant_id      uuid,
    iban             text
        unique,
    country_code     text,
    bank             text,
    description      text,
    bic              text,
    merchant_iban_id uuid                     default gen_random_uuid() not null
        unique,
    slug             text,
    account_holder   text
);

alter table merchant_ibans
    owner to postgres;

grant select, update, usage on sequence merchant_ibans_id_seq to anon;

grant select, update, usage on sequence merchant_ibans_id_seq to authenticated;

grant select, update, usage on sequence merchant_ibans_id_seq to service_role;

create index merchant_ibans_merchant_id_idx
    on merchant_ibans (merchant_id);

grant delete, insert, references, select, trigger, truncate, update on merchant_ibans to anon;

grant delete, insert, references, select, trigger, truncate, update on merchant_ibans to authenticated;

grant delete, insert, references, select, trigger, truncate, update on merchant_ibans to service_role;

create table microsoft_graph_onedrive_files
(
    id                               bigint generated always as identity
        primary key,
    created_at                       timestamp with time zone default now()             not null,
    microsoft_graph_onedrive_file_id uuid                     default gen_random_uuid() not null
        constraint microsoft_graph_onedrive_file_microsoft_graph_onedrive_file_key
            unique,
    microsoft_drive_item_id          text                                               not null
        unique,
    name                             text,
    size                             numeric,
    is_folder                        boolean                  default false,
    mime_type                        text,
    web_url                          text,
    created_time                     numeric,
    last_modified_time               numeric,
    parent_reference                 json,
    file                             json,
    folder                           json,
    file_system_info                 json,
    created_by                       json,
    last_modified_by                 json,
    drive_item_raw                   json,
    company_id                       uuid
        references companies (company_id)
);

alter table microsoft_graph_onedrive_files
    owner to postgres;

grant select, update, usage on sequence microsoft_graph_onedrive_files_id_seq to anon;

grant select, update, usage on sequence microsoft_graph_onedrive_files_id_seq to authenticated;

grant select, update, usage on sequence microsoft_graph_onedrive_files_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on microsoft_graph_onedrive_files to anon;

grant delete, insert, references, select, trigger, truncate, update on microsoft_graph_onedrive_files to authenticated;

grant delete, insert, references, select, trigger, truncate, update on microsoft_graph_onedrive_files to service_role;

create table microsoft_graph_inbox_rules
(
    id                            bigint generated always as identity
        primary key,
    created_at                    timestamp with time zone default now() not null,
    microsoft_rule_id             text                                   not null
        unique,
    microsoft_graph_inbox_rule_id uuid                     default gen_random_uuid(),
    display_name                  text,
    sequence                      numeric,
    is_enabled                    boolean,
    has_error                     boolean,
    conditions                    json,
    actions                       json,
    exceptions                    json,
    is_read_only                  boolean,
    company_id                    uuid
        references companies (company_id)
);

alter table microsoft_graph_inbox_rules
    owner to postgres;

grant select, update, usage on sequence microsoft_graph_inbox_rules_id_seq to anon;

grant select, update, usage on sequence microsoft_graph_inbox_rules_id_seq to authenticated;

grant select, update, usage on sequence microsoft_graph_inbox_rules_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on microsoft_graph_inbox_rules to anon;

grant delete, insert, references, select, trigger, truncate, update on microsoft_graph_inbox_rules to authenticated;

grant delete, insert, references, select, trigger, truncate, update on microsoft_graph_inbox_rules to service_role;

create table microsoft_groups
(
    id                               bigint generated always as identity
        primary key,
    created_at                       timestamp with time zone default now() not null,
    name                             text,
    company_id                       uuid
        references companies (company_id),
    microsoft_id                     text,
    microsoft_group_id               uuid                     default gen_random_uuid(),
    description                      text,
    membership_rule                  text,
    membership_rule_processing_state text,
    renewed_at                       numeric,
    security_identifier              text,
    creation_options                 json,
    group_types                      text,
    mail                             text,
    mail_nickname                    text,
    proxy_addresses                  json,
    resource_behavior_options        json,
    resource_provisioning_options    json,
    visibility                       text,
    security_enabled                 boolean                  default false
);

alter table microsoft_groups
    owner to postgres;

grant select, update, usage on sequence microsoft_groups_id_seq to anon;

grant select, update, usage on sequence microsoft_groups_id_seq to authenticated;

grant select, update, usage on sequence microsoft_groups_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on microsoft_groups to anon;

grant delete, insert, references, select, trigger, truncate, update on microsoft_groups to authenticated;

grant delete, insert, references, select, trigger, truncate, update on microsoft_groups to service_role;

create table microsoft_graph_calendars
(
    id                          bigint generated always as identity
        primary key,
    created_at                  timestamp with time zone default now() not null,
    company_id                  uuid
        references companies (company_id),
    microsoft_user_id           text,
    microsoft_id                text                                   not null
        unique,
    microsoft_graph_calendar_id uuid                     default gen_random_uuid(),
    name                        text,
    color                       text,
    hex_color                   text,
    is_default                  boolean                  default false,
    can_share                   boolean                  default false,
    can_view_private_items      boolean                  default false,
    can_edit                    boolean                  default false,
    owner                       json,
    raw                         json
);

alter table microsoft_graph_calendars
    owner to postgres;

grant select, update, usage on sequence microsoft_graph_calendars_id_seq to anon;

grant select, update, usage on sequence microsoft_graph_calendars_id_seq to authenticated;

grant select, update, usage on sequence microsoft_graph_calendars_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on microsoft_graph_calendars to anon;

grant delete, insert, references, select, trigger, truncate, update on microsoft_graph_calendars to authenticated;

grant delete, insert, references, select, trigger, truncate, update on microsoft_graph_calendars to service_role;

create table stargate_ponto_webhook_events
(
    id                              bigint generated by default as identity
        primary key,
    created_at                      timestamp with time zone default now()                                                          not null,
    time                            bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    event_id                        uuid,
    event_type                      text,
    organization_id                 uuid,
    account_id                      uuid,
    synchronization_id              uuid,
    payment_request_id              uuid,
    event_created_at                timestamp with time zone,
    synchronization_subtype         text,
    signature                       text,
    headers                         jsonb,
    payload                         jsonb,
    stargate_ponto_webhook_event_id uuid                     default gen_random_uuid()                                              not null
        constraint stargate_ponto_webhook_events_stargate_ponto_webhook_event__key
            unique
);

alter table stargate_ponto_webhook_events
    owner to postgres;

grant select, update, usage on sequence stargate_ponto_webhook_events_id_seq to anon;

grant select, update, usage on sequence stargate_ponto_webhook_events_id_seq to authenticated;

grant select, update, usage on sequence stargate_ponto_webhook_events_id_seq to service_role;

create index ponto_webhook_events_event_id_idx
    on stargate_ponto_webhook_events (event_id);

create index ponto_webhook_events_event_type_idx
    on stargate_ponto_webhook_events (event_type);

create index ponto_webhook_events_org_id_idx
    on stargate_ponto_webhook_events (organization_id);

create index ponto_webhook_events_account_id_idx
    on stargate_ponto_webhook_events (account_id);

create index ponto_webhook_events_sync_id_idx
    on stargate_ponto_webhook_events (synchronization_id);

create index ponto_webhook_events_time_idx
    on stargate_ponto_webhook_events (time);

create trigger ponto_webhook_events_audit_trg
    before insert or update or delete
    on stargate_ponto_webhook_events
    for each row
execute procedure stargate_audit_row_change();

create trigger trg_handle_account_revocation
    after insert
    on stargate_ponto_webhook_events
    for each row
execute procedure handle_account_revocation();

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_webhook_events to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_webhook_events to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_webhook_events to service_role;

create table stargate_ponto_consents
(
    id                        bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default now()                                                          not null,
    time                      bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    ponto_consent_id          uuid                                                                                            not null,
    status                    text,
    expires_at                timestamp with time zone,
    raw                       jsonb,
    stargate_ponto_consent_id uuid                     default gen_random_uuid()
);

alter table stargate_ponto_consents
    owner to postgres;

grant select, update, usage on sequence stargate_ponto_consents_id_seq to anon;

grant select, update, usage on sequence stargate_ponto_consents_id_seq to authenticated;

grant select, update, usage on sequence stargate_ponto_consents_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_consents to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_consents to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_consents to service_role;

create table stargate_ponto_tokens
(
    id                      bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default now()                                                          not null,
    time                    bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    state                   text                                                                                            not null,
    access_token            text                                                                                            not null
        unique,
    refresh_token           text,
    scope                   text,
    token_type              text,
    expires_in              integer,
    raw                     jsonb,
    stargate_ponto_token_id uuid                     default gen_random_uuid()                                              not null
        unique,
    account_id              uuid,
    sub                     text
);

alter table stargate_ponto_tokens
    owner to postgres;

grant select, update, usage on sequence stargate_ponto_tokens_id_seq to anon;

grant select, update, usage on sequence stargate_ponto_tokens_id_seq to authenticated;

grant select, update, usage on sequence stargate_ponto_tokens_id_seq to service_role;

create index ponto_tokens_time_idx
    on stargate_ponto_tokens (time);

create index ponto_tokens_state_idx
    on stargate_ponto_tokens (state);

create index ponto_tokens_refresh_idx
    on stargate_ponto_tokens (refresh_token);

create index ponto_tokens_account_idx
    on stargate_ponto_tokens (account_id);

create index ponto_tokens_account_time_idx
    on stargate_ponto_tokens (account_id asc, time desc);

create trigger ponto_tokens_audit_trg
    before insert or update or delete
    on stargate_ponto_tokens
    for each row
execute procedure stargate_audit_row_change();

create trigger stargate_ponto_tokens_protect_tokens_trg
    before update
    on stargate_ponto_tokens
    for each row
execute procedure stargate_ponto_tokens_protect_tokens();

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_tokens to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_tokens to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_tokens to service_role;

create table stargate_logs
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default now()                                                          not null,
    time            bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    level           text                                                                                            not null,
    message         text,
    http            boolean                  default false                                                          not null,
    method          text,
    route           text,
    path            text,
    status          integer,
    code            text,
    duration_ms     integer,
    ip              text,
    meta            jsonb,
    stargate_log_id uuid                     default gen_random_uuid()                                              not null
        unique,
    http_version    text,
    user_agent      text,
    referer         text,
    host            text,
    response_size   numeric,
    req_headers     jsonb,
    res_headers     jsonb,
    query           jsonb,
    req_body        text,
    res_body        text
);

alter table stargate_logs
    owner to postgres;

grant select, update, usage on sequence stargate_logs_id_seq to anon;

grant select, update, usage on sequence stargate_logs_id_seq to authenticated;

grant select, update, usage on sequence stargate_logs_id_seq to service_role;

create index stargate_logs_time_idx
    on stargate_logs (time);

create index stargate_logs_level_idx
    on stargate_logs (level);

create index stargate_logs_http_idx
    on stargate_logs (http);

create index stargate_logs_status_idx
    on stargate_logs (status);

create trigger logs_audit_trg
    before insert or update or delete
    on stargate_logs
    for each row
execute procedure stargate_audit_row_change();

grant delete, insert, references, select, trigger, truncate, update on stargate_logs to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_logs to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_logs to service_role;

create table stargate_api_codes
(
    id          bigint generated by default as identity
        primary key,
    created_at  timestamp with time zone default now() not null,
    code        text                                   not null
        unique,
    http_status integer,
    description text,
    remediation text,
    meta        jsonb
);

alter table stargate_api_codes
    owner to postgres;

grant select, update, usage on sequence stargate_api_codes_id_seq to anon;

grant select, update, usage on sequence stargate_api_codes_id_seq to authenticated;

grant select, update, usage on sequence stargate_api_codes_id_seq to service_role;

create index stargate_api_codes_code_idx
    on stargate_api_codes (code);

grant delete, insert, references, select, trigger, truncate, update on stargate_api_codes to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_api_codes to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_api_codes to service_role;

create table stargate_ponto_transactions
(
    id                                bigint generated by default as identity
        primary key,
    created_at                        timestamp with time zone default now()                                                          not null,
    time                              bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    ponto_transaction_id              uuid                                                                                            not null
        unique,
    ponto_account_id                  uuid                                                                                            not null,
    amount                            numeric(18, 2),
    fee                               numeric(18, 2),
    currency                          text,
    description                       text,
    digest                            text,
    additional_information            text,
    bank_transaction_code             text,
    card_reference                    text,
    card_reference_type               text,
    counterpart_name                  text,
    counterpart_reference             text,
    creditor_id                       text,
    end_to_end_id                     text,
    execution_date                    timestamp with time zone,
    mandate_id                        text,
    proprietary_bank_transaction_code text,
    purpose_code                      text,
    remittance_information            text,
    remittance_information_type       text,
    value_date                        timestamp with time zone,
    internal_reference                text,
    remote_created_at                 timestamp with time zone,
    remote_updated_at                 timestamp with time zone,
    raw                               jsonb,
    promoted_to_transaction           boolean                  default false,
    transaction_id                    uuid
        references transactions,
    company_id                        uuid
);

alter table stargate_ponto_transactions
    owner to postgres;

grant select, update, usage on sequence stargate_ponto_transactions_id_seq to anon;

grant select, update, usage on sequence stargate_ponto_transactions_id_seq to authenticated;

grant select, update, usage on sequence stargate_ponto_transactions_id_seq to service_role;

create index ponto_transactions_tx_id_idx
    on stargate_ponto_transactions (ponto_transaction_id);

create index ponto_transactions_account_id_idx
    on stargate_ponto_transactions (ponto_account_id);

create index ponto_transactions_time_idx
    on stargate_ponto_transactions (time);

create trigger ponto_transactions_audit_trg
    before insert or update or delete
    on stargate_ponto_transactions
    for each row
execute procedure stargate_audit_row_change();

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_transactions to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_transactions to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_transactions to service_role;

create table stargate_ponto_accounts
(
    id                                      bigint generated by default as identity
        primary key,
    created_at                              timestamp with time zone default now()                                                          not null,
    time                                    bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    ponto_account_id                        uuid                                                                                            not null
        unique,
    company_id                              uuid
        references companies (company_id)
        constraint stargate_ponto_accounts_company_id_not_null
            check (company_id IS NOT NULL),
    deprecated                              boolean,
    description                             text,
    product                                 text,
    reference                               text,
    currency                                text,
    subtype                                 text,
    available_balance                       numeric(18, 2),
    available_balance_changed_at            timestamp with time zone,
    available_balance_reference_date        timestamp with time zone,
    current_balance                         numeric(18, 2),
    current_balance_changed_at              timestamp with time zone,
    current_balance_reference_date          timestamp with time zone,
    holder_name                             text,
    reference_type                          text,
    available_balance_variation_observed_at timestamp with time zone,
    current_balance_variation_observed_at   timestamp with time zone,
    authorization_expiration_expected_at    timestamp with time zone,
    authorized_at                           timestamp with time zone,
    internal_reference                      text
        unique,
    institution_id                          uuid,
    raw                                     jsonb,
    promoted_to_bank_account                boolean                  default false,
    bank_account_id                         uuid
        references banking_accounts (banking_account_id),
    financial_institution_id                uuid,
    financial_institution_name              text,
    financial_institution_avatar            text,
    awaiting_revocation                     boolean                  default false
);

alter table stargate_ponto_accounts
    owner to postgres;

grant select, update, usage on sequence stargate_ponto_accounts_id_seq to anon;

grant select, update, usage on sequence stargate_ponto_accounts_id_seq to authenticated;

grant select, update, usage on sequence stargate_ponto_accounts_id_seq to service_role;

create index ponto_accounts_time_idx
    on stargate_ponto_accounts (time);

create index ponto_accounts_company_id_idx
    on stargate_ponto_accounts (company_id);

create trigger ponto_accounts_audit_trg
    before insert or update or delete
    on stargate_ponto_accounts
    for each row
execute procedure stargate_audit_row_change();

create trigger stargate_ponto_accounts_company_id_guard
    before insert or update
    on stargate_ponto_accounts
    for each row
execute procedure stargate_ponto_accounts_company_id_guard();

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_accounts to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_accounts to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_accounts to service_role;

create table stargate_ponto_financial_institutions
(
    id                              uuid                     default gen_random_uuid() not null
        primary key,
    name                            text,
    status                          text,
    deprecated                      boolean,
    country                         text,
    bic                             text,
    bulk_payments_enabled           boolean,
    bulk_payments_product_types     text[],
    future_dated_payments_allowed   boolean,
    logo_url                        text,
    maintenance_from                text,
    maintenance_to                  text,
    maintenance_type                text,
    payments_enabled                boolean,
    payments_product_types          text[],
    periodic_payments_enabled       boolean,
    periodic_payments_product_types text[],
    primary_color                   text,
    secondary_color                 text,
    shared_brand_name               text,
    shared_brand_reference          text,
    time_zone                       text,
    created_at                      timestamp with time zone default (now() AT TIME ZONE 'utc'::text)
);

comment on column stargate_ponto_financial_institutions.name is 'Name of the financial institution';

comment on column stargate_ponto_financial_institutions.status is 'Availability of the connection (experimental, beta, stable)';

comment on column stargate_ponto_financial_institutions.deprecated is 'Indicates if the financial institution has been deprecated. Very rarely we may need to deprecate a &lt;a href&#x3D;&#39;https://documentation.ibanity.com//api#financial-institution&#39;&gt;financial institution&lt;/a&gt; and ask your users to authorize their accounts again on its replacement. You will be able to access both accounts (if authorized) but you will not be able to synchronize the deprecated account once its authorization has expired.';

comment on column stargate_ponto_financial_institutions.country is 'Country of the financial institution, in &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2&#39;&gt;ISO 3166-1 alpha-2&lt;/a&gt; format. Is &lt;code&gt;null&lt;/code&gt; in the case of an international financial institution.';

comment on column stargate_ponto_financial_institutions.bic is 'Identifier for the financial institution, in &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_9362&#39;&gt;ISO9362&lt;/a&gt; format.';

comment on column stargate_ponto_financial_institutions.bulk_payments_enabled is 'Indicates whether the financial institution allows bulk payment initiation requests. Original param name - bulkPaymentsEnabled.';

comment on column stargate_ponto_financial_institutions.bulk_payments_product_types is 'Identifies which values are accepted for the bulk payment initiation request &lt;code&gt;productType&lt;/code&gt;. Original param name - bulkPaymentsProductTypes.';

comment on column stargate_ponto_financial_institutions.future_dated_payments_allowed is 'Indicates whether a &lt;code&gt;requestedExecutionDate&lt;/code&gt; is supported for &lt;a href&#x3D;&#39;https://documentation.ibanity.com//api#payment&#39;&gt;payments&lt;/a&gt; from accounts belonging to this financial institution. Original param name - futureDatedPaymentsAllowed.';

comment on column stargate_ponto_financial_institutions.logo_url is 'Location of the logo image for the financial institution. Original param name - logoUrl.';

comment on column stargate_ponto_financial_institutions.maintenance_from is 'Indicates the start date of the maintenance.. Original param name - maintenanceFrom.';

comment on column stargate_ponto_financial_institutions.maintenance_to is 'Indicates the end date of the maintenance.. Original param name - maintenanceTo.';

comment on column stargate_ponto_financial_institutions.maintenance_type is 'Indicates if there is an ongoing or scheduled maintenance. If present, the possible values are:&lt;ul&gt;&lt;li&gt;&lt;code&gt;internal&lt;/code&gt;, meaning we are working on the connection and no data access is possible&lt;/li&gt;&lt;li&gt;&lt;code&gt;financialInstitution&lt;/code&gt;, indicating the financial institution cannot be reached, but existing data is available in read-only mode&lt;/li&gt;&lt;/ul&gt;. Original param name - maintenanceType.';

comment on column stargate_ponto_financial_institutions.payments_enabled is 'Indicates whether the financial institution allows &lt;a href&#x3D;&#39;https://documentation.ibanity.com//api#payment-initiation-request&#39;&gt;payment initiation requests&lt;/a&gt;. Original param name - paymentsEnabled.';

comment on column stargate_ponto_financial_institutions.payments_product_types is 'Identifies which values are accepted for the &lt;a href&#x3D;&#39;https://documentation.ibanity.com//api#payment-initiation-request&#39;&gt;payment initiation request&lt;/a&gt; &lt;code&gt;productType&lt;/code&gt;. Original param name - paymentsProductTypes.';

comment on column stargate_ponto_financial_institutions.periodic_payments_enabled is 'Indicates whether the financial institution allows periodic payment initiation requests. Original param name - periodicPaymentsEnabled.';

comment on column stargate_ponto_financial_institutions.periodic_payments_product_types is 'Identifies which values are accepted for the periodic payment initiation request &lt;code&gt;productType&lt;/code&gt;. Original param name - periodicPaymentsProductTypes.';

comment on column stargate_ponto_financial_institutions.primary_color is 'Hexadecimal color code related to the primary branding color of the financial institution. Original param name - primaryColor.';

comment on column stargate_ponto_financial_institutions.secondary_color is 'Hexadecimal color code related to the secondary branding color of the financial institution. Original param name - secondaryColor.';

comment on column stargate_ponto_financial_institutions.shared_brand_name is 'Customer-friendly name of the financial institution&#39;s shared brand, if it is a member of one. Original param name - sharedBrandName.';

comment on column stargate_ponto_financial_institutions.shared_brand_reference is 'Attribute used to group multiple individual financial institutions in the same country. Original param name - sharedBrandReference.';

comment on column stargate_ponto_financial_institutions.time_zone is 'Indicates in which time zone the financial institution is located. Eg: &lt;code&gt;Europe/Paris&lt;/code&gt;. This field may be empty (null) if the financial institution is located in multiple countries with different time zones. Original param name - timeZone.';

alter table stargate_ponto_financial_institutions
    owner to postgres;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_financial_institutions to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_financial_institutions to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_financial_institutions to service_role;

create table stargate_ponto_auth_errors
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default now()                                                          not null,
    time              bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    state             text,
    error             text,
    error_description text,
    headers           jsonb,
    query             jsonb
);

alter table stargate_ponto_auth_errors
    owner to postgres;

grant select, update, usage on sequence stargate_ponto_auth_errors_id_seq to anon;

grant select, update, usage on sequence stargate_ponto_auth_errors_id_seq to authenticated;

grant select, update, usage on sequence stargate_ponto_auth_errors_id_seq to service_role;

create index ponto_auth_errors_time_idx
    on stargate_ponto_auth_errors (time);

create index ponto_auth_errors_state_idx
    on stargate_ponto_auth_errors (state);

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_auth_errors to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_auth_errors to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_auth_errors to service_role;

create table stargate_audit_log
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()                                                          not null,
    time                  bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    schema_name           text                                                                                            not null,
    table_name            text                                                                                            not null,
    operation             text                                                                                            not null,
    actor                 text,
    row_old               jsonb,
    row_new               jsonb,
    stargate_audit_log_id uuid                     default gen_random_uuid()                                              not null
        unique,
    diff                  jsonb
);

alter table stargate_audit_log
    owner to postgres;

grant select, update, usage on sequence stargate_audit_log_id_seq to anon;

grant select, update, usage on sequence stargate_audit_log_id_seq to authenticated;

grant select, update, usage on sequence stargate_audit_log_id_seq to service_role;

create index stargate_audit_time_idx
    on stargate_audit_log (time);

create index stargate_audit_table_op_idx
    on stargate_audit_log (table_name, operation);

grant delete, insert, references, select, trigger, truncate, update on stargate_audit_log to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_audit_log to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_audit_log to service_role;

create table stargate_ponto_states
(
    id                      bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default now()             not null,
    stargate_ponto_state_id uuid                     default gen_random_uuid() not null
        unique,
    company_id              uuid                     default gen_random_uuid()
        references companies (company_id),
    user_id                 text
        references users (user_id),
    state_serialized        text,
    state_hashed            text                                               not null
        unique,
    hash_algorithm          text                     default 'base64'::text,
    time                    numeric                                            not null
);

alter table stargate_ponto_states
    owner to postgres;

grant select, update, usage on sequence stargate_ponto_states_id_seq to anon;

grant select, update, usage on sequence stargate_ponto_states_id_seq to authenticated;

grant select, update, usage on sequence stargate_ponto_states_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_states to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_states to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_states to service_role;

create table gl_audit_log
(
    id         bigserial
        primary key,
    audit_id   uuid                     default gen_random_uuid() not null
        unique,
    table_name text                                               not null,
    record_id  uuid                                               not null,
    action     text                                               not null,
    changed_by text,
    old_data   jsonb,
    new_data   jsonb,
    changed_at timestamp with time zone default now()             not null
);

alter table gl_audit_log
    owner to postgres;

grant select, update, usage on sequence gl_audit_log_id_seq to anon;

grant select, update, usage on sequence gl_audit_log_id_seq to authenticated;

grant select, update, usage on sequence gl_audit_log_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on gl_audit_log to anon;

grant delete, insert, references, select, trigger, truncate, update on gl_audit_log to authenticated;

grant delete, insert, references, select, trigger, truncate, update on gl_audit_log to service_role;

create table gl_log
(
    id               bigserial
        primary key,
    log_id           uuid                     default gen_random_uuid() not null
        unique,
    company_id       uuid                                               not null,
    transaction_id   uuid,
    journal_entry_id uuid,
    action           text                                               not null,
    details          jsonb,
    created_at       timestamp with time zone default now()             not null
);

alter table gl_log
    owner to postgres;

grant select, update, usage on sequence gl_log_id_seq to anon;

grant select, update, usage on sequence gl_log_id_seq to authenticated;

grant select, update, usage on sequence gl_log_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on gl_log to anon;

grant delete, insert, references, select, trigger, truncate, update on gl_log to authenticated;

grant delete, insert, references, select, trigger, truncate, update on gl_log to service_role;

create table coa_providers
(
    id              bigserial
        primary key,
    coa_provider_id uuid                     default gen_random_uuid() not null
        unique,
    provider_code   text                                               not null,
    provider_name   text                                               not null,
    version         text                                               not null,
    country_code    char(2)                                            not null,
    description     text,
    released_at     date,
    deprecated      boolean                  default false             not null,
    created_at      timestamp with time zone default now()             not null,
    unique (provider_code, version, country_code)
);

alter table coa_providers
    owner to postgres;

grant select, update, usage on sequence coa_providers_id_seq to anon;

grant select, update, usage on sequence coa_providers_id_seq to authenticated;

grant select, update, usage on sequence coa_providers_id_seq to service_role;

create table gl_account_templates
(
    id              bigserial
        primary key,
    template_id     uuid                     default gen_random_uuid() not null
        unique,
    country_code    char(2)                  default 'NL'::bpchar      not null,
    coa_provider    text                     default 'RGS'::text       not null,
    coa_version     text                     default '3.7'::text       not null,
    code            varchar(20)                                        not null,
    name            text                                               not null,
    category        text                                               not null,
    is_postable     boolean                  default true              not null,
    created_at      timestamp with time zone default now()             not null,
    coa_provider_id uuid
        references coa_providers (coa_provider_id)
            on delete cascade,
    number          numeric,
    credit_or_debit text,
    constraint gl_account_templates_country_code_coa_provider_coa_version__key
        unique (country_code, coa_provider, coa_version, code)
);

alter table gl_account_templates
    owner to postgres;

grant select, update, usage on sequence gl_account_templates_id_seq to anon;

grant select, update, usage on sequence gl_account_templates_id_seq to authenticated;

grant select, update, usage on sequence gl_account_templates_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on gl_account_templates to anon;

grant delete, insert, references, select, trigger, truncate, update on gl_account_templates to authenticated;

grant delete, insert, references, select, trigger, truncate, update on gl_account_templates to service_role;

create table company_gl_accounts
(
    id                    bigserial
        primary key,
    company_gl_account_id uuid                     default gen_random_uuid() not null
        unique,
    company_id            uuid                                               not null
        references companies (company_id)
            on delete cascade,
    template_id           uuid                                               not null
        references gl_account_templates (template_id)
            on delete cascade,
    alias_name            text,
    is_active             boolean                  default true              not null,
    is_ar                 boolean                  default false             not null,
    is_revenue            boolean                  default false             not null,
    is_vat_payable        boolean                  default false             not null,
    is_ap                 boolean                  default false             not null,
    is_expense            boolean                  default false             not null,
    is_vat_receivable     boolean                  default false             not null,
    created_at            timestamp with time zone default now()             not null,
    unique (company_id, template_id)
);

alter table company_gl_accounts
    owner to postgres;

grant select, update, usage on sequence company_gl_accounts_id_seq to anon;

grant select, update, usage on sequence company_gl_accounts_id_seq to authenticated;

grant select, update, usage on sequence company_gl_accounts_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on company_gl_accounts to anon;

grant delete, insert, references, select, trigger, truncate, update on company_gl_accounts to authenticated;

grant delete, insert, references, select, trigger, truncate, update on company_gl_accounts to service_role;

grant delete, insert, references, select, trigger, truncate, update on coa_providers to anon;

grant delete, insert, references, select, trigger, truncate, update on coa_providers to authenticated;

grant delete, insert, references, select, trigger, truncate, update on coa_providers to service_role;

create table company_coa_profiles
(
    id                     bigserial
        primary key,
    company_coa_profile_id uuid                     default gen_random_uuid() not null
        unique,
    company_id             uuid                                               not null
        references companies (company_id)
            on delete cascade,
    coa_provider_id        uuid                                               not null
        references coa_providers (coa_provider_id)
            on delete cascade,
    profile_name           text                                               not null,
    is_active              boolean                  default true              not null,
    created_at             timestamp with time zone default now()             not null,
    constraint company_coa_profiles_company_id_coa_provider_id_profile_nam_key
        unique (company_id, coa_provider_id, profile_name)
);

alter table company_coa_profiles
    owner to postgres;

grant select, update, usage on sequence company_coa_profiles_id_seq to anon;

grant select, update, usage on sequence company_coa_profiles_id_seq to authenticated;

grant select, update, usage on sequence company_coa_profiles_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on company_coa_profiles to anon;

grant delete, insert, references, select, trigger, truncate, update on company_coa_profiles to authenticated;

grant delete, insert, references, select, trigger, truncate, update on company_coa_profiles to service_role;

create table journal_entries
(
    id                     bigserial
        primary key,
    journal_entry_id       uuid                     default gen_random_uuid() not null
        unique,
    company_id             uuid                                               not null
        references companies (company_id)
            on delete cascade,
    company_coa_profile_id uuid                                               not null
        references company_coa_profiles (company_coa_profile_id)
            on delete cascade,
    transaction_id         uuid
                                                                              references transactions
                                                                                  on delete set null,
    entry_date             date                     default CURRENT_DATE      not null,
    description            text,
    contact_id             uuid
                                                                              references contacts (contact_id)
                                                                                  on delete set null,
    vat_code               text,
    created_at             timestamp with time zone default now()             not null,
    constraint journal_entries_unique_per_invoice
        unique (company_id, transaction_id)
);

alter table journal_entries
    owner to postgres;

grant select, update, usage on sequence journal_entries_id_seq to anon;

grant select, update, usage on sequence journal_entries_id_seq to authenticated;

grant select, update, usage on sequence journal_entries_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on journal_entries to anon;

grant delete, insert, references, select, trigger, truncate, update on journal_entries to authenticated;

grant delete, insert, references, select, trigger, truncate, update on journal_entries to service_role;

create table stargate_ponto_token_usage
(
    id                 bigint generated by default as identity
        primary key,
    created_at         timestamp with time zone default now()                                                          not null,
    time               bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    correlation_id     text,
    method             text,
    url                text,
    path               text,
    ponto_operation    text,
    account_id         uuid,
    status_code        integer,
    duration_ms        integer,
    request_headers    jsonb,
    request_body       jsonb,
    response_body      jsonb,
    error              text,
    access_token_hash  text,
    refresh_token_hash text,
    used_access_token  boolean,
    used_refresh_token boolean,
    access_expires_at  bigint,
    refresh_expires_at bigint,
    state              text,
    sub                text
);

alter table stargate_ponto_token_usage
    owner to postgres;

grant select, update, usage on sequence stargate_ponto_token_usage_id_seq to anon;

grant select, update, usage on sequence stargate_ponto_token_usage_id_seq to authenticated;

grant select, update, usage on sequence stargate_ponto_token_usage_id_seq to service_role;

create index ponto_token_usage_time_idx
    on stargate_ponto_token_usage (time);

create index ponto_token_usage_account_idx
    on stargate_ponto_token_usage (account_id);

create index ponto_token_usage_correlation_idx
    on stargate_ponto_token_usage (correlation_id);

create index ponto_token_usage_access_hash_idx
    on stargate_ponto_token_usage (access_token_hash);

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_token_usage to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_token_usage to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ponto_token_usage to service_role;

create table stargate_jobs
(
    id                         bigint generated by default as identity
        primary key,
    created_at                 timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    subscription_id            uuid,
    status                     text                     default 'pending'::text,
    progress                   numeric                  default '0'::numeric,
    started_at                 timestamp with time zone,
    updated_at                 numeric                  default '0'::numeric,
    eta                        numeric                  default '0'::numeric,
    resource_reference_pointer text,
    finished                   boolean                  default false,
    repeat                     boolean                  default false,
    scheduled_time             timestamp with time zone,
    stargate_job_id            uuid                     default gen_random_uuid()                not null
        constraint stargate_job_id_key
            unique,
    progress_percent           numeric                  default '0'::numeric,
    progress_resource          numeric                  default '0'::numeric,
    progress_resource_total    numeric                  default '0'::numeric,
    company_id                 uuid
        constraint jobs_company_id_fkey
            references companies (company_id),
    requester_user_id          text,
    description                text,
    time_spent_seconds         numeric                  default '0'::numeric,
    invoice_id                 uuid,
    name                       text                     default 'null'::text,
    status_message             text,
    resource_id                text,
    resource_type              text,
    cronspec                   text,
    method                     text,
    headers                    json                     default '{"Content-Type":"application/json"}'::json,
    body                       json,
    url                        text,
    system                     boolean                  default false,
    job_type_id                text,
    max_retry_count            bigint,
    job_fail_count             bigint                   default '0'::bigint                      not null,
    timeout_minutes            numeric                  default '15'::numeric
);

alter table stargate_jobs
    owner to postgres;

grant select, update, usage on sequence stargate_jobs_id_seq to anon;

grant select, update, usage on sequence stargate_jobs_id_seq to authenticated;

grant select, update, usage on sequence stargate_jobs_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on stargate_jobs to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_jobs to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_jobs to service_role;

create table stargate_job_activity
(
    id                      bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    stargate_job_id         uuid                                                              not null,
    status                  text,
    message                 text,
    progress                numeric,
    progress_percent        numeric,
    progress_resource       numeric,
    progress_resource_total numeric,
    extra                   jsonb
);

alter table stargate_job_activity
    owner to postgres;

grant select, update, usage on sequence stargate_job_activity_id_seq to anon;

grant select, update, usage on sequence stargate_job_activity_id_seq to authenticated;

grant select, update, usage on sequence stargate_job_activity_id_seq to service_role;

create index stargate_job_activity_job_id_idx
    on stargate_job_activity (stargate_job_id);

grant delete, insert, references, select, trigger, truncate, update on stargate_job_activity to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_job_activity to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_job_activity to service_role;

create table stargate_mollie_states
(
    id                       bigint generated by default as identity
        primary key,
    created_at               timestamp with time zone default now()             not null,
    stargate_mollie_state_id uuid                     default gen_random_uuid() not null
        unique,
    company_id               uuid
        references companies (company_id),
    user_id                  text
        references users (user_id),
    state_serialized         text,
    state_hashed             text                                               not null
        unique,
    hash_algorithm           text                     default 'base64'::text,
    time                     numeric                                            not null
);

alter table stargate_mollie_states
    owner to postgres;

grant select, update, usage on sequence stargate_mollie_states_id_seq to anon;

grant select, update, usage on sequence stargate_mollie_states_id_seq to authenticated;

grant select, update, usage on sequence stargate_mollie_states_id_seq to service_role;

create trigger stargate_mollie_states_audit_trg
    after insert or update or delete
    on stargate_mollie_states
    for each row
execute procedure stargate_audit_row_change();

grant delete, insert, references, select, trigger, truncate, update on stargate_mollie_states to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_mollie_states to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_mollie_states to service_role;

create table booking_categories
(
    id                  bigint generated by default as identity
        primary key,
    booking_category_id uuid                     default gen_random_uuid() not null
        unique,
    company_id          uuid                                               not null
        references companies (company_id)
            on delete cascade,
    title               text                                               not null,
    description         text,
    translation_key     text,
    code                varchar(50),
    gl_account          varchar(50),
    country_code        char(2)                  default 'NL'::bpchar      not null,
    subcategory_of      uuid
                                                                           references booking_categories (booking_category_id)
                                                                               on delete set null,
    category_type       text                     default 'expense'::text   not null,
    status              text,
    created_by          text,
    applicable_for      text[],
    created_at          timestamp with time zone default now()             not null,
    updated_at          timestamp with time zone default now()             not null,
    constraint booking_categories_unique_per_company
        unique (company_id, title)
);

alter table booking_categories
    owner to postgres;

grant select, update, usage on sequence booking_categories_id_seq to anon;

grant select, update, usage on sequence booking_categories_id_seq to authenticated;

grant select, update, usage on sequence booking_categories_id_seq to service_role;

create index idx_booking_categories_company_id
    on booking_categories (company_id);

create index idx_booking_categories_subcategory_of
    on booking_categories (subcategory_of);

create index idx_booking_categories_category_type
    on booking_categories (category_type);

grant delete, insert, references, select, trigger, truncate, update on booking_categories to anon;

grant delete, insert, references, select, trigger, truncate, update on booking_categories to authenticated;

grant delete, insert, references, select, trigger, truncate, update on booking_categories to service_role;

create table bookings
(
    id                  bigint generated by default as identity
        primary key,
    booking_id          uuid                     default gen_random_uuid() not null
        unique,
    company_id          uuid                                               not null
        references companies (company_id)
            on delete cascade,
    transaction_id      uuid
                                                                           references transactions
                                                                               on delete set null,
    document_id         uuid
                                                                           references documents_v2 (document_id)
                                                                               on delete set null,
    reconciliation_id   uuid
                                                                           references reconciliations (reconciliation_id)
                                                                               on delete set null,
    gl_account_id       uuid                                               not null,
    booking_category_id uuid
                                                                           references booking_categories (booking_category_id)
                                                                               on delete set null,
    debit               numeric                  default 0                 not null,
    credit              numeric                  default 0                 not null,
    currency            text                     default 'EUR'::text       not null,
    exchange_rate       numeric,
    amount              numeric generated always as ((debit - credit)) stored,
    description         text,
    memo                text,
    booked_at           timestamp with time zone default now()             not null,
    fiscal_year         numeric,
    quarter             numeric,
    month               text,
    created_at          timestamp with time zone default now()             not null,
    updated_at          timestamp with time zone default now()             not null,
    processed_by        text                     default 'manual'::text,
    approved_by_user_id text
        references users (user_id),
    approved            boolean                  default false,
    vat_amount          numeric                  default '0'::numeric
);

alter table bookings
    owner to postgres;

grant select, update, usage on sequence bookings_id_seq to anon;

grant select, update, usage on sequence bookings_id_seq to authenticated;

grant select, update, usage on sequence bookings_id_seq to service_role;

create index idx_bookings_company_id
    on bookings (company_id);

create index idx_bookings_transaction_id
    on bookings (transaction_id);

create index idx_bookings_document_id
    on bookings (document_id);

create index idx_bookings_reconciliation_id
    on bookings (reconciliation_id);

create index idx_bookings_gl_account_id
    on bookings (gl_account_id);

grant delete, insert, references, select, trigger, truncate, update on bookings to anon;

grant delete, insert, references, select, trigger, truncate, update on bookings to authenticated;

grant delete, insert, references, select, trigger, truncate, update on bookings to service_role;

create table ifza_business_activities
(
    id                        bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default now() not null,
    ifza_business_activity_id uuid                     default gen_random_uuid(),
    code                      numeric                                not null
        unique,
    name                      text,
    description               text,
    type                      text,
    classification            text,
    regulation_type           text,
    approving_entity_1        text,
    approving_entity_2        text
);

alter table ifza_business_activities
    owner to postgres;

grant select, update, usage on sequence ifza_business_activities_id_seq to anon;

grant select, update, usage on sequence ifza_business_activities_id_seq to authenticated;

grant select, update, usage on sequence ifza_business_activities_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on ifza_business_activities to anon;

grant delete, insert, references, select, trigger, truncate, update on ifza_business_activities to authenticated;

grant delete, insert, references, select, trigger, truncate, update on ifza_business_activities to service_role;

create table sf_formation_tickets
(
    id                                        bigint generated by default as identity
        primary key,
    created_at                                timestamp with time zone default now()             not null,
    sf_formation_ticket_id                    uuid                     default gen_random_uuid() not null
        unique,
    user_id                                   text
        references users (user_id),
    state                                     text,
    entity_type                               text                     default 'dutch_bv'::text,
    status                                    text                     default 'pending'::text,
    updated_at                                numeric,
    number_of_shareholders                    numeric                  default '1'::numeric,
    shareholder_information                   json,
    primary_first_name                        text,
    primary_surname                           text,
    primary_date_of_birth                     text,
    primary_email                             text,
    primary_percentage_of_shares              numeric                  default '0'::numeric,
    bv_name                                   text,
    will_bv_sell_products_or_provide_services text                     default 'products'::text,
    which_sector_will_bv_be_active            text                     default 'holding_activities-administration-and-management'::text,
    currency                                  text                     default 'EUR'::text,
    purchase_management_and_holding           boolean                  default false,
    price_management_and_holding              numeric                  default '95'::numeric,
    purchase_online_entrepreneur              boolean                  default false,
    price_online_entrepreneur                 numeric                  default '145'::numeric,
    purchase_business_complete                boolean                  default false,
    price_business_complete                   numeric                  default '195'::numeric,
    purchase_essential_contracts              boolean                  default false,
    price_essential_contracts                 numeric                  default '99'::numeric,
    paid                                      boolean                  default false,
    paid_at                                   numeric,
    billing_email                             text,
    payment_ref_id                            text
        unique,
    time                                      numeric,
    primary_middle_name                       text,
    primary_salutation                        text                     default 'Mr'::text,
    residential_address                       json,
    residential_house_or_building_number      text,
    residential_region_or_state               text,
    residential_state                         text,
    residential_country_code                  text,
    residential_city                          text,
    primary_phone_number                      numeric,
    primary_phone_number_ext                  text,
    first_preferred_company_name              text,
    second_preferred_company_name             text,
    third_preferred_company_name              text,
    state_of_incorporation                    text,
    company_us_phone_number                   numeric,
    description_business_nature               text,
    intended_business_activities              text,
    intended_products_or_services             text,
    file_url_passport                         text,
    file_url_residential_address              text,
    aurora_preprocessed_data                  json,
    aurora_confidence                         numeric                  default '0'::numeric,
    residential_postal_code                   text,
    ubo_shareholder_percentage_shares         numeric                  default '0'::numeric,
    aurora_check_pass_identity                boolean                  default false,
    aurora_check_pass_utility_bill            boolean                  default false,
    aurora_response_json                      json,
    licence_type                              text,
    trade_licencse_validity_years             numeric,
    wants_to_apply_for_establishment_card     boolean                  default false,
    financial_year_start_date                 text,
    financial_year_end_date                   text,
    proposed_share_capital                    numeric,
    share_value                               numeric,
    total_number_of_shares                    numeric
);

alter table sf_formation_tickets
    owner to postgres;

grant select, update, usage on sequence sf_formation_tickets_id_seq to anon;

grant select, update, usage on sequence sf_formation_tickets_id_seq to authenticated;

grant select, update, usage on sequence sf_formation_tickets_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on sf_formation_tickets to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formation_tickets to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formation_tickets to service_role;

create table receipt_data
(
    id              bigserial
        primary key,
    company_name    text,
    processed_at    timestamp with time zone default now() not null,
    source          text                                   not null,
    user_id         bigint,
    channel_id      text,
    dates           jsonb                    default '[]'::jsonb,
    times           jsonb                    default '[]'::jsonb,
    websites        jsonb                    default '[]'::jsonb,
    emails          jsonb                    default '[]'::jsonb,
    items           jsonb                    default '[]'::jsonb,
    currencies      jsonb                    default '[]'::jsonb,
    tax_vat         jsonb                    default '[]'::jsonb,
    subtotal        jsonb,
    total           jsonb,
    created_at      timestamp with time zone default now() not null,
    receipt_date_id uuid                     default gen_random_uuid(),
    company_id      uuid
        references companies (company_id)
);

alter table receipt_data
    owner to postgres;

grant select, update, usage on sequence receipt_data_id_seq to anon;

grant select, update, usage on sequence receipt_data_id_seq to authenticated;

grant select, update, usage on sequence receipt_data_id_seq to service_role;

create index idx_receipt_data_company_name
    on receipt_data (company_name);

create index idx_receipt_data_source
    on receipt_data (source);

create index idx_receipt_data_processed_at
    on receipt_data (processed_at);

create index idx_receipt_data_user_id
    on receipt_data (user_id);

grant delete, insert, references, select, trigger, truncate, update on receipt_data to anon;

grant delete, insert, references, select, trigger, truncate, update on receipt_data to authenticated;

grant delete, insert, references, select, trigger, truncate, update on receipt_data to service_role;

create table test
(
    id         bigint generated by default as identity
        primary key,
    created_at timestamp with time zone default now() not null,
    email      text,
    number     numeric,
    dog        text,
    dog4       text,
    dog3       text,
    dog2       text,
    dog1       text
);

alter table test
    owner to postgres;

grant select, update, usage on sequence test_id_seq to anon;

grant select, update, usage on sequence test_id_seq to authenticated;

grant select, update, usage on sequence test_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on test to anon;

grant delete, insert, references, select, trigger, truncate, update on test to authenticated;

grant delete, insert, references, select, trigger, truncate, update on test to service_role;

create table ro_companies
(
    id             bigint generated by default as identity
        primary key,
    created_at     timestamp with time zone default now() not null,
    entity_type    text,
    company_number numeric
        unique,
    name           text,
    address        text,
    state          text,
    updated_at     numeric
);

alter table ro_companies
    owner to postgres;

grant select, update, usage on sequence ro_companies_id_seq to anon;

grant select, update, usage on sequence ro_companies_id_seq to authenticated;

grant select, update, usage on sequence ro_companies_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on ro_companies to anon;

grant delete, insert, references, select, trigger, truncate, update on ro_companies to authenticated;

grant delete, insert, references, select, trigger, truncate, update on ro_companies to service_role;

create table gl_rules
(
    id                        bigserial
        primary key,
    gl_rule_id                uuid                     default gen_random_uuid() not null
        unique,
    company_id                uuid                                               not null
        references companies (company_id)
            on delete cascade,
    company_coa_profile_id    uuid                                               not null
        references company_coa_profiles (company_coa_profile_id)
            on delete cascade,
    priority                  integer                  default 100               not null,
    condition_json            jsonb                                              not null,
    debit_company_gl_account  uuid                                               not null
        references company_gl_accounts (company_gl_account_id)
            on delete restrict,
    credit_company_gl_account uuid                                               not null
        references company_gl_accounts (company_gl_account_id)
            on delete restrict,
    contact_id                uuid
                                                                                 references contacts (contact_id)
                                                                                     on delete set null,
    vat_code                  text,
    active                    boolean                  default true              not null,
    created_at                timestamp with time zone default now()             not null,
    vat_account_debit         uuid
        references company_gl_accounts (company_gl_account_id),
    vat_account_credit        uuid
        references company_gl_accounts (company_gl_account_id),
    ar_account                uuid
        references company_gl_accounts (company_gl_account_id),
    revenue_account           uuid
        references company_gl_accounts (company_gl_account_id),
    vat_payable_account       uuid
        references company_gl_accounts (company_gl_account_id),
    constraint gl_rules_unique_per_profile
        unique (company_coa_profile_id, priority, condition_json)
);

alter table gl_rules
    owner to postgres;

grant select, update, usage on sequence gl_rules_id_seq to anon;

grant select, update, usage on sequence gl_rules_id_seq to authenticated;

grant select, update, usage on sequence gl_rules_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on gl_rules to anon;

grant delete, insert, references, select, trigger, truncate, update on gl_rules to authenticated;

grant delete, insert, references, select, trigger, truncate, update on gl_rules to service_role;

create table journal_lines
(
    id                     bigserial
        primary key,
    journal_line_id        uuid                     default gen_random_uuid() not null
        unique,
    journal_entry_id       uuid                                               not null
        references journal_entries (journal_entry_id)
            on delete cascade,
    company_coa_profile_id uuid                                               not null
        references company_coa_profiles (company_coa_profile_id)
            on delete cascade,
    company_gl_account_id  uuid                                               not null
        references company_gl_accounts (company_gl_account_id)
            on delete restrict,
    debit                  numeric                  default 0                 not null,
    credit                 numeric                  default 0                 not null,
    created_at             timestamp with time zone default now()             not null
);

alter table journal_lines
    owner to postgres;

grant select, update, usage on sequence journal_lines_id_seq to anon;

grant select, update, usage on sequence journal_lines_id_seq to authenticated;

grant select, update, usage on sequence journal_lines_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on journal_lines to anon;

grant delete, insert, references, select, trigger, truncate, update on journal_lines to authenticated;

grant delete, insert, references, select, trigger, truncate, update on journal_lines to service_role;

create table stargate_mollie_webhook_events
(
    id                               bigint generated by default as identity
        primary key,
    created_at                       timestamp with time zone default now()             not null,
    stargate_mollie_webhook_event_id uuid                     default gen_random_uuid() not null
        constraint stargate_mollie_webhook_event_stargate_mollie_webhook_event_key
            unique
        constraint stargate_mollie_webhook_events_mollie_event_uuid_key
            unique,
    host                             text,
    mollie_webhook_id                text,
    secret                           text,
    headers                          json,
    body                             json,
    mollie_signature                 text,
    time                             numeric,
    event_type                       text,
    resource                         text,
    entity_id                        text,
    event_created_at                 timestamp with time zone,
    embedded_entity_id               text,
    embedded_entity_resource         text,
    embedded_entity_href             text,
    self_href                        text,
    documentation_href               text,
    entity_href                      text,
    mode                             text,
    mollie_profile_id                text,
    amount_currency                  text,
    amount_value                     numeric(20, 4),
    paid_at                          timestamp with time zone,
    webhook_url                      text,
    sequence_type                    text
);

alter table stargate_mollie_webhook_events
    owner to postgres;

grant select, update, usage on sequence stargate_mollie_webhook_events_id_seq to anon;

grant select, update, usage on sequence stargate_mollie_webhook_events_id_seq to authenticated;

grant select, update, usage on sequence stargate_mollie_webhook_events_id_seq to service_role;

create index idx_stargate_mollie_webhook_events_time
    on stargate_mollie_webhook_events (time);

create index idx_stargate_mollie_webhook_events_event_type
    on stargate_mollie_webhook_events (event_type);

create index idx_stargate_mollie_webhook_events_webhook_id
    on stargate_mollie_webhook_events (mollie_webhook_id);

grant delete, insert, references, select, trigger, truncate, update on stargate_mollie_webhook_events to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_mollie_webhook_events to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_mollie_webhook_events to service_role;

create table vat_codes
(
    vat_code    text    not null
        primary key,
    rate        numeric not null,
    description text
);

alter table vat_codes
    owner to postgres;

grant delete, insert, references, select, trigger, truncate, update on vat_codes to anon;

grant delete, insert, references, select, trigger, truncate, update on vat_codes to authenticated;

grant delete, insert, references, select, trigger, truncate, update on vat_codes to service_role;

create table vat_rates
(
    id                     bigserial
        primary key,
    country_code           char(2)               not null,
    vat_code               text                  not null,
    rate                   numeric               not null,
    reverse_charge         boolean default false not null,
    vat_payable_account    uuid
        references company_gl_accounts (company_gl_account_id),
    vat_receivable_account uuid
        references company_gl_accounts (company_gl_account_id)
);

alter table vat_rates
    owner to postgres;

grant select, update, usage on sequence vat_rates_id_seq to anon;

grant select, update, usage on sequence vat_rates_id_seq to authenticated;

grant select, update, usage on sequence vat_rates_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on vat_rates to anon;

grant delete, insert, references, select, trigger, truncate, update on vat_rates to authenticated;

grant delete, insert, references, select, trigger, truncate, update on vat_rates to service_role;

create table stargate_microsoft_graph_tokens
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default now()                                                          not null,
    time          bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    tenant_id     text,
    user_id       text,
    state         text,
    access_token  text                                                                                            not null,
    refresh_token text,
    scope         text,
    token_type    text,
    expires_in    integer,
    raw           jsonb
);

alter table stargate_microsoft_graph_tokens
    owner to postgres;

grant select, update, usage on sequence stargate_microsoft_graph_tokens_id_seq to anon;

grant select, update, usage on sequence stargate_microsoft_graph_tokens_id_seq to authenticated;

grant select, update, usage on sequence stargate_microsoft_graph_tokens_id_seq to service_role;

create index ms_graph_tokens_time_idx
    on stargate_microsoft_graph_tokens (time);

create index ms_graph_tokens_tenant_idx
    on stargate_microsoft_graph_tokens (tenant_id);

create index ms_graph_tokens_user_idx
    on stargate_microsoft_graph_tokens (user_id);

create index ms_graph_tokens_refresh_idx
    on stargate_microsoft_graph_tokens (refresh_token);

create index ms_graph_tokens_state_idx
    on stargate_microsoft_graph_tokens (state);

create trigger stargate_microsoft_graph_tokens_protect_tokens_trg
    before update
    on stargate_microsoft_graph_tokens
    for each row
execute procedure stargate_microsoft_graph_tokens_protect_tokens();

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_tokens to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_tokens to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_tokens to service_role;

create table stargate_linear_webhook_events
(
    id                      bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default now()                                                          not null,
    time                    bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    linear_webhook_event_id uuid                     default gen_random_uuid(),
    host                    text,
    signature               text,
    secret                  text,
    delivery_id             text,
    headers                 jsonb,
    payload                 jsonb,
    event                   text,
    entity_type             text,
    entity_id               text
);

alter table stargate_linear_webhook_events
    owner to postgres;

grant select, update, usage on sequence stargate_linear_webhook_events_id_seq to anon;

grant select, update, usage on sequence stargate_linear_webhook_events_id_seq to authenticated;

grant select, update, usage on sequence stargate_linear_webhook_events_id_seq to service_role;

create index linear_webhook_events_time_idx
    on stargate_linear_webhook_events (time);

create index linear_webhook_events_event_idx
    on stargate_linear_webhook_events (event);

create index linear_webhook_events_entity_idx
    on stargate_linear_webhook_events (entity_type, entity_id);

grant delete, insert, references, select, trigger, truncate, update on stargate_linear_webhook_events to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_linear_webhook_events to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_linear_webhook_events to service_role;

create table integrations
(
    id                            bigint generated by default as identity
        primary key,
    created_at                    timestamp with time zone default now()             not null,
    integration_id                uuid                     default gen_random_uuid() not null
        unique,
    integration_provider          text,
    reference_account_id          text,
    reference_account_type        text,
    reference_account_table       text,
    company_id                    uuid
        references companies (company_id),
    connected_at                  numeric,
    status                        text                     default 'pending'::text,
    active                        boolean                  default false,
    integration_type_id           uuid                     default gen_random_uuid(),
    last_sync_at                  numeric                  default 0,
    connected_by_user             text
        references users (user_id),
    revoked                       boolean                  default false,
    label                         text,
    locale                        text,
    access_token                  text,
    refresh_token                 text,
    description                   text,
    integration_bundle_identifier text
        references integration_registry (integration_bundle_identifier),
    token_type                    text,
    scope                         text
);

alter table integrations
    owner to postgres;

grant select, update, usage on sequence integrations_id_seq to anon;

grant select, update, usage on sequence integrations_id_seq to authenticated;

grant select, update, usage on sequence integrations_id_seq to service_role;

create index integrations_provider_idx
    on integrations (integration_provider);

create index integrations_company_idx
    on integrations (company_id);

grant delete, insert, references, select, trigger, truncate, update on integrations to anon;

grant delete, insert, references, select, trigger, truncate, update on integrations to authenticated;

grant delete, insert, references, select, trigger, truncate, update on integrations to service_role;

create table stargate_microsoft_graph_microsoft_teams_channel_messages
(
    id                     bigint generated by default as identity
        primary key,
    created_at             timestamp with time zone default now()                                                          not null,
    time                   bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    tenant_id              text,
    team_id                text                                                                                            not null,
    channel_id             text                                                                                            not null,
    message_id             text                                                                                            not null,
    reply_to_id            text,
    message_type           text,
    created_datetime       timestamp with time zone,
    last_modified_datetime timestamp with time zone,
    deleted_datetime       timestamp with time zone,
    subject                text,
    summary                text,
    importance             text,
    locale                 text,
    web_url                text,
    from_user_id           text,
    from_user_display_name text,
    body_content_type      text,
    body_content           text,
    raw                    jsonb,
    constraint stargate_microsoft_graph_micr_team_id_channel_id_message_id_key
        unique (team_id, channel_id, message_id)
);

alter table stargate_microsoft_graph_microsoft_teams_channel_messages
    owner to postgres;

create index ms_graph_channel_messages_team_channel_idx
    on stargate_microsoft_graph_microsoft_teams_channel_messages (team_id, channel_id);

create index ms_graph_channel_messages_time_idx
    on stargate_microsoft_graph_microsoft_teams_channel_messages (time);

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_microsoft_teams_channel_messages to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_microsoft_teams_channel_messages to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_microsoft_teams_channel_messages to service_role;

create table stargate_microsoft_graph_microsoft_teams_channels
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default now()                                                          not null,
    time            bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    tenant_id       text,
    team_id         text                                                                                            not null,
    channel_id      text                                                                                            not null,
    display_name    text,
    description     text,
    email           text,
    membership_type text,
    is_archived     boolean,
    web_url         text,
    raw             jsonb,
    constraint stargate_microsoft_graph_microsoft_teams_team_id_channel_id_key
        unique (team_id, channel_id)
);

alter table stargate_microsoft_graph_microsoft_teams_channels
    owner to postgres;

grant select, update, usage on sequence stargate_microsoft_graph_microsoft_teams_channels_id_seq to anon;

grant select, update, usage on sequence stargate_microsoft_graph_microsoft_teams_channels_id_seq to authenticated;

grant select, update, usage on sequence stargate_microsoft_graph_microsoft_teams_channels_id_seq to service_role;

create index ms_graph_channels_time_idx
    on stargate_microsoft_graph_microsoft_teams_channels (time);

create index ms_graph_channels_team_idx
    on stargate_microsoft_graph_microsoft_teams_channels (team_id);

create index ms_graph_channels_tenant_idx
    on stargate_microsoft_graph_microsoft_teams_channels (tenant_id);

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_microsoft_teams_channels to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_microsoft_teams_channels to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_microsoft_teams_channels to service_role;

create table stargate_microsoft_graph_teams
(
    id           bigint generated by default as identity
        primary key,
    created_at   timestamp with time zone default now()                                                          not null,
    time         bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    tenant_id    text,
    team_id      text                                                                                            not null
        unique,
    display_name text,
    description  text,
    web_url      text,
    is_archived  boolean,
    visibility   text,
    raw          jsonb
);

alter table stargate_microsoft_graph_teams
    owner to postgres;

grant select, update, usage on sequence stargate_microsoft_graph_teams_id_seq to anon;

grant select, update, usage on sequence stargate_microsoft_graph_teams_id_seq to authenticated;

grant select, update, usage on sequence stargate_microsoft_graph_teams_id_seq to service_role;

create index ms_graph_teams_time_idx
    on stargate_microsoft_graph_teams (time);

create index ms_graph_teams_tenant_idx
    on stargate_microsoft_graph_teams (tenant_id);

create index ms_graph_teams_display_name_idx
    on stargate_microsoft_graph_teams (display_name);

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_teams to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_teams to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_microsoft_graph_teams to service_role;

create table stargate_linear_webhooks
(
    id         bigint generated by default as identity
        primary key,
    created_at timestamp with time zone default now()                                                          not null,
    time       bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    webhook_id uuid                     default gen_random_uuid(),
    team_id    text,
    url        text,
    secret     text,
    active     boolean,
    headers    jsonb,
    raw        jsonb
);

alter table stargate_linear_webhooks
    owner to postgres;

grant select, update, usage on sequence stargate_linear_webhooks_id_seq to anon;

grant select, update, usage on sequence stargate_linear_webhooks_id_seq to authenticated;

grant select, update, usage on sequence stargate_linear_webhooks_id_seq to service_role;

create index linear_webhooks_time_idx
    on stargate_linear_webhooks (time);

create index linear_webhooks_team_idx
    on stargate_linear_webhooks (team_id);

grant delete, insert, references, select, trigger, truncate, update on stargate_linear_webhooks to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_linear_webhooks to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_linear_webhooks to service_role;

create table stargate_mollie_payment_links
(
    id                     bigint generated by default as identity
        primary key,
    created_at             timestamp with time zone default now()                                                          not null,
    time                   bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    mollie_account_id      uuid,
    mollie_payment_link_id uuid                     default gen_random_uuid()                                              not null,
    label                  text,
    description            text,
    url                    text,
    status                 text                     default 'pending'::text,
    allowed_methods        json,
    amount_value           text,
    amount_currency        text,
    archived               boolean                  default false,
    expires_at             text,
    payment_link_id        text,
    mode                   text,
    paid_at                numeric,
    profile_id             text,
    redirect_url           text,
    resource               text                     default 'payment-link'::text,
    reusable               boolean                  default false,
    sequence_type          text                     default 'oneoff'::text,
    webhook_url            text,
    payment_link           text,
    self_link              text,
    invoice_id             uuid,
    link_payment           text,
    link_self              text,
    company_id             uuid
        references companies (company_id)
);

alter table stargate_mollie_payment_links
    owner to postgres;

grant select, update, usage on sequence stargate_mollie_payment_links_id_seq to anon;

grant select, update, usage on sequence stargate_mollie_payment_links_id_seq to authenticated;

grant select, update, usage on sequence stargate_mollie_payment_links_id_seq to service_role;

create unique index stargate_mollie_payment_links_mollie_payment_link_id_key
    on stargate_mollie_payment_links (mollie_payment_link_id);

create unique index stargate_mollie_payment_links_payment_link_id_key
    on stargate_mollie_payment_links (payment_link_id);

create index idx_stargate_mollie_payment_links_invoice
    on stargate_mollie_payment_links (invoice_id);

grant delete, insert, references, select, trigger, truncate, update on stargate_mollie_payment_links to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_mollie_payment_links to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_mollie_payment_links to service_role;

create table stargate_linear_oauth2_app
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default now() not null,
    client_secret text
);

alter table stargate_linear_oauth2_app
    owner to postgres;

grant select, update, usage on sequence stargate_linear_oauth2_app_id_seq to anon;

grant select, update, usage on sequence stargate_linear_oauth2_app_id_seq to authenticated;

grant select, update, usage on sequence stargate_linear_oauth2_app_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on stargate_linear_oauth2_app to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_linear_oauth2_app to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_linear_oauth2_app to service_role;

create table stargate_ozura_pay_tokens
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()                                                          not null,
    time                  bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    token                 text                                                                                            not null,
    expires               text,
    refresh_token         text,
    refresh_token_expires text,
    user_identifier       text,
    user_email            text,
    group_member_id       text,
    iso_id                text,
    raw                   jsonb
);

alter table stargate_ozura_pay_tokens
    owner to postgres;

grant select, update, usage on sequence stargate_ozura_pay_tokens_id_seq to anon;

grant select, update, usage on sequence stargate_ozura_pay_tokens_id_seq to authenticated;

grant select, update, usage on sequence stargate_ozura_pay_tokens_id_seq to service_role;

create index stargate_ozura_pay_tokens_time_idx
    on stargate_ozura_pay_tokens (time);

create index stargate_ozura_pay_tokens_user_identifier_idx
    on stargate_ozura_pay_tokens (user_identifier);

create index stargate_ozura_pay_tokens_user_email_idx
    on stargate_ozura_pay_tokens (user_email);

create trigger stargate_ozura_pay_tokens_protect_tokens_trg
    before update
    on stargate_ozura_pay_tokens
    for each row
execute procedure stargate_ozura_pay_tokens_protect_tokens();

grant delete, insert, references, select, trigger, truncate, update on stargate_ozura_pay_tokens to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ozura_pay_tokens to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ozura_pay_tokens to service_role;

create table stargate_ozura_pay_login_errors
(
    id         bigint generated by default as identity
        primary key,
    created_at timestamp with time zone default now()                                                          not null,
    time       bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    email      text,
    status     integer,
    message    text,
    headers    jsonb,
    body       jsonb
);

alter table stargate_ozura_pay_login_errors
    owner to postgres;

grant select, update, usage on sequence stargate_ozura_pay_login_errors_id_seq to anon;

grant select, update, usage on sequence stargate_ozura_pay_login_errors_id_seq to authenticated;

grant select, update, usage on sequence stargate_ozura_pay_login_errors_id_seq to service_role;

create index stargate_ozura_pay_login_errors_time_idx
    on stargate_ozura_pay_login_errors (time);

create index stargate_ozura_pay_login_errors_email_idx
    on stargate_ozura_pay_login_errors (email);

grant delete, insert, references, select, trigger, truncate, update on stargate_ozura_pay_login_errors to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_ozura_pay_login_errors to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_ozura_pay_login_errors to service_role;

create table credit_notes
(
    id                        bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default now()             not null,
    credit_note_id            uuid                     default gen_random_uuid() not null
        unique,
    credit_note_number        numeric,
    company_id                uuid
        references companies (company_id),
    time                      numeric,
    total                     numeric,
    currency                  text,
    country_code              text,
    country_code_counterparty text,
    credited_by_user          text
        references users (user_id),
    credits_invoice_id        uuid
        references invoices (invoice_id),
    credit_note_descriptor    text,
    customer_id               uuid
        references customers,
    status                    text,
    subtotal                  numeric,
    total_credited            numeric,
    credited                  boolean                  default false,
    ref_identifier            text,
    ref_provider              text
);

alter table credit_notes
    owner to postgres;

grant select, update, usage on sequence credit_notes_id_seq to anon;

grant select, update, usage on sequence credit_notes_id_seq to authenticated;

grant select, update, usage on sequence credit_notes_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on credit_notes to anon;

grant delete, insert, references, select, trigger, truncate, update on credit_notes to authenticated;

grant delete, insert, references, select, trigger, truncate, update on credit_notes to service_role;

create table resource_routes
(
    id                                   bigint generated by default as identity
        primary key,
    created_at                           timestamp with time zone default now() not null,
    "table"                              text,
    id_column                            text,
    enable_search                        boolean                  default false,
    columns                              json,
    search_by                            text,
    company_id_column                    text,
    disable_company_filter               boolean                  default false,
    enable_new_resource_creation         boolean                  default false,
    new_resource_button_text             text,
    new_resource_href                    text,
    force_wrapping_header_labels         boolean                  default false,
    enable_edit                          boolean                  default false,
    allowed_columns_edit                 json,
    denied_columns_edit                  json,
    scope                                text,
    ignore_company_check_before_mutation boolean                  default false,
    row_actions                          json
);

alter table resource_routes
    owner to postgres;

grant select, update, usage on sequence resource_routes_id_seq to anon;

grant select, update, usage on sequence resource_routes_id_seq to authenticated;

grant select, update, usage on sequence resource_routes_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on resource_routes to anon;

grant delete, insert, references, select, trigger, truncate, update on resource_routes to authenticated;

grant delete, insert, references, select, trigger, truncate, update on resource_routes to service_role;

create table user_preferences
(
    id                 bigint generated by default as identity
        primary key,
    user_preference_id uuid                     default gen_random_uuid() not null,
    table_name         text                                               not null,
    settings           jsonb                    default '{}'::jsonb       not null,
    created_at         timestamp with time zone default now()             not null,
    updated_at         timestamp with time zone default now()             not null,
    user_id            text
        references users (user_id)
);

alter table user_preferences
    owner to postgres;

grant select, update, usage on sequence user_preferences_id_seq to anon;

grant select, update, usage on sequence user_preferences_id_seq to authenticated;

grant select, update, usage on sequence user_preferences_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on user_preferences to anon;

grant delete, insert, references, select, trigger, truncate, update on user_preferences to authenticated;

grant delete, insert, references, select, trigger, truncate, update on user_preferences to service_role;

create table sf_formations_payment_links
(
    id                            bigint generated by default as identity
        primary key,
    created_at                    timestamp with time zone default now() not null,
    name                          text,
    sf_formations_payment_link_id uuid                     default gen_random_uuid(),
    active                        boolean                  default true,
    currency                      text                     default 'EUR'::text,
    url                           text,
    payment_provider              text                     default 'STRIPE'::text,
    product_slug                  text,
    sandbox                       boolean                  default true,
    price                         numeric
);

alter table sf_formations_payment_links
    owner to postgres;

grant select, update, usage on sequence sf_formations_payment_links_id_seq to anon;

grant select, update, usage on sequence sf_formations_payment_links_id_seq to authenticated;

grant select, update, usage on sequence sf_formations_payment_links_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_payment_links to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_payment_links to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_payment_links to service_role;

create table sf_formations_companies
(
    id                       bigint generated by default as identity
        primary key,
    created_at               timestamp with time zone default now() not null,
    sf_formations_company_id uuid                     default gen_random_uuid(),
    name                     text,
    company_id               uuid
        references companies (company_id),
    user_id                  text
        references users (user_id),
    processed_by_user        text
        references users (user_id)
);

alter table sf_formations_companies
    owner to postgres;

grant select, update, usage on sequence sf_formations_companies_id_seq to anon;

grant select, update, usage on sequence sf_formations_companies_id_seq to authenticated;

grant select, update, usage on sequence sf_formations_companies_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_companies to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_companies to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_companies to service_role;

create table sf_formations_documents
(
    id                        bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default now() not null,
    sf_formations_document_id uuid                     default gen_random_uuid(),
    name                      text,
    document_type             text,
    uploaded_by_user          text
        references users (user_id),
    size                      numeric
);

alter table sf_formations_documents
    owner to postgres;

grant select, update, usage on sequence sf_formations_documents_id_seq to anon;

grant select, update, usage on sequence sf_formations_documents_id_seq to authenticated;

grant select, update, usage on sequence sf_formations_documents_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_documents to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_documents to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_documents to service_role;

create table stargate_webhook_sink_events
(
    id                             text                     default gen_descriptor_id('sws'::text)                                 not null
        constraint stargate_webhook_sink_events_unique_id
            unique,
    rid                            bigint generated by default as identity
        primary key,
    created_at                     timestamp with time zone default now()                                                          not null,
    time                           bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    stargate_webhook_sink_event_id uuid                     default gen_random_uuid()                                              not null
        constraint stargate_webhook_sink_events__key
            unique,
    event_id                       text,
    event_type                     text,
    event_created_at               timestamp with time zone,
    signature                      text,
    headers                        jsonb,
    metadata                       jsonb,
    payload                        jsonb,
    body                           jsonb,
    provider_ref_value             text,
    provider_ref_identifier        text
);

alter table stargate_webhook_sink_events
    owner to postgres;

grant select, update, usage on sequence stargate_webhook_sink_events_rid_seq to anon;

grant select, update, usage on sequence stargate_webhook_sink_events_rid_seq to authenticated;

grant select, update, usage on sequence stargate_webhook_sink_events_rid_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on stargate_webhook_sink_events to anon;

grant delete, insert, references, select, trigger, truncate, update on stargate_webhook_sink_events to authenticated;

grant delete, insert, references, select, trigger, truncate, update on stargate_webhook_sink_events to service_role;

create table sf_formations_cases
(
    id                    text                     default gen_descriptor_id('f-case'::text)                              not null
        unique,
    rid                   bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()                                                          not null,
    time                  bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    sf_formations_case_id uuid                     default gen_random_uuid()                                              not null
        constraint sf_formations_cases_uuid_key
            unique,
    title                 text,
    description           text,
    status                text,
    entity_type           text,
    author_user_id        text
        references users (user_id),
    assignee              text
        references users (user_id),
    company_id            uuid
        references companies (company_id),
    metadata              json,
    contract_package      text,
    note                  text,
    customer_id           uuid
        references customers,
    case_number           numeric,
    case_descriptor       text
);

alter table sf_formations_cases
    owner to postgres;

grant select, update, usage on sequence sf_formations_cases_rid_seq to anon;

grant select, update, usage on sequence sf_formations_cases_rid_seq to authenticated;

grant select, update, usage on sequence sf_formations_cases_rid_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_cases to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_cases to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_cases to service_role;

create table sf_formations_addresses
(
    id                       text                     default gen_descriptor_id('f-address'::text)                           not null
        unique,
    rid                      bigint generated by default as identity
        primary key,
    created_at               timestamp with time zone default now()                                                          not null,
    time                     bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    sf_formations_address_id uuid                     default gen_random_uuid()                                              not null
        constraint sf_formations_addresses_uuid_key
            unique,
    case_id                  uuid
        references sf_formations_cases (sf_formations_case_id),
    company_id               uuid
        references companies (company_id),
    address_type             text,
    address_line_1           text,
    address_line_2           text,
    city                     text,
    state                    text,
    postal_code              text,
    country_code             text
);

alter table sf_formations_addresses
    owner to postgres;

grant select, update, usage on sequence sf_formations_addresses_rid_seq to anon;

grant select, update, usage on sequence sf_formations_addresses_rid_seq to authenticated;

grant select, update, usage on sequence sf_formations_addresses_rid_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_addresses to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_addresses to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_addresses to service_role;

create table sf_formations_shareholders
(
    id                           text                     default gen_descriptor_id('f-shareholder'::text)                       not null
        unique,
    rid                          bigint generated by default as identity
        primary key,
    created_at                   timestamp with time zone default now()                                                          not null,
    time                         bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    sf_formations_shareholder_id uuid                     default gen_random_uuid()                                              not null
        constraint sf_formations_shareholders_uuid_key
            unique,
    case_id                      uuid
        references sf_formations_cases (sf_formations_case_id),
    company_id                   uuid
        references companies (company_id),
    salutation                   text,
    first_name                   text,
    middle_name                  text,
    surname                      text,
    dob                          date,
    email                        text,
    phone                        text,
    country_of_birth             text,
    share_pct                    numeric
);

alter table sf_formations_shareholders
    owner to postgres;

grant select, update, usage on sequence sf_formations_shareholders_rid_seq to anon;

grant select, update, usage on sequence sf_formations_shareholders_rid_seq to authenticated;

grant select, update, usage on sequence sf_formations_shareholders_rid_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_shareholders to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_shareholders to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_shareholders to service_role;

create table sf_formations_members
(
    id                      text                     default gen_descriptor_id('f-member'::text)                            not null
        unique,
    rid                     bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default now()                                                          not null,
    time                    bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    sf_formations_member_id uuid                     default gen_random_uuid()                                              not null
        constraint sf_formations_members_uuid_key
            unique,
    case_id                 uuid
        references sf_formations_cases (sf_formations_case_id),
    company_id              uuid
        references companies (company_id),
    member_type             text,
    roles                   text[],
    first_name              text,
    middle_name             text,
    surname                 text,
    email                   text,
    phone                   text,
    dob                     date,
    shares                  numeric,
    gender                  text,
    passport_number         text,
    passport_issue_date     date,
    passport_expiry         date,
    nationality             text,
    address                 text
);

alter table sf_formations_members
    owner to postgres;

grant select, update, usage on sequence sf_formations_members_rid_seq to anon;

grant select, update, usage on sequence sf_formations_members_rid_seq to authenticated;

grant select, update, usage on sequence sf_formations_members_rid_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_members to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_members to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_members to service_role;

create table sf_formations_activities
(
    id                        text                     default gen_descriptor_id('f-activity'::text)                          not null
        unique,
    rid                       bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default now()                                                          not null,
    time                      bigint                   default (EXTRACT(epoch FROM (now() AT TIME ZONE 'utc'::text)))::bigint not null,
    sf_formations_activity_id uuid                     default gen_random_uuid()                                              not null
        constraint sf_formations_activities_uuid_key
            unique,
    case_id                   uuid
        references sf_formations_cases (sf_formations_case_id),
    company_id                uuid
        references companies (company_id),
    activity_name             text,
    activity_code             text,
    ded_license_type          text,
    tpa                       text,
    regulatory_authority      text,
    other_activity            boolean,
    country_operation         text
);

alter table sf_formations_activities
    owner to postgres;

grant select, update, usage on sequence sf_formations_activities_rid_seq to anon;

grant select, update, usage on sequence sf_formations_activities_rid_seq to authenticated;

grant select, update, usage on sequence sf_formations_activities_rid_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_activities to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_activities to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_activities to service_role;

create table sf_formations_case_attachments
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()             not null,
    case_attachment_id    uuid                     default gen_random_uuid() not null
        unique,
    sf_formations_case_id uuid                                               not null
        constraint sf_formations_case_attachments_case_fkey
            references sf_formations_cases (sf_formations_case_id),
    file_id               uuid
        constraint sf_formations_case_attachments_file_fkey
            references files (file_id),
    file_url              text,
    filename              text,
    mime                  text,
    size                  numeric
);

alter table sf_formations_case_attachments
    owner to postgres;

grant select, update, usage on sequence sf_formations_case_attachments_id_seq to anon;

grant select, update, usage on sequence sf_formations_case_attachments_id_seq to authenticated;

grant select, update, usage on sequence sf_formations_case_attachments_id_seq to service_role;

create index idx_sf_case_attachments_case_id
    on sf_formations_case_attachments (sf_formations_case_id);

grant delete, insert, references, select, trigger, truncate, update on sf_formations_case_attachments to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_case_attachments to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_case_attachments to service_role;

create table sf_formations_case_messages
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()             not null,
    case_message_id       uuid                     default gen_random_uuid() not null
        unique,
    sf_formations_case_id uuid                                               not null
        constraint sf_formations_case_messages_case_fkey
            references sf_formations_cases (sf_formations_case_id),
    author_user_id        text
        constraint sf_formations_case_messages_author_fkey
            references users (user_id),
    message               text                                               not null
);

alter table sf_formations_case_messages
    owner to postgres;

grant select, update, usage on sequence sf_formations_case_messages_id_seq to anon;

grant select, update, usage on sequence sf_formations_case_messages_id_seq to authenticated;

grant select, update, usage on sequence sf_formations_case_messages_id_seq to service_role;

create index idx_sf_case_messages_case_id
    on sf_formations_case_messages (sf_formations_case_id);

grant delete, insert, references, select, trigger, truncate, update on sf_formations_case_messages to anon;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_case_messages to authenticated;

grant delete, insert, references, select, trigger, truncate, update on sf_formations_case_messages to service_role;

