CREATE TABLE `warehouse` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `title` varchar(150) NOT NULL DEFAULT '',
    `comment` TEXT,
    PRIMARY KEY (`id`)
);

CREATE TABLE `stock_item_attribute_kit` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `title` varchar(150) NOT NULL DEFAULT '',
    PRIMARY KEY (`id`)
);

CREATE TABLE `stock_item_attribute` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `title` varchar(150) NOT NULL DEFAULT '',
    `type` tinyint,
    `required` tinyint NOT NULL DEFAULT 0,
    `unique_attr` tinyint NOT NULL DEFAULT 0,
    PRIMARY KEY (`id`)
);

CREATE TABLE `stock_item_attribute_link_kit` (
    `attribute_kit_id` int(10) unsigned NOT NULL,
    `attribute_id` int(10) unsigned NOT NULL,
    FOREIGN KEY (`attribute_id`) REFERENCES `stock_item_attribute` (`id`) ON DELETE CASCADE,
    FOREIGN KEY (`attribute_kit_id`) REFERENCES `stock_item_attribute_kit` (`id`) ON DELETE CASCADE
);

CREATE TABLE `stock_item_type` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `title` varchar(150) NOT NULL DEFAULT '',
    `stock_item_attribute_kit` int(10),
    `parent_type_id` int(10),
    PRIMARY KEY (`id`)
);

CREATE TABLE `stock_item` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `title` varchar(150) NOT NULL DEFAULT '',
    `warehouse_id` int(10) NOT NULL,
    `stock_item_type_id` int(10) unsigned NOT NULL,
    `contract_id` int(10) unsigned NOT NULL DEFAULT 0,
    PRIMARY KEY (`id`),
    FOREIGN KEY (`stock_item_type_id`) REFERENCES `stock_item_type` (`id`) ON DELETE CASCADE
);

CREATE TABLE `stock_item_attribute_value` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `stock_item_id` int(10) unsigned,
    `value` varchar(1024),
    `attribute_id` int(10) unsigned NOT NULL,
    PRIMARY KEY (`id`),
    FOREIGN KEY (`stock_item_id`) REFERENCES `stock_item` (`id`) ON DELETE CASCADE,
    FOREIGN KEY (`attribute_id`) REFERENCES `stock_item_attribute` (`id`) ON DELETE CASCADE
);

CREATE TABLE `contract_stock_item` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `stock_item_id` int(10) unsigned,
    `contract_id` int(10) unsigned,
    `date_from` datetime,
    `date_to` datetime,
    `user_id` int(10) unsigned,
    PRIMARY KEY (`id`)
);

CREATE TABLE `warehouse_operation` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `stock_item_id` int(10) unsigned,
    `stock_item_type_title` varchar(256) NO NULL DEFAULT '',
    `warehouse_from_id` int(10) unsigned,
    `warehouse_to_id` int(10) unsigned,
    `contract_id` int(10) unsigned,
    `operation_type` tinyint,
    `operation_time` datetime,
    `user_id` int(10) unsigned,
    PRIMARY KEY (`id`)
);