-- Schema: order
-- Brief: used by the Sale Controller component to persist the orders
-- Created by: amerolli
-- Table schema_version: must be defined for database update through the Persistence Component
CREATE TABLE schema_version AS
SELECT "$Author: amerolli $" AS Author,
       "$Date: 2015-11-12 17:00:00 -0300 (Thu, 12 Nov 2015) $" AS LastModifiedAt,
       "$Revision: 60358be062aba0d49c3c2140fd9967181a3e8336$" AS Revision;

-- -------------------------
-- Orders schema definition
-- -------------------------
CREATE TABLE OrderState (
	StateId INTEGER NOT NULL,
	StateDescr CHAR(32) NOT NULL,
	PRIMARY KEY(StateId)
);

CREATE TABLE OrderType (
	TypeId INTEGER NOT NULL,
	TypeDescr CHAR(32) NOT NULL,
	PRIMARY KEY(TypeId)
);

CREATE TABLE SaleType (
	TypeId INTEGER NOT NULL,
	TypeDescr CHAR(32) NOT NULL,
	Abreviation VARCHAR(4),
	PRIMARY KEY(TypeId)
);

CREATE TABLE Orders (
	OrderId INTEGER NOT NULL,
	StateId INTEGER NOT NULL
		CONSTRAINT FK_Orders_StateId REFERENCES OrderState(StateId),
	OrderType INTEGER NOT NULL
		CONSTRAINT FK_Orders_OrderType REFERENCES OrderType(TypeId),
	OrderSubType VARCHAR(32),
	OriginatorId VARCHAR(50) NOT NULL,
	OriginatorNumber VARCHAR(50) NULL,
	SaleType INTEGER NOT NULL DEFAULT 0,
	ExemptionCode INTEGER NULL,
	LineCounter INTEGER NOT NULL DEFAULT 0,
	CreatedAt DATETIME NOT NULL,
	LastNewLineAt DATETIME NULL,
	LastModifiedLine INTEGER NOT NULL DEFAULT 0,
	BusinessPeriod DATE NULL,
	DistributionPoint VARCHAR(16) NULL,
	SessionId VARCHAR(50) NULL,
    PriceListId1 VARCHAR(8) NULL,
    PriceListId2 VARCHAR(8) NULL,
    PriceListId3 VARCHAR(8) NULL,
	AdditionalInfo VARCHAR(1024) NULL,
	PriceListTotal VARCHAR(30) NULL,
	TotalNet VARCHAR(30) NULL,
	TotalGross VARCHAR(30) NULL,
	DiscountAmount VARCHAR(30) NULL,
	TotalTaxIncluded INTEGER NOT NULL DEFAULT 1,
	TotalTaxAmountBD VARCHAR(30) NULL,
	TotalTaxAmountAD VARCHAR(30) NULL,
	Fiscal CHAR(1) NOT NULL DEFAULT 0,
	Backup CHAR(1) NOT NULL DEFAULT 0,
	MultiOrderId INTEGER NULL,
	Major INTEGER NULL,
	Minor INTEGER NULL,
	Tip VARCHAR(30) NULL,
	PRIMARY KEY (OrderId)
);

CREATE INDEX IDX_Orders_StateId_SessionId ON Orders(OrderId,StateId,SessionId);
CREATE INDEX IDX_Orders_StateId_DistributionPoint ON Orders(OrderId,StateId,DistributionPoint);
CREATE INDEX IDX_Orders_BusinessPeriod ON Orders(BusinessPeriod);
CREATE INDEX IDX_Orders_OrderType ON Orders(OrderId,OrderType);
CREATE INDEX IDX_Orders_OrderSubType ON Orders(OrderId,OrderSubType);

CREATE TABLE OrderCustomProperties (
	OrderId INTEGER NOT NULL,
	Key VARCHAR(50) NOT NULL,
	Value VARCHAR(1024) NOT NULL,
	PRIMARY KEY (OrderId,Key)
);

CREATE INDEX IDX_OrderCustomProperties_Key_Value ON OrderCustomProperties(Key,Value);

CREATE TABLE OrderItemCustomProperties (
	OrderId INTEGER NOT NULL,
	LineNumber INTEGER NOT NULL,
	ItemId VARCHAR(50) NOT NULL,
	Level VARCHAR(30) NOT NULL DEFAULT '0',
	PartCode INTEGER NOT NULL,
	Key VARCHAR(50) NOT NULL,
	Value VARCHAR(1024) NOT NULL,
	PRIMARY KEY (OrderId, LineNumber, ItemId, Level, PartCode, Key)
);

