CREATE TABLE transactions
(
    id          BIGSERIAL PRIMARY KEY,
    family_id   BIGINT         NOT NULL REFERENCES families (id) ON DELETE CASCADE,
    description TEXT,
    type        TEXT           NOT NULL,
    datetime    TIMESTAMP      NOT NULL,
    category    TEXT           NOT NULL,
    amount      NUMERIC(14, 2) NOT NULL,
    created_at  TIMESTAMP      NOT NULL DEFAULT NOW(),
    created_by  BIGINT         NOT NULL REFERENCES users (id) ON DELETE RESTRICT
);

CREATE INDEX idx_transactions_family_id ON transactions (family_id);
CREATE INDEX idx_transactions_datetime ON transactions (datetime);
CREATE INDEX idx_transactions_created_by ON transactions (created_by);
CREATE INDEX idx_transactions_family_datetime ON transactions (family_id, datetime DESC);

CREATE TABLE receipts
(
    id              BIGSERIAL PRIMARY KEY,
    transaction_id  BIGINT UNIQUE REFERENCES transactions (id) ON DELETE SET NULL,
    receipt_number  TEXT      NOT NULL UNIQUE,
    ui              TEXT      NOT NULL,
    status          INTEGER   NOT NULL,
    issued_at       TIMESTAMP NOT NULL,
    total_amount    REAL      NOT NULL,
    payment_amount  REAL      NOT NULL,
    cash_amount     REAL      NOT NULL,
    another_amount  REAL      NOT NULL,
    clearing_amount REAL      NOT NULL,
    margin          REAL      NOT NULL,
    currency        TEXT      NOT NULL,
    payment_type    INTEGER   NOT NULL,
    cashbox_number  INTEGER   NOT NULL,
    cashier         TEXT,
    name_spd        TEXT,
    name_to         TEXT,
    name_np         TEXT,
    type_np         TEXT,
    street_to       TEXT,
    house_to        TEXT,
    kod_soato       TEXT,
    oblast_soato    TEXT,
    rayon_soato     TEXT,
    selsovet_soato  TEXT,
    doc_num         TEXT,
    skno_number     TEXT,
    unp             TEXT,
    success         TEXT,
    created_at      TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_receipts_issued_at ON receipts (issued_at);
CREATE INDEX idx_receipts_transaction_id ON receipts (transaction_id);
