Chuyển tới nội dung chính

xperise B2B Business Account, Membership, Role and Authentication Specification

Document type: Software Specification / Single Source of Truth
Feature domain: Business Account Management, User Membership, Authentication and Two-Factor Authentication
Version: 1.0 Draft
Status: Ready for product review and technical estimation

Confirmed Inputs and Assumptions​

Confirmed Requirements​

IDRequirement
CI-001xperise supports B2B businesses.
CI-002Each account is identified using an email address or phone number.
CI-003Users can log in with email/password, phone/password, or Google login.
CI-004A business can be created by an account that does not currently belong to a business.
CI-005Each business must have a unique tax code in the system.
CI-006Each business has a full name and a short name; the short name is the primary display name in most interfaces.
CI-007A business can have departments and users.
CI-008Each business user is associated with an account in the system.
CI-009A business admin can add a user using the user's name and email address.
CI-010A business user has one of three roles: ADMIN, ACCOUNTANT, or NORMAL_USER.
CI-011A business may enable two-factor authentication as an additional security layer.
CI-012When business-level 2FA is enabled, login requires primary authentication plus a valid 2FA challenge.
CI-0132FA codes may be delivered by email, phone number, or ZaloOA.
CI-014An account can join only one active business at a time.
CI-015An account has only one role within its active business.
CI-016Passwords must contain at least 12 characters, including uppercase letters, lowercase letters, and numbers.

Assumptions Requiring Confirmation​

IDAssumption
AS-001An account may exist without belonging to any business.
AS-002A business creator automatically becomes the first ADMIN of the business.
AS-003An admin adds an existing or new account through an invitation workflow rather than immediately activating membership.
AS-004A user belongs to zero or one department within a business.
AS-005Google-login users must still complete business-level 2FA when the business requires it.
AS-006Phone numbers must be verified before being usable for login or phone-based 2FA.
AS-007Email addresses must be verified before invitation acceptance or email-based 2FA.
AS-008ZaloOA delivery is available only after a compatible Zalo identity is linked and verified.
AS-009A removed user becomes eligible to join or create another business when no active membership remains.
AS-010Business short names do not need to be unique; tax codes must be unique.

1. Feature Overview

1.1 Purpose​

This feature enables xperise to manage B2B customer businesses and their users securely. It covers account identity, business registration, business membership, departments, role-based access, optional mandatory two-factor authentication, and user onboarding through invitation.

1.2 In Scope​

AreaIncluded capability
AccountAccount identity based on email address and/or phone number
AuthenticationLogin by email/password, phone/password, and Google authentication
Password SecurityPassword validation and secure storage rules
BusinessBusiness creation, tax code uniqueness, full name and short name
MembershipOne active business membership per account
DepartmentCreate, update, deactivate and assign users to departments
User AdministrationInvite users by name and email
RolesAdmin, Accountant and Normal User
SecurityEnable/disable mandatory business 2FA; supported delivery channels
AuditabilityCapture administration and security events

1.3 Out of Scope for This Version​

IDExcluded capability
OS-001Multiple active businesses for one account
OS-002Custom roles or custom permissions
OS-003Multiple roles per user in one business
OS-004Enterprise SSO providers other than Google
OS-005Organization hierarchy above business level
OS-006Department-level permissions
OS-007Billing, subscription and payment management
OS-008Bulk user import

2. Business Goal

2.1 Primary Goals​

IDGoal
BG-001Allow a company to create and manage its organization securely on xperise.
BG-002Ensure each business is uniquely identifiable by tax code.
BG-003Allow business administrators to onboard users efficiently.
BG-004Enforce clear role-based permissions.
BG-005Protect business access using optional mandatory 2FA.
BG-006Maintain reliable account-to-business membership integrity.

2.2 Success Criteria​

IDSuccess criterion
SC-001A new business can be registered without duplicate tax codes.
SC-002An invited user can activate membership and access the correct business.
SC-003A user cannot belong to more than one active business.
SC-004Admins can manage departments and membership without engineering support.
SC-005When 2FA is enabled, no member can access the business without completing the challenge.
SC-006Security and membership actions are auditable.

3. User Roles

3.1 Actor Definitions​

ActorDescription
GuestA person who has not authenticated.
Account Without BusinessAuthenticated account with no active business membership.
Invited UserAn account or email address with a pending business invitation.
Business UserAccount with active membership in one business.
Business AdminBusiness user with role ADMIN.
AccountantBusiness user with role ACCOUNTANT.
Normal UserBusiness user with role NORMAL_USER.

3.2 Business Role Definitions​

Role codeDisplay nameDescription
ADMINAdminManages business profile, departments, users, roles and business security settings.
ACCOUNTANTAccountantPerforms accounting-related work outside this feature; receives no administrative rights under this specification.
NORMAL_USERNormal UserUses the platform within the assigned business without administrative permissions.

3.3 Role Constraints​

IDRule
ROLE-001Each active business membership must contain exactly one role.
ROLE-002The business creator must be assigned role ADMIN automatically.
ROLE-003A business must always have at least one active ADMIN.
ROLE-004An admin must not remove or downgrade the final remaining active admin.
ROLE-005ACCOUNTANT and NORMAL_USER must not manage users, departments, roles or business security settings.

4. User Stories

4.1 Account and Authentication​

IDUser story
US-AUTH-001As a user, I want to log in using email and password so that I can access my account.
US-AUTH-002As a user, I want to log in using phone number and password so that I can access my account without email.
US-AUTH-003As a user, I want to log in using Google so that authentication is faster and easier.
US-AUTH-004As a user in a secured business, I want to receive and enter a 2FA code so that unauthorized access is prevented.
US-AUTH-005As a user, I want to choose an eligible 2FA delivery channel so that I can receive my code reliably.

