-- ============================================================
-- Story #55 - Sales Document persistence model
-- ============================================================
-- Objetivo:
--   Crear la base de persistencia para comprobantes de venta:
--   - Facturas internas
--   - Notas de debito / credito
--   - FCE / NDE / NCE futuras
--   - Autorizacion fiscal ARCA futura
--
-- Decisiones:
--   - No se crean nuevos talonarios.
--   - Se reutiliza PhS_FormSeries / PhS_FormSeriesNextNumber.
--   - La numeracion interna queda separada de la numeracion fiscal.
--   - El documento comercial queda separado del documento fiscal ARCA.
--   - El remito NO es obligatorio ni se modela como dependencia directa.
--   - El vinculo principal con origen comercial se mantiene por quote_detail_id.
-- ============================================================

IF OBJECT_ID('dbo.PhS_SalesFiscalDocumentAssociations', 'U') IS NOT NULL
    DROP TABLE dbo.PhS_SalesFiscalDocumentAssociations;

IF OBJECT_ID('dbo.PhS_SalesFiscalDocuments', 'U') IS NOT NULL
    DROP TABLE dbo.PhS_SalesFiscalDocuments;

IF OBJECT_ID('dbo.PhS_SalesDocumentDetails', 'U') IS NOT NULL
    DROP TABLE dbo.PhS_SalesDocumentDetails;

IF OBJECT_ID('dbo.PhS_SalesDocuments', 'U') IS NOT NULL
    DROP TABLE dbo.PhS_SalesDocuments;

-- ============================================================
-- Documento comercial interno
-- ============================================================
CREATE TABLE dbo.PhS_SalesDocuments
(
    id INT IDENTITY(1,1) NOT NULL,

    formseries_id INT NULL,

    internal_sequence_number INT NULL,
    internal_document_number NVARCHAR(50) NULL,

    document_type INT NOT NULL,

    fiscal_voucher_type INT NULL,
    fiscal_voucher_letter NVARCHAR(5) NULL,

    status INT NOT NULL CONSTRAINT DF_PhS_SalesDocuments_status DEFAULT (0),

    quote_id INT NULL,

    customer_id INT NOT NULL,
    bill_to_customer_id INT NOT NULL,

    issue_date DATETIME NULL,

    currency NVARCHAR(10) NOT NULL CONSTRAINT DF_PhS_SalesDocuments_currency DEFAULT ('ARS'),
    exchange_rate DECIMAL(18,6) NOT NULL CONSTRAINT DF_PhS_SalesDocuments_exchange_rate DEFAULT (1),

    net_amount DECIMAL(18,2) NOT NULL CONSTRAINT DF_PhS_SalesDocuments_net_amount DEFAULT (0),
    tax_amount DECIMAL(18,2) NOT NULL CONSTRAINT DF_PhS_SalesDocuments_tax_amount DEFAULT (0),
    total_amount DECIMAL(18,2) NOT NULL CONSTRAINT DF_PhS_SalesDocuments_total_amount DEFAULT (0),

    associated_document_type NVARCHAR(50) NULL,
    associated_document_number NVARCHAR(50) NULL,
    associated_document_date DATETIME NULL,

    observations NVARCHAR(MAX) NULL,
    extra_info_json NVARCHAR(MAX) NULL,

    createdat DATETIME NOT NULL CONSTRAINT DF_PhS_SalesDocuments_createdat DEFAULT (GETDATE()),
    modifiedat DATETIME NULL,

    CONSTRAINT PK_PhS_SalesDocuments PRIMARY KEY (id),

    CONSTRAINT FK_PhS_SalesDocuments_FormSeries
        FOREIGN KEY (formseries_id)
        REFERENCES dbo.PhS_FormSeries(id),

    CONSTRAINT FK_PhS_SalesDocuments_QuoteHeaders
        FOREIGN KEY (quote_id)
        REFERENCES dbo.PhS_QuoteHeaders(id),

    CONSTRAINT FK_PhS_SalesDocuments_Customers
        FOREIGN KEY (customer_id)
        REFERENCES dbo.PhS_Customers(id),

    CONSTRAINT FK_PhS_SalesDocuments_BillToCustomers
        FOREIGN KEY (bill_to_customer_id)
        REFERENCES dbo.PhS_Customers(id)
);

