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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .project-context/16-current-state.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ Snapshot of `dev` after per-stage customer notifications (#129, 2026-10-06). Mer
- Production 3, #214 (people): `/api/admin/users` in user-service: list (name prefix, role, status, verification, dates), exact phone/email search by POST, and detail. The account side comes from auth-service's internal SYSTEM route; `credentials.lastLoginAt` is set on sign-in.
- Production 3, #214 (drivers): `/api/admin/drivers` in driver-service: the list (status, verification, licences expiring, plate prefix), the review queue (`onboarding.review`) and the driver page with the ledger balance and rating from delivery-service's internal route. Names come from user-service's names-only internal route.
- Production 3, #214 (restaurants): `/api/admin/restaurants` in restaurant-service: the list (approval, status, name prefix, area), the review queue, the exact phone search (POST) and the restaurant page with owner, menu counts and today's orders (order-service internal route, Cairo day). The person page links drivers and owners to their records.
- Production 3, #317: staff views mask phone and email and withhold addresses (owner decision); `POST /api/admin/users/:id/reveal` and `/api/admin/restaurants/:id/reveal` return one value and record `pii.reveal`.
- Production 3, #215: staff actions, all audited in the same transaction and each telling the person through the same `admin.actions` event (notification-service, `ACCOUNT_UPDATE`): driver and restaurant review, suspend and reactivate (`/api/admin/drivers|restaurants/:id/...`; a BUSY driver finishes the delivery first), and account suspend, reactivate and sign-out-everywhere (`/api/admin/auth/users/:id/...`). A suspended restaurant disappears from customers (owner decision). The old staff routes are deprecated for one release.
- Production 3, #216: staff accounts by invitation (`/api/admin/auth/staff`, `staff.manage`): email invite with a single-use 48 h link, acceptance with a 12+ character password and exactly the invited permissions, permission changes (applied at the next refresh), disable/enable, role templates; nobody removes their own `staff.manage` and the last super admin stays. All audited.

Expand Down
167 changes: 167 additions & 0 deletions docs/openapi/admin.json
Original file line number Diff line number Diff line change
Expand Up @@ -504,6 +504,94 @@
}
}
},
"/api/admin/users/{id}/reveal": {
"post": {
"summary": "Reveal one of a person's masked values; audited as pii.reveal (staff with support.read)",
"description": "Requires staff permission: support.read.",
"tags": [
"users"
],
"operationId": "admin_users_post_api_admin_users_id_reveal",
"security": [
{
"bearerAuth": []
}
],
"x-permissions": [
"support.read"
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
}
}
],
"responses": {
"200": {
"description": "The resource",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"400": {
"description": "Invalid parameters or body",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
}
},
"401": {
"description": "Missing or invalid JWT, or a SYSTEM token on an admin route"
},
"403": {
"description": "Staff token without the required permission"
}
},
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"field",
"reason"
],
"properties": {
"field": {
"type": "string",
"enum": [
"phone",
"email",
"address"
]
},
"reason": {
"type": "string",
"minLength": 3,
"maxLength": 300,
"description": "Why, for the audit log."
}
}
}
}
}
},
"x-audit-action": "pii.reveal"
}
},
"/api/admin/drivers": {
"get": {
"summary": "List drivers: status, verification, licences expiring, plate prefix (staff with support.read)",
Expand Down Expand Up @@ -1713,6 +1801,85 @@
"x-audit-action": "restaurant.reactivate"
}
},
"/api/admin/restaurants/{id}/reveal": {
"post": {
"summary": "Reveal a restaurant's masked contact phone; audited as pii.reveal (staff with support.read)",
"description": "Requires staff permission: support.read.",
"tags": [
"restaurants"
],
"operationId": "admin_restaurants_post_api_admin_restaurants_id_reveal",
"security": [
{
"bearerAuth": []
}
],
"x-permissions": [
"support.read"
],
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"schema": {
"type": "string",
"format": "uuid"
}
}
],
"responses": {
"200": {
"description": "The resource",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
},
"400": {
"description": "Invalid parameters or body",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ErrorResponse"
}
}
}
},
"401": {
"description": "Missing or invalid JWT, or a SYSTEM token on an admin route"
},
"403": {
"description": "Staff token without the required permission"
}
},
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"required": [
"reason"
],
"properties": {
"reason": {
"type": "string",
"minLength": 3,
"maxLength": 300,
"description": "Why, for the audit log."
}
}
}
}
}
},
"x-audit-action": "pii.reveal"
}
},
"/api/admin/auth/users/{id}/suspend": {
"post": {
"summary": "Suspend an account and end its sessions (staff with users.manage)",
Expand Down
2 changes: 2 additions & 0 deletions docs/roadmap/production.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,8 @@ done
- **Partial refunds (#219):** not in M4. Staff refunds are full refunds only; partial refunds come with the real payment gateway in M6 (#224).
- **Finance read APIs (#220):** order-service owns `/admin/finance/*` and gets payment and ledger aggregates from payment- and delivery-service over internal routes (ADR 001). No money math in the admin app.
- **Suspended restaurants (#215):** disappear from customers at once (left out of the list, 404 by id); `BUSY` and `CLOSED` stay visible. `docs/business/restaurant-availability.md`.
- **Personal data for staff (#317):** masked by default; each reveal is its own call and is audited (`pii.reveal`).
- **Undo in the review queues (#318):** a second, audited action within 10 seconds, never a delete.
- **Search by phone or email (#217, #214):** a `POST .../search` with the value in the body, never in the URL or a log; exact match after normalising (E.164 phone, lowercased email).

**Still needed, before the milestone shown**
Expand Down
1 change: 1 addition & 0 deletions docs/services/restaurant-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ Published as `/api/admin/restaurants`:
| `GET /admin/restaurants/:id` | `support.read` | The staff application view with its reviews, the row with the owner's name, the menu counts (`categories`, `availableItems`, from the public menu) and today's orders (order-service, Cairo day). |

- Owners' names come from user-service's names-only internal route. A part whose service doesn't answer is null.
- The contact phone is masked in every staff view (#317); `POST /admin/restaurants/:id/reveal` `{reason}` (`support.read`) returns it and records `pii.reveal`. The owner's own view keeps it.
- `GET /internal/restaurants/by-owner/:ownerId` (SYSTEM, user-service only) links an owner account to its restaurants on the staff person page.
- Needs `USER_SERVICE_URL` and `ORDER_SERVICE_URL`.

Expand Down
2 changes: 1 addition & 1 deletion docs/services/user-service.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ Profiles live here; the account side (role, status, email verified, suspension,
- profile filters only, or none: user-service pages and auth-service adds the accounts;
- both: the profile filters give an id set (at most 1000; more is a 400 asking staff to narrow it), and auth-service pages within it.

The staff view may carry phone, email and address (the admin app masks them by default) and never hashes, codes or tokens (snapshot-tested).
The staff view never carries hashes, codes or tokens (snapshot-tested). **Personal data is masked** (#317, owner decision): the phone as `+20 10•• ••• 123`, the email as `m•••@example.com`, and the address withheld (`hasAddress`). `POST /admin/users/:id/reveal` `{field: phone|email|address, reason}` (`support.read`) returns one value and records a `pii.reveal` audit event: who saw which field of whom, never the value. Search still matches the full value; its results come back masked.

## Dependencies
- Calls `order-service` to fetch order history via `src/common/order-service.client.ts`
Expand Down
2 changes: 2 additions & 0 deletions services/api-gateway/src/main.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,8 @@ describe('admin OpenAPI contract (#212)', () => {
'POST /api/admin/restaurants/{id}/reactivate -> restaurant.reactivate',
'POST /api/admin/restaurants/{id}/review -> restaurant.approve',
'POST /api/admin/restaurants/{id}/suspend -> restaurant.suspend',
'POST /api/admin/restaurants/{id}/reveal -> pii.reveal',
'POST /api/admin/users/{id}/reveal -> pii.reveal',
].sort(),
);
});
Expand Down
33 changes: 33 additions & 0 deletions services/api-gateway/src/public-openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,23 @@
statusCode: 200,
response: 'object',
},
{
method: 'post',
path: '/{id}/reveal',
summary: "Reveal one of a person's masked values; audited as pii.reveal (staff with support.read)",
permissions: ['support.read'],
statusCode: 200,
response: 'object',
auditAction: 'pii.reveal',
requestBody: {
type: 'object',
required: ['field', 'reason'],
properties: {
field: { type: 'string', enum: ['phone', 'email', 'address'] },
reason: { type: 'string', minLength: 3, maxLength: 300, description: 'Why, for the audit log.' },
},
},
},
],
},
{
Expand Down Expand Up @@ -535,6 +552,22 @@
},
},
},
{
method: 'post',
path: '/{id}/reveal',
summary: "Reveal a restaurant's masked contact phone; audited as pii.reveal (staff with support.read)",
permissions: ['support.read'],
statusCode: 200,
response: 'object',
auditAction: 'pii.reveal',
requestBody: {
type: 'object',
required: ['reason'],
properties: {
reason: { type: 'string', minLength: 3, maxLength: 300, description: 'Why, for the audit log.' },
},
},
},
],
},
{
Expand Down Expand Up @@ -1474,7 +1507,7 @@
},
servers: [{ url: 'http://localhost:3000' }],
tags: SERVICE_DEFINITIONS.map(({ service }) => ({ name: service, description: `${service} service endpoints` })),
paths: {} as Record<string, Record<string, any>>,

Check warning on line 1510 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Test and build

Unexpected any. Specify a different type

Check warning on line 1510 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Lint, build, unit tests

Unexpected any. Specify a different type
components: {
securitySchemes: {
bearerAuth: {
Expand All @@ -1492,7 +1525,7 @@
const pathKey = joinPublicPath(service.publicPrefix, route.path);
const operationId = `${service.service}_${route.method}_${pathKey.replace(/[/:{}-]+/g, '_').replace(/^_+|_+$/g, '')}`;

const operation: Record<string, any> = {

Check warning on line 1528 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Test and build

Unexpected any. Specify a different type

Check warning on line 1528 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Lint, build, unit tests

Unexpected any. Specify a different type
summary: route.summary,
tags: [service.service],
operationId,
Expand Down Expand Up @@ -2098,7 +2131,7 @@
}

export function validatePublicOpenApiDocument(
doc: Record<string, any>,

Check warning on line 2134 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Test and build

Unexpected any. Specify a different type

Check warning on line 2134 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Lint, build, unit tests

Unexpected any. Specify a different type
servicePrefixes: readonly string[] = SERVICE_PREFIXES,
options: { forbidAdmin?: boolean } = {},
): void {
Expand Down Expand Up @@ -2136,18 +2169,18 @@
seenOperationIds.add(operation.operationId);

const parameterList = Array.isArray(operation.parameters) ? operation.parameters : [];
const declaredPathParams = parameterList.filter((parameter: any) => parameter && parameter.in === 'path');

Check warning on line 2172 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Test and build

Unexpected any. Specify a different type

Check warning on line 2172 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Lint, build, unit tests

Unexpected any. Specify a different type

const missing = expectedParameters.filter((name) => !declaredPathParams.some((parameter: any) => parameter.name === name));

Check warning on line 2174 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Test and build

Unexpected any. Specify a different type

Check warning on line 2174 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Lint, build, unit tests

Unexpected any. Specify a different type
assert(
missing.length === 0,
`Path ${path} is missing required OpenAPI path parameter definitions for: ${missing.join(', ')}`,
);

const unused = declaredPathParams.filter((parameter: any) => !expectedParameters.includes(parameter.name));

Check warning on line 2180 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Test and build

Unexpected any. Specify a different type

Check warning on line 2180 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Lint, build, unit tests

Unexpected any. Specify a different type
assert(
unused.length === 0,
`Path ${path} declares unused path parameters: ${unused.map((parameter: any) => parameter.name).join(', ')}`,

Check warning on line 2183 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Test and build

Unexpected any. Specify a different type

Check warning on line 2183 in services/api-gateway/src/public-openapi.ts

View workflow job for this annotation

GitHub Actions / Lint, build, unit tests

Unexpected any. Specify a different type
);

for (const parameter of declaredPathParams) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Body, Controller, Get, HttpCode, HttpStatus, Param, ParseUUIDPipe, Post, Query, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard, PermissionsGuard, RateLimitGuard, RequirePermissions } from '@food-delivery/shared';
import { CurrentUser, JwtAuthGuard, JwtPayload, PermissionsGuard, RateLimitGuard, RequirePermissions } from '@food-delivery/shared';
import { AdminRestaurantsService } from '../services/admin-restaurants.service';
import { AdminListRestaurantsQueryDto, AdminRestaurantQueueQueryDto, AdminSearchRestaurantsDto } from '../dto/admin-restaurants.dto';
import { AdminRestaurantReasonDto } from '../dto/admin-restaurant-actions.dto';

/** #214: staff restaurant lists and the restaurant page, published as /api/admin/restaurants. */
@ApiTags('admin')
Expand Down Expand Up @@ -36,6 +37,15 @@ export class AdminRestaurantsController {
return this.restaurants.search(dto.phone);
}

/** #317: the masked contact phone, shown to this staff member and recorded in the audit log. */
@Post(':id/reveal')
@HttpCode(HttpStatus.OK)
@RequirePermissions('support.read')
@ApiOperation({ summary: "Reveal a restaurant's contact phone; audited (support.read)" })
reveal(@Param('id', new ParseUUIDPipe()) id: string, @Body() dto: AdminRestaurantReasonDto, @CurrentUser() user: JwtPayload) {
return this.restaurants.revealContactPhone({ id: user.sub, email: user.email ?? null }, id, dto.reason);
}

@Get(':id')
@RequirePermissions('support.read')
@ApiOperation({ summary: "One restaurant: application, reviews, owner, menu counts and today's orders (support.read)" })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@ const restaurant = (id: string, ownerId: string) => ({
});

const setup = () => {
const restaurants = { findForAdmin: jest.fn(), findByContactPhone: jest.fn(), findById: jest.fn() };
const manager = { query: jest.fn().mockResolvedValue([]) };
const restaurants = { findForAdmin: jest.fn(), findByContactPhone: jest.fn(), findById: jest.fn(), transaction: jest.fn((work: (m: unknown) => unknown) => work(manager)), manager };
const restaurantsService = { getApplicationForStaff: jest.fn() };
const menu = { menuReadiness: jest.fn() };
const lookups = { names: jest.fn(), ordersToday: jest.fn() };
const outbox = { kick: jest.fn() };
return {
service: new AdminRestaurantsService(restaurants as never, restaurantsService as never, menu as never, lookups as never),
service: new AdminRestaurantsService(restaurants as never, restaurantsService as never, menu as never, lookups as never, outbox as never),
restaurants,
restaurantsService,
menu,
Expand Down Expand Up @@ -73,4 +75,18 @@ describe('AdminRestaurantsService (#214)', () => {
lookups.ordersToday.mockResolvedValueOnce(null);
await expect(service.detail('r1')).resolves.toMatchObject({ menu: null, ordersToday: null });
});

it('masks the contact phone in staff rows, and reveals it with one audit event (#317)', async () => {
const { service, restaurants, lookups } = setup();
restaurants.findByContactPhone.mockResolvedValue([restaurant('r1', 'o1')]);
lookups.names.mockResolvedValue(new Map());
expect((await service.search('+201011111111')).items[0].contactPhone).toBe('+20 10•• ••• 111');

restaurants.findById.mockResolvedValue(restaurant('r1', 'o1'));
await expect(service.revealContactPhone({ id: 'staff-1' }, 'r1', 'Calling the owner')).resolves.toEqual({ field: 'contactPhone', value: '+201011111111' });
const [, params] = restaurants.manager.query.mock.calls[0];
expect(JSON.parse(params[2]).payload).toMatchObject({ action: 'pii.reveal', targetType: 'RESTAURANT', after: { field: 'contactPhone' } });
expect(params[2]).not.toContain('1011111111');
});
});

Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Injectable } from '@nestjs/common';
import { PaginatedResult } from '@food-delivery/shared';
import { AdminAudit, AuditActor, maskPhone, NotFoundError, PaginatedResult } from '@food-delivery/shared';
import { OutboxRelayService } from '../common/outbox.module';
import { RestaurantsRepository } from '../repositories/restaurants.repository';
import { Restaurant } from '../entities/restaurant.entity';
import { MenuReadiness, MenuServiceClient } from '../common/menu-service.client';
Expand Down Expand Up @@ -44,8 +45,29 @@ export class AdminRestaurantsService {
private readonly restaurantsService: RestaurantsService,
private readonly menu: MenuServiceClient,
private readonly lookups: StaffLookupsClient,
private readonly outbox: OutboxRelayService,
) {}

/** #317: the contact phone of one restaurant, recorded as a `pii.reveal` audit event (never the value). */
async revealContactPhone(actor: AuditActor, id: string, reason: string): Promise<{ field: 'contactPhone'; value: string | null }> {
const restaurant = await this.restaurants.findById(id);
if (!restaurant) throw new NotFoundError(`Restaurant ${id} not found`);
await this.restaurants.transaction((manager) =>
AdminAudit.record(manager, {
actor,
permission: 'support.read',
action: 'pii.reveal',
targetType: 'RESTAURANT',
targetId: id,
reason,
after: { field: 'contactPhone' },
service: 'restaurant-service',
}),
);
this.outbox.kick();
return { field: 'contactPhone', value: restaurant.contactPhone ?? null };
}

async list(query: AdminListRestaurantsQueryDto): Promise<PaginatedResult<StaffRestaurantRow>> {
const near =
query.nearLat !== undefined && query.nearLng !== undefined && query.withinKm !== undefined
Expand Down Expand Up @@ -98,7 +120,8 @@ const toRow = (restaurant: Restaurant, names: Map<string, string> | null): Staff
latitude: restaurant.latitude,
longitude: restaurant.longitude,
deliveryRadiusKm: restaurant.deliveryRadiusKm,
contactPhone: restaurant.contactPhone ?? null,
// #317 (owner decision): masked; POST /admin/restaurants/:id/reveal shows it, audited.
contactPhone: maskPhone(restaurant.contactPhone),
submittedAt: restaurant.submittedAt,
approvedAt: restaurant.approvedAt,
createdAt: restaurant.createdAt,
Expand Down
Loading
Loading