4.2 Business, Department and Membership​

IDUser story
US-BIZ-001As an account without a business, I want to create a business workspace so my organization can use xperise.
US-BIZ-002As a business creator, I want duplicate tax code registration prevented.
US-BIZ-003As a business creator, I want to become admin automatically so I can complete setup.
US-DEPT-001As an admin, I want to create, update and deactivate departments so users can be organized accurately.
US-DEPT-002As an admin, I want to assign users to departments.
US-USER-001As an admin, I want to invite a user by name and email so they can join my business.
US-USER-002As an invited user, I want to accept an invitation and access the correct business.
US-USER-003As an admin, I want to set a user's role so access matches responsibility.
US-USER-004As an admin, I want to remove a user so former staff cannot access business information.
US-USER-005As an admin, I want to see invitation statuses so I can track onboarding.

4.3 Security​

IDUser story
US-SEC-001As an admin, I want to enable mandatory 2FA for the business so all members have stronger access protection.
US-SEC-002As an admin, I want to identify users who cannot complete selected 2FA methods before rollout.
US-SEC-003As a user, I want a secure fallback delivery method, where permitted, so channel failures do not permanently block me.

5. Functional Requirements

5.1 Account and Password Requirements​

IDRequirement
FR-ACC-001The system shall create an account record for each registered user.
FR-ACC-002An account shall support an email address, a phone number, or both.
FR-ACC-003Normalized email addresses shall be unique across accounts.
FR-ACC-004Normalized phone numbers shall be unique across accounts.
FR-ACC-005A verified identifier shall not be associated with multiple accounts.
FR-ACC-006The system shall maintain verification status separately for email and phone number.
FR-ACC-007An account may exist without an active business membership.
FR-PWD-001A password shall contain at least 12 characters.
FR-PWD-002A password shall contain at least one uppercase letter, one lowercase letter and one number.
FR-PWD-003Passwords shall never be stored in plain text.
FR-PWD-004Password rules shall apply during password creation and reset.
FR-PWD-005Google-authenticated users need not create a password unless password login is enabled later.

Normalization example: User@Company.com and user@company.com must be treated as the same email address after normalization.

5.2 Authentication Requirements​

IDRequirement
FR-AUTH-001The system shall support login using email address and password.
FR-AUTH-002The system shall support login using phone number and password.
FR-AUTH-003The system shall support login using Google authentication.
FR-AUTH-004Invalid identifiers or password validation failures shall reject login.
FR-AUTH-005After primary authentication succeeds, the system shall determine whether the active business requires 2FA.
FR-AUTH-006When 2FA is required, the system shall not issue an authenticated business session until 2FA validation succeeds.
FR-AUTH-007Google authentication shall not bypass mandatory business 2FA.
FR-AUTH-008Successful and failed authentication attempts shall be auditable.

5.3 Business Requirements​

IDRequirement
FR-BIZ-001Only an authenticated account with no active business membership may create a new business.
FR-BIZ-002Business creation shall require a tax code, full name and short name.
FR-BIZ-003Tax code shall be normalized before uniqueness validation.
FR-BIZ-004Normalized tax code shall be unique across all eligible non-deleted businesses.
FR-BIZ-005On successful creation, the creator shall automatically receive active membership with role ADMIN.
FR-BIZ-006Short name shall be the default display name in operational UI.
FR-BIZ-007Creation timestamp and creator account shall be captured.
FR-BIZ-008Business creation and creator membership creation shall be atomic.

5.4 Department Requirements​

IDRequirement
FR-DEPT-001An admin shall be able to create a department in their active business.
FR-DEPT-002A department shall require a department name.
FR-DEPT-003Normalized department names shall be unique within the same business.
FR-DEPT-004An admin shall be able to rename an active department.
FR-DEPT-005An admin shall be able to deactivate a department.
FR-DEPT-006A deactivated department shall not be available for new assignments.
FR-DEPT-007Handling users assigned to a deactivated department shall follow the decision documented in OQ-002/OQ-003.
FR-DEPT-008Under AS-004, a user shall be assigned to at most one department.

5.5 Invitation and Membership Requirements​

IDRequirement
FR-INV-001An admin shall be able to invite a business user using full name and email address.
FR-INV-002An invitation shall assign one role: ADMIN, ACCOUNTANT, or NORMAL_USER.
FR-INV-003Department assignment during invitation shall be optional unless later made mandatory.
FR-INV-004An invitation shall be rejected when its email belongs to an account with an active business membership.
FR-INV-005The system shall not create duplicate pending invitations for the same business and email.
FR-INV-006An invitation notification shall be sent to the provided email.
FR-INV-007Every invitation shall have an expiry time.
FR-INV-008An invited user shall not receive business access before acceptance and required authentication steps complete.
FR-INV-009An admin shall be able to resend or revoke a pending invitation.
FR-MEM-001An account shall have at most one active business membership.
FR-MEM-002An active membership shall link one account to one business and exactly one role.
FR-MEM-003A membership may link a user to one department.
FR-MEM-004Invitation acceptance shall revalidate that no conflicting active membership exists.
FR-MEM-005An admin shall be able to deactivate a member except when this violates the minimum-admin rule.
FR-MEM-006A deactivated member shall lose business access immediately.
FR-MEM-007Historical actions of a removed member shall be preserved for audit and reporting.

5.6 Role Management Requirements​

