اصلاحات امنیتی و بقیه اصلاحات

This commit is contained in:
mahmoodsht 2026-11-08 16:11:42 +03:30
parent 5d50aef5fd
commit 28dd0f8453
23 changed files with 435 additions and 102 deletions

View File

@ -2,12 +2,67 @@ import { Archive, Trash2 } from "lucide-react";
import { useState } from "react";
import { api } from "../lib/api";
export type BulkArchiveRecord={id:string;rowVersion:string};
export function SelectionCheckbox({checked,onChange,label}:{checked:boolean;onChange:(checked:boolean)=>void;label:string}){return <input type="checkbox" checked={checked} onChange={e=>onChange(e.target.checked)} aria-label={label}/>;}
export function BulkArchiveActions({entityType,records,selected,onSelectionChange,onArchived}:{entityType:string;records:BulkArchiveRecord[];selected:Set<string>;onSelectionChange:(next:Set<string>)=>void;onArchived:(ids:string[])=>void}){
const[busy,setBusy]=useState(false);const chosen=records.filter(x=>selected.has(x.id));
function done(){const ids=chosen.map(x=>x.id);onSelectionChange(new Set());onArchived(ids);}
async function archive(){if(!chosen.length||!window.confirm(`${chosen.length} رکورد به بایگانی منتقل شود؟`))return;setBusy(true);try{for(const x of chosen)await api(`/api/v1/archive/${entityType}/${x.id}/archive`,{method:"POST",body:JSON.stringify({rowVersion:x.rowVersion})});done();}catch(e){window.alert(e instanceof Error?e.message:"بایگانی گروهی ناموفق بود.");}finally{setBusy(false);}}
async function remove(){if(!chosen.length)return;const phrase=`حذف دائمی ${chosen.length} رکورد`;const answer=window.prompt(`رکوردها واقعاً از دیتابیس حذف می‌شوند و قابل بازگشت نیستند.\nبرای ادامه دقیقاً بنویسید:\n${phrase}`);if(answer!==phrase){if(answer!==null)window.alert("عبارت تأیید صحیح نیست.");return;}if(!window.confirm("تأیید نهایی حذف دائمی؟"))return;setBusy(true);try{for(const x of chosen)await api(`/api/v1/delete/${entityType}/${x.id}`,{method:"DELETE",body:JSON.stringify({rowVersion:x.rowVersion})});done();}catch(e){window.alert(e instanceof Error?e.message:"حذف گروهی ناموفق بود.");}finally{setBusy(false);}}
const all=records.length>0&&records.every(x=>selected.has(x.id));return <div className="bulk-archive-bar"><label><SelectionCheckbox checked={all} onChange={on=>onSelectionChange(on?new Set(records.map(x=>x.id)):new Set())} label="انتخاب همه رکوردهای صفحه"/>انتخاب همه صفحه</label><span>{chosen.length} رکورد انتخاب شده</span><button type="button" className="button" disabled={!chosen.length||busy} onClick={()=>void archive()}><Archive size={16}/>بایگانی گروهی</button><button type="button" className="button danger" disabled={!chosen.length||busy} onClick={()=>void remove()}><Trash2 size={16}/>حذف دائمی گروهی</button></div>;
export type BulkArchiveRecord = { id: string; rowVersion: string };
export function SelectionCheckbox({ checked, onChange, label }: {
checked: boolean; onChange: (checked: boolean) => void; label: string;
}) {
return <input type="checkbox" checked={checked} onChange={e => onChange(e.target.checked)} aria-label={label}/>;
}
export function BulkArchiveActions({ entityType, records, selected, onSelectionChange, onArchived }: {
entityType: string; records: BulkArchiveRecord[]; selected: Set<string>;
onSelectionChange: (next: Set<string>) => void; onArchived: (ids: string[]) => void;
}) {
const [busy, setBusy] = useState(false);
const [result, setResult] = useState<{ success: number; failures: string[] } | null>(null);
const chosen = records.filter(x => selected.has(x.id));
async function run(action: "archive" | "delete") {
if (!chosen.length) return;
if (action === "archive") {
if (!window.confirm(`${chosen.length} رکورد به بایگانی منتقل شود؟`)) return;
} else {
const phrase = `حذف دائمی ${chosen.length} رکورد`;
if (window.prompt(`رکوردها واقعاً از دیتابیس حذف می‌شوند و قابل بازگشت نیستند.\nبرای ادامه دقیقاً بنویسید:\n${phrase}`) !== phrase) return;
if (!window.confirm("تأیید نهایی حذف دائمی؟")) return;
}
setBusy(true);
setResult(null);
const succeeded: string[] = [];
const failures: string[] = [];
try {
for (const record of chosen) {
try {
const path = action === "archive"
? `/api/v1/archive/${entityType}/${record.id}/archive`
: `/api/v1/delete/${entityType}/${record.id}`;
await api(path, { method: action === "archive" ? "POST" : "DELETE",
body: JSON.stringify({ rowVersion: record.rowVersion }) });
succeeded.push(record.id);
} catch (reason) {
failures.push(`${record.id}: ${reason instanceof Error ? reason.message : "عملیات ناموفق بود."}`);
}
}
} finally {
if (succeeded.length) {
onSelectionChange(new Set([...selected].filter(id => !succeeded.includes(id))));
onArchived(succeeded);
}
setBusy(false);
}
setResult({ success: succeeded.length, failures });
}
const all = records.length > 0 && records.every(x => selected.has(x.id));
return <div className="bulk-archive-bar">
{result && <div role="status" className="bulk-archive-result">
<strong>{result.success} مورد انجام شد؛ {result.failures.length} مورد ناموفق بود.</strong>
{result.failures.length > 0 && <ul>{result.failures.map((failure, index) => <li key={index}>{failure}</li>)}</ul>}
</div>}
<label><SelectionCheckbox checked={all} onChange={on => onSelectionChange(on ? new Set(records.map(x => x.id)) : new Set())} label="انتخاب همه رکوردهای صفحه"/>انتخاب همه صفحه</label>
<span>{chosen.length} رکورد انتخاب شده</span>
<button type="button" className="button" disabled={!chosen.length || busy} onClick={() => void run("archive")}><Archive size={16}/>بایگانی گروهی</button>
<button type="button" className="button danger" disabled={!chosen.length || busy} onClick={() => void run("delete")}><Trash2 size={16}/>حذف دائمی گروهی</button>
</div>;
}

View File

@ -0,0 +1,54 @@
import { useEffect, useMemo, useState } from "react";
import { api } from "../lib/api";
import { useDebouncedValue } from "./ListControls";
import { Input, Select } from "./Ui";
type Option = { id: string; title: string; projectNumber?: string };
type Page = { items: Option[]; totalCount: number };
export function RelatedEntitySelect({ name, path, value, onChange, placeholder, required = true }: {
name: string; path: "/api/v1/ideas" | "/api/v1/projects";
value: string; onChange: (id: string) => void; placeholder: string; required?: boolean;
}) {
const [search, setSearch] = useState("");
const query = useDebouncedValue(search);
const [items, setItems] = useState<Option[]>([]);
const [selected, setSelected] = useState<Option | null>(null);
const [total, setTotal] = useState(0);
const [error, setError] = useState("");
const [loading, setLoading] = useState(false);
useEffect(() => {
let active = true;
setLoading(true); setError("");
const params = new URLSearchParams({ page: "1", pageSize: "100" });
if (query.trim()) params.set("search", query.trim());
void api<Page>(`${path}?${params}`).then(result => {
if (active) { setItems(result.items); setTotal(result.totalCount); }
}).catch(reason => { if (active) setError(reason instanceof Error ? reason.message : "دریافت گزینه‌ها ناموفق بود."); })
.finally(() => { if (active) setLoading(false); });
return () => { active = false; };
}, [path, query]);
useEffect(() => {
if (!value) { setSelected(null); return; }
let active = true;
void api<Option>(`${path}/${value}`).then(item => { if (active) setSelected(item); })
.catch(() => { if (active) setSelected(null); });
return () => { active = false; };
}, [path, value]);
const options = useMemo(() => selected && !items.some(item => item.id === selected.id)
? [selected, ...items] : items, [selected, items]);
const label = (item: Option) => item.projectNumber ? `${item.projectNumber} — ${item.title}` : item.title;
return <div className="related-record-select">
<Input value={search} onChange={event => setSearch(event.target.value)} placeholder={placeholder}/>
<Select name={name} value={value} onChange={event => onChange(event.target.value)} required={required}>
<option value="">انتخاب کنید</option>
{options.map(item => <option key={item.id} value={item.id}>{label(item)}</option>)}
</Select>
{loading && <small>در حال دریافت گزینه‌ها…</small>}
{total > 100 && <small>از میان {total} رکورد، جست‌وجو کنید تا گزینهٔ موردنظر نمایش داده شود.</small>}
{error && <small role="alert">{error}</small>}
</div>;
}

View File

@ -1,13 +1,26 @@
import { useState, type ButtonHTMLAttributes, type ChangeEvent, type InputHTMLAttributes, type ReactNode, type SelectHTMLAttributes } from "react";
import { createContext, isValidElement, useContext, useState, type ButtonHTMLAttributes, type ChangeEvent, type InputHTMLAttributes, type ReactNode, type SelectHTMLAttributes } from "react";
import { PersianDateInput } from "./PersianDateInput";
export function Card({ children, className = "" }: { children: ReactNode; className?: string }) {
return <section className={`card ${className}`}>{children}</section>;
export function Card({ children, className = "", dataTab }: { children: ReactNode; className?: string; dataTab?: string }) {
return <section className={`card ${className}`} data-tab={dataTab}>{children}</section>;
}
export function Field({ label, hint, error, children }: { label: string; hint?: string; error?: string; children: ReactNode }) {
const formErrors = createContext<Record<string, string>>({});
export function FormErrorProvider({ errors, children }: { errors: Record<string, string>; children: ReactNode }) {
return <formErrors.Provider value={errors}>{children}</formErrors.Provider>;
}
export function Field({ label, hint, error, name, children }: { label: string; hint?: string; error?: string; name?: string; children: ReactNode }) {
const errors = useContext(formErrors);
const childName = isValidElement<{name?: string}>(children) ? children.props.name : undefined;
const key = name ?? childName;
const inlineError = error ?? (key
? errors[key] ?? errors[key.charAt(0).toUpperCase() + key.slice(1)] ??
Object.entries(errors).find(([field]) => field.toLowerCase().endsWith(`.${key.toLowerCase()}`))?.[1]
: undefined);
const unit = hint?.startsWith("واحد:") ? hint.slice("واحد:".length).trim() : undefined;
return <label className={`field ${error ? "has-error" : ""}`}><span className="field-label">{label}{unit && <em>{unit}</em>}</span>{children}{hint && !unit && <small>{hint}</small>}{error && <small className="field-error">{error}</small>}</label>;
return <label data-field={key} className={`field ${inlineError ? "has-error" : ""}`}><span className="field-label">{label}{unit && <em>{unit}</em>}</span>{children}{hint && !unit && <small>{hint}</small>}{inlineError && <small className="field-error">{inlineError}</small>}</label>;
}
type InputProps = InputHTMLAttributes<HTMLInputElement> & { groupDigits?: boolean };
@ -17,15 +30,12 @@ const latinDigits = (value: string) => value
.replace(/[٠-٩]/g, digit => String("٠١٢٣٤٥٦٧٨٩".indexOf(digit)));
function rawNumber(value: unknown) {
const source = latinDigits(value == null ? "" : String(value)).replace(/[٬,\s]/g, "");
const sign = source.startsWith("-") ? "-" : "";
const unsigned = source.replace(/-/g, "").replace(/[^\d.]/g, "");
const [integer = "", ...fractions] = unsigned.split(".");
return sign + integer + (unsigned.includes(".") ? `.${fractions.join("")}` : "");
return latinDigits(value == null ? "" : String(value)).replace(/[٬,\s]/g, "");
}
function groupedNumber(value: string) {
if (!value || value === "-") return value;
if (!/^-?\d*(?:\.\d*)?$/.test(value)) return value;
const sign = value.startsWith("-") ? "-" : "";
const unsigned = sign ? value.slice(1) : value;
const [integer, fraction] = unsigned.split(".");
@ -39,6 +49,8 @@ function GroupedNumberInput({ name, value, defaultValue, onChange, className, ..
const rawValue = controlled ? rawNumber(value) : uncontrolledValue;
const handleChange = (event: ChangeEvent<HTMLInputElement>) => {
const next = rawNumber(event.target.value);
event.currentTarget.setCustomValidity(next === "" || /^-?\d+(?:\.\d+)?$/.test(next)
? "" : "عدد معتبر وارد کنید؛ از حرف و نشانه‌های دیگر استفاده نکنید.");
if (!controlled) setUncontrolledValue(next);
if (onChange) {
onChange({
@ -76,7 +88,15 @@ export function Input({ groupDigits = false, ...props }: InputProps) {
/>;
}
if (groupDigits) return <GroupedNumberInput {...props}/>;
return <input className="input" {...props}/>;
const limits: Record<string, number> = {
projectNumber: 100, title: 1000, innovatorFullName: 500, fullName: 1000,
writer: 500, writerOrTranslator: 500, publishingOrganization: 500,
publicationPlace: 500, registrationPlace: 500, place: 500, organizer: 500,
area: 500, specializedField: 500, email: 320,
website: 2048, socialPage: 2048, link: 2048, directLink: 2048,
};
const maxLength = props.maxLength ?? (props.name ? limits[props.name] : undefined);
return <input className="input" {...props} maxLength={maxLength}/>;
}
export function Select(props: SelectHTMLAttributes<HTMLSelectElement>) { return <select className="input" {...props}/>; }
export function Button({ className = "", ...props }: ButtonHTMLAttributes<HTMLButtonElement>) { return <button className={`button ${className}`} {...props}/>; }
@ -90,5 +110,3 @@ export function EmptyState({ title, description }: { title: string; description:
}
export function ErrorBanner({ message }: { message: string }) { return <div className="error-banner" role="alert">{message}</div>; }

View File

@ -13,10 +13,53 @@ if (typeof window !== "undefined") {
export class ApiError extends Error {
constructor(public status: number, public problem: ApiProblem) {
super(safeApiMessage(status, problem.code, problem.traceId));
super(adminApiMessage(status, problem));
}
}
const fieldLabels: Record<string, string> = {
projectNumber: "شماره پروژه", title: "عنوان", startDate: "تاریخ شروع",
endDate: "تاریخ پایان", rating: "امتیاز", strategicThemeId: "مضمون راهبردی",
innovationValueId: "ارزش فناوری و نوآوری", fiscalYear: "سال مالی",
quarters: "اطلاعات فصل‌ها", projectId: "پروژه مرتبط", ideaId: "ایده مرتبط",
fullName: "نام کامل", collaborationStartDate: "تاریخ شروع همکاری",
innovatorFullName: "نام ایده‌پرداز", ideaStatus: "وضعیت ایده",
incomeAfter: "درآمد بعد", articles: "مقاله‌ها", patents: "اختراع‌ها",
article: "مقاله", patent: "اختراع", directLink: "لینک مستقیم",
reportType: "نوع گزارش", language: "زبان", bookType: "نوع کتاب",
activityType: "نوع فعالیت", eventType: "نوع رویداد", role: "نقش",
participationType: "نوع مشارکت", presenceType: "نوع حضور",
pageCount: "تعداد صفحات", personnelNumber: "شماره پرسنلی",
ideaOriginality: "اصالت ایده", file: "فایل", rowVersion: "نسخه رکورد",
userName: "نام کاربری", displayName: "نام نمایشی", password: "رمز عبور",
newPassword: "رمز عبور جدید", approvedBudget: "بودجه مصوب",
budgetSpent: "بودجه مصرف‌شده", innovationDetails: "جزئیات نوآوری",
greenDetails: "جزئیات نوآوری سبز", technologyParameters: "پارامترهای فناوری",
exports: "اطلاعات صادرات", counts: "تعدادها", amounts: "مبالغ",
};
export function adminFieldErrors(problem: ApiProblem): Record<string, string> {
if (Array.isArray(problem.errors))
return Object.fromEntries(problem.errors.map(x => [x.fieldCode, x.message]));
if (problem.errors && typeof problem.errors === "object")
return Object.fromEntries(Object.entries(problem.errors).map(([key, values]) => [key, values[0] ?? "مقدار معتبر نیست."]));
return {};
}
function adminApiMessage(status: number, problem: ApiProblem): string {
const safe = safeApiMessage(status, problem.code, problem.traceId);
if (status >= 500 || status === 401 || status === 403 || problem.code === "invalid_csrf") return safe;
const errors = adminFieldErrors(problem);
const first = Object.entries(errors)[0];
if (first) {
const [field, detail] = first;
const label = fieldLabels[field] ?? fieldLabels[field.split(".").at(-1) ?? ""];
return label ? `${label}: ${detail}` : detail;
}
return status === 422 && typeof problem.title === "string" && problem.title.length <= 300
? problem.title : safe;
}
async function getCsrfToken() {
if (csrfToken) return csrfToken;
const response = await fetch(`${apiOrigin}/api/v1/auth/csrf`, { credentials: "include" });

View File

@ -0,0 +1,24 @@
export function validateAdminForm(form: HTMLFormElement, selectTab: (tab: string) => void): boolean {
const firstInvalid = Array.from(form.elements).find(element =>
element instanceof HTMLElement && "validity" in element && !(element as HTMLInputElement).validity.valid
) as HTMLElement | undefined;
if (!firstInvalid) return true;
const tab = firstInvalid.closest<HTMLElement>("[data-tab]")?.dataset.tab;
if (tab) selectTab(tab);
requestAnimationFrame(() => {
firstInvalid.focus();
if ("reportValidity" in firstInvalid) (firstInvalid as HTMLInputElement).reportValidity();
});
return false;
}
export function focusAdminServerError(errors: Record<string, string>, selectTab: (tab: string) => void): void {
const field = Object.keys(errors)[0];
if (!field) return;
const target = Array.from(document.querySelectorAll<HTMLElement>("form.form-stack [data-field]"))
.find(element => element.dataset.field === field || field.endsWith(`.${element.dataset.field}`));
if (!target) return;
const tab = target.closest<HTMLElement>("[data-tab]")?.dataset.tab;
if (tab) selectTab(tab);
requestAnimationFrame(() => target.querySelector<HTMLElement>("input,select,textarea")?.focus());
}

View File

@ -1,10 +1,12 @@
import { ArrowRight, Save } from "lucide-react";
import { focusAdminServerError, validateAdminForm } from "../lib/validateForm";
import { useEffect, useState, type FormEvent } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { Button, Card, ErrorBanner, Field, Input, PageTitle, Select } from "../components/Ui";
import { ApiError, api } from "../lib/api";
import type { ArticleItem, IdeaItem, PagedResult, PatentItem } from "../types";
import { Button, Card, ErrorBanner, Field, FormErrorProvider, Input, PageTitle, Select } from "../components/Ui";
import { ApiError, adminFieldErrors, api } from "../lib/api";
import type { ArticleItem, PatentItem } from "../types";
import { FormTabs } from "../components/FormTabs";
import { RelatedEntitySelect } from "../components/RelatedEntitySelect";
export function AchievementFormPage() {
const { kind = "article", id } = useParams();
@ -12,22 +14,23 @@ export function AchievementFormPage() {
const article = kind === "article";
const navigate = useNavigate();
const [details, setDetails] = useState<ArticleItem | PatentItem | null>(null);
const [ideas, setIdeas] = useState<IdeaItem[]>([]);
const [ideaId, setIdeaId] = useState("");
const [error, setError] = useState("");
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const [loading, setLoading] = useState(editing);
const [activeTab, setActiveTab] = useState("info");
useEffect(() => {
const requests: Promise<unknown>[] = [
api<PagedResult<IdeaItem>>("/api/v1/ideas?page=1&pageSize=100").then((x) => setIdeas(x.items)),
];
const requests: Promise<unknown>[] = [];
if (editing) requests.push(api<ArticleItem | PatentItem>(`/api/v1/${article ? "articles" : "patents"}/${id}`).then(setDetails));
void Promise.all(requests).catch((e) => setError(e.message)).finally(() => setLoading(false));
}, [article, editing, id]);
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault(); setBusy(true); setError("");
e.preventDefault();
if (!validateAdminForm(e.currentTarget, setActiveTab)) return;
setBusy(true); setError(""); setFieldErrors({});
const f = new FormData(e.currentTarget);
const data = article
? { title: f.get("title"), publicationPlace: f.get("place"), directLink: f.get("directLink"), publishedDate: f.get("date"), status: Number(f.get("status")) }
@ -40,6 +43,11 @@ export function AchievementFormPage() {
});
navigate("/admin/achievements", { replace: true });
} catch (reason) {
if (reason instanceof ApiError) {
const errors = adminFieldErrors(reason.problem);
setFieldErrors(errors);
focusAdminServerError(errors, setActiveTab);
}
setError(reason instanceof ApiError ? reason.message : "ذخیره دستاورد ناموفق بود.");
} finally { setBusy(false); }
}
@ -52,21 +60,21 @@ export function AchievementFormPage() {
action={<Link to="/admin/achievements" className="text-link"><ArrowRight size={17}/>بازگشت</Link>}/>
{error && <ErrorBanner message={error}/>}
{editing && <FormTabs active={activeTab} onChange={setActiveTab} tabs={[{id:"info",label:"اطلاعات رکورد"},{id:"image",label:"تصویر"}]}/>}
<form className="form-stack" onSubmit={submit}>
<Card className={editing && activeTab !== "info" ? "tab-hidden" : ""}><div className="form-grid cols-3">
<form className="form-stack" onSubmit={submit} noValidate>
<FormErrorProvider errors={fieldErrors}>
<Card dataTab="info" className={editing && activeTab !== "info" ? "tab-hidden" : ""}><div className="form-grid cols-3">
<Field label="عنوان"><Input name="title" required defaultValue={value("title")}/></Field>
<Field label={article ? "محل چاپ" : "محل ثبت"}><Input name="place" required defaultValue={value(article ? "publicationPlace" : "registrationPlace")}/></Field>
<Field name={article ? "publicationPlace" : "registrationPlace"} label={article ? "محل چاپ" : "محل ثبت"}><Input name="place" required defaultValue={value(article ? "publicationPlace" : "registrationPlace")}/></Field>
<Field label="تاریخ"><Input name="date" type="date" required defaultValue={value(article ? "publishedDate" : "registeredDate")}/></Field>
<Field label="لینک مستقیم"><Input name="directLink" type="url" dir="ltr" required defaultValue={value("directLink")}/></Field>
{!editing && <Field label="ایده مرتبط" hint="اختیاری"><Select name="ideaId"><option value="">رکورد مستقل</option>{ideas.map((x) => <option key={x.id} value={x.id}>{x.title}</option>)}</Select></Field>}
{!editing && <Field label="ایده مرتبط" hint="اختیاری؛ برای رکورد مستقل خالی بگذارید"><RelatedEntitySelect name="ideaId" path="/api/v1/ideas" value={ideaId} onChange={setIdeaId} placeholder="جست‌وجوی ایده بر اساس عنوان یا ایده‌پرداز" required={false}/></Field>}
<Field label="وضعیت انتشار"><Select name="status" defaultValue={value("status") || "0"}><option value="0">پیش‌نویس</option><option value="1">انتشار</option></Select></Field>
</div></Card>
{editing && <Card className={activeTab !== "image" ? "tab-hidden" : "nested-section"}><Link className="text-link" to={`/admin/files/${article ? "PublishedArticle" : "RegisteredPatent"}/${id}`}>
مدیریت تصویر صفحه اول {article ? "مقاله" : "اختراع"}
</Link></Card>}
<div className={`form-actions${editing && activeTab === "image" ? " tab-hidden" : ""}`}><span>رابطه اختیاری با شناسه ایده</span><Button disabled={busy}><Save size={17}/>{busy ? "در حال ذخیره…" : "ذخیره"}</Button></div>
</FormErrorProvider>
</form>
</>;
}

View File

@ -8,7 +8,7 @@ import { RecordAvatar,useFirstImages } from "../components/RecordImage";
import { ListToolbar,PaginationControls,useDebouncedValue } from "../components/ListControls";
import { ArchiveButton } from "../components/ArchiveButton";
import { BulkArchiveActions,SelectionCheckbox } from "../components/BulkArchive";
function usePage<T extends{id:string}>(path:string){const[data,setData]=useState<PagedResult<T>|null>(null),[page,setPage]=useState(1),[pageSize,setPageSize]=useState(25),[search,setSearch]=useState(""),[error,setError]=useState(""),[loading,setLoading]=useState(true),debounced=useDebouncedValue(search);useEffect(()=>{let active=true;setLoading(true);const q=new URLSearchParams({page:String(page),pageSize:String(pageSize)});if(debounced)q.set("search",debounced);void api<PagedResult<T>>(`${path}?${q}`).then(x=>{if(active)setData(x)}).catch(e=>setError(e.message)).finally(()=>setLoading(false));return()=>{active=false}},[path,page,pageSize,debounced]);const remove=(id:string)=>setData(old=>old?{...old,items:old.items.filter(x=>x.id!==id),totalCount:old.totalCount-1}:old);return{data,page,pageSize,search,error,loading,setPage,setPageSize,setSearch,remove}}
function usePage<T extends{id:string}>(path:string){const[data,setData]=useState<PagedResult<T>|null>(null),[page,setPage]=useState(1),[pageSize,setPageSize]=useState(25),[search,setSearch]=useState(""),[error,setError]=useState(""),[loading,setLoading]=useState(true),debounced=useDebouncedValue(search);useEffect(()=>{let active=true;setLoading(true);setError("");const q=new URLSearchParams({page:String(page),pageSize:String(pageSize)});if(debounced)q.set("search",debounced);void api<PagedResult<T>>(`${path}?${q}`).then(x=>{if(active)setData(x)}).catch(e=>{if(active)setError(e.message)}).finally(()=>{if(active)setLoading(false)});return()=>{active=false}},[path,page,pageSize,debounced]);const remove=(id:string)=>setData(old=>old?{...old,items:old.items.filter(x=>x.id!==id),totalCount:old.totalCount-1}:old);return{data,page,pageSize,search,error,loading,setPage,setPageSize,setSearch,remove}}
const toggle=(old:Set<string>,id:string,on:boolean)=>{const n=new Set(old);on?n.add(id):n.delete(id);return n};
export function AchievementsPage(){const articles=usePage<ArticleItem>("/api/v1/articles"),patents=usePage<PatentItem>("/api/v1/patents"),[as,setAs]=useState<Set<string>>(new Set()),[ps,setPs]=useState<Set<string>>(new Set()),ai=useFirstImages("PublishedArticle",articles.data?.items.map(x=>x.id)),pi=useFirstImages("RegisteredPatent",patents.data?.items.map(x=>x.id));return <><PageTitle title="مقاله‌ها و اختراع‌ها" description="ثبت مستقل یا وابسته به ایده" action={<div className="row-actions"><Link className="button link-button" to="/admin/achievements/new/article"><Plus size={17}/>مقاله</Link><Link className="button link-button" to="/admin/achievements/new/patent"><Plus size={17}/>اختراع</Link></div>}/>{(articles.error||patents.error)&&<ErrorBanner message={articles.error||patents.error}/>}<Table title="مقاله‌های چاپ‌شده" state={articles} bulk={articles.data?.items.length?<BulkArchiveActions entityType="PublishedArticle" records={articles.data.items} selected={as} onSelectionChange={setAs} onArchived={ids=>ids.forEach(articles.remove)}/>:null}>{articles.data?.items.map(x=><tr key={x.id}><td><SelectionCheckbox checked={as.has(x.id)} onChange={on=>setAs(toggle(as,x.id,on))} label={`انتخاب ${x.title}`}/></td><td><RecordAvatar attachmentId={ai[x.id]??x.firstPageAttachmentId} label={x.title}/></td><td><FileBadge size={14}/> {x.title}</td><td>{x.publicationPlace}</td><td className="latin">{x.publishedDate}</td><td>{x.ideaId?"وابسته":"مستقل"}</td><td><Actions kind="article" id={x.id} rowVersion={x.rowVersion} done={()=>articles.remove(x.id)}/></td></tr>)}</Table><Table title="اختراع‌های ثبت‌شده" state={patents} bulk={patents.data?.items.length?<BulkArchiveActions entityType="RegisteredPatent" records={patents.data.items} selected={ps} onSelectionChange={setPs} onArchived={ids=>ids.forEach(patents.remove)}/>:null}>{patents.data?.items.map(x=><tr key={x.id}><td><SelectionCheckbox checked={ps.has(x.id)} onChange={on=>setPs(toggle(ps,x.id,on))} label={`انتخاب ${x.title}`}/></td><td><RecordAvatar attachmentId={pi[x.id]??x.firstPageAttachmentId} label={x.title}/></td><td><FileBadge size={14}/> {x.title}</td><td>{x.registrationPlace}</td><td className="latin">{x.registeredDate}</td><td>{x.ideaId?"وابسته":"مستقل"}</td><td><Actions kind="patent" id={x.id} rowVersion={x.rowVersion} done={()=>patents.remove(x.id)}/></td></tr>)}</Table></>}
type State={data:PagedResult<unknown>|null;page:number;pageSize:number;search:string;loading:boolean;setPage:(x:number)=>void;setPageSize:(x:number)=>void;setSearch:(x:string)=>void};

View File

@ -9,11 +9,11 @@ import { PaginationControls } from "../components/ListControls";
const actionLabels:Record<string,string>={Added:"ایجاد",Modified:"ویرایش",Deleted:"حذف",UserCreated:"ایجاد کاربر",UserUpdated:"ویرایش کاربر",PasswordReset:"بازنشانی رمز"};
export function AuditPage(){
const[data,setData]=useState<AuditResult|null>(null);const[users,setUsers]=useState<AdminUser[]>([]);const[error,setError]=useState("");const[query,setQuery]=useState("");const[page,setPage]=useState(1);const[pageSize,setPageSize]=useState(25);
async function load(q=query,p=page,size=pageSize){const suffix=[q,`page=${p}`,`pageSize=${size}`].filter(Boolean).join("&");setData(await api(`/api/v1/administration/audit?${suffix}`));}
async function load(q=query,p=page,size=pageSize){const suffix=[q,`page=${p}`,`pageSize=${size}`].filter(Boolean).join("&");setError("");setData(await api(`/api/v1/administration/audit?${suffix}`));}
useEffect(()=>{void Promise.all([api<AdminUser[]>("/api/v1/administration/users").then(setUsers),load("",1)]).catch(x=>setError(x.message));},[]);
async function filter(e:FormEvent<HTMLFormElement>){e.preventDefault();const f=new FormData(e.currentTarget);const p=new URLSearchParams();for(const key of ["actorId","entityType","action","fromDate","toDate"]){let value=String(f.get(key)??"").trim();if(value&&(key==="fromDate"||key==="toDate"))value=persianToGregorianIso(value);if(value)p.set(key,value)}const q=p.toString();setQuery(q);setPage(1);await load(q,1)}
async function move(next:number){setPage(next);await load(query,next)}
async function resize(next:number){setPageSize(next);setPage(1);await load(query,1,next)}
async function filter(e:FormEvent<HTMLFormElement>){e.preventDefault();const f=new FormData(e.currentTarget);const p=new URLSearchParams();for(const key of ["actorId","entityType","action","fromDate","toDate"]){let value=String(f.get(key)??"").trim();if(value&&(key==="fromDate"||key==="toDate"))value=persianToGregorianIso(value);if(value)p.set(key,value)}const q=p.toString();await load(q,1);setQuery(q);setPage(1)}
async function move(next:number){try{await load(query,next);setPage(next)}catch(x){setError(x instanceof Error?x.message:String(x))}}
async function resize(next:number){try{await load(query,1,next);setPageSize(next);setPage(1)}catch(x){setError(x instanceof Error?x.message:String(x))}}
return <><PageTitle title="تاریخچه عملیات" description="ردیابی تغییرات داده و عملیات مدیریتی بدون نمایش اطلاعات محرمانه"/>{error&&<ErrorBanner message={error}/>}<Card><form className="form-grid cols-3" onSubmit={e=>void filter(e).catch(x=>setError(x.message))}>
<Field label="کاربر"><Select name="actorId"><option value="">همه کاربران</option>{users.map(x=><option key={x.id} value={x.id}>{x.displayName}</option>)}</Select></Field>
<Field label="نوع رکورد"><Input name="entityType" placeholder="Project، ApplicationUser و…"/></Field><Field label="عملیات"><Select name="action"><option value="">همه عملیات</option>{Object.entries(actionLabels).map(([v,l])=><option key={v} value={v}>{l}</option>)}</Select></Field>
@ -22,4 +22,3 @@ export function AuditPage(){
}
function formatJson(value:string){try{return JSON.stringify(JSON.parse(value),null,2)}catch{return value}}

View File

@ -1,10 +1,11 @@
import { ArrowRight, Save } from "lucide-react";
import { focusAdminServerError, validateAdminForm } from "../lib/validateForm";
import { useEffect, useState, type FormEvent } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { Button, Card, ErrorBanner, Field, Input, PageTitle, Select } from "../components/Ui";
import { ApiError, api } from "../lib/api";
import type { PagedResult, ProjectItem } from "../types";
import { Button, Card, ErrorBanner, Field, FormErrorProvider, Input, PageTitle, Select } from "../components/Ui";
import { ApiError, adminFieldErrors, api } from "../lib/api";
import { FormTabs } from "../components/FormTabs";
import { RelatedEntitySelect } from "../components/RelatedEntitySelect";
const names: Record<string, string> = { publication: "گزارش/انتشار", event: "فعالیت رویدادی", book: "کتاب", performer: "نوآور برتر" };
@ -19,17 +20,17 @@ export function ContentFormPage() {
const [details, setDetails] = useState<Record<string, unknown> | null>(null);
const [eventType, setEventType] = useState("1");
const [presence, setPresence] = useState("");
const [projects, setProjects] = useState<ProjectItem[]>([]);
const [projectId, setProjectId] = useState("");
const [activeTab, setActiveTab] = useState("info");
useEffect(() => {
let active = true;
setError(""); setDetails(null); setLoading(editing);
const requests: Promise<void>[] = [];
if (kind === "performer") requests.push(api<PagedResult<ProjectItem>>("/api/v1/projects?page=1&pageSize=100").then(x => { if (active) setProjects(x.items); }));
if (editing) requests.push(api<Record<string, unknown>>(`${endpoint(kind)}/${id}`).then(x => {
if (!active) return;
setDetails(x); setEventType(String(x.activityType ?? 1)); setPresence(String(x.presenceType ?? ""));
setProjectId(String(x.projectId ?? ""));
}));
void Promise.all(requests).catch((reason: unknown) => {
if (active) setError(reason instanceof Error ? reason.message : "دریافت اطلاعات ناموفق بود.");
@ -43,7 +44,9 @@ export function ContentFormPage() {
};
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault(); setBusy(true); setError(""); setFieldErrors({});
e.preventDefault();
if (!validateAdminForm(e.currentTarget, setActiveTab)) return;
setBusy(true); setError(""); setFieldErrors({});
const data = payload(kind, new FormData(e.currentTarget), eventType);
try {
await api(editing ? `${endpoint(kind)}/${id}` : endpoint(kind), {
@ -54,7 +57,9 @@ export function ContentFormPage() {
} catch (reason) {
if (reason instanceof ApiError) {
setError(reason.message);
setFieldErrors(Object.fromEntries((reason.problem.errors ?? []).map(x => [x.fieldCode, x.message])));
const errors = adminFieldErrors(reason.problem);
setFieldErrors(errors);
focusAdminServerError(errors, setActiveTab);
} else setError("ذخیره اطلاعات ناموفق بود.");
} finally { setBusy(false); }
}
@ -64,8 +69,9 @@ export function ContentFormPage() {
{error && <ErrorBanner message={error}/>}
{editing && kind === "performer" && <FormTabs active={activeTab} onChange={setActiveTab} tabs={[{id:"info",label:"اطلاعات نوآور"},{id:"image",label:"تصویر"}]}/>}
{loading ? <Card><p>در حال دریافت اطلاعات…</p></Card> : (!editing || details) &&
<form className="form-stack" onSubmit={submit} key={`${kind}-${id ?? "new"}`}>
<Card className={editing && kind === "performer" && activeTab !== "info" ? "tab-hidden" : ""}><div className="form-grid cols-3">
<form className="form-stack" onSubmit={submit} noValidate key={`${kind}-${id ?? "new"}`}>
<FormErrorProvider errors={fieldErrors}>
<Card dataTab="info" className={editing && kind === "performer" && activeTab !== "info" ? "tab-hidden" : ""}><div className="form-grid cols-3">
{kind === "publication" && <>
<Field label="عنوان گزارش" error={fieldErrors.title}><Input name="title" required defaultValue={value("title")}/></Field>
<Field label="نویسنده"><Input name="writer" required defaultValue={value("writer")}/></Field>
@ -100,8 +106,8 @@ export function ContentFormPage() {
</>}
{kind === "performer" && <>
<Field label="عنوان نوآور برتر"><Input name="title" required defaultValue={value("title")}/></Field>
<Field label="شماره پرسنلی"><Input name="personnelNumber" required dir="ltr" defaultValue={value("personnelNumber")}/></Field>
<Field label="پروژه مرتبط"><Select name="projectId" required defaultValue={value("projectId")}><option value="">انتخاب کنید</option>{projects.map(x => <option key={x.id} value={x.id}>{x.projectNumber} — {x.title}</option>)}</Select></Field>
<Field label="شماره پرسنلی"><Input name="personnelNumber" maxLength={100} required dir="ltr" defaultValue={value("personnelNumber")}/></Field>
<Field label="پروژه مرتبط"><RelatedEntitySelect name="projectId" path="/api/v1/projects" value={projectId} onChange={setProjectId} placeholder="جست‌وجوی شماره یا عنوان پروژه"/></Field>
<Field label="اصالت ایده"><Select name="ideaOriginality" defaultValue={value("ideaOriginality", "کپی")}><option>کپی</option><option>الهام داخلی</option><option>الهام بین‌المللی</option><option>اصیل</option></Select></Field>
<Money name="revenueBefore" label="درآمد قبل" defaultValue={value("revenueBefore", 0)}/><Money name="revenueAfter" label="درآمد بعد" defaultValue={value("revenueAfter", 0)}/>
{initiativeKinds.map(x => <Field key={x.key} label={x.countLabel}><Input name={`${x.key}InitiativesCount`} type="number" min="0" required defaultValue={value(`${x.key}InitiativesCount`, 0)}/></Field>)}
@ -116,6 +122,7 @@ export function ContentFormPage() {
مدیریت تصویر نوآور برتر
</Link></Card>}
<div className={`form-actions${editing && kind === "performer" && activeTab === "image" ? " tab-hidden" : ""}`}><span>ذخیره در مدل typed مستقل با کنترل هم‌زمانی</span><Button disabled={busy}><Save size={18}/>{busy ? "در حال ذخیره…" : editing ? "ذخیره تغییرات" : "ثبت اطلاعات"}</Button></div>
</FormErrorProvider>
</form>}
</>;
}
@ -138,5 +145,3 @@ function payload(kind: string, form: FormData, eventActivityType: string) {
if (kind === "event") return { activityType: Number(eventActivityType), title: str(form, "title"), eventDate: str(form, "eventDate"), place: str(form, "place"), organizer: str(form, "organizer"), link: str(form, "link"), eventType: str(form, "eventType"), role: str(form, "role"), audience: str(form, "audience"), summary: str(form, "summary"), achievement: str(form, "achievement"), axis: str(form, "axis"), participationType: str(form, "participationType"), presentationTitle: str(form, "presentationTitle"), area: str(form, "area"), presenceType: str(form, "presenceType"), productTitle: str(form, "productTitle"), status };
return { title: str(form, "title"), personnelNumber: str(form, "personnelNumber"), projectId: str(form, "projectId"), ideaOriginality: str(form, "ideaOriginality"), revenueBefore: str(form, "revenueBefore"), revenueAfter: str(form, "revenueAfter"), registeredInitiativesCount: num(form, "registeredInitiativesCount"), underReviewInitiativesCount: num(form, "underReviewInitiativesCount"), inProgressInitiativesCount: num(form, "inProgressInitiativesCount"), completedInitiativesCount: num(form, "completedInitiativesCount"), articlesCount: num(form, "articlesCount"), inventionsCount: num(form, "inventionsCount"), processImprovement: str(form, "processImprovement"), registeredInitiativesAmount: str(form, "registeredInitiativesAmount"), underReviewInitiativesAmount: str(form, "underReviewInitiativesAmount"), inProgressInitiativesAmount: str(form, "inProgressInitiativesAmount"), completedInitiativesAmount: str(form, "completedInitiativesAmount"), status };
}

View File

@ -1,4 +1,6 @@
import { ArrowRight, Save } from "lucide-react";
import { focusAdminServerError, validateAdminForm } from "../lib/validateForm";
import { FormErrorProvider } from "../components/Ui";
import { useEffect, useState, type FormEvent } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
@ -10,7 +12,7 @@ import {
PageTitle,
Select,
} from "../components/Ui";
import { ApiError, api } from "../lib/api";
import { ApiError, adminFieldErrors, api } from "../lib/api";
import type { EcosystemActorItem } from "../types";
import { actorLabels } from "./EcosystemPage";
import { isMoneyField, unitHint } from "../lib/fieldUnits";
@ -78,6 +80,7 @@ export function EcosystemFormPage() {
const [busy, setBusy] = useState(false);
const [loading, setLoading] = useState(editing);
const [error, setError] = useState("");
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [activeTab, setActiveTab] = useState("common");
useEffect(() => {
if (!editing) return;
@ -94,8 +97,10 @@ export function EcosystemFormPage() {
details?.[key] == null ? "" : String(details[key]);
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!validateAdminForm(event.currentTarget, setActiveTab)) return;
setBusy(true);
setError("");
setFieldErrors({});
const f = new FormData(event.currentTarget);
const payload: Record<string, unknown> = {
actorType: Number(type),
@ -122,6 +127,11 @@ export function EcosystemFormPage() {
});
navigate("/admin/ecosystem", { replace: true });
} catch (reason) {
if (reason instanceof ApiError) {
const errors = adminFieldErrors(reason.problem);
setFieldErrors(errors);
focusAdminServerError(errors, setActiveTab);
}
setError(
reason instanceof ApiError
? reason.message
@ -153,8 +163,9 @@ export function EcosystemFormPage() {
{editing && <FormTabs active={activeTab} onChange={setActiveTab} tabs={[
{id:"common",label:"مشخصات مشترک"},{id:"specific",label:"اطلاعات اختصاصی"},{id:"image",label:"تصویر یا لوگو"},
]}/>}
<form className="form-stack" onSubmit={submit} key={id ?? "new"}>
<Card className={editing && activeTab !== "common" ? "tab-hidden" : ""}>
<form className="form-stack" onSubmit={submit} noValidate key={id ?? "new"}>
<FormErrorProvider errors={fieldErrors}>
<Card dataTab="common" className={editing && activeTab !== "common" ? "tab-hidden" : ""}>
<div className="section-heading">
<span>۰۱</span>
<div>
@ -194,7 +205,7 @@ export function EcosystemFormPage() {
</Field>
</div>
</Card>
<Card className={editing && activeTab !== "specific" ? "tab-hidden" : ""}>
<Card dataTab="specific" className={editing && activeTab !== "specific" ? "tab-hidden" : ""}>
<div className="section-heading green-heading">
<span>۰۲</span>
<div>
@ -226,6 +237,7 @@ export function EcosystemFormPage() {
{busy ? "در حال ذخیره…" : editing ? "ذخیره تغییرات" : "ثبت بازیگر"}
</Button>
</div>
</FormErrorProvider>
</form>
</>
);
@ -265,5 +277,3 @@ function DynamicField({
</Field>
);
}

View File

@ -1,4 +1,6 @@
import { ArrowRight, Save } from "lucide-react";
import { focusAdminServerError, validateAdminForm } from "../lib/validateForm";
import { FormErrorProvider } from "../components/Ui";
import { useEffect, useState, type FormEvent } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
@ -10,7 +12,7 @@ import {
PageTitle,
Select,
} from "../components/Ui";
import { ApiError, api } from "../lib/api";
import { ApiError, adminFieldErrors, api } from "../lib/api";
import { unitHint } from "../lib/fieldUnits";
import { FormTabs } from "../components/FormTabs";
import type { FinancialYearDetails } from "../types";
@ -36,6 +38,7 @@ export function FinancialFormPage() {
const [busy, setBusy] = useState(false);
const [loading, setLoading] = useState(editing);
const [error, setError] = useState("");
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [activeTab, setActiveTab] = useState("base");
useEffect(() => {
if (!editing) return;
@ -60,8 +63,10 @@ export function FinancialFormPage() {
}, [editing, id]);
async function submit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (!validateAdminForm(e.currentTarget, setActiveTab)) return;
setBusy(true);
setError("");
setFieldErrors({});
const f = new FormData(e.currentTarget);
const quarters = [1, 2, 3, 4].map((quarter) => ({
quarter,
@ -81,6 +86,11 @@ export function FinancialFormPage() {
});
navigate("/admin/financial", { replace: true });
} catch (reason) {
if (reason instanceof ApiError) {
const errors = adminFieldErrors(reason.problem);
setFieldErrors(errors);
focusAdminServerError(errors, setActiveTab);
}
setError(
reason instanceof ApiError
? reason.message
@ -112,8 +122,9 @@ export function FinancialFormPage() {
{editing && <FormTabs active={activeTab} onChange={setActiveTab} tabs={[
{id:"base",label:"سال مالی"},...([1,2,3,4].map(q=>({id:`q${q}`,label:`فصل ${quarterNames[q]}`}))),
]}/>}
<form className="form-stack" onSubmit={submit}>
<Card className={editing && activeTab !== "base" ? "tab-hidden" : ""}>
<form className="form-stack" onSubmit={submit} noValidate>
<FormErrorProvider errors={fieldErrors}>
<Card dataTab="base" className={editing && activeTab !== "base" ? "tab-hidden" : ""}>
<div className="form-grid cols-3">
<Field label="سال مالی شمسی">
<Input
@ -137,7 +148,7 @@ export function FinancialFormPage() {
</div>
</Card>
{[1, 2, 3, 4].map((quarter) => (
<Card key={quarter} className={`nested-section${editing && activeTab !== `q${quarter}` ? " tab-hidden" : ""}`}>
<Card key={quarter} dataTab={`q${quarter}`} className={`nested-section${editing && activeTab !== `q${quarter}` ? " tab-hidden" : ""}`}>
<div className="section-heading">
<span>۰{quarter}</span>
<div>
@ -147,7 +158,7 @@ export function FinancialFormPage() {
</div>
<div className="form-grid cols-3">
{fields.map(([key, label]) => (
<Field key={key} label={label} hint={unitHint("financial", key)}>
<Field key={key} name={`${quarter}.${key}`} label={label} hint={unitHint("financial", key)}>
<Input
required={status === "1"}
groupDigits
@ -177,9 +188,8 @@ export function FinancialFormPage() {
: "ثبت سال مالی"}
</Button>
</div>
</FormErrorProvider>
</form>
</>
);
}

View File

@ -1,8 +1,9 @@
import { ArrowRight, Plus, Save, Trash2 } from "lucide-react";
import { focusAdminServerError, validateAdminForm } from "../lib/validateForm";
import { useEffect, useState, type FormEvent, type ReactNode } from "react";
import { Link, useNavigate, useParams } from "react-router";
import { Button, Card, ErrorBanner, Field, Input, PageTitle, Select } from "../components/Ui";
import { ApiError, api } from "../lib/api";
import { Button, Card, ErrorBanner, Field, FormErrorProvider, Input, PageTitle, Select } from "../components/Ui";
import { ApiError, adminFieldErrors, api } from "../lib/api";
import { isMoneyField, unitHint } from "../lib/fieldUnits";
import type { IdeaDetails } from "../types";
import { FormTabs } from "../components/FormTabs";
@ -50,6 +51,7 @@ export function IdeaFormPage() {
const [busy, setBusy] = useState(false);
const [loading, setLoading] = useState(editing);
const [error, setError] = useState("");
const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});
const [activeTab, setActiveTab] = useState("info");
useEffect(() => {
@ -64,7 +66,9 @@ export function IdeaFormPage() {
}
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault(); setBusy(true); setError("");
event.preventDefault();
if (!validateAdminForm(event.currentTarget, setActiveTab)) return;
setBusy(true); setError(""); setFieldErrors({});
const f = new FormData(event.currentTarget);
const read = (name: string) => f.get(name) || null;
const data = {
@ -84,6 +88,11 @@ export function IdeaFormPage() {
await api(editing ? `/api/v1/ideas/${id}` : "/api/v1/ideas", { method: editing ? "PUT" : "POST", body: JSON.stringify(data) });
navigate("/admin/ideas", { replace: true });
} catch (reason) {
if (reason instanceof ApiError) {
const errors = adminFieldErrors(reason.problem);
setFieldErrors(errors);
focusAdminServerError(errors, setActiveTab);
}
setError(reason instanceof ApiError ? reason.message : "ذخیره ایده ناموفق بود.");
} finally { setBusy(false); }
}
@ -97,8 +106,9 @@ export function IdeaFormPage() {
{editing && <FormTabs active={activeTab} onChange={setActiveTab} tabs={[
{id:"info",label:"اطلاعات ایده"},{id:"related",label:"دستاوردها و تصویر"},
]}/>}
<form className="form-stack" onSubmit={submit} key={id ?? "new"}>
<Card className={editing && activeTab !== "info" ? "tab-hidden" : ""}>
<form className="form-stack" onSubmit={submit} noValidate key={id ?? "new"}>
<FormErrorProvider errors={fieldErrors}>
<Card dataTab="info" className={editing && activeTab !== "info" ? "tab-hidden" : ""}>
<div className="section-heading"><span>۰۱</span><div><h3>اطلاعات ایده</h3><p>فیلدهای مستند فرایند ۱۲۳۰</p></div></div>
<div className="form-grid cols-3">
{fields.map(([key, label, kind]) => <Field key={key} label={label} hint={unitHint("idea", String(key))}>
@ -122,7 +132,7 @@ export function IdeaFormPage() {
<Input placeholder="عنوان مقاله" value={x.title} onChange={(e) => update(articles, setArticles, i, "title", e.target.value)} required/>
<Input placeholder="محل چاپ" value={x.publicationPlace} onChange={(e) => update(articles, setArticles, i, "publicationPlace", e.target.value)} required/>
<Input type="date" value={x.publishedDate} onChange={(e) => update(articles, setArticles, i, "publishedDate", e.target.value)} required/>
<Input placeholder="لینک مستقیم" dir="ltr" value={x.directLink} onChange={(e) => update(articles, setArticles, i, "directLink", e.target.value)} required/>
<Input placeholder="لینک مستقیم" type="url" dir="ltr" maxLength={2048} value={x.directLink} onChange={(e) => update(articles, setArticles, i, "directLink", e.target.value)} required/>
<button type="button" className="icon-remove" aria-label="حذف مقاله" onClick={() => setArticles(articles.filter((_, j) => j !== i))}><Trash2 size={17}/></button>
</div>)}
</AchievementCard>}
@ -131,7 +141,7 @@ export function IdeaFormPage() {
<Input placeholder="عنوان اختراع" value={x.title} onChange={(e) => update(patents, setPatents, i, "title", e.target.value)} required/>
<Input placeholder="محل ثبت" value={x.registrationPlace} onChange={(e) => update(patents, setPatents, i, "registrationPlace", e.target.value)} required/>
<Input type="date" value={x.registeredDate} onChange={(e) => update(patents, setPatents, i, "registeredDate", e.target.value)} required/>
<Input placeholder="لینک مستقیم" dir="ltr" value={x.directLink} onChange={(e) => update(patents, setPatents, i, "directLink", e.target.value)} required/>
<Input placeholder="لینک مستقیم" type="url" dir="ltr" maxLength={2048} value={x.directLink} onChange={(e) => update(patents, setPatents, i, "directLink", e.target.value)} required/>
<button type="button" className="icon-remove" aria-label="حذف اختراع" onClick={() => setPatents(patents.filter((_, j) => j !== i))}><Trash2 size={17}/></button>
</div>)}
</AchievementCard>}
@ -139,6 +149,7 @@ export function IdeaFormPage() {
<Link className="text-link" to={`/admin/files/Idea/${id}`}>مدیریت تصویر ایده‌پرداز</Link></div></Card>}
<div className={`form-actions${editing && activeTab === "related" ? " tab-hidden" : ""}`}><span>{editing ? "ویرایش با کنترل نسخه رکورد" : `ثبت اتمیک ایده و ${articles.length + patents.length} دستاورد`}</span>
<Button type="submit" disabled={busy}><Save size={18}/>{busy ? "در حال ذخیره…" : editing ? "ذخیره تغییرات" : "ثبت ایده"}</Button></div>
</FormErrorProvider>
</form>
</>;
}
@ -147,5 +158,3 @@ function AchievementCard({ title, add, children }: { title: string; add: () => v
return <Card className="nested-section"><div className="card-heading"><div><h3>{title}</h3><p>رابطه با شناسه ایده ذخیره می‌شود.</p></div>
<Button type="button" className="secondary" onClick={add}><Plus size={16}/>افزودن</Button></div>{children}</Card>;
}

View File

@ -1,4 +1,6 @@
import { ArrowRight, Check, Leaf, Plus, Save, Trash2 } from "lucide-react";
import { focusAdminServerError, validateAdminForm } from "../lib/validateForm";
import { FormErrorProvider } from "../components/Ui";
import { useEffect, useMemo, useState, type FormEvent } from "react";
import { Link, useNavigate, useParams } from "react-router";
import {
@ -10,7 +12,7 @@ import {
PageTitle,
Select,
} from "../components/Ui";
import { ApiError, api } from "../lib/api";
import { ApiError, adminFieldErrors, api } from "../lib/api";
import type { ProjectDetails, ReferenceItem } from "../types";
import {
buildInnovationPayload,
@ -118,6 +120,7 @@ export function ProjectFormPage() {
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
if (!validateAdminForm(event.currentTarget, setActiveTab)) return;
setBusy(true);
setError("");
setFieldErrors({});
@ -206,11 +209,9 @@ export function ProjectFormPage() {
} catch (reason) {
if (reason instanceof ApiError) {
setError(reason.message);
setFieldErrors(
Object.fromEntries(
(reason.problem.errors ?? []).map((x) => [x.fieldCode, x.message]),
),
);
const errors = adminFieldErrors(reason.problem);
setFieldErrors(errors);
focusAdminServerError(errors, setActiveTab);
} else setError("ذخیره پروژه ناموفق بود.");
} finally {
setBusy(false);
@ -246,8 +247,9 @@ export function ProjectFormPage() {
{ id: "details", label: "جزئیات نوآوری" },
{ id: "children", label: "اطلاعات وابسته" },
]}/>}
<form onSubmit={submit} className="form-stack" key={id ?? "new"}>
<Card className={editing && activeTab !== "base" ? "tab-hidden" : ""}>
<form onSubmit={submit} noValidate className="form-stack" key={id ?? "new"}>
<FormErrorProvider errors={fieldErrors}>
<Card dataTab="base" className={editing && activeTab !== "base" ? "tab-hidden" : ""}>
<div className="section-heading">
<span>۰۱</span>
<div>
@ -260,12 +262,13 @@ export function ProjectFormPage() {
<Input
name="projectNumber"
required
maxLength={100}
placeholder="PRJ-1405-001"
defaultValue={rootValue("projectNumber")}
/>
</Field>
<Field label="عنوان پروژه" error={fieldErrors.title}>
<Input name="title" required defaultValue={rootValue("title")} />
<Input name="title" required maxLength={1000} defaultValue={rootValue("title")} />
</Field>
<Field
label="نوع نوآوری"
@ -392,7 +395,7 @@ export function ProjectFormPage() {
</Field>
</div>
</Card>
<Card className={editing && activeTab !== "general" ? "tab-hidden" : ""}>
<Card dataTab="general" className={editing && activeTab !== "general" ? "tab-hidden" : ""}>
<div className="section-heading">
<span>۰۲</span>
<div>
@ -442,7 +445,7 @@ export function ProjectFormPage() {
</div>
</Card>
{innovationType === "4" && (
<Card className={editing && activeTab !== "details" ? "tab-hidden" : ""}>
<Card dataTab="details" className={editing && activeTab !== "details" ? "tab-hidden" : ""}>
<div className="section-heading green-heading">
<span>
<Leaf size={18} />
@ -705,6 +708,7 @@ export function ProjectFormPage() {
{busy ? "در حال ذخیره…" : editing ? "ذخیره تغییرات" : "ثبت پروژه"}
</Button>
</div>
</FormErrorProvider>
</form>
{editing && id && activeTab === "children" && <ProjectChildrenPage embeddedProjectId={id} />}
</>
@ -744,5 +748,3 @@ function stringValues(source: Record<string, unknown>, excluded?: string) {
.map(([key, value]) => [key, value == null ? "" : String(value)]),
);
}

View File

@ -34,6 +34,8 @@
.form-tabs button{font:inherit;white-space:nowrap;border:0;background:transparent;color:var(--muted,#64748b);padding:.7rem 1rem;border-radius:10px;cursor:pointer}
.form-tabs button.active{background:var(--primary,#176b87);color:#fff}
.tab-hidden{display:none!important}
.bulk-archive-result{width:100%;padding:.75rem;border:1px solid var(--border-color,#d1d5db);border-radius:.5rem;white-space:normal}
.bulk-archive-result ul{margin:.5rem 0 0;padding-inline-start:1.5rem;max-height:12rem;overflow:auto}
.activation-page{min-height:100vh;padding:36px 20px;display:grid;place-items:center;background:radial-gradient(circle at 10% 10%,#15324a,#07111f 58%);direction:rtl}.activation-card{width:min(760px,100%);background:#fff;border-radius:24px;padding:30px;box-shadow:0 35px 100px #0008}.activation-brand{display:flex;align-items:center;gap:14px;padding-bottom:20px;border-bottom:1px solid var(--line)}.activation-brand img{width:64px;height:64px;object-fit:contain}.activation-brand h1{font-size:18px;margin:0 0 5px}.activation-brand p{font-size:12px;color:var(--muted);margin:0}.activation-heading{display:flex;gap:13px;align-items:center;margin:24px 0 18px}.activation-heading>span{width:48px;height:48px;border-radius:14px;display:grid;place-items:center;background:#e5fff2;color:var(--green-dark)}.activation-heading h2{font-size:21px;margin:0 0 5px}.activation-heading p{font-size:11px;color:var(--muted);margin:0}.fingerprint-box{background:#f5f8fa;border:1px solid var(--line);border-radius:14px;padding:15px;margin-bottom:18px}.fingerprint-box>div{display:flex;justify-content:space-between;font-size:11px;margin-bottom:10px}.fingerprint-box code,.readonly-copy code{display:block;direction:ltr;text-align:left;word-break:break-all;font:12px/1.9 Consolas,monospace;color:#1c5065}.fingerprint-box button,.readonly-copy button{border:0;background:transparent;color:var(--green-dark);cursor:pointer;padding:6px 0}.activation-code-input{min-height:125px}.activation-submit{width:100%}.deployment-settings-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.deployment-section{min-width:0}.activation-status-card{grid-row:span 2}.settings-details{display:grid;gap:0;margin:0 0 18px}.settings-details>div{display:flex;justify-content:space-between;gap:18px;padding:10px 0;border-bottom:1px solid #edf1f3}.settings-details dt{color:var(--muted);font-size:11px}.settings-details dd{margin:0;font-size:11px;text-align:left}.readonly-copy{display:grid;grid-template-columns:1fr 34px;gap:8px;align-items:center;background:#f5f8fa;border:1px solid var(--line);border-radius:10px;padding:8px 11px}.theme-swatches{display:grid;gap:12px}.theme-swatches>div{display:grid;grid-template-columns:40px 1fr auto;align-items:center;gap:10px}.theme-swatches span{width:40px;height:40px;border-radius:12px;border:1px solid #0001}.theme-swatches small{color:var(--muted)}.configured-units{display:flex;gap:8px;flex-wrap:wrap}.configured-units span{background:#eef7fa;border:1px solid #d9e9ef;border-radius:99px;padding:7px 12px;font-size:10px}
@media(max-width:900px){.deployment-settings-grid{grid-template-columns:1fr}.activation-status-card{grid-row:auto}.activation-card{padding:22px}}
.form-grid.cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.deployment-logo-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.deployment-logo-grid>label{display:flex;flex-direction:column;align-items:center;gap:10px;border:1px solid var(--line);border-radius:14px;padding:14px;text-align:center}.deployment-logo-grid img{width:100%;height:100px;object-fit:contain;background:#f7f9fa;border-radius:10px}.deployment-logo-grid strong{font-size:10px}.deployment-logo-grid input{position:absolute;width:1px;height:1px;opacity:0;pointer-events:none}.theme-editor{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.color-field{display:grid;grid-template-columns:44px 1fr;gap:8px}.color-field input[type=color]{width:44px;height:43px;border:1px solid var(--line);border-radius:10px;padding:3px;background:#fff}.unit-settings-list{display:grid;gap:10px;margin-top:16px}.unit-settings-list>div{display:grid;grid-template-columns:75px 1fr 1fr;gap:10px;align-items:end;border:1px solid var(--line);border-radius:12px;padding:12px;background:#fafcfd}.unit-settings-list>div>strong{align-self:center;font-size:11px}.checkbox-row{display:flex;align-items:center;gap:9px;font-size:11px;color:#45535c}.checkbox-row input{width:17px;height:17px;accent-color:var(--green-dark)}

View File

@ -61,7 +61,7 @@ export type ApiProblem = {
title?: string;
code?: string;
traceId?: string;
errors?: Array<{ fieldCode: string; message: string }>;
errors?: Array<{ fieldCode: string; message: string }> | Record<string, string[]>;
};
export type ArchivePreview = { entityType:string; entityId:string; canArchive:boolean;
dependencies:Array<{code:string;label:string;count:number;blocksArchive:boolean}>;
@ -73,4 +73,3 @@ export type AuditEventItem = { id:string; occurredAtUtc:string; actorId:string;
action:string; entityType:string; entityId?:string; changesJson?:string; traceId?:string };
export type AuditPage = { items:AuditEventItem[]; totalCount:number; page:number; pageSize:number };

View File

@ -86,7 +86,28 @@ USE [Inogen_CompanyA]; IF USER_ID(N'inogen_runtime') IS NULL CREATE USER [inogen
رمز مدیر باید حداقل ۱۲ نویسه، حرف بزرگ، حرف کوچک، رقم و نویسهٔ ویژه داشته باشد. نام کاربری خروجی را ثبت کنید و رمز را جداگانه و امن تحویل دهید. حساب مدیر با رمز پیش‌فرض وجود ندارد.
پس از فعال‌سازی و ورود مدیر، صفحهٔ تنظیمات استقرار را مستقیم با نشانی مانند `https://app.example.com/admin/deployment-settings` باز کنید. این صفحه در منوی پنل نمایش داده نمی‌شود. در بخش `واحدهای داشبورد` نام واحدها و چیدمان را ثبت کنید و دکمهٔ `ذخیره تنظیمات` را بزنید. صفحهٔ ورود کد فعال‌سازی فقط کد را دریافت می‌کند؛ تنظیمات واحدها در صفحهٔ جداگانه انجام می‌شود.
پس از فعال‌سازی و اولین ورود مدیر، اگر تنظیمات شرکت هنوز کامل نشده باشد، صفحهٔ «تنظیمات استقرار» به‌صورت خودکار نمایش داده می‌شود. برای بازکردن آن در دفعات بعد، نشانی `https://app.example.com/admin/deployment-settings` را دستی در نوار آدرس مرورگر وارد کنید؛ این صفحه در منوی پنل نمایش داده نمی‌شود و فقط حساب مدیر به آن دسترسی دارد. صفحهٔ ورود کد فعال‌سازی فقط کد را دریافت می‌کند؛ مشخصات شرکت و واحدها در صفحهٔ جداگانهٔ تنظیمات استقرار ثبت می‌شوند.
### فایل‌های لازم برای راه‌اندازی شرکت جدید
پیش از ورود به صفحهٔ تنظیمات استقرار، این فایل‌ها و اطلاعات را از شرکت دریافت کنید:
- **لوگوی ورود داشبورد:** فایل SVG مخصوص صفحهٔ ورود بخش گزارش‌ها، حداکثر ۲ مگابایت.
- **لوگوی ورود ادمین:** فایل SVG مخصوص صفحهٔ ورود پنل مدیریت، حداکثر ۲ مگابایت. اگر قرار است هر دو صفحه یک نشان داشته باشند، همان فایل SVG را برای هر دو جایگاه انتخاب کنید.
- **تصویر هر واحد یا شرکت مرتبط در داشبورد، در صورت نیاز:** برای هر جایگاه یک فایل PNG، GIF، WebP یا SVG، حداکثر ۸ مگابایت. اگر تصویر اختصاصی ندارید، تصویر پیش‌فرض همان جایگاه باقی می‌ماند. برای PNG، عرض و ارتفاع نباید از ۴۰۹۶ پیکسل بیشتر باشد.
- **نام رسمی شرکت و فهرست واحدها:** نامی که باید در سامانه نمایش داده شود، نام هر واحد یا شرکت مرتبط، تعداد واحدها (یک تا شش)، و ترتیب دلخواه نمایش آن‌ها.
فایل‌های SVG باید معتبر و بدون کد اجرایی یا ارجاع خارجی باشند. لوگوی مرکز نمودار زیست‌بوم فایل جداگانه نمی‌خواهد؛ از یکی از دو لوگوی ورود انتخاب می‌شود. در نسخهٔ فعلی صفحه، بارگذاری لوگوی محصول یا favicon از این بخش انجام نمی‌شود.
### تکمیل صفحهٔ «تنظیمات استقرار»
1. **فعال‌سازی:** وضعیت فعال‌بودن، نسخهٔ پروفایل، زمان صدور، شناسهٔ سرور و کد ثبت‌شده را ببینید. کد فعال‌سازی و شناسه از این صفحه قابل ویرایش نیستند.
2. **هویت شرکت:** نام کامل شرکت را همان‌طور که باید در بخش‌های سامانه دیده شود وارد کنید.
3. **لوگوهای استقرار:** برای «لوگوی SVG ورود داشبورد» و «لوگوی SVG ورود ادمین» فایل مربوط را جداگانه انتخاب و بارگذاری کنید. هر فایل، لوگوی فعال همان جایگاه را جایگزین می‌کند.
4. **لوگوی مرکز زیست‌بوم:** مشخص کنید در مرکز نمودار زیست‌بوم، لوگوی ورود داشبورد نمایش داده شود یا لوگوی ورود ادمین.
5. **واحدهای داشبورد:** با «افزودن واحد» یا دکمهٔ حذف، تعداد واحدها را بین یک تا شش تنظیم کنید. الگوی چیدمان مناسب را انتخاب کنید؛ نام هر واحد/شرکت مرتبط را وارد کنید و جایگاه‌ها را با کشیدن یا فهرست «انتقال به جایگاه» مرتب کنید. در صورت نیاز، تصویر هر واحد را با «جایگزینی تصویر» بارگذاری کنید یا با «پیش‌فرض» به تصویر اولیه برگردانید.
6. **اطلاعات و نمودارها:** عنوان سری کاهش هزینه را وارد کنید، شاخص‌های نمایشی مشترک واحدها (افزایش درآمد، کاهش هزینه، افزایش ظرفیت) را انتخاب کنید و دربارهٔ نمایش سری درآمد در نمودار مقایسه‌ای تصمیم بگیرید.
7. در پایان، **«ذخیره تنظیمات»** را بزنید. پس از بارگذاری تصویر اختصاصی واحد، این ذخیره‌کردن برای نهایی‌شدن انتخاب آن ضروری است. صفحه‌های گزارش و مدیریت را دوباره بارگذاری کنید و نام‌ها، لوگوها، تعداد واحدها و ترتیب آن‌ها را ببینید.
اگر ساخت مدیر ناموفق بود، مرحلهٔ اعلام‌شده در خطای ابزار را بخوانید. برای خطای `Identity validation failed`، کد خطای سیاست رمز یا نام کاربری را اصلاح و فرمان را دوباره اجرا کنید. اگر نشست PowerShell عوض شده است، ابتدا فرمان `migrate-target.ps1` را با `-ConfigureOnly` در همان نشست اجرا کنید و سپس ساخت مدیر را تکرار کنید. اگر خطا در مرحلهٔ `create roles` یا `assign administrator role` رخ داد، مجوز حساب migration را روی دیتابیس مقصد بررسی کنید؛ حساب API را برای این فرمان به کار نبرید.

View File

@ -143,11 +143,59 @@
‫رمز مدیر باید حداقل ‪ ۱۲‬نویسه‪ ،‬حرف بزرگ‪ ،‬حرف کوچک‪ ،‬رقم و نویسٔه ویژه داشته باشد‪ .‬نام کاربری خروجی را ثبت‬
‫کنید و رمز را جداگانه و امن تحویل دهید‪ .‬حساب مدیر با رمز پی ‌ شفرض وجود ندارد‪.‬‬
‫پس از فعا ‌لسازی و ورود مدیر‪ ،‬صفحٔه تنظیمات استقرار را مستقیم با نشانی مانند‬
‫‪ https://app.example.com/admin/deployment-settings‬باز کنید‪ .‬این صفحه در منوی پنل نمایش داده نم ‌یشود‪.‬‬
‫پس از فعا ‌لسازی و اولین ورود مدیر‪ ،‬اگر تنظیمات شرکت هنوز کامل نشده باشد‪ ،‬صفحٔه «تنظیمات استقرار»‬
‫ب ‌هصورت خودکار نمایش داده م ‌یشود‪ .‬برای بازکردن آن در دفعات بعد‪ ،‬نشانی‬
‫در بخش واحدهای داشبورد نام واحدها و چیدمان را ثبت کنید و دکمٔه ذخیره تنظیمات را بزنید‪ .‬صفحٔه ورود کد‬
‫فعا ‌لسازی فقط کد را دریافت م ‌یکند؛ تنظیمات واحدها در صفحٔه جداگانه انجام م ‌یشود‪.‬‬
‫‪ https://app.example.com/admin/deployment-settings‬را دستی در نوار آدرس مرورگر وارد کنید؛ این صفحه در‬
‫منوی پنل نمایش داده نم ‌یشود و فقط حساب مدیر به آن دسترسی دارد‪ .‬صفحٔه ورود کد فعا ‌لسازی فقط کد را‬
‫دریافت می‌کند؛ مشخصات شرکت و واحدها در صفحٔه جداگانٔه تنظیمات استقرار ثبت م ‌یشوند‪.‬‬
‫فای ‌لهای لازم برای راه‌اندازی شرکت جدید‬
‫پیش از ورود به صفحٔه تنظیمات استقرار‪ ،‬این فای ‌لها و اطلاعات را از شرکت دریافت کنید‪:‬‬
‫لوگوی ورود داشبورد‪ :‬فایل ‪ SVG‬مخصوص صفحٔه ورود بخش گزار ‌ شها‪ ،‬حداکثر ‪ ۲‬مگابایت‪.‬‬
‫لوگوی ورود ادمین‪ :‬فایل ‪ SVG‬مخصوص صفحٔه ورود پنل مدیریت‪ ،‬حداکثر ‪ ۲‬مگابایت‪ .‬اگر قرار است هر دو‬
‫صفحه یک نشان داشته باشند‪ ،‬همان فایل ‪ SVG‬را برای هر دو جایگاه انتخاب کنید‪.‬‬
‫تصویر هر واحد یا شرکت مرتبط در داشبورد‪ ،‬در صورت نیاز‪ :‬برای هر جایگاه یک فایل ‪PNG، GIF، WebP‬‬
‫یا ‪ ،SVG‬حداکثر ‪ ۸‬مگابایت‪ .‬اگر تصویر اختصاصی ندارید‪ ،‬تصویر پی ‌ شفرض همان جایگاه باقی م ‌یماند‪ .‬برای ‪،PNG‬‬
‫عرض و ارتفاع نباید از ‪ ۴۰۹۶‬پیکسل بیشتر باشد‪.‬‬
‫نام رسمی شرکت و فهرست واحدها‪ :‬نامی که باید در سامانه نمایش داده شود‪ ،‬نام هر واحد یا شرکت‬
‫مرتبط‪ ،‬تعداد واحدها (یک تا شش)‪ ،‬و ترتیب دلخواه نمایش آ ‌نها‪.‬‬
‫فایل‌های ‪ SVG‬باید معتبر و بدون کد اجرایی یا ارجاع خارجی باشند‪ .‬لوگوی مرکز نمودار زیس ‌تبوم فایل جداگانه‬
‫نم ‌یخواهد؛ از یکی از دو لوگوی ورود انتخاب م ‌یشود‪ .‬در نسخٔه فعلی صفحه‪ ،‬بارگذاری لوگوی محصول یا ‪ favicon‬از‬
‫این بخش انجام نم ‌یشود‪.‬‬
‫تکمیل صفحٔه «تنظیمات استقرار»‬
‫‪ .1‬فعال‌سازی‪ :‬وضعیت فعا ‌لبودن‪ ،‬نسخٔه پروفایل‪ ،‬زمان صدور‪ ،‬شناسٔه سرور و کد ثب ‌تشده را ببینید‪ .‬کد‬
‫فعا ‌لسازی و شناسه از این صفحه قابل ویرایش نیستند‪.‬‬
‫‪ .2‬هویت شرکت‪ :‬نام کامل شرکت را هما ‌نطور که باید در بخ ‌ شهای سامانه دیده شود وارد کنید‪.‬‬
‫‪ .3‬لوگوهای استقرار‪ :‬برای «لوگوی ‪ SVG‬ورود داشبورد» و «لوگوی ‪ SVG‬ورود ادمین» فایل مربوط را جداگانه‬
‫انتخاب و بارگذاری کنید‪ .‬هر فایل‪ ،‬لوگوی فعال همان جایگاه را جایگزین م ‌یکند‪.‬‬
‫‪ .4‬لوگوی مرکز زیست‌بوم‪ :‬مشخص کنید در مرکز نمودار زیس ‌تبوم‪ ،‬لوگوی ورود داشبورد نمایش داده شود یا‬
‫لوگوی ورود ادمین‪.‬‬
‫‪ .5‬واحدهای داشبورد‪ :‬با «افزودن واحد» یا دکمٔه حذف‪ ،‬تعداد واحدها را بین یک تا شش تنظیم کنید‪ .‬الگوی‬
‫چیدمان مناسب را انتخاب کنید؛ نام هر واحد‪/‬شرکت مرتبط را وارد کنید و جایگا ‌هها را با کشیدن یا فهرست‬
‫«انتقال به جایگاه» مرتب کنید‪ .‬در صورت نیاز‪ ،‬تصویر هر واحد را با «جایگزینی تصویر» بارگذاری کنید یا با‬
‫«پیش‌فرض» به تصویر اولیه برگردانید‪.‬‬
‫‪ .6‬اطلاعات و نمودارها‪ :‬عنوان سری کاهش هزینه را وارد کنید‪ ،‬شاخ ‌ صهای نمایشی مشترک واحدها‬
‫(افزایش درآمد‪ ،‬کاهش هزینه‪ ،‬افزایش ظرفیت) را انتخاب کنید و دربارٔه نمایش سری درآمد در نمودار‬
‫مقایس ‌های تصمیم بگیرید‪.‬‬
‫‪ .7‬در پایان‪« ،‬ذخیره تنظیمات» را بزنید‪ .‬پس از بارگذاری تصویر اختصاصی واحد‪ ،‬این ذخیر ‌هکردن برای‬
‫نهای ‌یشدن انتخاب آن ضروری است‪ .‬صفح ‌ههای گزارش و مدیریت را دوباره بارگذاری کنید و نام‌ها‪ ،‬لوگوها‪،‬‬
‫تعداد واحدها و ترتیب آ ‌نها را ببینید‪.‬‬
‫اگر ساخت مدیر ناموفق بود‪ ،‬مرحلٔه اعلام‌شده در خطای ابزار را بخوانید‪ .‬برای خطای ‪،Identity validation failed‬‬
‫کد خطای سیاست رمز یا نام کاربری را اصلاح و فرمان را دوباره اجرا کنید‪ .‬اگر نشست ‪ PowerShell‬عوض شده‬

10
deployment/UPDATE.md Normal file
View File

@ -0,0 +1,10 @@
# راهنمای سادهٔ به‌روزرسانی سامانه
این بسته فایل‌های تغییرکردهٔ برنامه و چهار DLL اصلی لازم برای بررسی یکپارچگی را در پوشه‌های `backend`، `frontend` و `tools` دارد. نام نسخهٔ قبلی در فایل `VERSION.txt` نوشته شده است؛ پیش از نصب، آن را با نسخهٔ نصب‌شده تطبیق دهید.
1. پیش از شروع، از پایگاه داده و کل پوشهٔ نصب سامانه نسخهٔ پشتیبان بگیرید. از سالم بودن نسخهٔ پشتیبان مطمئن شوید.
2. در IIS، سایت‌های فرانت و API و App Pool مربوط به API را متوقف کنید.
3. فایل ZIP به‌روزرسانی را استخراج کنید. محتوای هر یک از پوشه‌های موجود `backend`، `frontend` و `tools` را روی پوشهٔ هم‌نام در محل نصب کپی کنید. گزینهٔ جایگزینی فایل‌های هم‌نام را تأیید کنید. پوشه‌های مقصد را پاک نکنید و از گزینهٔ «همگام‌سازی با حذف فایل‌های اضافی» استفاده نکنید.
4. فایل‌های `appsettings.json`، `appsettings.Production.json`، `frontend/config/runtime-config.js` و کل پوشهٔ `backend/data` را نگه دارید. این فایل‌ها در بستهٔ به‌روزرسانی نیستند و تنظیمات و داده‌های محیط نصب را نگه می‌دارند.
5. اگر نسخهٔ جدید به تغییر ساختار دیتابیس نیاز دارد، اسکریپت `migrate-target.ps1` را از بستهٔ کامل همان نسخه طبق راهنمای نصب اجرا کنید. سپس سایت‌ها و App Pool را در IIS روشن کنید.
6. آدرس `/health` مربوط به API، صفحهٔ ورود، و یک بخش اصلی سامانه را بررسی کنید. اگر به‌روزرسانی موفق نبود، فایل‌ها و دیتابیس را از نسخهٔ پشتیبان برگردانید.

26
deployment/UPDATE.pdf Normal file
View File

@ -0,0 +1,26 @@
‫راهنمای سادٔه ب ‌هروزرسانی سامانه‬
‫این بسته فایل‌های تغییرکردٔه برنامه و چهار ‪ DLL‬اصلی لازم برای بررسی یکپارچگی را در پوشه‌های ‪،backend‬‬
‫‪ frontend‬و ‪ tools‬دارد‪ .‬نام نسخٔه قبلی در فایل ‪ VERSION.txt‬نوشته شده است؛ پیش از نصب‪ ،‬آن را با نسخٔه‬
‫نص ‌بشده تطبیق دهید‪.‬‬
‫‪ .1‬پیش از شروع‪ ،‬از پایگاه داده و کل پوشٔه نصب سامانه نسخٔه پشتیبان بگیرید‪ .‬از سالم بودن نسخٔه پشتیبان‬
‫مطمئن شوید‪.‬‬
‫‪ .2‬در ‪ ،IIS‬سایت‌های فرانت و ‪ API‬و ‪ App Pool‬مربوط به ‪ API‬را متوقف کنید‪.‬‬
‫‪ .3‬فایل ‪ ZIP‬ب ‌هروزرسانی را استخراج کنید‪ .‬محتوای هر یک از پوش ‌ههای موجود ‪ frontend ،backend‬و ‪ tools‬را‬
‫روی پوشٔه ه ‌منام در محل نصب کپی کنید‪ .‬گزینٔه جایگزینی فایل‌های ه ‌منام را تأیید کنید‪ .‬پوشه‌های مقصد را‬
‫پاک نکنید و از گزینٔه «همگا ‌مسازی با حذف فای ‌لهای اضافی» استفاده نکنید‪.‬‬
‫‪ .4‬فایل‌های ‪ frontend/config/runtime-config.js ،appsettings.Production.json ،appsettings.json‬و کل‬
‫پوشٔه ‪ backend/data‬را نگه دارید‪ .‬این فای ‌لها در بستٔه به‌روزرسانی نیستند و تنظیمات و داد ‌ههای محیط نصب‬
‫را نگه می‌دارند‪.‬‬
‫‪ .5‬اگر نسخٔه جدید به تغییر ساختار دیتابیس نیاز دارد‪ ،‬اسکریپت ‪ migrate-target.ps1‬را از بستٔه کامل همان‬
‫نسخه طبق راهنمای نصب اجرا کنید‪ .‬سپس سایت‌ها و ‪ App Pool‬را در ‪ IIS‬روشن کنید‪.‬‬
‫‪ .6‬آدرس ‪ /health‬مربوط به ‪ ،API‬صفحٔه ورود‪ ،‬و یک بخش اصلی سامانه را بررسی کنید‪ .‬اگر ب ‌هروزرسانی موفق‬
‫نبود‪ ،‬فای ‌لها و دیتابیس را از نسخٔه پشتیبان برگردانید‪.‬‬

View File

@ -4,6 +4,7 @@ param(
[string]$OutputRoot = (Join-Path $PSScriptRoot "..\artifacts"),
[string]$SigningPrivateKey = $env:INOGEN_RELEASE_SIGNING_KEY,
[string]$ApiBaseUrl,
[string]$PreviousPackage,
[switch]$SkipNpmInstall,
[switch]$IncludeInternalTransfer
)
@ -17,7 +18,9 @@ if ($IncludeInternalTransfer) { $releaseName += "-Internal" }
$releasePath = Join-Path $outputRootPath $releaseName
$backendOutput = Join-Path $releasePath "backend"
$frontendOutput = Join-Path $releasePath "frontend"
$setupOutput = Join-Path $releasePath "tools\Inogen.Setup"
$transferOutput = Join-Path $releasePath "tools\Inogen.DataTransfer"
$updatePath = "$releasePath-Update"
if ([string]::IsNullOrWhiteSpace($SigningPrivateKey)) {
throw "Release signing key is not configured. Generate one once with: dotnet run --project '<backend>\tools\Inogen.ReleaseProtector' -- generate-key '<secure-directory>\inogen-release-private.pem'. Then set INOGEN_RELEASE_SIGNING_KEY to that absolute file path. Keep the private key outside the package and source tree."
@ -41,7 +44,7 @@ if (-not [Uri]::TryCreate($ApiBaseUrl.Trim(), [UriKind]::Absolute, [ref]$apiUri)
throw "ApiBaseUrl must be an absolute HTTPS URL ending in /api/v1 without query, fragment, or credentials."
}
New-Item -ItemType Directory -Force -Path $backendOutput, $frontendOutput | Out-Null
New-Item -ItemType Directory -Force -Path $backendOutput, $frontendOutput, $setupOutput | Out-Null
if ($IncludeInternalTransfer) { New-Item -ItemType Directory -Force -Path $transferOutput | Out-Null }
function Assert-NativeCommandSucceeded([string]$operation) {
@ -62,16 +65,20 @@ function Protect-Assemblies([string]$targetPath, [string[]]$moduleNames) {
" <Module file=`"$modulePath`">$([Environment]::NewLine)$($rules -join [Environment]::NewLine)$([Environment]::NewLine) </Module>"
}
$configPath = Join-Path $targetPath "obfuscar.xml"
$originalHashes = @{}
foreach ($module in $moduleNames) {
$originalHashes[$module] = (Get-FileHash -LiteralPath (Join-Path $targetPath $module) -Algorithm SHA256).Hash
}
$config = @(
"<?xml version=`"1.0`" encoding=`"utf-8`"?>",
"<Obfuscator>",
" <Var name=`"InPath`" value=`"$([System.Security.SecurityElement]::Escape($targetPath))`" />",
" <Var name=`"OutPath`" value=`"$([System.Security.SecurityElement]::Escape($obfuscatedPath))`" />",
" <Var name=`"KeepPublicApi`" value=`"true`" />",
" <Var name=`"HidePrivateApi`" value=`"true`" />",
" <Var name=`"HidePrivateApi`" value=`"false`" />",
" <Var name=`"HideStrings`" value=`"true`" />",
" <Var name=`"ReuseNames`" value=`"false`" />",
" <Var name=`"UseUnicodeNames`" value=`"true`" />",
" <Var name=`"UseUnicodeNames`" value=`"false`" />",
" <Var name=`"SkipGenerated`" value=`"true`" />",
($moduleElements -join [Environment]::NewLine),
"</Obfuscator>"
@ -84,7 +91,14 @@ function Protect-Assemblies([string]$targetPath, [string[]]$moduleNames) {
}
finally { Pop-Location }
foreach ($module in $moduleNames) {
Copy-Item -LiteralPath (Join-Path $obfuscatedPath $module) -Destination (Join-Path $targetPath $module) -Force
$protectedModule = Join-Path $obfuscatedPath $module
if (-not (Test-Path -LiteralPath $protectedModule -PathType Leaf)) {
throw "Obfuscator did not produce $module."
}
if ((Get-FileHash -LiteralPath $protectedModule -Algorithm SHA256).Hash -eq $originalHashes[$module]) {
throw "Obfuscator left $module unchanged."
}
Copy-Item -LiteralPath $protectedModule -Destination (Join-Path $targetPath $module) -Force
}
Remove-Item -LiteralPath $obfuscatedPath -Recurse -Force
Remove-Item -LiteralPath $configPath -Force
@ -107,6 +121,10 @@ try {
npm run build
Assert-NativeCommandSucceeded "Frontend build"
Copy-Item -Path (Join-Path $frontendSource "build\client\*") -Destination $frontendOutput -Recurse -Force
$viteManifestDirectory = Join-Path $frontendOutput '.vite'
if (Test-Path -LiteralPath $viteManifestDirectory) {
Remove-Item -LiteralPath $viteManifestDirectory -Recurse -Force
}
$runtimeConfigPath = Join-Path $frontendOutput "config\runtime-config.js"
$apiBaseUrlJson = ConvertTo-Json -InputObject $apiUri.AbsoluteUri.TrimEnd('/') -Compress
[IO.File]::WriteAllText($runtimeConfigPath,
@ -120,6 +138,9 @@ dotnet publish (Join-Path $backendSourcePath "src\Inogen.Api\Inogen.Api.csproj")
Assert-NativeCommandSucceeded "Backend publish"
$developmentSettings = Join-Path $backendOutput "appsettings.Development.json"
if (Test-Path -LiteralPath $developmentSettings) { Remove-Item -LiteralPath $developmentSettings -Force }
dotnet publish (Join-Path $backendSourcePath "tools\Inogen.Setup\Inogen.Setup.csproj") `
--configuration Release --output $setupOutput --no-self-contained
Assert-NativeCommandSucceeded "Customer setup tool publish"
if ($IncludeInternalTransfer) {
dotnet publish (Join-Path $backendSourcePath "tools\Inogen.DataTransfer\Inogen.DataTransfer.csproj") `
--configuration Release --output $transferOutput --no-self-contained
@ -131,10 +152,16 @@ try {
Assert-NativeCommandSucceeded "Obfuscator restore"
}
finally { Pop-Location }
$backendModules = @()
$backendModules = @("Inogen.Api.dll", "Inogen.Application.dll", "Inogen.Domain.dll", "Inogen.Infrastructure.dll")
$integrityModules = @("Inogen.Api.dll", "Inogen.Application.dll", "Inogen.Domain.dll", "Inogen.Infrastructure.dll")
if ($backendModules.Count -gt 0) { Protect-Assemblies $backendOutput $backendModules }
$publishedPaths = @($backendOutput)
Protect-Assemblies $backendOutput $backendModules
if (-not $IncludeInternalTransfer) {
foreach ($module in @("Inogen.Application.dll", "Inogen.Domain.dll", "Inogen.Infrastructure.dll")) {
Copy-Item -LiteralPath (Join-Path $backendOutput $module) -Destination (Join-Path $setupOutput $module) -Force
}
Protect-Assemblies $setupOutput @('Inogen.Setup.dll')
}
$publishedPaths = @($backendOutput, $setupOutput)
if ($IncludeInternalTransfer) { $publishedPaths += $transferOutput }
Get-ChildItem -LiteralPath $publishedPaths -Filter "*.pdb" -File | Remove-Item -Force
Get-ChildItem -LiteralPath $publishedPaths -Filter "Mapping.txt" -File | Remove-Item -Force
@ -162,6 +189,42 @@ foreach ($asset in @("product-logo.svg", "abniro.png", "besparan.png", "khwarazm
Copy-Item -LiteralPath (Join-Path $frontendSource "public\$asset") -Destination $assetPath -Force
}
if (-not $IncludeInternalTransfer) {
$previousRelease = $null
if (-not [string]::IsNullOrWhiteSpace($PreviousPackage)) {
$previousRelease = Get-Item -LiteralPath $PreviousPackage -ErrorAction Stop
if (-not $previousRelease.PSIsContainer -or
-not (Test-Path -LiteralPath (Join-Path $previousRelease.FullName 'backend\Inogen.Api.dll')) -or
-not (Test-Path -LiteralPath (Join-Path $previousRelease.FullName 'frontend\index.html'))) {
throw 'PreviousPackage must be an extracted customer release folder with backend and frontend.'
}
}
New-Item -ItemType Directory -Force -Path $updatePath | Out-Null
foreach ($section in @('backend', 'frontend', 'tools')) {
$sourceRoot = Join-Path $releasePath $section
Get-ChildItem -LiteralPath $sourceRoot -Recurse -File | ForEach-Object {
$relative = $_.FullName.Substring($sourceRoot.Length).TrimStart('\')
if ($section -eq 'backend' -and ($relative -match '^data\\' -or $relative -match '^appsettings(\..+)?\.json$')) { return }
if ($section -eq 'frontend' -and $relative -eq 'config\runtime-config.js') { return }
$oldFile = if ($previousRelease) { Join-Path (Join-Path $previousRelease.FullName $section) $relative } else { $null }
$requiredIntegrityModule = $section -eq 'backend' -and $relative -in $integrityModules
if (-not $requiredIntegrityModule -and $oldFile -and (Test-Path -LiteralPath $oldFile) -and
(Get-FileHash -LiteralPath $oldFile -Algorithm SHA256).Hash -eq (Get-FileHash -LiteralPath $_.FullName -Algorithm SHA256).Hash) { return }
$destination = Join-Path (Join-Path $updatePath $section) $relative
New-Item -ItemType Directory -Force -Path (Split-Path $destination -Parent) | Out-Null
Copy-Item -LiteralPath $_.FullName -Destination $destination -Force
}
}
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'UPDATE.pdf') -Destination $updatePath -Force
[IO.File]::WriteAllText((Join-Path $updatePath 'VERSION.txt'),
"Previous package: $(if ($previousRelease) { $previousRelease.Name } else { 'none (full application files)' })`r`nNew package: $releaseName`r`n",
[Text.UTF8Encoding]::new($false))
$updateZip = "$updatePath.zip"
Compress-Archive -LiteralPath $updatePath -DestinationPath $updateZip -CompressionLevel Optimal
Write-Host "Update folder: $updatePath"
Write-Host "Update archive: $updateZip"
}
$zipPath = "$releasePath.zip"
Compress-Archive -LiteralPath $releasePath -DestinationPath $zipPath -CompressionLevel Optimal
Write-Host "Release folder: $releasePath"

View File

@ -47,3 +47,4 @@ def render(source: str, destination: str) -> None:
if __name__ == "__main__":
render("INSTALL.md", "INSTALL.pdf")
render("INSTALL-INTERNAL.md", "INSTALL-INTERNAL.pdf")
render("UPDATE.md", "UPDATE.pdf")

View File

@ -45,7 +45,7 @@
<add name="Referrer-Policy" value="strict-origin-when-cross-origin" />
<add name="Permissions-Policy" value="camera=(), microphone=(), geolocation=()" />
<add name="X-Frame-Options" value="SAMEORIGIN" />
<add name="Strict-Transport-Security" value="max-age=2592000" />
<add name="Strict-Transport-Security" value="max-age=31536000" />
</customHeaders>
</httpProtocol>
<staticContent>