CREATE TABLE OrderStateHistory (
	OrderId INTEGER NOT NULL
		CONSTRAINT FK_OrderStateHistory_OrderId REFERENCES Orders(OrderId),
	StateId INTEGER NOT NULL
		CONSTRAINT FK_OrderStateHistory_StateId REFERENCES OrderState(StateId),
	Timestamp DATETIME NOT NULL,
	PRIMARY KEY(OrderId, StateId, Timestamp)
);

CREATE TABLE OrderItem (
	OrderId INTEGER NOT NULL
		CONSTRAINT FK_OrderItem_OrderId REFERENCES Orders(OrderId),
	LineNumber INTEGER NOT NULL,
	ItemId VARCHAR(50) NOT NULL,
	Level VARCHAR(30) NOT NULL DEFAULT '0',
	PartCode INTEGER NOT NULL,
	OrderedQty VARCHAR(30) NULL DEFAULT 1,
	LastOrderedQty INTEGER NULL,
	IncQty INTEGER NOT NULL DEFAULT 0,
	DecQty INTEGER NOT NULL DEFAULT 0,
	PriceKey INTEGER NULL,
	DiscountAmount VARCHAR(30) NOT NULL DEFAULT '0.00',
	SurchargeAmount VARCHAR(30) NOT NULL DEFAULT '0.00',
	OnlyFlag INTEGER NOT NULL DEFAULT 0,
	OverwrittenUnitPrice VARCHAR(30) NULL,
	DefaultQty INTEGER NULL,
	LastUpdate DATETIME NULL,
	PRIMARY KEY(OrderId, LineNumber, ItemId, Level, PartCode)
);

CREATE INDEX IDX_OrderItem_OrderId ON OrderItem(OrderId);
CREATE INDEX IDX_OrderItem_ItemId_PartCode ON OrderItem(ItemId,PartCode);
CREATE INDEX IDX_OrderItem_OrderId_LineNumber_Level ON OrderItem(OrderId,LineNumber,Level);

CREATE TABLE OrderTax (
	OrderId INTEGER NOT NULL,
	LineNumber INTEGER NOT NULL,
	ItemId VARCHAR(50) NOT NULL,
	Level VARCHAR(30) NOT NULL,
	PartCode INTEGER NOT NULL,
	TaxRuleId INTEGER NOT NULL,
	BaseAmountBD VARCHAR(30) NULL,
	BaseAmountAD VARCHAR(30) NULL,
	TaxAmountBD VARCHAR(30) NULL,
	TaxAmountAD VARCHAR(30) NULL,
  TaxFiscalIndex VARCHAR(30) NULL,
	TaxIncluded INTEGER NOT NULL DEFAULT 1,
	TaxRate VARCHAR(30) NULL,
	TaxAmount VARCHAR(30) NULL,
	PRIMARY KEY(OrderId, LineNumber, ItemId, Level, PartCode, TaxRuleId)
);

CREATE INDEX IDX_OrderTax_OrderTaxView ON OrderTax(OrderId, LineNumber, ItemId, Level, PartCode);

CREATE TABLE OrderDiscount (
	OrderId INTEGER NOT NULL,
	LineNumber INTEGER NOT NULL,
	ItemId VARCHAR(50) NOT NULL,
	Level VARCHAR(30) NOT NULL,
	PartCode INTEGER NOT NULL,
	DiscountId INTEGER NOT NULL,
	DiscountAmount VARCHAR(30) NOT NULL,
	PRIMARY KEY(OrderId, LineNumber, ItemId, Level, PartCode, DiscountId)
);

CREATE INDEX IDX_OrderDiscount_OrderDiscountView ON OrderDiscount(OrderId, LineNumber, ItemId, Level, PartCode);

CREATE TABLE OrderVoidHistory (
	OrderId INTEGER NOT NULL,
	LineNumber INTEGER NOT NULL,
	ItemId VARCHAR(50) NOT NULL,
	Level VARCHAR(30) NOT NULL,
	PartCode INTEGER NOT NULL,
	Timestamp NOT NULL,
	DecQty INTEGER NOT NULL,
	PriceKey INTEGER NULL,
	OverwrittenUnitPrice VARCHAR(30) NULL,
	AfterTotal INTEGER NOT NULL DEFAULT 0,
	PRIMARY KEY(OrderId, LineNumber, ItemId, Level, PartCode, Timestamp)
);

CREATE INDEX IDX_OrderVoidHistory_OrderId ON OrderVoidHistory(OrderId);

