create table emails
(
    id                   bigint generated by default as identity
        primary key,
    created_at           timestamp with time zone default now()             not null,
    email_id             uuid                     default gen_random_uuid() not null
        unique,
    subject              text,
    recipient_email      text,
    sender_email         text,
    body                 json,
    status               text,
    time                 numeric,
    user_id              text,
    email_code           text,
    title                text,
    html_body            text,
    template_id          text,
    replace_data         json,
    opened               boolean,
    delivered            boolean,
    request_id           text,
    request_message      text,
    data_code            text,
    data_message         text,
    data_additional_info json,
    resource_type_ref    text,
    resource_id_ref      text,
    locale               text                     default 'en-US'::text,
    message              text,
    company_id           uuid,
    recipient_name       text,
    has_attachments      boolean,
    attachments          jsonb,
    language             text                     default 'en'::text,
    view_key             text
        unique,
    starred              boolean                  default false
);

alter table emails
    owner to postgres;

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

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

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

create index emails_created_at_idx
    on emails (created_at);

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

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

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

create table companies
(
    id                        bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default now()             not null,
    company_id                uuid                     default gen_random_uuid() not null
        unique,
    name                      text,
    owner_user_id             text,
    kvk_number                numeric,
    vat_id                    text,
    trade_name                text,
    active                    boolean                  default true,
    rsin                      numeric,
    establishment_number      numeric,
    rights_form               text,
    main_sbi_code             numeric,
    main_activity             text,
    main_activity_description text,
    activities                json,
    country                   text,
    establishment             boolean                  default false,
    standard_business_layout  text,
    rights_form_code          text,
    neighborhood              text,
    house_number              numeric,
    city                      text,
    province                  text,
    longitude                 numeric,
    latitude                  numeric,
    area                      text,
    street                    text,
    postal_code               text,
    billing_email             text,
    contact_email             text,
    owner_email               text,
    custom_fields             json,
    brand_color               text                     default '#4085e6'::text,
    company_logo_url          text,
    municipality              text,
    website                   text,
    dissolved                 boolean                  default false,
    email_forward             text,
    email_forward_enabled     boolean,
    exempt_from_vat           boolean                  default false,
    is_kor                    boolean                  default false,
    company_number            text,
    address                   text,
    entity_type               text,
    country_code              text,
    website_favicon           text,
    website_verified          boolean                  default false,
    is_eu_sme_scheme          boolean                  default false,
    avatar                    text
);

alter table companies
    owner to postgres;

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

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

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

create table users
(
    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,
    email                      text                                   not null,
    avatar                     text,
    onboarded                  boolean                  default false,
    country                    text,
    city                       text,
    address_line_1             text,
    address_line_2             text,
    postal_code                text,
    state                      text,
    full_name                  text,
    first_name                 text,
    last_name                  text,
    status                     text                     default 'active'::text,
    auth_index                 numeric                  default '0'::numeric,
    domain                     text                     default 'suitsbooks.nl'::text,
    mfa_setup                  boolean                  default false,
    last_mfa_challenge_at      numeric,
    awaiting_mfa_challenge     boolean                  default false,
    display_name               text,
    default_organization       text,
    default_scope              text                     default 'account'::text,
    mfa_enabled                boolean                  default false,
    totp_secret                text,
    notification_count         numeric,
    theme                      text,
    is_verified                boolean                  default false,
    is_frozen                  boolean                  default false,
    is_flagged                 boolean                  default false,
    phone_number               text,
    username                   text
        unique,
    number_format              text                     default 'de-DE'::text,
    timezone                   text                     default 'cest'::text,
    totp_secret_qr_code_url    text,
    company_id                 uuid
        references companies (company_id),
    organization_id            text,
    owns_root_organization_id  boolean                  default false,
    root_organization_id       text,
    is_onboarded_first_company boolean                  default false,
    bio                        text,
    disable_global_drilldown   boolean                  default false,
    has_view_setting_record    boolean                  default false,
    role                       "Roles"                  default 'Customer'::"Roles",
    birth_date                 text,
    expo_push_token            text,
    mobile_signed_in           boolean
);

comment on column users.role is 'User role';

alter table users
    owner to postgres;

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

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

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

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

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

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

grant delete, insert, update on users to authenticator;

create table organizations
(
    id                       bigint generated by default as identity
        primary key,
    created_at               timestamp with time zone default now() not null,
    name                     text,
    organization_id          text                                   not null
        unique,
    avatar                   text,
    tier                     text,
    bio                      text,
    verified                 boolean,
    billing_address_line_1   text,
    billing_address_line_2   text,
    billing_city             text,
    billing_country          text,
    billing_postal_code      text,
    billing_state            text,
    billing_company_name     text,
    billing_email            text,
    billing_invoice_language text,
    owner_user_id            text
        references users (user_id),
    root_organization        boolean                  default false
);

alter table organizations
    owner to postgres;

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

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

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

alter table users
    add foreign key (organization_id) references organizations (organization_id);

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

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

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

create table access_groups
(
    id                 bigint generated by default as identity
        primary key,
    created_at         timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    organization_id    text
        references organizations (organization_id),
    user_id            text
        references users (user_id),
    role               text,
    auth_index         numeric                  default '0'::numeric,
    pending            boolean                  default true,
    invite_code        text,
    invited_by_user_id text
        references users (user_id),
    time               numeric,
    frozen             boolean                  default false,
    flagged            boolean                  default false,
    status             text,
    company_id         uuid
        references companies (company_id),
    exp_date           numeric,
    scopes             json,
    resource_name      text,
    resource_object    text,
    access_group_id    uuid                     default gen_random_uuid()
        unique,
    access_group_hash  text
        unique
);

alter table access_groups
    owner to postgres;

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

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

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

create index access_groups_user_id_idx
    on access_groups (user_id);

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

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

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

create table audit_log
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    user_id         text
        references users (user_id),
    username        text,
    action          text,
    time            numeric,
    route           text,
    request         text,
    status          text,
    message         text,
    author_user_id  text
        references users (user_id),
    email           text,
    domain          text                     default 'suitsbooks.nl'::text,
    organization_id text
        references organizations (organization_id),
    new_status      text,
    old_value       text,
    new_value       text,
    company_id      text,
    "table"         text,
    resource_id     text,
    resource        json,
    diff_resource   json,
    user_object     json,
    ipv4            text,
    audit_log_id    uuid                     default gen_random_uuid()                not null
        unique
);

alter table audit_log
    owner to postgres;

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

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

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

create index audit_log_company_id_idx
    on audit_log (company_id);

create index audit_log_resource_id_idx
    on audit_log (resource_id);

create index audit_log_table_idx
    on audit_log ("table");

create index audit_log_action_idx
    on audit_log (action);

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

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

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

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

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

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

create table ip_identities
(
    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),
    ipv4                text                                   not null
        unique,
    os                  text,
    user_agent          text,
    resolution          text,
    country             text,
    state               text,
    postal_code         text,
    locale              text,
    last_sign_in        numeric,
    first_seen          numeric,
    provider            text,
    hostname            text,
    session_id          text,
    lon                 numeric,
    lat                 numeric,
    suggested_addresses json,
    continent_code      text,
    continent           text,
    currency            text,
    district            text,
    hosting             boolean                  default false,
    isp                 text,
    message             text,
    mobile              boolean                  default false,
    "offset"            numeric,
    org                 text,
    proxy               boolean                  default false,
    query               text,
    region              text,
    region_name         text,
    reverse             text,
    status              text,
    timezone            text,
    zip                 text,
    hash                text
        unique
);

alter table ip_identities
    owner to postgres;

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

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

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

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

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

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

create table notifications
(
    id              bigint generated by default as identity
        primary key
        unique,
    created_at      timestamp with time zone default now()             not null,
    user_id         text
        references users (user_id)
        constraint notifications_user_id_fkey1
            references users (user_id),
    read            boolean                  default false,
    title           text,
    message         text,
    href            text,
    type            text,
    system_message  boolean,
    action          text,
    target          text,
    timestamp       numeric,
    "user"          text
        references users (user_id),
    image           text,
    notification_id uuid                     default gen_random_uuid() not null
        unique,
    company_id      uuid
        references companies (company_id),
    ticket_id       text,
    chat_id         text,
    column_scope    text
);

alter table notifications
    owner to postgres;

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

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

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

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

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

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

create table scopes
(
    id          bigint generated by default as identity
        primary key,
    created_at  timestamp with time zone default now() not null,
    scope_id    text                                   not null
        unique,
    name        text,
    description text
);

alter table scopes
    owner to postgres;

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

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

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

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

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

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

create table notes
(
    id             bigint generated by default as identity
        primary key,
    created_at     timestamp with time zone default now() not null,
    author_user_id text
        references users (user_id),
    note_id        text                                   not null
        unique,
    resource_type  text,
    resource_id    text,
    content        text
);

alter table notes
    owner to postgres;

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

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

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

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

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

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

create table event_log
(
    id          bigint generated by default as identity
        primary key,
    created_at  timestamp with time zone default now() not null,
    directive   text,
    time        numeric,
    path        text,
    content     text,
    server      text,
    api_version text,
    severity    text,
    message     text,
    json        json,
    user_id     text,
    company_id  text,
    status      text,
    ref_id      text
);

alter table event_log
    owner to postgres;

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

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

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

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

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

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

