Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion SafeSpace-Customer-UI/SafeSpace-Customer-UI/BE-CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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) ở
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
camera: true,
has_climate: offers.some((o) => o.type === "climate"),
Expand Down
Original file line number Diff line number Diff line change
@@ -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 (
<Modal title="Sửa thông tin cơ sở" size="md" onClose={onClose}>
<form className="biz-form" onSubmit={save} noValidate>
<p className="muted">{facility.name}</p>
<Field label="Tên cơ sở" error={errors.name}>
<input value={form.name} maxLength={150} onChange={set("name")} />
</Field>
<Field label="Địa chỉ" error={errors.address}>
<input value={form.address} maxLength={255} onChange={set("address")} />
</Field>
<Field label="Số điện thoại">
<input value={form.contactPhone} inputMode="tel" onChange={set("contactPhone")} />
</Field>
<div className="biz-form__pair">
<Field label="Giờ mở cửa"><input type="time" value={form.openingTime} onChange={set("openingTime")} /></Field>
<Field label="Giờ đóng cửa"><input type="time" value={form.closingTime} onChange={set("closingTime")} /></Field>
</div>
{errors.hours && <p className="field__error" role="alert">{errors.hours}</p>}
<div className="biz-form__pair">
<Field label="Vĩ độ"><input value={form.latitude} inputMode="decimal" placeholder="10.693500" onChange={set("latitude")} onPaste={pasteCoords} /></Field>
<Field label="Kinh độ"><input value={form.longitude} inputMode="decimal" placeholder="106.722200" onChange={set("longitude")} onPaste={pasteCoords} /></Field>
</div>
{errors.coords && <p className="field__error" role="alert">{errors.coords}</p>}
<p className="hint">
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.
</p>
<a href="https://www.google.com/maps" target="_blank" rel="noreferrer">Mở Google Maps ↗</a>
{errors.form && <Notice tone="error">{errors.form}</Notice>}
<div className="modal__actions">
<Button variant="outline" onClick={onClose}>Huỷ</Button>
<Button type="submit" disabled={busy}>{busy ? "Đang lưu…" : "Lưu thay đổi"}</Button>
</div>
</form>
</Modal>
);
}

// B05: select a facility and open its business report; no unrelated CRUD controls.
export default function BusinessFacilities({ query }) {
Expand All @@ -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 <main className="container page business-facilities">
<header className="page-header page-header--tight"><div>
<h1>Mạng lưới cơ sở</h1>
Expand All @@ -35,9 +109,14 @@ export default function BusinessFacilities({ query }) {
{current && <section className="panel biz-detail" aria-label={`Chi tiết ${current.name}`}>
<h2>{current.name}</h2>
<div className="muted"><p>{[areaOf(current.address).district, areaOf(current.address).city].filter(Boolean).join(', ')}{current.openingTime && ` · Giờ ra vào ${current.openingTime}–${current.closingTime}`}</p>
<p>{typeNames.length ? `${typeNames.join(' & ')} · ` : ''}Quản lý: {current.managerName || ('managerName' in current ? 'Chưa phân công' : 'Chưa có thông tin')}</p></div>
<div className="ops-actions"><Button onClick={() => go(`business/reports${qs({ facility: current.facilityId })}`)}>Xem hiệu quả kinh doanh</Button></div>
<p>{typeNames.length ? `${typeNames.join(' & ')} · ` : ''}Quản lý: {current.managerName || ('managerName' in current ? 'Chưa phân công' : 'Chưa có thông tin')}</p>
<p>Vị trí bản đồ: {coordinateLabel(current)}</p></div>
<div className="ops-actions">
<Button onClick={() => go(`business/reports${qs({ facility: current.facilityId })}`)}>Xem hiệu quả kinh doanh</Button>
<Button variant="outline" onClick={() => setEditing(current)}>Sửa thông tin cơ sở</Button>
</div>
</section>}
{editing && <EditFacilityDialog facility={editing} onClose={() => setEditing(null)} onSaved={() => { setEditing(null); load.reload(); }} />}
</>;
}}</LoadState>
</main>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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; } }
Original file line number Diff line number Diff line change
@@ -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ó";
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
});
1 change: 1 addition & 0 deletions StorageProject.Api/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,7 @@
var context = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await context.Database.MigrateAsync();
await DbSeeder.SeedAsync(context);
await FacilityCoordinateSeeder.SeedAsync(context);
}


Expand Down
4 changes: 3 additions & 1 deletion StorageProject.Core/DTOs/Facility/FacilityDtos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
8 changes: 6 additions & 2 deletions StorageProject.Core/DTOs/Operations/OperationsDtos.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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);
Expand Down
3 changes: 3 additions & 0 deletions StorageProject.Core/Entities/Facility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
Expand Down
Loading