CREATE TABLE OrderTender (
	OrderTenderId 			INTEGER NOT NULL,
	OrderId 				INTEGER NOT NULL
		CONSTRAINT FK_OrderTender_OrderId REFERENCES Orders(OrderId),
	TenderId 				INTEGER NOT NULL,
	Timestamp 				NOT NULL,
	TenderAmount 			VARCHAR(30) NOT NULL DEFAULT '0.00',
	TenderForeignAmount 	VARCHAR(30),
	ExchangeRateId 			INTEGER,
	TenderDetail 			VARCHAR(50),
	TipAmount 				VARCHAR(30),
	ChangeAmount 			VARCHAR(30),
	TenderDescr       		CHAR(32),
	ElectronicType    		INTEGER,
	PRIMARY KEY(OrderTenderId, OrderId)
);
CREATE INDEX IDX_OrderTender_OrderId  ON OrderTender(OrderId);
CREATE INDEX IDX_OrderTender_TenderId ON OrderTender(TenderId);

CREATE TABLE OrderComment (
	CommentId INTEGER NOT NULL,
	OrderId INTEGER NOT NULL,
	LineNumber INTEGER NOT NULL,
	ItemId VARCHAR(50) NOT NULL,
	Level VARCHAR(30) NOT NULL,
	PartCode INTEGER NOT NULL,
	Comment VARCHAR(256) NOT NULL,
	Hash INTEGER NOT NULL DEFAULT 0,
	PRIMARY KEY (CommentId, OrderId, LineNumber, ItemId, Level, PartCode)
);


CREATE TABLE POS (
	POSId INTEGER NOT NULL,
	CurrentOrder INTEGER,
	ProdDescrId INTEGER,
	RoundingModeId INTEGER NOT NULL DEFAULT 0,
	RoundingScale INTEGER NOT NULL DEFAULT 2,
	CustomData VARCHAR,
	PRIMARY KEY(POSId)
);

CREATE TABLE OrderPrice (
	OrderId INTEGER NOT NULL
		CONSTRAINT FK_OrderPrice_OrderId REFERENCES Orders(OrderId),
	PriceKey INTEGER NOT NULL,
	DefaultUnitPrice VARCHAR(30),
	AddedUnitPrice VARCHAR(30),
	SubtractedUnitPrice VARCHAR(30),
	Computed SMALLINT DEFAULT 1,
	IncludedQty INTEGER,
	ValidFrom DATETIME,
	ValidThru DATETIME,
	PRIMARY KEY(OrderId, PriceKey)
);

CREATE TABLE OrderProduct (
	OrderId 			INTEGER NOT NULL
		CONSTRAINT FK_OrderProduct_OrderId REFERENCES Orders(OrderId),
	ProductCode         INTEGER NOT NULL,
	PartCode            INTEGER NOT NULL,
    ProductName         VARCHAR(50),
	ProductType         VARCHAR(15),
    DefaultQty          INTEGER,
    MinQty              INTEGER,
    MaxQty              INTEGER,
    MeasureUnit         VARCHAR(5),
	ProductPriority     INTEGER DEFAULT 100,
	JsonArrayTags       VARCHAR(1024),
    PRIMARY KEY(OrderId, ProductCode, PartCode)
);
CREATE INDEX IDX_OrderProduct_OrderId ON OrderProduct(OrderId);
CREATE INDEX IDX_OrderProduct_OrderId_ProductCode_PartCode ON OrderProduct(OrderId, ProductCode, PartCode);

CREATE TABLE OrderChangeTimestamp (
	OrderId INTEGER NOT NULL CONSTRAINT FK_OrderChangeTimestamp_OrderId REFERENCES Orders(OrderId),
	LastChangedAt DATETIME NULL,
	PRIMARY KEY(OrderId)
);
CREATE INDEX IDX_OrderChangeTimestamp_OrderId ON OrderChangeTimestamp(OrderId);

-- Foreign Key Preventing insert
CREATE TRIGGER fki_Orders_StateId_OrderState_StateId
BEFORE INSERT ON [Orders]
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'insert on table "Orders" violates foreign key constraint "fki_Orders_StateId_OrderState_StateId"')
  WHERE (SELECT StateId FROM OrderState WHERE StateId = NEW.StateId) IS NULL;
END;

-- Foreign key preventing update
CREATE TRIGGER fku_Orders_StateId_OrderState_StateId
BEFORE UPDATE ON [Orders]
FOR EACH ROW BEGIN
    SELECT RAISE(ROLLBACK, 'update on table "Orders" violates foreign key constraint "fku_Orders_StateId_OrderState_StateId"')
      WHERE (SELECT StateId FROM OrderState WHERE StateId = NEW.StateId) IS NULL;
END;

-- Foreign key preventing delete
CREATE TRIGGER fkd_Orders_StateId_OrderState_StateId
BEFORE DELETE ON OrderState
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'delete on table "OrderState" violates foreign key constraint "fkd_Orders_StateId_OrderState_StateId"')
  WHERE (SELECT StateId FROM Orders WHERE StateId = OLD.StateId) IS NOT NULL;
