Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cbe48c2db9 | ||
|
|
39139ed7b1 | ||
|
|
5e5762cdcb | ||
|
|
41c616b3f6 | ||
|
|
ff4b12c2e9 | ||
|
|
3ab1a0e0e3 | ||
|
|
5583cf5897 | ||
|
|
03b85737d7 |
No files matched your search
@@ -112,6 +112,12 @@ Run the three in order before the new images go live: the new services-counter w
|
||||
|
||||
Run both before the new images go live: the new services-counter reads the new `event_lead` columns on every lead query and fails without them. Both need a user that may create tables. `99-rollback.sql` in the same folder undoes them and deletes the codes, the notices and the consent records.
|
||||
|
||||
| File | What it does |
|
||||
|---|---|
|
||||
| `openspec/changes/archive/2026-12-01-uppercase-company-codes/sql/01-uppercase-codes.sql` | Turns every company code and every staff login name to capitals (`ins` becomes `INS`, `sales9@cv` becomes `sales9@CV`). Safe to run twice. |
|
||||
|
||||
Run it when the new services-system and mobile-api go live. Staff who are signed in keep working until their session needs a refresh, then sign in again. Sign-in still ignores case, so staff may keep typing `ins` or `cv`. `99-rollback.sql` in the same folder turns codes and login names back to lowercase.
|
||||
|
||||
**Review the privacy notice before go-live.** The seeded text is a starting template written for the PDPA, not legal advice. INS and CV should each have theirs checked; a super admin changes it under **Companies → Privacy notice**. A company with no notice has no working QR codes.
|
||||
|
||||
**Database user:**
|
||||
|
||||
@@ -185,8 +185,8 @@ ALTER TABLE `company`
|
||||
ADD COLUMN `code` varchar(20) NULL AFTER `name`,
|
||||
ADD COLUMN `status` char(1) NOT NULL DEFAULT 'A' COMMENT 'A active, I inactive' AFTER `code`;
|
||||
|
||||
UPDATE `company` SET `name` = 'INS', `code` = 'ins' WHERE `id` = 1;
|
||||
INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'cv', 'A');
|
||||
UPDATE `company` SET `name` = 'INS', `code` = 'INS' WHERE `id` = 1;
|
||||
INSERT INTO `company` (`name`, `code`, `status`) VALUES ('CV', 'CV', 'A');
|
||||
|
||||
ALTER TABLE `company`
|
||||
MODIFY COLUMN `code` varchar(20) NOT NULL,
|
||||
@@ -226,7 +226,7 @@ DROP PROCEDURE `colite_check_admin_usernames`;
|
||||
UPDATE `user` u SET u.`company_id` = NULL
|
||||
WHERE u.`type` = 'A' AND EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
|
||||
|
||||
UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@ins')
|
||||
UPDATE `user` u SET u.`company_id` = 1, u.`username` = CONCAT(u.`username`, '@INS')
|
||||
WHERE u.`type` = 'A' AND NOT EXISTS (SELECT 1 FROM `users_roles` r WHERE r.`user_id` = u.`id` AND r.`role_id` = 1);
|
||||
|
||||
-- add-lead-dashboard/sql/01-status-change.sql (02 backfill has nothing to do on an empty volume)
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,2 @@
|
||||
schema: spec-driven
|
||||
created: 2026-12-01
|
||||
@@ -0,0 +1,27 @@
|
||||
## Why
|
||||
|
||||
Company codes are stored and shown in lowercase (`ins`, `cv`). The owner wants them in capitals (`INS`, `CV`), and the Companies screen cannot change `cv` to `CV`: the portal treats a case-only change as no change, and services-system lowercases every code it saves.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Company codes are stored and shown in capitals: 2 to 20 characters of `A-Z`, `0-9` and `-`. Any code entered is turned to capitals before it is checked and saved.
|
||||
- Sign-in keeps ignoring case: staff can type `cv`, `Cv` or `CV`.
|
||||
- Staff login names follow the code (`sales9@CV`).
|
||||
- A one-off SQL turns the existing codes and staff login names to capitals.
|
||||
|
||||
## Capabilities
|
||||
|
||||
### New Capabilities
|
||||
|
||||
None.
|
||||
|
||||
### Modified Capabilities
|
||||
|
||||
- `company-scoping`: the code format of the Companies requirement becomes capitals.
|
||||
|
||||
## Impact
|
||||
|
||||
- **services-system:** `CompanyService` code validation and normalisation.
|
||||
- **mobile-api:** the admin login builds the login name with the code in capitals.
|
||||
- **portal:** the Companies code fields show and send capitals. A case-only rename is no longer treated as no change.
|
||||
- **Data:** `sql/01-uppercase-codes.sql` on `service-system`. Signed-in staff must sign in again after it runs, as after any code change.
|
||||
@@ -0,0 +1,30 @@
|
||||
# Spec Delta
|
||||
|
||||
## MODIFIED Requirements
|
||||
|
||||
### Requirement: Companies
|
||||
|
||||
The system SHALL let a super admin list, create and edit companies, each with a name, a unique code and an active or inactive status. A code SHALL be 2 to 20 characters of capital letters, digits and hyphens. A code entered in any case SHALL be stored in capitals, and codes SHALL be compared ignoring case. Companies SHALL NOT be deletable. The Companies screen and its endpoints SHALL be available to super admins only.
|
||||
|
||||
#### Scenario: Create a company
|
||||
|
||||
- **WHEN** a super admin creates company `CV` with code `cv`
|
||||
- **THEN** it is listed as active with code `CV`
|
||||
- **AND** staff can be created in it
|
||||
|
||||
#### Scenario: Duplicate code
|
||||
|
||||
- **GIVEN** a company with code `INS`
|
||||
- **WHEN** a super admin creates or renames another company to code `ins`
|
||||
- **THEN** the save is refused and the code is reported as taken
|
||||
|
||||
#### Scenario: Not a super admin
|
||||
|
||||
- **WHEN** company staff open the Companies page or call a companies endpoint
|
||||
- **THEN** the page shows not-authorised and the endpoint responds 403
|
||||
|
||||
#### Scenario: Sign-in ignores case
|
||||
|
||||
- **GIVEN** company code `CV` and its user `sales9`
|
||||
- **WHEN** they sign in with company `cv`
|
||||
- **THEN** they are signed in as `sales9` of CV
|
||||
@@ -0,0 +1,9 @@
|
||||
-- Co-Lite change uppercase-company-codes: company codes and staff login names in capitals.
|
||||
-- Target: `service-system`. Signed-in staff must sign in again afterwards. Idempotent.
|
||||
USE `service-system`;
|
||||
|
||||
UPDATE `user` u JOIN `company` c ON c.`id` = u.`company_id`
|
||||
SET u.`username` = CONCAT(SUBSTRING(u.`username`, 1, CHAR_LENGTH(u.`username`) - CHAR_LENGTH(c.`code`) - 1), '@', UPPER(c.`code`))
|
||||
WHERE u.`type` = 'A' AND u.`username` LIKE CONCAT('%@', c.`code`) AND BINARY u.`username` <> BINARY CONCAT(SUBSTRING(u.`username`, 1, CHAR_LENGTH(u.`username`) - CHAR_LENGTH(c.`code`) - 1), '@', UPPER(c.`code`));
|
||||
|
||||
UPDATE `company` SET `code` = UPPER(`code`) WHERE BINARY `code` <> BINARY UPPER(`code`);
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Co-Lite change uppercase-company-codes: rollback to lowercase codes and login names.
|
||||
USE `service-system`;
|
||||
|
||||
UPDATE `user` u JOIN `company` c ON c.`id` = u.`company_id`
|
||||
SET u.`username` = CONCAT(SUBSTRING(u.`username`, 1, CHAR_LENGTH(u.`username`) - CHAR_LENGTH(c.`code`) - 1), '@', LOWER(c.`code`))
|
||||
WHERE u.`type` = 'A' AND u.`username` LIKE CONCAT('%@', c.`code`);
|
||||
|
||||
UPDATE `company` SET `code` = LOWER(`code`);
|
||||
@@ -0,0 +1,33 @@
|
||||
# Tasks
|
||||
|
||||
Serial. One implementer, in this session.
|
||||
|
||||
## 1. Data
|
||||
|
||||
- [x] 1.1 `sql/01-uppercase-codes.sql` and `sql/99-rollback.sql`; change the codes in `local/seed/03-colite.sql` to `INS` and `CV` (the `@ins` login names it builds follow); apply 01 to the local database.
|
||||
- Depends on: none
|
||||
- Scope: `local/seed/**`, `openspec/changes/uppercase-company-codes/sql/**`
|
||||
- Verify: `SELECT code FROM company` gives `INS`, `CV`; staff login names end in `@INS` or `@CV`.
|
||||
|
||||
## 2. Backend
|
||||
|
||||
- [x] 2.1 services-system `CompanyService` stores codes in capitals (`^[A-Z0-9-]{2,20}$`, entered value trimmed and turned to capitals); mobile-api admin login and forgot-password build the login name with the code in capitals.
|
||||
- Depends on: 1.1
|
||||
- Tests first: create with `cv` stores `CV`; rename `cv` to `CV` on a company whose code is `cv` succeeds; `ins` is taken when `INS` exists; an invalid code is refused; login with company `cv` looks up `user@CV`.
|
||||
- Scope: `solvway-services-system/src/**`, `solvway-mobile-api/src/**`
|
||||
- Verify: `mvn -T 1C -q -pl solvway-services-system,solvway-mobile-api verify`
|
||||
|
||||
## 3. Portal
|
||||
|
||||
- [x] 3.1 Companies: code inputs show capitals as typed and the rename compares case-sensitively, so `cv` to `CV` is a change.
|
||||
- Depends on: 2.1
|
||||
- Tests first: typing `cv` shows `CV`; renaming `cv` to `CV` sends the request.
|
||||
- Scope: `solvway-admin-portal/app/**`
|
||||
- Verify: `cd solvway-admin-portal && npm run lint; echo L=$?; npx tsc --noEmit; echo T=$?; npx vitest run; echo V=$?`
|
||||
|
||||
## 4. Release
|
||||
|
||||
- [x] 4.1 `docs/deployment.md` notes the SQL and that staff sign in again; Playwright: Companies shows `INS` and `CV`, sign in as `sales9` with company `cv` works.
|
||||
- Depends on: 3.1
|
||||
- Scope: `docs/deployment.md`, `openspec/changes/uppercase-company-codes/tasks.md`
|
||||
- Verify: the 2.1 and 3.1 verifies.
|
||||
@@ -0,0 +1,133 @@
|
||||
# qr-registration Specification
|
||||
|
||||
## Purpose
|
||||
|
||||
Walk-in visitors scan an event or salesperson QR code and register themselves as a lead, with recorded PDPA consent, abuse limits and staff tools to show, print and switch off codes.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Registration codes
|
||||
|
||||
The system SHALL give every event one registration code and one personal code per member of the event's team. A code SHALL be an unguessable token in a link of the form `/r/<token>`. Staff with `BO_EVENTS` SHALL see each code of an event of their company as a QR image, copy its link, download it as an image, and switch it off or on. Every staff user SHALL see their own personal codes for events of their company that have not ended.
|
||||
|
||||
#### Scenario: Event page codes
|
||||
|
||||
- **GIVEN** event `KL Expo` with `sales1` and `sales2` on its team
|
||||
- **WHEN** a user with `BO_EVENTS` opens the event
|
||||
- **THEN** the event's code and the personal codes of `sales1` and `sales2` are shown, each with its QR image and link
|
||||
|
||||
#### Scenario: Own codes
|
||||
|
||||
- **GIVEN** `sales1` is on the team of `KL Expo`, which ends tomorrow, and of `Penang Fair`, which ended last week
|
||||
- **WHEN** `sales1` opens My QR codes
|
||||
- **THEN** only the personal code for `KL Expo` is listed
|
||||
|
||||
#### Scenario: Switch a code off
|
||||
|
||||
- **WHEN** staff switch off the event code of `KL Expo`
|
||||
- **THEN** scanning that code shows that it is no longer active
|
||||
- **AND** the personal codes still work
|
||||
|
||||
### Requirement: When a code works
|
||||
|
||||
A code SHALL work only while it is switched on, its event is enabled, the event's end date in Malaysia time has not passed, and the event's company has a privacy notice. An inactive or unknown code SHALL show "This code is no longer active." and no event details. A personal code whose salesperson is no longer an active member of the event's team SHALL keep working, and its registrations SHALL have no salesperson.
|
||||
|
||||
#### Scenario: Ended event
|
||||
|
||||
- **GIVEN** `Penang Fair` ended yesterday
|
||||
- **WHEN** a visitor scans its code
|
||||
- **THEN** the page says the code is no longer active and shows no event details
|
||||
|
||||
#### Scenario: Salesperson left the team
|
||||
|
||||
- **GIVEN** `sales2` was removed from the team of `KL Expo`
|
||||
- **WHEN** a visitor registers through `sales2`'s code
|
||||
- **THEN** the registration succeeds and the event lead has no salesperson
|
||||
|
||||
### Requirement: Public registration
|
||||
|
||||
The registration page SHALL show the event's name, dates and location, and a form for name (required), mobile and email (at least one), company, job title, the company's active interests, and the privacy notice consent (required). Inputs SHALL be normalised and limited as in staff capture. Every accepted submission SHALL show the same thank-you page naming the event, with a button to register another person, whether or not the person was already known.
|
||||
|
||||
#### Scenario: Register
|
||||
|
||||
- **WHEN** a visitor scans the code of `KL Expo`, enters name `Aisyah`, mobile `012-345 6701` and ticks the consent
|
||||
- **THEN** the thank-you page names `KL Expo`
|
||||
- **AND** staff see `Aisyah` with mobile `+60123456701` in the event's leads as NEW and OPEN
|
||||
|
||||
#### Scenario: Missing consent or contact
|
||||
|
||||
- **WHEN** a visitor submits without ticking the consent, or without a mobile and an email
|
||||
- **THEN** nothing is saved and the page shows the error under the field
|
||||
|
||||
#### Scenario: Known person gets the same answer
|
||||
|
||||
- **GIVEN** a lead with mobile `+60123456701` exists in the company
|
||||
- **WHEN** a visitor registers with that mobile
|
||||
- **THEN** the page shows the same thank-you page as for a new person
|
||||
|
||||
### Requirement: Registration matching
|
||||
|
||||
A registration SHALL match a lead of the event's company by mobile first and then by email, the newest lead winning among several. A matched lead SHALL NOT be edited: it SHALL be linked as EXISTING, with every submitted value that differs from the lead's written into the event lead's notes. Without a match a new lead SHALL be created as NEW.
|
||||
|
||||
#### Scenario: Existing lead not edited
|
||||
|
||||
- **GIVEN** lead `Aisyah` with mobile `+60123456701` and no email
|
||||
- **WHEN** a visitor registers as `Aisyah Rahman` with that mobile and email `a@example.test`
|
||||
- **THEN** lead `Aisyah` still has no email and its name is unchanged
|
||||
- **AND** the new event lead is EXISTING and its notes list the submitted name and email
|
||||
|
||||
#### Scenario: Mobile beats email
|
||||
|
||||
- **GIVEN** lead `A` has mobile `+60123456701` and lead `B` has email `b@example.test`
|
||||
- **WHEN** a visitor registers with that mobile and that email
|
||||
- **THEN** the registration is linked to lead `A`
|
||||
|
||||
### Requirement: Registration of a person already captured
|
||||
|
||||
When the matched lead is already captured at the event, a registration SHALL change nothing, except that an event lead with no salesperson SHALL get the salesperson of a personal code whose salesperson is an active member of the event's team.
|
||||
|
||||
#### Scenario: Already captured, unassigned
|
||||
|
||||
- **GIVEN** `Aisyah` is captured at `KL Expo` with no salesperson
|
||||
- **WHEN** she registers again through `sales1`'s personal code and `sales1` is on the team
|
||||
- **THEN** her event lead's salesperson becomes `sales1` and nothing else changes
|
||||
|
||||
### Requirement: Registration record
|
||||
|
||||
An event lead created by a registration SHALL have status OPEN, source QR, captured by `qr`, the consent time and the privacy notice version shown, the chosen interests, and the code's salesperson when that salesperson is an active member of the event's team. Event leads captured by staff SHALL have source STAFF. The status history SHALL record the first status by `qr`.
|
||||
|
||||
#### Scenario: Personal code assigns
|
||||
|
||||
- **WHEN** a visitor registers through `sales1`'s personal code for `KL Expo`
|
||||
- **THEN** the event lead's salesperson is `sales1`, its source is QR and it records the consent time and notice version
|
||||
|
||||
### Requirement: Privacy notice
|
||||
|
||||
Each company SHALL have a privacy notice in English and Bahasa Malaysia, kept as versions: saving a change SHALL add a new version and keep the old ones. Only a super admin SHALL edit it, on the Companies page. The registration page SHALL show the company's current notice in both languages. INS and CV SHALL start with the default notice of the design, with the company's name filled in.
|
||||
|
||||
#### Scenario: Edit the notice
|
||||
|
||||
- **GIVEN** CV's notice is version 3
|
||||
- **WHEN** a super admin changes CV's English text and saves
|
||||
- **THEN** CV's registration pages show the new text
|
||||
- **AND** event leads registered before still point to version 3
|
||||
|
||||
#### Scenario: Not a super admin
|
||||
|
||||
- **WHEN** company staff call the privacy notice update endpoint
|
||||
- **THEN** it responds 403
|
||||
|
||||
### Requirement: Registration abuse limits
|
||||
|
||||
The system SHALL accept at most 60 registrations per client IP per event in 10 minutes and serve at most 120 registration page loads per client IP in 10 minutes, answering above either limit with "Too many registrations from this device. Try again later." A submission that fills the hidden honeypot field SHALL get the normal thank-you page and save nothing.
|
||||
|
||||
#### Scenario: Too many submissions
|
||||
|
||||
- **GIVEN** 60 registrations for `KL Expo` from one IP in the last 10 minutes
|
||||
- **WHEN** the 61st arrives from that IP
|
||||
- **THEN** nothing is saved and the page shows the too-many message
|
||||
|
||||
#### Scenario: Honeypot
|
||||
|
||||
- **WHEN** a submission fills the hidden field
|
||||
- **THEN** the thank-you page shows and no lead or event lead is saved
|
||||
@@ -13,7 +13,7 @@ vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth
|
||||
import CompaniesPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "ins", status: "A" }]);
|
||||
mocks.apiGet.mockReset().mockResolvedValue([{ id: 1, name: "Insight", code: "INS", status: "A" }]);
|
||||
mocks.apiPost.mockReset();
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
|
||||
});
|
||||
@@ -24,7 +24,7 @@ describe("CompaniesPage fixes", () => {
|
||||
await userEvent.click(await screen.findByRole("button", { name: "Change code" }));
|
||||
const input = screen.getByLabelText("New code");
|
||||
await userEvent.clear(input);
|
||||
await userEvent.type(input, " INS ");
|
||||
await userEvent.type(input, " ins ");
|
||||
await userEvent.click(screen.getByRole("button", { name: "Confirm" }));
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole("alert")).toBeInTheDocument();
|
||||
|
||||
@@ -39,7 +39,7 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
|
||||
if ((mode === "code" ? newCode : form.code).trim() === "" && (mode === "code" || !form.id)) {
|
||||
return setError(t("CompCodeRequired"));
|
||||
}
|
||||
if (mode === "code" && newCode.trim().toLowerCase() === company.code.toLowerCase()) {
|
||||
if (mode === "code" && newCode.trim().toUpperCase() === company.code) {
|
||||
return setError(t("CompCodeUnchanged"));
|
||||
}
|
||||
setError(null);
|
||||
@@ -74,7 +74,7 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
|
||||
<p className="text-sm">{t("CompChangeCodeWarning")}</p>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company-new-code">{t("CompNewCode")}</Label>
|
||||
<Input id="company-new-code" value={newCode} onChange={(e) => setNewCode(e.target.value)} disabled={saving} />
|
||||
<Input id="company-new-code" className="uppercase" value={newCode} onChange={(e) => setNewCode(e.target.value)} disabled={saving} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
@@ -86,7 +86,7 @@ function CompanyDialog({ state, onClose, onSaved }: { state: DialogState; onClos
|
||||
{!form.id && (
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="company-code">{t("Code")}</Label>
|
||||
<Input id="company-code" value={form.code} onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} />
|
||||
<Input id="company-code" className="uppercase" value={form.code} onChange={(e) => setForm((f) => ({ ...f, code: e.target.value }))} disabled={saving} />
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-1.5">
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { render, screen, waitFor, within } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({ apiGet: vi.fn(), apiPost: vi.fn(), useAdminAuth: vi.fn() }));
|
||||
vi.mock("@/app/lib/clientApi", async (importOriginal) => ({
|
||||
ApiError: (await importOriginal<typeof import("@/app/lib/clientApi")>()).ApiError,
|
||||
apiGet: mocks.apiGet,
|
||||
apiPost: mocks.apiPost,
|
||||
}));
|
||||
vi.mock("@/app/lib/AdminAuthContext", () => ({ useAdminAuth: mocks.useAdminAuth }));
|
||||
|
||||
import CompaniesPage from "./page";
|
||||
|
||||
beforeEach(() => {
|
||||
mocks.apiGet.mockReset().mockResolvedValue([{ id: 2, name: "Clever", code: "cv", status: "A" }]);
|
||||
mocks.apiPost.mockReset().mockResolvedValue({ id: 2, code: "CV" });
|
||||
mocks.useAdminAuth.mockReset().mockReturnValue({ loading: false, isSuper: true });
|
||||
});
|
||||
|
||||
async function openChangeCode() {
|
||||
render(<CompaniesPage />);
|
||||
const row = (await screen.findByText("Clever")).closest("tr")!;
|
||||
await userEvent.click(within(row).getByRole("button", { name: /change code/i }));
|
||||
return screen.getByLabelText("New code");
|
||||
}
|
||||
|
||||
describe("CompaniesPage company codes in capitals", () => {
|
||||
it("treats a change of case as a change and posts it", async () => {
|
||||
const code = await openChangeCode();
|
||||
await userEvent.clear(code);
|
||||
await userEvent.type(code, "CV");
|
||||
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
|
||||
await waitFor(() => expect(mocks.apiPost).toHaveBeenCalledWith("/api/companies/2/code", { code: "CV" }));
|
||||
});
|
||||
|
||||
it("still refuses the same code typed in any case", async () => {
|
||||
mocks.apiGet.mockResolvedValue([{ id: 2, name: "Clever", code: "CV", status: "A" }]);
|
||||
const code = await openChangeCode();
|
||||
await userEvent.clear(code);
|
||||
await userEvent.type(code, "cv");
|
||||
await userEvent.click(screen.getByRole("button", { name: /confirm/i }));
|
||||
expect(await screen.findByRole("alert")).toBeInTheDocument();
|
||||
expect(mocks.apiPost).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("shows code inputs in capitals", async () => {
|
||||
const code = await openChangeCode();
|
||||
expect(code).toHaveClass("uppercase");
|
||||
await userEvent.keyboard("{Escape}");
|
||||
await userEvent.click(screen.getByRole("button", { name: /add company/i }));
|
||||
expect(screen.getByLabelText("Code")).toHaveClass("uppercase");
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -207,7 +207,7 @@ public class AdminAuthController {
|
||||
if (!StringUtils.hasText(username) || username.contains("@")) {
|
||||
return null;
|
||||
}
|
||||
String code = company == null ? "" : company.trim().toLowerCase();
|
||||
String code = company == null ? "" : company.trim().toUpperCase(java.util.Locale.ROOT);
|
||||
return code.isEmpty() ? username.trim() : username.trim() + "@" + code;
|
||||
}
|
||||
}
|
||||
+7
-7
@@ -84,9 +84,9 @@ class AdminAuthControllerCompanyTest {
|
||||
|
||||
ArgumentCaptor<AuthRequest> sent = ArgumentCaptor.forClass(AuthRequest.class);
|
||||
verify(auth).getToken(sent.capture());
|
||||
assertThat(sent.getValue().getUsername()).isEqualTo("john@ins");
|
||||
verify(auth).isLocked("john@ins");
|
||||
verify(auth).record("john@ins", "LOGIN_SUCCESS", null);
|
||||
assertThat(sent.getValue().getUsername()).isEqualTo("john@INS");
|
||||
verify(auth).isLocked("john@INS");
|
||||
verify(auth).record("john@INS", "LOGIN_SUCCESS", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -114,7 +114,7 @@ class AdminAuthControllerCompanyTest {
|
||||
void login_wrongCompanyOrUnknownUser_isBadLogin() throws Exception {
|
||||
when(auth.getToken(any())).thenReturn(null);
|
||||
login("{\"company\":\"nope\",\"username\":\"john\",\"password\":\"pw\"}").andExpect(status().isUnauthorized());
|
||||
verify(auth).record("john@nope", "LOGIN_FAIL", null);
|
||||
verify(auth).record("john@NOPE", "LOGIN_FAIL", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -124,7 +124,7 @@ class AdminAuthControllerCompanyTest {
|
||||
|
||||
login("{\"company\":\"ins\",\"username\":\"john\",\"password\":\"pw\"}")
|
||||
.andExpect(status().isUnauthorized()).andExpect(jsonPath("$.message").value("Invalid username or password"));
|
||||
verify(auth).record("john@ins", "LOGIN_FAIL", null);
|
||||
verify(auth).record("john@INS", "LOGIN_FAIL", null);
|
||||
verify(authenticationService).logoutToken("tok");
|
||||
}
|
||||
|
||||
@@ -154,10 +154,10 @@ class AdminAuthControllerCompanyTest {
|
||||
mvc.perform(post("/api/admin/auth/forgot-password").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"company\":\"INS\",\"username\":\"john\",\"email\":\"j@x.com\"}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.result").value("true"));
|
||||
verify(auth).resetAdminPassword("john@ins", "j@x.com");
|
||||
verify(auth).resetAdminPassword("john@INS", "j@x.com");
|
||||
|
||||
mvc.perform(post("/api/admin/auth/forgot-password").contentType(MediaType.APPLICATION_JSON)
|
||||
.content("{\"company\":\"ins\",\"username\":\"a@b\",\"email\":\"j@x.com\"}")).andExpect(status().isOk());
|
||||
verify(auth, never()).resetAdminPassword(org.mockito.ArgumentMatchers.eq("a@b@ins"), anyString());
|
||||
verify(auth, never()).resetAdminPassword(org.mockito.ArgumentMatchers.eq("a@b@INS"), anyString());
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -18,7 +18,7 @@ import java.util.regex.Pattern;
|
||||
public class CompanyService {
|
||||
|
||||
private static final int USERNAME_MAX = 255; // user.username column length
|
||||
private static final Pattern CODE = Pattern.compile("^[a-z0-9-]{2,20}$");
|
||||
private static final Pattern CODE = Pattern.compile("^[A-Z0-9-]{2,20}$");
|
||||
|
||||
private final CompanyRepository companies;
|
||||
private final UserRepository users;
|
||||
@@ -97,8 +97,8 @@ public class CompanyService {
|
||||
}
|
||||
|
||||
private static String validCode(String code) {
|
||||
String v = code == null ? "" : code.trim().toLowerCase();
|
||||
if (!CODE.matcher(v).matches()) throw new IllegalArgumentException("Code must be 2 to 20 characters: a-z, 0-9 or -");
|
||||
String v = code == null ? "" : code.trim().toUpperCase(java.util.Locale.ROOT);
|
||||
if (!CODE.matcher(v).matches()) throw new IllegalArgumentException("Code must be 2 to 20 characters: A-Z, 0-9 or -");
|
||||
return v;
|
||||
}
|
||||
|
||||
|
||||
+11
-11
@@ -69,17 +69,17 @@ class CompanyServiceTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void createLowercasesCodeAndDefaultsToActive() {
|
||||
Company saved = service.save(company(null, " CV ", " CV-2 ", null));
|
||||
void createStoresCodeInCapitalsAndDefaultsToActive() {
|
||||
Company saved = service.save(company(null, " CV ", " cv-2 ", null));
|
||||
|
||||
assertThat(saved.getName()).isEqualTo("CV");
|
||||
assertThat(saved.getCode()).isEqualTo("cv-2");
|
||||
assertThat(saved.getCode()).isEqualTo("CV-2");
|
||||
assertThat(saved.getStatus()).isEqualTo("A");
|
||||
}
|
||||
|
||||
@Test
|
||||
void duplicateCodeIgnoringCaseIsRefused() {
|
||||
when(companies.findByCodeIgnoreCase("ins")).thenReturn(Optional.of(company(1L, "INS", "ins", "A")));
|
||||
when(companies.findByCodeIgnoreCase("INS")).thenReturn(Optional.of(company(1L, "INS", "ins", "A")));
|
||||
|
||||
assertThatThrownBy(() -> service.save(company(null, "Other", "INS", "A")))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class, e -> assertThat(e.getStatusCode().value()).isEqualTo(409));
|
||||
@@ -87,7 +87,7 @@ class CompanyServiceTest {
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", "a", "UPPER_case", "has space", "under_score", "abcdefghijklmnopqrstu"})
|
||||
@ValueSource(strings = {"", "a", "has space", "under_score", "abcdefghijklmnopqrstu"})
|
||||
void badCodeFormatIsRefused(String code) {
|
||||
assertThatThrownBy(() -> service.save(company(null, "X", code, "A"))).isInstanceOf(IllegalArgumentException.class);
|
||||
verify(companies, never()).save(any());
|
||||
@@ -129,9 +129,9 @@ class CompanyServiceTest {
|
||||
|
||||
Company renamed = service.renameCode(2L, "CVX");
|
||||
|
||||
assertThat(renamed.getCode()).isEqualTo("cvx");
|
||||
assertThat(a.getUsername()).isEqualTo("sales@cvx");
|
||||
assertThat(b.getUsername()).isEqualTo("odd@name@cvx");
|
||||
assertThat(renamed.getCode()).isEqualTo("CVX");
|
||||
assertThat(a.getUsername()).isEqualTo("sales@CVX");
|
||||
assertThat(b.getUsername()).isEqualTo("odd@name@CVX");
|
||||
verify(users).findByCompanyIdAndType(2L, UserType.A); // only that company, only admins
|
||||
verify(users).saveAll(List.of(a, b));
|
||||
// one transaction: company update and username rewrite share one @Transactional method
|
||||
@@ -142,7 +142,7 @@ class CompanyServiceTest {
|
||||
@Test
|
||||
void renameToTakenCodeIsRefusedAndRewritesNothing() {
|
||||
when(companies.findById(2L)).thenReturn(Optional.of(company(2L, "CV", "cv", "A")));
|
||||
when(companies.findByCodeIgnoreCase("ins")).thenReturn(Optional.of(company(1L, "INS", "ins", "A")));
|
||||
when(companies.findByCodeIgnoreCase("INS")).thenReturn(Optional.of(company(1L, "INS", "ins", "A")));
|
||||
|
||||
assertThatThrownBy(() -> service.renameCode(2L, "INS")).isInstanceOf(ResponseStatusException.class);
|
||||
verify(users, never()).saveAll(any());
|
||||
@@ -191,10 +191,10 @@ class CompanyServiceTest {
|
||||
void renameToOwnCodeIgnoringCaseIsAllowed() {
|
||||
Company cv = company(2L, "CV", "cv", "A");
|
||||
when(companies.findById(2L)).thenReturn(Optional.of(cv));
|
||||
when(companies.findByCodeIgnoreCase("cv")).thenReturn(Optional.of(cv));
|
||||
when(companies.findByCodeIgnoreCase("CV")).thenReturn(Optional.of(cv));
|
||||
when(users.findByCompanyIdAndType(2L, UserType.A)).thenReturn(List.of());
|
||||
|
||||
assertThat(service.renameCode(2L, "CV").getCode()).isEqualTo("cv");
|
||||
assertThat(service.renameCode(2L, "CV").getCode()).isEqualTo("CV");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user