IDRequirement
FR-RBAC-001An admin shall be able to change another active member's role.
FR-RBAC-002Supported roles shall be ADMIN, ACCOUNTANT, and NORMAL_USER.
FR-RBAC-003A member shall have exactly one role at a time.
FR-RBAC-004The system shall prevent removal or downgrade of the last active admin.
FR-RBAC-005Role changes shall take effect immediately for subsequent authorization checks.
FR-RBAC-006Role changes shall be audited with previous role, new role and actor.

5.7 Two-Factor Authentication Requirements​

IDRequirement
FR-2FA-001An admin shall be able to enable mandatory 2FA at business level.
FR-2FA-002When mandatory 2FA is enabled, every active business user shall complete 2FA after successful primary authentication.
FR-2FA-003Supported channels shall include EMAIL, PHONE, and ZALO_OA.
FR-2FA-004A user may use only a channel linked to a verified eligible destination.
FR-2FA-005The system shall generate a time-limited, one-time code per challenge.
FR-2FA-006A 2FA code shall be usable only once.
FR-2FA-007Expired, invalid or previously used codes shall be rejected.
FR-2FA-008The system shall limit resend frequency and failed verification attempts.
FR-2FA-009The verification UI shall mask email addresses and phone numbers.
FR-2FA-010Enablement, disablement, delivery requests and verification results shall be audited.
FR-2FA-011If no valid delivery channel exists, business access shall be blocked and a defined recovery path shall be displayed.
FR-2FA-012Channel readiness shall be validated or explicitly warned about before mandatory 2FA is enabled.

5.8 Audit Requirements​

IDRequirement
FR-AUD-001Business creation events shall be recorded.
FR-AUD-002Department creation, update and deactivation events shall be recorded.
FR-AUD-003Invitation creation, resend, acceptance, expiry and revocation events shall be recorded.
FR-AUD-004Role changes and membership deactivation events shall be recorded.
FR-AUD-005Business 2FA setting changes shall be recorded.
FR-AUD-006Audit records shall identify actor, business, action, timestamp and affected entity.
FR-AUD-007Audit records shall not store raw passwords, invitation tokens or OTP codes.

6. Business Rules

6.1 Account and Business Rules​

IDRule
BR-ACC-001Each account is internally identified by account_id, regardless of login method.
BR-ACC-002An email address or phone number may belong to only one account after normalization.
BR-ACC-003An unverified destination shall not be used for security-sensitive delivery.
BR-ACC-004A Google identity shall be linked to exactly one xperise account.
BR-BIZ-001Each business must have one unique normalized tax code.
BR-BIZ-002A business must have a full legal name and short display name.
BR-BIZ-003The short name is used by default in application operational screens.
BR-BIZ-004The full name is used where legal or formal identification is required.
BR-BIZ-005An account with active membership cannot create another business.
BR-BIZ-006The business creator automatically becomes its first active admin.

6.2 Membership and Department Rules​

IDRule
BR-MEM-001An account may have only one active membership at any moment.
BR-MEM-002Each membership must have exactly one role.
BR-MEM-003An invitation does not grant access until accepted.
BR-MEM-004Invitation acceptance must fail if the account has joined another business since the invitation was issued.
BR-MEM-005Membership deactivation revokes access but does not delete historical activities.
BR-MEM-006A business must retain at least one active admin.
BR-DEPT-001A department belongs to exactly one business.
BR-DEPT-002A normalized department name cannot be duplicated within one business.
BR-DEPT-003Different businesses may use identical department names.
BR-DEPT-004Under current assumption, a user belongs to at most one active department.

6.3 Security Rules​

IDRule
BR-SEC-001Mandatory business 2FA applies to every active member, including admins.
BR-SEC-002Primary authentication must succeed before a 2FA challenge is generated.
BR-SEC-003Google authentication is primary authentication only and does not replace required business 2FA.
BR-SEC-004A 2FA code expires after its configured duration and cannot be reused.
BR-SEC-005Repeated invalid attempts shall invalidate or temporarily block the challenge according to security configuration.
BR-SEC-006No admin shall be able to silently bypass 2FA for another member.

7. Workflow

7.1 New Account Creates a Business​

  1. The user registers or logs into an account.
  2. The system checks whether the account has active business membership.
  3. If membership exists, business creation is rejected.
  4. If no membership exists, the user enters tax code, full name and short name.
  5. The system validates required fields and normalized tax code uniqueness.
  6. The system creates the business and active ADMIN membership within one transaction.
  7. The system records an audit event and opens the new business workspace.

7.2 Admin Invites a User​

  1. Admin opens User Management and selects Add User.
  2. Admin enters full name and email, selects role and optionally department.
  3. The system validates permissions, email format, membership conflicts, duplicate invitations and department status.
  4. The system creates a PENDING invitation with token and expiry.
  5. The system sends an invitation email and records an audit event.
  6. The invitation is shown in the admin invitation list.

7.3 Invited User Accepts Invitation​

  1. The user opens an invitation link.
  2. The system validates that the token is valid, pending and unexpired.
  3. The user signs in or registers and verifies required identity fields.
  4. The system revalidates that the account has no active membership.
  5. The system activates membership with the invitation's role and eligible department assignment.
  6. The invitation is marked ACCEPTED; an audit event is recorded.
  7. The user receives access subject to the business's authentication/security settings.

7.4 Login With Mandatory 2FA​

  1. The user completes email/password, phone/password or Google authentication.
  2. The system checks the active business's two_fa_required setting.
  3. If false, the system issues a session.
  4. If true, the system identifies verified eligible 2FA channels.
  5. The user selects a channel, or the default eligible channel is applied.
  6. The system sends a time-limited one-time code.
  7. The user enters the code.
  8. Only a correct, unused and unexpired code grants an authenticated session.
  9. Failed and successful 2FA events are audited.