-- ============================================================
-- Detalle comercial
-- ============================================================
CREATE TABLE dbo.PhS_SalesDocumentDetails
(
    id INT IDENTITY(1,1) NOT NULL,
    salesdocument_id INT NOT NULL,

    line_number INT NOT NULL,

    origin_type NVARCHAR(50) NOT NULL,
    origin_id INT NULL,

    quote_detail_id INT NULL,

    product_id INT NULL,
    description NVARCHAR(255) NOT NULL,

    quantity DECIMAL(18,2) NOT NULL,

    authorized_unit_price DECIMAL(18,2) NULL,
    authorized_amount DECIMAL(18,2) NULL,

    billed_percentage DECIMAL(9,4) NULL,

    unit_price DECIMAL(18,2) NOT NULL,
    net_amount DECIMAL(18,2) NOT NULL,
    tax_amount DECIMAL(18,2) NOT NULL,
    total_amount DECIMAL(18,2) NOT NULL,

    origin_snapshot_json NVARCHAR(MAX) NULL,

    createdat DATETIME NOT NULL CONSTRAINT DF_PhS_SalesDocumentDetails_createdat DEFAULT (GETDATE()),
    modifiedat DATETIME NULL,

    CONSTRAINT PK_PhS_SalesDocumentDetails PRIMARY KEY (id),

    CONSTRAINT FK_PhS_SalesDocumentDetails_SalesDocuments
        FOREIGN KEY (salesdocument_id)
        REFERENCES dbo.PhS_SalesDocuments(id),

    CONSTRAINT FK_PhS_SalesDocumentDetails_QuoteDetails
        FOREIGN KEY (quote_detail_id)
        REFERENCES dbo.PhS_QuoteDetails(id),

    CONSTRAINT FK_PhS_SalesDocumentDetails_Products
        FOREIGN KEY (product_id)
        REFERENCES dbo.PhS_Products(id)
);

-- ============================================================
-- Documento fiscal ARCA / AFIP
-- ============================================================
CREATE TABLE dbo.PhS_SalesFiscalDocuments
(
    id INT IDENTITY(1,1) NOT NULL,
    salesdocument_id INT NOT NULL,

    fiscal_status INT NOT NULL CONSTRAINT DF_PhS_SalesFiscalDocuments_fiscal_status DEFAULT (0),

    environment NVARCHAR(20) NOT NULL,

    point_of_sale SMALLINT NULL,
    voucher_type INT NULL,
    voucher_letter NVARCHAR(5) NULL,
    voucher_number INT NULL,

    cae NVARCHAR(20) NULL,
    cae_expiration_date DATETIME NULL,

    request_fingerprint NVARCHAR(255) NULL,
    is_final BIT NOT NULL CONSTRAINT DF_PhS_SalesFiscalDocuments_is_final DEFAULT (0),

    arca_request_payload_json NVARCHAR(MAX) NULL,
    arca_response_payload_json NVARCHAR(MAX) NULL,
    errors_json NVARCHAR(MAX) NULL,
    events_json NVARCHAR(MAX) NULL,
    observations_json NVARCHAR(MAX) NULL,

    attempted_at_utc DATETIME NULL,
    completed_at_utc DATETIME NULL,
    reconciled_after_timeout BIT NOT NULL CONSTRAINT DF_PhS_SalesFiscalDocuments_reconciled DEFAULT (0),

    createdat DATETIME NOT NULL CONSTRAINT DF_PhS_SalesFiscalDocuments_createdat DEFAULT (GETDATE()),
    modifiedat DATETIME NULL,

    CONSTRAINT PK_PhS_SalesFiscalDocuments PRIMARY KEY (id),

    CONSTRAINT FK_PhS_SalesFiscalDocuments_SalesDocuments
        FOREIGN KEY (salesdocument_id)
        REFERENCES dbo.PhS_SalesDocuments(id)
);

