@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,46 @@
1
+ import type { AppContext, User } from "@opengis/fcore";
2
+ import {
3
+ admin,
4
+ applicationUpdateFailed,
5
+ audit,
6
+ history,
7
+ releaseReservesForParent,
8
+ type Db,
9
+ } from "../utils/shared.js";
10
+
11
+ /**
12
+ * Завершує перевірену заявку після інтеграції та звільняє доступні резерви.
13
+ * @param params Заявка, адміністратор і контекст FCore.
14
+ * @returns Статус, час завершення та перелік звільнених резервів.
15
+ */
16
+ export async function completeApplication(
17
+ { id, user, ctx }: { id: string; user: User | undefined; ctx: AppContext }
18
+ ) {
19
+ const uid = admin(user);
20
+ const result = await ctx.pg.transaction(async (db: Db) => {
21
+ // Узгоджує завершення та звільнення резервів із паралельним створенням заявок.
22
+ await db.query("SELECT pg_advisory_xact_lock(85437120)");
23
+ const updated = await db.query<{ integrated_at: Date }>(
24
+ `UPDATE surveyor.applications
25
+ SET status = 'completed',
26
+ integrated_at = now(),
27
+ integrated_by = $2,
28
+ updated_by = $2,
29
+ updated_at = now()
30
+ WHERE app_id = $1 AND status = 'verified'
31
+ RETURNING integrated_at`,
32
+ [id, uid]
33
+ );
34
+ if (!updated.rows[0]) {
35
+ await applicationUpdateFailed({ db, id, status: "verified" });
36
+ }
37
+ await history({ db, appId: id, from: "verified", to: "completed", by: uid });
38
+ const released = await releaseReservesForParent({ db, parentId: id, uid });
39
+ return { id, status: "completed", completed_at: updated.rows[0]!.integrated_at, released };
40
+ });
41
+ await audit({ ctx, action: "complete", appId: id, uid });
42
+ for (const released of result.released) {
43
+ await audit({ ctx, action: "releaseReserve", appId: released, uid });
44
+ }
45
+ return result;
46
+ }
@@ -0,0 +1,48 @@
1
+ import type { AppContext } from "@opengis/fcore";
2
+ import { NotFoundError, hashPassword } from "@opengis/fcore";
3
+ import { checkPassword, tokenHash } from "../utils/registration.js";
4
+
5
+ /**
6
+ * Завершує реєстрацію за чинним одноразовим токеном у профілі геодезиста.
7
+ * @param params Токен активації, пароль, підтвердження і контекст FCore.
8
+ * @returns Ознака успішного завершення реєстрації.
9
+ */
10
+ export async function completeSurveyorRegistration(
11
+ { rawToken, password, confirmation, ctx }: {
12
+ rawToken: string;
13
+ password: string;
14
+ confirmation: string;
15
+ ctx: AppContext;
16
+ }
17
+ ) {
18
+ const validPassword = checkPassword({ password, confirmation });
19
+ const passwordHash = await hashPassword(validPassword);
20
+
21
+ const result = await ctx.pg.query<{ surveyor_id: string }>(
22
+ `UPDATE surveyor.surveyors
23
+ SET password_hash = $2,
24
+ registered_at = now(),
25
+ password_changed_at = now(),
26
+ registration_token_hash = NULL,
27
+ registration_token_expires_at = NULL,
28
+ updated_at = now()
29
+ WHERE registration_token_hash = $1
30
+ AND registration_token_expires_at > now()
31
+ AND registered_at IS NULL
32
+ AND enabled = true
33
+ RETURNING surveyor_id`,
34
+ [tokenHash(rawToken), passwordHash]
35
+ );
36
+ const surveyorId = result.rows[0]?.surveyor_id;
37
+ if (!surveyorId) {
38
+ throw new NotFoundError("Registration token invalid or expired");
39
+ }
40
+
41
+ await ctx.audit.write({
42
+ module: "surveyor",
43
+ resource: "surveyors",
44
+ resourceId: surveyorId,
45
+ action: "completeRegistration",
46
+ });
47
+ return { registered: true };
48
+ }
@@ -0,0 +1,169 @@
1
+ import type { AppContext, User } from "@opengis/fcore";
2
+ import { BadRequestError, FCoreError, ForbiddenError } from "@opengis/fcore";
3
+ import {
4
+ actor,
5
+ audit,
6
+ history,
7
+ surveyorForUser,
8
+ type Db,
9
+ } from "../utils/shared.js";
10
+ import { limit, polygon, type CreateInput } from "../utils/application.js";
11
+
12
+ /**
13
+ * Створює заявку після перевірки сертифіката, членства, адреси, площі та перетинів.
14
+ * Початковий статус і перший запис історії зберігаються в одній транзакції.
15
+ * @param params Дані заявки, геодезист і контекст FCore.
16
+ * @returns Ідентифікатор, номер, статус і площа створеної заявки.
17
+ */
18
+ export async function createApplication(
19
+ { input, user, ctx }: { input: CreateInput; user: User | undefined; ctx: AppContext }
20
+ ) {
21
+ const uid = actor(user);
22
+ const orgId = input.organization_id;
23
+
24
+ const geojson = polygon(input.geom);
25
+
26
+ const result = await ctx.pg.transaction(async (db: Db) => {
27
+ // Один ключ серіалізує перевірку площі та перетинів для одночасних заявок.
28
+ await db.query("SELECT pg_advisory_xact_lock(85437120)");
29
+
30
+ const surveyorId = await surveyorForUser({ db, user });
31
+ const profile = await db.query(
32
+ `SELECT 1
33
+ FROM surveyor.surveyors AS s
34
+ JOIN surveyor.certificates AS c ON c.certificate_id = s.certificate_id
35
+ JOIN surveyor.organization_surveyors AS os ON os.surveyor_id = s.surveyor_id
36
+ WHERE s.surveyor_id = $1
37
+ AND os.org_id = $2
38
+ AND os.enabled = true
39
+ AND c.certificate_stopping IS NULL
40
+ AND c.certificate_suspension IS NULL
41
+ AND c.isvalid IS NOT FALSE`,
42
+ [surveyorId, orgId]
43
+ );
44
+ if (!profile.rowCount) {
45
+ throw new ForbiddenError("Active organization membership and certificate required");
46
+ }
47
+
48
+ const settlement = await db.query(
49
+ `SELECT 1
50
+ FROM data_address.atu
51
+ WHERE katottg = $1 AND level = 5`,
52
+ [input.settlement_id]
53
+ );
54
+ if (!settlement.rowCount) {
55
+ throw new BadRequestError("Settlement not found");
56
+ }
57
+
58
+ if (input.address_id) {
59
+ const address = await db.query(
60
+ `SELECT 1
61
+ FROM data_address.address AS address
62
+ JOIN data_address.street AS street ON street.str_id = address.parent
63
+ JOIN data_address.atu AS settlement ON settlement.atu_id = street.parent
64
+ WHERE address.addr_id = $1 AND settlement.katottg = $2`,
65
+ [input.address_id, input.settlement_id]
66
+ );
67
+ if (!address.rowCount) {
68
+ throw new BadRequestError("Address does not belong to settlement");
69
+ }
70
+ }
71
+
72
+ const geom = await db.query<{ valid: boolean; area: number }>(
73
+ `SELECT ST_IsValid(g) AS valid,
74
+ ST_Area(g::geography) / 10000 AS area
75
+ FROM (
76
+ SELECT ST_SetSRID(ST_GeomFromGeoJSON($1), 4326) AS g
77
+ ) AS polygon`,
78
+ [geojson]
79
+ );
80
+ const area = Number(geom.rows[0]?.area);
81
+ if (!geom.rows[0]?.valid || !Number.isFinite(area) || area <= 0) {
82
+ throw new BadRequestError("Invalid polygon geometry");
83
+ }
84
+ if (area > limit({ name: "SURVEYOR_MAX_APPLICATION_AREA_HA", fallback: 10 })) {
85
+ throw new FCoreError(
86
+ "APPLICATION_AREA_LIMIT_EXCEEDED",
87
+ "Application area limit exceeded",
88
+ 422
89
+ );
90
+ }
91
+
92
+ const activeArea = await db.query<{ area: number }>(
93
+ `SELECT COALESCE(sum(area), 0)::float8 AS area
94
+ FROM surveyor.applications
95
+ WHERE org_id = $1
96
+ AND status IN ('awaitingData', 'dataIssued', 'reserve', 'underReview', 'verified')`,
97
+ [orgId]
98
+ );
99
+ const organizationAreaLimit = limit({
100
+ name: "SURVEYOR_MAX_ORGANIZATION_AREA_HA",
101
+ fallback: 100,
102
+ });
103
+ if (Number(activeArea.rows[0]?.area) + area > organizationAreaLimit) {
104
+ throw new FCoreError(
105
+ "ORGANIZATION_AREA_LIMIT_EXCEEDED",
106
+ "Organization active area limit exceeded",
107
+ 422
108
+ );
109
+ }
110
+
111
+ const conflicts = await db.query<{ intersects: boolean }>(
112
+ `WITH incoming AS (
113
+ SELECT ST_SetSRID(ST_GeomFromGeoJSON($1), 4326) AS geom
114
+ )
115
+ SELECT EXISTS (
116
+ SELECT 1
117
+ FROM surveyor.applications AS b
118
+ CROSS JOIN incoming AS n
119
+ WHERE b.status IN ('awaitingData', 'dataIssued', 'underReview', 'verified')
120
+ AND b.geom && n.geom
121
+ AND ST_Relate(n.geom, b.geom, 'T********')
122
+ ) AS intersects`,
123
+ [geojson]
124
+ );
125
+ const status = conflicts.rows[0]?.intersects ? "reserve" : "awaitingData";
126
+
127
+ const year = new Date().getUTCFullYear().toString();
128
+ const next = await db.query<{ n: number }>(
129
+ `SELECT COALESCE(MAX(substring(number FROM 5)::integer), 0) + 1 AS n
130
+ FROM surveyor.applications
131
+ WHERE number ~ $1`,
132
+ [`^${year}[0-9]{6}$`]
133
+ );
134
+ const number = `${year}${String(next.rows[0]!.n).padStart(6, "0")}`;
135
+
136
+ const inserted = await db.query<{ app_id: string }>(
137
+ `INSERT INTO surveyor.applications (
138
+ number, org_id, surveyor_id, status, work_type, description,
139
+ execution_basis, settlement_id, is_found_address_id, address_id,
140
+ location, area, geom, created_by
141
+ ) VALUES (
142
+ $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12,
143
+ ST_SetSRID(ST_GeomFromGeoJSON($13), 4326), $14
144
+ ) RETURNING app_id`,
145
+ [
146
+ number,
147
+ orgId,
148
+ surveyorId,
149
+ status,
150
+ input.work_type,
151
+ input.description ?? null,
152
+ input.execution_basis ?? null,
153
+ input.settlement_id,
154
+ input.is_found_address_id,
155
+ input.address_id ?? null,
156
+ input.location ?? null,
157
+ area.toFixed(4),
158
+ geojson,
159
+ uid,
160
+ ]
161
+ );
162
+ const id = inserted.rows[0]!.app_id;
163
+ await history({ db, appId: id, from: null, to: status, by: uid });
164
+ return { id, number, status, area: Number(area.toFixed(4)) };
165
+ });
166
+
167
+ await audit({ ctx, action: "create", appId: result.id, uid });
168
+ return result;
169
+ }
@@ -0,0 +1,34 @@
1
+ import type { AppContext, User } from "@opengis/fcore";
2
+ import { NotFoundError } from "@opengis/fcore";
3
+ import { accessibleApplication } from "../utils/accessibleApplication.js";
4
+ import { exportSrid, type ExportOptions, type GeoJSONFeatureCollection } from "../utils/export.js";
5
+
6
+ /**
7
+ * Повертає полігон доступної користувачу заявки як GeoJSON FeatureCollection.
8
+ * @param params Заявка, користувач і контекст FCore.
9
+ * @returns Геометрія та основні атрибути заявки.
10
+ */
11
+ export async function geometryExport({
12
+ id,
13
+ user,
14
+ ctx,
15
+ ...options
16
+ }: {
17
+ id: string;
18
+ user: User | undefined;
19
+ ctx: AppContext;
20
+ } & ExportOptions): Promise<GeoJSONFeatureCollection> {
21
+
22
+ const srid = exportSrid(options);
23
+ const app = await accessibleApplication({ id, user, ctx, srid });
24
+
25
+ if (!app.geometry) {
26
+ throw new NotFoundError("Application geometry not found");
27
+ }
28
+
29
+ return {
30
+ type: "FeatureCollection",
31
+ crs: { type: "name", properties: { name: `EPSG:${srid}` } },
32
+ features: [{ type: "Feature", geometry: app.geometry, properties: app.properties }],
33
+ };
34
+ }
@@ -0,0 +1,66 @@
1
+ import path from "node:path";
2
+ import type { User } from "@opengis/fcore";
3
+ import { BadRequestError, FCoreError } from "@opengis/fcore";
4
+ import { actor } from "../utils/shared.js";
5
+ import { firstBoundary } from "../utils/firstBoundary.js";
6
+ import type { GeoJSONFeatureCollection } from "../utils/export.js";
7
+ import { convertVector } from "../../../plugins/convertVector.js";
8
+
9
+ export type GeometryImportInput = { file: string; filename: string; encoding?: string };
10
+
11
+ const formats = new Set(["zip", "kml", "gml", "geojson", "json"]);
12
+
13
+ /** Окремий ліміт для API імпорту геометрії: 50 МіБ. */
14
+ export const GEOMETRY_IMPORT_FILE_LIMIT = 50 * 1024 * 1024;
15
+
16
+ /** Конвертує файл із base64 і повертає перший об'єкт для форми створення заявки. */
17
+ export async function geometryImport({
18
+ input,
19
+ user,
20
+ }: {
21
+ input: GeometryImportInput;
22
+ user: User | undefined;
23
+ }): Promise<GeoJSONFeatureCollection> {
24
+ actor(user);
25
+
26
+ if (typeof input.file !== "string" || !input.file) {
27
+ throw new BadRequestError("Потрібен параметр file з вмістом файлу в base64");
28
+ }
29
+
30
+ if (
31
+ typeof input.filename !== "string" ||
32
+ !input.filename.trim() ||
33
+ /[\x00-\x1f]/.test(input.filename)
34
+ ) {
35
+ throw new BadRequestError("Потрібен параметр filename разом із file");
36
+ }
37
+
38
+ const filename = path.posix.basename(input.filename.replace(/\\/g, "/"));
39
+ const format = path.posix.extname(filename).slice(1).toLowerCase();
40
+ if (!formats.has(format)) {
41
+ throw new BadRequestError(`Підтримуються формати: ${[...formats].join(", ")}`);
42
+ }
43
+
44
+ if (input.file.length > Math.ceil(GEOMETRY_IMPORT_FILE_LIMIT / 3) * 4) {
45
+ throw new FCoreError("FILE_TOO_LARGE", "Файл перевищує ліміт 50 МіБ для імпорту геометрії", 413);
46
+ }
47
+ if (input.file.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(input.file)) {
48
+ throw new BadRequestError("Параметр file має містити коректний base64 без префікса data:");
49
+ }
50
+
51
+ const data = Buffer.from(input.file, "base64");
52
+ if (!data.length) {
53
+ throw new BadRequestError("Файл порожній");
54
+ }
55
+ if (data.length > GEOMETRY_IMPORT_FILE_LIMIT) {
56
+ throw new FCoreError("FILE_TOO_LARGE", "Файл перевищує ліміт 50 МіБ для імпорту геометрії", 413);
57
+ }
58
+
59
+ const geojson = await convertVector({
60
+ data,
61
+ format,
62
+ filename,
63
+ encoding: input.encoding ?? "UTF-8",
64
+ });
65
+ return firstBoundary(geojson);
66
+ }
@@ -0,0 +1,56 @@
1
+ import type { AppContext, User } from "@opengis/fcore";
2
+ import { ForbiddenError } from "@opengis/fcore";
3
+ import { actor } from "../utils/shared.js";
4
+
5
+ export type SurveyorUser = {
6
+ surveyor_id: string;
7
+ certificate_id: string;
8
+ first_name: string;
9
+ last_name: string;
10
+ middle_name: string | null;
11
+ email: string;
12
+ phone: string | null;
13
+ enabled: boolean;
14
+ organizations: {
15
+ org_id: string;
16
+ name: string;
17
+ legal_address: string | null;
18
+ phone: string;
19
+ email: string;
20
+ scan_path: string | null;
21
+ }[];
22
+ };
23
+
24
+ /** Повертає основні дані поточного геодезиста та організації з активним членством. */
25
+ export async function getSurveyorUser(
26
+ { user, ctx }: { user: User | undefined; ctx: AppContext }
27
+ ): Promise<SurveyorUser> {
28
+ const uid = actor(user);
29
+
30
+ const result = await ctx.pg.query<SurveyorUser>(
31
+ `SELECT s.surveyor_id, s.certificate_id,
32
+ s.first_name, s.last_name, s.middle_name,
33
+ s.email, s.phone, s.enabled,
34
+ COALESCE((
35
+ SELECT json_agg(json_build_object(
36
+ 'org_id', o.org_id,
37
+ 'name', o.name,
38
+ 'legal_address', o.legal_address,
39
+ 'phone', o.phone,
40
+ 'email', o.email,
41
+ 'scan_path', o.scan_path
42
+ ) ORDER BY o.name, o.org_id)
43
+ FROM surveyor.organization_surveyors AS m
44
+ JOIN surveyor.organizations AS o ON o.org_id = m.org_id
45
+ WHERE m.surveyor_id = s.surveyor_id AND m.enabled = true
46
+ ), '[]'::json) AS organizations
47
+ FROM surveyor.surveyors AS s
48
+ WHERE s.surveyor_id::text = $1
49
+ AND s.enabled = true AND s.registered_at IS NOT NULL`,
50
+ [uid]
51
+ );
52
+ if (!result.rows[0]) {
53
+ throw new ForbiddenError("Active surveyor profile required");
54
+ }
55
+ return result.rows[0];
56
+ }
@@ -0,0 +1,82 @@
1
+ import type { AppContext, User } from "@opengis/fcore";
2
+ import { BadRequestError } from "@opengis/fcore";
3
+ import applicationStatus from "../../../dictionaries/surveyor/application_status.js";
4
+ import { actor, surveyorForUser, type Status } from "../utils/shared.js";
5
+
6
+ const statusCodes = new Set(applicationStatus.items.map((item) => item.code));
7
+
8
+ export type ApplicationIdentifyInput = {
9
+ lng: number;
10
+ lat: number;
11
+ page?: number;
12
+ limit?: number;
13
+ filter?: Status;
14
+ statuses?: string;
15
+ };
16
+
17
+ export type ApplicationIdentifyResult = Record<string, unknown>;
18
+
19
+ function parseStatuses(value: string | undefined): Status[] {
20
+ if (!value?.trim()) return [];
21
+ const statuses = [...new Set(value.split(",").map((item) => item.trim()).filter(Boolean))];
22
+ const unknown = statuses.filter((status) => !statusCodes.has(status));
23
+ if (unknown.length) throw new BadRequestError(`Невідомий статус: ${unknown.join(", ")}`);
24
+ return statuses as Status[];
25
+ }
26
+
27
+ export async function identifyApplications({
28
+ input,
29
+ user,
30
+ ctx,
31
+ }: {
32
+ input: ApplicationIdentifyInput;
33
+ user: User | undefined;
34
+ ctx: AppContext;
35
+ }): Promise<{ total: number; page: number; count: number; data: ApplicationIdentifyResult[] }> {
36
+ actor(user);
37
+
38
+ const page = input.page ?? 1;
39
+ const limit = input.limit ?? 10;
40
+
41
+ const isAdmin = user?.type === "admin";
42
+ if (!isAdmin) await surveyorForUser({ db: ctx.pg, user });
43
+
44
+ const resourceName = isAdmin ? "applications" : "public_applications";
45
+
46
+ const matches = await ctx.pg.query<{ app_id: string }>(
47
+ `SELECT a.app_id
48
+ FROM surveyor.applications AS a
49
+ WHERE ST_Intersects(a.geom, ST_SetSRID(ST_MakePoint($1, $2), 4326))`,
50
+ [input.lng, input.lat]
51
+ );
52
+
53
+ const statuses = parseStatuses(input.statuses);
54
+ const statusFilter = statuses.length > 1
55
+ ? { status: { in: statuses.join(",") } }
56
+ : statuses.length === 1
57
+ ? { status: statuses[0] }
58
+ : input.filter
59
+ ? { status: input.filter }
60
+ : {};
61
+
62
+ const result = await ctx.resource.find({
63
+ name: resourceName,
64
+ user,
65
+ query: {
66
+ filter: {
67
+ app_id: { in: matches.rows.map(({ app_id }: { app_id: string }) => app_id) },
68
+ ...statusFilter,
69
+ },
70
+ sort: ["-created_at", "app_id"],
71
+ limit,
72
+ offset: (page - 1) * limit,
73
+ },
74
+ });
75
+
76
+ return {
77
+ total: Number(result.total ?? 0),
78
+ page,
79
+ count: result.rows.length,
80
+ data: result.rows,
81
+ };
82
+ }
@@ -0,0 +1,55 @@
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 { FileInput } from "../utils/application.js";
11
+
12
+ /**
13
+ * Прив'язує виданий адміністратором вихідний файл до заявки та змінює її статус.
14
+ * @param params Заявка, файл, адміністратор і контекст FCore.
15
+ * @returns Статус `dataIssued` і шлях вихідного файлу.
16
+ */
17
+ export async function issueSourceData(
18
+ { id, input, user, ctx }: {
19
+ id: string;
20
+ input: FileInput;
21
+ user: User | undefined;
22
+ ctx: AppContext;
23
+ }
24
+ ) {
25
+ const uid = admin(user);
26
+ const file = await attachedFile({ ctx, appId: id, filePath: input.file_path });
27
+ const result = await ctx.pg.transaction(async (db: Db) => {
28
+ const updated = await db.query<{ app_id: string }>(
29
+ `UPDATE surveyor.applications
30
+ SET file_output = $2,
31
+ source_data_issued_at = now(),
32
+ status = 'dataIssued',
33
+ updated_by = $3,
34
+ updated_at = now()
35
+ WHERE app_id = $1 AND status = 'awaitingData'
36
+ RETURNING app_id`,
37
+ [id, file, uid]
38
+ );
39
+ if (!updated.rows[0]) {
40
+ await applicationUpdateFailed({ db, id, status: "awaitingData" });
41
+ }
42
+ await history({
43
+ db,
44
+ appId: id,
45
+ from: "awaitingData",
46
+ to: "dataIssued",
47
+ by: uid,
48
+ reason: input.note,
49
+ file,
50
+ });
51
+ return { id, status: "dataIssued", output_file_path: file };
52
+ });
53
+ await audit({ ctx, action: "issueSourceData", appId: id, uid });
54
+ return result;
55
+ }
@@ -0,0 +1,67 @@
1
+ import type { AppContext } from "@opengis/fcore";
2
+ import { UnauthorizedError, verifyPassword } from "@opengis/fcore";
3
+ import type { FastifyRequest } from "fastify";
4
+ import { surveyorPermissions } from "../utils/permissions.js";
5
+
6
+ export type LoginInput = { email: string; password: string };
7
+ export type SessionRequest = FastifyRequest & {
8
+ logIn(user: { id: string; type: "regular"; permissions: string[] }): Promise<void>;
9
+ session: {
10
+ cookie: { maxAge?: number };
11
+ sessionId: string;
12
+ save(): Promise<void>;
13
+ };
14
+ };
15
+
16
+ /**
17
+ * Перевіряє пароль геодезиста та відкриває cookie-сесію FCore.
18
+ * @param params Облікові дані, запит Fastify та контекст FCore.
19
+ * @returns Дані автентифікованого користувача і адресу переходу.
20
+ */
21
+ export async function loginSurveyor(
22
+ { input, request, ctx }: { input: LoginInput; request: SessionRequest; ctx: AppContext }
23
+ ) {
24
+ const email = input.email.trim().toLowerCase();
25
+ const result = await ctx.pg.query<{ surveyor_id: string; password_hash: string | null }>(
26
+ `SELECT surveyor_id, password_hash
27
+ FROM surveyor.surveyors
28
+ WHERE lower(email) = $1
29
+ AND enabled = true
30
+ AND registered_at IS NOT NULL
31
+ LIMIT 1`,
32
+ [email]
33
+ );
34
+ const surveyor = result.rows[0];
35
+ if (!surveyor?.password_hash || !(await verifyPassword(input.password, surveyor.password_hash))) {
36
+ throw new UnauthorizedError("Invalid email or password");
37
+ }
38
+
39
+ const updated = await ctx.pg.query<{ surveyor_id: string }>(
40
+ `UPDATE surveyor.surveyors
41
+ SET last_login_at = now()
42
+ WHERE surveyor_id = $1
43
+ AND password_hash = $2
44
+ AND enabled = true
45
+ AND registered_at IS NOT NULL
46
+ RETURNING surveyor_id`,
47
+ [surveyor.surveyor_id, surveyor.password_hash]
48
+ );
49
+ if (!updated.rows[0]) {
50
+ throw new UnauthorizedError("Invalid email or password");
51
+ }
52
+
53
+ const user = { id: surveyor.surveyor_id, type: "regular" as const, permissions: [...surveyorPermissions] };
54
+ await request.logIn(user);
55
+ request.session.cookie.maxAge = ctx.config.auth.sessionTimeout * 60_000;
56
+ await request.session.save();
57
+
58
+ await ctx.audit.write({
59
+ module: "surveyor",
60
+ resource: "session",
61
+ resourceId: request.session.sessionId,
62
+ action: "login",
63
+ userId: user.id,
64
+ ipAddress: request.ip,
65
+ });
66
+ return { user, redirectUrl: ctx.config.auth.redirect };
67
+ }
@@ -0,0 +1,61 @@
1
+ import type { AppContext, User } from "@opengis/fcore";
2
+ import { actor } from "../utils/shared.js";
3
+
4
+ export type MapLayerComponent = "map" | "application-form" | "application-card";
5
+
6
+ export type MapLayersInput = { component?: MapLayerComponent };
7
+
8
+ export type MapLayer = {
9
+ code: string;
10
+ name: string;
11
+ layer_group: "base" | "overlay";
12
+ layer_type: "raster" | "vector" | "applications";
13
+ tiles: string[];
14
+ scheme: "xyz" | "tms";
15
+ source_layer: string | null;
16
+ attribution: string | null;
17
+ minzoom: number | null;
18
+ maxzoom: number | null;
19
+ opacity: number;
20
+ style: Record<string, unknown> | null;
21
+ legend: Record<string, unknown> | null;
22
+ preview: string | null;
23
+ components: MapLayerComponent[];
24
+ is_default: boolean;
25
+ has_filters: boolean;
26
+ };
27
+
28
+ export type MapLayersResult = {
29
+ default_base: string | null;
30
+ base: MapLayer[];
31
+ overlays: MapLayer[];
32
+ };
33
+
34
+ /**
35
+ * Повертає увімкнені шари панелі карти, згруповані на базові та додаткові у порядку відображення.
36
+ * Додаткові шари йдуть від верхнього до нижнього: перший у списку малюється поверх.
37
+ * Якщо передано `component`, повертаються лише шари, налаштовані для цього компонента.
38
+ */
39
+ export async function mapLayers(
40
+ { input, user, ctx }: { input: MapLayersInput; user: User | undefined; ctx: AppContext }
41
+ ): Promise<MapLayersResult> {
42
+ actor(user);
43
+
44
+ const { rows }: { rows: MapLayer[] } = await ctx.pg.query(
45
+ `SELECT code, name, layer_group, layer_type, tiles, scheme, source_layer, attribution,
46
+ minzoom, maxzoom, opacity::float AS opacity, style, legend, preview, components,
47
+ is_default, has_filters
48
+ FROM surveyor.map_layers
49
+ WHERE enabled
50
+ AND ($1::text IS NULL OR components @> ARRAY[$1::text])
51
+ ORDER BY layer_group, sort_order, name`,
52
+ [input.component ?? null]
53
+ );
54
+
55
+ const base = rows.filter((layer) => layer.layer_group === "base");
56
+ const overlays = rows.filter((layer) => layer.layer_group === "overlay");
57
+ // Підложку вимкнути не можна, тому без явного значення активна перша.
58
+ const defaultBase = base.find((layer) => layer.is_default) ?? base[0];
59
+
60
+ return { default_base: defaultBase?.code ?? null, base, overlays };
61
+ }