@opengis/surveyor 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +188 -3
  3. package/dist/chunks/AppIcon-CIR6y5uE.js +85 -0
  4. package/dist/chunks/AppealDetailField-CI-1qhs3.js +58 -0
  5. package/dist/chunks/AppealStatusBadge-CSXnfarR.js +132 -0
  6. package/dist/chunks/AppealStatusBadge-DYBe9hqP.js +171 -0
  7. package/dist/chunks/ApplicationHistorySection-C0wwhwA4.js +769 -0
  8. package/dist/chunks/BaseModal-C7PVYz0m.js +85 -0
  9. package/dist/chunks/FormFilePicker-C3XQw50i.js +76 -0
  10. package/dist/chunks/MapLayerMenu-DjYCxEc3.js +145 -0
  11. package/dist/chunks/RegistryForm-CEUqFmsF.js +99 -0
  12. package/dist/chunks/RegistryFormModal-DfY4z_7r.js +85 -0
  13. package/dist/chunks/RegistryToolbar-BV4mYVAc.js +452 -0
  14. package/dist/chunks/UserAccessBadge-D8JfgGfN.js +44 -0
  15. package/dist/chunks/UserTypeBadge-YIwwoCho.js +188 -0
  16. package/dist/chunks/VerifiedBadge-Bba8WnuB.js +34 -0
  17. package/dist/chunks/_plugin-vue_export-helper-B3ysoDQm.js +8 -0
  18. package/dist/chunks/account-types-Br7gx_D_.js +35 -0
  19. package/dist/chunks/account_types-DLL1w122.js +25 -0
  20. package/dist/chunks/appealMapLayers-CQMK3rrz.js +115 -0
  21. package/dist/chunks/application_status-BhNGiY2I.js +45 -0
  22. package/dist/chunks/applications-BB9JRcgl.js +132 -0
  23. package/dist/chunks/buildSchema-CccjX9TJ.js +37 -0
  24. package/dist/chunks/card-B-ftozcq.js +739 -0
  25. package/dist/chunks/card-BctFHFZe.js +538 -0
  26. package/dist/chunks/card-CKD1N0QD.js +330 -0
  27. package/dist/chunks/card-CiNZxAd5.js +297 -0
  28. package/dist/chunks/card-DUtDfwMk.js +607 -0
  29. package/dist/chunks/card-fL26_Gvc.js +1189 -0
  30. package/dist/chunks/certificates-BSd1i0un.js +424 -0
  31. package/dist/chunks/create-DxMC_IL1.js +1033 -0
  32. package/dist/chunks/filterQuery-CvfZrkTC.js +99 -0
  33. package/dist/chunks/form-Bh6i5n1U.js +315 -0
  34. package/dist/chunks/form-DDjELqZ9.js +89 -0
  35. package/dist/chunks/geometry-DyhIVRcw.js +67 -0
  36. package/dist/chunks/map-Z57iMvFb.js +2763 -0
  37. package/dist/chunks/map-layers-DnmkOEld.js +400 -0
  38. package/dist/chunks/mapLayersApi-CWoQ2be-.js +251 -0
  39. package/dist/chunks/organizations-BO1_JETm.js +476 -0
  40. package/dist/chunks/organizations-BbYipLwk.js +14 -0
  41. package/dist/chunks/profile-ByahbF4B.js +164 -0
  42. package/dist/chunks/profile-Dwwn_4Pr.js +243 -0
  43. package/dist/chunks/requests-BCin936Z.js +232 -0
  44. package/dist/chunks/requests-CFv5wwAN.js +530 -0
  45. package/dist/chunks/resendSurveyorRegistration-BHTTVIw1.js +27 -0
  46. package/dist/chunks/resources-2e8RFqWR.js +129 -0
  47. package/dist/chunks/rolldown-runtime-Dy4uBu1J.js +11 -0
  48. package/dist/chunks/surveyorAccount-C7UiiIYg.js +78 -0
  49. package/dist/chunks/users-DtTYsgMb.js +291 -0
  50. package/dist/chunks/work_types-Hwme-FEX.js +34 -0
  51. package/dist/index.css +3 -0
  52. package/dist/index.js +336 -0
  53. package/migrations/20260924120000_surveyor_schema.sql +450 -0
  54. package/migrations/20261008170000_address_lookup.sql +20 -0
  55. package/migrations/20261016120000_map_layers.sql +156 -0
  56. package/migrations/20261016150000_password_reset.sql +15 -0
  57. package/migrations/20261016170000_address_lookup_format.sql +37 -0
  58. package/migrations/20261016180000_settlement_lookup.sql +16 -0
  59. package/migrations/20261019170000_actor_lookup.sql +15 -0
  60. package/package.json +86 -6
  61. package/plugin.d.ts +15 -0
  62. package/plugin.js +8 -0
  63. package/server/app.ts +51 -0
  64. package/server/dictionaries/index.ts +17 -0
  65. package/server/dictionaries/surveyor/account_types.ts +12 -0
  66. package/server/dictionaries/surveyor/application_status.ts +16 -0
  67. package/server/dictionaries/surveyor/map_layer_components.ts +11 -0
  68. package/server/dictionaries/surveyor/map_layer_groups.ts +10 -0
  69. package/server/dictionaries/surveyor/map_layer_types.ts +11 -0
  70. package/server/dictionaries/surveyor/work_types.ts +15 -0
  71. package/server/dictionaries/surveyor/yes_no.ts +11 -0
  72. package/server/fastify.d.ts +12 -0
  73. package/server/index.ts +23 -0
  74. package/server/modules/surveyor/route.ts +410 -0
  75. package/server/modules/surveyor/schema.ts +439 -0
  76. package/server/modules/surveyor/services/applicationTile.ts +53 -0
  77. package/server/modules/surveyor/services/cancelApplication.ts +74 -0
  78. package/server/modules/surveyor/services/changeSurveyorPassword.ts +52 -0
  79. package/server/modules/surveyor/services/changeSurveyorPasswordByAdmin.ts +41 -0
  80. package/server/modules/surveyor/services/completeApplication.ts +46 -0
  81. package/server/modules/surveyor/services/completeSurveyorRegistration.ts +48 -0
  82. package/server/modules/surveyor/services/createApplication.ts +169 -0
  83. package/server/modules/surveyor/services/geometryExport.ts +34 -0
  84. package/server/modules/surveyor/services/geometryImport.ts +66 -0
  85. package/server/modules/surveyor/services/getSurveyorUser.ts +56 -0
  86. package/server/modules/surveyor/services/identifyApplications.ts +82 -0
  87. package/server/modules/surveyor/services/issueSourceData.ts +55 -0
  88. package/server/modules/surveyor/services/loginSurveyor.ts +67 -0
  89. package/server/modules/surveyor/services/mapLayers.ts +61 -0
  90. package/server/modules/surveyor/services/rasterExport.ts +15 -0
  91. package/server/modules/surveyor/services/registerSurveyor.ts +161 -0
  92. package/server/modules/surveyor/services/requestPasswordReset.ts +49 -0
  93. package/server/modules/surveyor/services/resendRegistration.ts +42 -0
  94. package/server/modules/surveyor/services/resetSurveyorPassword.ts +53 -0
  95. package/server/modules/surveyor/services/searchApplications.ts +63 -0
  96. package/server/modules/surveyor/services/submitSurvey.ts +70 -0
  97. package/server/modules/surveyor/services/updateSurveyorAccountStatus.ts +52 -0
  98. package/server/modules/surveyor/services/updateSurveyorStatus.ts +53 -0
  99. package/server/modules/surveyor/services/vectorExport.ts +86 -0
  100. package/server/modules/surveyor/services/verifyApplication.ts +59 -0
  101. package/server/modules/surveyor/utils/accessibleApplication.ts +37 -0
  102. package/server/modules/surveyor/utils/application.ts +68 -0
  103. package/server/modules/surveyor/utils/export.ts +39 -0
  104. package/server/modules/surveyor/utils/firstBoundary.ts +48 -0
  105. package/server/modules/surveyor/utils/mail.ts +161 -0
  106. package/server/modules/surveyor/utils/permissions.ts +29 -0
  107. package/server/modules/surveyor/utils/registration.ts +33 -0
  108. package/server/modules/surveyor/utils/shared.ts +305 -0
  109. package/server/modules/surveyor/utils/templates/ds.surveyor_admin_password.pt.hbs +79 -0
  110. package/server/modules/surveyor/utils/templates/ds.surveyor_password_reset.pt.hbs +79 -0
  111. package/server/modules/surveyor/utils/templates/ds.surveyor_registration.pt.hbs +80 -0
  112. package/server/modules/surveyor/utils/templates/ds.surveyor_send_mail.pt.hbs +79 -0
  113. package/server/modules/surveyor/utils/vectorLayer.ts +41 -0
  114. package/server/plugins/convertVector.ts +74 -0
  115. package/server/plugins/proto/convertVector.proto +21 -0
  116. package/server/plugins/swagger.ts +54 -0
  117. package/server/plugins/vite.dev.ts +52 -0
  118. package/server/plugins/vite.prod.ts +55 -0
  119. package/server/resources/helpers/actor_lookup.ts +5 -0
  120. package/server/resources/helpers/address_lookup.ts +8 -0
  121. package/server/resources/helpers/settlement_lookup.ts +7 -0
  122. package/server/resources/helpers/user_lookup.ts +5 -0
  123. package/server/resources/index.ts +30 -0
  124. package/server/resources/surveyor-admin/application_comments.ts +24 -0
  125. package/server/resources/surveyor-admin/application_status_history.ts +46 -0
  126. package/server/resources/surveyor-admin/applications.ts +125 -0
  127. package/server/resources/surveyor-admin/certificates.ts +87 -0
  128. package/server/resources/surveyor-admin/map_layers.ts +69 -0
  129. package/server/resources/surveyor-admin/organization_surveyors.ts +32 -0
  130. package/server/resources/surveyor-admin/organizations.ts +61 -0
  131. package/server/resources/surveyor-admin/surveyors.ts +71 -0
  132. package/server/resources/surveyor-user/application_status_history.ts +52 -0
  133. package/server/resources/surveyor-user/applications.ts +131 -0
  134. package/server/resources/surveyor-user/certificates.ts +67 -0
  135. package/server/resources/surveyor-user/organizations.ts +40 -0
  136. package/server/resources/surveyor-user/surveyors.ts +69 -0
  137. package/server/suggests/index.ts +17 -0
  138. package/server/tsconfig.json +3 -0
  139. package/surveyor-types.d.ts +30 -0