-- ============================================================
-- Asociaciones fiscales reales: CbtesAsoc
-- ============================================================
CREATE TABLE dbo.PhS_SalesFiscalDocumentAssociations
(
    id INT IDENTITY(1,1) NOT NULL,
    salesfiscaldocument_id INT NOT NULL,

    associated_salesdocument_id INT NULL,

    associated_voucher_type INT NOT NULL,
    associated_point_of_sale SMALLINT NOT NULL,
    associated_voucher_number INT NOT NULL,
    associated_voucher_cuit NVARCHAR(20) NULL,
    associated_voucher_date DATETIME NULL,

    createdat DATETIME NOT NULL CONSTRAINT DF_PhS_SalesFiscalDocumentAssociations_createdat DEFAULT (GETDATE()),

    CONSTRAINT PK_PhS_SalesFiscalDocumentAssociations PRIMARY KEY (id),

    CONSTRAINT FK_PhS_SalesFiscalDocumentAssociations_FiscalDocuments
        FOREIGN KEY (salesfiscaldocument_id)
        REFERENCES dbo.PhS_SalesFiscalDocuments(id),

    CONSTRAINT FK_PhS_SalesFiscalDocumentAssociations_SalesDocuments
        FOREIGN KEY (associated_salesdocument_id)
        REFERENCES dbo.PhS_SalesDocuments(id)
);

-- ============================================================
-- Indices
-- ============================================================

CREATE INDEX IX_PhS_SalesDocuments_FormSeries
    ON dbo.PhS_SalesDocuments(formseries_id);

CREATE INDEX IX_PhS_SalesDocuments_Quote
    ON dbo.PhS_SalesDocuments(quote_id);

CREATE INDEX IX_PhS_SalesDocuments_Customer
    ON dbo.PhS_SalesDocuments(customer_id);

CREATE INDEX IX_PhS_SalesDocuments_BillToCustomer
    ON dbo.PhS_SalesDocuments(bill_to_customer_id);

CREATE INDEX IX_PhS_SalesDocuments_Status
    ON dbo.PhS_SalesDocuments(status);

CREATE INDEX IX_PhS_SalesDocuments_IssueDate
    ON dbo.PhS_SalesDocuments(issue_date);

CREATE UNIQUE INDEX UX_PhS_SalesDocuments_InternalNumber
    ON dbo.PhS_SalesDocuments(formseries_id, internal_sequence_number)
    WHERE formseries_id IS NOT NULL
      AND internal_sequence_number IS NOT NULL;

CREATE UNIQUE INDEX UX_PhS_SalesDocuments_InternalDocumentNumber
    ON dbo.PhS_SalesDocuments(formseries_id, internal_document_number)
    WHERE formseries_id IS NOT NULL
      AND internal_document_number IS NOT NULL;

CREATE INDEX IX_PhS_SalesDocumentDetails_Document
    ON dbo.PhS_SalesDocumentDetails(salesdocument_id);

CREATE UNIQUE INDEX UX_PhS_SalesDocumentDetails_Line
    ON dbo.PhS_SalesDocumentDetails(salesdocument_id, line_number);

CREATE INDEX IX_PhS_SalesDocumentDetails_QuoteDetail
    ON dbo.PhS_SalesDocumentDetails(quote_detail_id);

CREATE INDEX IX_PhS_SalesFiscalDocuments_Document
    ON dbo.PhS_SalesFiscalDocuments(salesdocument_id);

CREATE UNIQUE INDEX UX_PhS_SalesFiscalDocuments_Document
    ON dbo.PhS_SalesFiscalDocuments(salesdocument_id);

CREATE UNIQUE INDEX UX_PhS_SalesFiscalDocuments_FiscalNumber
    ON dbo.PhS_SalesFiscalDocuments(environment, point_of_sale, voucher_type, voucher_number)
    WHERE point_of_sale IS NOT NULL
      AND voucher_type IS NOT NULL
      AND voucher_number IS NOT NULL;