7.5 Admin Enables Mandatory 2FA​

  1. Admin opens Security Settings.
  2. Admin selects Enable Mandatory 2FA.
  3. The system calculates active-user readiness by verified delivery channel.
  4. If all members are ready, admin confirms enablement.
  5. If any member is not ready, the system blocks enablement or presents an explicit impact confirmation according to the final product decision.
  6. The system records the changed setting in the audit log.
  7. 2FA is enforced from the next applicable login or session renewal.

8. Status / State Transition Rules

8.1 Business Status​

StatusDescription
ACTIVEBusiness can be accessed by active members.
INACTIVEBusiness exists but access is suspended.
DELETEDSoft-deleted record retained for audit or retention requirements.
FromActionToAllowed actorValidation
NoneCreate businessACTIVEAccount without businessTax code must be unique.
ACTIVESuspend businessINACTIVEPlatform administration, outside business-admin scopeAll business access blocked.
INACTIVEReactivate businessACTIVEPlatform administrationMembership rules remain valid.
ACTIVE / INACTIVESoft deleteDELETEDPlatform administrationTax-code reuse policy requires decision.

8.2 Membership Status​

StatusDescription
ACTIVEMember can access business according to role and security rules.
DEACTIVATEDMembership is not valid for access.
FromActionToAllowed actorValidation
NoneBusiness creation completesACTIVESystemCreator receives ADMIN.
NoneAccept valid invitationACTIVEInvited userNo other active membership.
ACTIVERemove userDEACTIVATEDAdminMust not remove final admin.
DEACTIVATEDReactivate userACTIVEAdminAccount has no other active membership.

8.3 Invitation Status​

StatusDescription
PENDINGInvitation may be accepted.
ACCEPTEDInvitation was accepted and membership activated.
EXPIREDExpiry occurred before acceptance.
REVOKEDInvitation was cancelled by an admin.
FromActionToValidation
NoneSend invitationPENDINGNo conflicting active membership or duplicate pending invitation.
PENDINGAccept invitationACCEPTEDToken valid; membership eligibility rechecked.
PENDINGExpiry reachedEXPIREDAutomatic transition.
PENDINGRevoke invitationREVOKEDNo membership is created.
EXPIRED / REVOKEDResend invitationNew PENDING invitationNew token and expiry are required.

8.4 Department Status​

StatusDescription
ACTIVEDepartment can receive user assignments.
INACTIVEDepartment cannot receive new assignments.
FromActionToValidation
NoneCreate departmentACTIVEName unique within business.
ACTIVEDeactivate departmentINACTIVEAssigned-user handling requires product decision.
INACTIVEReactivate departmentACTIVEName remains unique.

8.5 2FA Challenge Status​

StatusDescription
CREATEDChallenge generated but delivery not confirmed.
SENTCode delivered through selected channel.
VERIFIEDCorrect code successfully validated.
FAILEDChallenge exceeded permitted attempts.
EXPIREDChallenge expiry time reached.
CANCELLEDChallenge was replaced or invalidated.
FromActionToRule
NoneGenerate challengeCREATEDPrimary authentication must have succeeded.
CREATEDDeliver codeSENTChannel must be eligible.
SENTEnter valid codeVERIFIEDCode must be correct, unused and unexpired.
SENTExpiry reachedEXPIREDNo session is issued.
SENTMaximum invalid attempts reachedFAILEDA new challenge is required.
SENTSend replacement codeCANCELLEDPrevious code becomes unusable.

9. Data Model Requirements

9.1 Core Entities​

Account​

FieldTypeRequiredRules
account_idUUIDYesPrimary key.
full_nameStringYesUser display name.
emailStringConditionalRequired if phone is absent or invitation is email-based.
normalized_emailStringConditionalUnique when present.
email_verified_atTimestampNoNull until verified.
phone_numberStringConditionalRequired if email is absent.
normalized_phone_numberStringConditionalUnique when present.
phone_verified_atTimestampNoNull until verified.
password_hashStringConditionalRequired for password login only.
statusEnumYesACTIVE, LOCKED, DEACTIVATED.
created_at / updated_atTimestampYesSystem generated.

Authentication Identity​

FieldTypeRequiredRules
auth_identity_idUUIDYesPrimary key.
account_idUUIDYesReferences account.
providerEnumYesPASSWORD, GOOGLE.
provider_subject_idStringConditionalRequired for Google; unique within provider.
created_atTimestampYesSystem generated.

Business​

FieldTypeRequiredRules
business_idUUIDYesPrimary key.
tax_codeStringYesOriginal value entered.
normalized_tax_codeStringYesGlobally unique for eligible records.
full_nameStringYesLegal business name.
short_nameStringYesPrimary display name.
statusEnumYesACTIVE, INACTIVE, DELETED.
two_fa_requiredBooleanYesDefault false.
created_by_account_idUUIDYesReferences creator.
created_at / updated_atTimestampYesSystem generated.

Department​

FieldTypeRequiredRules
department_idUUIDYesPrimary key.
business_idUUIDYesReferences business.
nameStringYesDisplay name.
normalized_nameStringYesUnique within business.
statusEnumYesACTIVE, INACTIVE.
created_by_account_idUUIDYesReferences admin creator.
created_at / updated_atTimestampYesSystem generated.

Business Membership​

FieldTypeRequiredRules
membership_idUUIDYesPrimary key.
business_idUUIDYesReferences business.
account_idUUIDYesReferences account.
roleEnumYesADMIN, ACCOUNTANT, NORMAL_USER.
department_idUUIDNoActive department in same business.
statusEnumYesACTIVE, DEACTIVATED.
activated_atTimestampConditionalRequired when active.
deactivated_atTimestampNoSet when removed.
created_at / updated_atTimestampYesSystem generated.

