CREATE TABLE IF NOT EXISTS nshift_shipments_status (
    id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    package_number TEXT NOT NULL UNIQUE,
    order_id INT REFERENCES orders(id),
    product_name TEXT,
    carrier_name TEXT,
    number TEXT,
    order_number TEXT,
    shipment_created TIMESTAMP WITH TIME ZONE NOT NULL,
    in_transit TIMESTAMP WITH TIME ZONE,
    delivered TIMESTAMP WITH TIME ZONE,
    carrier_exception TIMESTAMP WITH TIME ZONE,
    receiver_exception TIMESTAMP WITH TIME ZONE,
    sender_exception TIMESTAMP WITH TIME ZONE,
    latest_event_status_id INT,
    latest_event_status_text TEXT,
    latest_event_date TIMESTAMP WITH TIME ZONE
);

CREATE OR REPLACE VIEW v_funnel_nshift_shipments AS
SELECT
    nshift_shipments_status.package_number,
    nshift_shipments_status.order_id,
    nshift_shipments_status.product_name,
    nshift_shipments_status.carrier_name,
    orders.inserted AS order_created,
    nshift_shipments_status.shipment_created,
    nshift_shipments_status.in_transit,
    nshift_shipments_status.delivered,
    nshift_shipments_status.carrier_exception,
    nshift_shipments_status.receiver_exception,
    nshift_shipments_status.sender_exception,
    nshift_shipments_status.latest_event_status_id,
    nshift_shipments_status.latest_event_status_text,
    nshift_shipments_status.latest_event_date
FROM nshift_shipments_status
LEFT JOIN orders ON order_id = orders.id;

GRANT SELECT ON TABLE v_funnel_nshift_shipments TO funnel;