create table ponto_financial_institution
(
    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 table ponto_financial_institution is 'Original model name - financialInstitution_attributes.';

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

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

comment on column ponto_financial_institution.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 ponto_financial_institution.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 ponto_financial_institution.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 ponto_financial_institution.bulk_payments_enabled is 'Indicates whether the financial institution allows bulk payment initiation requests. Original param name - bulkPaymentsEnabled.';

comment on column ponto_financial_institution.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 ponto_financial_institution.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 ponto_financial_institution.logo_url is 'Location of the logo image for the financial institution. Original param name - logoUrl.';

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

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

comment on column ponto_financial_institution.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 ponto_financial_institution.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 ponto_financial_institution.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 ponto_financial_institution.periodic_payments_enabled is 'Indicates whether the financial institution allows periodic payment initiation requests. Original param name - periodicPaymentsEnabled.';

comment on column ponto_financial_institution.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 ponto_financial_institution.primary_color is 'Hexadecimal color code related to the primary branding color of the financial institution. Original param name - primaryColor.';

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

comment on column ponto_financial_institution.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 ponto_financial_institution.shared_brand_reference is 'Attribute used to group multiple individual financial institutions in the same country. Original param name - sharedBrandReference.';

comment on column ponto_financial_institution.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 ponto_financial_institution
    owner to postgres;

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

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

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

create table ponto_account
(
    account_id                              uuid                                   not null
        primary key
        unique,
    deprecated                              boolean,
    description                             text,
    product                                 text,
    reference                               text,
    currency                                text,
    subtype                                 text,
    available_balance                       numeric(20, 9)           default NULL::numeric,
    available_balance_changed_at            timestamp,
    available_balance_reference_date        timestamp,
    current_balance                         numeric(20, 9)           default NULL::numeric,
    current_balance_changed_at              timestamp,
    current_balance_reference_date          timestamp,
    holder_name                             text,
    reference_type                          text,
    authorization_expiration_expected_at    timestamp,
    authorized_at                           timestamp,
    available_balance_variation_observed_at timestamp,
    current_balance_variation_observed_at   timestamp,
    internal_reference                      text,
    created_at                              timestamp with time zone default (now() AT TIME ZONE 'utc'::text),
    user_id                                 text                                   not null
        references users (user_id)
            on update restrict on delete restrict,
    organization_id                         uuid                                   not null,
    financial_institution_id                uuid,
    revoked                                 boolean                  default false not null,
    company_id                              uuid                                   not null
        references companies (company_id),
    id                                      bigint generated by default as identity
        unique,
    ponto_account_id                        uuid                     default gen_random_uuid(),
    block_revoke                            boolean                  default false,
    test_mode                               boolean                  default false,
    is_hard_deleted                         boolean                  default false,
    deleted_at                              numeric
);

comment on column ponto_account.deprecated is 'Indicates if the account 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 ponto_account.description is 'Description of the account';

comment on column ponto_account.product is 'Name of the account product';

comment on column ponto_account.reference is 'Financial institution&#39;s internal reference for this account';

comment on column ponto_account.currency is 'Currency of the account, in &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_4217&#39;&gt;ISO4217&lt;/a&gt; format';

comment on column ponto_account.subtype is 'Type of account. Can be &lt;code&gt;checking&lt;/code&gt;, &lt;code&gt;savings&lt;/code&gt;, &lt;code&gt;securities&lt;/code&gt;, &lt;code&gt;card&lt;/code&gt; or &lt;code&gt;psp&lt;/code&gt;';

comment on column ponto_account.available_balance is 'Amount of account funds that can be accessed immediately. Original param name - availableBalance.';

comment on column ponto_account.available_balance_changed_at is 'When the available balance was changed for the last time. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - availableBalanceChangedAt.';

comment on column ponto_account.available_balance_reference_date is 'Reference date of the available balance. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - availableBalanceReferenceDate.';

comment on column ponto_account.current_balance is 'Total funds currently in the account. Original param name - currentBalance.';

comment on column ponto_account.current_balance_changed_at is 'When the current balance was changed for the last time. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - currentBalanceChangedAt.';

comment on column ponto_account.current_balance_reference_date is 'Reference date of the current balance. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - currentBalanceReferenceDate.';

comment on column ponto_account.holder_name is 'Name of the account holder. Original param name - holderName.';

comment on column ponto_account.reference_type is 'Type of financial institution reference (can be &lt;code&gt;IBAN&lt;/code&gt;, &lt;code&gt;BBAN&lt;/code&gt;, &lt;code&gt;email&lt;/code&gt;, &lt;code&gt;PAN&lt;/code&gt;, &lt;code&gt;MASKEDPAN&lt;/code&gt; or &lt;code&gt;MSISDN&lt;/code&gt;). Original param name - referenceType.';

comment on column ponto_account.authorization_expiration_expected_at is 'When the authorization towards the account is expected to end. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - authorizationExpirationExpectedAt.';

comment on column ponto_account.authorized_at is 'When the account was authorized for the last time. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - authorizedAt.';

comment on column ponto_account.available_balance_variation_observed_at is 'Last time that a variation (positive or negative) was detected in our system on the available balance. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - availableBalanceVariationObservedAt.';

comment on column ponto_account.current_balance_variation_observed_at is 'Last time that a variation (positive or negative) was detected in our system on the current balance. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - currentBalanceVariationObservedAt.';

comment on column ponto_account.internal_reference is 'Internal resource reference given by the financial institution. Original param name - internalReference.';

alter table ponto_account
    owner to postgres;

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

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

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

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

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

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

create table ponto_transaction
(
    transaction_id                    uuid    not null
        constraint ponto_transaction_id_key
            unique,
    account_id                        uuid    not null
        references ponto_account
            on update restrict on delete restrict,
    description                       text,
    currency                          text,
    digest                            text,
    created_at                        timestamp      default (now() AT TIME ZONE 'utc'::text),
    updated_at                        timestamp,
    amount                            numeric(20, 9) default NULL::numeric,
    fee                               numeric(20, 9) default NULL::numeric,
    additional_information            text,
    bank_transaction_code             text,
    card_reference                    text,
    card_reference_type               text,
    counterpart_name                  json,
    counterpart_reference             text,
    creditor_id                       text,
    end_to_end_id                     text,
    execution_date                    timestamp,
    mandate_id                        text,
    proprietary_bank_transaction_code text,
    purpose_code                      text,
    remittance_information            text,
    remittance_information_type       text,
    value_date                        timestamp,
    internal_reference                text,
    user_id                           text    not null
        references users (user_id)
            on update restrict on delete restrict,
    created_at_unixtime_milli         numeric not null,
    updated_at_unixtime_milli         numeric not null,
    execution_date_unixtime_milli     numeric,
    id                                bigint generated by default as identity
        primary key
        constraint ponto_transaction_id_key1
            unique
);

comment on column ponto_transaction.description is 'Description of the transaction';

comment on column ponto_transaction.currency is 'Currency of the transaction, in &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_4217&#39;&gt;ISO4217&lt;/a&gt; format';

comment on column ponto_transaction.digest is 'A Base64-encoded SHA-256 digest of the transaction payload from the financial institution. This may NOT be unique if the exact same transaction happens on the same day, on the same account.';

comment on column ponto_transaction.created_at is 'When this transaction was created. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - createdAt.';

comment on column ponto_transaction.updated_at is 'When this transaction was last synchronized successfully. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - updatedAt.';

comment on column ponto_transaction.amount is 'Amount of the transaction. Can be positive or negative';

comment on column ponto_transaction.fee is 'A fee that was withheld from this transaction at the financial institution';

comment on column ponto_transaction.additional_information is 'Additional transaction-related information provided from the financial institution to the customer. Original param name - additionalInformation.';

comment on column ponto_transaction.bank_transaction_code is 'Bank transaction code, based on &lt;a href&#x3D;&#39;https://www.iso20022.org/catalogue-messages/additional-content-messages/external-code-sets&#39;&gt;ISO 20022&lt;/a&gt;. Original param name - bankTransactionCode.';

comment on column ponto_transaction.card_reference is 'Reference for card related to the transaction (if any). For example the last 4 digits of the card number.. Original param name - cardReference.';

comment on column ponto_transaction.card_reference_type is 'Type of card reference (can be &lt;code&gt;PAN&lt;/code&gt; or &lt;code&gt;MASKEDPAN&lt;/code&gt;). Original param name - cardReferenceType.';

comment on column ponto_transaction.counterpart_name is 'Legal name of the counterpart. Original param name - counterpartName.';

comment on column ponto_transaction.counterpart_reference is 'Number representing the counterpart&#39;s account. Original param name - counterpartReference.';

comment on column ponto_transaction.creditor_id is 'Identification of the creditor, e.g. a SEPA Creditor ID.. Original param name - creditorId.';

comment on column ponto_transaction.end_to_end_id is 'Identifier assigned by the initiating party to identify the transaction. This identification is passed on, unchanged, throughout the entire end-to-end chain. Limited to 35 characters in the set &lt;code&gt;a b c d e f g h i j k l m n o p q r s t u v w x y z A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9 / - ? : ( ) . , &#39; + Space&lt;/code&gt; to ensure it is not rejected by the financial institution.. Original param name - endToEndId.';

comment on column ponto_transaction.execution_date is 'Date representing the moment when the financial institution recorded the {resource}.. Original param name - executionDate.';

comment on column ponto_transaction.mandate_id is 'Unique reference of the mandate which is signed between the remitter and the debtor. Original param name - mandateId.';

comment on column ponto_transaction.proprietary_bank_transaction_code is 'Bank transaction code prorietary to the financial institution. Content will vary per financial institution. Original param name - proprietaryBankTransactionCode.';

comment on column ponto_transaction.purpose_code is 'Purpose code, based on &lt;a href&#x3D;&#39;https://www.iso20022.org/&#39;&gt;ISO 20022&lt;/a&gt;. Original param name - purposeCode.';

comment on column ponto_transaction.remittance_information is 'Content of the remittance information (aka communication). Original param name - remittanceInformation.';

comment on column ponto_transaction.remittance_information_type is 'Type of remittance information, can be &lt;code&gt;structured&lt;/code&gt; or &lt;code&gt;unstructured&lt;/code&gt;. Original param name - remittanceInformationType.';

comment on column ponto_transaction.value_date is 'Date representing the moment the transaction is considered effective. Original param name - valueDate.';

comment on column ponto_transaction.internal_reference is 'Internal resource reference given by the financial institution. Original param name - internalReference.';

alter table ponto_transaction
    owner to postgres;

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

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

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

create index ponto_transaction_account_id_idx
    on ponto_transaction (account_id);

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

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

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

create table ponto_onboarding_details
(
    id                                      uuid                     default gen_random_uuid() not null
        primary key,
    email                                   text,
    first_name                              text,
    last_name                               text,
    address_city                            text,
    address_country                         text,
    address_postal_code                     text,
    address_street_address                  text,
    enterprise_number                       text,
    vat_number                              text,
    phone_number                            text,
    automatic_submission_on_completed_forms boolean,
    initial_financial_institution_id        uuid,
    organization_name                       text,
    organization_type                       text,
    preferred_otp_method                    json,
    requested_organisation_id               text,
    partner_reference                       text,
    created_at_unixtime                     numeric,
    created_at                              timestamp with time zone default (now() AT TIME ZONE 'utc'::text),
    ponto_onboarding_id                     uuid                     default gen_random_uuid()
);

comment on table ponto_onboarding_details is 'Original model name - onboardingDetails_attributes.';

comment on column ponto_onboarding_details.email is 'Email belonging to the onboarding user';

comment on column ponto_onboarding_details.first_name is 'First name of the onboarding user. Original param name - firstName.';

comment on column ponto_onboarding_details.last_name is 'Last name of the onboarding user. Original param name - lastName.';

comment on column ponto_onboarding_details.address_city is 'City of the onboarding user&#39;s organization. Original param name - addressCity.';

comment on column ponto_onboarding_details.address_country is 'Country of the onboarding user&#39;s organization. Original param name - addressCountry.';

comment on column ponto_onboarding_details.address_postal_code is 'Postal code of the onboarding user&#39;s organization. Original param name - addressPostalCode.';

comment on column ponto_onboarding_details.address_street_address is 'Street address of the onboarding user&#39;s organization. Original param name - addressStreetAddress.';

comment on column ponto_onboarding_details.enterprise_number is 'Enterprise number corresponding to the onboarding user&#39;s organization. Original param name - enterpriseNumber.';

comment on column ponto_onboarding_details.vat_number is 'VAT number corresponding to the onboarding user&#39;s organization. Original param name - vatNumber.';

comment on column ponto_onboarding_details.phone_number is 'Phone number of the onboarding user. Original param name - phoneNumber.';

comment on column ponto_onboarding_details.automatic_submission_on_completed_forms is 'Indicates if the form should be automatically submitted when all fields are completed. Defaults to &lt;code&gt;false&lt;/code&gt;.. Original param name - automaticSubmissionOnCompletedForms.';

comment on column ponto_onboarding_details.initial_financial_institution_id is 'Unique identifier of the financial institution that should be preselected during the Ponto onboarding process. Original param name - initialFinancialInstitutionId.';

comment on column ponto_onboarding_details.organization_name is 'Name of the onboarding user&#39;s organization. Original param name - organizationName.';

comment on column ponto_onboarding_details.organization_type is 'Type of the onboarding user&#39;s organization. Can be &lt;code&gt;business&lt;/code&gt; or &lt;code&gt;personal&lt;/code&gt;. Original param name - organizationType.';

comment on column ponto_onboarding_details.preferred_otp_method is 'Preferred OTP method for the user. If &lt;code&gt;sms&lt;/code&gt; provided, the phone number will be validated. Defaults to &lt;code&gt;email&lt;/code&gt;. Original param name - preferredOtpMethod.';

comment on column ponto_onboarding_details.requested_organisation_id is 'Unique identifier of the organization that should be preselected during the Ponto onboarding process. Original param name - requestedOrganisationId.';

comment on column ponto_onboarding_details.partner_reference is 'Unique identifier that can be used to identify records on the partner side.. Original param name - partnerReference.';

alter table ponto_onboarding_details
    owner to postgres;

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

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

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

create table ponto_usage
(
    month                     text not null,
    organization_id           uuid not null,
    account_count             numeric,
    bulk_payment_bundle_count numeric,
    bulk_payment_count        numeric,
    payment_account_count     numeric,
    payment_count             numeric,
    total_accounts            numeric,
    id                        bigserial
        primary key,
    created_at                timestamp with time zone default (now() AT TIME ZONE 'utc'::text)
);

comment on column ponto_usage.month is 'Month of the usage, idfk check pontos docs';

comment on column ponto_usage.account_count is 'Number of accounts linked to the integration. The total is prorated, so may be a decimal number if accounts have been linked or unlinked during the month.. Original param name - accountCount.';

comment on column ponto_usage.bulk_payment_bundle_count is '&lt;strong&gt;[Deprecated - use &lt;code&gt;bulkPaymentCount&lt;/code&gt; instead]&lt;/strong&gt;Number of initiated bulk payment bundles created by the integration. Original param name - bulkPaymentBundleCount.';

comment on column ponto_usage.bulk_payment_count is 'Number of initiated bulk payment created by the integration. Original param name - bulkPaymentCount.';

comment on column ponto_usage.payment_account_count is '&lt;strong&gt;[Deprecated]&lt;/strong&gt;Number of accounts which initiated a payment created by the integration. Original param name - paymentAccountCount.';

comment on column ponto_usage.payment_count is 'Number of initiated payments created by the integration. Original param name - paymentCount.';

comment on column ponto_usage.total_accounts is 'Original param name - totalAccounts.';

alter table ponto_usage
    owner to postgres;

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

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

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

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

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

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

create table ponto_user_info
(
    name                                  text,
    sub                                   uuid                                   not null
        unique,
    payments_activated                    boolean,
    payments_activation_requested         boolean,
    payment_requests_activated            boolean,
    payment_requests_activation_requested boolean,
    onboarding_complete                   boolean,
    user_id                               text                                   not null
        primary key
        unique
        references users (user_id)
            on update restrict on delete restrict,
    blocked                               boolean                  default false not null,
    created_at                            timestamp with time zone default (now() AT TIME ZONE 'utc'::text)
);

comment on table ponto_user_info is 'Original model name - userInfo_attributes.';

comment on column ponto_user_info.name is 'Name of the organization';

comment on column ponto_user_info.sub is 'ID of the organization corresponding to the provided access token';

comment on column ponto_user_info.payments_activated is 'Indicates whether the organization can currently sign live payments from Ponto. Must be &lt;code&gt;true&lt;/code&gt; to use the (bulk) payment redirect flow.. Original param name - paymentsActivated.';

comment on column ponto_user_info.payments_activation_requested is 'Indicates whether the organization has requested to be able to sign payments from Ponto. If it is &lt;code&gt;false&lt;/code&gt; (or you are in the sandbox), you may use the &lt;a href&#x3D;&#39;https://documentation.ibanity.com//api#request-payment-activation&#39;&gt;payment activation request&lt;/a&gt; redirect flow.. Original param name - paymentsActivationRequested.';

comment on column ponto_user_info.payment_requests_activated is 'Original param name - paymentRequestsActivated.';

comment on column ponto_user_info.payment_requests_activation_requested is 'Original param name - paymentRequestsActivationRequested.';

comment on column ponto_user_info.onboarding_complete is 'Indicates whether the organization has completed the onboarding process in the Ponto dashboard.. Original param name - onboardingComplete.';

comment on column ponto_user_info.blocked is 'its ponto that blocks and unblocks';

alter table ponto_user_info
    owner to postgres;

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

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

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

create table ponto_tokens
(
    created_at               numeric not null,
    expires_at               numeric,
    user_id                  text    not null
        constraint integration_tokens_pkey
            primary key
        references users (user_id),
    access_token             text    not null,
    refresh_token            text,
    token_type               text,
    scope                    text,
    ponto_token_id           uuid default gen_random_uuid(),
    access_token_expires_at  numeric,
    refresh_token_expires_at numeric
);

alter table ponto_tokens
    owner to postgres;

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

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

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

create table ponto_synchronization
(
    id                        uuid not null
        primary key,
    status                    text,
    errors                    json,
    subtype                   text,
    created_at                timestamp,
    resource_id               uuid,
    resource_type             text not null,
    updated_at                timestamp,
    updated_transactions_link text,
    created_at_unixtime_milli numeric,
    updated_at_unixtime_milli numeric
);

comment on column ponto_synchronization.status is 'Current status of the synchronization, which changes from &lt;code&gt;pending&lt;/code&gt; to &lt;code&gt;running&lt;/code&gt; to &lt;code&gt;success&lt;/code&gt; or &lt;code&gt;error&lt;/code&gt;';

comment on column ponto_synchronization.errors is 'Details of any errors that have occurred during synchronization, due to invalid authorization or technical failure. &lt;a href&#x3D;&#39;https://documentation.ibanity.com//api#sync&#39;&gt;See possible errors&lt;/a&gt;';

comment on column ponto_synchronization.subtype is 'What is being synchronized. Account information such as balance is updated using &lt;code&gt;accountDetails&lt;/code&gt;, while &lt;code&gt;accountTransactions&lt;/code&gt; is used to synchronize the settled transactions, and &lt;code&gt;accountTransactionsWithUnsettled&lt;/code&gt; is used to synchronize the pending and settled transactions together.';

comment on column ponto_synchronization.created_at is 'When this synchronization was created. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - createdAt.';

comment on column ponto_synchronization.resource_id is 'Identifier of the resource to be synchronized. Original param name - resourceId.';

comment on column ponto_synchronization.resource_type is 'Type of the resource to be synchronized. Currently must be &lt;code&gt;account&lt;/code&gt;. Original param name - resourceType.';

comment on column ponto_synchronization.updated_at is 'When this synchronization was last synchronized successfully. Formatted according to &lt;a href&#x3D;&#39;https://en.wikipedia.org/wiki/ISO_8601&#39;&gt;ISO8601&lt;/a&gt; spec. Original param name - updatedAt.';

alter table ponto_synchronization
    owner to postgres;

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

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

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

create table ponto_webhook_events
(
    id                      uuid not null,
    resource                text not null,
    event                   text,
    created_at              timestamp with time zone,
    synchronization_subtype text,
    account_id              uuid,
    organization_id         uuid,
    synchronization_id      uuid,
    payment_request_id      uuid,
    count                   numeric,
    row_id                  bigint generated by default as identity
        primary key
);

alter table ponto_webhook_events
    owner to postgres;

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

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

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

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

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

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

create table contacts
(
    id                         bigint generated by default as identity,
    contact_id                 uuid                     default gen_random_uuid() not null
        constraint unique_contact_id
            unique,
    name                       text                                               not null,
    email                      text,
    phone                      text,
    postal_code                text,
    city                       text,
    country                    text,
    iban                       text,
    type                       text,
    created_at                 timestamp with time zone default now()             not null,
    address                    text,
    contact_person_name        text,
    website                    text,
    bic                        text,
    bank_recipient_name        text,
    vat_id                     text,
    kvk                        text,
    rights_form                text,
    subject_to_vat             boolean,
    memo                       text,
    description                text,
    avatar                     text,
    default_invoicing_template text,
    company_id                 uuid
        references companies (company_id),
    identity_provider          text,
    job_title                  text,
    display_name               text,
    given_name                 text,
    office_location            text,
    surname                    text,
    personal_phone             text,
    business_phone             text,
    identity_provider_id       text,
    primary key (id, contact_id)
);

alter table contacts
    owner to postgres;

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

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

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

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

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

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

create table transaction_categories
(
    id                      bigint generated by default as identity
        unique,
    label                   text                                               not null,
    company_id              uuid
        references companies (company_id),
    created_at              timestamp with time zone default now()             not null,
    time                    numeric,
    author_user_id          text                                               not null
        references users (user_id),
    icon                    text,
    transaction_category_id uuid                     default gen_random_uuid() not null
        constraint unique_transaction_category_id
            unique,
    primary key (id, transaction_category_id)
);

alter table transaction_categories
    owner to postgres;

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

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

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

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

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

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

create table invoice_logs
(
    id               bigint generated by default as identity,
    created_at       timestamp with time zone default now()             not null,
    invoice_id       uuid,
    user_id          text
        references users (user_id),
    company_id       uuid
        references companies (company_id),
    message          text,
    action           text,
    ip               text,
    user_agent       text,
    view_key         text,
    invoice_url      text,
    time             numeric,
    display_name     text,
    log_id           uuid                     default gen_random_uuid() not null
        unique,
    system_only_view boolean                  default false,
    email            text,
    primary key (id, log_id)
);

alter table invoice_logs
    owner to postgres;

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

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

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

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

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

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

create table products
(
    id                     bigint generated by default as identity,
    product_id             uuid                     default gen_random_uuid() not null,
    name                   text                                               not null,
    price                  numeric,
    tax_id                 text,
    created_at             timestamp with time zone default now()             not null,
    images                 json,
    image_thumbnail        text,
    description            text,
    statement_descriptor   text,
    unit_label             text,
    metadata               json,
    marketing_feature_list json,
    price_ids              json,
    mrr                    numeric,
    mrr_last_computed      numeric,
    created                numeric,
    updated                numeric,
    awaiting_archival      boolean                  default false,
    company_id             uuid
        references companies (company_id),
    product_category_id    text,
    ref_identifier         text
        unique,
    ref_provider           text,
    price_id_primary       uuid,
    primary key (id, product_id)
);

alter table products
    owner to postgres;

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

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

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

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

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

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

create table tax_calender
(
    id               bigint generated by default as identity
        primary key,
    created_at       timestamp with time zone default now() not null,
    country          text,
    timeframe        text,
    deadline_date    text,
    filing_frequency text,
    tax_type         text,
    tax_calendar_id  uuid                     default gen_random_uuid()
        unique,
    country_code     text,
    event_code       text
);

alter table tax_calender
    owner to postgres;

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

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

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

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

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

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

create table integration_middleware_logs
(
    id                        bigint generated by default as identity
        constraint ponto_middleware_logs_pkey
            primary key,
    created_at                timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    log_id                    uuid                     default gen_random_uuid(),
    created_at_unixtime_milli numeric,
    route                     text,
    user_id                   uuid,
    request_body              jsonb,
    response_body             jsonb,
    method                    text,
    status_code               smallint,
    request_headers           jsonb,
    request_id                uuid
);

alter table integration_middleware_logs
    owner to postgres;

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

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

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

create table projects
(
    id           bigint generated by default as identity
        primary key,
    created_at   timestamp with time zone default now() not null,
    project_id   uuid                     default gen_random_uuid(),
    name         text,
    icon         text,
    company_id   text,
    description  text,
    resources    json,
    team_id      uuid                     default gen_random_uuid(),
    status       text,
    start_date   numeric,
    target_date  numeric,
    project_lead text
        references users (user_id),
    priority     text
);

alter table projects
    owner to postgres;

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

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

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

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

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

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

create table tax_setting
(
    id                               bigint generated by default as identity
        primary key,
    created_at                       timestamp with time zone default now() not null,
    country                          text,
    tax_id                           uuid                     default gen_random_uuid(),
    tax_code                         text,
    behavior                         text,
    head_office_address_city         text,
    head_office_address_country      text,
    head_office_address_line1        text,
    head_office_address_line2        text,
    head_office_address_postal_code  text,
    head_office_address_state        text,
    head_office_address_house_number numeric,
    livemode                         boolean                  default false,
    status                           text,
    author_id                        text
        references users (user_id),
    tax_setting_id                   uuid                     default gen_random_uuid()
);

alter table tax_setting
    owner to postgres;

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

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

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

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

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

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

create table tax_registration
(
    id                            bigint generated by default as identity
        primary key,
    created_at                    timestamp with time zone default now() not null,
    tax_registration_id           uuid                     default gen_random_uuid(),
    active_from                   numeric,
    object                        text                     default 'tax.registration'::text,
    country                       text,
    country_options               json,
    created                       numeric,
    expires_at                    numeric,
    livemode                      boolean,
    status                        text,
    state                         text,
    registration_type             text,
    kvk_number                    numeric,
    tax_id                        text,
    company_id                    uuid
        references companies (company_id),
    rights_form                   text,
    rights_form_code              text,
    main_activity                 text,
    main_sbi_code                 text,
    main_activity_description     text,
    is_emz                        boolean                  default false,
    is_kor                        boolean                  default false,
    first_fiscal_year             numeric,
    vat_filing_frequency_strategy text                     default 'quarterly'::text
);

alter table tax_registration
    owner to postgres;

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

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

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

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

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

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

create table coupons
(
    id               bigint generated by default as identity
        primary key,
    created_at       timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    coupon_id        uuid                     default gen_random_uuid()
        unique,
    name             text                                                              not null,
    type             text                                                              not null,
    percentage_off   bigint,
    discount_amount  numeric,
    currency         text,
    duration         text                                                              not null,
    months           bigint,
    date_range_limit timestamp with time zone,
    usage_limit      bigint,
    company_id       uuid
        references companies (company_id)
);

comment on column coupons.type is 'either fixed or percentage';

comment on column coupons.discount_amount is 'only needed when discount type is fixed, ie not percentage based';

comment on column coupons.currency is 'only needed when discount type is fixed, ie not percentage based';

comment on column coupons.duration is 'how long the cupon will apply once redeemed (once, forever or a specific amount of months)';

comment on column coupons.date_range_limit is 'latest date the cupon can be redeemed';

comment on column coupons.usage_limit is 'total number of times this cupon can be redeemed, this limit applies across customers so it wont prevent a single customer from redeeming multiple times';

alter table coupons
    owner to postgres;

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

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

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

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

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

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

create table prices
(
    id                        bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default now() not null,
    price_id                  uuid                     default gen_random_uuid(),
    amount                    numeric,
    currency                  text,
    include_tax_in_price      boolean                  default false,
    billing_period            text,
    charge_model              text                     default 'one-off'::text,
    pricing_model             text,
    price_description_private text,
    lookup_key                text,
    unit_quantity             numeric,
    location                  text,
    tax_registration          text,
    product_id                uuid                     default gen_random_uuid(),
    company_id                uuid                     default gen_random_uuid(),
    locked                    boolean
);

alter table prices
    owner to postgres;

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

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

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

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

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

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

create table line_item_invoice
(
    id             bigint generated by default as identity
        primary key,
    created_at     timestamp with time zone default now() not null,
    line_item_id   uuid                     default gen_random_uuid(),
    tax_id         text,
    tax_rate       numeric,
    tax_amount     numeric,
    tax_type       text,
    tax_code       text,
    price_id       uuid,
    product_id     uuid,
    invoice_id     uuid,
    quantity       numeric,
    unit_price     numeric,
    subtotal       numeric,
    total          numeric,
    product_name   text,
    total_fmt      text,
    subtotal_fmt   text,
    unit_price_fmt text,
    tax_inclusive  boolean                  default true,
    tax_exempt     boolean                  default false,
    archived       boolean                  default false
);

alter table line_item_invoice
    owner to postgres;

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

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

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

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

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

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

create table tax_definition
(
    id                         bigint generated by default as identity
        primary key,
    created_at                 timestamp with time zone default now() not null,
    tax_id                     uuid                     default gen_random_uuid(),
    tax_code                   text,
    country_code               text,
    effective_from             numeric,
    effective_till             numeric,
    percent_rate               numeric,
    tax_type                   text,
    definition_last_updated_at numeric,
    source                     text,
    description                text,
    threshold_min              numeric,
    threshold_max              numeric,
    transaction_count_max      numeric,
    translation_key            text
);

alter table tax_definition
    owner to postgres;

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

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

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

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

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

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

create table product_tax_codes
(
    id                  text not null
        primary key,
    type                text,
    description         text,
    name                text,
    product_tax_code_id uuid                     default gen_random_uuid(),
    created_at          timestamp with time zone default (now() AT TIME ZONE 'utc'::text)
);

alter table product_tax_codes
    owner to postgres;

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

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

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

create table invoice_templates
(
    id                   bigint generated by default as identity
        primary key,
    created_at           timestamp with time zone default now() not null,
    invoice_template_id  uuid                     default gen_random_uuid(),
    name                 text,
    memo                 text,
    footer               text,
    custom_fields        json,
    descriptor           text,
    active               boolean                  default true,
    archived             boolean                  default false,
    status               text,
    company_id           uuid
        references companies (company_id),
    note                 text,
    reverse_charged      boolean                  default false,
    has_payment_callback boolean                  default false,
    payment_method_count numeric                  default '0'::numeric,
    payment_methods      json,
    payment_instructions text,
    link_privacy_policy  text,
    link_tos             text,
    currency             text,
    items                json,
    pay_button_href      text,
    descriptor_global    text,
    descriptor_relation  text
);

alter table invoice_templates
    owner to postgres;

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

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

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

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

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

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

create table 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
        unique,
    price_id                uuid,
    trial_end               timestamp with time zone,
    trial_start             timestamp with time zone,
    effective_till          text,
    renewal_at              timestamp with time zone,
    proration_behavior      text,
    billing_cycle_anchor    text,
    cancel_at_period_end    boolean                  default true,
    description             text,
    metadata                json,
    pause_collection        boolean,
    status                  text,
    coupon_id               uuid,
    application_fee_percent numeric                  default '0'::numeric,
    invoice_settings        text,
    collection_method       text,
    discounts               text,
    default_payment_method  text,
    default_source          text,
    on_behalf_of            boolean                  default false,
    billing_tresholds       boolean                  default false,
    currency                text,
    items                   json,
    company_id              uuid,
    contact_id              uuid,
    cycle_duration          text,
    job_created             text,
    latest_invoice_id       uuid,
    cancel_at               timestamp with time zone,
    invoice_due_date        numeric
);