END;

-- Foreign Key Preventing insert
CREATE TRIGGER fki_Orders_OrderType_OrderType_TypeId
BEFORE INSERT ON [Orders]
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'insert on table "Orders" violates foreign key constraint "fki_Orders_OrderType_OrderType_TypeId"')
  WHERE (SELECT TypeId FROM OrderType WHERE TypeId = NEW.OrderType) IS NULL;
END;

-- Foreign key preventing update
CREATE TRIGGER fku_Orders_OrderType_OrderType_TypeId
BEFORE UPDATE ON [Orders]
FOR EACH ROW BEGIN
    SELECT RAISE(ROLLBACK, 'update on table "Orders" violates foreign key constraint "fku_Orders_OrderType_OrderType_TypeId"')
      WHERE (SELECT TypeId FROM OrderType WHERE TypeId = NEW.OrderType) IS NULL;
END;

-- Foreign key preventing delete
CREATE TRIGGER fkd_Orders_OrderType_OrderType_TypeId
BEFORE DELETE ON OrderType
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'delete on table "OrderType" violates foreign key constraint "fkd_Orders_OrderType_OrderType_TypeId"')
  WHERE (SELECT OrderType FROM Orders WHERE OrderType = OLD.TypeId) IS NOT NULL;
END;

-- Foreign Key Preventing insert
CREATE TRIGGER fki_OrderStateHistory_OrderId_Orders_OrderId
BEFORE INSERT ON [OrderStateHistory]
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'insert on table "OrderStateHistory" violates foreign key constraint "fki_OrderStateHistory_OrderId_Orders_OrderId"')
  WHERE (SELECT OrderId FROM Orders WHERE OrderId = NEW.OrderId) IS NULL;
END;

-- Foreign key preventing update
CREATE TRIGGER fku_OrderStateHistory_OrderId_Orders_OrderId
BEFORE UPDATE ON [OrderStateHistory]
FOR EACH ROW BEGIN
    SELECT RAISE(ROLLBACK, 'update on table "OrderStateHistory" violates foreign key constraint "fku_OrderStateHistory_OrderId_Orders_OrderId"')
      WHERE (SELECT OrderId FROM Orders WHERE OrderId = NEW.OrderId) IS NULL;
END;

-- Foreign key preventing delete
CREATE TRIGGER fkd_OrderStateHistory_OrderId_Orders_OrderId
BEFORE DELETE ON Orders
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'delete on table "Orders" violates foreign key constraint "fkd_OrderStateHistory_OrderId_Orders_OrderId"')
  WHERE (SELECT OrderId FROM OrderStateHistory WHERE OrderId = OLD.OrderId) IS NOT NULL;
END;

-- Foreign Key Preventing insert
CREATE TRIGGER fki_OrderStateHistory_StateId_OrderState_StateId
BEFORE INSERT ON [OrderStateHistory]
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'insert on table "OrderStateHistory" violates foreign key constraint "fki_OrderStateHistory_StateId_OrderState_StateId"')
  WHERE (SELECT StateId FROM OrderState WHERE StateId = NEW.StateId) IS NULL;
END;

-- Foreign key preventing update
CREATE TRIGGER fku_OrderStateHistory_StateId_OrderState_StateId
BEFORE UPDATE ON [OrderStateHistory]
FOR EACH ROW BEGIN
    SELECT RAISE(ROLLBACK, 'update on table "OrderStateHistory" violates foreign key constraint "fku_OrderStateHistory_StateId_OrderState_StateId"')
      WHERE (SELECT StateId FROM OrderState WHERE StateId = NEW.StateId) IS NULL;
END;

-- Foreign key preventing delete
CREATE TRIGGER fkd_OrderStateHistory_StateId_OrderState_StateId
BEFORE DELETE ON OrderState
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'delete on table "OrderState" violates foreign key constraint "fkd_OrderStateHistory_StateId_OrderState_StateId"')
  WHERE (SELECT StateId FROM OrderStateHistory WHERE StateId = OLD.StateId) IS NOT NULL;
END;

-- Foreign Key Preventing insert
CREATE TRIGGER fki_OrderItem_OrderId_Orders_OrderId
BEFORE INSERT ON [OrderItem]
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'insert on table "OrderItem" violates foreign key constraint "fki_OrderItem_OrderId_Orders_OrderId"')
  WHERE (SELECT OrderId FROM Orders WHERE OrderId = NEW.OrderId) IS NULL;
END;