CREATE UNIQUE INDEX UX_PhS_SalesFiscalDocuments_Idempotency
    ON dbo.PhS_SalesFiscalDocuments(environment, point_of_sale, voucher_type, request_fingerprint)
    WHERE point_of_sale IS NOT NULL
      AND voucher_type IS NOT NULL
      AND request_fingerprint IS NOT NULL;

CREATE INDEX IX_PhS_SalesFiscalDocumentAssociations_FiscalDocument
    ON dbo.PhS_SalesFiscalDocumentAssociations(salesfiscaldocument_id);

CREATE INDEX IX_PhS_SalesFiscalDocumentAssociations_AssociatedDocument
    ON dbo.PhS_SalesFiscalDocumentAssociations(associated_salesdocument_id);

-- ============================================================
-- Extended properties / MS_Description
-- ============================================================

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Documentos comerciales internos de venta: facturas, notas de debito, notas de credito, FCE, NDE y NCE. Mantiene la emision interna separada de la autorizacion fiscal ARCA.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Identificador interno del documento comercial.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Talonario/serie interna existente en PhronCare. Reutiliza PhS_FormSeries para numeracion interna.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'formseries_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Numero secuencial interno asignado al emitir internamente el documento. No corresponde al numero fiscal ARCA.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'internal_sequence_number';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Numero visible interno del documento, formado desde la serie/talonario interno. Puede diferir del numero fiscal.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'internal_document_number';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Tipo comercial interno del documento. Ejemplos: Invoice, DebitNote, CreditNote, CreditInvoice, CreditDebitNote, CreditCreditNote.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'document_type';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Tipo de comprobante fiscal AFIP/ARCA previsto para autorizacion futura. Ejemplos: 1, 6, 11, 201, 202, 203.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'fiscal_voucher_type';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Letra fiscal prevista del comprobante: A, B, C u otras segun configuracion fiscal.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'fiscal_voucher_letter';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Estado comercial interno. Ejemplos: Draft, Validated, Issued, Cancelled. Independiente del estado fiscal.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'status';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Presupuesto origen opcional. Puede ser NULL para ventas manuales o de escritorio.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'quote_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Cliente origen de la operacion comercial.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'customer_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Cliente al que se factura realmente. Permite escenarios obra social / particular u otros terceros pagadores.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'bill_to_customer_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Fecha de emision interna del documento comercial.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'issue_date';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Moneda del documento comercial.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'currency';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Cotizacion utilizada para la moneda del documento.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'exchange_rate';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Importe neto total del documento.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'net_amount';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Importe total de impuestos del documento.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'tax_amount';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Importe total del documento.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'total_amount';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Tipo de documento interno asociado opcional, por ejemplo remito, orden de compra o autorizacion. No representa CbtesAsoc fiscal.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'associated_document_type';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Numero del documento interno asociado opcional.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'associated_document_number';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Fecha del documento interno asociado opcional.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'associated_document_date';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Observaciones comerciales del documento.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'observations';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Snapshot JSON con informacion extra contextual del documento.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocuments',
    @level2type=N'COLUMN', @level2name=N'extra_info_json';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Detalles valorizados de documentos comerciales de venta.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Documento comercial al que pertenece el detalle.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'salesdocument_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Numero de linea dentro del documento.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'line_number';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Origen logico del item: Manual, QuoteDetail, Adjustment u otro valor definido por Domain/Core.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'origin_type';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Identificador generico del origen cuando aplique.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'origin_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Detalle del presupuesto aprobado que origina la linea, cuando exista. Puede ser NULL en ventas manuales.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'quote_detail_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Producto asociado a la linea, si aplica.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'product_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Descripcion visible de la linea facturada.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'description';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Cantidad facturada.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'quantity';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Precio unitario autorizado o de referencia proveniente del origen comercial.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'authorized_unit_price';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Importe autorizado o de referencia proveniente del origen comercial.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'authorized_amount';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Porcentaje facturado sobre el origen. Permite facturacion parcial obra social / particular.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'billed_percentage';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Precio unitario efectivo de la linea del documento.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'unit_price';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Importe neto de la linea.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'net_amount';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Importe de impuestos de la linea.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'tax_amount';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Importe total de la linea.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'total_amount';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Snapshot JSON del origen de la linea para trazabilidad historica.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesDocumentDetails',
    @level2type=N'COLUMN', @level2name=N'origin_snapshot_json';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Documento fiscal asociado a un documento comercial de venta. Guarda estado, CAE, numeracion fiscal, request/response e idempotencia ARCA.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Documento comercial interno vinculado al documento fiscal.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'salesdocument_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Estado fiscal independiente del estado comercial. Ejemplos: None, Pending, Authorized, Rejected, Error, PendingReconciliation.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'fiscal_status';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Ambiente fiscal usado para autorizacion: homologacion, produccion u otro valor definido por configuracion.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'environment';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Punto de venta fiscal ARCA/AFIP.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'point_of_sale';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Tipo de comprobante fiscal ARCA/AFIP utilizado en FECAESolicitar.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'voucher_type';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Letra fiscal del comprobante autorizado o a autorizar.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'voucher_letter';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Numero fiscal del comprobante asignado para ARCA. Se mantiene separado del numero interno.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'voucher_number';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Codigo de autorizacion electronico obtenido desde ARCA/AFIP.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'cae';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Fecha de vencimiento del CAE.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'cae_expiration_date';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Huella de idempotencia fiscal para evitar duplicacion de solicitudes ante ARCA.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'request_fingerprint';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Indica si el resultado fiscal es final y no debe volver a mutar salvo procesos controlados de auditoria.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'is_final';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Payload JSON enviado a ARCA/AFIP.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'arca_request_payload_json';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Payload JSON recibido desde ARCA/AFIP.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'arca_response_payload_json';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Errores devueltos por ARCA/AFIP serializados como JSON.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'errors_json';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Eventos devueltos por ARCA/AFIP serializados como JSON.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'events_json';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Observaciones devueltas por ARCA/AFIP serializadas como JSON.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'observations_json';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Fecha/hora UTC del intento de autorizacion fiscal.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'attempted_at_utc';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Fecha/hora UTC de finalizacion del flujo fiscal.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'completed_at_utc';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Indica que el documento fiscal fue resuelto mediante reconciliacion posterior a timeout o resultado ambiguo.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocuments',
    @level2type=N'COLUMN', @level2name=N'reconciled_after_timeout';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Comprobantes fiscales asociados enviados como CbtesAsoc. Aplica a notas de credito, notas de debito, NCE/NDE y casos FCE donde corresponda.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocumentAssociations';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Documento fiscal que contiene esta asociacion.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocumentAssociations',
    @level2type=N'COLUMN', @level2name=N'salesfiscaldocument_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Documento comercial interno asociado, si existe dentro de PhronCare.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocumentAssociations',
    @level2type=N'COLUMN', @level2name=N'associated_salesdocument_id';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Tipo fiscal ARCA/AFIP del comprobante asociado.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocumentAssociations',
    @level2type=N'COLUMN', @level2name=N'associated_voucher_type';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Punto de venta fiscal del comprobante asociado.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocumentAssociations',
    @level2type=N'COLUMN', @level2name=N'associated_point_of_sale';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Numero fiscal del comprobante asociado.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocumentAssociations',
    @level2type=N'COLUMN', @level2name=N'associated_voucher_number';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'CUIT emisor del comprobante asociado, cuando sea requerido por ARCA.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocumentAssociations',
    @level2type=N'COLUMN', @level2name=N'associated_voucher_cuit';

EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'Fecha del comprobante fiscal asociado.',
    @level0type=N'SCHEMA', @level0name=N'dbo',
    @level1type=N'TABLE', @level1name=N'PhS_SalesFiscalDocumentAssociations',
    @level2type=N'COLUMN', @level2name=N'associated_voucher_date';