alter table subscriptions
    owner to postgres;

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

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

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

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

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

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

create table payment_methods
(
    id                         bigint generated by default as identity,
    created_at                 timestamp with time zone default now()             not null,
    payment_method_id          uuid                     default gen_random_uuid() not null
        primary key,
    icon_url                   text,
    status                     text,
    company_id                 uuid
        references companies (company_id),
    name                       text,
    type_method                text,
    confirmation_speed         text                     default 'immediate'::text,
    recurring_payments_support boolean                  default true,
    refund_support             boolean                  default true,
    dispute_support            boolean                  default true,
    enabled                    boolean                  default true,
    customer_country           text                     default 'global'::text,
    suitsbooks_account_country text                     default 'all'::text,
    supported_currencies       json                     default '["EUR"]'::json,
    details                    jsonb,
    is_default                 boolean                  default false,
    url                        text
);

alter table payment_methods
    owner to postgres;

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

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

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

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

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

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

create table quote_templates
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default now() not null,
    quote_template_id uuid                     default gen_random_uuid(),
    header            text,
    memo              text,
    footer            text,
    expiration_date   numeric
);

alter table quote_templates
    owner to postgres;

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

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

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

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

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

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

create table tasks
(
    id                        bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default now() not null,
    task_id                   uuid                     default gen_random_uuid(),
    active                    boolean                  default true,
    completed                 boolean                  default false,
    deadline                  numeric,
    title                     text,
    language                  text,
    impact                    text,
    affected_user             text
        references users (user_id),
    description               text,
    view_details_href         text,
    start_href                text,
    company_id                uuid
        references companies (company_id),
    affected_resource_objects json
);

alter table tasks
    owner to postgres;

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

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

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

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

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

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

create table tax_content_docs
(
    id                     bigint generated by default as identity
        primary key,
    created_at             timestamp with time zone default now() not null,
    title                  text,
    country                text,
    language               text,
    tax_type               text,
    tax_type_eng           text,
    fiscal_year            numeric,
    deadline               text,
    category               text,
    tags                   json,
    tags_eng               json,
    description            text,
    description_eng        text,
    content                text,
    source_url             text,
    related_topics         json,
    content_id             uuid                     default gen_random_uuid(),
    related_topics_eng     json,
    updated_at             numeric,
    document_type          text,
    word_count             numeric,
    keywords               json,
    keywords_eng           json,
    file_name              text
        unique,
    file_url               text                     default 'https://suitsbooks.nl/cache/tax_md_files/'::text
        unique,
    referenced_content_ids json,
    referenced_years       json,
    referenced_months      json,
    referenced_quarters    json,
    referenced_dates       json,
    naked_content          text
);

alter table tax_content_docs
    owner to postgres;

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

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

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

create index tax_content_docs_content_id_idx
    on tax_content_docs (content_id);

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

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

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

create table nginx_logs
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default now() not null,
    ip              text,
    request         text,
    time            numeric,
    client_addr     text,
    host            text,
    path            text,
    status          text,
    content_type    text,
    body_bytes_sent numeric,
    http_referrer   text,
    user_agent      text,
    nginx_log_id    uuid                     default gen_random_uuid()
        unique
);

alter table nginx_logs
    owner to postgres;

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

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

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

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

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

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

create table currencies
(
    id          serial
        primary key,
    code        text                                not null
        unique,
    name        text                                not null,
    symbol      text                                not null,
    created_at  timestamp default now(),
    currency_id uuid      default gen_random_uuid() not null
        unique
);

alter table currencies
    owner to postgres;

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

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

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

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

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

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

create table invoice_settings
(
    id                                          bigint generated by default as identity,
    default_currency                            text,
    created_at                                  timestamp with time zone default now()             not null,
    invoice_prefix                              text,
    due_date_days                               bigint                   default '30'::bigint,
    company_id                                  uuid                                               not null
        unique
        references companies (company_id),
    default_note                                text,
    default_footer                              text,
    starting_number                             numeric                  default '1'::numeric,
    year_format                                 text                     default 'show'::text,
    invoice_setting_id                          uuid                     default gen_random_uuid() not null
        primary key
        unique,
    hosted_invoice_page                         boolean                  default true,
    retry_schedule_one_time_invoice_max_retries numeric                  default '3'::numeric,
    invoice_finalization_grace_period_minutes   numeric                  default '60'::numeric,
    include_tax_on_line_items                   boolean                  default true,
    customer_info_left                          boolean                  default false,
    auto_invoice_on_quote_accept                boolean                  default true
);

alter table invoice_settings
    owner to postgres;

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

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

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

create table auth_log
(
    id                        bigint generated by default as identity
        primary key,
    created_at                timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    message                   text,
    user_id                   text,
    session_token             text,
    created_at_unixtime_milli numeric,
    action                    text,
    status                    text,
    ip                        text,
    user_agent                text,
    browser                   text,
    os                        text,
    device                    text,
    cpu                       text,
    route                     text,
    auth_log_id               uuid                     default gen_random_uuid()
        unique
);

alter table auth_log
    owner to postgres;

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

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

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

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

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

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

create table assets
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    created_at_unixtime   numeric,
    asset_id              uuid                     default gen_random_uuid()                not null
        unique,
    name                  text,
    category_id           uuid,
    purchase_price        numeric,
    date_of_commissioning date,
    usage_period_years    smallint,
    residual_value        numeric,
    status                text,
    current_value         numeric,
    monthly_depreciation  numeric,
    company_id            uuid
);

alter table assets
    owner to postgres;

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

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

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

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

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

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

create table asset_categories
(
    id                  bigint generated by default as identity
        primary key,
    created_at          timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    created_at_unixtime numeric,
    company_id          text                                                              not null,
    name                text                                                              not null,
    asset_category_id   uuid                     default gen_random_uuid()                not null
        constraint asset_categories_category_id_key
            unique,
    category_group      text                                                              not null
);

alter table asset_categories
    owner to postgres;

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

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

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

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

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

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

create table currency_rates
(
    id               bigint generated by default as identity
        primary key,
    created_at       timestamp with time zone default now()             not null,
    base             text,
    quote            text,
    close_time       text,
    average_bid      numeric,
    average_ask      numeric,
    high_bid         numeric,
    high_ask         numeric,
    low_bid          numeric,
    low_ask          numeric,
    updated_at       numeric,
    ticker           text
        unique,
    currency_rate_id uuid                     default gen_random_uuid() not null
        unique
);

