From c9b72cfbf805cc6fd4e345103766eadfd56762f0 Mon Sep 17 00:00:00 2001 From: Vector Date: Thu, 15 Oct 2026 22:21:50 +0700 Subject: [PATCH 1/2] =?UTF-8?q?feat(B05a,C02m):=20to=E1=BA=A1=20=C4=91?= =?UTF-8?q?=E1=BB=99=20c=C6=A1=20s=E1=BB=9F=20trong=20database,=20s?= =?UTF-8?q?=E1=BB=ADa=20=E1=BB=9F=20B05a?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- DECISIONS.md | 6 ++ .../SafeSpace-Customer-UI/BE-CONTRACT.md | 2 +- .../mock/mock-business.mjs | 6 +- .../SafeSpace-Customer-UI/src/api/mappers.js | 3 + .../src/business/Facilities.jsx | 87 ++++++++++++++++++- .../src/business/design.css | 5 ++ .../src/business/facility-form.js | 75 ++++++++++++++++ .../tests/api-mappers.test.js | 9 ++ .../tests/business-frontend.test.mjs | 14 +++ StorageProject.Api/Program.cs | 1 + .../DTOs/Facility/FacilityDtos.cs | 4 +- .../DTOs/Operations/OperationsDtos.cs | 8 +- StorageProject.Core/Entities/Facility.cs | 3 + .../Configurations/FacilityConfigurations.cs | 5 ++ .../Data/FacilityCoordinateSeeder.cs | 46 ++++++++++ .../Services/FacilityService.cs | 8 +- .../Services/OperationsService.cs | 31 ++++++- docs/operations-api.md | 11 ++- progress.md | 11 +++ 19 files changed, 318 insertions(+), 17 deletions(-) create mode 100644 SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/facility-form.js create mode 100644 StorageProject.Infrastructure/Data/FacilityCoordinateSeeder.cs diff --git a/DECISIONS.md b/DECISIONS.md index 6ba929d..eeeea3c 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -86,3 +86,9 @@ "Cọc còn giữ"; "Doanh thu thuê và phí" không trừ REFUND. Khi thêm hoàn tiền thuê/phí thì phải thêm liên kết khoản gốc. - Cơ sở `TEMPORARILY_CLOSED` chặn đặt chỗ mới; `INACTIVE` chỉ khi không còn hợp đồng / đơn đang xử lý. Không xoá cơ sở. +## D20 — Toạ độ cơ sở lưu trong database, Vận hành KD sửa ở B05a — Đã chốt (15/10/2026) +- Bảng `facilities` thêm `Latitude`, `Longitude` (decimal(9,6), cùng có hoặc cùng trống). API cơ sở công khai và `/api/operations/facilities` trả / nhận hai trường này. +- Màn B05 thêm nút "Sửa thông tin cơ sở" mở hộp thoại B05a (tên, địa chỉ, điện thoại, giờ ra vào, vĩ độ, kinh độ). Dán cặp toạ độ copy từ Google Maps vào một ô thì tự tách hai ô. +- Bản đồ Tìm kho (C02m) đọc toạ độ từ API; `src/config/geo.js` chỉ còn là toạ độ dự phòng cho cơ sở chưa nhập. +- Toạ độ khởi tạo của 12 cơ sở lấy giống `geo.js` (ước lượng); Vận hành KD nên kiểm tra lại trên Google Maps và sửa ở B05a. + diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md index 98c15f0..1a67aca 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md @@ -103,7 +103,7 @@ Cách giao diện xử lý các điểm lệch hiện tại của backend: | Màn | Endpoint đề xuất | Thay ở | |---|---|---| | C03b-sđ | `GET /api/facilities/{id}/units` → `unitNumber, zone, floor, sizeM2, unitTypeId, status` (StorageUnit) | `unitsFor()` trong `src/lib/units.js`; `fromBackendStatus()` đã map trạng thái | -| C02m | Thêm `latitude, longitude` vào `GET /api/facilities` | `coordsOf()` trong `src/config/geo.js` | +| C02m | **Đã có** `latitude, longitude` trong `GET /api/facilities` (nhập ở B05a) | `mapCatalog` gán `lat/lng`; `coordsOf()` trong `src/config/geo.js` chỉ dùng toạ độ dự phòng khi cơ sở chưa có toạ độ | | S01–S09, M01–M08 | `/api/ops/*` — **đã chốt hợp đồng ở `BACKEND-TODO.md` mục A2–A3**, giao diện gọi qua `src/ops/api.js` | `src/ops/store.jsx` | Hình dạng dữ liệu giao diện đang dùng nằm ở `src/ops/data.js`; nghiệp vụ (điều kiện chặn, chuyển trạng thái) ở diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs index cf8f346..d0f7d1d 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/mock/mock-business.mjs @@ -92,12 +92,13 @@ export function handleBusiness({ req, res, path, url, body, S, me, send }) { pricedUnitTypes: new Set(S.rates.filter((r) => r.facilityId === f.facilityId && (r.status ?? "ACTIVE") === "ACTIVE").map((r) => r.unitTypeId)).size, assignedStaff: f.facilityId === 1 ? 2 : 0, managerName: f.facilityId === 1 ? "Phạm Thu Hà" : null, createdAt: "2026-09-15T12:40:41", updatedAt: "2026-09-15T12:40:41", + latitude: f.latitude ?? null, longitude: f.longitude ?? null, }; }; if (req.method === "GET" && path === "/api/operations/facilities") return send(200, S.facilities.map(facilityDto)), true; if (req.method === "POST" && path === "/api/operations/facilities") { if (!body?.name?.trim() || !body?.address?.trim()) return bad("Tên và địa chỉ cơ sở là bắt buộc."); - const f = { facilityId: S.facilities.length + 1, name: body.name.trim(), address: body.address.trim(), contactPhone: body.contactPhone, openingTime: body.openingTime, closingTime: body.closingTime, status: "ACTIVE" }; + const f = { facilityId: S.facilities.length + 1, name: body.name.trim(), address: body.address.trim(), contactPhone: body.contactPhone, openingTime: body.openingTime, closingTime: body.closingTime, status: "ACTIVE", latitude: body.latitude ?? null, longitude: body.longitude ?? null }; S.facilities.push(f); return send(201, { facility: facilityDto(f), warnings: ["Cơ sở đang hoạt động nhưng chưa có bảng giá, ô kho hoặc nhân sự."] }), true; } @@ -111,7 +112,8 @@ export function handleBusiness({ req, res, path, url, body, S, me, send }) { return send(200, { facility: facilityDto(f), warnings: [] }), true; } if (req.method === "PUT") { - Object.assign(f, { name: body.name, address: body.address, contactPhone: body.contactPhone, openingTime: body.openingTime, closingTime: body.closingTime }); + if ((body.latitude == null) !== (body.longitude == null)) return bad("Cần nhập cả vĩ độ và kinh độ, hoặc để trống cả hai."); + Object.assign(f, { name: body.name, address: body.address, contactPhone: body.contactPhone, openingTime: body.openingTime, closingTime: body.closingTime, latitude: body.latitude ?? null, longitude: body.longitude ?? null }); return send(200, { facility: facilityDto(f), warnings: [] }), true; } if (req.method === "GET") return send(200, facilityDto(f)), true; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js index 9093887..a8261df 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/api/mappers.js @@ -81,6 +81,9 @@ export function mapCatalog({ facilities = [], unitTypes = [], rates = [] }) { district, city, phone: f.contactPhone || "", + // Toạ độ ghim bản đồ từ backend; null thì config/geo.js dùng toạ độ dự phòng theo tên + lat: f.latitude ?? null, + lng: f.longitude ?? null, hours: open && close ? `${open}–${close}` : "06:00–22:00", distance_km: null, camera: true, diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx index aa2f358..0c36700 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/Facilities.jsx @@ -1,11 +1,84 @@ -import React from "react"; +import React, { useState } from "react"; import { businessApi } from "../api/business"; -import { Button } from "../components/UI"; +import { Button, Field, Modal, Notice } from "../components/UI"; import { useLoad } from "../admin/util"; import { go, href, qs } from "../lib/router"; import { useApp } from "../state/store"; import { FACILITY_STATUS, areaOf, rateLabel, shortFacility } from "./format"; import { LoadState } from "./parts"; +import { coordinateLabel, facilityToForm, formToRequest, splitCoordinates } from "./facility-form"; + +// B05a · Sửa thông tin cơ sở (tên, địa chỉ, điện thoại, giờ ra vào, toạ độ ghim bản đồ) +function EditFacilityDialog({ facility, onClose, onSaved }) { + const { notify } = useApp(); + const [form, setForm] = useState(() => facilityToForm(facility)); + const [errors, setErrors] = useState({}); + const [busy, setBusy] = useState(false); + const set = (k) => (e) => { + setForm((f) => ({ ...f, [k]: e.target.value })); + setErrors({}); + }; + // Dán cả cặp "10.6935, 106.7222" vào ô vĩ độ / kinh độ thì tự tách ra hai ô + const pasteCoords = (e) => { + const pair = splitCoordinates(e.clipboardData?.getData("text")); + if (!pair) return; + e.preventDefault(); + setForm((f) => ({ ...f, ...pair })); + setErrors({}); + }; + const save = async (e) => { + e.preventDefault(); + const { errors: errs, body } = formToRequest(form); + if (errs) return setErrors(errs); + setBusy(true); + try { + const res = await businessApi.updateFacility(facility.facilityId, body); + const warnings = res?.warnings || []; + notify(warnings.length ? `Đã lưu thông tin cơ sở. ${warnings.join(" ")}` : "Đã lưu thông tin cơ sở."); + onSaved(); + } catch (err) { + setErrors({ form: err.message }); + } finally { + setBusy(false); + } + }; + return ( + +
+