User Invitation​

FieldTypeRequiredRules
invitation_idUUIDYesPrimary key.
business_idUUIDYesReferences inviting business.
invited_nameStringYesName entered by admin.
invited_email / normalized_invited_emailStringYesNotification address and lookup value.
roleEnumYesAssigned on acceptance.
department_idUUIDNoOptional active department.
statusEnumYesPENDING, ACCEPTED, EXPIRED, REVOKED.
invitation_token_hashStringYesRaw token shall not be stored.
expires_atTimestampYesRequired.
accepted_by_account_idUUIDNoSet on acceptance.
invited_by_account_idUUIDYesAdmin actor.
created_at / updated_atTimestampYesSystem generated.

Two-Factor Destination and Challenge​

EntityKey fieldsRules
TWO_FA_DESTINATIONdestination_id, account_id, channel, destination_reference, verified_at, status, is_defaultChannels: EMAIL, PHONE, ZALO_OA; only verified active destinations usable.
TWO_FA_CHALLENGEchallenge_id, account_id, business_id, channel, destination_id, code_hash, status, attempt_count, expires_at, verified_atRaw code shall not be stored; one-time usage and expiry enforced.

Audit Log​

FieldTypeRequiredRules
audit_log_idUUIDYesPrimary key.
business_idUUIDConditionalRequired for business-related actions.
actor_account_idUUIDConditionalNull only for automated events.
action_typeString/EnumYesExample: BUSINESS_CREATED, USER_INVITED, ROLE_CHANGED.
target_type / target_idString/UUIDYesAffected entity.
previous_value / new_valueJSONNoSensitive information excluded.
created_atTimestampYesImmutable timestamp.

9.2 Data Constraints​

IDConstraint
DM-001At most one ACTIVE membership shall exist per account_id.
DM-002A membership's department_id, when present, must belong to the same business.
DM-003An active business must retain at least one active membership where role = ADMIN.
DM-004Only one active pending invitation may exist for a business and normalized invited email.
DM-005Unique constraints shall protect email, phone and tax code against concurrent duplicate writes.

10. API Requirements

10.1 API Principles​

IDRequirement
API-GEN-001Authenticated endpoints shall validate the account session.
API-GEN-002Business-scoped endpoints shall validate active membership in the requested business.
API-GEN-003Admin-only endpoints shall validate role = ADMIN.
API-GEN-004APIs shall return stable machine-readable error codes and user-readable messages.
API-GEN-005Login, OTP resend and OTP verification endpoints shall be rate limited.
API-GEN-006Passwords, raw invitation tokens and raw OTP values shall never be returned.

10.2 Endpoint Catalogue​

MethodEndpointPurposeAuthorization
POST/api/v1/auth/registerRegister account with email/phone and passwordPublic
POST/api/v1/auth/loginLogin using email/phone and passwordPublic
POST/api/v1/auth/googleLogin using GooglePublic
POST/api/v1/auth/2fa/challengesSend 2FA codeTemporary authenticated challenge
POST/api/v1/auth/2fa/challenges/{challengeId}/verifyVerify 2FA codeTemporary authenticated challenge
POST/api/v1/businessesCreate businessAuthenticated account without business
GET/api/v1/businesses/currentGet current businessActive member
PATCH/api/v1/businesses/{businessId}Edit basic business informationAdmin
GET/api/v1/businesses/{businessId}/departmentsList departmentsActive member
POST/api/v1/businesses/{businessId}/departmentsCreate departmentAdmin
PATCH/api/v1/businesses/{businessId}/departments/{departmentId}Edit departmentAdmin
POST/api/v1/businesses/{businessId}/departments/{departmentId}/deactivateDeactivate departmentAdmin
GET/api/v1/businesses/{businessId}/invitationsList invitationsAdmin
POST/api/v1/businesses/{businessId}/invitationsSend invitationAdmin
POST/api/v1/businesses/{businessId}/invitations/{invitationId}/resendResend invitationAdmin
POST/api/v1/businesses/{businessId}/invitations/{invitationId}/revokeRevoke invitationAdmin
POST/api/v1/invitations/{token}/acceptAccept invitationInvited authenticated user
GET/api/v1/businesses/{businessId}/membersList membersAdmin
PATCH/api/v1/businesses/{businessId}/members/{membershipId}Update role/departmentAdmin
POST/api/v1/businesses/{businessId}/members/{membershipId}/deactivateRemove member accessAdmin
GET/api/v1/businesses/{businessId}/security-settingsView security settingsAdmin
GET/api/v1/businesses/{businessId}/security-settings/2fa-readinessView 2FA readinessAdmin
PATCH/api/v1/businesses/{businessId}/security-settingsEnable/disable mandatory 2FAAdmin

10.3 Example Requests and Responses​

Create Business​

{
"taxCode": "0312345678",
"fullName": "ABC Technology Joint Stock Company",
"shortName": "ABC Tech"
}
{
"businessId": "<uuid>",
"taxCode": "0312345678",
"fullName": "ABC Technology Joint Stock Company",
"shortName": "ABC Tech",
"status": "ACTIVE",
"currentUserRole": "ADMIN"
}

Login Response When 2FA Is Required​

{
"authenticationStatus": "TWO_FA_REQUIRED",
"temporaryAuthToken": "<temporary-token>",
"availableChannels": [
{
"channel": "EMAIL",
"maskedDestination": "a***@company.com"
}
]
}

Invite User​