-- Foreign key preventing update
CREATE TRIGGER fku_OrderItem_OrderId_Orders_OrderId
BEFORE UPDATE ON [OrderItem]
FOR EACH ROW BEGIN
    SELECT RAISE(ROLLBACK, 'update on table "OrderItem" violates foreign key constraint "fku_OrderItem_OrderId_Orders_OrderId"')
      WHERE (SELECT OrderId FROM Orders WHERE OrderId = NEW.OrderId) IS NULL;
END;

-- Foreign key preventing delete
CREATE TRIGGER fkd_OrderItem_OrderId_Orders_OrderId
BEFORE DELETE ON Orders
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'delete on table "Orders" violates foreign key constraint "fkd_OrderItem_OrderId_Orders_OrderId"')
  WHERE (SELECT OrderId FROM OrderItem WHERE OrderId = OLD.OrderId) IS NOT NULL;
END;

-- Foreign Key Preventing insert
CREATE TRIGGER fki_OrderTender_OrderId_Orders_OrderId
BEFORE INSERT ON [OrderTender]
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'insert on table "OrderTender" violates foreign key constraint "fki_OrderTender_OrderId_Orders_OrderId"')
  WHERE (SELECT OrderId FROM Orders WHERE OrderId = NEW.OrderId) IS NULL;
END;

-- Foreign key preventing update
CREATE TRIGGER fku_OrderTender_OrderId_Orders_OrderId
BEFORE UPDATE ON [OrderTender]
FOR EACH ROW BEGIN
    SELECT RAISE(ROLLBACK, 'update on table "OrderTender" violates foreign key constraint "fku_OrderTender_OrderId_Orders_OrderId"')
      WHERE (SELECT OrderId FROM Orders WHERE OrderId = NEW.OrderId) IS NULL;
END;

-- Foreign key preventing delete
CREATE TRIGGER fkd_OrderTender_OrderId_Orders_OrderId
BEFORE DELETE ON Orders
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'delete on table "Orders" violates foreign key constraint "fkd_OrderTender_OrderId_Orders_OrderId"')
  WHERE (SELECT OrderId FROM OrderTender WHERE OrderId = OLD.OrderId) IS NOT NULL;
END;

-- Foreign Key Preventing insert
CREATE TRIGGER fki_OrderProduct_OrderId_Orders_OrderId
BEFORE INSERT ON [OrderProduct]
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'insert on table "OrderProduct" violates foreign key constraint "fki_OrderProduct_OrderId_Orders_OrderId"')
  WHERE (SELECT OrderId FROM Orders WHERE OrderId = NEW.OrderId) IS NULL;
END;

-- Foreign key preventing update
CREATE TRIGGER fku_OrderProduct_OrderId_Orders_OrderId
BEFORE UPDATE ON [OrderProduct]
FOR EACH ROW BEGIN
    SELECT RAISE(ROLLBACK, 'update on table "OrderProduct" violates foreign key constraint "fku_OrderProduct_OrderId_Orders_OrderId"')
      WHERE (SELECT OrderId FROM Orders WHERE OrderId = NEW.OrderId) IS NULL;
END;

-- Foreign key preventing delete
CREATE TRIGGER fkd_OrderProduct_OrderId_Orders_OrderId
BEFORE DELETE ON Orders
FOR EACH ROW BEGIN
  SELECT RAISE(ROLLBACK, 'delete on table "Orders" violates foreign key constraint "fkd_OrderProduct_OrderId_Orders_OrderId"')
  WHERE (SELECT OrderId FROM OrderProduct WHERE OrderId = OLD.OrderId) IS NOT NULL;
END;


-- -------------------------------
-- CurrentOrderItem defition
-- ------------------------------

CREATE TABLE CurrentOrderItem (
	OrderId INTEGER NOT NULL,
	LineNumber INTEGER NOT NULL,
	ItemId VARCHAR(50) NOT NULL,
	Level VARCHAR(30) NOT NULL DEFAULT '0',
	PartCode INTEGER NOT NULL,
	OrderedQty VARCHAR(30) NULL DEFAULT 1,
	LastOrderedQty INTEGER NULL,
	IncQty INTEGER NOT NULL DEFAULT 0,
	DecQty INTEGER NOT NULL DEFAULT 0,
	PriceKey INTEGER NULL,
	DiscountAmount VARCHAR(30) NOT NULL DEFAULT '0.00',
	SurchargeAmount VARCHAR(30) NOT NULL DEFAULT '0.00',
	OnlyFlag INTEGER NOT NULL DEFAULT 0,
	OverwrittenUnitPrice VARCHAR(30) NULL,
	DefaultQty INTEGER NULL,
	LastUpdate DATETIME NULL,
	PRIMARY KEY(OrderId, LineNumber, ItemId, Level, PartCode)
);