alter table currency_rates
    owner to postgres;

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

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

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

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

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

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

create table 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,
    job_id                     uuid                     default gen_random_uuid()                not null
        unique,
    progress_percent           numeric                  default '0'::numeric,
    progress_resource          numeric                  default '0'::numeric,
    progress_resource_total    numeric                  default '0'::numeric,
    company_id                 uuid
        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                uuid,
    max_retry_count            bigint,
    job_fail_count             bigint                   default '0'::bigint                      not null
);

alter table jobs
    owner to postgres;

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

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

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

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

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

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

create table files
(
    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),
    filename              text,
    url                   text,
    public                boolean                  default false,
    url_private           text,
    mime                  text,
    is_directory          boolean                  default false,
    extension             text,
    deleted               boolean                  default false,
    file_id               uuid                     default gen_random_uuid() not null
        unique,
    real_file_path        text,
    masked_file_path      text,
    object                text,
    user_id_uploader      text
        references users (user_id),
    uploaded_at           numeric,
    updated_at            numeric,
    hash                  text
        unique,
    upload_source         text,
    file_url              text,
    size                  numeric,
    aurora_processed      boolean                  default false,
    aurora_description    text,
    aurora_record_id      uuid,
    possible_receipt      boolean                  default false,
    aurora_should_process boolean                  default false,
    document_type         file_document_type,
    masked_name           text,
    file_key              text,
    aurora_errored        boolean                  default false,
    aurora_error          text
);

comment on column files.document_type is 'Type of document - Receipt, Invoice, or Mail. Nullable to allow files without specific document types';

alter table files
    owner to postgres;

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

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

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

create index idx_files_document_type
    on files (document_type);

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

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

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

create table sessions
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default now() not null,
    user_id       text,
    updated_at    timestamp with time zone,
    factor_id     uuid                     default gen_random_uuid(),
    aal           text,
    user_agent    text,
    ip            text,
    tag           text,
    refreshed_at  timestamp with time zone,
    not_after     timestamp with time zone,
    session_id    uuid
        unique,
    session_token text
);

alter table sessions
    owner to postgres;

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

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

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

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

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

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

create table auth_sessions
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default now() not null,
    user_id       text,
    updated_at    timestamp with time zone,
    factor_id     uuid                     default gen_random_uuid(),
    aal           text,
    user_agent    text,
    ip            text,
    tag           text,
    refreshed_at  timestamp with time zone,
    not_after     timestamp with time zone,
    session_id    uuid
        unique,
    session_token text,
    mfa_verified  boolean                  default false not null
);

alter table auth_sessions
    owner to postgres;

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

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

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

create index auth_sessions_session_token_idx
    on auth_sessions (session_token);

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

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

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

create table tax_documents
(
    id                   bigint generated by default as identity
        primary key,
    created_at           timestamp with time zone default now() not null,
    url                  text,
    country              text,
    name                 text,
    fiscal_year_validity numeric                  default '2025'::numeric,
    downloads            text,
    description          text
);

alter table tax_documents
    owner to postgres;

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

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

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

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

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

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

create table rss_feeds
(
    id         bigint generated by default as identity
        primary key,
    created_at timestamp with time zone default now() not null,
    url        text,
    name       text,
    provider   text
);

alter table rss_feeds
    owner to postgres;

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

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

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

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

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

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

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

alter table stripe_credentials
    owner to postgres;

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

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

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

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

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

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

create table stripe_customers
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default now() not null,
    object            text,
    address           json,
    balance           numeric,
    created           numeric,
    delinquent        boolean,
    description       text,
    discount          text,
    email             text,
    invoice_prefix    text,
    invoice_settings  json,
    livemode          boolean,
    metadata          json,
    name              text,
    phone             text,
    shipping          text,
    preferred_locales text,
    tax_exempt        text,
    test_clock        text,
    currency          text,
    default_source    text,
    customer_id       text
);

alter table stripe_customers
    owner to postgres;

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

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

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

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

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

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

create table stripe_charges
(
    id                              bigint generated by default as identity
        primary key,
    created_at                      timestamp with time zone default now() not null,
    amount                          numeric,
    object                          text,
    charge_id                       text,
    amount_captured                 numeric,
    amount_refunded                 numeric,
    application                     text,
    application_fee                 text,
    application_fee_amount          text,
    balance_transaction             text,
    billing_details                 json,
    email                           text,
    name                            text,
    phone                           text,
    calculated_statement_descriptor text,
    captured                        boolean,
    created                         numeric,
    currency                        text,
    customer                        text,
    description                     text,
    destination                     text,
    dispute                         text,
    disputed                        boolean,
    failure_balance_transaction     text,
    failure_code                    text,
    failure_message                 text,
    fraud_details                   json,
    invoice                         text,
    livemode                        boolean,
    metadata                        json,
    on_behalf_of                    text,
    "order"                         text,
    outcome                         json,
    paid                            boolean,
    payment_intent                  text,
    payment_method                  text,
    payment_method_details          json,
    radar_options                   json,
    receipt_email                   text,
    receipt_number                  text,
    receipt_url                     text,
    refunded                        boolean,
    review                          text,
    shipping                        text,
    source                          text,
    source_transfer                 text,
    statement_descriptor            text,
    statement_descriptor_suffix     text,
    status                          text,
    transfer_data                   text,
    transfer_group                  text,
    company_id                      uuid
        references companies (company_id),
    stripe_credential               text
);

alter table stripe_charges
    owner to postgres;

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

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

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

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

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

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

create table yuki_companies
(
    id                         bigint generated by default as identity
        primary key,
    created_at                 timestamp with time zone default now() not null,
    importer_company_id        uuid
        references companies (company_id),
    name                       text,
    description                text,
    key_contact_person         text,
    address_1                  text,
    address_2                  text,
    pc                         text,
    city                       text,
    country                    text,
    postal_address_1           text,
    postal_address_2           text,
    postal_code_postal_address text,
    city_postal_address        text,
    phone                      text,
    fax                        text,
    email_address              text,
    website                    text,
    logo                       text,
    notes                      text,
    contact_code               text,
    vat_number                 text,
    coc_number                 numeric,
    tags                       json,
    heading                    text,
    email_address_private      text,
    bank_account               text
);

alter table yuki_companies
    owner to postgres;

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

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

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

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

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

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

create table yuki_persons
(
    id                         bigint generated by default as identity
        primary key,
    created_at                 timestamp with time zone default now() not null,
    importer_company_id        uuid
        references companies (company_id),
    name                       text,
    job_title                  text,
    company                    text,
    address_1                  text,
    address_2                  text,
    pc                         text,
    city                       text,
    country                    text,
    mobile_phone               text,
    phone_private              text,
    fax_private                text,
    email_address_work         text,
    email_address_private      text,
    website                    text,
    photo                      text,
    business_card              text,
    notes                      text,
    postal_address_line_1      text,
    postal_address_line_2      text,
    postal_code_postal_address text,
    extra_address_line_1       text,
    extra_address_line_2       text,
    postal_code_work           text,
    city_work                  text,
    phone                      text,
    mobile                     text,
    fax                        text,
    tags                       json,
    first_name                 text,
    infixes                    text,
    last_name                  text,
    initials                   text,
    heading                    text,
    label                      text,
    nickname                   text,
    gender                     text,
    date_of_birth              text,
    contact_code               text,
    vat_number                 text,
    coc_number                 numeric,
    bank_account               text
);

alter table yuki_persons
    owner to postgres;

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

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

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

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

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

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

create table invoice_views
(
    id                 bigint generated by default as identity
        primary key,
    created_at         timestamp with time zone default now() not null,
    view_id            uuid                     default gen_random_uuid(),
    invoice_id         uuid,
    viewer_hash        text,
    ip_address         text,
    user_agent         text,
    host               text,
    lat                numeric,
    lon                numeric,
    country            text,
    window_data        json,
    locale             text,
    device_memory      text,
    app_code_name      text,
    gpu                text,
    logical_processors text,
    language           text,
    languages          json,
    pdf_viewer_enabled boolean                  default false,
    platform           text,
    plugins            json,
    product            text,
    product_sub        text,
    mobile             boolean                  default false,
    virtual_keyboard   text,
    webdriver          boolean                  default false,
    time_zone          text,
    "current_time"     text,
    "current_date"     text,
    view_hash          text,
    time               numeric,
    page               text,
    resource_id        text,
    user_id            text,
    known_user         boolean                  default false,
    email              text
);

alter table invoice_views
    owner to postgres;

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

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

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

create index invoice_views_invoice_id_idx
    on invoice_views (invoice_id);

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

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

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

create table charts
(
    id                     bigint generated by default as identity
        primary key,
    created_at             timestamp with time zone default now() not null,
    table_name             text,
    title                  text,
    color                  text,
    target_column          text,
    calculation_strategy   text,
    dragonfly_key          text,
    chart_type             text,
    x_axis_group_by        text,
    has_label              boolean                  default false,
    label_color_body       text,
    label_color_text       text,
    is_currency            boolean                  default false,
    currency_number_format text,
    show_last_updated_at   boolean                  default false,
    is_percentage          boolean                  default false,
    currency               text,
    chart_id               uuid                     default gen_random_uuid(),
    enabled                boolean                  default false,
    data_endpoint          text,
    eq_column              text,
    eq_value               text
);

comment on table charts is 'Holds global configs for the chart generator';

alter table charts
    owner to postgres;

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

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

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

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

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

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

create table sql_queries
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default now()             not null,
    query             text,
    name              text,
    description       text,
    tables            json,
    schema            text,
    variables         json,
    total_ran         numeric                  default '0'::numeric,
    query_id          uuid                     default gen_random_uuid() not null
        unique,
    title             text,
    data_type         text                     default 'currency'::text,
    translation_key   text,
    resource_provider text                     default 'base'::text,
    dangerous         boolean                  default false,
    decimals          numeric                  default '2'::numeric
);

alter table sql_queries
    owner to postgres;

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

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

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

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

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

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

create table moneybird_tokens
(
    id            bigint generated by default as identity
        primary key,
    created_at    numeric not null,
    expires_at    numeric,
    user_id       text
        references users (user_id),
    access_token  text,
    refresh_token text,
    scope         text,
    token_type    text
);

alter table moneybird_tokens
    owner to postgres;

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

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

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

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

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

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

create table moneybird_adnimistrations
(
    id                  bigint generated by default as identity
        constraint moneybird_adnimistraion_pkey
            primary key,
    created_at          timestamp with time zone default now() not null,
    administration_id   bigint
        constraint moneybird_adnimistraions_administration_id_key
            unique,
    name                text,
    language            text,
    currency            text,
    country             text,
    time_zone           text,
    access              text,
    suspended           text,
    period_locked_until jsonb
);

alter table moneybird_adnimistrations
    owner to postgres;

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

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

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

create table moneybird_contact_people
(
    id                bigint generated by default as identity
        primary key,
    contact_people_id text,
    contact_id        text,
    administration_id bigint,
    firstname         text,
    lastname          text,
    phone             text,
    email             text,
    department        text,
    created_at        timestamp with time zone not null,
    updated_at        timestamp with time zone,
    version           bigint
);

alter table moneybird_contact_people
    owner to postgres;

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

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

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

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

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

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

create table yuki_transactions
(
    id                 bigint generated by default as identity
        primary key,
    created_at         timestamp with time zone default now() not null,
    company_id         uuid                     default gen_random_uuid(),
    datum              text,
    jaar               text,
    periode            text,
    code               text,
    grootboekrekening  text,
    type               text,
    attribuut          text,
    bedrag             text,
    relatie            text,
    administratie      text,
    referentie         text,
    omschrijving       text,
    project            text,
    transactie         text,
    file_url           text,
    iban               text,
    bic                text,
    name               text,
    kenmerk            text,
    transaction_number text,
    order_number       text,
    fx_conversion      text,
    betalings_kenmerk  text,
    fb_ads_ref         text,
    refund             boolean                  default false,
    incassant          text,
    machtiging         text
);

alter table yuki_transactions
    owner to postgres;

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

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

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

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

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

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

create table moneybird_contacts
(
    id                          bigint generated by default as identity
        primary key,
    contact_id                  text                           not null,
    administration_id           bigint,
    company_name                text,
    firstname                   text,
    lastname                    text,
    address1                    text,
    address2                    text,
    zipcode                     text,
    city                        text,
    country                     text,
    phone                       text,
    delivery_method             text,
    customer_id                 text,
    tax_number                  text,
    chamber_of_commerce         text,
    bank_account                text,
    is_trusted                  boolean,
    max_transfer_amount         numeric,
    attention                   text,
    email                       text,
    email_ubl                   boolean,
    send_invoices_to_attention  text,
    send_invoices_to_email      text,
    send_estimates_to_attention text,
    send_estimates_to_email     text,
    sepa_active                 boolean,
    sepa_iban                   text,
    sepa_iban_account_name      text,
    sepa_bic                    text,
    sepa_mandate_id             text,
    sepa_mandate_date           date,
    sepa_sequence_type          text,
    credit_card_number          text,
    credit_card_reference       text,
    credit_card_type            text,
    tax_number_validated_at     date,
    tax_number_valid            boolean,
    invoice_workflow_id         text,
    estimate_workflow_id        text,
    si_identifier               text,
    si_identifier_type          text,
    moneybird_payments_mandate  boolean,
    created_at                  timestamp with time zone,
    updated_at                  timestamp with time zone,
    version                     bigint,
    sales_invoices_url          text,
    notes                       jsonb[],
    custom_fields               jsonb,
    archived                    boolean,
    moneybird_contact_id        uuid default gen_random_uuid() not null
        unique
);

comment on table moneybird_contacts is 'This is still WIP, some columns might have wrong datatype';

alter table moneybird_contacts
    owner to postgres;

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

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

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

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

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

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

create table yuki_addresses
(
    id                   bigint generated by default as identity
        primary key,
    created_at           timestamp default now() not null,
    naam                 text,
    voornaam             text,
    middelste_naam       text,
    achternaam           text,
    bijnaam              text,
    aanhef               text,
    initialen            text,
    bedrijf              text,
    afdeling             text,
    functie              text,
    werkadres_straat     text,
    werkadres_2_straat   text,
    werkadres_plaats     text,
    werkadres_postcode   text,
    land_regio_werk      text,
    huisadres_straat     text,
    huisadres_straat_2   text,
    huisadres_plaats     text,
    huisadres_postcode   text,
    land_regio_thuis     text,
    ander_adres_straat   text,
    ander_adres_straat_2 text,
    ander_adres_plaats   text,
    ander_adres_postcode text,
    fax_op_werk          text,
    telefoon_op_werk     text,
    fax_thuis            text,
    telefoon_thuis       text,
    mobiele_telefoon     text,
    naam_assistent       text,
    verjaardag           text,
    e_mailadres          text,
    e_mailadres_2        text,
    geslacht             text,
    sofinummer           text,
    naam_manager         text,
    notities             text,
    webpagina            text,
    etiket               text,
    code                 text,
    yuki_address_id      uuid      default gen_random_uuid()
);

alter table yuki_addresses
    owner to postgres;

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

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

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

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

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

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

create table blog_items
(
    id               bigint generated by default as identity
        primary key,
    created_at       timestamp with time zone default now() not null,
    title            text,
    author_name      text,
    user_id          text
        references users (user_id),
    content          text,
    content_json     json,
    url              text,
    content_id       text,
    updated_at       numeric,
    blog_id          uuid                     default gen_random_uuid(),
    slug             text
        unique,
    autosave         json,
    autosave_content text,
    description      text,
    headings         json,
    og_image         text,
    blocks           json,
    time             numeric,
    version          text
);