{
"fullName": "Tran Thi Mai",
"email": "mai@company.com",
"role": "ACCOUNTANT",
"departmentId": "<uuid>"
}

Standard Error Response​

{
"errorCode": "BUSINESS_TAX_CODE_ALREADY_EXISTS",
"message": "A business with this tax code already exists.",
"fieldErrors": [
{
"field": "taxCode",
"message": "Tax code is already registered."
}
],
"traceId": "<trace-id>"
}

11. Frontend UI Requirements

11.1 General UI Rules​

IDRequirement
UI-GEN-001Business short name shall appear in primary navigation and business context headers.
UI-GEN-002Business full name and tax code shall appear in profile details.
UI-GEN-003Actions not permitted for the current role shall be hidden or disabled according to product design standards.
UI-GEN-004UI visibility rules shall not replace backend authorization checks.
UI-GEN-005Form errors shall identify invalid fields with actionable messages.

11.2 Required Screens and Forms​

ScreenRequired content
LoginEmail/password, phone/password and Google login paths; show/hide password; error state.
2FA VerificationEligible channel selector, masked destination, OTP input, expiry/resend status, validation errors.
Create BusinessTax code, full name, short name; duplicate/error validation.
Business ProfileShort name, full name, tax code; editable name fields for admin only.
Department ManagementDepartment name, status, optional user count, create/edit/deactivate actions for admin.
User ManagementUser name, email, department, role, membership status and admin actions.
Invitation ManagementInvited user, email, role, department, status, sent/expiry dates, resend/revoke actions.
Security SettingsMandatory 2FA toggle, supported channels, readiness summary, impacted users and confirmation dialog.

11.3 Form and Interaction Rules​

IDRequirement
UI-AUTH-001Login shall allow switching between email and phone login.
UI-AUTH-002A successful primary login requiring 2FA shall redirect to verification instead of the business workspace.
UI-BIZ-001Create Business shall be available only to accounts without active membership.
UI-DEPT-001Inactive departments shall not be selectable for new assignments.
UI-USER-001Add User form shall require full name, email and role; department remains optional until confirmed otherwise.
UI-SEC-001Only admins shall be able to change business-level 2FA settings.
UI-SEC-002Before mandatory 2FA is enabled, user readiness shall be displayed.
UI-SEC-003Verification UI shall never reveal complete phone numbers or email addresses.

12. Permission Matrix

ActionAccount Without BusinessAdminAccountantNormal User
Create a businessYesNoNoNo
View own business basic informationN/AYesYesYes
Update business full name or short nameNoYesNoNo
Update tax code through standard editNoNoNoNo
Create, rename or deactivate departmentNoYesNoNo
View department listNoYesYesYes, where operationally required
Invite, resend or revoke user invitationNoYesNoNo
View full business user listNoYesTo confirmTo confirm
Change role or department assignmentNoYesNoNo
Deactivate or reactivate memberNoYes, except final adminNoNo
Enable or disable business 2FANoYesNoNo
View 2FA readiness reportNoYesNoNo

13. Edge Cases

IDScenarioExpected result
EC-AUTH-001User enters email using different casing.Same account identified after normalization.
EC-AUTH-002User registers with an existing email or normalized phone number.Registration rejected.
EC-AUTH-003Google email matches an existing password account.Apply confirmed account-linking policy; no silent duplicate account.
EC-AUTH-004Google auth succeeds but business requires 2FA.2FA is required before access.
EC-BIZ-001Active business member attempts to create another business.Creation rejected.
EC-BIZ-002Two users submit the same tax code simultaneously.Database uniqueness permits only one creation.
EC-BIZ-003Business is created but admin membership creation fails.Entire transaction rolls back.
EC-INV-001Admin invites a current same-business member.No duplicate invitation is created.
EC-INV-002Admin invites an account active in another business.Invitation rejected.
EC-INV-003Two admins invite the same email simultaneously.Only one active pending invitation exists.
EC-INV-004A user has invitations from two businesses.First accepted membership succeeds; second acceptance fails.
EC-INV-005Invitation expires or is revoked before acceptance.Acceptance denied.
EC-INV-006Assigned department becomes inactive before acceptance.Acceptance follows pending product decision on reassignment/blocking.
EC-DEPT-001Finance is created when finance already exists.Duplicate rejected after normalization.
EC-DEPT-002Admin assigns a user to another business's department or inactive department.Request rejected.
EC-RBAC-001Final admin downgrades or deactivates themselves.Request rejected.
EC-RBAC-002Concurrent admin changes would leave no admin.Transactional validation prevents invalid final state.
EC-2FA-0012FA is enabled but a user has no verified channel.Follow readiness policy; do not silently allow access.
EC-2FA-002User repeatedly requests OTP or enters invalid codes.Resend/attempt rate limits apply.
EC-2FA-003Correct OTP is entered after expiry or after prior usage.Verification rejected.
EC-2FA-004A replacement OTP is sent.Previous OTP is invalidated.
EC-2FA-005Delivery provider fails but another channel is eligible.User may use eligible fallback where allowed.
EC-2FA-006User changes email or phone destination.New destination must be verified before 2FA use.

14. Error Handling

14.1 Principles​

IDRule
ERR-001Errors shall contain a stable machine-readable code.
ERR-002Errors shall contain a user-readable message.
ERR-003Authentication errors shall not expose sensitive account existence details where applicable.
ERR-004Validation errors shall identify invalid input fields.
ERR-005Security-related failures shall be auditable.
ERR-006Backend validation remains authoritative regardless of frontend validation.

14.2 Error Code Catalogue​