CREATE TRIGGER IF NOT EXISTS CurrentOrderItem_AfterUpdateOfDecQty
AFTER UPDATE OF DecQty ON CurrentOrderItem
FOR EACH ROW WHEN ((NEW.DecQty-OLD.DecQty)>0 AND (SELECT COUNT() FROM Orders WHERE OrderId=NEW.OrderId AND StateId IN (1,3))>0)
BEGIN
	INSERT INTO OrderVoidHistory(OrderId,LineNumber,ItemId,Level,PartCode,Timestamp,DecQty,PriceKey,OverwrittenUnitPrice,AfterTotal)
	SELECT OrderId, LineNumber, ItemId, Level, PartCode, Timestamp, DecQty, PriceKey, OverwrittenUnitPrice, (CASE WHEN COALESCE(FirstTotalTimestamp, Timestamp) < Timestamp THEN 1 ELSE 0 END)
	FROM (
		SELECT
			NEW.OrderId AS OrderId,
			NEW.LineNumber AS LineNumber,
			NEW.ItemId AS ItemId,
			NEW.Level AS Level,
			NEW.PartCode AS PartCode,
			strftime('%Y-%m-%dT%H:%M:%f','now') AS Timestamp,
			(NEW.DecQty-OLD.DecQty) AS DecQty,
			NEW.PriceKey AS PriceKey,
			NEW.OverwrittenUnitPrice AS OverwrittenUnitPrice,
			(SELECT MIN(Timestamp) FROM OrderStateHistory WHERE OrderId=NEW.OrderId AND StateId=3) AS FirstTotalTimestamp
	) AS OrderVoid;
END;

CREATE TRIGGER IF NOT EXISTS CurrentOrderItem_BeforeInsert
BEFORE INSERT ON CurrentOrderItem
FOR EACH ROW WHEN ((SELECT COUNT() FROM Orders WHERE OrderId=NEW.OrderId AND StateId IN (1,3))>0)
BEGIN
	INSERT INTO OrderItem(OrderId, LineNumber, ItemId, Level, PartCode, OrderedQty, LastOrderedQty, IncQty, DecQty, PriceKey, DiscountAmount, SurchargeAmount, OnlyFlag, OverwrittenUnitPrice, DefaultQty, LastUpdate)
	VALUES(NEW.OrderId, NEW.LineNumber, NEW.ItemId, NEW.Level, NEW.PartCode, NEW.OrderedQty, NEW.LastOrderedQty, NEW.IncQty, NEW.DecQty, NEW.PriceKey, NEW.DiscountAmount, NEW.SurchargeAmount, NEW.OnlyFlag, NEW.OverwrittenUnitPrice, NEW.DefaultQty, NEW.LastUpdate);
END;

CREATE TRIGGER IF NOT EXISTS CurrentOrderItem_BeforeUpdate
BEFORE UPDATE ON CurrentOrderItem
FOR EACH ROW WHEN ((SELECT COUNT() FROM Orders WHERE OrderId=NEW.OrderId AND StateId IN (1,3))>0)
BEGIN
	UPDATE OrderItem
	SET OrderedQty=NEW.OrderedQty,
	    LastOrderedQty=NEW.LastOrderedQty,
	    IncQty=NEW.IncQty,
		DecQty=NEW.DecQty,
		PriceKey=NEW.PriceKey,
		DiscountAmount=NEW.DiscountAmount,
		SurchargeAmount=NEW.SurchargeAmount,
		ItemId=COALESCE(NEW.ItemId,OLD.ItemId),
		Level=COALESCE(NEW.Level,OLD.Level),
		PartCode=COALESCE(NEW.PartCode,OLD.PartCode),
		OnlyFlag=NEW.OnlyFlag,
		OverwrittenUnitPrice=NEW.OverwrittenUnitPrice,
		DefaultQty=NEW.DefaultQty,
		LastUpdate=NEW.LastUpdate
	WHERE OrderId=OLD.OrderId AND
	      LineNumber=OLD.LineNumber AND
		  ItemId=OLD.ItemId AND
		  Level=OLD.Level AND
		  PartCode=OLD.PartCode;
END;

CREATE TRIGGER IF NOT EXISTS CurrentOrderItem_BeforeDelete
BEFORE DELETE ON CurrentOrderItem
FOR EACH ROW WHEN ((SELECT COUNT() FROM Orders WHERE OrderId=OLD.OrderId AND StateId=1)>0)
BEGIN
	DELETE FROM OrderItem
	WHERE OrderId=OLD.OrderId AND
	      LineNumber=OLD.LineNumber AND
		  ItemId=OLD.ItemId AND
		  Level=OLD.Level AND
		  PartCode=OLD.PartCode;
END;

