초기화

This commit is contained in:
2026-07-15 18:37:19 +09:00
commit 94abc5461d
1268 changed files with 380198 additions and 0 deletions
+553
View File
@@ -0,0 +1,553 @@
-- phpMyAdmin SQL Dump
-- version 5.2.2
-- https://www.phpmyadmin.net/
--
-- 호스트: localhost
-- 생성 시간: 26-06-22 18:35
-- 서버 버전: 10.11.11-MariaDB
-- PHP 버전: 8.2.28
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- 데이터베이스: `carbon_cutting_mc_db`
--
-- --------------------------------------------------------
--
-- 테이블 구조 `contacts`
--
CREATE TABLE `contacts` (
`id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
`name` varchar(100) NOT NULL,
`email` varchar(255) DEFAULT NULL,
`phone_number` varchar(50) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`position` varchar(255) DEFAULT '',
`work_location` varchar(255) DEFAULT '',
`is_deleted` tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- 테이블 구조 `control_target`
--
CREATE TABLE `control_target` (
`equipment_id` int(11) NOT NULL,
`operation_mode_target` varchar(20) DEFAULT NULL COMMENT 'Target mode (auto, manual)',
`operation_command_target` varchar(20) DEFAULT NULL COMMENT 'Target command (start, stop, reset)',
`line_heaters_target` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Target for 20 heaters. e.g., {"heater_1": 1, "heater_2": 0}' CHECK (json_valid(`line_heaters_target`)),
`line_feeders_target` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Target for 10 feeder motors. e.g., {"line_1": 1} (0:STOP, 1:FWD,2:REV)' CHECK (json_valid(`line_feeders_target`)),
`utility_target` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Target for pumps and fans. e.g., {"pumps": {"pump_1": 1}, "fans":{"fan_1": 1}}' CHECK (json_valid(`utility_target`)),
`transfer_roller_target` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Target for transfer roller. e.g., {"speed": 120.5, "direction":1, "enabled": 1}' CHECK (json_valid(`transfer_roller_target`)),
`cutting_motor_target` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Target for cutting motor. e.g., {"speed": 300.0, "direction": 0,"enabled": 1}' CHECK (json_valid(`cutting_motor_target`)),
`system_outputs_target` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Target for buzzer, tower light. e.g., {"buzzer": 0, "tower_red":1}' CHECK (json_valid(`system_outputs_target`)),
`spare_digital_outputs_target` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Target for spare digital outputs. e.g., {"R21": 1, "R24":0}' CHECK (json_valid(`spare_digital_outputs_target`)),
`spare_pwm_outputs_target` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'Target for spare PWM outputs. e.g., {"D10": 128, "D11": 255}' CHECK (json_valid(`spare_pwm_outputs_target`)),
`last_updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='Target control states set by users or apps.';
-- --------------------------------------------------------
--
-- 테이블 구조 `customers`
--
CREATE TABLE `customers` (
`id` int(11) NOT NULL,
`name_kr` varchar(255) NOT NULL,
`name_en` varchar(255) DEFAULT NULL,
`business_registration_number` varchar(50) DEFAULT NULL,
`contact_number` varchar(50) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- 테이블 구조 `equipment`
--
CREATE TABLE `equipment` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`yarn_bobbin_count` int(11) DEFAULT NULL,
`dryer_type` varchar(255) DEFAULT NULL,
`power_consumption` double DEFAULT NULL,
`max_cutting_speed` int(11) DEFAULT NULL,
`max_feed_speed` int(11) DEFAULT NULL,
`status` varchar(50) NOT NULL DEFAULT 'available' COMMENT '장비의 현재 상태 (available, maintenance, broken)'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- 테이블 구조 `inventory`
--
CREATE TABLE `inventory` (
`id` int(11) NOT NULL,
`material_id` int(11) DEFAULT NULL COMMENT 'material_properties 테이블 ID',
`item_name` varchar(255) NOT NULL,
`item_number` varchar(255) NOT NULL,
`supplier` varchar(255) NOT NULL,
`supplier_id` int(11) DEFAULT NULL,
`receipt_date` date NOT NULL,
`receipt_quantity` int(11) NOT NULL,
`usage_quantity` int(11) NOT NULL,
`stock` int(11) NOT NULL,
`unit_cost` decimal(10,2) DEFAULT NULL COMMENT '입고 시점의 단위당 원가 (원/kg)',
`remarks` text DEFAULT NULL,
`is_depleted` tinyint(1) DEFAULT 0
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- 테이블 구조 `machine_status`
--
CREATE TABLE `machine_status` (
`equipment_id` int(11) NOT NULL COMMENT '설비 마스터 ID',
`device_state` varchar(20) DEFAULT 'OFFLINE' COMMENT 'ONLINE / OFFLINE 상태',
`m_read_raw` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'M영역 읽기비트 전체 상태 JSON {bit_id: value}',
`m_write_raw` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT 'M영역 쓰기제어비트 전체 상태 JSON {bit_id: value}',
`d_read_g0` bigint(20) DEFAULT 0 COMMENT 'D영역 읽기 그룹0: 컷팅속도',
`d_read_g1` double DEFAULT 0 COMMENT 'D영역 읽기 그룹1: 이송속도',
`d_read_g2` double DEFAULT 0 COMMENT 'D영역 읽기 그룹2: 챔버온도',
`d_read_g3` double DEFAULT 0 COMMENT 'D영역 읽기 그룹3',
`d_read_g4` double DEFAULT 0 COMMENT 'D영역 읽기 그룹4',
`d_read_g5` bigint(20) DEFAULT 0 COMMENT 'D영역 읽기 그룹5',
`d_read_g6` double DEFAULT 0 COMMENT 'D영역 읽기 그룹6',
`d_read_g7` double DEFAULT 0 COMMENT 'D영역 읽기 그룹7',
`d_read_g8` double DEFAULT 0 COMMENT 'D영역 읽기 그룹8',
`d_read_g9` double DEFAULT 0 COMMENT 'D영역 읽기 그룹9',
`d_write_g0` bigint(20) DEFAULT 0 COMMENT 'D영역 쓰기 제어 설정 그룹0: 컷팅 타겟 속도',
`d_write_g1` bigint(20) DEFAULT 0 COMMENT 'D영역 쓰기 제어 설정 그룹1: 이송 타겟 속도',
`d_write_g2` bigint(20) DEFAULT 0 COMMENT 'D영역 쓰기 제어 설정 그룹2',
`d_write_g3` bigint(20) DEFAULT 0 COMMENT 'D영역 쓰기 제어 설정 그룹3',
`timestamp` bigint(20) NOT NULL DEFAULT 0 COMMENT '게이트웨이 전송 타임스탬프 (ms)',
`last_updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() COMMENT '서버 최종 수신 시간'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='각 설비의 14개 워드 및 M분리 최신 상태 저장 테이블';
-- --------------------------------------------------------
--
-- 테이블 구조 `material_properties`
--
CREATE TABLE `material_properties` (
`id` int(11) NOT NULL,
`material_code` varchar(100) DEFAULT NULL COMMENT '자재 관리 코드',
`material_name` varchar(255) NOT NULL COMMENT '자재명',
`material_type` varchar(50) NOT NULL COMMENT '자재 타입 (Yarn, Bond 등)',
`density` decimal(10,5) DEFAULT NULL COMMENT '비중 또는 밀도 (g/cm³)',
`remarks` text DEFAULT NULL COMMENT '비고',
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='원자재 물성 마스터 테이블';
-- --------------------------------------------------------
--
-- 테이블 구조 `plan_assignments`
--
CREATE TABLE `plan_assignments` (
`assignment_id` int(11) NOT NULL,
`plan_id` int(11) NOT NULL,
`equipment_id` int(11) NOT NULL,
`start_date` date NOT NULL,
`end_date` date NOT NULL,
`works_on_saturday` tinyint(1) NOT NULL DEFAULT 1 COMMENT '토요일 작업 여부 (1: 작업, 0: 휴무)',
`works_on_sunday` tinyint(1) NOT NULL DEFAULT 0 COMMENT '일요일 작업 여부 (1: 작업, 0: 휴무)'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- 테이블 구조 `production_plans`
--
CREATE TABLE `production_plans` (
`plan_id` int(11) NOT NULL,
`plan_name` varchar(255) NOT NULL COMMENT 'Plan name (Customer + Yarn + Bond + Quantity)',
`customer_name` varchar(255) NOT NULL COMMENT 'Snapshot of customer name',
`customer_id` int(11) DEFAULT NULL COMMENT 'FK to customers table',
`yarn_name` varchar(255) NOT NULL COMMENT 'Snapshot of yarn name',
`yarn_inventory_id` int(11) DEFAULT NULL COMMENT 'FK to inventory table for yarn',
`bond_name` varchar(255) NOT NULL COMMENT 'Snapshot of bond name',
`bond_inventory_id` int(11) DEFAULT NULL COMMENT 'FK to inventory table for bond',
`requested_quantity_kg` decimal(10,2) NOT NULL COMMENT 'Requested production quantity in kg',
`start_date` date NOT NULL COMMENT 'Planned start date',
`end_date` date NOT NULL COMMENT 'Calculated end date',
`production_days` int(11) NOT NULL COMMENT 'Calculated number of days for production',
`status` varchar(50) NOT NULL DEFAULT 'Planned' COMMENT 'Status of the plan (e.g., Planned, In Progress, Completed, Cancelled)',
`yarn_diameter` float DEFAULT NULL COMMENT 'Yarn Diameter (μm)',
`yarn_k` int(11) DEFAULT NULL COMMENT 'Yarn K (number of strands)',
`ports` int(11) DEFAULT NULL COMMENT 'Number of ports used',
`cycle_time` float DEFAULT NULL COMMENT 'Cycle Time (Hz)',
`cut_length` float DEFAULT NULL COMMENT 'Cut Length (mm)',
`work_hours_day` int(11) DEFAULT NULL COMMENT 'Work hours per day',
`num_machines` int(11) DEFAULT NULL COMMENT 'Number of machines assigned',
`created_at` timestamp NOT NULL DEFAULT current_timestamp(),
`hourly_net_cost_per_machine` decimal(15,2) DEFAULT NULL COMMENT '설비 1대당 시간당 순가공비',
`hourly_profit_per_machine` decimal(15,2) DEFAULT NULL COMMENT '설비 1대당 시간당 이윤',
`plan_total_material_cost` decimal(15,2) DEFAULT NULL COMMENT '계획에 필요한 총 원자재 비용',
`plan_net_processing_cost` decimal(15,2) DEFAULT NULL COMMENT '계획 전체의 총 순가공비',
`plan_company_margin` decimal(15,2) DEFAULT NULL COMMENT '계획 전체의 총 기업 마진',
`plan_processing_fee` decimal(15,2) DEFAULT NULL COMMENT '계획 전체의 총 가공비',
`plan_yarn_cost` decimal(15,2) DEFAULT NULL COMMENT '계획 전체의 원사 매입비',
`plan_bond_cost` decimal(15,2) DEFAULT NULL COMMENT '계획 전체의 본드 매입비',
`plan_estimated_sales` decimal(15,2) DEFAULT NULL COMMENT '계획 전체의 예상 매출액',
`work_days_month` int(11) DEFAULT NULL COMMENT '분석에 사용된 월 작업일'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- 테이블 구조 `purchase_activities`
--
CREATE TABLE `purchase_activities` (
`id` int(11) NOT NULL,
`supplier_id` int(11) NOT NULL,
`contact_id` int(11) DEFAULT NULL,
`activity_type` varchar(100) NOT NULL,
`activity_date` date NOT NULL,
`memo` text DEFAULT NULL,
`created_at` timestamp NULL DEFAULT current_timestamp(),
`updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- 테이블 구조 `sales_activities`
--
CREATE TABLE `sales_activities` (
`id` int(11) NOT NULL,
`customer_id` int(11) NOT NULL,
`contact_id` int(11) DEFAULT NULL,
`activity_date` date NOT NULL,
`activity_type` varchar(100) DEFAULT NULL,
`memo` text DEFAULT NULL,
`created_at` timestamp NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- 테이블 구조 `settings`
--
CREATE TABLE `settings` (
`id` int(11) NOT NULL,
`setting_group` varchar(100) NOT NULL COMMENT '설정 그룹 (예: analysis, general)',
`setting_key` varchar(100) NOT NULL COMMENT '설정 키 (예: labor_cost)',
`setting_value` text DEFAULT NULL COMMENT '설정 값',
`setting_type` varchar(50) DEFAULT 'string' COMMENT '값의 타입 힌트 (string, integer, decimal, json)',
`description` text DEFAULT NULL COMMENT '설정에 대한 설명',
`updated_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='앱 전체 설정 관리 테이블';
-- --------------------------------------------------------
--
-- 테이블 구조 `suppliers`
--
CREATE TABLE `suppliers` (
`id` int(11) NOT NULL,
`name_kr` varchar(255) NOT NULL,
`name_en` varchar(255) DEFAULT NULL,
`business_registration_number` varchar(20) DEFAULT NULL,
`contact_number` varchar(20) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT current_timestamp(),
`updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- --------------------------------------------------------
--
-- 테이블 구조 `supplier_contacts`
--
CREATE TABLE `supplier_contacts` (
`id` int(11) NOT NULL,
`supplier_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`email` varchar(255) DEFAULT NULL,
`phone_number` varchar(20) DEFAULT NULL,
`position` varchar(100) DEFAULT NULL,
`work_location` varchar(255) DEFAULT NULL,
`is_deleted` tinyint(1) DEFAULT 0,
`created_at` timestamp NULL DEFAULT current_timestamp(),
`updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- 덤프된 테이블의 인덱스
--
--
-- 테이블의 인덱스 `contacts`
--
ALTER TABLE `contacts`
ADD PRIMARY KEY (`id`),
ADD KEY `company_id` (`customer_id`);
--
-- 테이블의 인덱스 `control_target`
--
ALTER TABLE `control_target`
ADD PRIMARY KEY (`equipment_id`);
--
-- 테이블의 인덱스 `customers`
--
ALTER TABLE `customers`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `business_registration_number` (`business_registration_number`);
--
-- 테이블의 인덱스 `equipment`
--
ALTER TABLE `equipment`
ADD PRIMARY KEY (`id`);
--
-- 테이블의 인덱스 `inventory`
--
ALTER TABLE `inventory`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `item_number` (`item_number`),
ADD KEY `fk_inventory_material_properties` (`material_id`),
ADD KEY `fk_inventory_supplier` (`supplier_id`);
--
-- 테이블의 인덱스 `machine_status`
--
ALTER TABLE `machine_status`
ADD PRIMARY KEY (`equipment_id`);
--
-- 테이블의 인덱스 `material_properties`
--
ALTER TABLE `material_properties`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `material_name` (`material_name`);
--
-- 테이블의 인덱스 `plan_assignments`
--
ALTER TABLE `plan_assignments`
ADD PRIMARY KEY (`assignment_id`),
ADD KEY `plan_id` (`plan_id`),
ADD KEY `equipment_id` (`equipment_id`);
--
-- 테이블의 인덱스 `production_plans`
--
ALTER TABLE `production_plans`
ADD PRIMARY KEY (`plan_id`),
ADD KEY `fk_plan_customer` (`customer_id`),
ADD KEY `fk_plan_yarn_inventory` (`yarn_inventory_id`),
ADD KEY `fk_plan_bond_inventory` (`bond_inventory_id`);
--
-- 테이블의 인덱스 `purchase_activities`
--
ALTER TABLE `purchase_activities`
ADD PRIMARY KEY (`id`),
ADD KEY `supplier_id` (`supplier_id`),
ADD KEY `contact_id` (`contact_id`);
--
-- 테이블의 인덱스 `sales_activities`
--
ALTER TABLE `sales_activities`
ADD PRIMARY KEY (`id`),
ADD KEY `company_id` (`customer_id`),
ADD KEY `contact_id` (`contact_id`);
--
-- 테이블의 인덱스 `settings`
--
ALTER TABLE `settings`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `unique_group_key` (`setting_group`,`setting_key`);
--
-- 테이블의 인덱스 `suppliers`
--
ALTER TABLE `suppliers`
ADD PRIMARY KEY (`id`);
--
-- 테이블의 인덱스 `supplier_contacts`
--
ALTER TABLE `supplier_contacts`
ADD PRIMARY KEY (`id`),
ADD KEY `supplier_id` (`supplier_id`);
--
-- 덤프된 테이블의 AUTO_INCREMENT
--
--
-- 테이블의 AUTO_INCREMENT `contacts`
--
ALTER TABLE `contacts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `customers`
--
ALTER TABLE `customers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `equipment`
--
ALTER TABLE `equipment`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `inventory`
--
ALTER TABLE `inventory`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `material_properties`
--
ALTER TABLE `material_properties`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `plan_assignments`
--
ALTER TABLE `plan_assignments`
MODIFY `assignment_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `production_plans`
--
ALTER TABLE `production_plans`
MODIFY `plan_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `purchase_activities`
--
ALTER TABLE `purchase_activities`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `sales_activities`
--
ALTER TABLE `sales_activities`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `settings`
--
ALTER TABLE `settings`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `suppliers`
--
ALTER TABLE `suppliers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 테이블의 AUTO_INCREMENT `supplier_contacts`
--
ALTER TABLE `supplier_contacts`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- 덤프된 테이블의 제약사항
--
--
-- 테이블의 제약사항 `contacts`
--
ALTER TABLE `contacts`
ADD CONSTRAINT `contacts_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE;
--
-- 테이블의 제약사항 `control_target`
--
ALTER TABLE `control_target`
ADD CONSTRAINT `fk_control_target_equipment` FOREIGN KEY (`equipment_id`) REFERENCES `equipment` (`id`) ON DELETE CASCADE;
--
-- 테이블의 제약사항 `inventory`
--
ALTER TABLE `inventory`
ADD CONSTRAINT `fk_inventory_material_properties` FOREIGN KEY (`material_id`) REFERENCES `material_properties` (`id`) ON DELETE SET NULL ON UPDATE CASCADE,
ADD CONSTRAINT `fk_inventory_supplier` FOREIGN KEY (`supplier_id`) REFERENCES `suppliers` (`id`);
--
-- 테이블의 제약사항 `machine_status`
--
ALTER TABLE `machine_status`
ADD CONSTRAINT `fk_machine_status_equipment` FOREIGN KEY (`equipment_id`) REFERENCES `equipment` (`id`) ON DELETE CASCADE;
--
-- 테이블의 제약사항 `plan_assignments`
--
ALTER TABLE `plan_assignments`
ADD CONSTRAINT `fk_assignment_equipment` FOREIGN KEY (`equipment_id`) REFERENCES `equipment` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `fk_assignment_plan` FOREIGN KEY (`plan_id`) REFERENCES `production_plans` (`plan_id`) ON DELETE CASCADE;
--
-- 테이블의 제약사항 `production_plans`
--
ALTER TABLE `production_plans`
ADD CONSTRAINT `fk_plan_bond_inventory` FOREIGN KEY (`bond_inventory_id`) REFERENCES `inventory` (`id`) ON DELETE SET NULL,
ADD CONSTRAINT `fk_plan_customer` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE SET NULL,
ADD CONSTRAINT `fk_plan_yarn_inventory` FOREIGN KEY (`yarn_inventory_id`) REFERENCES `inventory` (`id`) ON DELETE SET NULL;
--
-- 테이블의 제약사항 `purchase_activities`
--
ALTER TABLE `purchase_activities`
ADD CONSTRAINT `purchase_activities_ibfk_1` FOREIGN KEY (`supplier_id`) REFERENCES `suppliers` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `purchase_activities_ibfk_2` FOREIGN KEY (`contact_id`) REFERENCES `supplier_contacts` (`id`) ON DELETE SET NULL;
--
-- 테이블의 제약사항 `sales_activities`
--
ALTER TABLE `sales_activities`
ADD CONSTRAINT `sa_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`id`) ON DELETE CASCADE,
ADD CONSTRAINT `sa_ibfk_2` FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`id`) ON DELETE SET NULL;
--
-- 테이블의 제약사항 `supplier_contacts`
--
ALTER TABLE `supplier_contacts`
ADD CONSTRAINT `supplier_contacts_ibfk_1` FOREIGN KEY (`supplier_id`) REFERENCES `suppliers` (`id`) ON DELETE CASCADE;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
+46
View File
@@ -0,0 +1,46 @@
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from database.connection import get_db_connection
def check():
try:
with get_db_connection() as conn:
with conn.cursor(dictionary=True) as cursor:
# Check tables
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
print("Tables in database:", [list(t.values())[0] for t in tables])
# Check equipment table structure and data
cursor.execute("DESCRIBE equipment")
cols = cursor.fetchall()
print("\nEquipment columns:")
for c in cols:
print(f" {c['Field']}: {c['Type']}")
cursor.execute("SELECT * FROM equipment")
eqs = cursor.fetchall()
print(f"\nEquipment rows ({len(eqs)}):")
for eq in eqs:
print(" ", eq)
# Check machine_status table structure
cursor.execute("DESCRIBE machine_status")
cols = cursor.fetchall()
print("\nmachine_status columns:")
for c in cols:
print(f" {c['Field']}: {c['Type']}")
cursor.execute("SELECT * FROM machine_status")
statuses = cursor.fetchall()
print(f"\nmachine_status rows ({len(statuses)}):")
for s in statuses:
print(" ", s)
except Exception as e:
print("Error during check:", e)
if __name__ == "__main__":
check()
+49
View File
@@ -0,0 +1,49 @@
import mysql.connector
import json
from datetime import datetime
DB_HOST = "localhost"
DB_PORT = 3306
DB_USER = "ctnt_root"
DB_PASSWORD = "Umsang6595!!"
DB_NAME = "carbon_cutting_mc_db"
def main():
try:
conn = mysql.connector.connect(
host=DB_HOST,
port=DB_PORT,
user=DB_USER,
password=DB_PASSWORD,
database=DB_NAME
)
cur = conn.cursor(dictionary=True)
cur.execute("SELECT m_read_raw, device_state, timestamp FROM machine_status WHERE equipment_id = 8")
row = cur.fetchone()
print("\n================ [DB REAL-TIME STATUS] ================")
if row:
print(f"Device State : {row['device_state']}")
print(f"Last Update : {row['timestamp']}")
m_read_raw_str = row['m_read_raw']
print(f"Raw String : {m_read_raw_str}")
if m_read_raw_str:
m_read = json.loads(m_read_raw_str)
active_bits = [int(k) for k, v in m_read.items() if int(v) == 1]
active_bits.sort()
print(f"Active Bits (val=1): {active_bits}")
else:
print("Active Bits : No Data")
else:
print("No status row found for equipment_id = 8")
print("========================================================\n")
cur.close()
conn.close()
except Exception as e:
print(f"DB Connection or Query failed: {e}")
if __name__ == "__main__":
main()
+21
View File
@@ -0,0 +1,21 @@
import os
def search_files(directory):
for root, dirs, files in os.walk(directory):
if "venv" in root or "__pycache__" in root or ".git" in root or ".gemini" in root:
continue
for file in files:
if file.endswith((".py", ".json", ".ini", ".conf", ".cfg", ".yml", ".yaml")):
path = os.path.join(root, file)
try:
with open(path, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
if "mysql" in content.lower() or "db_host" in content.lower() or "host =" in content.lower():
print(f"Found in {path}:")
for line in content.splitlines():
if any(x in line.lower() for x in ["host", "port", "user", "password", "db"]):
print(f" {line.strip()}")
except Exception as e:
pass
search_files("D:\\04_CTNT\\01_카본절단MC(CC)\\CC0324_양산_V0\\02_전장제어\\PLC_Communication_MQTT\\step5_modify")
+46
View File
@@ -0,0 +1,46 @@
import sys
import os
# server 디렉토리를 path에 추가하여 database 패키지 임포트 허용
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from database.connection import get_db_connection
def run_migration():
sql_script = """
SET FOREIGN_KEY_CHECKS = 0;
DROP TABLE IF EXISTS `machine_status`;
CREATE TABLE `machine_status` (
`equipment_id` int(11) NOT NULL,
`device_state` varchar(20) DEFAULT 'OFFLINE',
`m_area_raw` longtext DEFAULT NULL,
`cutting_motor_value` float DEFAULT 0.0,
`transfer_motor_value` float DEFAULT 0.0,
`chamber_temperature` float DEFAULT 0.0,
`d_area_raw` longtext DEFAULT NULL,
`timestamp` bigint(20) NOT NULL DEFAULT 0,
`last_updated_at` timestamp NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
PRIMARY KEY (`equipment_id`),
CONSTRAINT `fk_machine_status_equipment` FOREIGN KEY (`equipment_id`) REFERENCES `equipment` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
SET FOREIGN_KEY_CHECKS = 1;
"""
print("[MIGRATION] Connecting to MariaDB...")
try:
with get_db_connection() as conn:
with conn.cursor() as cursor:
# 다중 쿼리 실행을 위해 세미콜론 기준으로 분할하여 실행
queries = sql_script.split(';')
for query in queries:
clean_query = query.strip()
if clean_query:
print(f"[SQL] Executing: {clean_query[:60]}...")
cursor.execute(clean_query)
conn.commit()
print("[MIGRATION] Successfully updated machine_status schema in MariaDB!")
except Exception as e:
print(f"[ERROR] Migration failed: {e}")
if __name__ == "__main__":
run_migration()
+21
View File
@@ -0,0 +1,21 @@
import mysql.connector
hosts = ["localhost", "dsm.chemifactory.com"]
ports = [3306, 3307]
for host in hosts:
for port in ports:
print(f"Trying {host}:{port}...")
try:
conn = mysql.connector.connect(
host=host,
port=port,
user="ctnt_root",
password="Umsang6595!!",
database="carbon_cutting_mc_db",
connection_timeout=3
)
print(f"SUCCESS: Connected to {host}:{port}!")
conn.close()
except Exception as e:
print(f"FAILED {host}:{port}: {e}")