Error codeHTTP statusTriggerUser-facing message
ACCOUNT_EMAIL_ALREADY_EXISTS409Email already belongs to an accountThis email address is already registered.
ACCOUNT_PHONE_ALREADY_EXISTS409Phone already belongs to an accountThis phone number is already registered.
PASSWORD_POLICY_NOT_MET400Password fails validationPassword does not meet security requirements.
INVALID_LOGIN_CREDENTIALS401Invalid identifier or passwordEmail/phone number or password is incorrect.
GOOGLE_AUTHENTICATION_FAILED401Google sign-in cannot be validatedGoogle sign-in failed. Please try again.
TWO_FA_REQUIRED202Primary login succeeded; OTP requiredVerification is required to continue.
TWO_FA_NO_ELIGIBLE_CHANNEL403No verified destination availableNo verified verification method is available. Contact your administrator.
TWO_FA_CODE_INVALID400OTP incorrectVerification code is incorrect.
TWO_FA_CODE_EXPIRED400OTP expiredVerification code has expired. Request a new code.
TWO_FA_ATTEMPTS_EXCEEDED429Too many failed OTP entriesToo many failed attempts. Request a new code later.
TWO_FA_RESEND_TOO_SOON429Resend cooldown activePlease wait before requesting another code.
BUSINESS_ACTIVE_MEMBERSHIP_EXISTS409User tries to create or join another businessYour account already belongs to an active business.
BUSINESS_TAX_CODE_ALREADY_EXISTS409Duplicate tax codeA business with this tax code already exists.
DEPARTMENT_NAME_ALREADY_EXISTS409Duplicate department nameA department with this name already exists.
DEPARTMENT_INACTIVE409Assignment to inactive departmentThis department is inactive and cannot receive users.
INVITATION_ALREADY_PENDING409Duplicate pending invitationAn active invitation has already been sent to this email.
INVITATION_EXPIRED410Token expiredThis invitation has expired. Please request a new invitation.
INVITATION_REVOKED410Token revokedThis invitation is no longer valid.
LAST_ADMIN_REQUIRED409Change would leave business with no adminThe business must have at least one active admin.
FORBIDDEN_ROLE_PERMISSION403Role lacks permissionYou do not have permission to perform this action.

15. Acceptance Criteria

IDGivenWhenThen
AC-AUTH-001A unique email/phone and valid password are suppliedAccount is registeredUser can log in with the registered identifier and password.
AC-AUTH-002Password fails length or composition rulesRegistration/reset is submittedRequest is rejected with PASSWORD_POLICY_NOT_MET.
AC-AUTH-003Valid Google login for a business without 2FAAuthentication succeedsAuthenticated session is issued.
AC-AUTH-004Valid Google login for a business requiring 2FAAuthentication succeedsUser must complete 2FA before access.
AC-BIZ-001Authenticated account has no active businessUnique tax code, full name and short name are submittedActive business is created.
AC-BIZ-002Business creation succeedsTransaction completesCreator receives active ADMIN membership.
AC-BIZ-003Normalized tax code already existsCreation is submittedRequest is rejected.
AC-BIZ-004User already has active membershipCreation is attemptedRequest is rejected.
AC-DEPT-001Admin is authenticatedUnique department is submittedActive department appears in list.
AC-DEPT-002Inactive department existsUser assignment is submitted for itAssignment is rejected.
AC-INV-001Admin enters eligible user name, email and roleInvitation is submittedPENDING invitation is created and sent.
AC-INV-002Valid pending invitation and user has no active businessUser acceptsMembership becomes ACTIVE with invited role.
AC-INV-003User already joined another businessUser accepts invitationAcceptance is rejected.
AC-MEM-001Membership is deactivatedUser requests business accessAccess is denied immediately.
AC-RBAC-001Business has two active adminsOne admin downgrades the otherChange succeeds and is audited.
AC-RBAC-002Business has only one active adminThat admin is downgraded or removedRequest is rejected with LAST_ADMIN_REQUIRED.
AC-2FA-001Business 2FA is disabledUser completes primary authAccess may be granted without OTP.
AC-2FA-002Business 2FA is enabled and eligible channel existsUser logs inUser must validate OTP before access.
AC-2FA-003Valid unused unexpired OTP existsCorrect code is submittedSession is issued; challenge becomes VERIFIED.
AC-2FA-004OTP is expired or already usedCode is submittedAccess is rejected.
AC-2FA-005No eligible channel exists in 2FA-required businessUser authenticatesBusiness access is blocked and recovery guidance shown.

16. Open Questions

16.1 Product Decisions​

IDQuestionImpact
OQ-001Can a user belong to multiple departments, or only one?Data model, UI and reporting; current assumption is one maximum.
OQ-002Is department assignment mandatory for each business user?Invitation and membership validation.
OQ-003What happens to users assigned to a deactivated department?Department deactivation flow.
OQ-004Should business short name be unique?Registration and display ambiguity.
OQ-005Can tax code be changed after registration or reused after deletion?Verification and uniqueness policy.
OQ-006What is the invitation expiry duration?Security and onboarding UX.
OQ-007Can a deactivated member be reactivated directly, or must they be re-invited?Membership lifecycle.
OQ-008Should Accountants or Normal Users view the business user directory?Privacy and permissions.

16.2 Security and Technical Decisions​