alter table blog_items
    owner to postgres;

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

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

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

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

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

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

create table user_kpi_canvas
(
    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),
    query_id   uuid
        references sql_queries (query_id),
    params     json                     default '["user_id"]'::json
);

alter table user_kpi_canvas
    owner to postgres;

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

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

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

create index user_kpi_canvas_user_id_idx
    on user_kpi_canvas (user_id);

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

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

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

create table email_templates
(
    id                bigint generated by default as identity,
    email_template_id uuid                     default gen_random_uuid() not null,
    company_id        uuid
        references companies (company_id),
    name              text                                               not null,
    type              text                                               not null,
    subject           text                                               not null,
    body              text                                               not null,
    is_default        boolean                  default false,
    is_global         boolean                  default false,
    created_at        timestamp with time zone default now()             not null,
    primary key (id, email_template_id)
);

alter table email_templates
    owner to postgres;

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

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

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

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

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

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

create table loan_types
(
    id                   bigint generated by default as identity
        primary key,
    created_at           timestamp with time zone default now()             not null,
    country_code         text,
    key                  text,
    loan_type_id         uuid                     default gen_random_uuid() not null
        unique,
    title                text,
    description          text,
    docs_url             text,
    longer_than_one_year boolean                  default false,
    code                 text,
    slug                 text
);

alter table loan_types
    owner to postgres;

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

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

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

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

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

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

create table invoice_groups
(
    id                bigint generated by default as identity,
    invoice_group_id  uuid                     default gen_random_uuid() not null,
    invoice_ids       text                                               not null,
    status            text,
    paid              boolean                  default false,
    created_at        timestamp with time zone default now()             not null,
    email_template_id uuid,
    primary key (id, invoice_group_id)
);

alter table invoice_groups
    owner to postgres;

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

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

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

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

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

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

create table objects
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default now()             not null,
    object_type     text,
    object_id       uuid                     default gen_random_uuid() not null
        unique,
    name            text,
    type            text,
    attribute_count numeric                  default '0'::numeric,
    activated       boolean                  default false,
    slug            text                                               not null
        unique,
    singular_noun   text,
    plurar_noun     text,
    identifier      text,
    description     text,
    author_user_id  text
        references users (user_id),
    icon            text,
    color           text,
    attributes      json,
    system_object   boolean                  default false,
    sql_table       text
);

alter table objects
    owner to postgres;

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

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

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

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

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

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

create table object_attribute
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default now() not null,
    object_id         uuid
        references objects (object_id),
    name              text,
    description       text,
    default_value     text,
    type              text,
    author_user_id    text
        references users (user_id),
    global            boolean                  default false,
    unique_constraint boolean                  default false,
    attribute_id      uuid                     default gen_random_uuid()
        unique,
    slug              text
);

alter table object_attribute
    owner to postgres;

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

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

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

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

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

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

create table changelog
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default now() not null,
    title         text,
    version_major numeric                  default '0'::numeric,
    version_minor numeric                  default '0'::numeric,
    version_patch numeric                  default '0'::numeric,
    description   text,
    og_image      text,
    og_title      text,
    thumbnail     text,
    fixes         text,
    improvements  text,
    new           text,
    release_date  numeric,
    published     boolean                  default false,
    changelog_id  uuid                     default gen_random_uuid()
        unique
);

alter table changelog
    owner to postgres;

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

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

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

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

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

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

create table sidebar_layout
(
    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),
    items                     json,
    pinned                    json,
    recents                   json,
    updated_at                numeric,
    view_key                  text                                   not null
        unique,
    company_switcher_position text                     default 'bottom'::text,
    show_objects_in_recents   boolean                  default false
);

alter table sidebar_layout
    owner to postgres;

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

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

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

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

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

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

create table balance_sheets2
(
    id                     bigint generated by default as identity
        constraint balance_sheets_pkey
            primary key,
    created_at             timestamp with time zone default now()             not null,
    company_id             uuid
        constraint balance_sheets_company_id_fkey
            references companies (company_id),
    accounting_period      text,
    open_accounting_period text,
    currency               text,
    account_type           text,
    account                text,
    gl_code                text,
    starting_balance       numeric,
    ending_balance         numeric,
    net_change             numeric,
    amount_inflow          numeric,
    amount_outflow         numeric,
    balance_sheet_id       uuid                     default gen_random_uuid() not null
        constraint balance_sheets_balance_sheet_id_key
            unique
);

alter table balance_sheets2
    owner to postgres;

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

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

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

create table income_types
(
    id             bigint generated by default as identity
        primary key,
    created_at     timestamp with time zone default now() not null,
    country_code   text                     default 'NL'::text,
    name           text,
    income_type_id uuid                     default gen_random_uuid()
);

alter table income_types
    owner to postgres;

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

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

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

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

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

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

create table cmdk
(
    id             bigint generated by default as identity
        primary key,
    created_at     timestamp with time zone default now() not null,
    href           text,
    icon           text,
    text           text,
    shortcut       text,
    cmdk_id        uuid                     default gen_random_uuid(),
    parent         text,
    top_level_item boolean                  default true
);

alter table cmdk
    owner to postgres;

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

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

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

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

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

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

create table permissions_matrix
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default now() not null,
    action        text,
    description   text,
    auth_index    numeric                  default '0'::numeric,
    read          boolean                  default false,
    write         boolean                  default false,
    delete        boolean                  default false,
    "create"      boolean                  default false,
    update        boolean                  default false,
    permission_id uuid                     default gen_random_uuid()
);

alter table permissions_matrix
    owner to postgres;

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

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

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

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

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

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

create table sbi_codes_nl
(
    "SBI"         bigint,
    "Description" text
);

alter table sbi_codes_nl
    owner to postgres;

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

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

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

create table rgs
(
    id          bigint generated by default as identity
        primary key,
    created_at  timestamp with time zone default now() not null,
    rgs_code    text,
    description text,
    rgs_nr      numeric
        unique,
    nv          numeric,
    cover_code  text,
    d_c         text,
    zzp         text,
    ez          text,
    bv          text,
    sv          text,
    branch      text,
    bw_2        text
);

alter table rgs
    owner to postgres;

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

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

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

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

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

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

create table ponto_webhook_logs
(
    id         bigint generated by default as identity
        primary key,
    created_at timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    webhook_id uuid,
    log_id     uuid                     default gen_random_uuid(),
    file_name  text,
    message    text,
    status     text
);

alter table ponto_webhook_logs
    owner to postgres;

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

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

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

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

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

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

create table merchants
(
    id                     bigint generated by default as identity
        primary key,
    created_at             timestamp with time zone default now() not null,
    name                   text,
    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_country        text,
    language               text,
    industry               text,
    phone_number           text,
    slug                   text
        unique,
    enabled                boolean                  default true,
    country                text,
    public                 boolean                  default true,
    vat_id                 text,
    billing_city           text,
    billing_state          text,
    billing_province       text,
    company_number         text,
    company_number_type    text,
    verified               boolean                  default false
);

alter table merchants
    owner to postgres;

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

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

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

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

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

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

create table audit_log_actions
(
    id                  bigint generated by default as identity
        primary key,
    created_at          timestamp with time zone default now()             not null,
    name                text,
    description         text,
    affected_resource   text,
    icon                text                     default 'null'::text,
    message_template    text                     default 'null'::text,
    audit_log_action_id uuid                     default gen_random_uuid() not null
        unique
);

alter table audit_log_actions
    owner to postgres;

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

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

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

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

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

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

create table user_view_settings
(
    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),
    company_switcher_position                 text                     default 'bottom'::text,
    sidebar_pinned                            json,
    tables_extra_side_padding                 boolean                  default false,
    rows_per_page_invoices                    numeric                  default '25'::numeric,
    rows_per_page_contacts                    numeric                  default '25'::numeric,
    rows_per_page_transactions                numeric                  default '25'::numeric,
    disable_definition_tooltips               boolean                  default false,
    locale                                    text                     default 'en'::text,
    debug_mode                                boolean                  default false,
    test_mode                                 boolean                  default false,
    theme                                     text,
    default_theme                             text,
    default_company_id                        uuid
        references companies (company_id),
    sidebar_show_recents                      boolean                  default true,
    rows_per_page_products                    numeric                  default '25'::numeric,
    format_big_numbers_with_letter_suffix     boolean                  default false,
    time_format                               text                     default '24h'::text,
    table_invoices_sort_by                    text                     default 'invoice_nr'::text,
    close_mobile_sidebar_after_company_switch boolean                  default true,
    aurora_extra_diagnostics                  boolean                  default false,
    linear_bug_reporting                      boolean                  default false,
    linear_bug_lists                          boolean                  default false,
    aurora_experimental                       boolean                  default false,
    table_transactions_sort_by                text
);

alter table user_view_settings
    owner to postgres;

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

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

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

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

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

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

create table user_permission_scopes
(
    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),
    scope                    text,
    global                   boolean                  default false,
    company_id               uuid
        references companies (company_id),
    user_permission_scope_id uuid                     default gen_random_uuid(),
    enabled                  boolean                  default false
);

alter table user_permission_scopes
    owner to postgres;

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

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

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

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

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

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

create table company_invite_codes
(
    id                     bigint generated by default as identity
        primary key,
    created_at             timestamp with time zone default now()             not null,
    invite_code            text                                               not null
        unique,
    company_id             uuid
        references companies (company_id),
    max_uses               numeric                  default '1'::numeric,
    exp_date               numeric                  default '0'::numeric,
    created_by_user_id     text
        references users (user_id),
    time                   numeric                  default '0'::numeric,
    company_invite_code_id uuid                     default gen_random_uuid() not null
        unique
);

alter table company_invite_codes
    owner to postgres;

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

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

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

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

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

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

create table banking_recipients
(
    id                   bigint generated by default as identity
        constraint banking_recipients_v2_pkey
            primary key,
    created_at           timestamp with time zone default now()             not null,
    company_id           uuid
        constraint banking_recipients_v2_company_id_fkey
            references companies (company_id),
    name                 text,
    iban                 text,
    contact_id           uuid
        constraint banking_recipients_v2_contact_id_fkey
            references contacts (contact_id),
    banking_recipient_id uuid                     default gen_random_uuid() not null
        unique
);

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

alter table banking_recipients
    owner to postgres;

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

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

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

create table domains
(
    id                    bigint generated by default as identity
        constraint wildcard_router_pkey
            primary key,
    created_at            timestamp with time zone default now()             not null,
    wildcard              text                                               not null
        constraint wildcard_router_wildcard_key
            unique,
    name                  text,
    logo                  text,
    company_id            uuid
        constraint wildcard_router_company_id_fkey
            references companies (company_id),
    background_image      text,
    main_language         text,
    url                   text,
    icon                  text,
    slogan                text,
    domain_branding       boolean                  default false,
    og_logo_url           text,
    og_background_color   text,
    override_image_og     boolean                  default false,
    block_sign_up         boolean                  default false,
    domain_id             uuid                     default gen_random_uuid() not null
        unique,
    allowed_email_domains json,
    relay_email           text
);

alter table domains
    owner to postgres;

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

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

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

create table versioning
(
    id              bigint generated by default as identity
        primary key,
    created_at      timestamp with time zone default now()             not null,
    service_name    text                                               not null
        unique,
    version_minor   numeric                  default '0'::numeric,
    version_major   numeric                  default '0'::numeric,
    version_patch   numeric                  default '0'::numeric,
    domain          text,
    description     text,
    project_name    text
        unique,
    last_deployment numeric                  default '0'::numeric,
    port            numeric,
    online          boolean                  default false,
    versioning_id   uuid                     default gen_random_uuid() not null
        unique
);

alter table versioning
    owner to postgres;

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

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

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

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

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

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

create table daemon_subscriptions_config
(
    id                            bigint generated by default as identity
        primary key,
    created_at                    timestamp with time zone default now() not null,
    daemon_enabled                boolean,
    interval_seconds              numeric                  default '3600'::numeric,
    daemon_user_id                text
        references users (user_id),
    daemon_organization_id        text
        references organizations (organization_id),
    daemon_company_id             uuid
        references companies (company_id),
    daemon_subscription_config_id uuid                     default gen_random_uuid()
        unique,
    concurency_limit              bigint
);

alter table daemon_subscriptions_config
    owner to postgres;

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

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

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

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

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

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

create table definition_tooltips
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now() not null,
    author_user_id        text
        references users (user_id),
    definition_tooltip_id uuid                     default gen_random_uuid()
        unique,
    title                 text,
    key                   text
        unique,
    description           text,
    href                  text,
    country_code          text,
    language_code         text                     default 'EN'::text,
    translation_key       text
);

alter table definition_tooltips
    owner to postgres;

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

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

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

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

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

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

create table notification_types
(
    id                   bigint generated by default as identity
        primary key,
    created_at           timestamp with time zone default now()             not null,
    enabled              boolean                  default false,
    action               text,
    hierarchy_scope      text                     default 'company'::text,
    title                text,
    description          text,
    resource_type        text,
    permission_scope     text,
    slug                 text,
    notification_type_id uuid                     default gen_random_uuid() not null
        unique,
    column_scope         text
);

alter table notification_types
    owner to postgres;

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

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

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

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

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

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

create table mollie_accounts
(
    id                          bigint generated by default as identity
        primary key,
    created_at                  timestamp with time zone default now()             not null,
    name                        text,
    company_id                  uuid
        references companies (company_id),
    mollie_account_id           uuid                     default gen_random_uuid() not null
        unique,
    revoked                     boolean                  default false,
    status                      text                     default 'pending'::text,
    connected_at                numeric,
    user_id                     text
        references users (user_id),
    api_key                     text,
    api_key_encrypted           text,
    active                      boolean                  default true,
    apikeys_read                boolean                  default false,
    apikeys_write               boolean                  default false,
    balance_reports_read        boolean                  default false,
    balances_read               boolean                  default false,
    clients_write               boolean                  default false,
    customers_read              boolean                  default false,
    customers_write             boolean                  default false,
    external_accounts_read      boolean                  default false,
    external_accounts_write     boolean                  default false,
    invoices_read               boolean                  default false,
    mandates_read               boolean                  default false,
    mandates_write              boolean                  default false,
    onboarding_read             boolean                  default false,
    onboarding_write            boolean                  default false,
    orders_read                 boolean                  default false,
    orders_write                boolean                  default false,
    organizations_read          boolean                  default false,
    organizations_write         boolean                  default false,
    payment_links_read          boolean                  default false,
    payment_linsks_write        boolean                  default false,
    payments_read               boolean                  default false,
    payments_write              boolean                  default false,
    persons_read                boolean                  default false,
    persons_write               boolean                  default false,
    profiles_read               boolean                  default false,
    profiles_write              boolean                  default false,
    refunds_read                boolean                  default false,
    refunds_write               boolean                  default false,
    settlements_read            boolean                  default false,
    shipments_read              boolean                  default false,
    shipments_write             boolean                  default false,
    subscriptions_read          boolean                  default false,
    subscriptions_write         boolean                  default false,
    terminals_read              boolean                  default false,
    terminals_write             boolean                  default false,
    webhook_subscriptions_read  boolean                  default false,
    webhook_subscriptions_write boolean                  default false,
    balance_transfers_read      boolean                  default false,
    balance_transfers_write     boolean                  default false,
    permission_scopes           text                     default ''::text,
    organization_access_token   text,
    last_sync_at                numeric                  default '0'::numeric,
    primary_iban                text,
    primary_beneficiary         text,
    profile_id                  text,
    live_api_key                text,
    test_api_key                text
);

alter table mollie_accounts
    owner to postgres;

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

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

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

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

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

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

create table mollie_payment_methods
(
    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_method_id uuid                     default gen_random_uuid() not null
        constraint mollie_payment_methods_payment_method_id_key
            unique
);