CREATE TRIGGER IF NOT EXISTS POS_BeforeInsert
BEFORE INSERT ON POS WHEN ((NEW.CurrentOrder IS NOT NULL) AND ((SELECT COUNT(*) FROM CurrentOrderItem WHERE OrderId=NEW.CurrentOrder)==0))
BEGIN
	DELETE FROM CurrentOrderItem WHERE OrderId IN (SELECT CurrentOrder FROM POS WHERE POSId=NEW.POSId);
	INSERT INTO CurrentOrderItem(OrderId, LineNumber, ItemId, Level, PartCode, OrderedQty, LastOrderedQty, IncQty, DecQty, PriceKey, DiscountAmount, SurchargeAmount, OnlyFlag, OverwrittenUnitPrice, DefaultQty, LastUpdate)
	SELECT OrderId, LineNumber, ItemId, Level, PartCode, OrderedQty, LastOrderedQty, IncQty, DecQty, PriceKey, DiscountAmount, SurchargeAmount, OnlyFlag, OverwrittenUnitPrice, DefaultQty, LastUpdate
	FROM OrderItem WHERE OrderId=NEW.CurrentOrder;
END;

CREATE TRIGGER IF NOT EXISTS POS_BeforeDelete
BEFORE DELETE ON POS
BEGIN
	DELETE FROM CurrentOrderItem;
END;

-- ------------------------------
-- Tables and triggers for
-- current order backup/restore
-- feature.
-- ------------------------------

-- BackupOrders: equivalient to Orders table.
CREATE TABLE BackupOrders (
	OrderId				INTEGER,
	StateId				INTEGER,
	OrderType			INTEGER,
    OrderSubType        VARCHAR(32),
	OriginatorId		VARCHAR(50),
	OriginatorNumber	VARCHAR(50),
	SaleType			INTEGER,
	ExemptionCode		INTEGER,
	LineCounter			INTEGER,
	CreatedAt			DATETIME,
	LastNewLineAt		DATETIME,
	LastModifiedLine	INTEGER,
	BusinessPeriod		DATE,
	DistributionPoint	VARCHAR(16),
	SessionId			VARCHAR(50),
    PriceListId1		VARCHAR(8),
    PriceListId2		VARCHAR(8),
    PriceListId3		VARCHAR(8),
	AdditionalInfo		VARCHAR(1024),
	PriceListTotal		VARCHAR(30),
	TotalNet			VARCHAR(30),
	TotalGross			VARCHAR(30),
	DiscountAmount		VARCHAR(30),
	TotalTaxIncluded	INTEGER,
	TotalTaxAmountBD	VARCHAR(30),
	TotalTaxAmountAD	VARCHAR(30),
	Fiscal				CHAR(1),
	Backup				CHAR(1),
	MultiOrderId		INTEGER,
	Major				INTEGER,
	Minor				INTEGER,
	Tip                 VARCHAR(30)
);
CREATE INDEX IDX_BackupOrders_OrderId ON BackupOrders(OrderId);

-- BackupCurrentOrderItem: equivalient to CurrentOrderItem table.
CREATE TABLE BackupCurrentOrderItem (
	OrderId					INTEGER,
	LineNumber				INTEGER,
	ItemId					VARCHAR(50),
	Level					VARCHAR(30),
	PartCode				INTEGER,
	OrderedQty				INTEGER,
	LastOrderedQty			INTEGER,
	IncQty					INTEGER,
	DecQty					INTEGER,
	PriceKey				INTEGER,
	DiscountAmount			VARCHAR(30),
	SurchargeAmount			VARCHAR(30),
	OnlyFlag				INTEGER,
	OverwrittenUnitPrice	VARCHAR(30),
	DefaultQty				INTEGER,
	LastUpdate DATETIME NULL
);
CREATE INDEX IDX_BackupCurrentOrderItem_OrderId ON BackupCurrentOrderItem(OrderId);

CREATE TRIGGER IF NOT EXISTS TGR_CurrentOrderBackup
BEFORE UPDATE OF Backup ON Orders WHEN (CAST(NEW.Backup AS INTEGER)=1 AND CAST(OLD.Backup AS INTEGER)=0 AND CAST(NEW.StateId AS INTEGER) IN(1,3))
BEGIN
	DELETE FROM BackupOrders WHERE OrderId=NEW.OrderId;
	DELETE FROM BackupCurrentOrderItem WHERE OrderId=NEW.OrderId;
	INSERT INTO BackupOrders SELECT * FROM Orders WHERE OrderId=NEW.OrderId;
	INSERT INTO BackupCurrentOrderItem SELECT * FROM CurrentOrderItem WHERE OrderId=NEW.OrderId;
END;