IDQuestionImpact
OQ-SEC-001What are OTP length, expiry duration, resend cooldown and failed-attempt limit?API, UI and security configuration.
OQ-SEC-002Can an admin enable 2FA if some users have no verified delivery channel?Rollout and lockout handling.
OQ-SEC-003Does disabling 2FA require admin reauthentication or 2FA confirmation?Protection from compromised admin sessions.
OQ-SEC-004How is ZaloOA identity linked and verified?Integration and data model.
OQ-SEC-005Does phone-based 2FA use SMS, voice call or another delivery service?Integration scope.
OQ-SEC-006Are recovery codes or backup methods supported?Lockout prevention.
OQ-TECH-001What tax-code normalization rules apply per supported country?International data integrity.
OQ-TECH-002Does initial rollout support only Vietnamese businesses or multiple countries?Tax code and phone validation.
OQ-TECH-003Which email, phone and ZaloOA service providers will be used?Delivery implementation.
OQ-TECH-004What authentication/session/token strategy is required?Security architecture.
OQ-TECH-005What audit retention period is required?Compliance and storage.

17. Test Case Generation Notes

17.1 Test Case Principles​

IDInstruction
TGN-001Generate tests by requirement ID so each rule is traceable.
TGN-002Include positive, negative, permission, concurrency, security and state-transition tests.
TGN-003Separate API, frontend, integration and end-to-end test suites.
TGN-004Every acceptance criterion shall map to at least one end-to-end test.
TGN-005Every error code shall map to at least one negative test.
TGN-006Every role restriction shall be tested against every unauthorized role.
TGN-007Security tests shall confirm sensitive values are absent from API responses, logs and UI.
TGN-008Tests dependent on unresolved decisions shall be labelled BLOCKED_PENDING_PRODUCT_DECISION.

17.2 Required Test Suites​

SuiteRequired coverage
Account and LoginRegistration by email/phone, duplicate identifiers, password policy, login methods, Google identity linking and normalization.
BusinessCreation eligibility, required fields, tax code uniqueness, concurrency, atomic creator-admin membership and short-name display.
DepartmentCreate/update/deactivate permissions, normalized name duplicates, active assignment validation and cross-business rejection.
Invitation and MembershipInvite lifecycle, acceptance, expiry/revocation, conflicts across businesses, membership removal/reactivation and historical preservation.
Roles and PermissionsAll roles, authorized and unauthorized actions, last-admin protection, immediate permission updates and frontend visibility.
Two-Factor AuthenticationEnablement readiness, all delivery channels, valid/invalid/expired/reused OTP, resend limits, fallback failure, masking and audit.

17.3 Suggested Test Case Template​

### TC-{MODULE}-{NUMBER}: {Test Case Name}

**Requirement References:** FR-XXX-001, BR-XXX-001, AC-XXX-001
**Test Type:** API / UI / Integration / End-to-End / Security
**Priority:** Critical / High / Medium / Low

**Preconditions**
1. ...

**Test Data**
- ...

**Steps**
1. ...
2. ...

**Expected Results**
1. ...
2. ...

**Error Code Expected, if applicable**
- `ERROR_CODE`

**Automation Candidate**
- Yes / No

**Notes**
- ...

17.4 High-Priority Automation Candidates​

PriorityTest scenarioReason
CriticalPrevent duplicate tax code registrationCore data integrity.
CriticalPrevent account from joining more than one active businessCore membership integrity.
CriticalAutomatically assign creator as adminRequired initial administration access.
CriticalPrevent removal or downgrade of last active adminPrevent business lockout.
CriticalRequire 2FA when business enables itSecurity-critical.
CriticalReject expired or reused OTPSecurity-critical.
HighInvite and accept eligible userMain onboarding workflow.
HighAuthorize every admin API by roleAccess-control integrity.
HighValidate department assignmentsOrganization-data integrity.
HighRequire mandatory 2FA after Google authenticationSecurity consistency.

Recommended Initial Implementation Decisions

IDRecommendation
REC-001Keep one active business membership per account in version 1.
REC-002Keep one role per membership and one department per user in version 1.
REC-003Make the business creator the first admin automatically.
REC-004Use invitation-based onboarding rather than directly adding activated users.
REC-005Do not allow tax code changes through standard business editing; define a separate verified process later.
REC-006Require at least one verified 2FA destination for every active user before mandatory business 2FA can be enabled.
REC-007Treat Google login as primary authentication only; mandatory business 2FA remains required.
REC-008Use deactivation/soft deletion for business, membership and department lifecycle to preserve auditability.
REC-009Record all administrative and security-related actions in an immutable audit log.

Requirement Traceability Summary

Feature areaFunctional requirementsBusiness rulesAcceptance criteria
Account and PasswordFR-ACC-001 to FR-ACC-007; FR-PWD-001 to FR-PWD-005BR-ACC-001 to BR-ACC-004AC-AUTH-001 to AC-AUTH-004
AuthenticationFR-AUTH-001 to FR-AUTH-008BR-SEC-001 to BR-SEC-006AC-AUTH-001 to AC-AUTH-004
Business CreationFR-BIZ-001 to FR-BIZ-008BR-BIZ-001 to BR-BIZ-006AC-BIZ-001 to AC-BIZ-004
DepartmentFR-DEPT-001 to FR-DEPT-008BR-DEPT-001 to BR-DEPT-004AC-DEPT-001 to AC-DEPT-002
Invitation and MembershipFR-INV-001 to FR-INV-009; FR-MEM-001 to FR-MEM-007BR-MEM-001 to BR-MEM-006AC-INV-001 to AC-INV-003; AC-MEM-001
Role ManagementFR-RBAC-001 to FR-RBAC-006ROLE-001 to ROLE-005AC-RBAC-001 to AC-RBAC-002
Two-Factor AuthenticationFR-2FA-001 to FR-2FA-012BR-SEC-001 to BR-SEC-006AC-2FA-001 to AC-2FA-005
AuditFR-AUD-001 to FR-AUD-007Applies across modulesValidated through administration and security test suites