@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.
- package/CHANGELOG.md +42 -0
- package/README.md +188 -3
- package/dist/chunks/AppIcon-CIR6y5uE.js +85 -0
- package/dist/chunks/AppealDetailField-CI-1qhs3.js +58 -0
- package/dist/chunks/AppealStatusBadge-CSXnfarR.js +132 -0
- package/dist/chunks/AppealStatusBadge-DYBe9hqP.js +171 -0
- package/dist/chunks/ApplicationHistorySection-C0wwhwA4.js +769 -0
- package/dist/chunks/BaseModal-C7PVYz0m.js +85 -0
- package/dist/chunks/FormFilePicker-C3XQw50i.js +76 -0
- package/dist/chunks/MapLayerMenu-DjYCxEc3.js +145 -0
- package/dist/chunks/RegistryForm-CEUqFmsF.js +99 -0
- package/dist/chunks/RegistryFormModal-DfY4z_7r.js +85 -0
- package/dist/chunks/RegistryToolbar-BV4mYVAc.js +452 -0
- package/dist/chunks/UserAccessBadge-D8JfgGfN.js +44 -0
- package/dist/chunks/UserTypeBadge-YIwwoCho.js +188 -0
- package/dist/chunks/VerifiedBadge-Bba8WnuB.js +34 -0
- package/dist/chunks/_plugin-vue_export-helper-B3ysoDQm.js +8 -0
- package/dist/chunks/account-types-Br7gx_D_.js +35 -0
- package/dist/chunks/account_types-DLL1w122.js +25 -0
- package/dist/chunks/appealMapLayers-CQMK3rrz.js +115 -0
- package/dist/chunks/application_status-BhNGiY2I.js +45 -0
- package/dist/chunks/applications-BB9JRcgl.js +132 -0
- package/dist/chunks/buildSchema-CccjX9TJ.js +37 -0
- package/dist/chunks/card-B-ftozcq.js +739 -0
- package/dist/chunks/card-BctFHFZe.js +538 -0
- package/dist/chunks/card-CKD1N0QD.js +330 -0
- package/dist/chunks/card-CiNZxAd5.js +297 -0
- package/dist/chunks/card-DUtDfwMk.js +607 -0
- package/dist/chunks/card-fL26_Gvc.js +1189 -0
- package/dist/chunks/certificates-BSd1i0un.js +424 -0
- package/dist/chunks/create-DxMC_IL1.js +1033 -0
- package/dist/chunks/filterQuery-CvfZrkTC.js +99 -0
- package/dist/chunks/form-Bh6i5n1U.js +315 -0
- package/dist/chunks/form-DDjELqZ9.js +89 -0
- package/dist/chunks/geometry-DyhIVRcw.js +67 -0
- package/dist/chunks/map-Z57iMvFb.js +2763 -0
- package/dist/chunks/map-layers-DnmkOEld.js +400 -0
- package/dist/chunks/mapLayersApi-CWoQ2be-.js +251 -0
- package/dist/chunks/organizations-BO1_JETm.js +476 -0
- package/dist/chunks/organizations-BbYipLwk.js +14 -0
- package/dist/chunks/profile-ByahbF4B.js +164 -0
- package/dist/chunks/profile-Dwwn_4Pr.js +243 -0
- package/dist/chunks/requests-BCin936Z.js +232 -0
- package/dist/chunks/requests-CFv5wwAN.js +530 -0
- package/dist/chunks/resendSurveyorRegistration-BHTTVIw1.js +27 -0
- package/dist/chunks/resources-2e8RFqWR.js +129 -0
- package/dist/chunks/rolldown-runtime-Dy4uBu1J.js +11 -0
- package/dist/chunks/surveyorAccount-C7UiiIYg.js +78 -0
- package/dist/chunks/users-DtTYsgMb.js +291 -0
- package/dist/chunks/work_types-Hwme-FEX.js +34 -0
- package/dist/index.css +3 -0
- package/dist/index.js +336 -0
- package/migrations/20260924120000_surveyor_schema.sql +450 -0
- package/migrations/20261008170000_address_lookup.sql +20 -0
- package/migrations/20261016120000_map_layers.sql +156 -0
- package/migrations/20261016150000_password_reset.sql +15 -0
- package/migrations/20261016170000_address_lookup_format.sql +37 -0
- package/migrations/20261016180000_settlement_lookup.sql +16 -0
- package/migrations/20261019170000_actor_lookup.sql +15 -0
- package/package.json +86 -6
- package/plugin.d.ts +15 -0
- package/plugin.js +8 -0
- package/server/app.ts +51 -0
- package/server/dictionaries/index.ts +17 -0
- package/server/dictionaries/surveyor/account_types.ts +12 -0
- package/server/dictionaries/surveyor/application_status.ts +16 -0
- package/server/dictionaries/surveyor/map_layer_components.ts +11 -0
- package/server/dictionaries/surveyor/map_layer_groups.ts +10 -0
- package/server/dictionaries/surveyor/map_layer_types.ts +11 -0
- package/server/dictionaries/surveyor/work_types.ts +15 -0
- package/server/dictionaries/surveyor/yes_no.ts +11 -0
- package/server/fastify.d.ts +12 -0
- package/server/index.ts +23 -0
- package/server/modules/surveyor/route.ts +410 -0
- package/server/modules/surveyor/schema.ts +439 -0
- package/server/modules/surveyor/services/applicationTile.ts +53 -0
- package/server/modules/surveyor/services/cancelApplication.ts +74 -0
- package/server/modules/surveyor/services/changeSurveyorPassword.ts +52 -0
- package/server/modules/surveyor/services/changeSurveyorPasswordByAdmin.ts +41 -0
- package/server/modules/surveyor/services/completeApplication.ts +46 -0
- package/server/modules/surveyor/services/completeSurveyorRegistration.ts +48 -0
- package/server/modules/surveyor/services/createApplication.ts +169 -0
- package/server/modules/surveyor/services/geometryExport.ts +34 -0
- package/server/modules/surveyor/services/geometryImport.ts +66 -0
- package/server/modules/surveyor/services/getSurveyorUser.ts +56 -0
- package/server/modules/surveyor/services/identifyApplications.ts +82 -0
- package/server/modules/surveyor/services/issueSourceData.ts +55 -0
- package/server/modules/surveyor/services/loginSurveyor.ts +67 -0
- package/server/modules/surveyor/services/mapLayers.ts +61 -0
- package/server/modules/surveyor/services/rasterExport.ts +15 -0
- package/server/modules/surveyor/services/registerSurveyor.ts +161 -0
- package/server/modules/surveyor/services/requestPasswordReset.ts +49 -0
- package/server/modules/surveyor/services/resendRegistration.ts +42 -0
- package/server/modules/surveyor/services/resetSurveyorPassword.ts +53 -0
- package/server/modules/surveyor/services/searchApplications.ts +63 -0
- package/server/modules/surveyor/services/submitSurvey.ts +70 -0
- package/server/modules/surveyor/services/updateSurveyorAccountStatus.ts +52 -0
- package/server/modules/surveyor/services/updateSurveyorStatus.ts +53 -0
- package/server/modules/surveyor/services/vectorExport.ts +86 -0
- package/server/modules/surveyor/services/verifyApplication.ts +59 -0
- package/server/modules/surveyor/utils/accessibleApplication.ts +37 -0
- package/server/modules/surveyor/utils/application.ts +68 -0
- package/server/modules/surveyor/utils/export.ts +39 -0
- package/server/modules/surveyor/utils/firstBoundary.ts +48 -0
- package/server/modules/surveyor/utils/mail.ts +161 -0
- package/server/modules/surveyor/utils/permissions.ts +29 -0
- package/server/modules/surveyor/utils/registration.ts +33 -0
- package/server/modules/surveyor/utils/shared.ts +305 -0
- package/server/modules/surveyor/utils/templates/ds.surveyor_admin_password.pt.hbs +79 -0
- package/server/modules/surveyor/utils/templates/ds.surveyor_password_reset.pt.hbs +79 -0
- package/server/modules/surveyor/utils/templates/ds.surveyor_registration.pt.hbs +80 -0
- package/server/modules/surveyor/utils/templates/ds.surveyor_send_mail.pt.hbs +79 -0
- package/server/modules/surveyor/utils/vectorLayer.ts +41 -0
- package/server/plugins/convertVector.ts +74 -0
- package/server/plugins/proto/convertVector.proto +21 -0
- package/server/plugins/swagger.ts +54 -0
- package/server/plugins/vite.dev.ts +52 -0
- package/server/plugins/vite.prod.ts +55 -0
- package/server/resources/helpers/actor_lookup.ts +5 -0
- package/server/resources/helpers/address_lookup.ts +8 -0
- package/server/resources/helpers/settlement_lookup.ts +7 -0
- package/server/resources/helpers/user_lookup.ts +5 -0
- package/server/resources/index.ts +30 -0
- package/server/resources/surveyor-admin/application_comments.ts +24 -0
- package/server/resources/surveyor-admin/application_status_history.ts +46 -0
- package/server/resources/surveyor-admin/applications.ts +125 -0
- package/server/resources/surveyor-admin/certificates.ts +87 -0
- package/server/resources/surveyor-admin/map_layers.ts +69 -0
- package/server/resources/surveyor-admin/organization_surveyors.ts +32 -0
- package/server/resources/surveyor-admin/organizations.ts +61 -0
- package/server/resources/surveyor-admin/surveyors.ts +71 -0
- package/server/resources/surveyor-user/application_status_history.ts +52 -0
- package/server/resources/surveyor-user/applications.ts +131 -0
- package/server/resources/surveyor-user/certificates.ts +67 -0
- package/server/resources/surveyor-user/organizations.ts +40 -0
- package/server/resources/surveyor-user/surveyors.ts +69 -0
- package/server/suggests/index.ts +17 -0
- package/server/tsconfig.json +3 -0
- package/surveyor-types.d.ts +30 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { AppContext, User } from "@opengis/fcore";
|
|
2
|
+
import { UnsupportedError } from "@opengis/fcore";
|
|
3
|
+
import { accessibleApplication } from "../utils/accessibleApplication.js";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Перевіряє доступ до заявки й повідомляє, що джерело растру ще не визначено.
|
|
7
|
+
* @param params Заявка, користувач і контекст FCore.
|
|
8
|
+
* @throws `UnsupportedError` після перевірки доступу.
|
|
9
|
+
*/
|
|
10
|
+
export async function rasterExport(
|
|
11
|
+
{ id, user, ctx }: { id: string; user: User | undefined; ctx: AppContext }
|
|
12
|
+
): Promise<never> {
|
|
13
|
+
await accessibleApplication({ id, user, ctx });
|
|
14
|
+
throw new UnsupportedError("Raster export requires a raster source");
|
|
15
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import type { AppContext, User } from "@opengis/fcore";
|
|
2
|
+
import { ConflictError, NotFoundError } from "@opengis/fcore";
|
|
3
|
+
import { admin, type Db } from "../utils/shared.js";
|
|
4
|
+
import { token, tokenHash } from "../utils/registration.js";
|
|
5
|
+
import { sendActivationEmail } from "../utils/mail.js";
|
|
6
|
+
|
|
7
|
+
export type RegisterInput = {
|
|
8
|
+
organization_id: string;
|
|
9
|
+
certificate_id: string;
|
|
10
|
+
email: string;
|
|
11
|
+
phone?: string;
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Створює або оновлює незавершену реєстрацію геодезиста та його зв'язок з організацією.
|
|
16
|
+
* Уже зареєстрованого геодезиста лише прикріплює до організації, якщо email збігається.
|
|
17
|
+
* @param params Дані геодезиста, адміністратор і контекст FCore.
|
|
18
|
+
* @returns Ідентифікатор геодезиста та стан реєстрації.
|
|
19
|
+
*/
|
|
20
|
+
export async function registerSurveyor(
|
|
21
|
+
{ input, user, ctx }: { input: RegisterInput; user: User | undefined; ctx: AppContext }
|
|
22
|
+
) {
|
|
23
|
+
const uid = admin(user);
|
|
24
|
+
const orgId = input.organization_id;
|
|
25
|
+
const certId = input.certificate_id;
|
|
26
|
+
const email = input.email.toLowerCase();
|
|
27
|
+
|
|
28
|
+
const rawToken = token();
|
|
29
|
+
const result = await ctx.pg.transaction(async (db: Db) => {
|
|
30
|
+
const org = await db.query("SELECT 1 FROM surveyor.organizations WHERE org_id = $1", [orgId]);
|
|
31
|
+
if (!org.rowCount) {
|
|
32
|
+
throw new NotFoundError("Organization not found");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const cert = await db.query<{
|
|
36
|
+
first_name: string | null;
|
|
37
|
+
last_name: string | null;
|
|
38
|
+
middle_name: string | null;
|
|
39
|
+
}>(
|
|
40
|
+
`SELECT first_name, last_name, middle_name
|
|
41
|
+
FROM surveyor.certificates
|
|
42
|
+
WHERE certificate_id = $1
|
|
43
|
+
AND certificate_stopping IS NULL
|
|
44
|
+
AND certificate_suspension IS NULL
|
|
45
|
+
AND isvalid IS NOT FALSE`,
|
|
46
|
+
[certId]
|
|
47
|
+
);
|
|
48
|
+
if (!cert.rows[0]) {
|
|
49
|
+
throw new ConflictError("Certificate is unavailable");
|
|
50
|
+
}
|
|
51
|
+
if (!cert.rows[0].first_name || !cert.rows[0].last_name) {
|
|
52
|
+
throw new ConflictError("Certificate must contain first and last name");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const otherEmail = await db.query(
|
|
56
|
+
`SELECT 1
|
|
57
|
+
FROM surveyor.surveyors
|
|
58
|
+
WHERE lower(email) = $1 AND certificate_id <> $2`,
|
|
59
|
+
[email, certId]
|
|
60
|
+
);
|
|
61
|
+
if (otherEmail.rowCount) {
|
|
62
|
+
throw new ConflictError("Email is already registered");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Зареєстрований геодезист прикріплюється до організації, якщо email збігається з його обліковим записом.
|
|
66
|
+
const registered = await db.query<{ surveyor_id: string; email: string }>(
|
|
67
|
+
`SELECT surveyor_id, email
|
|
68
|
+
FROM surveyor.surveyors
|
|
69
|
+
WHERE certificate_id = $1 AND registered_at IS NOT NULL`,
|
|
70
|
+
[certId]
|
|
71
|
+
);
|
|
72
|
+
if (registered.rows[0]) {
|
|
73
|
+
if (registered.rows[0].email.toLowerCase() !== email) {
|
|
74
|
+
throw new ConflictError("Certificate is already registered with another email");
|
|
75
|
+
}
|
|
76
|
+
const id = registered.rows[0].surveyor_id;
|
|
77
|
+
const membership = await db.query(
|
|
78
|
+
`INSERT INTO surveyor.organization_surveyors (org_id, surveyor_id, created_by)
|
|
79
|
+
VALUES ($1, $2, $3)
|
|
80
|
+
ON CONFLICT (org_id, surveyor_id) DO NOTHING`,
|
|
81
|
+
[orgId, id, uid]
|
|
82
|
+
);
|
|
83
|
+
if (!membership.rowCount) {
|
|
84
|
+
throw new ConflictError("Surveyor is already a member of this organization");
|
|
85
|
+
}
|
|
86
|
+
return { id, email, registration_status: "attached" as const };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Новий профіль створюємо; незавершену реєстрацію з тим самим email оновлюємо.
|
|
90
|
+
let profile: { rows: { surveyor_id: string }[] };
|
|
91
|
+
try {
|
|
92
|
+
profile = await db.query<{ surveyor_id: string }>(
|
|
93
|
+
`INSERT INTO surveyor.surveyors AS s (
|
|
94
|
+
certificate_id, first_name, last_name, middle_name, email, phone,
|
|
95
|
+
registration_token_hash, registration_token_expires_at, created_by
|
|
96
|
+
) VALUES (
|
|
97
|
+
$1, $2, $3, $4, $5, $6, $7, now() + interval '48 hours', $8
|
|
98
|
+
)
|
|
99
|
+
ON CONFLICT (certificate_id) DO UPDATE
|
|
100
|
+
SET phone = EXCLUDED.phone,
|
|
101
|
+
registration_token_hash = EXCLUDED.registration_token_hash,
|
|
102
|
+
registration_token_expires_at = EXCLUDED.registration_token_expires_at,
|
|
103
|
+
enabled = true,
|
|
104
|
+
updated_by = EXCLUDED.created_by,
|
|
105
|
+
updated_at = now()
|
|
106
|
+
WHERE s.registered_at IS NULL
|
|
107
|
+
AND lower(s.email) = EXCLUDED.email
|
|
108
|
+
RETURNING surveyor_id`,
|
|
109
|
+
[
|
|
110
|
+
certId,
|
|
111
|
+
cert.rows[0].first_name,
|
|
112
|
+
cert.rows[0].last_name,
|
|
113
|
+
cert.rows[0].middle_name,
|
|
114
|
+
email,
|
|
115
|
+
input.phone ?? null,
|
|
116
|
+
tokenHash(rawToken),
|
|
117
|
+
uid,
|
|
118
|
+
]
|
|
119
|
+
);
|
|
120
|
+
} catch (error) {
|
|
121
|
+
if (error && typeof error === "object" && "code" in error && error.code === "23505") {
|
|
122
|
+
throw new ConflictError("Certificate or email is already registered");
|
|
123
|
+
}
|
|
124
|
+
throw error;
|
|
125
|
+
}
|
|
126
|
+
const id = profile.rows[0]?.surveyor_id;
|
|
127
|
+
if (!id) {
|
|
128
|
+
throw new ConflictError("Certificate is already registered");
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
await db.query(
|
|
132
|
+
`INSERT INTO surveyor.organization_surveyors (org_id, surveyor_id, created_by)
|
|
133
|
+
VALUES ($1, $2, $3)
|
|
134
|
+
ON CONFLICT (org_id, surveyor_id) DO UPDATE SET enabled = true`,
|
|
135
|
+
[orgId, id, uid]
|
|
136
|
+
);
|
|
137
|
+
return { id, email, registration_status: "pending" as const };
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
if (result.registration_status === "attached") {
|
|
141
|
+
await ctx.audit.write({
|
|
142
|
+
module: "surveyor",
|
|
143
|
+
resource: "surveyors",
|
|
144
|
+
resourceId: result.id,
|
|
145
|
+
action: "attach",
|
|
146
|
+
userId: uid,
|
|
147
|
+
metadata: { org_id: orgId },
|
|
148
|
+
});
|
|
149
|
+
return result;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
await sendActivationEmail({ email, token: rawToken });
|
|
153
|
+
await ctx.audit.write({
|
|
154
|
+
module: "surveyor",
|
|
155
|
+
resource: "surveyors",
|
|
156
|
+
resourceId: result.id,
|
|
157
|
+
action: "register",
|
|
158
|
+
userId: uid,
|
|
159
|
+
});
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { AppContext } from "@opengis/fcore";
|
|
2
|
+
import { token, tokenHash } from "../utils/registration.js";
|
|
3
|
+
import { sendPasswordResetEmail } from "../utils/mail.js";
|
|
4
|
+
|
|
5
|
+
export type PasswordResetRequestInput = { email: string };
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Створює одноразовий токен відновлення пароля і надсилає посилання на пошту геодезиста.
|
|
9
|
+
* Відповідь не залежить від того, чи існує обліковий запис, щоб не розкривати зареєстровані адреси.
|
|
10
|
+
* Повторний запит протягом хвилини після попереднього ігнорується.
|
|
11
|
+
* @param params Електронна пошта геодезиста і контекст FCore.
|
|
12
|
+
* @returns Ознака прийняття запиту.
|
|
13
|
+
*/
|
|
14
|
+
export async function requestPasswordReset(
|
|
15
|
+
{ input, ctx }: { input: PasswordResetRequestInput; ctx: AppContext }
|
|
16
|
+
) {
|
|
17
|
+
const email = input.email.trim().toLowerCase();
|
|
18
|
+
const rawToken = token();
|
|
19
|
+
const result = await ctx.pg.query<{ surveyor_id: string; email: string }>(
|
|
20
|
+
`UPDATE surveyor.surveyors
|
|
21
|
+
SET password_reset_token_hash = $2,
|
|
22
|
+
password_reset_token_expires_at = now() + interval '1 hour',
|
|
23
|
+
updated_at = now()
|
|
24
|
+
WHERE lower(email) = $1
|
|
25
|
+
AND enabled = true
|
|
26
|
+
AND registered_at IS NOT NULL
|
|
27
|
+
AND (password_reset_token_expires_at IS NULL
|
|
28
|
+
OR password_reset_token_expires_at < now() + interval '59 minutes')
|
|
29
|
+
RETURNING surveyor_id, email`,
|
|
30
|
+
[email, tokenHash(rawToken)]
|
|
31
|
+
);
|
|
32
|
+
const surveyor = result.rows[0];
|
|
33
|
+
if (!surveyor) {
|
|
34
|
+
return { success: true };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
try {
|
|
38
|
+
await sendPasswordResetEmail({ email: surveyor.email, token: rawToken });
|
|
39
|
+
} catch (err) {
|
|
40
|
+
ctx.logger.error({ err, surveyorId: surveyor.surveyor_id }, "Failed to send password reset email");
|
|
41
|
+
}
|
|
42
|
+
await ctx.audit.write({
|
|
43
|
+
module: "surveyor",
|
|
44
|
+
resource: "surveyors",
|
|
45
|
+
resourceId: surveyor.surveyor_id,
|
|
46
|
+
action: "requestPasswordReset",
|
|
47
|
+
});
|
|
48
|
+
return { success: true };
|
|
49
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { AppContext, User } from "@opengis/fcore";
|
|
2
|
+
import { NotFoundError } from "@opengis/fcore";
|
|
3
|
+
import { admin } from "../utils/shared.js";
|
|
4
|
+
import { token, tokenHash } from "../utils/registration.js";
|
|
5
|
+
import { sendActivationEmail } from "../utils/mail.js";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Створює новий токен і надсилає лист геодезисту, який ще не завершив реєстрацію.
|
|
9
|
+
* @param params Геодезист, адміністратор і контекст FCore.
|
|
10
|
+
* @returns Стан очікування реєстрації та результат надсилання листа.
|
|
11
|
+
*/
|
|
12
|
+
export async function resendRegistration(
|
|
13
|
+
{ id, user, ctx }: { id: string; user: User | undefined; ctx: AppContext }
|
|
14
|
+
) {
|
|
15
|
+
const uid = admin(user);
|
|
16
|
+
const rawToken = token();
|
|
17
|
+
const result = await ctx.pg.query<{ email: string }>(
|
|
18
|
+
`UPDATE surveyor.surveyors
|
|
19
|
+
SET registration_token_hash = $2,
|
|
20
|
+
registration_token_expires_at = now() + interval '48 hours',
|
|
21
|
+
updated_by = $3,
|
|
22
|
+
updated_at = now()
|
|
23
|
+
WHERE surveyor_id = $1
|
|
24
|
+
AND registered_at IS NULL
|
|
25
|
+
AND enabled = true
|
|
26
|
+
RETURNING email`,
|
|
27
|
+
[id, tokenHash(rawToken), uid]
|
|
28
|
+
);
|
|
29
|
+
if (!result.rows[0]) {
|
|
30
|
+
throw new NotFoundError("Pending surveyor not found");
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
const sent = await sendActivationEmail({ email: result.rows[0].email, token: rawToken });
|
|
34
|
+
await ctx.audit.write({
|
|
35
|
+
module: "surveyor",
|
|
36
|
+
resource: "surveyors",
|
|
37
|
+
resourceId: id,
|
|
38
|
+
action: "resendRegistration",
|
|
39
|
+
userId: uid,
|
|
40
|
+
});
|
|
41
|
+
return { sent, registration_status: "pending" };
|
|
42
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { AppContext } from "@opengis/fcore";
|
|
2
|
+
import { NotFoundError, hashPassword } from "@opengis/fcore";
|
|
3
|
+
import { checkPassword, tokenHash } from "../utils/registration.js";
|
|
4
|
+
import { sendPasswordChangedEmail } from "../utils/mail.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Встановлює новий пароль за чинним одноразовим токеном відновлення.
|
|
8
|
+
* @param params Токен відновлення, пароль, підтвердження і контекст FCore.
|
|
9
|
+
* @returns Ознака успішної зміни пароля.
|
|
10
|
+
*/
|
|
11
|
+
export async function resetSurveyorPassword(
|
|
12
|
+
{ rawToken, password, confirmation, ctx }: {
|
|
13
|
+
rawToken: string;
|
|
14
|
+
password: string;
|
|
15
|
+
confirmation: string;
|
|
16
|
+
ctx: AppContext;
|
|
17
|
+
}
|
|
18
|
+
) {
|
|
19
|
+
const validPassword = checkPassword({ password, confirmation });
|
|
20
|
+
const passwordHash = await hashPassword(validPassword);
|
|
21
|
+
|
|
22
|
+
const result = await ctx.pg.query<{ surveyor_id: string; email: string }>(
|
|
23
|
+
`UPDATE surveyor.surveyors
|
|
24
|
+
SET password_hash = $2,
|
|
25
|
+
password_changed_at = now(),
|
|
26
|
+
password_reset_token_hash = NULL,
|
|
27
|
+
password_reset_token_expires_at = NULL,
|
|
28
|
+
updated_at = now()
|
|
29
|
+
WHERE password_reset_token_hash = $1
|
|
30
|
+
AND password_reset_token_expires_at > now()
|
|
31
|
+
AND enabled = true
|
|
32
|
+
AND registered_at IS NOT NULL
|
|
33
|
+
RETURNING surveyor_id, email`,
|
|
34
|
+
[tokenHash(rawToken), passwordHash]
|
|
35
|
+
);
|
|
36
|
+
const surveyor = result.rows[0];
|
|
37
|
+
if (!surveyor) {
|
|
38
|
+
throw new NotFoundError("Password reset token invalid or expired");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
await ctx.audit.write({
|
|
42
|
+
module: "surveyor",
|
|
43
|
+
resource: "surveyors",
|
|
44
|
+
resourceId: surveyor.surveyor_id,
|
|
45
|
+
action: "resetPassword",
|
|
46
|
+
});
|
|
47
|
+
try {
|
|
48
|
+
await sendPasswordChangedEmail({ email: surveyor.email });
|
|
49
|
+
} catch (err) {
|
|
50
|
+
ctx.logger.error({ err, surveyorId: surveyor.surveyor_id }, "Failed to send password changed email");
|
|
51
|
+
}
|
|
52
|
+
return { success: true };
|
|
53
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { AppContext, User } from "@opengis/fcore";
|
|
2
|
+
import { actor, surveyorForUser, type Status } from "../utils/shared.js";
|
|
3
|
+
|
|
4
|
+
export type ApplicationSearchInput = {
|
|
5
|
+
search: string;
|
|
6
|
+
page?: number;
|
|
7
|
+
limit?: number;
|
|
8
|
+
filter?: Status;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export type ApplicationSearchResult = {
|
|
12
|
+
id: string;
|
|
13
|
+
number: string | null;
|
|
14
|
+
address: string;
|
|
15
|
+
geometry: { type: "Polygon"; coordinates: number[][][] };
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** Знаходить доступні заявки за номером або адресою та повертає геометрію для наближення карти. */
|
|
19
|
+
export async function searchApplications(
|
|
20
|
+
{ input, user, ctx }: { input: ApplicationSearchInput; user: User | undefined; ctx: AppContext }
|
|
21
|
+
): Promise<{ total: number; page: number; count: number; data: ApplicationSearchResult[] }> {
|
|
22
|
+
actor(user);
|
|
23
|
+
|
|
24
|
+
const search = input.search.trim();
|
|
25
|
+
const page = input.page ?? 1;
|
|
26
|
+
const limit = input.limit ?? 20;
|
|
27
|
+
|
|
28
|
+
const surveyorId = user?.type === "admin" ? null : await surveyorForUser({ db: ctx.pg, user });
|
|
29
|
+
const pattern = `%${search.replace(/[\\%_]/g, "\\$&")}%`;
|
|
30
|
+
|
|
31
|
+
const fromWhere = `FROM surveyor.applications AS a
|
|
32
|
+
LEFT JOIN surveyor.address_lookup AS address ON address.addr_id = a.address_id
|
|
33
|
+
LEFT JOIN surveyor.organization_surveyors AS os
|
|
34
|
+
ON os.org_id = a.org_id
|
|
35
|
+
AND os.surveyor_id = $2
|
|
36
|
+
AND os.enabled = true
|
|
37
|
+
WHERE (
|
|
38
|
+
a.number ILIKE $1 ESCAPE '\\'
|
|
39
|
+
OR concat_ws(', ', NULLIF(address.address_text, ''), NULLIF(a.location, '')) ILIKE $1 ESCAPE '\\'
|
|
40
|
+
)
|
|
41
|
+
AND ($2::text IS NULL OR os.surveyor_id IS NOT NULL)
|
|
42
|
+
AND ($3::text IS NULL OR a.status::text = $3)`;
|
|
43
|
+
|
|
44
|
+
const values = [pattern, surveyorId, input.filter ?? null];
|
|
45
|
+
|
|
46
|
+
const totals = await ctx.pg.query<{ total: string }>(
|
|
47
|
+
`SELECT COUNT(*) AS total ${fromWhere}`,
|
|
48
|
+
values
|
|
49
|
+
);
|
|
50
|
+
const total = Number(totals.rows[0]?.total ?? 0);
|
|
51
|
+
|
|
52
|
+
const result = await ctx.pg.query<ApplicationSearchResult>(
|
|
53
|
+
`SELECT a.app_id AS id, a.number,
|
|
54
|
+
concat_ws(', ', NULLIF(address.address_text, ''), NULLIF(a.location, '')) AS address,
|
|
55
|
+
ST_AsGeoJSON(a.geom)::json AS geometry
|
|
56
|
+
${fromWhere}
|
|
57
|
+
ORDER BY (lower(a.number) = lower($4)) DESC NULLS LAST, a.number, a.app_id
|
|
58
|
+
LIMIT $5 OFFSET $6`,
|
|
59
|
+
[...values, search, limit, (page - 1) * limit]
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
return { total, page, count: result.rows.length, data: result.rows };
|
|
63
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { AppContext, User } from "@opengis/fcore";
|
|
2
|
+
import { ForbiddenError } from "@opengis/fcore";
|
|
3
|
+
import {
|
|
4
|
+
actor,
|
|
5
|
+
applicationUpdateFailed,
|
|
6
|
+
assertStatus,
|
|
7
|
+
attachedFile,
|
|
8
|
+
audit,
|
|
9
|
+
history,
|
|
10
|
+
readApplication,
|
|
11
|
+
surveyorForUser,
|
|
12
|
+
type Db,
|
|
13
|
+
} from "../utils/shared.js";
|
|
14
|
+
import type { FileInput } from "../utils/application.js";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Приймає матеріали знімання від автора заявки та передає її на перевірку.
|
|
18
|
+
* Попередню версію файлу зберігає в історії статусів.
|
|
19
|
+
* @param params Заявка, файл, геодезист і контекст FCore.
|
|
20
|
+
* @returns Статус `underReview` і шлях актуального файлу.
|
|
21
|
+
*/
|
|
22
|
+
export async function submitSurvey(
|
|
23
|
+
{ id, input, user, ctx }: {
|
|
24
|
+
id: string;
|
|
25
|
+
input: FileInput;
|
|
26
|
+
user: User | undefined;
|
|
27
|
+
ctx: AppContext;
|
|
28
|
+
}
|
|
29
|
+
) {
|
|
30
|
+
const uid = actor(user);
|
|
31
|
+
const file = await attachedFile({ ctx, appId: id, filePath: input.file_path });
|
|
32
|
+
const result = await ctx.pg.transaction(async (db: Db) => {
|
|
33
|
+
const app = await readApplication({ db, id });
|
|
34
|
+
assertStatus({ app, status: "dataIssued" });
|
|
35
|
+
const surveyorId = await surveyorForUser({ db, user });
|
|
36
|
+
if (app.surveyor_id !== surveyorId) {
|
|
37
|
+
throw new ForbiddenError("Only the application surveyor may submit data");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const updated = await db.query<{ app_id: string }>(
|
|
41
|
+
`UPDATE surveyor.applications
|
|
42
|
+
SET file_geodetic_survey = $2,
|
|
43
|
+
survey_uploaded_at = now(),
|
|
44
|
+
status = 'underReview',
|
|
45
|
+
updated_by = $3,
|
|
46
|
+
updated_at = now()
|
|
47
|
+
WHERE app_id = $1
|
|
48
|
+
AND status = 'dataIssued'
|
|
49
|
+
AND surveyor_id = $4
|
|
50
|
+
AND file_geodetic_survey IS NOT DISTINCT FROM $5
|
|
51
|
+
RETURNING app_id`,
|
|
52
|
+
[id, file, uid, surveyorId, app.file_geodetic_survey]
|
|
53
|
+
);
|
|
54
|
+
if (!updated.rows[0]) {
|
|
55
|
+
await applicationUpdateFailed({ db, id, status: "dataIssued" });
|
|
56
|
+
}
|
|
57
|
+
await history({
|
|
58
|
+
db,
|
|
59
|
+
appId: id,
|
|
60
|
+
from: "dataIssued",
|
|
61
|
+
to: "underReview",
|
|
62
|
+
by: uid,
|
|
63
|
+
reason: input.note,
|
|
64
|
+
file: app.file_geodetic_survey ?? file,
|
|
65
|
+
});
|
|
66
|
+
return { id, status: "underReview", survey_file_path: file };
|
|
67
|
+
});
|
|
68
|
+
await audit({ ctx, action: "submitSurvey", appId: id, uid });
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { AppContext, User } from "@opengis/fcore";
|
|
2
|
+
import { BadRequestError, NotFoundError } from "@opengis/fcore";
|
|
3
|
+
import { admin } from "../utils/shared.js";
|
|
4
|
+
|
|
5
|
+
export type SurveyorAccountStatusInput = { enabled: boolean };
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Повністю блокує або розблоковує обліковий запис геодезиста (`surveyors.enabled`)
|
|
9
|
+
* та записує автора і значення зміни в аудит FCore. Членство в організаціях не змінюється.
|
|
10
|
+
*/
|
|
11
|
+
export async function updateSurveyorAccountStatus(
|
|
12
|
+
{ id, input, user, ctx }: {
|
|
13
|
+
id: string;
|
|
14
|
+
input: SurveyorAccountStatusInput;
|
|
15
|
+
user: User | undefined;
|
|
16
|
+
ctx: AppContext;
|
|
17
|
+
}
|
|
18
|
+
) {
|
|
19
|
+
const uid = admin(user);
|
|
20
|
+
if (typeof input.enabled !== "boolean") {
|
|
21
|
+
throw new BadRequestError("Enabled must be a boolean");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const updated = await ctx.pg.query<{ surveyor_id: string }>(
|
|
25
|
+
`UPDATE surveyor.surveyors
|
|
26
|
+
SET enabled = $2, updated_by = $3, updated_at = now()
|
|
27
|
+
WHERE surveyor_id = $1 AND enabled <> $2
|
|
28
|
+
RETURNING surveyor_id`,
|
|
29
|
+
[id, input.enabled, uid]
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
if (!updated.rows[0]) {
|
|
33
|
+
const existing = await ctx.pg.query(
|
|
34
|
+
"SELECT 1 FROM surveyor.surveyors WHERE surveyor_id = $1",
|
|
35
|
+
[id]
|
|
36
|
+
);
|
|
37
|
+
if (!existing.rowCount) {
|
|
38
|
+
throw new NotFoundError("Surveyor not found");
|
|
39
|
+
}
|
|
40
|
+
} else {
|
|
41
|
+
await ctx.audit.write({
|
|
42
|
+
module: "surveyor",
|
|
43
|
+
resource: "surveyors",
|
|
44
|
+
resourceId: id,
|
|
45
|
+
action: input.enabled ? "unblock" : "block",
|
|
46
|
+
userId: uid,
|
|
47
|
+
fields: ["enabled"],
|
|
48
|
+
changes: [{ field: "enabled", oldValue: !input.enabled, newValue: input.enabled }],
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return { id, enabled: input.enabled };
|
|
52
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { AppContext, User } from "@opengis/fcore";
|
|
2
|
+
import { BadRequestError, NotFoundError } from "@opengis/fcore";
|
|
3
|
+
import { admin } from "../utils/shared.js";
|
|
4
|
+
|
|
5
|
+
export type SurveyorStatusInput = { org_id: string; enabled: boolean };
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Змінює доступ геодезиста до однієї організації (членство в `organization_surveyors`)
|
|
9
|
+
* та записує автора і значення зміни в аудит FCore. Обліковий запис геодезиста не змінюється.
|
|
10
|
+
*/
|
|
11
|
+
export async function updateSurveyorStatus(
|
|
12
|
+
{ id, input, user, ctx }: {
|
|
13
|
+
id: string;
|
|
14
|
+
input: SurveyorStatusInput;
|
|
15
|
+
user: User | undefined;
|
|
16
|
+
ctx: AppContext;
|
|
17
|
+
}
|
|
18
|
+
) {
|
|
19
|
+
const uid = admin(user);
|
|
20
|
+
if (typeof input.enabled !== "boolean") {
|
|
21
|
+
throw new BadRequestError("Enabled must be a boolean");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const updated = await ctx.pg.query<{ surveyor_id: string }>(
|
|
25
|
+
`UPDATE surveyor.organization_surveyors
|
|
26
|
+
SET enabled = $3
|
|
27
|
+
WHERE org_id = $1 AND surveyor_id = $2 AND enabled <> $3
|
|
28
|
+
RETURNING surveyor_id`,
|
|
29
|
+
[input.org_id, id, input.enabled]
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
if (!updated.rows[0]) {
|
|
33
|
+
const existing = await ctx.pg.query(
|
|
34
|
+
"SELECT 1 FROM surveyor.organization_surveyors WHERE org_id = $1 AND surveyor_id = $2",
|
|
35
|
+
[input.org_id, id]
|
|
36
|
+
);
|
|
37
|
+
if (!existing.rowCount) {
|
|
38
|
+
throw new NotFoundError("Surveyor is not a member of this organization");
|
|
39
|
+
}
|
|
40
|
+
} else {
|
|
41
|
+
await ctx.audit.write({
|
|
42
|
+
module: "surveyor",
|
|
43
|
+
resource: "surveyors",
|
|
44
|
+
resourceId: id,
|
|
45
|
+
action: input.enabled ? "enable" : "disable",
|
|
46
|
+
userId: uid,
|
|
47
|
+
fields: ["enabled"],
|
|
48
|
+
changes: [{ field: "enabled", oldValue: !input.enabled, newValue: input.enabled }],
|
|
49
|
+
metadata: { org_id: input.org_id },
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
return { id, org_id: input.org_id, enabled: input.enabled };
|
|
53
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { AppContext, User } from "@opengis/fcore";
|
|
2
|
+
import { BadRequestError } from "@opengis/fcore";
|
|
3
|
+
import { accessibleApplication } from "../utils/accessibleApplication.js";
|
|
4
|
+
import { exportSrid, type ExportOptions, type GeoJSONFeatureCollection } from "../utils/export.js";
|
|
5
|
+
import { vectorLayer } from "../utils/vectorLayer.js";
|
|
6
|
+
|
|
7
|
+
export type VectorExportInput = ExportOptions & { layer_id: string; buffer?: number };
|
|
8
|
+
|
|
9
|
+
/** Експортує об'єкти шару, обрізані буфером доступної користувачу заявки. */
|
|
10
|
+
export async function vectorExport({
|
|
11
|
+
id,
|
|
12
|
+
input,
|
|
13
|
+
user,
|
|
14
|
+
ctx,
|
|
15
|
+
}: {
|
|
16
|
+
id: string;
|
|
17
|
+
input: VectorExportInput;
|
|
18
|
+
user: User | undefined;
|
|
19
|
+
ctx: AppContext;
|
|
20
|
+
}): Promise<GeoJSONFeatureCollection> {
|
|
21
|
+
const app = await accessibleApplication({ id, user, ctx });
|
|
22
|
+
const srid = exportSrid(input);
|
|
23
|
+
const { layer_id: layer, buffer = 100 } = input;
|
|
24
|
+
|
|
25
|
+
if (!layer?.trim()) {
|
|
26
|
+
throw new BadRequestError("Layer ID is required");
|
|
27
|
+
}
|
|
28
|
+
if (!Number.isFinite(buffer) || buffer < 0) {
|
|
29
|
+
throw new BadRequestError("Buffer must be a non-negative number");
|
|
30
|
+
}
|
|
31
|
+
if (!app.geometry) {
|
|
32
|
+
throw new BadRequestError(`Application geometry not found: ${id}`);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const { table, query } = await vectorLayer({ layer, ctx });
|
|
36
|
+
|
|
37
|
+
if (!/^[A-Za-z_][A-Za-z0-9_$]*(\.[A-Za-z_][A-Za-z0-9_$]*)?$/.test(table)) {
|
|
38
|
+
throw new BadRequestError("Invalid layer table name");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const quotedTable = table
|
|
42
|
+
.split(".")
|
|
43
|
+
.map((part) => `"${part}"`)
|
|
44
|
+
.join(".");
|
|
45
|
+
|
|
46
|
+
const tables = await ctx.pg.query<{ exists: boolean; has_geometry: boolean }>(
|
|
47
|
+
`SELECT to_regclass($1) IS NOT NULL AS exists,
|
|
48
|
+
EXISTS (SELECT 1 FROM pg_attribute
|
|
49
|
+
WHERE attrelid = to_regclass($1) AND attname = 'geom' AND NOT attisdropped) AS has_geometry`,
|
|
50
|
+
[quotedTable]
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
if (!tables.rows[0]?.exists) {
|
|
54
|
+
throw new BadRequestError(`Layer table does not exist: ${table}`);
|
|
55
|
+
}
|
|
56
|
+
if (!tables.rows[0].has_geometry) {
|
|
57
|
+
throw new BadRequestError(`Layer table has no geometry column: ${table}`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Умова з каталогу застосовується лише до таблиці шару, перед просторовим перетином.
|
|
61
|
+
const source = query ? `(SELECT * FROM ${quotedTable} t WHERE (${query}))` : quotedTable;
|
|
62
|
+
const result = await ctx.pg.query<{ geojson: GeoJSONFeatureCollection | null }>(
|
|
63
|
+
`WITH boundary AS (
|
|
64
|
+
SELECT ST_Buffer(ST_Transform(geom, 3857), $2) AS geom
|
|
65
|
+
FROM surveyor.applications WHERE app_id = $1
|
|
66
|
+
)
|
|
67
|
+
SELECT jsonb_build_object(
|
|
68
|
+
'type', 'FeatureCollection',
|
|
69
|
+
'crs', jsonb_build_object('type', 'name', 'properties', jsonb_build_object('name', 'EPSG:' || $3::text)),
|
|
70
|
+
'features', jsonb_agg(jsonb_build_object(
|
|
71
|
+
'type', 'Feature',
|
|
72
|
+
'geometry', ST_AsGeoJSON(ST_Transform(ST_Intersection(ST_Transform(t.geom, 3857), boundary.geom), $3::integer))::jsonb,
|
|
73
|
+
'properties', to_jsonb(t) - 'geom'
|
|
74
|
+
))
|
|
75
|
+
) AS geojson
|
|
76
|
+
FROM ${source} t CROSS JOIN boundary
|
|
77
|
+
WHERE ST_Intersects(ST_Transform(t.geom, 3857), boundary.geom)`,
|
|
78
|
+
[id, buffer, srid]
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
const geojson = result.rows[0]?.geojson;
|
|
82
|
+
if (!geojson?.features?.length) {
|
|
83
|
+
throw new BadRequestError("No features found in the selected layer");
|
|
84
|
+
}
|
|
85
|
+
return geojson;
|
|
86
|
+
}
|