CREATE TRIGGER IF NOT EXISTS TGR_CurrentOrderBackupReset
AFTER UPDATE OF Backup ON Orders WHEN (CAST(NEW.Backup AS INTEGER)=2 OR (CAST(OLD.Backup AS INTEGER)=1 AND CAST(NEW.StateId AS INTEGER) NOT IN(1,3)))
BEGIN
	DELETE FROM BackupOrders WHERE OrderId=NEW.OrderId;
	DELETE FROM BackupCurrentOrderItem WHERE OrderId=NEW.OrderId;
	UPDATE Orders SET Backup=0 WHERE OrderId=NEW.OrderId;
END;

CREATE TRIGGER IF NOT EXISTS TGR_CurrentOrderRestore
AFTER UPDATE OF Backup ON Orders WHEN (CAST(NEW.Backup AS INTEGER)=0 AND CAST(OLD.Backup AS INTEGER)=1 AND CAST(NEW.StateId AS INTEGER) IN(1,3))
BEGIN
	INSERT OR REPLACE INTO Orders(OrderId,StateId,OrderType,OrderSubType,OriginatorId,OriginatorNumber,SaleType,ExemptionCode,LineCounter,CreatedAt,LastNewLineAt,LastModifiedLine,BusinessPeriod,DistributionPoint,SessionId,PriceListId1,PriceListId2,PriceListId3,AdditionalInfo,PriceListTotal,TotalNet,TotalGross,DiscountAmount,TotalTaxIncluded,TotalTaxAmountBD,TotalTaxAmountAD,Fiscal,MultiOrderId,Major,Minor,Tip)
	SELECT OrderId,StateId,OrderType,OrderSubType,OriginatorId,OriginatorNumber,SaleType,ExemptionCode,LineCounter,CreatedAt,LastNewLineAt,LastModifiedLine,BusinessPeriod,DistributionPoint,SessionId,PriceListId1,PriceListId2,PriceListId3,AdditionalInfo,PriceListTotal,TotalNet,TotalGross,DiscountAmount,TotalTaxIncluded,TotalTaxAmountBD,TotalTaxAmountAD,Fiscal,MultiOrderId,Major,Minor,Tip
	FROM BackupOrders WHERE OrderId=NEW.OrderId;
	DELETE FROM CurrentOrderItem WHERE OrderId=NEW.OrderId;
	INSERT INTO CurrentOrderItem SELECT * FROM BackupCurrentOrderItem WHERE OrderId=NEW.OrderId;
	DELETE FROM BackupOrders WHERE OrderId=NEW.OrderId;
	DELETE FROM BackupCurrentOrderItem WHERE OrderId=NEW.OrderId;
END;

-- ------------------------------
-- Order initial data
-- ------------------------------

BEGIN TRANSACTION;

-- ------------------------------
-- Currently defined order states
-- ------------------------------
INSERT INTO OrderState(StateId,StateDescr) VALUES(0,'UNDEFINED');
INSERT INTO OrderState(StateId,StateDescr) VALUES(1,'IN_PROGRESS');
INSERT INTO OrderState(StateId,StateDescr) VALUES(2,'STORED');
INSERT INTO OrderState(StateId,StateDescr) VALUES(3,'TOTALED');
INSERT INTO OrderState(StateId,StateDescr) VALUES(4,'VOIDED');
INSERT INTO OrderState(StateId,StateDescr) VALUES(5,'PAID');
INSERT INTO OrderState(StateId,StateDescr) VALUES(6,'RECALLED');
INSERT INTO OrderState(StateId,StateDescr) VALUES(7,'SYSTEM_VOIDED');
INSERT INTO OrderState(StateId,StateDescr) VALUES(8,'ABANDONED');

-- ------------------------------
-- Currently known order types
-- ------------------------------
INSERT INTO OrderType(TypeId,TypeDescr) VALUES(0,'SALE');
INSERT INTO OrderType(TypeId,TypeDescr) VALUES(1,'REFUND');
INSERT INTO OrderType(TypeId,TypeDescr) VALUES(2,'WASTE');
INSERT INTO OrderType(TypeId,TypeDescr) VALUES(3,'SKIPCAR');

-- ------------------------------
-- Currently known sale types
-- ------------------------------
INSERT INTO SaleType(TypeId,TypeDescr,Abreviation) VALUES(0,'EAT_IN', 'EI');
INSERT INTO SaleType(TypeId,TypeDescr,Abreviation) VALUES(1,'TAKE_OUT', 'TO');
INSERT INTO SaleType(TypeId,TypeDescr,Abreviation) VALUES(2,'DRIVE_THRU', 'DT');
INSERT INTO SaleType(TypeId,TypeDescr,Abreviation) VALUES(3,'DELIVERY', 'DL');

COMMIT TRANSACTION;