alter table mollie_payment_methods
    owner to postgres;

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

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

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

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

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

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

create table mollie_refunds
(
    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_refund_id  uuid                     default gen_random_uuid() not null
        unique
);

alter table mollie_refunds
    owner to postgres;

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

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

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

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

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

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

create table mollie_chargebacks
(
    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_chargeback_id uuid                     default gen_random_uuid() not null
        constraint mollie_chargebacks_chargeback_id_key
            unique
);

alter table mollie_chargebacks
    owner to postgres;

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

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

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

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

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

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

create table mollie_customers
(
    id                 bigint generated by default as identity
        primary key,
    created_at         timestamp with time zone default now()             not null,
    mollie_account_id  uuid                                               not null
        unique
        references mollie_accounts (mollie_account_id),
    mollie_customer_id uuid                     default gen_random_uuid() not null
        unique
);

alter table mollie_customers
    owner to postgres;

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

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

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

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

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

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

create table mollie_invoices
(
    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_invoice_id uuid                     default gen_random_uuid() not null
        unique
);

alter table mollie_invoices
    owner to postgres;

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

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

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

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

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

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

create table mollie_payments
(
    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_id          uuid                     default gen_random_uuid() not null
        unique,
    amount_value               numeric                  default '0'::numeric,
    amount_currency            text                     default 'EUR'::text,
    amount_refunded_value      numeric                  default '0'::numeric,
    amount_refunded_currency   text                     default 'EUR'::text,
    amount_remaining_value     numeric                  default '0'::numeric,
    amount_remaining_currency  text                     default 'EUR'::text,
    country_code               text,
    description                text,
    details                    json,
    consumer_account           text,
    consumer_bic               text,
    consumer_name              text,
    payment_id                 text
        unique,
    locale                     text,
    metadata                   json,
    method                     text,
    mode                       text,
    paid_at                    numeric,
    profile_id                 text,
    redirect_url               text,
    resource                   text,
    sequence_type              text,
    settlement_amount_value    numeric                  default '0'::numeric,
    settlement_amount_currency text                     default 'EUR'::text,
    status                     text,
    webhook_url                text,
    promoted_to_tx             boolean                  default false,
    transaction_id             text
);

alter table mollie_payments
    owner to postgres;

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

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

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

create index mollie_payments_created_at_idx
    on mollie_payments (created_at);

create index idx_mollie_payments_payment_id
    on mollie_payments (payment_id);

create index idx_mollie_payments_status
    on mollie_payments (status);

create index idx_mollie_payments_company
    on mollie_payments (mollie_account_id);

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

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

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

create table mollie_balances
(
    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_balance_id uuid                     default gen_random_uuid() not null
        unique,
    "primary"         boolean                  default false
);

alter table mollie_balances
    owner to postgres;

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

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

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

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

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

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

create table mollie_orders
(
    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_order_id   uuid                     default gen_random_uuid() not null
        unique
);

alter table mollie_orders
    owner to postgres;

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

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

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

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

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

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

create table mollie_organizations
(
    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_organization_id uuid                     default gen_random_uuid() not null
        unique
);

alter table mollie_organizations
    owner to postgres;

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

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

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

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

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

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

create table mollie_persons
(
    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_person_id  uuid                     default gen_random_uuid() not null
        unique
);

alter table mollie_persons
    owner to postgres;

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

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

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

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

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

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

create table stripe_accounts
(
    id                                       bigint generated by default as identity
        primary key,
    created_at                               timestamp with time zone default now()             not null,
    stripe_account_id                        uuid                     default gen_random_uuid() not null
        unique,
    api_key                                  text,
    api_key_encrypted                        text,
    enabled                                  boolean                  default false,
    company_id                               uuid
        references companies (company_id),
    label                                    text,
    added_by_user_id                         text
        references users (user_id),
    v2_core_account_person_created           boolean                  default false,
    v2_core_acount_person_deleted            boolean                  default false,
    v2_core_acount_person_updated            boolean                  default false,
    account_updated                          boolean                  default false,
    balance_available                        boolean                  default false,
    charge_captured                          boolean                  default false,
    charge_expired                           boolean                  default false,
    charge_failed                            boolean                  default false,
    charge_pending                           boolean                  default false,
    charge_refunded                          boolean                  default false,
    charge_created                           boolean                  default false,
    charge_succeeded                         boolean                  default false,
    charge_updated                           boolean                  default false,
    charge_dispute_created                   boolean                  default false,
    charge_dispute_closed                    boolean                  default false,
    charge_dispute_funds_reinstated          boolean                  default false,
    charge_dispute_funds_withdrawn           boolean                  default false,
    charge_dispute_updated                   boolean                  default false,
    charge_refund_updated                    boolean                  default false,
    refund_updated                           boolean                  default false,
    checkout_session_completed               boolean                  default false,
    checkout_session_expired                 boolean                  default false,
    coupon_created                           boolean                  default false,
    coupon_deleted                           boolean                  default false,
    coupon_updated                           boolean                  default false,
    customer_created                         boolean                  default false,
    customer_updated                         boolean                  default false,
    customer_deleted                         boolean                  default false,
    customer_tax_id_created                  boolean                  default false,
    customer_tax_id_deleted                  boolean                  default false,
    customer_tax_id_updated                  boolean                  default false,
    invoice_created                          boolean                  default false,
    invoice_deleted                          boolean                  default false,
    invoice_finalization_failed              boolean                  default false,
    invoice_finalized                        boolean                  default false,
    invoice_marked_uncollectible             boolean                  default false,
    invoice_overdue                          boolean                  default false,
    invoice_overpaid                         boolean                  default false,
    invoice_paid                             boolean                  default false,
    invoice_payment_action_required          boolean                  default false,
    invoice_payment_failed                   boolean                  default false,
    invoice_payment_succeeded                boolean                  default false,
    invoice_sent                             boolean                  default false,
    invoice_upcoming                         boolean                  default false,
    invoice_updated                          boolean                  default false,
    invoice_voided                           boolean                  default false,
    invoice_will_be_due                      boolean                  default false,
    invoiceitem_created                      boolean                  default false,
    invoiceitem_deleted                      boolean                  default false,
    payment_intent_amount_capturable_updated boolean                  default false,
    payment_intent_canceled                  boolean                  default false,
    payment_intent_created                   boolean                  default false,
    payment_intent_partially_refunded        boolean                  default false,
    payment_intent_payment_failed            boolean                  default false,
    payment_intent_processing                boolean                  default false,
    payment_intent_requries_action           boolean                  default false,
    payment_intent_succeeded                 boolean                  default false,
    payment_link_created                     boolean                  default false,
    payment_link_updated                     boolean                  default false,
    payout_canceled                          boolean                  default false,
    payout_created                           boolean                  default false,
    payout_failed                            boolean                  default false,
    payout_paid                              boolean                  default false,
    payout_reconciliation_completed          boolean                  default false,
    payout_updated                           boolean                  default false,
    plan_created                             boolean                  default false,
    plan_deleted                             boolean                  default false,
    plan_updated                             boolean                  default false,
    price_created                            boolean                  default false,
    price_deleted                            boolean                  default false,
    price_updated                            boolean                  default false,
    product_created                          boolean                  default false,
    product_deleted                          boolean                  default false,
    product_updated                          boolean                  default false,
    quote_accepted                           boolean                  default false,
    quote_canceled                           boolean                  default false,
    quote_created                            boolean                  default false,
    quote_finalized                          boolean                  default false,
    quote_will_expire                        boolean                  default false,
    refund_created                           boolean                  default false,
    refund_failed                            boolean                  default false,
    tax_rate_created                         boolean                  default false,
    tax_rate_updated                         boolean                  default false,
    tax_settings_updated                     boolean                  default false,
    transfer_created                         boolean                  default false,
    transfer_reversed                        boolean                  default false,
    transfer_updated                         boolean                  default false,
    subscription_schedule_aborted            boolean                  default false,
    subscription_schedule_canceled           boolean                  default false,
    subscription_schedule_completed          boolean                  default false,
    subscription_schedule_created            boolean                  default false,
    subscription_schedule_expiring           boolean                  default false,
    subscription_schedule_released           boolean                  default false,
    subscription_schedule_updated            boolean                  default false,
    api_key_live_publishable                 text,
    api_key_live_secret                      text
);

alter table stripe_accounts
    owner to postgres;

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

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

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

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

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

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

create table stripe_webhook_logs
(
    id                    bigint generated by default as identity
        primary key,
    created_at            timestamp with time zone default now()             not null,
    stripe_account_id     uuid
        references stripe_accounts (stripe_account_id),
    webhook_log_id        text,
    object                text,
    stripe_webhook_log_id uuid                     default gen_random_uuid() not null
        unique,
    type                  text,
    livemode              boolean                  default false,
    created               text,
    related_objects       json,
    api_version           text,
    data                  json,
    pending_webhooks      numeric                  default '0'::numeric,
    request               text,
    context               text,
    reason                json,
    url                   text,
    time                  numeric                  default '0'::numeric,
    stripe_signature      text,
    cf_ray                text,
    user_agent            text,
    x_forwarded_for       text,
    x_request_start       numeric,
    cf_connecting_ip      text,
    content               json,
    host                  text,
    webhook_id            text,
    body                  json,
    http_status_code      numeric                  default '0'::numeric,
    x_real_ip             text
);

alter table stripe_webhook_logs
    owner to postgres;

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

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

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

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

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

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

create table notification_settings
(
    id                                     bigint generated by default as identity
        primary key,
    created_at                             timestamp with time zone default now() not null,
    user_id                                text                     default gen_random_uuid()
        references users (user_id),
    company_id                             uuid
        references companies (company_id),
    enabled                                boolean                  default false,
    email                                  boolean                  default false,
    email_address                          text,
    mobile_push_notification               boolean                  default false,
    browser_push_notification              boolean                  default false,
    in_app_notification                    boolean                  default false,
    auto_subscribe_thread_on_first_message boolean                  default false,
    settings_id                            uuid                                   not null
        unique
);

alter table notification_settings
    owner to postgres;

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

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

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

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

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

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

create table mollie_webhooks
(
    id                     bigint generated by default as identity
        primary key,
    created_at             timestamp with time zone default now()             not null,
    mollie_account_id      uuid                                               not null
        references mollie_accounts (mollie_account_id),
    mollie_webhook_id      uuid                     default gen_random_uuid() not null
        unique,
    time                   numeric,
    name                   text,
    webhook_url            text,
    payload_style          text                     default 'snapshot'::text,
    event_types            text,
    payment_link_paid      boolean                  default false,
    profile_created        boolean                  default false,
    profile_verified       boolean                  default false,
    profile_blocked        boolean                  default false,
    profile_deleted        boolean                  default false,
    secret_token           text,
    secret_token_encrypted text,
    status                 text                     default 'suspended'::text,
    enabled                boolean                  default true,
    webhook_id             text
        unique,
    paused_deliveries      boolean                  default false
);

alter table mollie_webhooks
    owner to postgres;

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

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

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

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

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

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

create table mollie_webhook_logs
(
    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_webhook_log        uuid                     default gen_random_uuid() not null
        unique,
    mollie_webhook_id         text,
    time                      numeric,
    mollie_signature          text,
    user_agent                text,
    datadog_tags              text,
    host                      text,
    datadog_trace_id          text,
    datadog_sampling_priority numeric,
    traceparent               text,
    x_real_ip                 text,
    tracestate                text,
    x_forwarded_for           text,
    http_status_code          numeric                  default '0'::numeric,
    body                      json,
    cf_ray                    text,
    cf_ipcountry              text,
    x_request_start           numeric,
    headers                   json,
    secret                    text
);

alter table mollie_webhook_logs
    owner to postgres;

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

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

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

create index idx_mollie_webhook_logs_time
    on mollie_webhook_logs (time);

create index idx_mollie_webhook_logs_account
    on mollie_webhook_logs (mollie_account_id);

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

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

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

create table stripe_webhooks
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default now()             not null,
    stripe_account_id uuid
        references stripe_accounts (stripe_account_id),
    stripe_webhook_id uuid                     default gen_random_uuid() not null
        unique,
    added_by_user_id  text
        references users (user_id),
    webhook_url       text,
    api_version       text,
    events            json,
    event_count       numeric                  default '0'::numeric,
    enabled           boolean                  default false,
    payload_style     text                     default 'snapshot'::text,
    signing_secret    text
);

alter table stripe_webhooks
    owner to postgres;

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

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

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

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

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

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

create table payments
(
    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),
    payment_method_id uuid,
    amount            numeric                  default '0'::numeric,
    currency          text,
    provider          text,
    status            text,
    time              numeric,
    reference_id      text,
    payment_id        uuid                     default gen_random_uuid() not null
        unique,
    refunded          boolean                  default false,
    amount_refunded   numeric                  default '0'::numeric
);

alter table payments
    owner to postgres;

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

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

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

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

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

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

create table mollie_synchronization_triggers
(
    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),
    last_sync_time                    numeric,
    action                            text,
    title                             text,
    trigger                           text,
    mollie_synchronization_trigger_id uuid                     default gen_random_uuid() not null
        constraint mollie_synchronization_trigge_mollie_synchronization_trigge_key
            unique
);

alter table mollie_synchronization_triggers
    owner to postgres;

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

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

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

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

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

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

create table integration_registry
(
    id                              bigint generated by default as identity
        primary key,
    created_at                      timestamp with time zone default now()             not null,
    title                           text,
    integration_type_id             uuid                     default gen_random_uuid() not null
        unique,
    avatar                          text,
    description                     text,
    company_name                    text,
    permission_scopes               json,
    pricing_per_connection_value    numeric                  default '0'::numeric,
    pricing_per_connection_currency text                     default 'EUR'::text,
    max_connections_per_company     numeric                  default '5'::numeric,
    max_connections_per_user        numeric                  default '5'::numeric,
    billed_seperately               boolean                  default false,
    active                          boolean                  default false,
    status                          text                     default 'experimental'::text,
    version                         text,
    developer_author                text
        references users (user_id),
    system_integration              boolean                  default false,
    company_website                 text,
    category                        text,
    is_sb_partner                   boolean                  default false,
    supported_langs                 json                     default '{"english": true}'::json,
    support_email                   text,
    support_url                     text,
    install_url                     text,
    callback_uri                    text,
    based_in_country                text                     default 'nl'::text,
    about                           text,
    disabled                        boolean                  default true,
    supported_apis                  json,
    integration_bundle_identifier   text
        unique,
    scopes                          json,
    integration_provider            text,
    generate_install_url            text
);

alter table integration_registry
    owner to postgres;

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

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

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

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

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

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

create table tax_rules
(
    id                  bigint generated by default as identity,
    tax_rule_id         text                     default gen_random_uuid() not null,
    name                text                                               not null,
    percentage          numeric                                            not null,
    country             text                                               not null,
    created_at          timestamp with time zone default now()             not null,
    product_tax_code_id text                     default gen_random_uuid()
        references product_tax_codes,
    primary key (id, tax_rule_id)
);

alter table tax_rules
    owner to postgres;

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

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

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

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

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

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

create table tax_significant_developments
(
    id                             bigint generated by default as identity
        primary key,
    created_at                     timestamp with time zone default now() not null,
    tax_significant_development_id uuid                     default gen_random_uuid(),
    country_code                   text,
    title                          text,
    time                           numeric,
    effective_date                 text,
    content                        text,
    translation_key                uuid                     default gen_random_uuid()
);

alter table tax_significant_developments
    owner to postgres;

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

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

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

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

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

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