{facility.name}

+ + + + + + + + + +
+ + +
+ {errors.hours &&

{errors.hours}

} +
+ + +
+ {errors.coords &&

{errors.coords}

} +

+ Lấy toạ độ: mở Google Maps, nhấp chuột phải vào đúng vị trí cơ sở, bấm dòng số đầu tiên để sao chép rồi dán vào ô Vĩ độ. + Toạ độ dùng để đặt ghim trên bản đồ Tìm kho và nút Chỉ đường. +

+ Mở Google Maps ↗ + {errors.form && {errors.form}} +
+ + +
+
+
+ ); +} // B05: select a facility and open its business report; no unrelated CRUD controls. export default function BusinessFacilities({ query }) { @@ -15,6 +88,7 @@ export default function BusinessFacilities({ query }) { return { facilities, rates }; }, [], onApiError); const selectedId = Number(query.get("id")); + const [editing, setEditing] = useState(null); return

Mạng lưới cơ sở

@@ -35,9 +109,14 @@ export default function BusinessFacilities({ query }) { {current &&

{current.name}

{[areaOf(current.address).district, areaOf(current.address).city].filter(Boolean).join(', ')}{current.openingTime && ` · Giờ ra vào ${current.openingTime}–${current.closingTime}`}

-

{typeNames.length ? `${typeNames.join(' & ')} · ` : ''}Quản lý: {current.managerName || ('managerName' in current ? 'Chưa phân công' : 'Chưa có thông tin')}

-
+

{typeNames.length ? `${typeNames.join(' & ')} · ` : ''}Quản lý: {current.managerName || ('managerName' in current ? 'Chưa phân công' : 'Chưa có thông tin')}

+

Vị trí bản đồ: {coordinateLabel(current)}

+
+ + +
} + {editing && setEditing(null)} onSaved={() => { setEditing(null); load.reload(); }} />} ; }}
; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css index 1d15886..7a2d2ea 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/design.css @@ -144,3 +144,8 @@ .business-app .btn--outline { color: var(--text); } .business-app .bell { padding: 0; } .business-app .business-facilities .table tbody tr { background: var(--white); } + +/* B05a · Sửa thông tin cơ sở */ +.biz-form { display: grid; gap: 14px; } +.biz-form__pair { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; } +@media (max-width: 520px) { .biz-form__pair { grid-template-columns: 1fr; } } diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/facility-form.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/facility-form.js new file mode 100644 index 0000000..5f72a50 --- /dev/null +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/src/business/facility-form.js @@ -0,0 +1,75 @@ +// B05a · Sửa thông tin cơ sở — chuyển giữa dữ liệu API và form, kiểm tra trước khi gửi +// (backend kiểm tra lại y hệt trong OperationsService.ValidateFacility). + +const VN = { latMin: 8, latMax: 24, lngMin: 102, lngMax: 110 }; + +const text = (v) => (v == null ? "" : String(v)); +const num = (v) => Number(String(v).trim().replace(",", ".")); + +export function facilityToForm(f) { + return { + name: text(f?.name), + address: text(f?.address), + contactPhone: text(f?.contactPhone), + openingTime: text(f?.openingTime), + closingTime: text(f?.closingTime), + latitude: f?.latitude == null ? "" : String(f.latitude), + longitude: f?.longitude == null ? "" : String(f.longitude), + }; +} + +// Dán "10.6935, 106.7222" (copy từ Google Maps) → tách thành vĩ độ / kinh độ. Không phải cặp số thì trả null. +export function splitCoordinates(value) { + const m = String(value || "").trim().match(/^(-?\d+(?:\.\d+)?)\s*[,;\s]\s*(-?\d+(?:\.\d+)?)$/); + return m ? { latitude: m[1], longitude: m[2] } : null; +} + +// Trả { errors } nếu sai, hoặc { body } đúng hợp đồng PUT /api/operations/facilities/{id} +export function formToRequest(form) { + const errors = {}; + const name = form.name.trim(); + const address = form.address.trim(); + if (!name) errors.name = "Tên cơ sở không được để trống."; + else if (name.length > 150) errors.name = "Tên cơ sở tối đa 150 ký tự."; + if (!address) errors.address = "Địa chỉ không được để trống."; + else if (address.length > 255) errors.address = "Địa chỉ tối đa 255 ký tự."; + + const open = form.openingTime.trim(); + const close = form.closingTime.trim(); + if (Boolean(open) !== Boolean(close)) errors.hours = "Nhập cả giờ mở cửa và giờ đóng cửa, hoặc để trống cả hai."; + else if (open && close && open >= close) errors.hours = "Giờ mở cửa phải trước giờ đóng cửa."; + + const latText = form.latitude.trim(); + const lngText = form.longitude.trim(); + let latitude = null; + let longitude = null; + if (latText || lngText) { + latitude = num(latText); + longitude = num(lngText); + if (!latText || !lngText) errors.coords = "Cần nhập cả vĩ độ và kinh độ, hoặc để trống cả hai."; + else if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) errors.coords = "Vĩ độ và kinh độ phải là số, ví dụ 10.6935 và 106.7222."; + else if (latitude < VN.latMin || latitude > VN.latMax || longitude < VN.lngMin || longitude > VN.lngMax) + errors.coords = "Toạ độ phải nằm trong Việt Nam (vĩ độ 8–24, kinh độ 102–110). Kiểm tra có nhập ngược hai ô không."; + else { + latitude = Math.round(latitude * 1e6) / 1e6; + longitude = Math.round(longitude * 1e6) / 1e6; + } + } + if (Object.keys(errors).length) return { errors }; + + return { + body: { + name, + address, + contactPhone: form.contactPhone.trim() || null, + openingTime: open || null, + closingTime: close || null, + status: null, // đổi trạng thái dùng endpoint /status riêng + latitude, + longitude, + }, + }; +} + +export const coordinateLabel = (f) => + f?.latitude != null && f?.longitude != null ? `${Number(f.latitude).toFixed(6)}, ${Number(f.longitude).toFixed(6)}` : "Chưa có"; diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js index 18fac75..d4883e3 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/api-mappers.test.js @@ -117,6 +117,15 @@ test("phần lưu cục bộ: tên hiển thị, lịch trả kho, thông báo assert.equal(d.notifications.length, 1); }); +test("toạ độ cơ sở: lấy latitude / longitude từ backend, thiếu thì để null", () => { + const base = catalogDto.facilities[0]; + const withCoords = mapCatalog({ ...catalogDto, facilities: [{ ...base, latitude: 10.6935, longitude: 106.7222 }] }); + assert.equal(withCoords.facilities[0].lat, 10.6935); + assert.equal(withCoords.facilities[0].lng, 106.7222); + const without = mapCatalog({ ...catalogDto, facilities: [base] }); + assert.equal(without.facilities[0].lat, null); +}); + test("tên đăng nhập backend sinh từ email (≤ 50 ký tự)", () => { assert.equal(usernameFromEmail(" Mai.Tran@Example.com "), "mai.tran@example.com"); assert.ok(usernameFromEmail(`${"a".repeat(60)}@example.com`).length <= 50); diff --git a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/business-frontend.test.mjs b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/business-frontend.test.mjs index 9b48811..b7e7fe5 100644 --- a/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/business-frontend.test.mjs +++ b/SafeSpace-Customer-UI/SafeSpace-Customer-UI/tests/business-frontend.test.mjs @@ -6,6 +6,7 @@ import { homeFor, isBusinessRoles, isOpsRoles } from '../src/lib/roles.js'; import { policyFields, fieldValue, fieldPolicy, policyJobs } from '../src/business/policy-fields.js'; import { activateWithConfirm, replacePolicy } from '../src/business/actions.js'; import { parseCsv, workbookBytes } from '../src/business/export.js'; +import { facilityToForm, formToRequest, splitCoordinates } from '../src/business/facility-form.js'; import { startMockApi } from '../mock/mock-api.mjs'; const field = key => policyFields.find(f => f.key === key); const day='2026-10-15'; @@ -67,3 +68,16 @@ test('strict contract: conflict cancellation never sends replaceExisting; confir assert.equal(await activateWithConfirm(draft,async()=>true),true);active=await businessApi.policies({status:'ACTIVE'});assert.ok(active.some(x=>x.policyId===draft.policyId));assert.ok(!active.some(x=>x.policyId===old.policyId)); }finally{setToken(null);server.close();} }); + +test('B05a: toạ độ cơ sở — dán cặp số, bắt buộc đủ hai ô, trong Việt Nam, làm tròn 6 chữ số',()=>{ + assert.deepEqual(splitCoordinates('10.6935, 106.7222'),{latitude:'10.6935',longitude:'106.7222'}); + assert.equal(splitCoordinates('Phú Xuân'),null); + const base=facilityToForm({facilityId:3,name:'SafeSpace Phú Xuân',address:'Đường Nguyễn Hữu Thọ',contactPhone:null,openingTime:'06:00',closingTime:'22:00',latitude:null,longitude:null}); + assert.equal(base.latitude,''); + assert.deepEqual(formToRequest(base).body,{name:'SafeSpace Phú Xuân',address:'Đường Nguyễn Hữu Thọ',contactPhone:null,openingTime:'06:00',closingTime:'22:00',status:null,latitude:null,longitude:null}); + assert.ok(formToRequest({...base,latitude:'10.69'}).errors.coords); + assert.ok(formToRequest({...base,latitude:'106.7222',longitude:'10.6935'}).errors.coords); + const ok=formToRequest({...base,latitude:'10,69351234',longitude:'106.7222'}).body; + assert.equal(ok.latitude,10.693512);assert.equal(ok.longitude,106.7222); + assert.ok(formToRequest({...base,openingTime:'22:00',closingTime:'06:00'}).errors.hours); +}); diff --git a/StorageProject.Api/Program.cs b/StorageProject.Api/Program.cs index eaa3f52..62785d8 100644 --- a/StorageProject.Api/Program.cs +++ b/StorageProject.Api/Program.cs @@ -135,6 +135,7 @@ var context = scope.ServiceProvider.GetRequiredService(); await context.Database.MigrateAsync(); await DbSeeder.SeedAsync(context); + await FacilityCoordinateSeeder.SeedAsync(context); } diff --git a/StorageProject.Core/DTOs/Facility/FacilityDtos.cs b/StorageProject.Core/DTOs/Facility/FacilityDtos.cs index 9de2a37..6d26be3 100644 --- a/StorageProject.Core/DTOs/Facility/FacilityDtos.cs +++ b/StorageProject.Core/DTOs/Facility/FacilityDtos.cs @@ -7,7 +7,9 @@ public record FacilityDto( string? ContactPhone, string? OpeningTime, string? ClosingTime, - string Status + string Status, + decimal? Latitude = null, // toạ độ ghim bản đồ (C02m); null = chưa nhập + decimal? Longitude = null ); public record UnitTypeDto( diff --git a/StorageProject.Core/DTOs/Operations/OperationsDtos.cs b/StorageProject.Core/DTOs/Operations/OperationsDtos.cs index f5a7fa1..c3e57b8 100644 --- a/StorageProject.Core/DTOs/Operations/OperationsDtos.cs +++ b/StorageProject.Core/DTOs/Operations/OperationsDtos.cs @@ -19,7 +19,9 @@ public record OpsFacilityDto( int PricedUnitTypes, // số loại kho đang có giá áp dụng hôm nay int AssignedStaff, // số nhân sự (STAFF/MANAGER) đang được phân công DateTime CreatedAt, - DateTime UpdatedAt + DateTime UpdatedAt, + decimal? Latitude = null, + decimal? Longitude = null ); public record UpsertFacilityRequest( @@ -28,7 +30,9 @@ public record UpsertFacilityRequest( string? ContactPhone, string? OpeningTime, // "HH:mm" string? ClosingTime, // "HH:mm" - string? Status // chỉ dùng khi tạo mới; đổi trạng thái dùng endpoint /status + string? Status, // chỉ dùng khi tạo mới; đổi trạng thái dùng endpoint /status + decimal? Latitude = null, // toạ độ ghim bản đồ; nhập cả hai hoặc để trống cả hai + decimal? Longitude = null ); public record ChangeFacilityStatusRequest(string Status, string? Reason); diff --git a/StorageProject.Core/Entities/Facility.cs b/StorageProject.Core/Entities/Facility.cs index db31e3c..5a3ef2e 100644 --- a/StorageProject.Core/Entities/Facility.cs +++ b/StorageProject.Core/Entities/Facility.cs @@ -8,6 +8,9 @@ public class Facility public string? ContactPhone { get; set; } public TimeOnly? OpeningTime { get; set; } public TimeOnly? ClosingTime { get; set; } + // Toạ độ ghim trên bản đồ (WGS84, giống Google Maps). Cả hai cùng có hoặc cùng trống. + public decimal? Latitude { get; set; } + public decimal? Longitude { get; set; } public string Status { get; set; } = "ACTIVE"; // ACTIVE, INACTIVE, TEMPORARILY_CLOSED public DateTime CreatedAt { get; set; } public DateTime UpdatedAt { get; set; } diff --git a/StorageProject.Infrastructure/Data/Configurations/FacilityConfigurations.cs b/StorageProject.Infrastructure/Data/Configurations/FacilityConfigurations.cs index 4fa9887..5ca43a8 100644 --- a/StorageProject.Infrastructure/Data/Configurations/FacilityConfigurations.cs +++ b/StorageProject.Infrastructure/Data/Configurations/FacilityConfigurations.cs @@ -11,12 +11,17 @@ public void Configure(EntityTypeBuilder b) b.ToTable("facilities", t => { t.HasCheckConstraint("CK_facilities_status", "[Status] IN ('ACTIVE','INACTIVE','TEMPORARILY_CLOSED')"); + t.HasCheckConstraint("CK_facilities_coordinates", + "([Latitude] IS NULL AND [Longitude] IS NULL) OR " + + "([Latitude] BETWEEN -90 AND 90 AND [Longitude] BETWEEN -180 AND 180)"); }); b.HasKey(f => f.FacilityId); b.Property(f => f.FacilityId).UseIdentityColumn(); b.Property(f => f.Name).IsRequired().HasMaxLength(150); b.Property(f => f.Address).IsRequired().HasMaxLength(255); b.Property(f => f.ContactPhone).HasMaxLength(20); + b.Property(f => f.Latitude).HasPrecision(9, 6); + b.Property(f => f.Longitude).HasPrecision(9, 6); b.Property(f => f.Status).IsRequired().HasMaxLength(30).HasDefaultValue("ACTIVE"); b.Property(f => f.CreatedAt).IsRequired(); b.Property(f => f.UpdatedAt).IsRequired(); diff --git a/StorageProject.Infrastructure/Data/FacilityCoordinateSeeder.cs b/StorageProject.Infrastructure/Data/FacilityCoordinateSeeder.cs new file mode 100644 index 0000000..d89aa1a --- /dev/null +++ b/StorageProject.Infrastructure/Data/FacilityCoordinateSeeder.cs @@ -0,0 +1,46 @@ +using Microsoft.EntityFrameworkCore; + +namespace StorageProject.Infrastructure.Data; + +/// +/// Điền toạ độ ghim bản đồ cho 12 cơ sở SafeSpace (khớp src/config/geo.js của giao diện). +/// Chỉ điền cơ sở CHƯA có toạ độ, nên toạ độ Vận hành KD sửa ở màn B05 không bị ghi đè khi chạy lại. +/// Khớp theo một phần tên cơ sở (vd. "SafeSpace Phú Xuân" chứa "Phú Xuân"). +/// +public static class FacilityCoordinateSeeder +{ + private static readonly (string Key, decimal Latitude, decimal Longitude)[] KnownFacilities = + [ + ("Nguyễn Lương Bằng", 10.729500m, 106.721900m), + ("Him Lam", 10.745600m, 106.698000m), + ("Phú Xuân", 10.693500m, 106.722200m), + ("Tân Thuận", 10.756000m, 106.729000m), + ("Phú Mỹ Hưng", 10.728500m, 106.706000m), + ("Bình Thạnh", 10.815000m, 106.709000m), + ("Nhà Bè", 10.696000m, 106.739000m), + ("Bình Chánh", 10.697000m, 106.656000m), + ("Thủ Đức", 10.850000m, 106.770000m), + ("Gò Vấp", 10.835000m, 106.666000m), + ("Tân Bình", 10.801000m, 106.642000m), + ("Bình Tân", 10.739000m, 106.615000m), + ]; + + public static async Task SeedAsync(AppDbContext context, CancellationToken ct = default) + { + var missing = await context.Facilities + .Where(f => f.Latitude == null || f.Longitude == null) + .ToListAsync(ct); + if (missing.Count == 0) return; + + var changed = false; + foreach (var facility in missing) + { + var hit = KnownFacilities.FirstOrDefault(k => facility.Name.Contains(k.Key, StringComparison.OrdinalIgnoreCase)); + if (hit.Key is null) continue; + facility.Latitude = hit.Latitude; + facility.Longitude = hit.Longitude; + changed = true; + } + if (changed) await context.SaveChangesAsync(ct); + } +} diff --git a/StorageProject.Infrastructure/Services/FacilityService.cs b/StorageProject.Infrastructure/Services/FacilityService.cs index 8ea92c3..e14c66e 100644 --- a/StorageProject.Infrastructure/Services/FacilityService.cs +++ b/StorageProject.Infrastructure/Services/FacilityService.cs @@ -20,7 +20,9 @@ public async Task> GetActiveFacilitiesAsync(Cancellat f.ContactPhone, f.OpeningTime != null ? f.OpeningTime.Value.ToString(@"hh\:mm") : null, f.ClosingTime != null ? f.ClosingTime.Value.ToString(@"hh\:mm") : null, - f.Status + f.Status, + f.Latitude, + f.Longitude )) .ToListAsync(ct); } @@ -41,7 +43,9 @@ public async Task> GetActiveFacilitiesAsync(Cancellat f.ContactPhone, f.OpeningTime != null ? f.OpeningTime.Value.ToString(@"hh\:mm") : null, f.ClosingTime != null ? f.ClosingTime.Value.ToString(@"hh\:mm") : null, - f.Status + f.Status, + f.Latitude, + f.Longitude ); } diff --git a/StorageProject.Infrastructure/Services/OperationsService.cs b/StorageProject.Infrastructure/Services/OperationsService.cs index 1dc090d..31b42b9 100644 --- a/StorageProject.Infrastructure/Services/OperationsService.cs +++ b/StorageProject.Infrastructure/Services/OperationsService.cs @@ -61,6 +61,8 @@ public async Task CreateFacilityAsync(UpsertFacilityRequest ContactPhone = input.Phone, OpeningTime = input.Opening, ClosingTime = input.Closing, + Latitude = input.Latitude, + Longitude = input.Longitude, Status = status, CreatedAt = now, UpdatedAt = now @@ -89,6 +91,8 @@ public async Task UpdateFacilityAsync(long facilityId, Upser facility.ContactPhone = input.Phone; facility.OpeningTime = input.Opening; facility.ClosingTime = input.Closing; + facility.Latitude = input.Latitude; + facility.Longitude = input.Longitude; facility.UpdatedAt = DateTime.UtcNow; var newStatus = NormalizeFacilityStatus(request.Status); @@ -202,7 +206,9 @@ private async Task> ToFacilityDtosAsync(List faci pricedTypes.Count(r => r.FacilityId == f.FacilityId), staff.Count(s => s.FacilityId == f.FacilityId), f.CreatedAt, - f.UpdatedAt); + f.UpdatedAt, + f.Latitude, + f.Longitude); }).ToList(); } @@ -242,7 +248,8 @@ private async Task> FacilityWarningsAsync(Facility facilit return warnings; } - private sealed record FacilityInput(string Name, string Address, string? Phone, TimeOnly? Opening, TimeOnly? Closing); + private sealed record FacilityInput(string Name, string Address, string? Phone, TimeOnly? Opening, TimeOnly? Closing, + decimal? Latitude, decimal? Longitude); private static FacilityInput ValidateFacility(UpsertFacilityRequest request) { @@ -276,7 +283,21 @@ private static FacilityInput ValidateFacility(UpsertFacilityRequest request) throw new ArgumentException("Giờ mở cửa phải trước giờ đóng cửa."); } - return new FacilityInput(name, address, phone, opening, closing); + var (latitude, longitude) = ValidateCoordinates(request.Latitude, request.Longitude); + + return new FacilityInput(name, address, phone, opening, closing, latitude, longitude); + } + + // Toạ độ ghim bản đồ: nhập cả hai hoặc để trống cả hai; phải nằm trong khung lãnh thổ Việt Nam + // (vĩ độ 8–24, kinh độ 102–110) để bắt lỗi nhập ngược hai ô. Làm tròn 6 chữ số thập phân (~0,1 m). + private static (decimal? Latitude, decimal? Longitude) ValidateCoordinates(decimal? latitude, decimal? longitude) + { + if (latitude is null && longitude is null) return (null, null); + if (latitude is null || longitude is null) + throw new ArgumentException("Cần nhập cả vĩ độ và kinh độ, hoặc để trống cả hai."); + if (latitude < 8m || latitude > 24m || longitude < 102m || longitude > 110m) + throw new ArgumentException("Toạ độ phải nằm trong Việt Nam (vĩ độ 8–24, kinh độ 102–110). Kiểm tra có nhập ngược hai ô không."); + return (Math.Round(latitude.Value, 6), Math.Round(longitude.Value, 6)); } private static TimeOnly? ParseTime(string? value, string label) @@ -318,7 +339,9 @@ private static string NameKey(string name) f.ContactPhone, OpeningTime = f.OpeningTime?.ToString("HH:mm"), ClosingTime = f.ClosingTime?.ToString("HH:mm"), - f.Status + f.Status, + f.Latitude, + f.Longitude }; [GeneratedRegex(@"[\s.\-()]")] diff --git a/docs/operations-api.md b/docs/operations-api.md index 3be1799..c6ec7b9 100644 --- a/docs/operations-api.md +++ b/docs/operations-api.md @@ -16,7 +16,7 @@ Quy ước chung: |---|---|---|---| | GET | `/api/operations/facilities` | `?status=ACTIVE&search=quận 7` | Gồm cả cơ sở INACTIVE / TEMPORARILY_CLOSED | | GET | `/api/operations/facilities/{id}` | — | | -| POST | `/api/operations/facilities` | `{ name, address, contactPhone, openingTime, closingTime, status? }` | `201` + `{ facility, warnings[] }` | +| POST | `/api/operations/facilities` | `{ name, address, contactPhone, openingTime, closingTime, status?, latitude?, longitude? }` | `201` + `{ facility, warnings[] }` | | PUT | `/api/operations/facilities/{id}` | như trên | Sửa thông tin; `status` nếu gửi thì đi qua cùng kiểm tra như endpoint dưới | | PUT | `/api/operations/facilities/{id}/status` | `{ status, reason? }` | `ACTIVE` · `TEMPORARILY_CLOSED` · `INACTIVE` | @@ -28,6 +28,8 @@ Một cơ sở trả về: "name": "SafeSpace Nguyễn Lương Bằng", "address": "12 Nguyễn Lương Bằng, Phường Tân Phú, Quận 7, TP. Hồ Chí Minh", "contactPhone": "02837001012", + "latitude": 10.7295, + "longitude": 106.7219, "openingTime": "06:00", "closingTime": "22:00", "status": "ACTIVE", @@ -148,3 +150,10 @@ Bộ lọc chung: `from`, `to` (`yyyy-MM-dd`, giờ Việt Nam; mặc định t Giả định của bản cơ bản (D16): bảng `payments` chưa có `original_payment_id`, và hoàn tiền hiện chỉ có hoàn cọc sau trả kho, nên mọi khoản REFUND trừ vào "Cọc còn giữ"; "Doanh thu thuê và phí" không trừ REFUND. + +### Toạ độ cơ sở (B05a, C02m) +- `latitude`, `longitude` (số thập phân, 6 chữ số) có trong `POST`/`PUT /api/operations/facilities`, `GET /api/operations/facilities` + và `GET /api/facilities` (công khai). Nhập cả hai hoặc để trống cả hai; phải nằm trong Việt Nam (vĩ độ 8–24, kinh độ 102–110). +- `PUT` ghi đè toạ độ theo đúng giá trị gửi lên (gửi `null` cả hai = xoá toạ độ). Form B05a luôn gửi lại toạ độ đang có. +- Khi khởi động, `FacilityCoordinateSeeder` điền toạ độ cho 12 cơ sở SafeSpace còn trống (không ghi đè toạ độ đã sửa). + diff --git a/progress.md b/progress.md index 6894e70..64d4bef 100644 --- a/progress.md +++ b/progress.md @@ -16,6 +16,17 @@ > Mỗi phiên làm việc với AI thêm MỘT mục ở đầu danh sách (mới nhất trên cùng). > Ghi đủ để phiên sau tiếp tục ngay mà không phải hỏi lại. Không xoá mục cũ. +## 2026-10-15 — Toạ độ bản đồ (B05a, C02m) — Claude (việc của Thắng) + +- Figma: B05 thêm dòng "Vị trí bản đồ" + nút "Sửa thông tin cơ sở"; hộp thoại mới B05a. +- Backend: `Facility.Latitude/Longitude` + check constraint, trả trong `FacilityDto` và `OpsFacilityDto`, nhận trong + `UpsertFacilityRequest` (kiểm tra trong khung Việt Nam), `FacilityCoordinateSeeder` điền 12 cơ sở còn trống. +- Frontend: `mapCatalog` gán `lat/lng`; B05a (`src/business/facility-form.js` + `Facilities.jsx`); mock business có toạ độ. +- Kiểm chứng: `npm test` 39/39, `npm run test:business` 9/9, `npm run test:render` PASS, `npm run build` PASS; + biên dịch thử các service bằng stub EF (không tải được NuGet trong môi trường AI); Playwright: sửa toạ độ ở B05a qua mock → lưu thành công. +- Phiên sau: `dotnet ef migrations add AddFacilityCoordinates --project StorageProject.Infrastructure --startup-project StorageProject.Api`, + `dotnet build StorageProject.slnx`, chạy API, kiểm tra `GET /api/facilities` có toạ độ và bản đồ Tìm kho đúng vị trí. + ## Mẫu một mục ``` From a6c3eef9586b0bdb8ddfe97afc173e017e6eebc0 Mon Sep 17 00:00:00 2001 From: Vector Date: Thu, 15 Oct 2026 22:31:52 +0700 Subject: [PATCH 2/2] chore: migration AddFacilityCoordinates --- ...5153130_AddFacilityCoordinates.Designer.cs | 1967 +++++++++++++++++ .../20261015153130_AddFacilityCoordinates.cs | 51 + .../Migrations/AppDbContextModelSnapshot.cs | 10 + 3 files changed, 2028 insertions(+) create mode 100644 StorageProject.Infrastructure/Migrations/20261015153130_AddFacilityCoordinates.Designer.cs create mode 100644 StorageProject.Infrastructure/Migrations/20261015153130_AddFacilityCoordinates.cs diff --git a/StorageProject.Infrastructure/Migrations/20261015153130_AddFacilityCoordinates.Designer.cs b/StorageProject.Infrastructure/Migrations/20261015153130_AddFacilityCoordinates.Designer.cs new file mode 100644 index 0000000..a2a1a9b --- /dev/null +++ b/StorageProject.Infrastructure/Migrations/20261015153130_AddFacilityCoordinates.Designer.cs @@ -0,0 +1,1967 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using StorageProject.Infrastructure.Data; + +#nullable disable + +namespace StorageProject.Infrastructure.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20261015153130_AddFacilityCoordinates")] + partial class AddFacilityCoordinates + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.12") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("StorageProject.Core.Entities.AccessCredential", b => + { + b.Property("CredentialId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("CredentialId")); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CredentialReference") + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("CredentialType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("IssuedAt") + .HasColumnType("datetime2"); + + b.Property("IssuedBy") + .HasColumnType("bigint"); + + b.Property("ReturnedAt") + .HasColumnType("datetime2"); + + b.Property("SecretHash") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("ACTIVE"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("CredentialId"); + + b.HasIndex("ContractId"); + + b.HasIndex("IssuedBy"); + + b.HasIndex("UnitId"); + + b.ToTable("access_credentials", null, t => + { + t.HasCheckConstraint("CK_access_credentials_status", "[Status] IN ('ACTIVE','RETURNED','LOST','REVOKED','REPLACED')"); + + t.HasCheckConstraint("CK_access_credentials_type", "[CredentialType] IN ('KEY','LOCK','ACCESS_CARD','ACCESS_CODE')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ActivityLog", b => + { + b.Property("LogId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("LogId")); + + b.Property("Action") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("EntityId") + .HasColumnType("bigint"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("nvarchar(80)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("LoggedAt") + .HasColumnType("datetime2"); + + b.Property("NewValue") + .HasColumnType("nvarchar(max)"); + + b.Property("OldValue") + .HasColumnType("nvarchar(max)"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("LogId"); + + b.HasIndex("UserId"); + + b.ToTable("activity_logs", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b => + { + b.Property("RenewalId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RenewalId")); + + b.Property("ApprovedAt") + .HasColumnType("datetime2"); + + b.Property("ApprovedBy") + .HasColumnType("bigint"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("NewEndDate") + .HasColumnType("date"); + + b.Property("NewMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("OldEndDate") + .HasColumnType("date"); + + b.Property("OldMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("RenewalAmount") + .HasColumnType("decimal(15,2)"); + + b.Property("RenewalPeriodMonths") + .HasColumnType("int"); + + b.Property("RequestedAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("PENDING"); + + b.HasKey("RenewalId"); + + b.HasIndex("ApprovedBy"); + + b.HasIndex("ContractId"); + + b.ToTable("contract_renewals", null, t => + { + t.HasCheckConstraint("CK_contract_renewals_amount", "[RenewalAmount] >= 0"); + + t.HasCheckConstraint("CK_contract_renewals_period", "[RenewalPeriodMonths] > 0"); + + t.HasCheckConstraint("CK_contract_renewals_status", "[Status] IN ('PENDING','APPROVED','REJECTED','PAID','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Facility", b => + { + b.Property("FacilityId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("FacilityId")); + + b.Property("Address") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ClosingTime") + .HasColumnType("time"); + + b.Property("ContactPhone") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Latitude") + .HasPrecision(9, 6) + .HasColumnType("decimal(9,6)"); + + b.Property("Longitude") + .HasPrecision(9, 6) + .HasColumnType("decimal(9,6)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("OpeningTime") + .HasColumnType("time"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("ACTIVE"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.HasKey("FacilityId"); + + b.ToTable("facilities", null, t => + { + t.HasCheckConstraint("CK_facilities_coordinates", "([Latitude] IS NULL AND [Longitude] IS NULL) OR ([Latitude] BETWEEN -90 AND 90 AND [Longitude] BETWEEN -180 AND 180)"); + + t.HasCheckConstraint("CK_facilities_status", "[Status] IN ('ACTIVE','INACTIVE','TEMPORARILY_CLOSED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.HandoverRecord", b => + { + b.Property("HandoverId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("HandoverId")); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerConfirmed") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("HandoverAt") + .HasColumnType("datetime2"); + + b.Property("InitialCondition") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Notes") + .HasColumnType("nvarchar(max)"); + + b.Property("ScheduledAt") + .HasColumnType("datetime2"); + + b.Property("StaffConfirmed") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("StaffId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("SCHEDULED"); + + b.Property("VerifiedAt") + .HasColumnType("datetime2"); + + b.HasKey("HandoverId"); + + b.HasIndex("ContractId") + .IsUnique(); + + b.HasIndex("StaffId"); + + b.ToTable("handover_records", null, t => + { + t.HasCheckConstraint("CK_handover_records_status", "[Status] IN ('SCHEDULED','VERIFIED','HANDED_OVER','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.LoginHistory", b => + { + b.Property("LoginHistoryId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("LoginHistoryId")); + + b.Property("DeviceInfo") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("IpAddress") + .HasMaxLength(45) + .HasColumnType("nvarchar(45)"); + + b.Property("LoginAt") + .HasColumnType("datetime2"); + + b.Property("LoginStatus") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LogoutAt") + .HasColumnType("datetime2"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("LoginHistoryId"); + + b.HasIndex("UserId"); + + b.ToTable("login_history", null, t => + { + t.HasCheckConstraint("CK_login_history_status", "[LoginStatus] IN ('SUCCESS','FAILED','BLOCKED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.MaintenanceRequest", b => + { + b.Property("MaintenanceId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("MaintenanceId")); + + b.Property("AssignedStaffId") + .HasColumnType("bigint"); + + b.Property("CompletedAt") + .HasColumnType("datetime2"); + + b.Property("Cost") + .ValueGeneratedOnAdd() + .HasColumnType("decimal(15,2)") + .HasDefaultValue(0m); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("IssueDescription") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("MaintenanceType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("Notes") + .HasColumnType("nvarchar(max)"); + + b.Property("Priority") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("NORMAL"); + + b.Property("ReportedBy") + .HasColumnType("bigint"); + + b.Property("ScheduledAt") + .HasColumnType("datetime2"); + + b.Property("StartedAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("OPEN"); + + b.Property("SupportTicketId") + .HasColumnType("bigint"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("MaintenanceId"); + + b.HasIndex("AssignedStaffId"); + + b.HasIndex("ReportedBy"); + + b.HasIndex("SupportTicketId"); + + b.HasIndex("UnitId"); + + b.ToTable("maintenance_requests", null, t => + { + t.HasCheckConstraint("CK_maintenance_requests_priority", "[Priority] IN ('LOW','NORMAL','HIGH','URGENT')"); + + t.HasCheckConstraint("CK_maintenance_requests_status", "[Status] IN ('OPEN','SCHEDULED','IN_PROGRESS','COMPLETED','CANCELLED')"); + + t.HasCheckConstraint("CK_maintenance_requests_type", "[MaintenanceType] IN ('INSPECTION','REPAIR','CLEANING','LOCK','ACCESS_SYSTEM','OTHER')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.OverdueCase", b => + { + b.Property("OverdueCaseId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("OverdueCaseId")); + + b.Property("AssignedStaffId") + .HasColumnType("bigint"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("GraceDeadline") + .HasColumnType("date"); + + b.Property("Notes") + .HasColumnType("nvarchar(max)"); + + b.Property("OpenedAt") + .HasColumnType("datetime2"); + + b.Property("OutstandingAmount") + .ValueGeneratedOnAdd() + .HasColumnType("decimal(15,2)") + .HasDefaultValue(0m); + + b.Property("OverdueFrom") + .HasColumnType("date"); + + b.Property("ResolvedAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("OPEN"); + + b.HasKey("OverdueCaseId"); + + b.HasIndex("AssignedStaffId"); + + b.HasIndex("ContractId"); + + b.ToTable("overdue_cases", null, t => + { + t.HasCheckConstraint("CK_overdue_cases_status", "[Status] IN ('OPEN','CONTACTED','PAYMENT_PENDING','RETURN_PENDING','RESOLVED','ESCALATED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Payment", b => + { + b.Property("PaymentId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PaymentId")); + + b.Property("Amount") + .HasColumnType("decimal(15,2)"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Currency") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(3) + .HasColumnType("nvarchar(3)") + .HasDefaultValue("VND"); + + b.Property("DueDate") + .HasColumnType("date"); + + b.Property("PaidAt") + .HasColumnType("datetime2"); + + b.Property("PaymentMethod") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("PaymentType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("RenewalId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("PENDING"); + + b.Property("TransactionReference") + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.HasKey("PaymentId"); + + b.HasIndex("ContractId"); + + b.HasIndex("RenewalId"); + + b.HasIndex("TransactionReference") + .IsUnique() + .HasFilter("[TransactionReference] IS NOT NULL"); + + b.ToTable("payments", null, t => + { + t.HasCheckConstraint("CK_payments_amount", "[Amount] >= 0"); + + t.HasCheckConstraint("CK_payments_payment_method", "[PaymentMethod] IN ('CASH','BANK_TRANSFER','CARD','E_WALLET','PAYMENT_GATEWAY')"); + + t.HasCheckConstraint("CK_payments_payment_type", "[PaymentType] IN ('DEPOSIT','RENT','RENEWAL','EXTRA_FEE','OVERDUE_FEE','DAMAGE_FEE','CLEANING_FEE','LOST_KEY_FEE','ACCESS_CARD_FEE','REFUND')"); + + t.HasCheckConstraint("CK_payments_status", "[Status] IN ('PENDING','PAID','FAILED','REFUNDED','PARTIALLY_REFUNDED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Permission", b => + { + b.Property("PermissionId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PermissionId")); + + b.Property("Description") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("PermissionCode") + .IsRequired() + .HasMaxLength(80) + .HasColumnType("nvarchar(80)"); + + b.Property("PermissionName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.HasKey("PermissionId"); + + b.HasIndex("PermissionCode") + .IsUnique(); + + b.ToTable("permissions", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Policy", b => + { + b.Property("PolicyId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("PolicyId")); + + b.Property("CalculationType") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CreatedBy") + .HasColumnType("bigint"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("EffectiveTo") + .HasColumnType("date"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("MaxValue") + .HasColumnType("decimal(15,2)"); + + b.Property("MinValue") + .HasColumnType("decimal(15,2)"); + + b.Property("PolicyName") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("PolicyType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("RuleDescription") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("DRAFT"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Value") + .HasColumnType("decimal(15,2)"); + + b.HasKey("PolicyId"); + + b.HasIndex("CreatedBy"); + + b.HasIndex("FacilityId"); + + b.HasIndex("UnitTypeId"); + + b.ToTable("policies", null, t => + { + t.HasCheckConstraint("CK_policies_calculation_type", "[CalculationType] IS NULL OR [CalculationType] IN ('FIXED','PERCENTAGE','RANGE','RULE')"); + + t.HasCheckConstraint("CK_policies_policy_type", "[PolicyType] IN ('DEPOSIT','RENEWAL','CANCELLATION','RETURN','OVERDUE','EXTRA_FEE','DISCOUNT','FEE_WAIVER','PRICE_RANGE')"); + + t.HasCheckConstraint("CK_policies_status", "[Status] IN ('DRAFT','ACTIVE','INACTIVE','EXPIRED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => + { + b.Property("ContractId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("ContractId")); + + b.Property("ActivatedAt") + .HasColumnType("datetime2"); + + b.Property("AgreedMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("CompletedAt") + .HasColumnType("datetime2"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("DepositAmount") + .HasColumnType("decimal(15,2)"); + + b.Property("EndDate") + .HasColumnType("date"); + + b.Property("ReservationId") + .HasColumnType("bigint"); + + b.Property("StartDate") + .HasColumnType("date"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("DRAFT"); + + b.Property("TerminationReason") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("ContractId"); + + b.HasIndex("CustomerId"); + + b.HasIndex("ReservationId") + .IsUnique(); + + b.HasIndex("UnitId"); + + b.ToTable("rental_contracts", null, t => + { + t.HasCheckConstraint("CK_rental_contracts_dates", "[EndDate] > [StartDate]"); + + t.HasCheckConstraint("CK_rental_contracts_deposit", "[DepositAmount] >= 0"); + + t.HasCheckConstraint("CK_rental_contracts_rate", "[AgreedMonthlyRate] >= 0"); + + t.HasCheckConstraint("CK_rental_contracts_status", "[Status] IN ('DRAFT','ACTIVE','EXPIRING','OVERDUE','RETURN_PENDING','COMPLETED','TERMINATED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalRate", b => + { + b.Property("RateId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RateId")); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("EffectiveFrom") + .HasColumnType("date"); + + b.Property("EffectiveTo") + .HasColumnType("date"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("MonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("SetBy") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("DRAFT"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.HasKey("RateId"); + + b.HasIndex("FacilityId"); + + b.HasIndex("SetBy"); + + b.HasIndex("UnitTypeId"); + + b.ToTable("rental_rates", null, t => + { + t.HasCheckConstraint("CK_rental_rates_monthly_rate", "[MonthlyRate] > 0"); + + t.HasCheckConstraint("CK_rental_rates_status", "[Status] IN ('DRAFT','ACTIVE','EXPIRED','INACTIVE')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => + { + b.Property("ReservationId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("ReservationId")); + + b.Property("CancellationReason") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("CancelledAt") + .HasColumnType("datetime2"); + + b.Property("CheckInAppointmentAt") + .HasColumnType("datetime2"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("EstimatedAmount") + .HasColumnType("decimal(15,2)"); + + b.Property("ExpectedEndDate") + .HasColumnType("date"); + + b.Property("ExpiresAt") + .HasColumnType("datetime2"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("QuotedMonthlyRate") + .HasColumnType("decimal(15,2)"); + + b.Property("RentalPeriodMonths") + .HasColumnType("int"); + + b.Property("RequiredDeposit") + .HasColumnType("decimal(15,2)"); + + b.Property("StartDate") + .HasColumnType("date"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("PENDING_PAYMENT"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.HasKey("ReservationId"); + + b.HasIndex("CustomerId"); + + b.HasIndex("FacilityId"); + + b.HasIndex("UnitTypeId"); + + b.ToTable("reservations", null, t => + { + t.HasCheckConstraint("CK_reservations_estimated_amount", "[EstimatedAmount] >= 0"); + + t.HasCheckConstraint("CK_reservations_quoted_rate", "[QuotedMonthlyRate] >= 0"); + + t.HasCheckConstraint("CK_reservations_rental_period", "[RentalPeriodMonths] > 0"); + + t.HasCheckConstraint("CK_reservations_required_deposit", "[RequiredDeposit] >= 0"); + + t.HasCheckConstraint("CK_reservations_status", "[Status] IN ('PENDING_PAYMENT','CONFIRMED','UNIT_ASSIGNED','CHECKED_IN','CANCELLED','EXPIRED','NO_SHOW')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ReturnInspection", b => + { + b.Property("InspectionId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("InspectionId")); + + b.Property("CleaningFee") + .ValueGeneratedOnAdd() + .HasColumnType("decimal(15,2)") + .HasDefaultValue(0m); + + b.Property("CleaningRequired") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("ConditionStatus") + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("DamageDescription") + .HasColumnType("nvarchar(max)"); + + b.Property("DamageFee") + .ValueGeneratedOnAdd() + .HasColumnType("decimal(15,2)") + .HasDefaultValue(0m); + + b.Property("InspectedAt") + .HasColumnType("datetime2"); + + b.Property("MaintenanceRequired") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("Notes") + .HasColumnType("nvarchar(max)"); + + b.Property("ScheduledAt") + .HasColumnType("datetime2"); + + b.Property("StaffId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("SCHEDULED"); + + b.HasKey("InspectionId"); + + b.HasIndex("ContractId"); + + b.HasIndex("StaffId"); + + b.ToTable("return_inspections", null, t => + { + t.HasCheckConstraint("CK_return_inspections_condition", "[ConditionStatus] IS NULL OR [ConditionStatus] IN ('GOOD','DIRTY','DAMAGED','MAINTENANCE_REQUIRED')"); + + t.HasCheckConstraint("CK_return_inspections_status", "[Status] IN ('SCHEDULED','IN_PROGRESS','COMPLETED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Role", b => + { + b.Property("RoleId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("RoleId")); + + b.Property("Description") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("RoleName") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("RoleId"); + + b.HasIndex("RoleName") + .IsUnique(); + + b.ToTable("roles", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RolePermission", b => + { + b.Property("RoleId") + .HasColumnType("bigint"); + + b.Property("PermissionId") + .HasColumnType("bigint"); + + b.HasKey("RoleId", "PermissionId"); + + b.HasIndex("PermissionId"); + + b.ToTable("role_permissions", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.StorageUnit", b => + { + b.Property("UnitId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UnitId")); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("Floor") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("LocationDescription") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)") + .HasDefaultValue("AVAILABLE"); + + b.Property("UnitNumber") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("UnitTypeId") + .HasColumnType("bigint"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Zone") + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("UnitId"); + + b.HasIndex("UnitTypeId"); + + b.HasIndex("FacilityId", "UnitNumber") + .IsUnique(); + + b.ToTable("storage_units", null, t => + { + t.HasCheckConstraint("CK_storage_units_status", "[Status] IN ('AVAILABLE','RESERVED','ASSIGNED','OCCUPIED','RETURN_PENDING','INSPECTION','MAINTENANCE','OUT_OF_SERVICE')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.SupportTicket", b => + { + b.Property("TicketId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("TicketId")); + + b.Property("AssignedAt") + .HasColumnType("datetime2"); + + b.Property("AssignedStaffId") + .HasColumnType("bigint"); + + b.Property("ClosedAt") + .HasColumnType("datetime2"); + + b.Property("ContractId") + .HasColumnType("bigint"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("CustomerId") + .HasColumnType("bigint"); + + b.Property("Description") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("IssueType") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("Priority") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("NORMAL"); + + b.Property("ResolvedAt") + .HasColumnType("datetime2"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("OPEN"); + + b.Property("Title") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("TicketId"); + + b.HasIndex("AssignedStaffId"); + + b.HasIndex("ContractId"); + + b.HasIndex("CustomerId"); + + b.HasIndex("UnitId"); + + b.ToTable("support_tickets", null, t => + { + t.HasCheckConstraint("CK_support_tickets_issue_type", "[IssueType] IN ('UNIT','LOCK','ACCESS_CODE','ACCESS_CARD','PAYMENT','STORED_ITEM','OTHER')"); + + t.HasCheckConstraint("CK_support_tickets_priority", "[Priority] IN ('LOW','NORMAL','HIGH','URGENT')"); + + t.HasCheckConstraint("CK_support_tickets_status", "[Status] IN ('OPEN','ASSIGNED','IN_PROGRESS','RESOLVED','CLOSED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitAssignment", b => + { + b.Property("AssignmentId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("AssignmentId")); + + b.Property("AssignedAt") + .HasColumnType("datetime2"); + + b.Property("AssignedBy") + .HasColumnType("bigint"); + + b.Property("Reason") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("ReservationId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("ACTIVE"); + + b.Property("UnassignedAt") + .HasColumnType("datetime2"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("AssignmentId"); + + b.HasIndex("AssignedBy"); + + b.HasIndex("ReservationId"); + + b.HasIndex("UnitId"); + + b.ToTable("unit_assignments", null, t => + { + t.HasCheckConstraint("CK_unit_assignments_status", "[Status] IN ('ACTIVE','REPLACED','CANCELLED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitStatusHistory", b => + { + b.Property("StatusHistoryId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("StatusHistoryId")); + + b.Property("ChangedAt") + .HasColumnType("datetime2"); + + b.Property("ChangedBy") + .HasColumnType("bigint"); + + b.Property("NewStatus") + .IsRequired() + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("OldStatus") + .HasMaxLength(30) + .HasColumnType("nvarchar(30)"); + + b.Property("Reason") + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("UnitId") + .HasColumnType("bigint"); + + b.HasKey("StatusHistoryId"); + + b.HasIndex("ChangedBy"); + + b.HasIndex("UnitId"); + + b.ToTable("unit_status_history", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitType", b => + { + b.Property("UnitTypeId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UnitTypeId")); + + b.Property("Area") + .HasColumnType("decimal(8,2)"); + + b.Property("ClimateControlled") + .ValueGeneratedOnAdd() + .HasColumnType("bit") + .HasDefaultValue(false); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Description") + .HasMaxLength(500) + .HasColumnType("nvarchar(500)"); + + b.Property("Height") + .HasColumnType("decimal(8,2)"); + + b.Property("Length") + .HasColumnType("decimal(8,2)"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("TypeName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("nvarchar(100)"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Width") + .HasColumnType("decimal(8,2)"); + + b.HasKey("UnitTypeId"); + + b.HasIndex("TypeName") + .IsUnique(); + + b.ToTable("unit_types", null, t => + { + t.HasCheckConstraint("CK_unit_types_area", "[Area] > 0"); + + t.HasCheckConstraint("CK_unit_types_height", "[Height] IS NULL OR [Height] > 0"); + + t.HasCheckConstraint("CK_unit_types_length", "[Length] IS NULL OR [Length] > 0"); + + t.HasCheckConstraint("CK_unit_types_status", "[Status] IN ('ACTIVE','INACTIVE')"); + + t.HasCheckConstraint("CK_unit_types_width", "[Width] IS NULL OR [Width] > 0"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.User", b => + { + b.Property("UserId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UserId")); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("FullName") + .IsRequired() + .HasMaxLength(150) + .HasColumnType("nvarchar(150)"); + + b.Property("PasswordHash") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("Phone") + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)") + .HasDefaultValue("ACTIVE"); + + b.Property("UpdatedAt") + .HasColumnType("datetime2"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("nvarchar(50)"); + + b.HasKey("UserId"); + + b.HasIndex("Email") + .IsUnique(); + + b.HasIndex("Username") + .IsUnique(); + + b.ToTable("users", null, t => + { + t.HasCheckConstraint("CK_users_status", "[Status] IN ('ACTIVE','INACTIVE','LOCKED','SUSPENDED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserFacility", b => + { + b.Property("UserFacilityId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("UserFacilityId")); + + b.Property("AssignedBy") + .HasColumnType("bigint"); + + b.Property("AssignedFrom") + .HasColumnType("date"); + + b.Property("AssignedTo") + .HasColumnType("date"); + + b.Property("CreatedAt") + .HasColumnType("datetime2"); + + b.Property("FacilityId") + .HasColumnType("bigint"); + + b.Property("Status") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("nvarchar(20)"); + + b.Property("UserId") + .HasColumnType("bigint"); + + b.HasKey("UserFacilityId"); + + b.HasIndex("AssignedBy"); + + b.HasIndex("FacilityId"); + + b.HasIndex("UserId"); + + b.ToTable("user_facilities", null, t => + { + t.HasCheckConstraint("CK_user_facilities_status", "[Status] IN ('ACTIVE','ENDED','SUSPENDED')"); + }); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserRole", b => + { + b.Property("UserId") + .HasColumnType("bigint"); + + b.Property("RoleId") + .HasColumnType("bigint"); + + b.Property("AssignedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2") + .HasDefaultValueSql("GETUTCDATE()"); + + b.Property("AssignedBy") + .HasColumnType("bigint"); + + b.HasKey("UserId", "RoleId"); + + b.HasIndex("AssignedBy"); + + b.HasIndex("RoleId"); + + b.ToTable("user_roles", (string)null); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.AccessCredential", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("AccessCredentials") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "IssuedByUser") + .WithMany() + .HasForeignKey("IssuedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("AccessCredentials") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Contract"); + + b.Navigation("IssuedByUser"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ActivityLog", b => + { + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("ActivityLogs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b => + { + b.HasOne("StorageProject.Core.Entities.User", "ApprovedByUser") + .WithMany() + .HasForeignKey("ApprovedBy") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("ContractRenewals") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ApprovedByUser"); + + b.Navigation("Contract"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.HandoverRecord", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithOne("HandoverRecord") + .HasForeignKey("StorageProject.Core.Entities.HandoverRecord", "ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "Staff") + .WithMany() + .HasForeignKey("StaffId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Contract"); + + b.Navigation("Staff"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.LoginHistory", b => + { + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("LoginHistories") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.MaintenanceRequest", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedStaff") + .WithMany() + .HasForeignKey("AssignedStaffId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.User", "ReportedByUser") + .WithMany() + .HasForeignKey("ReportedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.SupportTicket", "SupportTicket") + .WithMany("MaintenanceRequests") + .HasForeignKey("SupportTicketId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("MaintenanceRequests") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedStaff"); + + b.Navigation("ReportedByUser"); + + b.Navigation("SupportTicket"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.OverdueCase", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedStaff") + .WithMany() + .HasForeignKey("AssignedStaffId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("OverdueCases") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedStaff"); + + b.Navigation("Contract"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Payment", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("Payments") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.ContractRenewal", "Renewal") + .WithMany("Payments") + .HasForeignKey("RenewalId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Contract"); + + b.Navigation("Renewal"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Policy", b => + { + b.HasOne("StorageProject.Core.Entities.User", "CreatedByUser") + .WithMany() + .HasForeignKey("CreatedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("Policies") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("Policies") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("CreatedByUser"); + + b.Navigation("Facility"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany("RentalContracts") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithOne("RentalContract") + .HasForeignKey("StorageProject.Core.Entities.RentalContract", "ReservationId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("RentalContracts") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Customer"); + + b.Navigation("Reservation"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalRate", b => + { + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("RentalRates") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "SetByUser") + .WithMany() + .HasForeignKey("SetBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("RentalRates") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Facility"); + + b.Navigation("SetByUser"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany("Reservations") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("Reservations") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("Reservations") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Customer"); + + b.Navigation("Facility"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ReturnInspection", b => + { + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("ReturnInspections") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "Staff") + .WithMany() + .HasForeignKey("StaffId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Contract"); + + b.Navigation("Staff"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RolePermission", b => + { + b.HasOne("StorageProject.Core.Entities.Permission", "Permission") + .WithMany("RolePermissions") + .HasForeignKey("PermissionId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Role", "Role") + .WithMany("RolePermissions") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Permission"); + + b.Navigation("Role"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.StorageUnit", b => + { + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("StorageUnits") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.UnitType", "UnitType") + .WithMany("StorageUnits") + .HasForeignKey("UnitTypeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Facility"); + + b.Navigation("UnitType"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.SupportTicket", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedStaff") + .WithMany() + .HasForeignKey("AssignedStaffId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.RentalContract", "Contract") + .WithMany("SupportTickets") + .HasForeignKey("ContractId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.User", "Customer") + .WithMany("SupportTickets") + .HasForeignKey("CustomerId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("SupportTickets") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("AssignedStaff"); + + b.Navigation("Contract"); + + b.Navigation("Customer"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitAssignment", b => + { + b.HasOne("StorageProject.Core.Entities.User", "AssignedByUser") + .WithMany() + .HasForeignKey("AssignedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.Reservation", "Reservation") + .WithMany("UnitAssignments") + .HasForeignKey("ReservationId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("UnitAssignments") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("AssignedByUser"); + + b.Navigation("Reservation"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitStatusHistory", b => + { + b.HasOne("StorageProject.Core.Entities.User", "ChangedByUser") + .WithMany() + .HasForeignKey("ChangedBy") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.StorageUnit", "Unit") + .WithMany("StatusHistories") + .HasForeignKey("UnitId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("ChangedByUser"); + + b.Navigation("Unit"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserFacility", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Assigner") + .WithMany() + .HasForeignKey("AssignedBy") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.Facility", "Facility") + .WithMany("UserFacilities") + .HasForeignKey("FacilityId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("UserFacilities") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Assigner"); + + b.Navigation("Facility"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UserRole", b => + { + b.HasOne("StorageProject.Core.Entities.User", "Assigner") + .WithMany() + .HasForeignKey("AssignedBy") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("StorageProject.Core.Entities.Role", "Role") + .WithMany("UserRoles") + .HasForeignKey("RoleId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("StorageProject.Core.Entities.User", "User") + .WithMany("UserRoles") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Assigner"); + + b.Navigation("Role"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.ContractRenewal", b => + { + b.Navigation("Payments"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Facility", b => + { + b.Navigation("Policies"); + + b.Navigation("RentalRates"); + + b.Navigation("Reservations"); + + b.Navigation("StorageUnits"); + + b.Navigation("UserFacilities"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Permission", b => + { + b.Navigation("RolePermissions"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.RentalContract", b => + { + b.Navigation("AccessCredentials"); + + b.Navigation("ContractRenewals"); + + b.Navigation("HandoverRecord"); + + b.Navigation("OverdueCases"); + + b.Navigation("Payments"); + + b.Navigation("ReturnInspections"); + + b.Navigation("SupportTickets"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Reservation", b => + { + b.Navigation("RentalContract"); + + b.Navigation("UnitAssignments"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.Role", b => + { + b.Navigation("RolePermissions"); + + b.Navigation("UserRoles"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.StorageUnit", b => + { + b.Navigation("AccessCredentials"); + + b.Navigation("MaintenanceRequests"); + + b.Navigation("RentalContracts"); + + b.Navigation("StatusHistories"); + + b.Navigation("SupportTickets"); + + b.Navigation("UnitAssignments"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.SupportTicket", b => + { + b.Navigation("MaintenanceRequests"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.UnitType", b => + { + b.Navigation("Policies"); + + b.Navigation("RentalRates"); + + b.Navigation("Reservations"); + + b.Navigation("StorageUnits"); + }); + + modelBuilder.Entity("StorageProject.Core.Entities.User", b => + { + b.Navigation("ActivityLogs"); + + b.Navigation("LoginHistories"); + + b.Navigation("RentalContracts"); + + b.Navigation("Reservations"); + + b.Navigation("SupportTickets"); + + b.Navigation("UserFacilities"); + + b.Navigation("UserRoles"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/StorageProject.Infrastructure/Migrations/20261015153130_AddFacilityCoordinates.cs b/StorageProject.Infrastructure/Migrations/20261015153130_AddFacilityCoordinates.cs new file mode 100644 index 0000000..5014488 --- /dev/null +++ b/StorageProject.Infrastructure/Migrations/20261015153130_AddFacilityCoordinates.cs @@ -0,0 +1,51 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace StorageProject.Infrastructure.Migrations +{ + /// + public partial class AddFacilityCoordinates : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.AddColumn( + name: "Latitude", + table: "facilities", + type: "decimal(9,6)", + precision: 9, + scale: 6, + nullable: true); + + migrationBuilder.AddColumn( + name: "Longitude", + table: "facilities", + type: "decimal(9,6)", + precision: 9, + scale: 6, + nullable: true); + + migrationBuilder.AddCheckConstraint( + name: "CK_facilities_coordinates", + table: "facilities", + sql: "([Latitude] IS NULL AND [Longitude] IS NULL) OR ([Latitude] BETWEEN -90 AND 90 AND [Longitude] BETWEEN -180 AND 180)"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropCheckConstraint( + name: "CK_facilities_coordinates", + table: "facilities"); + + migrationBuilder.DropColumn( + name: "Latitude", + table: "facilities"); + + migrationBuilder.DropColumn( + name: "Longitude", + table: "facilities"); + } + } +} diff --git a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs index a2c6714..b480905 100644 --- a/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs +++ b/StorageProject.Infrastructure/Migrations/AppDbContextModelSnapshot.cs @@ -212,6 +212,14 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Property("CreatedAt") .HasColumnType("datetime2"); + b.Property("Latitude") + .HasPrecision(9, 6) + .HasColumnType("decimal(9,6)"); + + b.Property("Longitude") + .HasPrecision(9, 6) + .HasColumnType("decimal(9,6)"); + b.Property("Name") .IsRequired() .HasMaxLength(150) @@ -234,6 +242,8 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("facilities", null, t => { + t.HasCheckConstraint("CK_facilities_coordinates", "([Latitude] IS NULL AND [Longitude] IS NULL) OR ([Latitude] BETWEEN -90 AND 90 AND [Longitude] BETWEEN -180 AND 180)"); + t.HasCheckConstraint("CK_facilities_status", "[Status] IN ('ACTIVE','INACTIVE','TEMPORARILY_CLOSED')"); }); });