@@ -0,0 +1,59 @@
1
+ import type { AppContext, User } from "@opengis/fcore";
2
+ import {
3
+ admin,
4
+ applicationUpdateFailed,
5
+ attachedFile,
6
+ audit,
7
+ history,
8
+ type Db,
9
+ } from "../utils/shared.js";
10
+ import type { VerifyInput } from "../utils/application.js";
11
+
12
+ /**
13
+ * Фіксує результат перевірки матеріалів: підтвердження або повернення на доопрацювання.
14
+ * @param params Заявка, результат перевірки, адміністратор і контекст FCore.
15
+ * @returns Новий статус і час підтвердження, якщо матеріали прийнято.
16
+ */
17
+ export async function verifyApplication(
18
+ { id, input, user, ctx }: {
19
+ id: string;
20
+ input: VerifyInput;
21
+ user: User | undefined;
22
+ ctx: AppContext;
23
+ }
24
+ ) {
25
+ const uid = admin(user);
26
+ const file = input.file_path
27
+ ? await attachedFile({ ctx, appId: id, filePath: input.file_path })
28
+ : null;
29
+ const result = await ctx.pg.transaction(async (db: Db) => {
30
+ const updated = await db.query<{ verified_at: Date | null }>(
31
+ `UPDATE surveyor.applications
32
+ SET status = $2::text::surveyor.application_status_enum,
33
+ file_corrected_geodetic_survey = $3,
34
+ note_4_file_corrected_geodetic_survey = $4,
35
+ verified_at = CASE WHEN $2::text = 'verified' THEN now() ELSE NULL END,
36
+ verified_by = $5,
37
+ updated_by = $5,
38
+ updated_at = now()
39
+ WHERE app_id = $1 AND status = 'underReview'
40
+ RETURNING verified_at`,
41
+ [id, input.status, file, input.note_4_file_corrected_geodetic_survey ?? null, uid]
42
+ );
43
+ if (!updated.rows[0]) {
44
+ await applicationUpdateFailed({ db, id, status: "underReview" });
45
+ }
46
+ await history({
47
+ db,
48
+ appId: id,
49
+ from: "underReview",
50
+ to: input.status,
51
+ by: uid,
52
+ reason: input.note_4_file_corrected_geodetic_survey,
53
+ file,
54
+ });
55
+ return { id, status: input.status, verified_at: updated.rows[0]!.verified_at };
56
+ });
57
+ await audit({ ctx, action: "verify", appId: id, uid });
58
+ return result;
59
+ }
@@ -0,0 +1,37 @@
1
+ import type { AppContext, User } from "@opengis/fcore";
2
+ import { NotFoundError } from "@opengis/fcore";
3
+ import { actor, canReadApplication, type Application } from "./shared.js";
4
+ import type { GeoJSONGeometry } from "./export.js";
5
+
6
+ type ExportApplication = Application & {
7
+ number: string | null;
8
+ work_type: string;
9
+ area: string;
10
+ geometry: GeoJSONGeometry | null;
11
+ properties: Record<string, unknown>;
12
+ };
13
+
14
+ /**
15
+ * Завантажує геометрію заявки та перевіряє право користувача на її перегляд.
16
+ * @param params Ідентифікатор заявки, користувач і контекст FCore.
17
+ * @returns Дані заявки, необхідні для експорту.
18
+ */
19
+ export async function accessibleApplication(
20
+ { id, user, ctx, srid = 4326 }: { id: string; user: User | undefined; ctx: AppContext; srid?: number }
21
+ ): Promise<ExportApplication> {
22
+ actor(user);
23
+ const result = await ctx.pg.query<ExportApplication>(
24
+ `SELECT app_id, org_id, surveyor_id, status, file_geodetic_survey,
25
+ number, work_type, area, ST_AsGeoJSON(ST_Transform(geom, $2::integer))::json AS geometry,
26
+ jsonb_build_object('app_id', app_id, 'number', number) AS properties
27
+ FROM surveyor.applications AS app
28
+ WHERE app_id = $1`,
29
+ [id, srid]
30
+ );
31
+ const app = result.rows[0];
32
+ if (!app) {
33
+ throw new NotFoundError("Application not found");
34
+ }
35
+ await canReadApplication({ db: ctx.pg, app, user });
36
+ return app;
37
+ }
@@ -0,0 +1,68 @@
1
+ import { BadRequestError } from "@opengis/fcore";
2
+
3
+ export type CreateInput = {
4
+ organization_id: string;
5
+ work_type: string;
6
+ description?: string;
7
+ execution_basis?: string;
8
+ settlement_id: string;
9
+ is_found_address_id: boolean;
10
+ address_id?: string;
11
+ location?: string;
12
+ geom: { type: "Polygon"; coordinates: number[][][] };
13
+ };
14
+
15
+ export type FileInput = { file_path: string; note?: string };
16
+
17
+ export type VerifyInput = {
18
+ status: "verified" | "dataIssued";
19
+ file_path?: string;
20
+ note_4_file_corrected_geodetic_survey?: string;
21
+ };
22
+
23
+ /**
24
+ * Читає додатний ліміт із змінної середовища або бере значення за замовчуванням.
25
+ * @param params Назва змінної середовища та значення за замовчуванням.
26
+ * @returns Налаштований ліміт.
27
+ */
28
+ export function limit({ name, fallback }: { name: string; fallback: number }): number {
29
+ const value = Number(process.env[name] ?? fallback);
30
+ if (!Number.isFinite(value) || value <= 0) {
31
+ throw new Error(`Invalid ${name}`);
32
+ }
33
+ return value;
34
+ }
35
+
36
+ /**
37
+ * Перевіряє структуру, географічні межі координат і замкненість кілець полігона.
38
+ * @param shape Полігон GeoJSON.
39
+ * @returns Серіалізований полігон для запитів PostGIS.
40
+ */
41
+ export function polygon(shape: CreateInput["geom"]): string {
42
+ if (
43
+ shape?.type !== "Polygon" ||
44
+ !Array.isArray(shape.coordinates) ||
45
+ !shape.coordinates.length ||
46
+ shape.coordinates.some(
47
+ (ring) =>
48
+ !Array.isArray(ring) ||
49
+ ring.length < 4 ||
50
+ ring.some(
51
+ (point) => !Array.isArray(point) || point.length < 2 || !point.every(Number.isFinite)
52
+ )
53
+ )
54
+ ) {
55
+ throw new BadRequestError("Invalid polygon geometry");
56
+ }
57
+ for (const ring of shape.coordinates) {
58
+ if (
59
+ ring.some(([longitude, latitude]) => Math.abs(longitude) > 180 || Math.abs(latitude) > 90)
60
+ ) {
61
+ throw new BadRequestError("Polygon coordinates are outside geographic bounds");
62
+ }
63
+ if (ring[0]![0] !== ring[ring.length - 1]![0] || ring[0]![1] !== ring[ring.length - 1]![1]) {
64
+ throw new BadRequestError("Polygon rings must be closed");
65
+ }
66
+ }
67
+ return JSON.stringify(shape);
68
+ }
@@ -0,0 +1,39 @@
1
+ import { BadRequestError } from "@opengis/fcore";
2
+
3
+ export type GeoJSONGeometry =
4
+ | {
5
+ type: "Point" | "MultiPoint" | "LineString" | "MultiLineString" | "Polygon" | "MultiPolygon";
6
+ coordinates: unknown[];
7
+ }
8
+ | { type: "GeometryCollection"; geometries: GeoJSONGeometry[] };
9
+
10
+ export type GeoJSONFeatureCollection = {
11
+ type: "FeatureCollection";
12
+ crs: { type: "name"; properties: { name: string } };
13
+ features: { type: "Feature"; geometry: GeoJSONGeometry; properties: Record<string, unknown> }[];
14
+ };
15
+
16
+ export type ExportOptions = {
17
+ format?: "geoJson" | "geojson";
18
+ srid?: number;
19
+ crs?: string;
20
+ };
21
+
22
+ /** Визначає SRID експорту з числового параметра або назви CRS. */
23
+ export function exportSrid({ format, srid, crs }: ExportOptions): number {
24
+ if (format !== undefined && format !== "geoJson" && format !== "geojson") {
25
+ throw new BadRequestError("Only GeoJSON export is supported");
26
+ }
27
+ if (crs !== undefined && !/^EPSG:[1-9][0-9]*$/.test(crs)) {
28
+ throw new BadRequestError("Invalid export CRS");
29
+ }
30
+ const crsSrid = crs === undefined ? undefined : Number(crs.slice(5));
31
+ const value = srid ?? crsSrid ?? 4326;
32
+ if (!Number.isInteger(value) || value < 1 || value > 2_147_483_647) {
33
+ throw new BadRequestError("Invalid export SRID");
34
+ }
35
+ if (srid !== undefined && crsSrid !== undefined && srid !== crsSrid) {
36
+ throw new BadRequestError("Export SRID and CRS must match");
37
+ }
38
+ return value;
39
+ }
@@ -0,0 +1,48 @@
1
+ import { BadRequestError } from "@opengis/fcore";
2
+ import { polygon, type CreateInput } from "./application.js";
3
+ import type { GeoJSONFeatureCollection } from "./export.js";
4
+
5
+ /** Повертає перший об'єкт із полігонною межею у двовимірному GeoJSON. */
6
+ export function firstBoundary(value: unknown): GeoJSONFeatureCollection {
7
+ const geojson = value as Record<string, any> | null;
8
+ let feature = geojson;
9
+ if (geojson?.type === "FeatureCollection") {
10
+ feature = Array.isArray(geojson.features) ? geojson.features[0] : null;
11
+ }
12
+ if (geojson?.type === "Polygon" || geojson?.type === "MultiPolygon") {
13
+ feature = { type: "Feature", geometry: geojson };
14
+ }
15
+ if (feature?.type !== "Feature" || !feature.geometry) {
16
+ throw new BadRequestError("Файл не містить першого об'єкта з геометрією");
17
+ }
18
+ let geometry = feature.geometry;
19
+ if (geometry.type === "MultiPolygon" && geometry.coordinates?.length === 1) {
20
+ geometry = { type: "Polygon", coordinates: geometry.coordinates[0] };
21
+ }
22
+ if (geometry.type !== "Polygon") {
23
+ throw new BadRequestError(
24
+ `Перший об'єкт файлу має геометрію ${geometry.type ?? "невідомого типу"}. ` +
25
+ "Для межі заявки потрібен Polygon; MultiPolygon допускається лише з одним полігоном."
26
+ );
27
+ }
28
+ polygon(geometry);
29
+ const boundary: CreateInput["geom"] = {
30
+ type: "Polygon",
31
+ coordinates: geometry.coordinates.map((ring: number[][]) => ring.map(([x, y]) => [x!, y!])),
32
+ };
33
+ const properties = feature.properties;
34
+ return {
35
+ type: "FeatureCollection",
36
+ crs: { type: "name", properties: { name: "EPSG:4326" } },
37
+ features: [
38
+ {
39
+ type: "Feature",
40
+ geometry: boundary,
41
+ properties:
42
+ properties && typeof properties === "object" && !Array.isArray(properties)
43
+ ? properties
44
+ : {},
45
+ },
46
+ ],
47
+ };
48
+ }
@@ -0,0 +1,161 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { FCoreError } from "@opengis/fcore";
3
+ import nodemailer from "nodemailer";
4
+
5
+ type MailTemplate =
6
+ | "ds.surveyor_registration.pt"
7
+ | "ds.surveyor_send_mail.pt"
8
+ | "ds.surveyor_admin_password.pt"
9
+ | "ds.surveyor_password_reset.pt";
10
+
11
+ function escapeHtml(value: string): string {
12
+ return value
13
+ .replaceAll("&", "&amp;")
14
+ .replaceAll("<", "&lt;")
15
+ .replaceAll(">", "&gt;")
16
+ .replaceAll('"', "&quot;")
17
+ .replaceAll("'", "&#39;");
18
+ }
19
+
20
+ function mailSetting(name: string): string {
21
+ const value = process.env[`mail.${name}`];
22
+ if (!value?.trim()) {
23
+ throw new FCoreError("MAIL_NOT_CONFIGURED", `Missing mail.${name}`, 500);
24
+ }
25
+ return value;
26
+ }
27
+
28
+ function mailDisabled(): boolean {
29
+ return process.env["mail.disable"]?.trim().toLowerCase() === "true";
30
+ }
31
+
32
+ function activationLink(token: string): URL {
33
+ return tokenLink("activation_url", token);
34
+ }
35
+
36
+ function tokenLink(setting: "activation_url" | "password_reset_url", token: string): URL {
37
+ const template = mailSetting(setting).trim();
38
+ try {
39
+ if (!template.includes("{token}")) {
40
+ throw new Error();
41
+ }
42
+ const url = new URL(template.replaceAll("{token}", encodeURIComponent(token)));
43
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
44
+ throw new Error();
45
+ }
46
+ return url;
47
+ } catch {
48
+ throw new FCoreError(
49
+ "MAIL_NOT_CONFIGURED",
50
+ `mail.${setting} must be an HTTP(S) URL containing {token}`,
51
+ 500
52
+ );
53
+ }
54
+ }
55
+
56
+ async function sendEmail(
57
+ { email, subject, template, data }: {
58
+ email: string;
59
+ subject: string;
60
+ template: MailTemplate;
61
+ data: Record<string, string>;
62
+ }
63
+ ): Promise<boolean> {
64
+ let html: string;
65
+ try {
66
+ const source = await readFile(new URL(`./templates/${template}.hbs`, import.meta.url), "utf8");
67
+ html = source.replace(/\{\{([^{}]+)\}\}/g, (_, key: string) => {
68
+ const name = key.trim();
69
+ if (!Object.hasOwn(data, name)) {
70
+ throw new Error(`Missing template variable: ${name}`);
71
+ }
72
+ return escapeHtml(data[name]);
73
+ });
74
+ } catch {
75
+ throw new FCoreError("MAIL_TEMPLATE_ERROR", "Failed to render email template", 500);
76
+ }
77
+
78
+ const from = mailSetting("from");
79
+ const transport = nodemailer.createTransport({
80
+ service: mailSetting("service").trim(),
81
+ auth: { user: mailSetting("auth.user"), pass: mailSetting("auth.pass") },
82
+ requireTLS: true,
83
+ connectionTimeout: 10_000,
84
+ greetingTimeout: 10_000,
85
+ socketTimeout: 20_000,
86
+ logger: false,
87
+ debug: false,
88
+ });
89
+
90
+ try {
91
+ const result = await transport.sendMail({ from, to: email, subject, html });
92
+ if (!result.accepted.length) {
93
+ throw new Error();
94
+ }
95
+ return true;
96
+ } catch {
97
+ throw new FCoreError("MAIL_SEND_FAILED", "Failed to send email", 502);
98
+ } finally {
99
+ transport.close();
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Надсилає лист реєстрації зі старого шаблону та одноразовим посиланням активації.
105
+ * @returns Чи прийняв поштовий сервер лист; false, якщо mail.disable=true.
106
+ */
107
+ export async function sendActivationEmail(
108
+ { email, token }: { email: string; token: string }
109
+ ): Promise<boolean> {
110
+ if (mailDisabled()) return false;
111
+ const url = activationLink(token);
112
+ return sendEmail({
113
+ email,
114
+ subject: "Вас зареєстровано в кабінеті геодезиста",
115
+ template: "ds.surveyor_registration.pt",
116
+ data: { protocol: url.protocol.slice(0, -1), host: url.host, login: email, activationUrl: url.href },
117
+ });
118
+ }
119
+
120
+ /**
121
+ * Надсилає одноразове посилання відновлення пароля (mail.password_reset_url).
122
+ * @returns Чи прийняв поштовий сервер лист; false, якщо mail.disable=true.
123
+ */
124
+ export async function sendPasswordResetEmail(
125
+ { email, token }: { email: string; token: string }
126
+ ): Promise<boolean> {
127
+ if (mailDisabled()) return false;
128
+ const url = tokenLink("password_reset_url", token);
129
+ return sendEmail({
130
+ email,
131
+ subject: "Відновлення пароля до кабінету геодезиста",
132
+ template: "ds.surveyor_password_reset.pt",
133
+ data: { protocol: url.protocol.slice(0, -1), host: url.host, login: email, resetUrl: url.href },
134
+ });
135
+ }
136
+
137
+ /** Повідомляє геодезиста про зміну пароля через шаблон ds.surveyor_send_mail.pt. */
138
+ export async function sendPasswordChangedEmail({ email }: { email: string }): Promise<boolean> {
139
+ if (mailDisabled()) return false;
140
+ const url = activationLink("");
141
+ return sendEmail({
142
+ email,
143
+ subject: "Пароль до кабінету геодезиста змінено",
144
+ template: "ds.surveyor_send_mail.pt",
145
+ data: { protocol: url.protocol.slice(0, -1), host: url.host, login: email },
146
+ });
147
+ }
148
+
149
+ /** Надсилає логін і згенерований адміністратором пароль. */
150
+ export async function sendAdminPasswordChangedEmail(
151
+ { email, password }: { email: string; password: string }
152
+ ): Promise<boolean> {
153
+ if (mailDisabled()) return false;
154
+ const url = activationLink("");
155
+ return sendEmail({
156
+ email,
157
+ subject: "Адміністратор порталу змінив Вам пароль до кабінету геодезиста",
158
+ template: "ds.surveyor_admin_password.pt",
159
+ data: { protocol: url.protocol.slice(0, -1), host: url.host, login: email, password },
160
+ });
161
+ }
@@ -0,0 +1,29 @@
1
+ import type { AfterUserHook } from "@opengis/fcore";
2
+
3
+ export const surveyorPermissions = [
4
+ "public_applications:read",
5
+ "public_applications:create",
6
+ "public_applications:update",
7
+ "public_application_status_history:read",
8
+ "public_organizations:read",
9
+ "public_surveyors:read",
10
+ "public_certificates:read",
11
+ ];
12
+
13
+ /** Restore cabinet access after FCore reloads permissions from platform roles. */
14
+ export const afterSurveyorUser: AfterUserHook = async (user, ctx) => {
15
+ if (user.type !== "regular") return;
16
+
17
+ // Remove stale cabinet grants before rechecking the profile, even if the query fails.
18
+ user.permissions = user.permissions.filter((permission) => !surveyorPermissions.includes(permission));
19
+ const result = await ctx.pg.query<{ surveyor_id: string }>(
20
+ `SELECT surveyor_id
21
+ FROM surveyor.surveyors
22
+ WHERE surveyor_id::text = $1
23
+ AND enabled = true AND registered_at IS NOT NULL`,
24
+ [user.id]
25
+ );
26
+ if (result.rows[0]) {
27
+ return { permissions: [...user.permissions, ...surveyorPermissions] };
28
+ }
29
+ };
@@ -0,0 +1,33 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { BadRequestError } from "@opengis/fcore";
3
+
4
+ /**
5
+ * Обчислює SHA-256 хеш токена реєстрації для зберігання в базі.
6
+ * @param token Токен у відкритому вигляді.
7
+ * @returns Хеш у шістнадцятковому форматі.
8
+ */
9
+ export function tokenHash(token: string): string {
10
+ return createHash("sha256").update(token).digest("hex");
11
+ }
12
+
13
+ /**
14
+ * Створює криптографічно випадковий одноразовий токен реєстрації.
15
+ * @returns Токен у форматі base64url.
16
+ */
17
+ export function token(): string {
18
+ return randomBytes(32).toString("base64url");
19
+ }
20
+
21
+ /**
22
+ * Перевіряє збіг пароля з підтвердженням після валідації довжини в схемі запиту.
23
+ * @param params Новий пароль та його підтвердження.
24
+ * @returns Перевірений пароль.
25
+ */
26
+ export function checkPassword(
27
+ { password, confirmation }: { password: string; confirmation: string }
28
+ ): string {
29
+ if (password !== confirmation) {
30
+ throw new BadRequestError("Password confirmation does not match");
31
+ }
32
+ return password;
33
+ }