create table ponto_pending_transaction
(
    transaction_id                    uuid    not null
        primary key,
    account_id                        uuid    not null
        references ponto_account
            on update restrict on delete restrict,
    description                       text,
    currency                          text,
    digest                            text,
    created_at                        timestamp default (now() AT TIME ZONE 'utc'::text),
    updated_at                        timestamp,
    amount                            numeric(20, 9),
    fee                               numeric(20, 9),
    additional_information            text,
    bank_transaction_code             text,
    card_reference                    text,
    card_reference_type               text,
    counterpart_name                  json,
    counterpart_reference             text,
    creditor_id                       text,
    end_to_end_id                     text,
    execution_date                    timestamp,
    mandate_id                        text,
    proprietary_bank_transaction_code text,
    purpose_code                      text,
    remittance_information            text,
    remittance_information_type       text,
    value_date                        timestamp,
    internal_reference                text,
    user_id                           text    not null
        references users (user_id)
            on update restrict on delete restrict,
    created_at_unixtime_milli         numeric not null,
    updated_at_unixtime_milli         numeric not null,
    execution_date_unixtime_milli     numeric,
    id                                bigint generated by default as identity
        unique
);

alter table ponto_pending_transaction
    owner to postgres;

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

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

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

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

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

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

create table ponto_account_timeseries
(
    id                  bigint generated by default as identity
        primary key,
    created_at          timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    account_id          uuid
        references ponto_account
            on delete cascade,
    company_id          uuid
        references companies (company_id),
    created_at_unixtime numeric,
    balance             numeric
);

alter table ponto_account_timeseries
    owner to postgres;

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

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

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

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

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

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

create table transaction_providers
(
    id                      bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default now()             not null,
    transaction_provider_id uuid                     default gen_random_uuid() not null
        unique,
    provider_name           text                                               not null
        unique,
    icon                    text,
    author                  text
        references users (user_id),
    description             text,
    versioning_id           uuid
        references versioning (versioning_id)
);

alter table transaction_providers
    owner to postgres;

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

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

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

create table transactions
(
    id                                        bigint generated by default as identity,
    created_at                                timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    bank                                      text,
    iban_recipient                            text,
    iban_sender                               text,
    type                                      text,
    product                                   text,
    started_date                              numeric,
    completed_date                            numeric,
    description                               text,
    amount                                    numeric,
    fee                                       numeric                  default '0'::numeric,
    currency                                  text,
    balance                                   numeric,
    user_id                                   text
        references users (user_id),
    bank_account_id                           text,
    reconciliation_id                         uuid,
    verified                                  boolean                  default false,
    data_author                               text,
    money_out                                 numeric,
    money_in                                  numeric,
    opening_balance                           numeric,
    closing_balance                           numeric,
    user_id_recipient                         text,
    user_id_sender                            text,
    document_provider                         text,
    transaction_id                            uuid                                                              not null
        primary key,
    hash                                      text,
    transaction_type                          text,
    company_id                                text,
    status                                    text,
    category                                  uuid
        constraint fk_transaction_category
            references transaction_categories (transaction_category_id)
            on update cascade on delete cascade
        references transaction_categories (transaction_category_id),
    contact                                   uuid
        references contacts (contact_id)
            on delete set default,
    memo                                      text,
    apple_pay_card_number                     text,
    feature                                   text,
    sepa_debtor_id                            numeric,
    apple_pay_tx_id                           text,
    referenced_website                        text,
    sepa_consent_id                           text,
    referenced_date                           text,
    is_loan                                   boolean                  default false,
    loan_type_id                              uuid
        references loan_types (loan_type_id),
    transaction_provider_id                   uuid
        references transaction_providers (transaction_provider_id),
    mollie_payment_id                         text
        constraint transactions_mollie_tx_id_key
            unique,
    metadata                                  json,
    locale                                    text,
    method                                    text,
    mode                                      text,
    country_code                              text,
    paid_at                                   numeric,
    resource                                  text,
    name_recipient                            text,
    merchant_id                               uuid
        references merchants (merchant_id),
    iban_beneficiary                          text,
    name_beneficiary                          text,
    name_consumer                             text,
    iban_consumer                             text,
    bic_consumer                              text,
    bank_consumer                             text,
    time                                      numeric,
    iban_id_consumer                          uuid,
    receipt_id                                uuid,
    invoice_id                                text,
    bic_beneficiary                           text,
    processed_description                     text,
    invoice_nr                                text,
    remittance_information                    text,
    invoice_aggregate_id                      text,
    fiscal_year                               numeric,
    quarter                                   numeric,
    credit_note                               numeric,
    amount_discount                           numeric,
    debit_note                                numeric,
    amount_adjustment                         numeric,
    reason_adjustment                         text,
    amount_tax                                numeric,
    rate_tax                                  numeric,
    fx_conversion_date                        text,
    transfer_reference                        text,
    normalized                                boolean                  default false,
    debited                                   numeric                  default '0'::numeric,
    credited                                  numeric                  default '0'::numeric,
    iban                                      text,
    iban_counterparty                         text,
    bank_counterparty                         text,
    bic                                       text,
    bic_counterparty                          text,
    updated_at                                numeric,
    account_holder_name                       text,
    account_holder_name_counterparty          text,
    creditor_identifier                       text,
    direct_debit_aggregate_id                 text,
    scheduled_on                              text,
    signature_date                            text,
    bank_reason                               text,
    bank_reason_code                          text,
    country_code_counterparty                 text,
    has_given_authorization_for_auto_charging boolean                  default false,
    order_id                                  text,
    test_mode                                 boolean                  default false,
    month                                     text,
    reconciled                                boolean                  default false                            not null,
    tax_rate                                  numeric                  default '21'::numeric
);

alter table transactions
    owner to postgres;

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

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

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

create index transactions_company_id_idx
    on transactions (company_id);

create index transactions_status_idx
    on transactions (status);

create index transactions_transaction_id_idx
    on transactions (transaction_id);

create index transactions_company_id_completed_date_idx
    on transactions (company_id, completed_date);

create index transactions_company_id_invoice_nr_idx
    on transactions (company_id, invoice_nr);

create index transactions_company_id_order_id_idx
    on transactions (company_id, order_id);

create index transactions_company_id_currency_idx
    on transactions (company_id, currency);

create index transactions_company_id_merchant_id_idx
    on transactions (company_id, merchant_id);

create index transactions_company_id_name_consumer_idx
    on transactions (company_id, name_consumer);

create index transactions_company_id_amount_idx
    on transactions (company_id, amount);

create index transactions_company_id_amount_currency_idx
    on transactions (company_id, amount, currency);

create index transactions_company_id_currency_merchant_id_idx
    on transactions (company_id, currency, merchant_id);

create index transactions_company_id_currency_name_consumer_idx
    on transactions (company_id, currency, name_consumer);

create index idx_transactions_reconciled
    on transactions (company_id, reconciled, transaction_id);

create index ix_tx_company_completed_unrec
    on transactions (company_id asc, completed_date desc, transaction_id asc)
    where (reconciled IS NOT TRUE);

create index ix_tx_company_invoice_nr
    on transactions (company_id, invoice_nr)
    where ((invoice_nr <> ''::text) AND (reconciled IS NOT TRUE));

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

create index ix_tx_company_currency_merchant
    on transactions (company_id, currency, merchant_id)
    where (reconciled IS NOT TRUE);

create index ix_tx_company_currency_consumer
    on transactions (company_id, currency, name_consumer)
    where (reconciled IS NOT TRUE);

create index brin_tx_company_completed
    on transactions using brin (company_id, completed_date);

create index tx_company_currency_debited_date_idx
    on transactions (company_id, currency, debited, completed_date)
    where ((reconciled IS NOT TRUE) AND (debited IS NOT NULL) AND (debited > (0)::numeric));

create index tx_company_currency_credited_date_idx
    on transactions (company_id, currency, credited, completed_date)
    where ((reconciled IS NOT TRUE) AND (credited IS NOT NULL) AND (credited > (0)::numeric));

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

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

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

create table banking_accounts
(
    id                         bigint generated by default as identity
        primary key,
    created_at                 timestamp with time zone default now()             not null,
    account_id                 uuid                     default gen_random_uuid() not null
        unique,
    added_by_user_id           text
        references users (user_id),
    company_id                 uuid                     default gen_random_uuid()
        references companies (company_id),
    name                       text,
    type                       text,
    card_number                text,
    expiry_date                text,
    bank                       text,
    status                     text,
    hash                       text,
    iban                       text,
    banking_account_id         uuid                     default gen_random_uuid() not null
        unique,
    beneficiary_name           text,
    provider                   text,
    account_type               text,
    transaction_provider_id    uuid
        references transaction_providers (transaction_provider_id),
    financial_institution_id   uuid
        references ponto_financial_institution,
    onboarding_complete        boolean                  default false,
    expiry_at                  numeric,
    total_transactions         numeric,
    balance                    numeric,
    balance_updated_at         numeric,
    transactions_updated_at    numeric,
    synchronization_updated_at numeric,
    last_webhook_event_at      numeric,
    country_code               text,
    authorized_at              numeric,
    test_mode                  boolean                  default false,
    currency                   text,
    refresh_token_refreshed_at numeric,
    refresh_token_expire_at    numeric
);

alter table banking_accounts
    owner to postgres;

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

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

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

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

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

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

create table reconciliations
(
    id                   bigint generated by default as identity
        primary key,
    created_at           timestamp with time zone default now()             not null,
    reconciliation_id    uuid                     default gen_random_uuid() not null
        unique,
    engine_version       text,
    transaction_id       uuid
        references transactions,
    verified             boolean                  default false,
    note                 text,
    booked               boolean                  default false,
    document_id          uuid,
    company_id           uuid
        references companies (company_id),
    confidence           numeric                  default '0'::numeric,
    summary              text,
    time                 numeric,
    processing_time      numeric,
    hash                 text,
    is_duplicate_hash    boolean                  default false,
    updated_at           numeric,
    fiscal_year          numeric,
    quarter              numeric,
    month                text,
    relation_customer_id text,
    invoice_id           uuid
);

alter table reconciliations
    owner to postgres;

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

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

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

alter table transactions
    add foreign key (reconciliation_id) references reconciliations (reconciliation_id);

create index idx_reconciliations_tx
    on reconciliations (transaction_id);

create index idx_reconciliations_doc
    on reconciliations (document_id);

create index rec_tx_company_conf_idx
    on reconciliations (company_id asc, transaction_id asc, confidence desc);

create index rec_doc_company_conf_idx
    on reconciliations (company_id asc, document_id asc, confidence desc);

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

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

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

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

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

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

create table ponto_user_company_mapping
(
    created_at timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    user_id    text                                                              not null
        unique,
    company_id uuid                                                              not null,
    id         bigint generated by default as identity
        primary key
);

comment on table ponto_user_company_mapping is 'This table is needed to map newly added ponto connect account to the correct company id';

alter table ponto_user_company_mapping
    owner to postgres;

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

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

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

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

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

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

create table jobs_ran
(
    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,
    job_id                     text,
    progress_percent           numeric                  default '0'::numeric,
    progress_resource          numeric                  default '0'::numeric,
    progress_resource_total    numeric                  default '0'::numeric,
    company_id                 uuid
        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,
    body                       json,
    url                        text,
    response                   json,
    ms_taken                   text,
    http_status                text,
    error                      text
);

comment on table jobs_ran is 'This is a duplicate of jobs';

alter table jobs_ran
    owner to postgres;

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

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

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

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

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

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

create table mollie_apps
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default now() not null,
    mollie_app_id     uuid                     default gen_random_uuid(),
    mollie_account_id uuid
        references mollie_accounts (mollie_account_id),
    name              text,
    description       text,
    redirect_url      text,
    client_id         text,
    client_secret     text
);

alter table mollie_apps
    owner to postgres;

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

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

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

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

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

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

create table mollie_oath2_authorizations
(
    id                            bigint generated by default as identity
        primary key,
    created_at                    timestamp with time zone default now() not null,
    refresh_token                 text,
    scope                         text,
    token_type                    text,
    expires_in                    numeric,
    mollie_oath2_authorization_id uuid                     default gen_random_uuid(),
    access_token                  text,
    time                          numeric,
    expires_at                    numeric,
    active                        boolean                  default true,
    updated_at                    numeric,
    expired                       boolean                  default false,
    company_id                    uuid
        references companies (company_id),
    user_id                       text
        references users (user_id),
    state                         text
        unique
);

alter table mollie_oath2_authorizations
    owner to postgres;

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

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

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

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

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

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

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

create table balances
(
    id                 bigint generated by default as identity
        primary key,
    created_at         timestamp with time zone default now()             not null,
    banking_account_id uuid
        references banking_accounts (banking_account_id),
    amount_pending     numeric                  default '0'::numeric,
    amount_available   numeric                  default '0'::numeric,
    currency           text                     default 'EUR'::text,
    time               numeric                  default '0'::numeric,
    resource_id        text,
    resource_type      text,
    iban               text,
    beneficiary_name   text,
    balance_id         uuid                     default gen_random_uuid() not null
        unique
);

alter table balances
    owner to postgres;

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

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

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

create index balances_created_at_idx
    on balances (created_at);

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

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

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

create table ibans
(
    id                bigint generated by default as identity
        constraint contact_ibans_pkey
            primary key,
    created_at        timestamp with time zone default now() not null,
    iban_id           uuid                     default gen_random_uuid(),
    iban              text                                   not null
        constraint contact_ibans_iban_key
            unique,
    bank              text,
    bic               text,
    country_code      text,
    beneficiary_name  text,
    is_business       boolean                  default false,
    global_company_id uuid
);

alter table ibans
    owner to postgres;

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

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

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

create table payment_method_providers
(
    id                         bigint generated by default as identity
        primary key,
    created_at                 timestamp with time zone default now()             not null,
    payment_method_provider_id uuid                     default gen_random_uuid() not null
        unique,
    name                       text,
    type                       text,
    author                     text,
    avatar_url                 text,
    is_integration             boolean                  default false,
    integration_id             uuid
);

alter table payment_method_providers
    owner to postgres;

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

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

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

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

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

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

create table payment_method_configuration
(
    id                              bigint generated by default as identity
        primary key,
    created_at                      timestamp with time zone default now() not null,
    payment_method_configuration_id uuid                     default gen_random_uuid(),
    name                            text,
    masked_id                       text,
    company_id                      uuid
        references companies (company_id),
    country_code                    text,
    payment_method_ids              json,
    last_updated                    numeric,
    status                          text,
    enabled                         boolean,
    description                     text
);

alter table payment_method_configuration
    owner to postgres;

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

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

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

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

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

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

create table company_settings
(
    id                                   bigint generated by default as identity
        primary key,
    created_at                           timestamp with time zone default now()             not null,
    company_id                           uuid
        unique
        references companies (company_id),
    company_setting_id                   uuid                     default gen_random_uuid() not null
        unique,
    first_month_of_fiscal_year           text                     default 'january'::text,
    data_region                          text                     default 'European Union'::text,
    data_region_locked                   boolean                  default true,
    enable_invite_links                  boolean                  default false,
    approved_email_domain                text,
    restrict_new_user_invitations        boolean                  default true,
    restrict_integrations_for_non_admins boolean                  default true,
    timezone                             text,
    enforce_full_company_mfa_setup       boolean                  default false,
    allowed_export_objects               json                     default '[]'::json,
    allowed_import_objects               json                     default '["transactions", "customers", "invoices"]'::json
);

alter table company_settings
    owner to postgres;

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

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

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

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

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

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

create table dashboard_configs
(
    id                  bigint generated by default as identity
        primary key,
    created_at          timestamp with time zone default now() not null,
    dashboard_config_id uuid                     default gen_random_uuid(),
    company_id          uuid
        references companies (company_id),
    name                text,
    country_code        text,
    description         text,
    "default"           boolean                  default true,
    user_id             text
        references users (user_id),
    user_scoped         boolean                  default false
);

alter table dashboard_configs
    owner to postgres;

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

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

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

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

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

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

