38808-vm/db/migrations/021_add_stock_module.sql
2026-03-27 03:32:55 +00:00

77 lines
3.0 KiB
SQL

-- 021_add_stock_module.sql
CREATE TABLE IF NOT EXISTS stock_stores (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
location VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS stock_categories (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS stock_items (
id INT AUTO_INCREMENT PRIMARY KEY,
category_id INT,
name VARCHAR(255) NOT NULL,
sku VARCHAR(100),
description TEXT,
min_quantity INT DEFAULT 0,
unit VARCHAR(50) DEFAULT 'piece',
image_path VARCHAR(255),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (category_id) REFERENCES stock_categories(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS stock_quantities (
id INT AUTO_INCREMENT PRIMARY KEY,
store_id INT NOT NULL,
item_id INT NOT NULL,
quantity DECIMAL(10,2) DEFAULT 0,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
UNIQUE KEY unique_item_store (store_id, item_id),
FOREIGN KEY (store_id) REFERENCES stock_stores(id) ON DELETE CASCADE,
FOREIGN KEY (item_id) REFERENCES stock_items(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS stock_transactions (
id INT AUTO_INCREMENT PRIMARY KEY,
transaction_type ENUM('in', 'out', 'transfer', 'damage', 'lend', 'return') NOT NULL,
store_id INT NOT NULL,
item_id INT NOT NULL,
quantity DECIMAL(10,2) NOT NULL,
user_id INT,
reference VARCHAR(255),
notes TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (store_id) REFERENCES stock_stores(id),
FOREIGN KEY (item_id) REFERENCES stock_items(id),
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS stock_lending (
id INT AUTO_INCREMENT PRIMARY KEY,
transaction_id INT NOT NULL,
borrower_name VARCHAR(255) NOT NULL,
borrower_phone VARCHAR(50),
expected_return_date DATE,
return_transaction_id INT,
status ENUM('active', 'returned', 'overdue') DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (transaction_id) REFERENCES stock_transactions(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Add default store if none exists
INSERT INTO stock_stores (name, location)
SELECT 'المستودع الرئيسي', 'المقر الرئيسي'
WHERE NOT EXISTS (SELECT 1 FROM stock_stores);
-- Add default category
INSERT INTO stock_categories (name)
SELECT 'عام'
WHERE NOT EXISTS (SELECT 1 FROM stock_categories);