create table dashboard_widgets
(
    id                  bigint generated by default as identity
        constraint dashboard_widgets_pkey1
            primary key,
    created_at          timestamp with time zone default now()             not null,
    dashboard_widget_id uuid                     default gen_random_uuid() not null
        unique,
    title               text,
    tooltip             text,
    has_tooltip         boolean                  default false,
    translation_key     text,
    visualization_type  text,
    is_currency         boolean                  default false,
    is_percentage       boolean                  default false,
    has_view_more       boolean                  default false,
    view_more_href      text                     default ''::text,
    category            text,
    is_system           boolean                  default false,
    author              text
        references users (user_id),
    hash                text
        unique
);

comment on table dashboard_widgets is 'This is a duplicate of dashboard_widgets_provider';

alter table dashboard_widgets
    owner to postgres;

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

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

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

create table de_companies_balances
(
    id             bigint generated by default as identity
        primary key,
    created_at     timestamp with time zone default now() not null,
    name           text,
    company_number text,
    type           text,
    company_href   text,
    info           text,
    info_href      text,
    info2          text,
    rights_form    text,
    register       text,
    description    text
);

comment on table de_companies_balances is 'This is a duplicate of de_companies';

alter table de_companies_balances
    owner to postgres;

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

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

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

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

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

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

create table system_analytics
(
    id                 bigint generated by default as identity
        primary key,
    created_at         timestamp with time zone default now() not null,
    system_analytic_id uuid                     default gen_random_uuid(),
    name               text,
    description        text,
    value_numberic     numeric,
    value_string       text,
    value_json         json,
    updated_at         numeric,
    code               text,
    value_numberic_max numeric
);

alter table system_analytics
    owner to postgres;

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

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

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

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

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

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

create table dashboards
(
    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),
    name             text,
    description      text,
    widgets          json,
    updated_at       numeric,
    user_scoped_only boolean                  default false,
    dashboard_id     uuid                     default gen_random_uuid(),
    slug             text,
    hash             text,
    tags             json,
    idempotency_key  text
        unique,
    slug_hash        text
        unique
);

alter table dashboards
    owner to postgres;

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

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

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

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

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

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

create table translation_keys
(
    id                 bigint generated by default as identity
        primary key,
    created_at         timestamp with time zone default now()             not null,
    translation_key    text
        unique,
    translation_key_id uuid                     default gen_random_uuid() not null
        unique,
    en                 text,
    ru                 text,
    nl                 text,
    de                 text,
    tr                 text,
    ar                 text,
    zh                 text,
    sv                 text,
    se                 text,
    lt                 text,
    cz                 text,
    es                 text
);

alter table translation_keys
    owner to postgres;

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

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

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

create table dashboard_widgets_provider
(
    id                           bigint generated by default as identity
        constraint dashboard_widgets_pkey
            primary key,
    created_at                   timestamp with time zone default now()             not null,
    dashboard_widget_provider_id uuid                     default gen_random_uuid() not null
        constraint dashboard_widgets_provider_dashboard_widget_id_key
            unique,
    title                        text,
    has_tooltip                  boolean                  default false,
    translation_key              text
        references translation_keys (translation_key),
    visualization_type           text,
    is_currency                  boolean                  default false,
    is_percentage                boolean                  default false,
    has_view_more                boolean                  default false,
    view_more_href               text                     default ''::text,
    query_id                     uuid
        references sql_queries (query_id),
    chart_colors                 json,
    definition_tooltip_id        uuid
        references definition_tooltips (definition_tooltip_id),
    support_week_data            boolean                  default false,
    support_month_data           boolean                  default false,
    object_name_singular         text,
    object_name_plurar           text,
    has_last_updated_timestamp   boolean                  default false,
    is_system                    boolean                  default false,
    category                     text,
    "group"                      text,
    hash                         text
        unique,
    author                       text
        references users (user_id),
    support_all_time_data        boolean                  default false,
    live                         boolean                  default false
);

alter table dashboard_widgets_provider
    owner to postgres;

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

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

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

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

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

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

create table system_emails
(
    id               bigint generated by default as identity
        primary key,
    created_at       timestamp with time zone default now() not null,
    email_id         uuid                     default gen_random_uuid(),
    action           text                                   not null
        unique,
    variables        json,
    html_url         text,
    attachments      text,
    language         text,
    subject          text,
    resource_id_type text,
    html_body        text,
    html_repeater    text
);

alter table system_emails
    owner to postgres;

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

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

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

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

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

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

create table tax_ids
(
    id           bigint generated by default as identity
        primary key,
    created_at   timestamp with time zone default now() not null,
    tax_id       text                                   not null
        unique,
    country_code text,
    name         text,
    company_id   uuid
        references companies (company_id),
    is_defaults  boolean                  default false,
    tax_uuid     uuid                     default gen_random_uuid()
        unique
);

alter table tax_ids
    owner to postgres;

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

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

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

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

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

grant delete, insert, references, select, trigger, truncate, update on tax_ids to service_role;

create table parser_set
(
    id            bigint generated by default as identity
        primary key,
    created_at    timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    parser_set_id uuid                     default gen_random_uuid()                not null
        unique,
    name          text
);

alter table parser_set
    owner to postgres;

grant select, update, usage on sequence parser_set_id_seq to anon;

grant select, update, usage on sequence parser_set_id_seq to authenticated;

grant select, update, usage on sequence parser_set_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on parser_set to anon;

grant delete, insert, references, select, trigger, truncate, update on parser_set to authenticated;

grant delete, insert, references, select, trigger, truncate, update on parser_set to service_role;

create table parser_mapping
(
    id                bigint generated by default as identity
        primary key,
    created_at        timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    parser_set_id     uuid                                                              not null
        references parser_set (parser_set_id),
    parser_id         uuid                                                              not null,
    parser_type       text                                                              not null,
    parser_mapping_id uuid                     default gen_random_uuid()
        unique
);

alter table parser_mapping
    owner to postgres;

grant select, update, usage on sequence parser_mapping_id_seq to anon;

grant select, update, usage on sequence parser_mapping_id_seq to authenticated;

grant select, update, usage on sequence parser_mapping_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on parser_mapping to anon;

grant delete, insert, references, select, trigger, truncate, update on parser_mapping to authenticated;

grant delete, insert, references, select, trigger, truncate, update on parser_mapping to service_role;

create table zeptomail_webhook_logs
(
    id                       bigint generated by default as identity
        primary key,
    created_at               timestamp with time zone default now() not null,
    zeptomail_webhook_log_id uuid                     default gen_random_uuid(),
    time                     numeric,
    event_name               text,
    event_message            json,
    mailagent_key            text,
    webhook_request_id       text,
    event_data               json,
    email_id                 text
);

alter table zeptomail_webhook_logs
    owner to postgres;

grant select, update, usage on sequence zeptomail_webhook_logs_id_seq to anon;

grant select, update, usage on sequence zeptomail_webhook_logs_id_seq to authenticated;

grant select, update, usage on sequence zeptomail_webhook_logs_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on zeptomail_webhook_logs to anon;

grant delete, insert, references, select, trigger, truncate, update on zeptomail_webhook_logs to authenticated;

grant delete, insert, references, select, trigger, truncate, update on zeptomail_webhook_logs to service_role;

create table connect_tickets
(
    id                 bigint generated by default as identity,
    created_at         timestamp with time zone default now()             not null,
    ticket_type        text,
    connect_ticket_id  uuid                     default gen_random_uuid() not null
        unique,
    company_id         uuid
        references companies (company_id),
    trigger            text,
    is_periodic_ticket boolean                  default false,
    assigned_user      text
        references users (user_id),
    status             text,
    tasklist_id        uuid,
    updated_at         numeric,
    message_count      numeric,
    case_number        bigint generated by default as identity,
    primary key (id, case_number)
);

alter table connect_tickets
    owner to postgres;

grant select, update, usage on sequence connect_tickets_id_seq to anon;

grant select, update, usage on sequence connect_tickets_id_seq to authenticated;

grant select, update, usage on sequence connect_tickets_id_seq to service_role;

grant select, update, usage on sequence connect_tickets_case_number_seq to anon;

grant select, update, usage on sequence connect_tickets_case_number_seq to authenticated;

grant select, update, usage on sequence connect_tickets_case_number_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on connect_tickets to anon;

grant delete, insert, references, select, trigger, truncate, update on connect_tickets to authenticated;

grant delete, insert, references, select, trigger, truncate, update on connect_tickets to service_role;

create table connect_tasklists
(
    id             bigint generated by default as identity
        primary key,
    created_at     timestamp with time zone default now() not null,
    tasklist_id    uuid,
    title          text,
    index          numeric,
    status         text,
    description    text,
    author_user_id text
        references users (user_id),
    company_id     uuid
        references companies (company_id),
    task_id        uuid                     default gen_random_uuid()
);

alter table connect_tasklists
    owner to postgres;

grant select, update, usage on sequence connect_tasklists_id_seq to anon;

grant select, update, usage on sequence connect_tasklists_id_seq to authenticated;

grant select, update, usage on sequence connect_tasklists_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on connect_tasklists to anon;

grant delete, insert, references, select, trigger, truncate, update on connect_tasklists to authenticated;

grant delete, insert, references, select, trigger, truncate, update on connect_tasklists to service_role;

create table connect_audit_log
(
    id                   bigint generated by default as identity
        primary key,
    created_at           timestamp with time zone default (now() AT TIME ZONE 'utc'::text) not null,
    user_id              text
        references users (user_id),
    username             text,
    action               text,
    time                 numeric,
    route                text,
    request              text,
    status               text,
    message              text,
    author_user_id       text
        references users (user_id),
    email                text,
    domain               text                     default 'suitsbooks.nl'::text,
    organization_id      text
        references organizations (organization_id),
    new_status           text,
    old_value            text,
    new_value            text,
    company_id           text,
    "table"              text,
    resource_id          text,
    resource             json,
    diff_resource        json,
    user_object          json,
    ipv4                 text,
    connect_audit_log_id uuid                     default gen_random_uuid()                not null
        constraint connect_audit_log_audit_log_id_key
            unique
);

alter table connect_audit_log
    owner to postgres;

grant select, update, usage on sequence connect_audit_log_id_seq to anon;

grant select, update, usage on sequence connect_audit_log_id_seq to authenticated;

grant select, update, usage on sequence connect_audit_log_id_seq to service_role;

create index connect_audit_log_company_id_idx
    on connect_audit_log (company_id);

create index connect_audit_log_resource_id_idx
    on connect_audit_log (resource_id);

create index connect_audit_log_table_idx
    on connect_audit_log ("table");

create index connect_audit_log_action_idx
    on connect_audit_log (action);

grant delete, insert, references, select, trigger, truncate, update on connect_audit_log to anon;

grant delete, insert, references, select, trigger, truncate, update on connect_audit_log to authenticated;

grant delete, insert, references, select, trigger, truncate, update on connect_audit_log to service_role;

create table aurora_foundry
(
    id                 bigint generated by default as identity
        primary key,
    created_at         timestamp with time zone default now() not null,
    aurora_foundry_id  uuid                     default gen_random_uuid()
        unique,
    document_provider  text,
    merchant_id        uuid
        references merchants (merchant_id),
    description        text,
    file_type          text,
    headers            json,
    delimiter_token    text,
    reference          text,
    sample_url         text,
    original_file_name text,
    platform           text
);

alter table aurora_foundry
    owner to postgres;

grant select, update, usage on sequence aurora_foundry_id_seq to anon;

grant select, update, usage on sequence aurora_foundry_id_seq to authenticated;

grant select, update, usage on sequence aurora_foundry_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on aurora_foundry to anon;

grant delete, insert, references, select, trigger, truncate, update on aurora_foundry to authenticated;

grant delete, insert, references, select, trigger, truncate, update on aurora_foundry to service_role;

create table purchasing_invoices
(
    id                      bigint generated by default as identity
        primary key,
    created_at              timestamp with time zone default now()             not null,
    purchasing_invoice_id   uuid                     default gen_random_uuid() not null
        unique,
    company_id              uuid
        references companies (company_id),
    user_id_uploader        text
        references users (user_id),
    object_type             text                     default 'invoice_purchase'::text,
    administration          text,
    supplier                text,
    currency                text,
    amount                  numeric,
    description             text,
    title                   text,
    document_provider       text,
    invoice_number          text,
    status                  text,
    relation                text,
    invoice_date            text,
    execution_date          text,
    bank_account            text,
    payment_reference       text,
    payment_description     text,
    language                text,
    file_url                text,
    fee                     numeric,
    merchant_name           text,
    merchant_location       text,
    merchant_address        json,
    merchant_email          text,
    subtotal                numeric,
    total                   numeric,
    tip_suggestionsj        json,
    receipt_number          text,
    table_number            text,
    items                   json,
    card_details            json,
    reverse_charged         boolean                  default false,
    merchant_website        text,
    merchant_id             uuid
        references merchants (merchant_id),
    ledger_breakdown        json,
    tax_breakdown           json,
    merchant_company_number text,
    country_code            text,
    address_line_1          text,
    address_line_2          text,
    postal_code             text,
    city                    text,
    state                   text,
    amount_due              numeric,
    payment_instructions    text,
    vat_id                  text,
    iban                    text,
    hash                    text
        unique,
    customer_number         text,
    subtotal_excl_vat       numeric,
    vat_amount              numeric,
    billing_period          text,
    payment_method          text,
    amount_paid             numeric,
    date_paid               text,
    phone_number            text,
    vat_summary             text,
    notes                   text,
    total_incl_vat          numeric,
    vat_exempt              boolean                  default false,
    delivery_date           text,
    metadata                json,
    bank_account_holder     text,
    bic                     text,
    body                    json,
    all_ocr_content         text,
    all_ocr_content_eng     text,
    order_details           json,
    month_year              text,
    consumer_company_name   text,
    consumer_address_line_1 text,
    consumer_address_line_2 text,
    consumer_country_code   text,
    consumer_postal_code    text,
    consumer_city           text,
    consumer_province       text,
    consumer_state          text,
    original_filename       text,
    general_ledger_account  text,
    terminal_id             text
);

alter table purchasing_invoices
    owner to postgres;

grant select, update, usage on sequence purchasing_invoices_id_seq to anon;

grant select, update, usage on sequence purchasing_invoices_id_seq to authenticated;

grant select, update, usage on sequence purchasing_invoices_id_seq to service_role;

grant delete, insert, references, select, trigger, truncate, update on purchasing_invoices to anon;

grant delete, insert, references, select, trigger, truncate, update on purchasing_invoices to authenticated;

grant delete, insert, references, select, trigger, truncate, update on purchasing_invoices to service_role;

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;

create table pm_postgrest
(
    id                               bigint generated by default as identity
        constraint pm_postgres_pkey
            primary key,
    created_at                       timestamp with time zone default now()             not null,
    slug                             text                                               not null
        unique,
    project_id                       text,
    table_count                      numeric,
    tables                           json,
    size_bytes                       numeric,
    name                             text,
    anon_key                         text,
    connection_string                text,
    jwt_secret                       text,
    jwt_key                          text,
    db_password                      text,
    postgrest_port                   numeric,
    host                             text,
    admin_email                      text,
    db_id                            uuid                     default gen_random_uuid() not null
        unique,
    "collate"                        text,
    ctype                            text,
    encoding                         text,
    pg_owner                         text,
    postgrest_systemd_service_file   text,
    postgrest_systemd_service_name   text,
    postgrest_systemd_service_status text,
    backup                           boolean                  default false,
    rest_endpoint                    text,
    api_max_rows                     numeric                  default '1000'::numeric,
    rest_endpoint_cached             text,
    monitor_id                       text
        unique,
    monitor_type                     text                     default 'systemd_service'::text,
    postgrest_config_file            text,
    athena_bootstrapped              boolean                  default false,
    athena_host                      text
);

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;

