Merge branch 'master' into feature/cases
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -32,6 +32,7 @@ Thumbs.db
|
||||
|
||||
# === Docker ===
|
||||
docker-compose.override.yml
|
||||
infrastructure/nginx/generated/
|
||||
*.log
|
||||
docker-data/
|
||||
postgres-data/
|
||||
|
||||
34
README.md
34
README.md
@@ -6,6 +6,40 @@ Local development: see **`backend/README.md`** and **`frontend/README.md`**.
|
||||
|
||||
---
|
||||
|
||||
## Production deploy (Docker Hub + HTTPS + Let's Encrypt)
|
||||
|
||||
**Full step-by-step guide:** [`infrastructure/DEPLOY.md`](infrastructure/DEPLOY.md)
|
||||
|
||||
Minimal server setup: install Docker, create `.env` + `secrets/`, `docker login`, run one script.
|
||||
|
||||
| On server (once) | In repo / Docker |
|
||||
|------------------|------------------|
|
||||
| DNS A record → server IP | `docker-compose.prod.yml`, nginx, certbot |
|
||||
| `docker login` (private Hub) | Build & push images from dev machine |
|
||||
| `secrets/database.env`, `secrets/backend.env` | Examples: `database.prod.env.example`, `backend.prod.env.example` |
|
||||
| `infrastructure/.env` (`DOMAIN`, `LETSENCRYPT_EMAIL`) | `deploy.prod.env.example` |
|
||||
|
||||
**Dev machine** — build frontend with the public domain baked in, push to Docker Hub:
|
||||
|
||||
```bash
|
||||
./infrastructure/scripts/build-and-push-prod.sh wixur.ir latest
|
||||
```
|
||||
|
||||
**Server** — from `infrastructure/`:
|
||||
|
||||
```bash
|
||||
cp deploy.prod.env.example .env # edit DOMAIN, paths
|
||||
mkdir -p ../secrets && cp database.prod.env.example ../secrets/database.env
|
||||
cp backend.prod.env.example ../secrets/backend.env # set passwords + FRONTEND_URL
|
||||
docker login
|
||||
chmod +x scripts/*.sh
|
||||
./scripts/deploy-prod.sh
|
||||
```
|
||||
|
||||
SSL is issued automatically via **Certbot** (`scripts/init-letsencrypt.sh`). Nginx config is generated from `DOMAIN` in `.env`. When you move to another domain (e.g. `dyolink.com`), update `.env` + `backend.env`, re-run `init-letsencrypt.sh`, and **rebuild the frontend image** with the new URL.
|
||||
|
||||
---
|
||||
|
||||
## Deploy on your own server (Docker + Gitea)
|
||||
|
||||
High level: **build container images → push to a registry → server pulls images and runs Compose**. Optionally **Gitea Actions** automates that on every merge to `main` / `master`.
|
||||
|
||||
@@ -39,3 +39,8 @@ SMTP_HOST=smtp.gmail.com
|
||||
SMTP_PORT=587
|
||||
SMTP_USER=your_email@gmail.com
|
||||
SMTP_PASSWORD=your_app_password
|
||||
|
||||
# SMS (sms.ir — use Sandbox API key for development)
|
||||
# SMS_IR_API_KEY=4QKMiSU4Kh7tWPLCdRMV0QpDh8WgF33YkWRS18BcG3vf4QHi
|
||||
SMS_IR_API_KEY=lwbK7hxmjimNjFS4g5DWahh75EKCgJUfcUIinUQzfQXwXkSp
|
||||
SMS_IR_TEMPLATE_ID=123456
|
||||
|
||||
5
backend/.gitignore
vendored
5
backend/.gitignore
vendored
@@ -3,6 +3,11 @@
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# Accidental tsc output next to Prisma sources (keep only .ts / schema / migrations)
|
||||
/prisma/*.js
|
||||
/prisma/*.d.ts
|
||||
/prisma/*.js.map
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
@@ -52,4 +52,4 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
|
||||
|
||||
ENTRYPOINT ["dumb-init", "--", "docker-entrypoint.sh"]
|
||||
|
||||
CMD ["node", "dist/main"]
|
||||
CMD ["node", "dist/src/main.js"]
|
||||
|
||||
@@ -9,6 +9,13 @@ if [ "$NODE_ENV" = "production" ]; then
|
||||
echo "Running in PRODUCTION mode"
|
||||
echo "Running database migrations..."
|
||||
./node_modules/.bin/prisma migrate deploy
|
||||
if [ -f "dist/prisma/seed.js" ]; then
|
||||
echo "Seeding reference data (plans, org types, permissions)..."
|
||||
node dist/prisma/seed.js
|
||||
elif [ -f "prisma/seed.ts" ] || [ -f "prisma/seed.js" ]; then
|
||||
echo "Running database seed..."
|
||||
./node_modules/.bin/prisma db seed
|
||||
fi
|
||||
else
|
||||
echo "Running in DEVELOPMENT mode"
|
||||
echo "Syncing database schema..."
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
"start": "nest start",
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"start:prod": "node dist/src/main.js",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
"test:watch": "jest --watch",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ADD COLUMN "mobile" TEXT;
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "users_mobile_key" ON "users"("mobile");
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "phone_verification_codes" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT,
|
||||
"mobile" TEXT NOT NULL,
|
||||
"codeHash" TEXT NOT NULL,
|
||||
"purpose" TEXT NOT NULL,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"verifiedAt" TIMESTAMP(3),
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "phone_verification_codes_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "phone_verification_codes_mobile_purpose_createdAt_idx" ON "phone_verification_codes"("mobile", "purpose", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "phone_verification_codes" ADD CONSTRAINT "phone_verification_codes_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,11 @@
|
||||
-- Enforce one treatment detail per lab case (1:1 via join table).
|
||||
-- Keep the earliest-linked detail when duplicate rows exist for the same case.
|
||||
|
||||
DELETE FROM "lab_case_details" lcd
|
||||
WHERE lcd.ctid NOT IN (
|
||||
SELECT MIN(inner_lcd.ctid)
|
||||
FROM "lab_case_details" inner_lcd
|
||||
GROUP BY inner_lcd."labCaseId"
|
||||
);
|
||||
|
||||
CREATE UNIQUE INDEX "lab_case_details_labCaseId_key" ON "lab_case_details"("labCaseId");
|
||||
@@ -11,6 +11,7 @@ datasource db {
|
||||
model User {
|
||||
id String @id @default(uuid())
|
||||
email String @unique
|
||||
mobile String? @unique
|
||||
passwordHash String?
|
||||
googleId String? @unique
|
||||
facebookId String? @unique
|
||||
@@ -26,6 +27,7 @@ model User {
|
||||
statusChangedLabCaseTasks LabCaseTask[] @relation("LabCaseTaskLastStatusChangedBy")
|
||||
labCaseTaskStatusEvents LabCaseTaskStatusEvent[]
|
||||
labCaseComments LabCaseComment[]
|
||||
phoneVerificationCodes PhoneVerificationCode[]
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -33,6 +35,22 @@ model User {
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model PhoneVerificationCode {
|
||||
id String @id @default(uuid())
|
||||
userId String?
|
||||
mobile String
|
||||
codeHash String
|
||||
purpose String
|
||||
expiresAt DateTime
|
||||
verifiedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([mobile, purpose, createdAt])
|
||||
@@map("phone_verification_codes")
|
||||
}
|
||||
|
||||
model OrganizationType {
|
||||
id String @id @default(uuid())
|
||||
name String @unique // "CLINIC" or "LAB"
|
||||
@@ -222,7 +240,7 @@ model LabCaseAttachment {
|
||||
}
|
||||
|
||||
model LabCaseDetail {
|
||||
labCaseId String
|
||||
labCaseId String @unique
|
||||
treatmentDetailId String @unique
|
||||
|
||||
labCase LabCase @relation(fields: [labCaseId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@ -12,16 +12,15 @@ import {
|
||||
buildProsthesisStepCodes,
|
||||
} from './catalog-seed-data';
|
||||
|
||||
// Load environment variables from the correct path
|
||||
const envPath = path.join(__dirname, '..', '.env');
|
||||
console.log('Loading .env from:', envPath);
|
||||
config({ path: envPath });
|
||||
// Load .env when running locally; Docker injects DATABASE_URL via env_file.
|
||||
if (!process.env.DATABASE_URL) {
|
||||
const envPath = path.join(__dirname, '..', '.env');
|
||||
console.log('Loading .env from:', envPath);
|
||||
config({ path: envPath });
|
||||
}
|
||||
|
||||
// Verify DATABASE_URL is loaded
|
||||
if (!process.env.DATABASE_URL) {
|
||||
console.error('❌ DATABASE_URL is not set in environment');
|
||||
console.log('Current directory:', process.cwd());
|
||||
console.log('.env path:', envPath);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
|
||||
20
backend/src/common/utils/mobile.util.ts
Normal file
20
backend/src/common/utils/mobile.util.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
const IRAN_MOBILE_PATTERN = /^9\d{9}$/;
|
||||
|
||||
/** Normalize Iranian mobile to sms.ir format (e.g. 9123456789). */
|
||||
export function normalizeIranMobile(input: string): string {
|
||||
let digits = input.replace(/\D/g, '');
|
||||
|
||||
if (digits.startsWith('98') && digits.length === 12) {
|
||||
digits = digits.slice(2);
|
||||
}
|
||||
|
||||
if (digits.startsWith('0') && digits.length === 11) {
|
||||
digits = digits.slice(1);
|
||||
}
|
||||
|
||||
return digits;
|
||||
}
|
||||
|
||||
export function isValidIranMobile(input: string): boolean {
|
||||
return IRAN_MOBILE_PATTERN.test(normalizeIranMobile(input));
|
||||
}
|
||||
@@ -46,6 +46,10 @@ export interface Config {
|
||||
ttl: number;
|
||||
limit: number;
|
||||
};
|
||||
sms: {
|
||||
apiKey: string | null;
|
||||
templateId: number;
|
||||
};
|
||||
}
|
||||
|
||||
export default (): Config => {
|
||||
@@ -100,5 +104,9 @@ export default (): Config => {
|
||||
ttl: getEnvVarAsNumber('THROTTLE_TTL', 60),
|
||||
limit: getEnvVarAsNumber('THROTTLE_LIMIT', 100),
|
||||
},
|
||||
sms: {
|
||||
apiKey: process.env.SMS_IR_API_KEY?.trim() || null,
|
||||
templateId: getEnvVarAsNumber('SMS_IR_TEMPLATE_ID', 123456),
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -31,10 +31,18 @@ import { CreateOrganizationDto } from './dto/create-organization.dto';
|
||||
import { JwtAuthGuard } from './guards/jwt-auth.guard';
|
||||
import { LocalAuthGuard } from './guards/local-auth.guard';
|
||||
import { UpdateLanguageDto } from './dto/update-language.dto';
|
||||
import {
|
||||
ForgotPasswordSendCodeDto,
|
||||
ForgotPasswordVerifyDto,
|
||||
} from './dto/forgot-password.dto';
|
||||
import { ChangePasswordDto } from './dto/change-password.dto';
|
||||
|
||||
@ApiTags('auth')
|
||||
@Controller('auth')
|
||||
export class AuthController {
|
||||
private static readonly REMEMBER_ME_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
|
||||
private static readonly PASSWORD_RESET_MAX_AGE_MS = 15 * 60 * 1000;
|
||||
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
|
||||
// =========================
|
||||
@@ -56,9 +64,14 @@ export class AuthController {
|
||||
console.log('Login endpoint hit');
|
||||
|
||||
const result = await this.authService.login(loginDto, req.user);
|
||||
const rememberMe = Boolean(loginDto.rememberMe);
|
||||
|
||||
// ✅ SET COOKIES HERE
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
this.setAuthCookies(
|
||||
res,
|
||||
result.data.accessToken,
|
||||
result.data.refreshToken,
|
||||
rememberMe,
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
@@ -113,8 +126,11 @@ export class AuthController {
|
||||
organizationId
|
||||
);
|
||||
|
||||
// 🔥 Replace access token with org-scoped token
|
||||
this.setAccessToken(res, result.data.accessToken);
|
||||
this.setAccessToken(
|
||||
res,
|
||||
result.data.accessToken,
|
||||
this.isPersistentSession(req),
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
@@ -160,6 +176,67 @@ export class AuthController {
|
||||
return this.authService.updateLanguage(req.user.id, dto);
|
||||
}
|
||||
|
||||
@Patch('profile/password')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth('JWT-auth')
|
||||
@ApiOperation({ summary: 'Change account password' })
|
||||
async changePassword(
|
||||
@Req() req,
|
||||
@Body() dto: ChangePasswordDto,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
const skipCurrentPassword = req?.cookies?.passwordResetVerified === '1';
|
||||
|
||||
const result = await this.authService.changePassword(
|
||||
req.user.id,
|
||||
dto.currentPassword,
|
||||
dto.newPassword,
|
||||
skipCurrentPassword,
|
||||
);
|
||||
|
||||
this.clearAuthCookies(res);
|
||||
res.clearCookie('passwordResetVerified', this.baseCookieOptions());
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@Post('forgot-password/send-code')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Send forgot-password SMS verification code' })
|
||||
async sendForgotPasswordCode(@Body() dto: ForgotPasswordSendCodeDto) {
|
||||
return this.authService.sendForgotPasswordCode(dto);
|
||||
}
|
||||
|
||||
@Post('forgot-password/verify')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'Verify SMS code and sign in for password reset' })
|
||||
async verifyForgotPasswordCode(
|
||||
@Body() dto: ForgotPasswordVerifyDto,
|
||||
@Res({ passthrough: true }) res: Response,
|
||||
) {
|
||||
const result = await this.authService.verifyForgotPasswordCode(dto);
|
||||
|
||||
this.setAuthCookies(
|
||||
res,
|
||||
result.data.accessToken,
|
||||
result.data.refreshToken,
|
||||
);
|
||||
|
||||
res.cookie('passwordResetVerified', '1', {
|
||||
...this.baseCookieOptions(),
|
||||
maxAge: AuthController.PASSWORD_RESET_MAX_AGE_MS,
|
||||
});
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: result.data.user,
|
||||
organizations: result.data.organizations,
|
||||
redirectTo: '/settings/account',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@Get('subscription-alert')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@ApiBearerAuth('JWT-auth')
|
||||
@@ -191,7 +268,11 @@ export class AuthController {
|
||||
|
||||
const result = await this.authService.refreshToken(refreshToken);
|
||||
|
||||
this.setAccessToken(res, result.data.accessToken);
|
||||
this.setAccessToken(
|
||||
res,
|
||||
result.data.accessToken,
|
||||
this.isPersistentSession(req),
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
@@ -235,45 +316,65 @@ export class AuthController {
|
||||
// =========================
|
||||
// 🔥 COOKIE HELPERS
|
||||
// =========================
|
||||
private isPersistentSession(req: { cookies?: Record<string, string> }): boolean {
|
||||
return req?.cookies?.authRemember === '1';
|
||||
}
|
||||
|
||||
private baseCookieOptions() {
|
||||
return {
|
||||
httpOnly: true,
|
||||
secure: false, // ⚠️ true in production (HTTPS)
|
||||
sameSite: 'lax' as const,
|
||||
path: '/',
|
||||
};
|
||||
}
|
||||
|
||||
private setAuthCookies(
|
||||
res: Response,
|
||||
accessToken: string,
|
||||
refreshToken: string
|
||||
refreshToken: string,
|
||||
rememberMe = false,
|
||||
) {
|
||||
this.setAccessToken(res, accessToken);
|
||||
this.setRefreshToken(res, refreshToken);
|
||||
this.setAccessToken(res, accessToken, rememberMe);
|
||||
this.setRefreshToken(res, refreshToken, rememberMe);
|
||||
this.setRememberMeFlag(res, rememberMe);
|
||||
}
|
||||
|
||||
private setAccessToken(res: Response, token: string) {
|
||||
private setAccessToken(res: Response, token: string, rememberMe = false) {
|
||||
res.cookie('accessToken', token, {
|
||||
httpOnly: true,
|
||||
secure: false, // ⚠️ true in production (HTTPS)
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
...this.baseCookieOptions(),
|
||||
...(rememberMe
|
||||
? { maxAge: AuthController.REMEMBER_ME_MAX_AGE_MS }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
private setRefreshToken(res: Response, token: string) {
|
||||
private setRefreshToken(res: Response, token: string, rememberMe = false) {
|
||||
res.cookie('refreshToken', token, {
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
...this.baseCookieOptions(),
|
||||
...(rememberMe
|
||||
? { maxAge: AuthController.REMEMBER_ME_MAX_AGE_MS }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
private setRememberMeFlag(res: Response, rememberMe: boolean) {
|
||||
if (rememberMe) {
|
||||
res.cookie('authRemember', '1', {
|
||||
...this.baseCookieOptions(),
|
||||
maxAge: AuthController.REMEMBER_ME_MAX_AGE_MS,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
res.clearCookie('authRemember', this.baseCookieOptions());
|
||||
}
|
||||
|
||||
private clearAuthCookies(res: Response) {
|
||||
res.clearCookie('accessToken', {
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
});
|
||||
res.clearCookie('refreshToken', {
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
});
|
||||
const options = this.baseCookieOptions();
|
||||
res.clearCookie('accessToken', options);
|
||||
res.clearCookie('refreshToken', options);
|
||||
res.clearCookie('authRemember', options);
|
||||
res.clearCookie('passwordResetVerified', options);
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,12 @@ import { AuthController } from './auth.controller';
|
||||
import { PrismaService } from '../../../prisma/prisma.service';
|
||||
import { LocalStrategy } from './strategies/local.strategy';
|
||||
import { JwtStrategy } from './strategies/jwt.strategy';
|
||||
import { SmsModule } from '../sms/sms.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
PassportModule,
|
||||
SmsModule,
|
||||
JwtModule.registerAsync({
|
||||
imports: [ConfigModule],
|
||||
useFactory: async (configService: ConfigService) => ({
|
||||
|
||||
@@ -21,6 +21,18 @@ import {
|
||||
} from './dto/update-language.dto';
|
||||
import { JwtPayload } from './interfaces/jwt-payload.interface';
|
||||
import { ownerPermissionsForOrgType, type OrganizationTypeName } from '../../common/organization-type';
|
||||
import { SmsService } from '../sms/sms.service';
|
||||
import {
|
||||
ForgotPasswordSendCodeDto,
|
||||
ForgotPasswordVerifyDto,
|
||||
} from './dto/forgot-password.dto';
|
||||
import { normalizeIranMobile } from '../../common/utils/mobile.util';
|
||||
import * as crypto from 'crypto';
|
||||
|
||||
const FORGOT_PASSWORD_PURPOSE = 'forgot_password';
|
||||
const VERIFICATION_CODE_TTL_MS = 10 * 60 * 1000;
|
||||
const SEND_CODE_COOLDOWN_MS = 60 * 1000;
|
||||
const PASSWORD_RESET_WINDOW_MS = 15 * 60 * 1000;
|
||||
|
||||
const ALL_PERMISSIONS = [
|
||||
'TAB_TODAY_READ',
|
||||
@@ -62,6 +74,7 @@ export class AuthService {
|
||||
private prisma: PrismaService,
|
||||
private jwtService: JwtService,
|
||||
private configService: ConfigService,
|
||||
private smsService: SmsService,
|
||||
) { }
|
||||
|
||||
private accessJwtSignOptions(): JwtSignOptions {
|
||||
@@ -208,13 +221,24 @@ export class AuthService {
|
||||
const { password, name, organizationName, organizationEmail, organizationType } = registerDto;
|
||||
const email = registerDto.email.trim().toLowerCase();
|
||||
|
||||
if (!RegisterDto.isValidMobile(registerDto.mobile)) {
|
||||
throw new BadRequestException('Please enter a valid mobile number');
|
||||
}
|
||||
|
||||
const mobile = normalizeIranMobile(registerDto.mobile);
|
||||
|
||||
// 1. Check existing user
|
||||
const existingUser = await this.prisma.user.findUnique({
|
||||
where: { email },
|
||||
const existingUser = await this.prisma.user.findFirst({
|
||||
where: {
|
||||
OR: [{ email }, { mobile }],
|
||||
},
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
throw new ConflictException('User already exists. Please login and create a new organization from your account.');
|
||||
if (existingUser.email === email) {
|
||||
throw new ConflictException('User already exists. Please login and create a new organization from your account.');
|
||||
}
|
||||
throw new ConflictException('This mobile number is already registered.');
|
||||
}
|
||||
|
||||
// 2. Hash password
|
||||
@@ -226,6 +250,7 @@ export class AuthService {
|
||||
const user = await tx.user.create({
|
||||
data: {
|
||||
email,
|
||||
mobile,
|
||||
passwordHash: hashedPassword,
|
||||
name,
|
||||
trialUsedAt: new Date(),
|
||||
@@ -531,11 +556,17 @@ export class AuthService {
|
||||
/**
|
||||
* Change user password
|
||||
* @param userId - User ID
|
||||
* @param oldPassword - Current password
|
||||
* @param oldPassword - Current password (optional when reset verified via SMS)
|
||||
* @param newPassword - New password
|
||||
* @param skipCurrentPassword - True when user verified mobile via forgot-password flow
|
||||
* @returns Success message
|
||||
*/
|
||||
async changePassword(userId: string, oldPassword: string, newPassword: string) {
|
||||
async changePassword(
|
||||
userId: string,
|
||||
oldPassword: string | undefined,
|
||||
newPassword: string,
|
||||
skipCurrentPassword = false,
|
||||
) {
|
||||
try {
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
@@ -545,22 +576,29 @@ export class AuthService {
|
||||
throw new BadRequestException('User not found or invalid password method');
|
||||
}
|
||||
|
||||
// Verify old password
|
||||
const isPasswordValid = await bcrypt.compare(oldPassword, user.passwordHash);
|
||||
if (!isPasswordValid) {
|
||||
throw new UnauthorizedException('Current password is incorrect');
|
||||
if (skipCurrentPassword) {
|
||||
const hasRecentReset = await this.hasRecentPasswordResetVerification(userId);
|
||||
if (!hasRecentReset) {
|
||||
throw new UnauthorizedException('Password reset verification expired. Please verify your mobile again.');
|
||||
}
|
||||
} else {
|
||||
if (!oldPassword) {
|
||||
throw new BadRequestException('Current password is required');
|
||||
}
|
||||
|
||||
const isPasswordValid = await bcrypt.compare(oldPassword, user.passwordHash);
|
||||
if (!isPasswordValid) {
|
||||
throw new UnauthorizedException('Current password is incorrect');
|
||||
}
|
||||
}
|
||||
|
||||
// Hash new password
|
||||
const hashedPassword = await bcrypt.hash(newPassword, 10);
|
||||
|
||||
// Update password
|
||||
await this.prisma.user.update({
|
||||
where: { id: userId },
|
||||
data: { passwordHash: hashedPassword },
|
||||
});
|
||||
|
||||
// Invalidate all sessions for this user (force re-login)
|
||||
await this.prisma.session.deleteMany({
|
||||
where: { userId },
|
||||
});
|
||||
@@ -577,6 +615,156 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
async sendForgotPasswordCode(dto: ForgotPasswordSendCodeDto) {
|
||||
if (!ForgotPasswordSendCodeDto.validateMobile(dto.mobile)) {
|
||||
throw new BadRequestException('Please enter a valid mobile number');
|
||||
}
|
||||
|
||||
const mobile = normalizeIranMobile(dto.mobile);
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { mobile },
|
||||
select: { id: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
return {
|
||||
success: true,
|
||||
message: 'If this mobile number is registered, a verification code has been sent.',
|
||||
};
|
||||
}
|
||||
|
||||
const recentCode = await this.prisma.phoneVerificationCode.findFirst({
|
||||
where: {
|
||||
mobile,
|
||||
purpose: FORGOT_PASSWORD_PURPOSE,
|
||||
createdAt: { gt: new Date(Date.now() - SEND_CODE_COOLDOWN_MS) },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
if (recentCode) {
|
||||
throw new BadRequestException('Please wait before requesting another code');
|
||||
}
|
||||
|
||||
const code = this.generateVerificationCode();
|
||||
const codeHash = this.hashVerificationCode(code);
|
||||
|
||||
await this.prisma.phoneVerificationCode.create({
|
||||
data: {
|
||||
userId: user.id,
|
||||
mobile,
|
||||
codeHash,
|
||||
purpose: FORGOT_PASSWORD_PURPOSE,
|
||||
expiresAt: new Date(Date.now() + VERIFICATION_CODE_TTL_MS),
|
||||
},
|
||||
});
|
||||
|
||||
await this.smsService.sendVerificationCode(mobile, code);
|
||||
|
||||
if (this.configService.get<string>('NODE_ENV') === 'development') {
|
||||
console.log(`[dev] forgot-password code for ${mobile}: ${code}`);
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
message: 'If this mobile number is registered, a verification code has been sent.',
|
||||
};
|
||||
}
|
||||
|
||||
async verifyForgotPasswordCode(dto: ForgotPasswordVerifyDto) {
|
||||
if (!ForgotPasswordSendCodeDto.validateMobile(dto.mobile)) {
|
||||
throw new BadRequestException('Please enter a valid mobile number');
|
||||
}
|
||||
|
||||
const mobile = normalizeIranMobile(dto.mobile);
|
||||
const code = dto.code.trim();
|
||||
|
||||
const verification = await this.prisma.phoneVerificationCode.findFirst({
|
||||
where: {
|
||||
mobile,
|
||||
purpose: FORGOT_PASSWORD_PURPOSE,
|
||||
verifiedAt: null,
|
||||
expiresAt: { gt: new Date() },
|
||||
},
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
|
||||
if (!verification || !this.isVerificationCodeValid(code, verification.codeHash)) {
|
||||
throw new UnauthorizedException('Invalid or expired verification code');
|
||||
}
|
||||
|
||||
await this.prisma.phoneVerificationCode.update({
|
||||
where: { id: verification.id },
|
||||
data: { verifiedAt: new Date() },
|
||||
});
|
||||
|
||||
const user = await this.prisma.user.findUnique({
|
||||
where: { mobile },
|
||||
include: {
|
||||
memberships: {
|
||||
include: {
|
||||
organization: {
|
||||
include: {
|
||||
type: true,
|
||||
plan: true,
|
||||
},
|
||||
},
|
||||
permissions: {
|
||||
include: {
|
||||
permission: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('Invalid or expired verification code');
|
||||
}
|
||||
|
||||
const loginResult = await this.login(
|
||||
{ email: user.email, password: '' } as LoginDto,
|
||||
user,
|
||||
);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
accessToken: loginResult.data.accessToken,
|
||||
refreshToken: loginResult.data.refreshToken,
|
||||
user: loginResult.data.user,
|
||||
organizations: loginResult.data.organizations,
|
||||
passwordResetVerified: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async hasRecentPasswordResetVerification(userId: string): Promise<boolean> {
|
||||
const recent = await this.prisma.phoneVerificationCode.findFirst({
|
||||
where: {
|
||||
userId,
|
||||
purpose: FORGOT_PASSWORD_PURPOSE,
|
||||
verifiedAt: { gt: new Date(Date.now() - PASSWORD_RESET_WINDOW_MS) },
|
||||
},
|
||||
orderBy: { verifiedAt: 'desc' },
|
||||
});
|
||||
|
||||
return Boolean(recent);
|
||||
}
|
||||
|
||||
private generateVerificationCode(): string {
|
||||
return String(Math.floor(10000 + Math.random() * 90000));
|
||||
}
|
||||
|
||||
private hashVerificationCode(code: string): string {
|
||||
return crypto.createHash('sha256').update(code).digest('hex');
|
||||
}
|
||||
|
||||
private isVerificationCodeValid(code: string, codeHash: string): boolean {
|
||||
return this.hashVerificationCode(code.trim()) === codeHash;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all active sessions for a user
|
||||
* @param userId - User ID
|
||||
@@ -963,12 +1151,14 @@ export class AuthService {
|
||||
email: string;
|
||||
name: string;
|
||||
language?: string | null;
|
||||
mobile?: string | null;
|
||||
}) {
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
language: user.language ?? 'en',
|
||||
mobile: user.mobile ?? null,
|
||||
};
|
||||
}
|
||||
}
|
||||
11
backend/src/modules/auth/dto/change-password.dto.ts
Normal file
11
backend/src/modules/auth/dto/change-password.dto.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { IsOptional, IsString, MinLength } from 'class-validator';
|
||||
|
||||
export class ChangePasswordDto {
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
currentPassword?: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
newPassword: string;
|
||||
}
|
||||
22
backend/src/modules/auth/dto/forgot-password.dto.ts
Normal file
22
backend/src/modules/auth/dto/forgot-password.dto.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { IsString, Matches, Length } from 'class-validator';
|
||||
import { isValidIranMobile } from '../../../common/utils/mobile.util';
|
||||
|
||||
export class ForgotPasswordSendCodeDto {
|
||||
@IsString()
|
||||
@Matches(/^[\d+\s()-]+$/, { message: 'Mobile number format is invalid' })
|
||||
mobile: string;
|
||||
|
||||
static validateMobile(mobile: string): boolean {
|
||||
return isValidIranMobile(mobile);
|
||||
}
|
||||
}
|
||||
|
||||
export class ForgotPasswordVerifyDto {
|
||||
@IsString()
|
||||
@Matches(/^[\d+\s()-]+$/, { message: 'Mobile number format is invalid' })
|
||||
mobile: string;
|
||||
|
||||
@IsString()
|
||||
@Length(5, 6)
|
||||
code: string;
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// backend/src/modules/auth/dto/login.dto.ts
|
||||
import { IsEmail, IsString, MinLength } from 'class-validator';
|
||||
import { IsBoolean, IsEmail, IsOptional, IsString, MinLength } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class LoginDto {
|
||||
@@ -20,4 +20,13 @@ export class LoginDto {
|
||||
@IsString()
|
||||
@MinLength(6, { message: 'Password must be at least 6 characters long' })
|
||||
password: string;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Keep the user signed in for 30 days on this device',
|
||||
required: false,
|
||||
default: false,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
rememberMe?: boolean;
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
import { IsEmail, IsString, MinLength, IsEnum } from 'class-validator';
|
||||
import { IsEmail, IsString, MinLength, IsEnum, Matches } from 'class-validator';
|
||||
import { isValidIranMobile } from '../../../common/utils/mobile.util';
|
||||
|
||||
export class RegisterDto {
|
||||
@IsEmail()
|
||||
email: string;
|
||||
|
||||
@IsString()
|
||||
@Matches(/^[\d+\s()-]+$/, { message: 'Mobile number format is invalid' })
|
||||
mobile: string;
|
||||
|
||||
@IsString()
|
||||
@MinLength(8)
|
||||
password: string;
|
||||
@@ -19,4 +24,8 @@ export class RegisterDto {
|
||||
|
||||
@IsEnum(['CLINIC', 'LAB'])
|
||||
organizationType: 'CLINIC' | 'LAB';
|
||||
|
||||
static isValidMobile(mobile: string): boolean {
|
||||
return isValidIranMobile(mobile);
|
||||
}
|
||||
}
|
||||
@@ -449,7 +449,7 @@ export class CasesService {
|
||||
details: Array<{ detail: { treatmentType: string } }>;
|
||||
tasks: Array<{ id: string; status: LabTaskStatus }>;
|
||||
}) {
|
||||
const treatmentTypes = [...new Set(lc.details.map((d) => d.detail.treatmentType))];
|
||||
const treatmentType = lc.details[0]?.detail.treatmentType ?? null;
|
||||
const completedTasks = lc.tasks.filter((t) => t.status === LabTaskStatus.COMPLETED).length;
|
||||
|
||||
return {
|
||||
@@ -462,7 +462,7 @@ export class CasesService {
|
||||
lastName: lc.treatment.patient.lastName,
|
||||
mobile: lc.treatment.patient.mobile,
|
||||
},
|
||||
treatmentTypes,
|
||||
treatmentType,
|
||||
taskProgress: {
|
||||
completed: completedTasks,
|
||||
total: lc.tasks.length,
|
||||
@@ -475,7 +475,8 @@ export class CasesService {
|
||||
localeInput?: string | null,
|
||||
) {
|
||||
const locale = normalizeCatalogLocale(localeInput);
|
||||
const treatmentTypes = [...new Set(lc.details.map((d) => d.detail.treatmentType))];
|
||||
const treatmentType = lc.details[0]?.detail.treatmentType ?? null;
|
||||
const link = lc.details[0];
|
||||
const prosthesisCodes = [...new Set(lc.tasks.map((t) => t.prosthesisTypeCode).filter(Boolean))];
|
||||
const prosthesisLabels = await this.catalogLabels.resolveLabels(
|
||||
CatalogEntityKind.PROSTHESIS_TYPE,
|
||||
@@ -491,13 +492,15 @@ export class CasesService {
|
||||
clinic: lc.treatment.organization,
|
||||
patient: lc.treatment.patient,
|
||||
appointmentStartAt: lc.treatment.appointment?.startAt.toISOString() ?? null,
|
||||
treatmentTypes,
|
||||
details: lc.details.map((link) => ({
|
||||
id: link.detail.id,
|
||||
treatmentType: link.detail.treatmentType,
|
||||
teeth: normalizeTeeth(link.detail.teeth),
|
||||
comment: link.detail.comment,
|
||||
})),
|
||||
treatmentType,
|
||||
detail: link
|
||||
? {
|
||||
id: link.detail.id,
|
||||
treatmentType: link.detail.treatmentType,
|
||||
teeth: normalizeTeeth(link.detail.teeth),
|
||||
comment: link.detail.comment,
|
||||
}
|
||||
: null,
|
||||
toothProsthesis: lc.toothProsthesis.map((row) => ({
|
||||
treatmentDetailId: row.treatmentDetailId,
|
||||
tooth: row.tooth,
|
||||
|
||||
8
backend/src/modules/sms/sms.module.ts
Normal file
8
backend/src/modules/sms/sms.module.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { SmsService } from './sms.service';
|
||||
|
||||
@Module({
|
||||
providers: [SmsService],
|
||||
exports: [SmsService],
|
||||
})
|
||||
export class SmsModule {}
|
||||
63
backend/src/modules/sms/sms.service.ts
Normal file
63
backend/src/modules/sms/sms.service.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { Injectable, InternalServerErrorException, Logger } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
interface SmsIrVerifyResponse {
|
||||
status: number;
|
||||
message: string;
|
||||
data?: {
|
||||
messageId: number;
|
||||
cost: number;
|
||||
};
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class SmsService {
|
||||
private readonly logger = new Logger(SmsService.name);
|
||||
|
||||
constructor(private readonly configService: ConfigService) {}
|
||||
|
||||
async sendVerificationCode(mobile: string, code: string): Promise<void> {
|
||||
const apiKey = this.configService.get<string>('sms.apiKey');
|
||||
const templateId = this.configService.get<number>('sms.templateId');
|
||||
|
||||
if (!apiKey) {
|
||||
this.logger.warn(`SMS_IR_API_KEY not set — verification code for ${mobile}: ${code}`);
|
||||
return;
|
||||
}
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch('https://api.sms.ir/v1/send/verify', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'text/plain',
|
||||
'x-api-key': apiKey,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
mobile,
|
||||
templateId,
|
||||
parameters: [{ name: 'Code', value: code }],
|
||||
}),
|
||||
});
|
||||
console.log('request', templateId , apiKey,mobile, code);
|
||||
console.log('response', response);
|
||||
|
||||
} catch (error) {
|
||||
this.logger.error('sms.ir request failed', error);
|
||||
throw new InternalServerErrorException('Failed to send verification code');
|
||||
}
|
||||
|
||||
let payload: SmsIrVerifyResponse;
|
||||
try {
|
||||
payload = (await response.json()) as SmsIrVerifyResponse;
|
||||
} catch {
|
||||
throw new InternalServerErrorException('Invalid response from SMS provider');
|
||||
}
|
||||
|
||||
if (!response.ok || payload.status !== 1) {
|
||||
this.logger.error(`sms.ir error: ${payload.message}`);
|
||||
throw new InternalServerErrorException('Failed to send verification code');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -71,10 +71,8 @@ export class SaveLabCaseDto {
|
||||
@IsUUID()
|
||||
destinationOrganizationId?: string;
|
||||
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@IsUUID(undefined, { each: true })
|
||||
treatmentDetailIds: string[];
|
||||
@IsUUID()
|
||||
treatmentDetailId: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
|
||||
@@ -329,7 +329,7 @@ export class TreatmentsService {
|
||||
throw new NotFoundException('Save treatment details before creating lab cases');
|
||||
}
|
||||
|
||||
const detailIds = dto.labCases.flatMap((lc) => lc.treatmentDetailIds);
|
||||
const detailIds = dto.labCases.map((lc) => lc.treatmentDetailId);
|
||||
const uniqueDetailIds = new Set(detailIds);
|
||||
if (uniqueDetailIds.size !== detailIds.length) {
|
||||
throw new BadRequestException('Each treatment detail can belong to only one lab case');
|
||||
@@ -356,9 +356,9 @@ export class TreatmentsService {
|
||||
}
|
||||
|
||||
for (const row of lc.toothProsthesis ?? []) {
|
||||
if (!lc.treatmentDetailIds.includes(row.treatmentDetailId)) {
|
||||
if (lc.treatmentDetailId !== row.treatmentDetailId) {
|
||||
throw new BadRequestException(
|
||||
'Tooth prosthesis must reference a detail included in this lab case',
|
||||
'Tooth prosthesis must reference the lab case treatment detail',
|
||||
);
|
||||
}
|
||||
const detail = detailById.get(row.treatmentDetailId);
|
||||
@@ -416,11 +416,11 @@ export class TreatmentsService {
|
||||
});
|
||||
|
||||
await tx.labCaseDetail.deleteMany({ where: { labCaseId: row.id } });
|
||||
await tx.labCaseDetail.createMany({
|
||||
data: lc.treatmentDetailIds.map((treatmentDetailId) => ({
|
||||
await tx.labCaseDetail.create({
|
||||
data: {
|
||||
labCaseId: row.id,
|
||||
treatmentDetailId,
|
||||
})),
|
||||
treatmentDetailId: lc.treatmentDetailId,
|
||||
},
|
||||
});
|
||||
|
||||
await tx.labCaseToothProsthesis.deleteMany({ where: { labCaseId: row.id } });
|
||||
@@ -441,7 +441,7 @@ export class TreatmentsService {
|
||||
const validAttachments = await tx.treatmentDetailAttachment.findMany({
|
||||
where: {
|
||||
id: { in: attachmentIds },
|
||||
detailId: { in: lc.treatmentDetailIds },
|
||||
detailId: lc.treatmentDetailId,
|
||||
},
|
||||
select: { id: true },
|
||||
});
|
||||
@@ -502,7 +502,11 @@ export class TreatmentsService {
|
||||
}
|
||||
|
||||
if (labCase.details.length === 0) {
|
||||
throw new BadRequestException('Lab case must include at least one treatment detail');
|
||||
throw new BadRequestException('Lab case must include a treatment detail');
|
||||
}
|
||||
|
||||
if (labCase.details.length > 1) {
|
||||
throw new BadRequestException('Lab case can include only one treatment detail');
|
||||
}
|
||||
|
||||
assertCompleteToothProsthesisMap(labCase);
|
||||
@@ -811,13 +815,15 @@ export class TreatmentsService {
|
||||
clientId: lc.clientKey ?? lc.id,
|
||||
destinationOrganizationId: lc.destinationOrganizationId ?? null,
|
||||
sentAt: lc.sentAt?.toISOString() ?? null,
|
||||
treatmentDetailIds: lc.details?.map((d) => d.treatmentDetailId) ?? [],
|
||||
details: (lc.details ?? []).map((d) => ({
|
||||
id: d.detail?.id ?? d.treatmentDetailId,
|
||||
clientId: d.detail?.clientKey ?? d.treatmentDetailId,
|
||||
treatmentType: d.detail?.treatmentType ?? '',
|
||||
teeth: d.detail ? normalizeTeeth(d.detail.teeth) : [],
|
||||
})),
|
||||
treatmentDetailId: lc.details?.[0]?.treatmentDetailId ?? null,
|
||||
detail: lc.details?.[0]
|
||||
? {
|
||||
id: lc.details[0].detail?.id ?? lc.details[0].treatmentDetailId,
|
||||
clientId: lc.details[0].detail?.clientKey ?? lc.details[0].treatmentDetailId,
|
||||
treatmentType: lc.details[0].detail?.treatmentType ?? '',
|
||||
teeth: lc.details[0].detail ? normalizeTeeth(lc.details[0].detail.teeth) : [],
|
||||
}
|
||||
: null,
|
||||
toothProsthesis: (lc.toothProsthesis ?? []).map((tp) => ({
|
||||
treatmentDetailId: tp.treatmentDetailId,
|
||||
tooth: tp.tooth,
|
||||
|
||||
1
backend/tsconfig.build.tsbuildinfo
Normal file
1
backend/tsconfig.build.tsbuildinfo
Normal file
File diff suppressed because one or more lines are too long
@@ -12,6 +12,7 @@
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"target": "ES2023",
|
||||
"jsx": "react",
|
||||
"sourceMap": true,
|
||||
"outDir": "./dist",
|
||||
"baseUrl": "./",
|
||||
|
||||
@@ -132,7 +132,19 @@
|
||||
"organizationEmailPlaceholder": "contact@sunshineclinic.com",
|
||||
"organizationType": "Organization type",
|
||||
"dentalClinic": "Dental Clinic",
|
||||
"dentalLab": "Dental Lab"
|
||||
"dentalLab": "Dental Lab",
|
||||
"mobile": "Mobile number",
|
||||
"mobilePlaceholder": "0912 345 6789",
|
||||
"forgotPasswordTitle": "Reset your password",
|
||||
"forgotPasswordSubtitle": "Enter the mobile number on your account. We will send a verification code.",
|
||||
"codeSentHint": "Enter the verification code we sent to your mobile.",
|
||||
"sendCode": "Send verification code",
|
||||
"verificationCode": "Verification code",
|
||||
"verificationCodePlaceholder": "12345",
|
||||
"verifyAndContinue": "Verify and continue",
|
||||
"backToSignIn": "Back to sign in",
|
||||
"codeSendFailed": "Could not send verification code. Please try again.",
|
||||
"verifyFailed": "Invalid or expired verification code."
|
||||
},
|
||||
"landing": {
|
||||
"heroTitle": "Connect Dental Clinics & Labs",
|
||||
@@ -170,7 +182,10 @@
|
||||
"organizationNameMinLength": "Organization name must be at least 2 characters",
|
||||
"organizationEmailInvalid": "Please enter a valid organization email",
|
||||
"organizationTypeRequired": "Please select organization type",
|
||||
"passwordsDoNotMatch": "Passwords don't match"
|
||||
"passwordsDoNotMatch": "Passwords don't match",
|
||||
"mobileRequired": "Mobile number is required",
|
||||
"mobileInvalid": "Please enter a valid Iranian mobile number",
|
||||
"codeRequired": "Verification code is required"
|
||||
},
|
||||
"today": {
|
||||
"welcomeBack": "Welcome back!!",
|
||||
@@ -679,6 +694,16 @@
|
||||
"accountTitle": "Account",
|
||||
"accountSubtitle": "Profile and security settings for your login.",
|
||||
"accountPlaceholder": "Password change and profile editing will be wired here next (e.g. invite flow, reset password).",
|
||||
"changePasswordTitle": "Change password",
|
||||
"resetPasswordTitle": "Set a new password",
|
||||
"resetPasswordSubtitle": "Your mobile was verified. Choose a new password for your account.",
|
||||
"currentPassword": "Current password",
|
||||
"newPassword": "New password",
|
||||
"confirmNewPassword": "Confirm new password",
|
||||
"updatePassword": "Update password",
|
||||
"setNewPassword": "Save new password",
|
||||
"passwordChanged": "Password updated. Please sign in again.",
|
||||
"passwordChangeFailed": "Could not update password. Please try again.",
|
||||
"subscriptionsTitle": "Subscriptions",
|
||||
"subscriptionsSubtitle": "Your DyoLink workspace plan and seats for {orgName}. Clinic and lab income tracking stays under the sidebar Billing tab.",
|
||||
"noSubscriptionNotice": "This organization has no active subscription. Select a plan below to start the purchase process.",
|
||||
|
||||
@@ -132,7 +132,19 @@
|
||||
"organizationEmailPlaceholder": "contact@sunshineclinic.com",
|
||||
"organizationType": "نوع سازمان",
|
||||
"dentalClinic": "کلینیک دندانپزشکی",
|
||||
"dentalLab": "لابراتوار دندانپزشکی"
|
||||
"dentalLab": "لابراتوار دندانپزشکی",
|
||||
"mobile": "شماره موبایل",
|
||||
"mobilePlaceholder": "۰۹۱۲ ۳۴۵ ۶۷۸۹",
|
||||
"forgotPasswordTitle": "بازیابی رمز عبور",
|
||||
"forgotPasswordSubtitle": "شماره موبایل ثبتشده در حساب خود را وارد کنید. کد تأیید برای شما ارسال میشود.",
|
||||
"codeSentHint": "کد تأیید ارسالشده به موبایل خود را وارد کنید.",
|
||||
"sendCode": "ارسال کد تأیید",
|
||||
"verificationCode": "کد تأیید",
|
||||
"verificationCodePlaceholder": "۱۲۳۴۵",
|
||||
"verifyAndContinue": "تأیید و ادامه",
|
||||
"backToSignIn": "بازگشت به ورود",
|
||||
"codeSendFailed": "ارسال کد تأیید انجام نشد. دوباره تلاش کنید.",
|
||||
"verifyFailed": "کد تأیید نامعتبر یا منقضی شده است."
|
||||
},
|
||||
"landing": {
|
||||
"heroTitle": "اتصال کلینیکها و لابراتوارهای دندانپزشکی",
|
||||
@@ -170,7 +182,10 @@
|
||||
"organizationNameMinLength": "نام سازمان باید حداقل ۲ کاراکتر باشد",
|
||||
"organizationEmailInvalid": "لطفاً یک ایمیل سازمانی معتبر وارد کنید",
|
||||
"organizationTypeRequired": "لطفاً نوع سازمان را انتخاب کنید",
|
||||
"passwordsDoNotMatch": "رمزهای عبور مطابقت ندارند"
|
||||
"passwordsDoNotMatch": "رمزهای عبور مطابقت ندارند",
|
||||
"mobileRequired": "شماره موبایل الزامی است",
|
||||
"mobileInvalid": "لطفاً یک شماره موبایل ایرانی معتبر وارد کنید",
|
||||
"codeRequired": "کد تأیید الزامی است"
|
||||
},
|
||||
"today": {
|
||||
"welcomeBack": "خوش آمدید!!",
|
||||
@@ -680,6 +695,16 @@
|
||||
"accountTitle": "حساب کاربری",
|
||||
"accountSubtitle": "تنظیمات پروفایل و امنیت برای ورود شما.",
|
||||
"accountPlaceholder": "تغییر رمز عبور و ویرایش پروفایل در مرحله بعدی در اینجا قرار میگیرند (مثلاً فرآیند دعوت، بازنشانی رمز عبور).",
|
||||
"changePasswordTitle": "تغییر رمز عبور",
|
||||
"resetPasswordTitle": "تنظیم رمز عبور جدید",
|
||||
"resetPasswordSubtitle": "موبایل شما تأیید شد. رمز عبور جدید برای حساب خود انتخاب کنید.",
|
||||
"currentPassword": "رمز عبور فعلی",
|
||||
"newPassword": "رمز عبور جدید",
|
||||
"confirmNewPassword": "تأیید رمز عبور جدید",
|
||||
"updatePassword": "بهروزرسانی رمز عبور",
|
||||
"setNewPassword": "ذخیره رمز عبور جدید",
|
||||
"passwordChanged": "رمز عبور بهروزرسانی شد. لطفاً دوباره وارد شوید.",
|
||||
"passwordChangeFailed": "بهروزرسانی رمز عبور انجام نشد. دوباره تلاش کنید.",
|
||||
"subscriptionsTitle": "اشتراکها",
|
||||
"subscriptionsSubtitle": "طرح و مجوزهای فضای کاری DyoLink شما برای {orgName}. پیگیری درآمد کلینیک و لابراتوار در برگه صورتحساب در نوار کناری قرار دارد.",
|
||||
"noSubscriptionNotice": "این سازمان اشتراک فعالی ندارد. برای شروع فرآیند خرید، یک طرح زیر را انتخاب کنید.",
|
||||
|
||||
@@ -132,7 +132,19 @@
|
||||
"organizationEmailPlaceholder": "contact@sunshineclinic.com",
|
||||
"organizationType": "Organisatietype",
|
||||
"dentalClinic": "Tandartspraktijk",
|
||||
"dentalLab": "Tandtechnisch Laboratorium"
|
||||
"dentalLab": "Tandtechnisch Laboratorium",
|
||||
"mobile": "Mobiel nummer",
|
||||
"mobilePlaceholder": "0612 345 678",
|
||||
"forgotPasswordTitle": "Wachtwoord herstellen",
|
||||
"forgotPasswordSubtitle": "Voer het mobiele nummer van uw account in. We sturen een verificatiecode.",
|
||||
"codeSentHint": "Voer de verificatiecode in die we naar uw mobiel hebben gestuurd.",
|
||||
"sendCode": "Verificatiecode versturen",
|
||||
"verificationCode": "Verificatiecode",
|
||||
"verificationCodePlaceholder": "12345",
|
||||
"verifyAndContinue": "Verifiëren en doorgaan",
|
||||
"backToSignIn": "Terug naar inloggen",
|
||||
"codeSendFailed": "Verificatiecode kon niet worden verstuurd. Probeer het opnieuw.",
|
||||
"verifyFailed": "Ongeldige of verlopen verificatiecode."
|
||||
},
|
||||
"landing": {
|
||||
"heroTitle": "Verbind Tandheelkundige Klinieken & Laboratoria",
|
||||
@@ -170,7 +182,10 @@
|
||||
"organizationNameMinLength": "Organisatienaam moet minimaal 2 tekens bevatten",
|
||||
"organizationEmailInvalid": "Voer een geldig organisatie-e-mailadres in",
|
||||
"organizationTypeRequired": "Selecteer een organisatietype",
|
||||
"passwordsDoNotMatch": "Wachtwoorden komen niet overeen"
|
||||
"passwordsDoNotMatch": "Wachtwoorden komen niet overeen",
|
||||
"mobileRequired": "Mobiel nummer is verplicht",
|
||||
"mobileInvalid": "Voer een geldig Iraans mobiel nummer in",
|
||||
"codeRequired": "Verificatiecode is verplicht"
|
||||
},
|
||||
"today": {
|
||||
"welcomeBack": "Welkom terug!!",
|
||||
@@ -680,6 +695,16 @@
|
||||
"accountTitle": "Account",
|
||||
"accountSubtitle": "Profiel- en beveiligingsinstellingen voor uw login.",
|
||||
"accountPlaceholder": "Wachtwoordwijziging en profielbewerking worden hierna hier aangesloten (bijv. uitnodigingsflow, wachtwoord herstellen).",
|
||||
"changePasswordTitle": "Wachtwoord wijzigen",
|
||||
"resetPasswordTitle": "Nieuw wachtwoord instellen",
|
||||
"resetPasswordSubtitle": "Uw mobiel is geverifieerd. Kies een nieuw wachtwoord voor uw account.",
|
||||
"currentPassword": "Huidig wachtwoord",
|
||||
"newPassword": "Nieuw wachtwoord",
|
||||
"confirmNewPassword": "Bevestig nieuw wachtwoord",
|
||||
"updatePassword": "Wachtwoord bijwerken",
|
||||
"setNewPassword": "Nieuw wachtwoord opslaan",
|
||||
"passwordChanged": "Wachtwoord bijgewerkt. Log opnieuw in.",
|
||||
"passwordChangeFailed": "Wachtwoord kon niet worden bijgewerkt. Probeer het opnieuw.",
|
||||
"subscriptionsTitle": "Abonnementen",
|
||||
"subscriptionsSubtitle": "Uw DyoLink-werkruimteplan en plaatsen voor {orgName}. Kliniek- en laboratoriuminkomsten blijven onder het tabblad Facturatie in de zijbalk.",
|
||||
"noSubscriptionNotice": "Deze organisatie heeft geen actief abonnement. Selecteer hieronder een abonnement om het aankoopproces te starten.",
|
||||
|
||||
@@ -340,7 +340,7 @@ export default function CasesPage() {
|
||||
{formatCaseDateTime(item.sentAt, locale)}
|
||||
</div>
|
||||
<div className="text-xs text-text-muted mt-1 truncate">
|
||||
{item.treatmentTypes.map(treatmentLabel).join(', ')}
|
||||
{item.treatmentType ? treatmentLabel(item.treatmentType) : '—'}
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<CaseTaskProgressBar
|
||||
|
||||
@@ -1,28 +1,180 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Link } from '@/i18n/navigation';
|
||||
import { Link, useRouter } from '@/i18n/navigation';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { Lock } from 'lucide-react';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { authApi } from '@/lib/api/auth';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import { Toast } from '@/components/ui/shared/Toast';
|
||||
|
||||
type PasswordForm = {
|
||||
currentPassword: string;
|
||||
newPassword: string;
|
||||
confirmPassword: string;
|
||||
};
|
||||
|
||||
export default function AccountSettingsPage() {
|
||||
const t = useTranslations('settings');
|
||||
const tAuth = useTranslations('auth');
|
||||
const tCommon = useTranslations('common');
|
||||
const tValidation = useTranslations('validation');
|
||||
const { user, isAuthReady } = useAuth();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const isResetFlow = searchParams.get('reset') === '1';
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
const passwordSchema = useMemo(
|
||||
() =>
|
||||
z
|
||||
.object({
|
||||
currentPassword: z.string(),
|
||||
newPassword: z
|
||||
.string()
|
||||
.min(8, tValidation('passwordMinLength'))
|
||||
.regex(/[A-Z]/, tValidation('passwordUppercase'))
|
||||
.regex(/[0-9]/, tValidation('passwordNumber')),
|
||||
confirmPassword: z.string(),
|
||||
})
|
||||
.refine((data) => data.newPassword === data.confirmPassword, {
|
||||
message: tValidation('passwordsDoNotMatch'),
|
||||
path: ['confirmPassword'],
|
||||
})
|
||||
.superRefine((data, ctx) => {
|
||||
if (!isResetFlow && !data.currentPassword.trim()) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: tValidation('passwordRequired'),
|
||||
path: ['currentPassword'],
|
||||
});
|
||||
}
|
||||
}),
|
||||
[isResetFlow, tValidation],
|
||||
);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
formState: { errors },
|
||||
} = useForm<PasswordForm>({
|
||||
resolver: zodResolver(passwordSchema),
|
||||
defaultValues: {
|
||||
currentPassword: '',
|
||||
newPassword: '',
|
||||
confirmPassword: '',
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (isAuthReady && !user) {
|
||||
router.replace('/login');
|
||||
}
|
||||
}, [isAuthReady, user, router]);
|
||||
|
||||
const onSubmit = async (data: PasswordForm) => {
|
||||
try {
|
||||
setError(null);
|
||||
setSuccessMessage(null);
|
||||
setIsSubmitting(true);
|
||||
|
||||
await authApi.changePassword({
|
||||
...(isResetFlow ? {} : { currentPassword: data.currentPassword }),
|
||||
newPassword: data.newPassword,
|
||||
});
|
||||
|
||||
reset();
|
||||
setSuccessMessage(t('passwordChanged'));
|
||||
router.replace('/login');
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : t('passwordChangeFailed');
|
||||
setError(message || t('passwordChangeFailed'));
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!isAuthReady || !user) {
|
||||
return (
|
||||
<p className="text-text-secondary text-sm">{tCommon('loadingEllipsis')}</p>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div>
|
||||
<Link
|
||||
href="/today"
|
||||
className="text-sm text-primary hover:opacity-90"
|
||||
>
|
||||
<Link href="/today" className="text-sm text-primary hover:opacity-90">
|
||||
{tCommon('backToApp')}
|
||||
</Link>
|
||||
<h1 className="text-2xl font-semibold text-text-primary mt-4">{t('accountTitle')}</h1>
|
||||
<p className="text-text-secondary text-sm mt-2">{t('accountSubtitle')}</p>
|
||||
<p className="text-text-secondary text-sm mt-2">
|
||||
{isResetFlow ? t('resetPasswordSubtitle') : t('accountSubtitle')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="surface-card p-6 space-y-3">
|
||||
<p className="text-sm text-text-secondary">{t('accountPlaceholder')}</p>
|
||||
<div className="surface-card p-6 sm:p-8 max-w-lg">
|
||||
<h2 className="text-lg font-medium text-text-primary mb-1">
|
||||
{isResetFlow ? t('resetPasswordTitle') : t('changePasswordTitle')}
|
||||
</h2>
|
||||
<p className="text-sm text-text-secondary mb-6">
|
||||
{user.email}
|
||||
{user.mobile ? ` · ${user.mobile}` : ''}
|
||||
</p>
|
||||
|
||||
<form className="space-y-5" onSubmit={handleSubmit(onSubmit)}>
|
||||
{!isResetFlow && (
|
||||
<Input
|
||||
label={t('currentPassword')}
|
||||
{...register('currentPassword')}
|
||||
type="password"
|
||||
placeholder={tAuth('passwordPlaceholder')}
|
||||
error={errors.currentPassword?.message}
|
||||
icon={<Lock className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
)}
|
||||
|
||||
<Input
|
||||
label={t('newPassword')}
|
||||
{...register('newPassword')}
|
||||
type="password"
|
||||
placeholder={tAuth('passwordPlaceholder')}
|
||||
error={errors.newPassword?.message}
|
||||
icon={<Lock className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
|
||||
<Input
|
||||
label={t('confirmNewPassword')}
|
||||
{...register('confirmPassword')}
|
||||
type="password"
|
||||
placeholder={tAuth('passwordPlaceholder')}
|
||||
error={errors.confirmPassword?.message}
|
||||
icon={<Lock className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-950/30 border border-red-600/40 rounded-[var(--radius-md)]">
|
||||
<p className="text-sm text-red-600">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button type="submit" variant="primary" isLoading={isSubmitting}>
|
||||
{isResetFlow ? t('setNewPassword') : t('updatePassword')}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{successMessage && (
|
||||
<Toast variant="success">{successMessage}</Toast>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
206
frontend/src/app/[locale]/(public)/forgot-password/page.tsx
Normal file
206
frontend/src/app/[locale]/(public)/forgot-password/page.tsx
Normal file
@@ -0,0 +1,206 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Link, useRouter } from '@/i18n/navigation';
|
||||
import { Phone, ShieldCheck } from 'lucide-react';
|
||||
import { authApi } from '@/lib/api/auth';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import { TopBarControls } from '@/components/ui/shared/TopBarControls';
|
||||
|
||||
type ForgotPasswordForm = {
|
||||
mobile: string;
|
||||
code: string;
|
||||
};
|
||||
|
||||
function normalizeIranMobile(input: string): string {
|
||||
let digits = input.replace(/\D/g, '');
|
||||
if (digits.startsWith('98') && digits.length === 12) digits = digits.slice(2);
|
||||
if (digits.startsWith('0') && digits.length === 11) digits = digits.slice(1);
|
||||
return digits;
|
||||
}
|
||||
|
||||
export default function ForgotPasswordPage() {
|
||||
const t = useTranslations('auth');
|
||||
const tCommon = useTranslations('common');
|
||||
const tValidation = useTranslations('validation');
|
||||
const router = useRouter();
|
||||
const { refreshSession } = useAuth();
|
||||
const [step, setStep] = useState<'mobile' | 'code'>('mobile');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [isVerifying, setIsVerifying] = useState(false);
|
||||
const [sentMobile, setSentMobile] = useState('');
|
||||
|
||||
const schema = useMemo(
|
||||
() =>
|
||||
z.object({
|
||||
mobile: z
|
||||
.string()
|
||||
.min(1, tValidation('mobileRequired'))
|
||||
.refine((value) => /^9\d{9}$/.test(normalizeIranMobile(value)), {
|
||||
message: tValidation('mobileInvalid'),
|
||||
}),
|
||||
code: z.string(),
|
||||
}),
|
||||
[tValidation],
|
||||
);
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
getValues,
|
||||
formState: { errors },
|
||||
} = useForm<ForgotPasswordForm>({
|
||||
resolver: zodResolver(schema),
|
||||
defaultValues: { mobile: '', code: '' },
|
||||
});
|
||||
|
||||
const onSendCode = async () => {
|
||||
const mobile = getValues('mobile');
|
||||
const parsed = schema.safeParse({ mobile, code: '' });
|
||||
if (!parsed.success) {
|
||||
setError(parsed.error.issues[0]?.message ?? tValidation('mobileInvalid'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
setIsSending(true);
|
||||
await authApi.sendForgotPasswordCode(mobile);
|
||||
setSentMobile(mobile);
|
||||
setStep('code');
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : t('codeSendFailed');
|
||||
setError(message || t('codeSendFailed'));
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
}
|
||||
};
|
||||
|
||||
const onVerify = async (data: ForgotPasswordForm) => {
|
||||
if (!data.code.trim()) {
|
||||
setError(tValidation('codeRequired'));
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setError(null);
|
||||
setIsVerifying(true);
|
||||
const response = await authApi.verifyForgotPasswordCode(
|
||||
sentMobile || data.mobile,
|
||||
data.code.trim(),
|
||||
);
|
||||
|
||||
const orgs = response.data.organizations;
|
||||
if (orgs.length === 1) {
|
||||
await authApi.selectOrganization(orgs[0].id);
|
||||
localStorage.setItem('currentOrganizationId', orgs[0].id);
|
||||
await refreshSession();
|
||||
router.push('/settings/account?reset=1');
|
||||
return;
|
||||
}
|
||||
|
||||
if (orgs.length > 1) {
|
||||
sessionStorage.setItem('authRedirect', '/settings/account?reset=1');
|
||||
await refreshSession();
|
||||
router.push('/select-organization');
|
||||
return;
|
||||
}
|
||||
|
||||
await refreshSession();
|
||||
router.push('/settings/account?reset=1');
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : t('verifyFailed');
|
||||
setError(message || t('verifyFailed'));
|
||||
} finally {
|
||||
setIsVerifying(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="relative min-h-screen app-web-bg flex flex-col justify-center py-12 sm:px-6 lg:px-8">
|
||||
<div className="absolute top-4 right-4">
|
||||
<TopBarControls />
|
||||
</div>
|
||||
|
||||
<div className="sm:mx-auto sm:w-full sm:max-w-md">
|
||||
<Link href="/" className="flex justify-center">
|
||||
<span className="text-3xl font-semibold text-text-primary">{tCommon('appName')}</span>
|
||||
</Link>
|
||||
<h2 className="mt-6 text-center text-3xl font-semibold text-text-primary">
|
||||
{t('forgotPasswordTitle')}
|
||||
</h2>
|
||||
<p className="mt-2 text-center text-sm text-text-secondary">
|
||||
{step === 'mobile' ? t('forgotPasswordSubtitle') : t('codeSentHint')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
|
||||
<div className="surface-card py-8 px-4 sm:px-10">
|
||||
<form
|
||||
className="space-y-6"
|
||||
onSubmit={handleSubmit(step === 'code' ? onVerify : () => undefined)}
|
||||
>
|
||||
{step === 'mobile' ? (
|
||||
<Input
|
||||
label={t('mobile')}
|
||||
{...register('mobile')}
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
autoComplete="tel"
|
||||
placeholder={t('mobilePlaceholder')}
|
||||
error={errors.mobile?.message}
|
||||
icon={<Phone className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
) : (
|
||||
<Input
|
||||
label={t('verificationCode')}
|
||||
{...register('code')}
|
||||
type="text"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
placeholder={t('verificationCodePlaceholder')}
|
||||
error={errors.code?.message}
|
||||
icon={<ShieldCheck className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<div className="p-3 bg-red-50 border border-red-200 rounded-lg">
|
||||
<p className="text-sm text-red-600">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'mobile' ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
isLoading={isSending}
|
||||
fullWidth
|
||||
onClick={() => void onSendCode()}
|
||||
>
|
||||
{t('sendCode')}
|
||||
</Button>
|
||||
) : (
|
||||
<Button type="submit" variant="primary" isLoading={isVerifying} fullWidth>
|
||||
{t('verifyAndContinue')}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<p className="text-center text-sm text-text-secondary">
|
||||
<Link href="/login" className="font-medium text-primary hover:opacity-90">
|
||||
{t('backToSignIn')}
|
||||
</Link>
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { useTranslations } from 'next-intl';
|
||||
import { Link } from '@/i18n/navigation';
|
||||
import { Mail, Lock } from 'lucide-react';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { getRememberedEmail } from '@/lib/auth/rememberMe';
|
||||
import { Button } from '@/components/ui/shared/Button';
|
||||
import { Input } from '@/components/ui/shared/Input';
|
||||
import { TopBarControls } from '@/components/ui/shared/TopBarControls';
|
||||
@@ -16,6 +17,7 @@ import { TopBarControls } from '@/components/ui/shared/TopBarControls';
|
||||
type LoginForm = {
|
||||
email: string;
|
||||
password: string;
|
||||
rememberMe: boolean;
|
||||
};
|
||||
|
||||
export default function LoginPage() {
|
||||
@@ -25,12 +27,14 @@ export default function LoginPage() {
|
||||
const { login, isLoading, user, isAuthReady } = useAuth();
|
||||
const router = useRouter();
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [savedEmail] = useState(() => getRememberedEmail());
|
||||
|
||||
const loginSchema = useMemo(
|
||||
() =>
|
||||
z.object({
|
||||
email: z.string().email(tValidation('emailInvalid')),
|
||||
password: z.string().min(1, tValidation('passwordRequired')),
|
||||
rememberMe: z.boolean(),
|
||||
}),
|
||||
[tValidation],
|
||||
);
|
||||
@@ -47,12 +51,16 @@ export default function LoginPage() {
|
||||
formState: { errors },
|
||||
} = useForm<LoginForm>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
defaultValues: {
|
||||
email: savedEmail,
|
||||
rememberMe: Boolean(savedEmail),
|
||||
},
|
||||
});
|
||||
|
||||
const onSubmit = async (data: LoginForm) => {
|
||||
try {
|
||||
setError(null);
|
||||
await login(data.email, data.password);
|
||||
await login(data.email, data.password, data.rememberMe);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : t('invalidCredentials');
|
||||
setError(message || t('invalidCredentials'));
|
||||
@@ -112,9 +120,9 @@ export default function LoginPage() {
|
||||
<div className="flex items-center">
|
||||
<input
|
||||
id="remember-me"
|
||||
name="remember-me"
|
||||
type="checkbox"
|
||||
className="h-4 w-4 rounded border-border bg-background-secondary text-primary focus:ring-primary/40"
|
||||
{...register('rememberMe')}
|
||||
/>
|
||||
<label htmlFor="remember-me" className="ml-2 block text-sm text-text-secondary">
|
||||
{t('rememberMe')}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { zodResolver } from '@hookform/resolvers/zod';
|
||||
import * as z from 'zod';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { Link } from '@/i18n/navigation';
|
||||
import { Mail, Lock, User } from 'lucide-react';
|
||||
import { Mail, Lock, User, Phone } from 'lucide-react';
|
||||
import { useAuth } from '@/lib/hooks/useAuth';
|
||||
import { OrganizationDetailsFields } from '@/components/ui/auth/OrganizationDetailsFields';
|
||||
import { RegistrationProgressSteps } from '@/components/ui/auth/RegistrationProgressSteps';
|
||||
@@ -17,6 +17,7 @@ import { TopBarControls } from '@/components/ui/shared/TopBarControls';
|
||||
type RegisterForm = {
|
||||
name: string;
|
||||
email: string;
|
||||
mobile: string;
|
||||
password: string;
|
||||
confirmPassword: string;
|
||||
organizationName: string;
|
||||
@@ -24,6 +25,13 @@ type RegisterForm = {
|
||||
organizationType: 'CLINIC' | 'LAB';
|
||||
};
|
||||
|
||||
function normalizeIranMobile(input: string): string {
|
||||
let digits = input.replace(/\D/g, '');
|
||||
if (digits.startsWith('98') && digits.length === 12) digits = digits.slice(2);
|
||||
if (digits.startsWith('0') && digits.length === 11) digits = digits.slice(1);
|
||||
return digits;
|
||||
}
|
||||
|
||||
export default function RegisterPage() {
|
||||
const t = useTranslations('auth');
|
||||
const tCommon = useTranslations('common');
|
||||
@@ -38,6 +46,12 @@ export default function RegisterPage() {
|
||||
.object({
|
||||
name: z.string().min(2, tValidation('nameMinLength')),
|
||||
email: z.string().email(tValidation('emailInvalid')),
|
||||
mobile: z
|
||||
.string()
|
||||
.min(1, tValidation('mobileRequired'))
|
||||
.refine((value) => /^9\d{9}$/.test(normalizeIranMobile(value)), {
|
||||
message: tValidation('mobileInvalid'),
|
||||
}),
|
||||
password: z
|
||||
.string()
|
||||
.min(8, tValidation('passwordMinLength'))
|
||||
@@ -74,7 +88,7 @@ export default function RegisterPage() {
|
||||
const handleNext = async () => {
|
||||
const fieldsToValidate =
|
||||
step === 1
|
||||
? (['name', 'email', 'password', 'confirmPassword'] as const)
|
||||
? (['name', 'email', 'mobile', 'password', 'confirmPassword'] as const)
|
||||
: (['organizationName', 'organizationEmail', 'organizationType'] as const);
|
||||
|
||||
const isValid = await trigger([...fieldsToValidate]);
|
||||
@@ -90,6 +104,7 @@ export default function RegisterPage() {
|
||||
data.email,
|
||||
data.password,
|
||||
data.name,
|
||||
data.mobile,
|
||||
data.organizationName,
|
||||
data.organizationEmail,
|
||||
data.organizationType,
|
||||
@@ -157,6 +172,16 @@ export default function RegisterPage() {
|
||||
error={errors.email?.message}
|
||||
icon={<Mail className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
<Input
|
||||
label={t('mobile')}
|
||||
{...register('mobile')}
|
||||
type="tel"
|
||||
inputMode="tel"
|
||||
autoComplete="tel"
|
||||
placeholder={t('mobilePlaceholder')}
|
||||
error={errors.mobile?.message}
|
||||
icon={<Phone className="h-5 w-5 icon-flat" />}
|
||||
/>
|
||||
<Input
|
||||
label={t('password')}
|
||||
{...register('password')}
|
||||
|
||||
@@ -152,27 +152,23 @@ export function CaseDetailPanel({
|
||||
</header>
|
||||
|
||||
<CaseToothChartPanel
|
||||
details={labCase.details}
|
||||
details={labCase.detail ? [{ teeth: labCase.detail.teeth }] : []}
|
||||
prosthesisRows={prosthesisRows}
|
||||
className="w-full"
|
||||
/>
|
||||
|
||||
{labCase.details.length > 0 ? (
|
||||
{labCase.detail ? (
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-sm font-medium text-text-primary">{t('treatmentDetails')}</h3>
|
||||
<ul className="space-y-2 text-sm">
|
||||
{labCase.details.map((detail) => (
|
||||
<li key={detail.id} className="rounded-md bg-background border border-border p-2">
|
||||
<div className="font-medium">{treatmentLabel(detail.treatmentType)}</div>
|
||||
<div className="text-text-muted">
|
||||
{t('teethLabel')}: {detail.teeth.join(', ') || '—'}
|
||||
</div>
|
||||
{detail.comment ? (
|
||||
<div className="text-text-muted mt-1">{detail.comment}</div>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="rounded-md bg-background border border-border p-2 text-sm">
|
||||
<div className="font-medium">{treatmentLabel(labCase.detail.treatmentType)}</div>
|
||||
<div className="text-text-muted">
|
||||
{t('teethLabel')}: {labCase.detail.teeth.join(', ') || '—'}
|
||||
</div>
|
||||
{labCase.detail.comment ? (
|
||||
<div className="text-text-muted mt-1">{labCase.detail.comment}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -247,7 +247,7 @@ export function ConnectionCaseHistoryContent({
|
||||
{formatCaseDateTime(item.sentAt, locale)}
|
||||
</div>
|
||||
<div className="text-xs text-text-muted mt-1 truncate">
|
||||
{item.treatmentTypes.map(treatmentLabel).join(', ')}
|
||||
{item.treatmentType ? treatmentLabel(item.treatmentType) : '—'}
|
||||
</div>
|
||||
<div className="mt-2">
|
||||
<CaseTaskProgressBar
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
'use client';
|
||||
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import React, { forwardRef } from 'react';
|
||||
import React, { forwardRef, useId } from 'react';
|
||||
|
||||
interface DropdownProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
|
||||
label?: string;
|
||||
@@ -10,7 +10,8 @@ interface DropdownProps extends React.SelectHTMLAttributes<HTMLSelectElement> {
|
||||
|
||||
export const Dropdown = forwardRef<HTMLSelectElement, DropdownProps>(
|
||||
({ label, error, className = '', id, children, ...props }, ref) => {
|
||||
const selectId = id || `dropdown-${Math.random().toString(36).slice(2, 9)}`;
|
||||
const genId = useId();
|
||||
const selectId = id ?? genId;
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// src/components/ui/Input.tsx
|
||||
'use client';
|
||||
|
||||
import React, { forwardRef, useId } from 'react';
|
||||
|
||||
interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
@@ -9,8 +10,8 @@ interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {
|
||||
|
||||
export const Input = forwardRef<HTMLInputElement, InputProps>(
|
||||
({ label, error, icon, className = '', id, ...props }, ref) => {
|
||||
const generatedId = useId();
|
||||
const inputId = id || generatedId;
|
||||
const genId = useId();
|
||||
const inputId = id ?? genId;
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
|
||||
@@ -22,7 +22,6 @@ interface LabCasesDispatchPanelProps {
|
||||
labDependentCodes: Set<string>;
|
||||
treatmentCatalog: TreatmentCatalogEntry[];
|
||||
activeLabCaseId: string | null;
|
||||
onActiveLabCaseChange: (id: string) => void;
|
||||
onLabCasesChange: (labCases: LabCaseDraft[]) => void;
|
||||
disabled: boolean;
|
||||
canEdit: boolean;
|
||||
@@ -40,64 +39,30 @@ interface LabCasesDispatchPanelProps {
|
||||
function sentDetailClientIds(labCases: LabCaseDraft[]): Set<string> {
|
||||
const ids = new Set<string>();
|
||||
for (const lc of labCases) {
|
||||
if (!lc.sentAt) continue;
|
||||
for (const id of lc.detailClientIds) ids.add(id);
|
||||
if (lc.sentAt && lc.detailClientId) ids.add(lc.detailClientId);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function detailInOtherDraftShipment(
|
||||
detailClientId: string,
|
||||
labCases: LabCaseDraft[],
|
||||
activeLabCaseClientId: string,
|
||||
): boolean {
|
||||
return labCases.some(
|
||||
(lc) =>
|
||||
!lc.sentAt &&
|
||||
lc.clientId !== activeLabCaseClientId &&
|
||||
lc.detailClientIds.includes(detailClientId),
|
||||
);
|
||||
}
|
||||
|
||||
function selectableDetailsForDraftShipment(
|
||||
details: TreatmentDetailDraft[],
|
||||
labCases: LabCaseDraft[],
|
||||
labDependentCodes: Set<string>,
|
||||
activeLabCase: LabCaseDraft,
|
||||
): TreatmentDetailDraft[] {
|
||||
const sent = sentDetailClientIds(labCases);
|
||||
return details.filter((d) => {
|
||||
if (!labDependentCodes.has(d.treatmentType)) return false;
|
||||
if (sent.has(d.clientId)) return false;
|
||||
if (activeLabCase.detailClientIds.includes(d.clientId)) return true;
|
||||
return !detailInOtherDraftShipment(d.clientId, labCases, activeLabCase.clientId);
|
||||
});
|
||||
}
|
||||
|
||||
function prosthesisTeethRows(
|
||||
labCase: LabCaseDraft,
|
||||
details: TreatmentDetailDraft[],
|
||||
scopeDetailClientId?: string,
|
||||
activeDetail: TreatmentDetailDraft,
|
||||
detailNumber: number,
|
||||
): Array<{ detailClientId: string; tooth: string; detailNumber: number }> {
|
||||
const rows: Array<{ detailClientId: string; tooth: string; detailNumber: number }> = [];
|
||||
for (const clientId of labCase.detailClientIds) {
|
||||
if (scopeDetailClientId && clientId !== scopeDetailClientId) continue;
|
||||
const detail = details.find((d) => d.clientId === clientId);
|
||||
if (!detail || detail.treatmentType !== 'prosthesis') continue;
|
||||
const detailNumber = details.findIndex((d) => d.clientId === clientId) + 1;
|
||||
for (const tooth of detail.teeth) {
|
||||
rows.push({ detailClientId: clientId, tooth, detailNumber });
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
if (labCase.detailClientId !== activeDetail.clientId) return [];
|
||||
if (activeDetail.treatmentType !== 'prosthesis') return [];
|
||||
|
||||
return activeDetail.teeth.map((tooth) => ({
|
||||
detailClientId: activeDetail.clientId,
|
||||
tooth,
|
||||
detailNumber,
|
||||
}));
|
||||
}
|
||||
|
||||
function isProsthesisMapComplete(
|
||||
labCase: LabCaseDraft,
|
||||
details: TreatmentDetailDraft[],
|
||||
scopeDetailClientId?: string,
|
||||
rows: Array<{ detailClientId: string; tooth: string }>,
|
||||
): boolean {
|
||||
const rows = prosthesisTeethRows(labCase, details, scopeDetailClientId);
|
||||
if (rows.length === 0) return true;
|
||||
return rows.every((row) =>
|
||||
labCase.toothProsthesis.some(
|
||||
@@ -116,7 +81,6 @@ export function LabCasesDispatchPanel({
|
||||
labDependentCodes,
|
||||
treatmentCatalog,
|
||||
activeLabCaseId,
|
||||
onActiveLabCaseChange,
|
||||
onLabCasesChange,
|
||||
disabled,
|
||||
canEdit,
|
||||
@@ -151,7 +115,7 @@ export function LabCasesDispatchPanel({
|
||||
);
|
||||
|
||||
const labCaseForActiveDetail =
|
||||
labCases.find((lc) => lc.detailClientIds.includes(activeDetailId)) ?? null;
|
||||
labCases.find((lc) => lc.detailClientId === activeDetailId) ?? null;
|
||||
|
||||
const activeLabCase =
|
||||
labCaseForActiveDetail ??
|
||||
@@ -159,21 +123,20 @@ export function LabCasesDispatchPanel({
|
||||
|
||||
const detailAlreadyInShipment = Boolean(labCaseForActiveDetail);
|
||||
const canAddLabShipment =
|
||||
!detailAlreadyInShipment &&
|
||||
!detailInOtherDraftShipment(activeDetailId, labCases, '') &&
|
||||
!sentDetailClientIds(labCases).has(activeDetailId);
|
||||
!detailAlreadyInShipment && !sentDetailClientIds(labCases).has(activeDetailId);
|
||||
|
||||
const sent = Boolean(activeLabCase?.sentAt);
|
||||
const activeDetailNumber = details.findIndex((d) => d.clientId === activeDetailId) + 1;
|
||||
|
||||
const activeLabOrgName = activeLabCase?.destinationOrganizationId
|
||||
? orgs.find((o) => o.id === activeLabCase.destinationOrganizationId)?.name
|
||||
: null;
|
||||
|
||||
const prosthesisRows = activeLabCase
|
||||
? prosthesisTeethRows(activeLabCase, details, activeDetailId)
|
||||
const prosthesisRows = activeLabCase && activeDetail
|
||||
? prosthesisTeethRows(activeLabCase, activeDetail, activeDetailNumber)
|
||||
: [];
|
||||
const prosthesisComplete = activeLabCase
|
||||
? isProsthesisMapComplete(activeLabCase, details, activeDetailId)
|
||||
? isProsthesisMapComplete(activeLabCase, prosthesisRows)
|
||||
: true;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -197,25 +160,18 @@ export function LabCasesDispatchPanel({
|
||||
};
|
||||
}, [activeLabCase?.destinationOrganizationId]);
|
||||
|
||||
// Reset the pending (unposted) comment when switching to another shipment.
|
||||
useEffect(() => {
|
||||
setPendingComment('');
|
||||
}, [activeLabCase?.clientId]);
|
||||
|
||||
// Hide dispatch when the selected treatment detail is not lab-dependent.
|
||||
if (!activeDetail || !isLabDependentDetail) {
|
||||
return null;
|
||||
}
|
||||
|
||||
function detailNumber(d: TreatmentDetailDraft) {
|
||||
const idx = details.findIndex((row) => row.clientId === d.clientId);
|
||||
return idx >= 0 ? idx + 1 : 0;
|
||||
}
|
||||
|
||||
function detailSummary(d: TreatmentDetailDraft) {
|
||||
const typeLabel = treatmentTypeLabelFromCatalog(d.treatmentType, treatmentCatalog);
|
||||
const teeth = d.teeth.length ? d.teeth.join(', ') : t('teethNone');
|
||||
return `${t('detailLabel', { n: detailNumber(d) })} · ${typeLabel} · ${teeth}`;
|
||||
return `${t('detailLabel', { n: activeDetailNumber })} · ${typeLabel} · ${teeth}`;
|
||||
}
|
||||
|
||||
function updateActiveLabCase(patch: Partial<LabCaseDraft>) {
|
||||
@@ -250,36 +206,6 @@ export function LabCasesDispatchPanel({
|
||||
updateActiveLabCase({ toothProsthesis: next });
|
||||
}
|
||||
|
||||
function toggleDetailInActiveLabCase(detailClientId: string, checked: boolean) {
|
||||
if (!activeLabCase || sent) return;
|
||||
|
||||
onLabCasesChange(
|
||||
labCases.map((lc) => {
|
||||
if (lc.sentAt) return lc;
|
||||
|
||||
if (lc.clientId === activeLabCase.clientId) {
|
||||
const set = new Set(lc.detailClientIds);
|
||||
if (checked) set.add(detailClientId);
|
||||
else set.delete(detailClientId);
|
||||
|
||||
const keptProsthesis = lc.toothProsthesis.filter((tp) =>
|
||||
[...set].includes(tp.detailClientId),
|
||||
);
|
||||
|
||||
return { ...lc, detailClientIds: [...set], toothProsthesis: keptProsthesis };
|
||||
}
|
||||
|
||||
if (checked) {
|
||||
return {
|
||||
...lc,
|
||||
detailClientIds: lc.detailClientIds.filter((id) => id !== detailClientId),
|
||||
};
|
||||
}
|
||||
return lc;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function toggleAttachmentInActiveLabCase(attachmentId: string, checked: boolean) {
|
||||
if (!activeLabCase || sent) return;
|
||||
const set = new Set(activeLabCase.attachmentIds);
|
||||
@@ -288,18 +214,7 @@ export function LabCasesDispatchPanel({
|
||||
updateActiveLabCase({ attachmentIds: [...set] });
|
||||
}
|
||||
|
||||
const activeDetailAttachments = activeDetail?.attachmentMetas ?? [];
|
||||
|
||||
const includedInActiveShipment = activeLabCase
|
||||
? [activeDetail]
|
||||
: [];
|
||||
|
||||
const pickableForActiveDraft =
|
||||
activeLabCase && !sent
|
||||
? selectableDetailsForDraftShipment(details, labCases, labDependentCodes, activeLabCase).filter(
|
||||
(d) => d.clientId === activeDetailId,
|
||||
)
|
||||
: [];
|
||||
const activeDetailAttachments = activeDetail.attachmentMetas ?? [];
|
||||
|
||||
return (
|
||||
<div className="surface-card p-4 space-y-4">
|
||||
@@ -326,275 +241,249 @@ export function LabCasesDispatchPanel({
|
||||
<p className="text-xs text-text-muted">{t('labDispatchEmpty')}</p>
|
||||
) : activeLabCase ? (
|
||||
<div className="space-y-4 border border-border/60 rounded-[var(--radius-md)] p-4 bg-background-secondary/30">
|
||||
{sent ? (
|
||||
<>
|
||||
<div>
|
||||
<p className="text-xs font-medium text-text-secondary mb-2">
|
||||
{t('labShipmentIncludedDetails')}
|
||||
</p>
|
||||
{includedInActiveShipment.length === 0 ? (
|
||||
<p className="text-xs text-text-muted">{t('labShipmentNoIncludedDetails')}</p>
|
||||
) : (
|
||||
<ul className="space-y-1.5">
|
||||
{includedInActiveShipment.map((d) => (
|
||||
<li
|
||||
key={d.clientId}
|
||||
className="text-sm text-text-primary rounded-[var(--radius-sm)] border border-border/50 bg-background-secondary/50 px-3 py-2"
|
||||
>
|
||||
{detailSummary(d)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{sent ? (
|
||||
<>
|
||||
<div>
|
||||
<p className="text-xs font-medium text-text-secondary mb-2">
|
||||
{t('labShipmentIncludedDetails')}
|
||||
</p>
|
||||
<p className="text-sm text-text-primary rounded-[var(--radius-sm)] border border-border/50 bg-background-secondary/50 px-3 py-2">
|
||||
{detailSummary(activeDetail)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{activeLabCase.id ? (
|
||||
<LabCaseCommentsPanel
|
||||
caseId={activeLabCase.id}
|
||||
canPost={false}
|
||||
canToggleVisibility={false}
|
||||
loadComments={async () => {
|
||||
const r = await treatmentsApi.listLabCaseComments(activeLabCase.id!);
|
||||
return r.data;
|
||||
}}
|
||||
onPost={async () => {
|
||||
throw new Error('Read-only');
|
||||
}}
|
||||
onError={onCommentError}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{activeLabOrgName ? (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-text-secondary">{t('selectLab')}</p>
|
||||
<p className="text-sm text-text-primary mt-1">{activeLabOrgName}</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<CaseSentLabel
|
||||
treatmentCase={{
|
||||
destinationOrganizationId: activeLabCase.destinationOrganizationId,
|
||||
sendToOrganizationIds: activeLabCase.destinationOrganizationId
|
||||
? [activeLabCase.destinationOrganizationId]
|
||||
: [],
|
||||
sentAt: activeLabCase.sentAt ?? null,
|
||||
sends: activeLabCase.sends,
|
||||
}}
|
||||
orgs={orgs}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<p className="text-xs font-medium text-text-secondary mb-2">
|
||||
{t('labShipmentIncludedDetails')}
|
||||
</p>
|
||||
<p className="text-sm text-text-primary rounded-[var(--radius-sm)] border border-border/50 bg-background-secondary/50 px-3 py-2">
|
||||
{detailSummary(activeDetail)}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{!sent && activeDetailAttachments.length > 0 ? (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-text-secondary mb-2">
|
||||
{t('labShipmentAttachments')}
|
||||
</p>
|
||||
<p className="text-[11px] text-text-muted mb-2">{t('labShipmentAttachmentsHint')}</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
{activeDetailAttachments.map((att) => (
|
||||
<Checkbox
|
||||
key={att.id}
|
||||
checked={activeLabCase.attachmentIds.includes(att.id)}
|
||||
disabled={disabled}
|
||||
onChange={(next) => toggleAttachmentInActiveLabCase(att.id, next)}
|
||||
label={`${att.fileName} (${(att.sizeBytes / 1024).toFixed(1)} KB)`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{activeLabCase.id ? (
|
||||
<LabCaseCommentsPanel
|
||||
caseId={activeLabCase.id}
|
||||
canPost={false}
|
||||
canToggleVisibility={false}
|
||||
loadComments={async () => {
|
||||
const r = await treatmentsApi.listLabCaseComments(activeLabCase.id!);
|
||||
return r.data;
|
||||
}}
|
||||
onPost={async () => {
|
||||
throw new Error('Read-only');
|
||||
}}
|
||||
onError={onCommentError}
|
||||
/>
|
||||
) : null}
|
||||
{activeLabCase.id ? (
|
||||
<LabCaseCommentsPanel
|
||||
caseId={activeLabCase.id}
|
||||
canPost={canEdit && !disabled}
|
||||
canToggleVisibility={false}
|
||||
deferSubmit
|
||||
composerValue={pendingComment}
|
||||
onComposerValueChange={setPendingComment}
|
||||
loadComments={async () => {
|
||||
const r = await treatmentsApi.listLabCaseComments(activeLabCase.id!);
|
||||
return r.data;
|
||||
}}
|
||||
onPost={async (body) => {
|
||||
const r = await treatmentsApi.addLabCaseComment(activeLabCase.id!, { body });
|
||||
return r.data;
|
||||
}}
|
||||
onError={onCommentError}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{activeLabOrgName ? (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-text-secondary">{t('selectLab')}</p>
|
||||
<p className="text-sm text-text-primary mt-1">{activeLabOrgName}</p>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<CaseSentLabel
|
||||
treatmentCase={{
|
||||
destinationOrganizationId: activeLabCase.destinationOrganizationId,
|
||||
sendToOrganizationIds: activeLabCase.destinationOrganizationId
|
||||
? [activeLabCase.destinationOrganizationId]
|
||||
: [],
|
||||
sentAt: activeLabCase.sentAt ?? null,
|
||||
sends: activeLabCase.sends,
|
||||
}}
|
||||
orgs={orgs}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div>
|
||||
<p className="text-xs font-medium text-text-secondary mb-2">
|
||||
{t('includeDetails')}
|
||||
</p>
|
||||
{pickableForActiveDraft.length === 0 ? (
|
||||
<p className="text-xs text-text-muted">{t('labShipmentNoDetailsAvailable')}</p>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{pickableForActiveDraft.map((d) => {
|
||||
const checked = activeLabCase.detailClientIds.includes(d.clientId);
|
||||
return (
|
||||
<Checkbox
|
||||
key={d.clientId}
|
||||
checked={checked}
|
||||
disabled={disabled}
|
||||
onChange={(next) => toggleDetailInActiveLabCase(d.clientId, next)}
|
||||
label={detailSummary(d)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium text-text-secondary">{t('selectLab')}</p>
|
||||
<SearchBar
|
||||
embedded
|
||||
value={organizationSearch}
|
||||
onChange={onOrganizationSearchChange}
|
||||
placeholder={t('searchOrgsPlaceholder')}
|
||||
/>
|
||||
{recentOrganizations.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-xs text-text-muted">{t('recent')}</span>
|
||||
{recentOrganizations.map((o) => (
|
||||
<button
|
||||
key={o.id}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={() => onRecentOrganizationPick(o.id)}
|
||||
className="text-xs rounded-[var(--radius-sm)] border border-border/70 px-2 py-1 text-text-secondary hover:text-text-primary hover:border-border focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/35 disabled:opacity-50"
|
||||
>
|
||||
{o.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<Dropdown
|
||||
value={activeLabCase.destinationOrganizationId ?? ''}
|
||||
onChange={(e) => {
|
||||
const nextOrgId = e.target.value || null;
|
||||
updateActiveLabCase({
|
||||
destinationOrganizationId: nextOrgId,
|
||||
toothProsthesis: [],
|
||||
});
|
||||
setApplyAllProsthesis('');
|
||||
}}
|
||||
disabled={disabled || filteredOrganizations.length === 0}
|
||||
>
|
||||
<option value="">{t('selectLabPlaceholder')}</option>
|
||||
{filteredOrganizations.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
</option>
|
||||
))}
|
||||
</Dropdown>
|
||||
{filteredOrganizations.length === 0 && (
|
||||
<p className="text-xs text-text-muted">{t('noOrgMatch')}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!sent && activeDetailAttachments.length > 0 ? (
|
||||
<div>
|
||||
<p className="text-xs font-medium text-text-secondary mb-2">
|
||||
{t('labShipmentAttachments')}
|
||||
</p>
|
||||
<p className="text-[11px] text-text-muted mb-2">{t('labShipmentAttachmentsHint')}</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
{activeDetailAttachments.map((att) => (
|
||||
<Checkbox
|
||||
key={att.id}
|
||||
checked={activeLabCase.attachmentIds.includes(att.id)}
|
||||
disabled={disabled}
|
||||
onChange={(next) => toggleAttachmentInActiveLabCase(att.id, next)}
|
||||
label={`${att.fileName} (${(att.sizeBytes / 1024).toFixed(1)} KB)`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{activeLabCase.id ? (
|
||||
<LabCaseCommentsPanel
|
||||
caseId={activeLabCase.id}
|
||||
canPost={canEdit && !disabled}
|
||||
canToggleVisibility={false}
|
||||
deferSubmit
|
||||
composerValue={pendingComment}
|
||||
onComposerValueChange={setPendingComment}
|
||||
loadComments={async () => {
|
||||
const r = await treatmentsApi.listLabCaseComments(activeLabCase.id!);
|
||||
return r.data;
|
||||
}}
|
||||
onPost={async (body) => {
|
||||
const r = await treatmentsApi.addLabCaseComment(activeLabCase.id!, { body });
|
||||
return r.data;
|
||||
}}
|
||||
onError={onCommentError}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium text-text-secondary">{t('selectLab')}</p>
|
||||
<SearchBar
|
||||
embedded
|
||||
value={organizationSearch}
|
||||
onChange={onOrganizationSearchChange}
|
||||
placeholder={t('searchOrgsPlaceholder')}
|
||||
/>
|
||||
{recentOrganizations.length > 0 && (
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="text-xs text-text-muted">{t('recent')}</span>
|
||||
{recentOrganizations.map((o) => (
|
||||
<button
|
||||
key={o.id}
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={() => onRecentOrganizationPick(o.id)}
|
||||
className="text-xs rounded-[var(--radius-sm)] border border-border/70 px-2 py-1 text-text-secondary hover:text-text-primary hover:border-border focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/35 disabled:opacity-50"
|
||||
>
|
||||
{o.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<Dropdown
|
||||
value={activeLabCase.destinationOrganizationId ?? ''}
|
||||
{prosthesisRows.length > 0 && activeLabCase.destinationOrganizationId ? (
|
||||
<div className="space-y-3 border-t border-border/60 pt-3">
|
||||
<p className="text-xs font-medium text-text-secondary">
|
||||
{t('prosthesisTypesTitle')}
|
||||
</p>
|
||||
<label className="block text-xs text-text-muted space-y-1">
|
||||
{t('prosthesisApplyAll')}
|
||||
<select
|
||||
value={applyAllProsthesis}
|
||||
disabled={disabled || prosthesisOptions.length === 0}
|
||||
onChange={(e) => {
|
||||
const nextOrgId = e.target.value || null;
|
||||
updateActiveLabCase({
|
||||
destinationOrganizationId: nextOrgId,
|
||||
toothProsthesis: [],
|
||||
});
|
||||
setApplyAllProsthesis('');
|
||||
const code = e.target.value;
|
||||
setApplyAllProsthesis(code);
|
||||
if (code) applyProsthesisToAll(code);
|
||||
}}
|
||||
disabled={disabled || filteredOrganizations.length === 0}
|
||||
className={`${FORM_SELECT_CLASS} w-full mt-1`}
|
||||
>
|
||||
<option value="">{t('selectLabPlaceholder')}</option>
|
||||
{filteredOrganizations.map((o) => (
|
||||
<option key={o.id} value={o.id}>
|
||||
{o.name}
|
||||
<option value="">{t('prosthesisSelectPlaceholder')}</option>
|
||||
{prosthesisOptions.map((opt) => (
|
||||
<option key={opt.code} value={opt.code}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</Dropdown>
|
||||
{filteredOrganizations.length === 0 && (
|
||||
<p className="text-xs text-text-muted">{t('noOrgMatch')}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{prosthesisRows.length > 0 && activeLabCase.destinationOrganizationId ? (
|
||||
<div className="space-y-3 border-t border-border/60 pt-3">
|
||||
<p className="text-xs font-medium text-text-secondary">
|
||||
{t('prosthesisTypesTitle')}
|
||||
</p>
|
||||
<label className="block text-xs text-text-muted space-y-1">
|
||||
{t('prosthesisApplyAll')}
|
||||
<select
|
||||
value={applyAllProsthesis}
|
||||
disabled={disabled || prosthesisOptions.length === 0}
|
||||
onChange={(e) => {
|
||||
const code = e.target.value;
|
||||
setApplyAllProsthesis(code);
|
||||
if (code) applyProsthesisToAll(code);
|
||||
}}
|
||||
className={`${FORM_SELECT_CLASS} w-full mt-1`}
|
||||
>
|
||||
<option value="">{t('prosthesisSelectPlaceholder')}</option>
|
||||
{prosthesisOptions.map((opt) => (
|
||||
<option key={opt.code} value={opt.code}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-left text-xs text-text-muted">
|
||||
<th className="pb-2 pr-3 font-medium">{t('prosthesisColTooth')}</th>
|
||||
<th className="pb-2 pr-3 font-medium">{t('prosthesisColDetail')}</th>
|
||||
<th className="pb-2 font-medium">{t('prosthesisColType')}</th>
|
||||
</select>
|
||||
</label>
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-left text-xs text-text-muted">
|
||||
<th className="pb-2 pr-3 font-medium">{t('prosthesisColTooth')}</th>
|
||||
<th className="pb-2 pr-3 font-medium">{t('prosthesisColDetail')}</th>
|
||||
<th className="pb-2 font-medium">{t('prosthesisColType')}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{prosthesisRows.map((row) => {
|
||||
const current =
|
||||
activeLabCase.toothProsthesis.find(
|
||||
(tp) =>
|
||||
tp.detailClientId === row.detailClientId &&
|
||||
tp.tooth === row.tooth,
|
||||
)?.prosthesisTypeCode ?? '';
|
||||
return (
|
||||
<tr key={`${row.detailClientId}-${row.tooth}`} className="border-t border-border/40">
|
||||
<td className="py-2 pr-3 text-text-primary">{row.tooth}</td>
|
||||
<td className="py-2 pr-3 text-text-secondary">
|
||||
{t('detailLabel', { n: row.detailNumber })}
|
||||
</td>
|
||||
<td className="py-2">
|
||||
<select
|
||||
value={current}
|
||||
disabled={disabled}
|
||||
onChange={(e) =>
|
||||
setToothProsthesis(
|
||||
row.detailClientId,
|
||||
row.tooth,
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
className={`${FORM_SELECT_CLASS} w-full min-w-[160px]`}
|
||||
>
|
||||
<option value="">{t('prosthesisSelectPlaceholder')}</option>
|
||||
{prosthesisOptions.map((opt) => (
|
||||
<option key={opt.code} value={opt.code}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{prosthesisRows.map((row) => {
|
||||
const current =
|
||||
activeLabCase.toothProsthesis.find(
|
||||
(tp) =>
|
||||
tp.detailClientId === row.detailClientId &&
|
||||
tp.tooth === row.tooth,
|
||||
)?.prosthesisTypeCode ?? '';
|
||||
return (
|
||||
<tr key={`${row.detailClientId}-${row.tooth}`} className="border-t border-border/40">
|
||||
<td className="py-2 pr-3 text-text-primary">{row.tooth}</td>
|
||||
<td className="py-2 pr-3 text-text-secondary">
|
||||
{t('detailLabel', { n: row.detailNumber })}
|
||||
</td>
|
||||
<td className="py-2">
|
||||
<select
|
||||
value={current}
|
||||
disabled={disabled}
|
||||
onChange={(e) =>
|
||||
setToothProsthesis(
|
||||
row.detailClientId,
|
||||
row.tooth,
|
||||
e.target.value,
|
||||
)
|
||||
}
|
||||
className={`${FORM_SELECT_CLASS} w-full min-w-[160px]`}
|
||||
>
|
||||
<option value="">{t('prosthesisSelectPlaceholder')}</option>
|
||||
{prosthesisOptions.map((opt) => (
|
||||
<option key={opt.code} value={opt.code}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 pt-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
disabled={
|
||||
disabled ||
|
||||
sendBusyId === activeLabCase.clientId ||
|
||||
!activeLabCase.destinationOrganizationId ||
|
||||
activeLabCase.detailClientIds.length === 0 ||
|
||||
!prosthesisComplete
|
||||
}
|
||||
isLoading={sendBusyId === activeLabCase.clientId}
|
||||
onClick={() => onSendLabCase(activeLabCase, pendingComment.trim())}
|
||||
>
|
||||
{t('sendToLab')}
|
||||
</Button>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className="flex flex-wrap items-center gap-3 pt-1">
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
disabled={
|
||||
disabled ||
|
||||
sendBusyId === activeLabCase.clientId ||
|
||||
!activeLabCase.destinationOrganizationId ||
|
||||
!activeLabCase.detailClientId ||
|
||||
!prosthesisComplete
|
||||
}
|
||||
isLoading={sendBusyId === activeLabCase.clientId}
|
||||
onClick={() => onSendLabCase(activeLabCase, pendingComment.trim())}
|
||||
>
|
||||
{t('sendToLab')}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -43,29 +43,36 @@ function isTreatmentDayHistorical(treatmentAt: string, todayStart: Date): boolea
|
||||
return compareLocalDayStart(new Date(treatmentAt), todayStart) < 0;
|
||||
}
|
||||
|
||||
function withoutEmptyLabCaseDrafts(drafts: LabCaseDraft[]): LabCaseDraft[] {
|
||||
return drafts.filter((lc) => lc.sentAt || Boolean(lc.detailClientId));
|
||||
}
|
||||
|
||||
function labCaseDraftsToPast(
|
||||
labCaseDrafts: LabCaseDraft[],
|
||||
details: TreatmentDetailDraft[],
|
||||
): PastLabCase[] {
|
||||
return labCaseDrafts.map((lc) => ({
|
||||
id: lc.id ?? lc.clientId,
|
||||
clientId: lc.clientId,
|
||||
destinationOrganizationId: lc.destinationOrganizationId,
|
||||
sentAt: lc.sentAt ?? null,
|
||||
treatmentDetailIds: lc.detailClientIds
|
||||
.map((cid) => details.find((d) => d.clientId === cid)?.id)
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
details: lc.detailClientIds.map((cid) => {
|
||||
const d = details.find((x) => x.clientId === cid);
|
||||
return {
|
||||
id: d?.id ?? cid,
|
||||
clientId: cid,
|
||||
treatmentType: d?.treatmentType ?? 'consultation',
|
||||
teeth: d?.teeth ?? [],
|
||||
};
|
||||
}),
|
||||
sends: lc.sends ?? [],
|
||||
}));
|
||||
return labCaseDrafts.map((lc) => {
|
||||
const linkedDetail = lc.detailClientId
|
||||
? details.find((d) => d.clientId === lc.detailClientId)
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: lc.id ?? lc.clientId,
|
||||
clientId: lc.clientId,
|
||||
destinationOrganizationId: lc.destinationOrganizationId,
|
||||
sentAt: lc.sentAt ?? null,
|
||||
treatmentDetailId: linkedDetail?.id ?? null,
|
||||
detail: linkedDetail
|
||||
? {
|
||||
id: linkedDetail.id ?? linkedDetail.clientId,
|
||||
clientId: linkedDetail.clientId,
|
||||
treatmentType: linkedDetail.treatmentType,
|
||||
teeth: linkedDetail.teeth,
|
||||
}
|
||||
: null,
|
||||
sends: lc.sends ?? [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function enrichDetailsWithLabSendState(
|
||||
@@ -74,7 +81,7 @@ function enrichDetailsWithLabSendState(
|
||||
): TreatmentDetailDraft[] {
|
||||
return details.map((detail) => {
|
||||
const sentLabCase = labCaseDrafts.find(
|
||||
(lc) => lc.sentAt && lc.detailClientIds.includes(detail.clientId),
|
||||
(lc) => lc.sentAt && lc.detailClientId === detail.clientId,
|
||||
);
|
||||
if (!sentLabCase) return detail;
|
||||
return {
|
||||
@@ -142,7 +149,7 @@ function newLabCaseDraft(): LabCaseDraft {
|
||||
? crypto.randomUUID()
|
||||
: `lab-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`,
|
||||
destinationOrganizationId: null,
|
||||
detailClientIds: [],
|
||||
detailClientId: null,
|
||||
toothProsthesis: [],
|
||||
attachmentIds: [],
|
||||
sentAt: null,
|
||||
@@ -179,16 +186,13 @@ function mapDetailFromApi(d: PastTreatmentCase): TreatmentDetailDraft {
|
||||
}
|
||||
|
||||
function mapLabCaseDraftFromApi(lc: PastLabCase): LabCaseDraft {
|
||||
const detailClientById = new Map(lc.details.map((d) => [d.id, d.clientId]));
|
||||
|
||||
return {
|
||||
clientId: lc.clientId,
|
||||
id: lc.id,
|
||||
destinationOrganizationId: lc.destinationOrganizationId,
|
||||
detailClientIds: lc.details.map((d) => d.clientId),
|
||||
detailClientId: lc.detail?.clientId ?? null,
|
||||
toothProsthesis: (lc.toothProsthesis ?? []).map((tp) => ({
|
||||
detailClientId:
|
||||
detailClientById.get(tp.treatmentDetailId) ?? tp.treatmentDetailId,
|
||||
detailClientId: lc.detail?.clientId ?? tp.treatmentDetailId,
|
||||
tooth: tp.tooth,
|
||||
prosthesisTypeCode: tp.prosthesisTypeCode,
|
||||
})),
|
||||
@@ -313,7 +317,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
|
||||
const isDetailLocked = useCallback(
|
||||
(detail: TreatmentDetailDraft) =>
|
||||
labCaseDrafts.some((lc) => lc.sentAt && lc.detailClientIds.includes(detail.clientId)),
|
||||
labCaseDrafts.some((lc) => lc.sentAt && lc.detailClientId === detail.clientId),
|
||||
[labCaseDrafts],
|
||||
);
|
||||
|
||||
@@ -388,7 +392,9 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
return stillExists ? prev : mapped[0]?.clientId ?? prev;
|
||||
});
|
||||
setSavedSnapshot(serializeDetails(mapped));
|
||||
const mappedLabCases = (treatment.labCases ?? []).map(mapLabCaseDraftFromApi);
|
||||
const mappedLabCases = withoutEmptyLabCaseDrafts(
|
||||
(treatment.labCases ?? []).map(mapLabCaseDraftFromApi),
|
||||
);
|
||||
setLabCaseDrafts(mappedLabCases);
|
||||
setActiveLabCaseId(mappedLabCases[0]?.clientId ?? null);
|
||||
setOrganizationSearch('');
|
||||
@@ -433,7 +439,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
|
||||
// Sync active lab shipment when the selected treatment detail changes.
|
||||
useEffect(() => {
|
||||
const match = labCaseDrafts.find((lc) => lc.detailClientIds.includes(activeDetailId));
|
||||
const match = labCaseDrafts.find((lc) => lc.detailClientId === activeDetailId);
|
||||
setActiveLabCaseId(match?.clientId ?? null);
|
||||
}, [activeDetailId, labCaseDrafts]);
|
||||
|
||||
@@ -581,7 +587,9 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
setSavedSnapshot(serializeDetails([first]));
|
||||
}
|
||||
|
||||
const mappedLabCases = (response.data?.labCases ?? []).map(mapLabCaseDraftFromApi);
|
||||
const mappedLabCases = withoutEmptyLabCaseDrafts(
|
||||
(response.data?.labCases ?? []).map(mapLabCaseDraftFromApi),
|
||||
);
|
||||
setLabCaseDrafts(mappedLabCases);
|
||||
setActiveLabCaseId(mappedLabCases[0]?.clientId ?? null);
|
||||
setOrganizationSearch('');
|
||||
@@ -848,26 +856,35 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
savedTreatment.details.map((d) => [d.clientId, d.id]),
|
||||
);
|
||||
|
||||
const payload = drafts.map((lc) => ({
|
||||
clientId: lc.clientId,
|
||||
id: lc.id,
|
||||
destinationOrganizationId: lc.destinationOrganizationId ?? undefined,
|
||||
treatmentDetailIds: lc.detailClientIds
|
||||
.map((clientId) => detailIdByClientId.get(clientId))
|
||||
.filter((id): id is string => Boolean(id)),
|
||||
toothProsthesis: lc.toothProsthesis
|
||||
.map((tp) => {
|
||||
const detailId = detailIdByClientId.get(tp.detailClientId);
|
||||
if (!detailId) return null;
|
||||
return {
|
||||
treatmentDetailId: detailId,
|
||||
tooth: tp.tooth,
|
||||
prosthesisTypeCode: tp.prosthesisTypeCode,
|
||||
};
|
||||
})
|
||||
.filter((row): row is { treatmentDetailId: string; tooth: string; prosthesisTypeCode: string } => row !== null),
|
||||
attachmentIds: lc.attachmentIds,
|
||||
}));
|
||||
const payload = drafts
|
||||
.map((lc) => {
|
||||
if (!lc.detailClientId) return null;
|
||||
const treatmentDetailId = detailIdByClientId.get(lc.detailClientId);
|
||||
if (!treatmentDetailId) return null;
|
||||
|
||||
return {
|
||||
clientId: lc.clientId,
|
||||
id: lc.id,
|
||||
destinationOrganizationId: lc.destinationOrganizationId ?? undefined,
|
||||
treatmentDetailId,
|
||||
toothProsthesis: lc.toothProsthesis
|
||||
.map((tp) => {
|
||||
const detailId = detailIdByClientId.get(tp.detailClientId);
|
||||
if (!detailId) return null;
|
||||
return {
|
||||
treatmentDetailId: detailId,
|
||||
tooth: tp.tooth,
|
||||
prosthesisTypeCode: tp.prosthesisTypeCode,
|
||||
};
|
||||
})
|
||||
.filter(
|
||||
(row): row is { treatmentDetailId: string; tooth: string; prosthesisTypeCode: string } =>
|
||||
row !== null,
|
||||
),
|
||||
attachmentIds: lc.attachmentIds,
|
||||
};
|
||||
})
|
||||
.filter((row): row is NonNullable<typeof row> => row !== null);
|
||||
|
||||
if (payload.length === 0) {
|
||||
return savedTreatment;
|
||||
@@ -876,7 +893,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
const response = await treatmentsApi.saveLabCases(selectedAppointment.id, {
|
||||
labCases: payload,
|
||||
});
|
||||
const mapped = response.data.labCases.map(mapLabCaseDraftFromApi);
|
||||
const mapped = withoutEmptyLabCaseDrafts(response.data.labCases.map(mapLabCaseDraftFromApi));
|
||||
setLabCaseDrafts(mapped);
|
||||
setActiveLabCaseId((prev) => {
|
||||
if (prev && mapped.some((lc) => lc.clientId === prev)) return prev;
|
||||
@@ -887,18 +904,86 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
[labCaseDrafts, selectedAppointment],
|
||||
);
|
||||
|
||||
const handleLabCasesChange = useCallback(
|
||||
(next: LabCaseDraft[]) => {
|
||||
const prevCleaned = withoutEmptyLabCaseDrafts(labCaseDrafts);
|
||||
const cleaned = withoutEmptyLabCaseDrafts(next);
|
||||
setLabCaseDrafts(cleaned);
|
||||
|
||||
if (!cleaned.some((lc) => lc.detailClientId === activeDetailId)) {
|
||||
setActiveLabCaseId((prev) =>
|
||||
prev && cleaned.some((lc) => lc.clientId === prev) ? prev : null,
|
||||
);
|
||||
}
|
||||
|
||||
const removedPersistedDraft = prevCleaned.some(
|
||||
(lc) => lc.id && !cleaned.some((row) => row.clientId === lc.clientId),
|
||||
);
|
||||
if (
|
||||
removedPersistedDraft &&
|
||||
selectedAppointment &&
|
||||
canEditTreatmentForDay
|
||||
) {
|
||||
void (async () => {
|
||||
try {
|
||||
const saved = await persistDraft({ force: true });
|
||||
await persistLabCases(saved, cleaned);
|
||||
} catch (error: unknown) {
|
||||
showError(formatApiErrorMessage(error, t('errorSaveLabShipments')));
|
||||
}
|
||||
})();
|
||||
}
|
||||
},
|
||||
[
|
||||
activeDetailId,
|
||||
canEditTreatmentForDay,
|
||||
labCaseDrafts,
|
||||
persistDraft,
|
||||
persistLabCases,
|
||||
selectedAppointment,
|
||||
showError,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
const handleAddLabCase = useCallback(async () => {
|
||||
if (!canEditTreatmentForDay || !selectedAppointment) return;
|
||||
|
||||
const cleaned = withoutEmptyLabCaseDrafts(labCaseDrafts);
|
||||
const existing = cleaned.find(
|
||||
(lc) => !lc.sentAt && lc.detailClientId === activeDetailId,
|
||||
);
|
||||
if (existing) {
|
||||
setActiveLabCaseId(existing.clientId);
|
||||
return;
|
||||
}
|
||||
|
||||
const activeDetail = details.find((d) => d.clientId === activeDetailId);
|
||||
const shouldIncludeActive =
|
||||
Boolean(activeDetail && labDependentCodes.has(activeDetail.treatmentType));
|
||||
|
||||
const orphan = cleaned.find((lc) => !lc.sentAt && !lc.detailClientId);
|
||||
if (orphan && shouldIncludeActive) {
|
||||
const updatedLabCases = cleaned.map((lc) =>
|
||||
lc.clientId === orphan.clientId ? { ...lc, detailClientId: activeDetailId } : lc,
|
||||
);
|
||||
setLabCaseDrafts(updatedLabCases);
|
||||
setActiveLabCaseId(orphan.clientId);
|
||||
|
||||
try {
|
||||
const saved = await persistDraft({ force: true });
|
||||
await persistLabCases(saved, updatedLabCases);
|
||||
} catch (error: unknown) {
|
||||
showError(formatApiErrorMessage(error, t('errorSaveLabShipments')));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const next: LabCaseDraft = {
|
||||
...newLabCaseDraft(),
|
||||
detailClientIds:
|
||||
activeDetail && labDependentCodes.has(activeDetail.treatmentType)
|
||||
? [activeDetailId]
|
||||
: [],
|
||||
detailClientId: shouldIncludeActive ? activeDetailId : null,
|
||||
};
|
||||
const updatedLabCases = [...labCaseDrafts, next];
|
||||
const updatedLabCases = [...cleaned, next];
|
||||
setLabCaseDrafts(updatedLabCases);
|
||||
setActiveLabCaseId(next.clientId);
|
||||
|
||||
@@ -928,7 +1013,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
showError(t('errorChooseOrg'));
|
||||
return;
|
||||
}
|
||||
if (labCase.detailClientIds.length === 0) {
|
||||
if (!labCase.detailClientId) {
|
||||
showError(t('errorLabCaseNeedsDetails'));
|
||||
return;
|
||||
}
|
||||
@@ -958,10 +1043,10 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
|
||||
const response = await treatmentsApi.sendLabCase(refreshedLabCase.id);
|
||||
|
||||
const sentDetailClientIds = new Set(labCase.detailClientIds);
|
||||
const sentDetailClientId = labCase.detailClientId;
|
||||
setDetails((prev) =>
|
||||
prev.map((detail) => {
|
||||
if (!sentDetailClientIds.has(detail.clientId)) return detail;
|
||||
if (detail.clientId !== sentDetailClientId) return detail;
|
||||
return {
|
||||
...detail,
|
||||
labCaseId: response.data.id,
|
||||
@@ -1155,8 +1240,7 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
labDependentCodes={labDependentCodes}
|
||||
treatmentCatalog={treatmentCatalog}
|
||||
activeLabCaseId={activeLabCaseId}
|
||||
onActiveLabCaseChange={setActiveLabCaseId}
|
||||
onLabCasesChange={setLabCaseDrafts}
|
||||
onLabCasesChange={handleLabCasesChange}
|
||||
disabled={!canEditTreatmentForDay}
|
||||
canEdit={canEdit}
|
||||
orgs={orgs}
|
||||
@@ -1164,14 +1248,18 @@ export function TreatmentWorkspace({ userId, currentOrganization }: TreatmentWor
|
||||
onOrganizationSearchChange={setOrganizationSearch}
|
||||
recentOrganizationIds={recentOrganizationIds}
|
||||
onRecentOrganizationPick={(orgId) => {
|
||||
if (!activeLabCaseId) return;
|
||||
setLabCaseDrafts((prev) =>
|
||||
prev.map((lc) =>
|
||||
lc.clientId === activeLabCaseId && !lc.sentAt
|
||||
setLabCaseDrafts((prev) => {
|
||||
const targetId =
|
||||
activeLabCaseId ??
|
||||
prev.find((lc) => !lc.sentAt && lc.detailClientId === activeDetailId)
|
||||
?.clientId;
|
||||
if (!targetId) return prev;
|
||||
return prev.map((lc) =>
|
||||
lc.clientId === targetId && !lc.sentAt
|
||||
? { ...lc, destinationOrganizationId: orgId }
|
||||
: lc,
|
||||
),
|
||||
);
|
||||
);
|
||||
});
|
||||
}}
|
||||
sendBusyId={sendBusyId}
|
||||
onAddLabCase={() => void handleAddLabCase()}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// src/lib/api/auth.ts
|
||||
import { apiClient } from './client';
|
||||
import type { AuthResponse, TrialRegistrationData, LoginData } from '@/types/auth';
|
||||
import type { AuthResponse, TrialRegistrationData, LoginData, ForgotPasswordVerifyResponse } from '@/types/auth';
|
||||
import type { SubscriptionAlertData } from '@/types/subscription';
|
||||
|
||||
export const authApi = {
|
||||
@@ -65,4 +65,25 @@ export const authApi = {
|
||||
const response = await apiClient.post('/auth/refresh', { refreshToken });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
sendForgotPasswordCode: async (mobile: string): Promise<{ success: boolean; message: string }> => {
|
||||
const response = await apiClient.post('/auth/forgot-password/send-code', { mobile });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
verifyForgotPasswordCode: async (
|
||||
mobile: string,
|
||||
code: string,
|
||||
): Promise<ForgotPasswordVerifyResponse> => {
|
||||
const response = await apiClient.post('/auth/forgot-password/verify', { mobile, code });
|
||||
return response.data;
|
||||
},
|
||||
|
||||
changePassword: async (data: {
|
||||
currentPassword?: string;
|
||||
newPassword: string;
|
||||
}): Promise<{ success: boolean; message: string }> => {
|
||||
const response = await apiClient.patch('/auth/profile/password', data);
|
||||
return response.data;
|
||||
},
|
||||
};
|
||||
@@ -34,7 +34,9 @@ function shouldSkipRefreshRetry(url: string | undefined): boolean {
|
||||
url.includes('/auth/refresh') ||
|
||||
url.includes('/auth/login') ||
|
||||
url.includes('/auth/register') ||
|
||||
url.includes('/auth/logout')
|
||||
url.includes('/auth/logout') ||
|
||||
url.includes('/auth/forgot-password') ||
|
||||
url.includes('/auth/profile/password')
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
14
frontend/src/lib/auth/rememberMe.ts
Normal file
14
frontend/src/lib/auth/rememberMe.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
const REMEMBERED_EMAIL_KEY = 'rememberedEmail';
|
||||
|
||||
export function getRememberedEmail(): string {
|
||||
if (typeof window === 'undefined') return '';
|
||||
return localStorage.getItem(REMEMBERED_EMAIL_KEY) ?? '';
|
||||
}
|
||||
|
||||
export function setRememberedEmail(email: string): void {
|
||||
localStorage.setItem(REMEMBERED_EMAIL_KEY, email);
|
||||
}
|
||||
|
||||
export function clearRememberedEmail(): void {
|
||||
localStorage.removeItem(REMEMBERED_EMAIL_KEY);
|
||||
}
|
||||
@@ -4,6 +4,11 @@ import React, { createContext, useCallback, useContext, useEffect, useMemo, useS
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useRouter } from '@/i18n/navigation';
|
||||
import { authApi } from '@/lib/api/auth';
|
||||
import {
|
||||
clearRememberedEmail,
|
||||
getRememberedEmail,
|
||||
setRememberedEmail,
|
||||
} from '@/lib/auth/rememberMe';
|
||||
import { User, Organization } from '@/types/organization';
|
||||
import { isAppLocale, getLocaleFromPathname } from '@/i18n/routing';
|
||||
|
||||
@@ -18,11 +23,12 @@ interface AuthContextType {
|
||||
email: string,
|
||||
password: string,
|
||||
name: string,
|
||||
mobile: string,
|
||||
organizationName: string,
|
||||
organizationEmail: string,
|
||||
organizationType: 'CLINIC' | 'LAB'
|
||||
) => Promise<void>;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
login: (email: string, password: string, rememberMe?: boolean) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
selectOrganization: (orgId: string) => Promise<void>;
|
||||
createOrganization: (
|
||||
@@ -32,6 +38,7 @@ interface AuthContextType {
|
||||
planName?: string,
|
||||
) => Promise<string>;
|
||||
setUserLanguage: (language: string) => void;
|
||||
refreshSession: () => Promise<void>;
|
||||
clearError: () => void;
|
||||
}
|
||||
|
||||
@@ -153,6 +160,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
email: string,
|
||||
password: string,
|
||||
name: string,
|
||||
mobile: string,
|
||||
organizationName: string,
|
||||
organizationEmail: string,
|
||||
organizationType: 'CLINIC' | 'LAB'
|
||||
@@ -163,6 +171,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
|
||||
const response = await authApi.registerTrial({
|
||||
email,
|
||||
mobile,
|
||||
password,
|
||||
name,
|
||||
organizationName,
|
||||
@@ -196,12 +205,22 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
}, [applyUrlLocaleToUser, router, t]);
|
||||
|
||||
// ✅ LOGIN
|
||||
const login = useCallback(async (email: string, password: string) => {
|
||||
const login = useCallback(async (
|
||||
email: string,
|
||||
password: string,
|
||||
rememberMe = false,
|
||||
) => {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await authApi.login({ email, password });
|
||||
const response = await authApi.login({ email, password, rememberMe });
|
||||
|
||||
if (rememberMe) {
|
||||
setRememberedEmail(email);
|
||||
} else {
|
||||
clearRememberedEmail();
|
||||
}
|
||||
|
||||
const userData = await applyUrlLocaleToUser(response.data.user);
|
||||
setUser(userData);
|
||||
@@ -235,7 +254,11 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
} catch (err) {
|
||||
console.error('Logout API failed:', err);
|
||||
} finally {
|
||||
const rememberedEmail = getRememberedEmail();
|
||||
localStorage.clear();
|
||||
if (rememberedEmail) {
|
||||
setRememberedEmail(rememberedEmail);
|
||||
}
|
||||
setUser(null);
|
||||
setOrganizations([]);
|
||||
setCurrentOrganization(null);
|
||||
@@ -265,7 +288,16 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
plan: (organization as { plan?: Organization['plan'] }).plan,
|
||||
});
|
||||
|
||||
router.push('/today');
|
||||
const redirectPath =
|
||||
typeof window !== 'undefined'
|
||||
? sessionStorage.getItem('authRedirect')
|
||||
: null;
|
||||
if (redirectPath) {
|
||||
sessionStorage.removeItem('authRedirect');
|
||||
router.push(redirectPath);
|
||||
} else {
|
||||
router.push('/today');
|
||||
}
|
||||
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
@@ -308,6 +340,10 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
}
|
||||
}, [normalizeProfilePayload, t]);
|
||||
|
||||
const refreshSession = useCallback(async () => {
|
||||
await checkAuth();
|
||||
}, [checkAuth]);
|
||||
|
||||
const clearError = useCallback(() => setError(null), []);
|
||||
|
||||
const setUserLanguage = useCallback((language: string) => {
|
||||
@@ -329,6 +365,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
selectOrganization,
|
||||
createOrganization,
|
||||
setUserLanguage,
|
||||
refreshSession,
|
||||
clearError,
|
||||
}),
|
||||
[
|
||||
@@ -344,6 +381,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
||||
selectOrganization,
|
||||
createOrganization,
|
||||
setUserLanguage,
|
||||
refreshSession,
|
||||
clearError,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -12,6 +12,7 @@ export interface AuthResponse {
|
||||
|
||||
export interface TrialRegistrationData {
|
||||
email: string;
|
||||
mobile: string;
|
||||
password: string;
|
||||
name: string;
|
||||
organizationName: string;
|
||||
@@ -22,4 +23,14 @@ export interface TrialRegistrationData {
|
||||
export interface LoginData {
|
||||
email: string;
|
||||
password: string;
|
||||
rememberMe?: boolean;
|
||||
}
|
||||
|
||||
export interface ForgotPasswordVerifyResponse {
|
||||
success: boolean;
|
||||
data: {
|
||||
user: AuthResponse['data']['user'];
|
||||
organizations: AuthResponse['data']['organizations'];
|
||||
redirectTo: string;
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ export interface LabCaseListItem {
|
||||
lastName: string;
|
||||
mobile: string;
|
||||
};
|
||||
treatmentTypes: string[];
|
||||
treatmentType: string | null;
|
||||
taskProgress: { completed: number; total: number };
|
||||
}
|
||||
|
||||
@@ -85,13 +85,13 @@ export interface LabCaseDetail {
|
||||
mobile: string;
|
||||
};
|
||||
appointmentStartAt: string | null;
|
||||
treatmentTypes: string[];
|
||||
details: Array<{
|
||||
treatmentType: string | null;
|
||||
detail: {
|
||||
id: string;
|
||||
treatmentType: string;
|
||||
teeth: string[];
|
||||
comment: string | null;
|
||||
}>;
|
||||
} | null;
|
||||
toothProsthesis: Array<{
|
||||
treatmentDetailId: string;
|
||||
tooth: string;
|
||||
|
||||
@@ -3,6 +3,7 @@ export interface User {
|
||||
email: string;
|
||||
name: string;
|
||||
language?: string;
|
||||
mobile?: string | null;
|
||||
}
|
||||
|
||||
export interface OrganizationPlan {
|
||||
|
||||
@@ -90,13 +90,13 @@ export interface PastLabCase {
|
||||
clientId: string;
|
||||
destinationOrganizationId: string | null;
|
||||
sentAt?: string | null;
|
||||
treatmentDetailIds: string[];
|
||||
details: Array<{
|
||||
treatmentDetailId: string | null;
|
||||
detail: {
|
||||
id: string;
|
||||
clientId: string;
|
||||
treatmentType: string;
|
||||
teeth: FdiToothId[];
|
||||
}>;
|
||||
} | null;
|
||||
toothProsthesis?: Array<{
|
||||
treatmentDetailId: string;
|
||||
tooth: string;
|
||||
@@ -143,7 +143,7 @@ export interface LabCaseDraft {
|
||||
clientId: string;
|
||||
id?: string;
|
||||
destinationOrganizationId: string | null;
|
||||
detailClientIds: string[];
|
||||
detailClientId: string | null;
|
||||
toothProsthesis: LabCaseToothProsthesisDraft[];
|
||||
attachmentIds: string[];
|
||||
sentAt?: string | null;
|
||||
@@ -166,7 +166,7 @@ export interface SaveLabCasePayload {
|
||||
clientId: string;
|
||||
id?: string;
|
||||
destinationOrganizationId?: string;
|
||||
treatmentDetailIds: string[];
|
||||
treatmentDetailId: string;
|
||||
toothProsthesis?: Array<{
|
||||
treatmentDetailId: string;
|
||||
tooth: string;
|
||||
@@ -186,13 +186,13 @@ export interface LabCaseResponse {
|
||||
clientId: string;
|
||||
destinationOrganizationId: string | null;
|
||||
sentAt: string | null;
|
||||
treatmentDetailIds: string[];
|
||||
details: Array<{
|
||||
treatmentDetailId: string | null;
|
||||
detail: {
|
||||
id: string;
|
||||
clientId: string;
|
||||
treatmentType: string;
|
||||
teeth: string[];
|
||||
}>;
|
||||
} | null;
|
||||
sends: LabCaseSendInfo[];
|
||||
toothProsthesis?: LabCaseToothProsthesisDraft[];
|
||||
attachments?: TreatmentAttachmentMeta[];
|
||||
|
||||
@@ -19,6 +19,8 @@ DOMAIN=dyolink.com
|
||||
# JWT_REFRESH_SECRET=another_long_random_secret_different_from_JWT_SECRET
|
||||
# JWT_REFRESH_EXPIRES_IN=30d
|
||||
# FRONTEND_URL=https://dyolink.com
|
||||
# SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY
|
||||
# SMS_IR_TEMPLATE_ID=123456
|
||||
|
||||
# Frontend Environment (create frontend.env from this)
|
||||
# NEXT_PUBLIC_API_URL=/api
|
||||
|
||||
421
infrastructure/DEPLOY.md
Normal file
421
infrastructure/DEPLOY.md
Normal file
@@ -0,0 +1,421 @@
|
||||
# Dyolink — Production Server Deploy Guide
|
||||
|
||||
Deploy the full stack (Postgres, NestJS API, Next.js, Nginx, Let's Encrypt) on a fresh Linux server using **Docker Hub** images.
|
||||
|
||||
**Example used in production:** `https://wixur.ir` on server `185.243.48.140`.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Internet → Nginx (:80 / :443)
|
||||
├── / → frontend:3000 (Next.js)
|
||||
└── /api → backend:3000 (NestJS)
|
||||
└── postgres:5432
|
||||
```
|
||||
|
||||
| Service | Image | Notes |
|
||||
|-----------|------------------------------------|--------------------------------|
|
||||
| postgres | `postgres:15-alpine` | Data in Docker volume |
|
||||
| backend | `dyolink/dyolink-backend:latest` | Runs migrations + seed on start |
|
||||
| frontend | `dyolink/dyolink-frontend:latest` | URLs baked in at **build time** |
|
||||
| nginx | `nginx:alpine` | SSL termination + reverse proxy |
|
||||
| certbot | `certbot/certbot` | Auto-renews certificates |
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
### On your Mac (build machine)
|
||||
|
||||
- Docker Desktop running
|
||||
- Repo cloned
|
||||
- Docker Hub account (`dyolink`) with images pushed
|
||||
|
||||
### On the server
|
||||
|
||||
- Ubuntu 24.04 (or similar)
|
||||
- Root or sudo access
|
||||
- **Domain** with DNS **A record** → server public IP
|
||||
- Ports **22**, **80**, **443** open (UFW + cloud provider firewall)
|
||||
|
||||
---
|
||||
|
||||
## Part 1 — Build & push images (Mac)
|
||||
|
||||
Frontend URLs are **compiled into the image**. Always build with the real public domain:
|
||||
|
||||
```bash
|
||||
cd /path/to/dyolink
|
||||
docker login # only needed on Mac to push
|
||||
|
||||
./infrastructure/scripts/build-and-push-prod.sh YOUR_DOMAIN.com latest
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
./infrastructure/scripts/build-and-push-prod.sh wixur.ir latest
|
||||
```
|
||||
|
||||
This pushes:
|
||||
|
||||
- `dyolink/dyolink-backend:latest`
|
||||
- `dyolink/dyolink-frontend:latest`
|
||||
|
||||
**When to rebuild:** domain changes, frontend env (`NEXT_PUBLIC_*`) changes, or new app release.
|
||||
|
||||
---
|
||||
|
||||
## Part 2 — Server bootstrap (once per server)
|
||||
|
||||
SSH as root:
|
||||
|
||||
```bash
|
||||
ssh root@YOUR_SERVER_IP
|
||||
```
|
||||
|
||||
### 2.1 Update system & create deploy user
|
||||
|
||||
```bash
|
||||
apt update && apt upgrade -y
|
||||
apt install -y curl git ufw fail2ban
|
||||
|
||||
adduser dyolink
|
||||
usermod -aG sudo dyolink
|
||||
|
||||
# Optional: copy SSH keys from root
|
||||
mkdir -p /home/dyolink/.ssh
|
||||
cp /root/.ssh/authorized_keys /home/dyolink/.ssh/ 2>/dev/null || true
|
||||
chown -R dyolink:dyolink /home/dyolink/.ssh
|
||||
chmod 700 /home/dyolink/.ssh
|
||||
```
|
||||
|
||||
### 2.2 Install Docker
|
||||
|
||||
If `curl -fsSL https://get.docker.com | sh` returns **403**, use Ubuntu packages:
|
||||
|
||||
```bash
|
||||
apt update
|
||||
apt install -y docker.io docker-compose-v2
|
||||
systemctl enable --now docker
|
||||
usermod -aG docker dyolink
|
||||
```
|
||||
|
||||
Verify:
|
||||
|
||||
```bash
|
||||
docker --version
|
||||
docker compose version
|
||||
```
|
||||
|
||||
### 2.3 Docker Hub login (if images are private)
|
||||
|
||||
```bash
|
||||
docker login
|
||||
```
|
||||
|
||||
Public images skip this step.
|
||||
|
||||
### 2.4 Firewall
|
||||
|
||||
```bash
|
||||
ufw default deny incoming
|
||||
ufw default allow outgoing
|
||||
ufw allow OpenSSH
|
||||
ufw allow 80/tcp
|
||||
ufw allow 443/tcp
|
||||
ufw --force enable
|
||||
```
|
||||
|
||||
Also open **80** and **443** in your VPS provider's cloud firewall panel if one exists.
|
||||
|
||||
### 2.5 DNS
|
||||
|
||||
Before SSL, confirm DNS:
|
||||
|
||||
```bash
|
||||
dig +short YOUR_DOMAIN.com
|
||||
# Must return YOUR_SERVER_IP
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Part 3 — Copy infrastructure to server (Mac)
|
||||
|
||||
```bash
|
||||
cd /path/to/dyolink
|
||||
|
||||
ssh dyolink@YOUR_SERVER_IP "sudo mkdir -p /opt/dyolink/secrets && sudo chown -R dyolink:dyolink /opt/dyolink"
|
||||
|
||||
scp -r infrastructure/docker-compose.prod.yml \
|
||||
infrastructure/nginx \
|
||||
infrastructure/scripts \
|
||||
infrastructure/database \
|
||||
infrastructure/deploy.prod.env.example \
|
||||
infrastructure/backend.prod.env.example \
|
||||
infrastructure/database.prod.env.example \
|
||||
dyolink@YOUR_SERVER_IP:/opt/dyolink/infrastructure/
|
||||
```
|
||||
|
||||
On the server:
|
||||
|
||||
```bash
|
||||
ssh dyolink@YOUR_SERVER_IP
|
||||
chmod +x /opt/dyolink/infrastructure/scripts/*.sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Part 4 — Configure secrets (server)
|
||||
|
||||
### 4.1 Main `.env`
|
||||
|
||||
```bash
|
||||
cd /opt/dyolink/infrastructure
|
||||
cp deploy.prod.env.example .env
|
||||
nano .env
|
||||
```
|
||||
|
||||
```env
|
||||
DOMAIN=wixur.ir
|
||||
DOCKER_USERNAME=dyolink
|
||||
TAG=latest
|
||||
LETSENCRYPT_EMAIL=your-email@example.com
|
||||
DEPLOY_SECRETS_DIR=/opt/dyolink/secrets
|
||||
```
|
||||
|
||||
### 4.2 Database secrets
|
||||
|
||||
```bash
|
||||
cp database.prod.env.example /opt/dyolink/secrets/database.env
|
||||
nano /opt/dyolink/secrets/database.env
|
||||
```
|
||||
|
||||
```env
|
||||
POSTGRES_USER=dyolink_user
|
||||
POSTGRES_PASSWORD=STRONG_PASSWORD_HERE
|
||||
POSTGRES_DB=dyolink_db
|
||||
```
|
||||
|
||||
### 4.3 Backend secrets
|
||||
|
||||
```bash
|
||||
cp backend.prod.env.example /opt/dyolink/secrets/backend.env
|
||||
nano /opt/dyolink/secrets/backend.env
|
||||
```
|
||||
|
||||
Generate JWT secrets:
|
||||
|
||||
```bash
|
||||
openssl rand -hex 32 # use for JWT_SECRET
|
||||
openssl rand -hex 32 # use for JWT_REFRESH_SECRET (must be different)
|
||||
```
|
||||
|
||||
```env
|
||||
NODE_ENV=production
|
||||
PORT=3000
|
||||
|
||||
DATABASE_URL=postgresql://dyolink_user:STRONG_PASSWORD_HERE@postgres:5432/dyolink_db
|
||||
|
||||
JWT_SECRET=<first openssl output>
|
||||
JWT_EXPIRES_IN=15m
|
||||
JWT_REFRESH_SECRET=<second openssl output>
|
||||
JWT_REFRESH_EXPIRES_IN=30d
|
||||
|
||||
FRONTEND_URL=https://wixur.ir
|
||||
|
||||
SMS_IR_API_KEY=your_key
|
||||
SMS_IR_TEMPLATE_ID=your_template_id
|
||||
```
|
||||
|
||||
**Critical checks:**
|
||||
|
||||
| Rule | Why |
|
||||
|------|-----|
|
||||
| `DATABASE_URL` password = `POSTGRES_PASSWORD` | Backend cannot connect otherwise |
|
||||
| `FRONTEND_URL` = `https://YOUR_DOMAIN` | CORS, cookies, invite links |
|
||||
| JWT secrets must **not** contain `CHANGE_ME` | App refuses to start (by design) |
|
||||
| Postgres password set **before first** `up` | Password only applied on first volume create |
|
||||
|
||||
---
|
||||
|
||||
## Part 5 — Deploy (server)
|
||||
|
||||
```bash
|
||||
cd /opt/dyolink/infrastructure
|
||||
./scripts/deploy-prod.sh
|
||||
```
|
||||
|
||||
This script:
|
||||
|
||||
1. Issues Let's Encrypt certificate (first run)
|
||||
2. Renders HTTPS nginx config
|
||||
3. Pulls images from Docker Hub
|
||||
4. Starts all containers
|
||||
|
||||
First deploy takes **3–5 minutes**.
|
||||
|
||||
---
|
||||
|
||||
## Part 6 — Verify
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.prod.yml --env-file .env ps
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
| Container | Status |
|
||||
|-----------|--------|
|
||||
| dyolink_db_prod | Up (healthy) |
|
||||
| dyolink_backend_prod | Up (healthy) |
|
||||
| dyolink_frontend_prod | Up |
|
||||
| dyolink_nginx_prod | Up |
|
||||
| dyolink_certbot_prod | Up |
|
||||
|
||||
```bash
|
||||
curl -s https://YOUR_DOMAIN/api/health
|
||||
# {"status":"ok","timestamp":"..."}
|
||||
|
||||
curl -I https://YOUR_DOMAIN/
|
||||
# HTTP/2 200
|
||||
```
|
||||
|
||||
Open `https://YOUR_DOMAIN` in a browser.
|
||||
|
||||
---
|
||||
|
||||
## Updating the app (new release)
|
||||
|
||||
**On Mac** — build & push:
|
||||
|
||||
```bash
|
||||
./infrastructure/scripts/build-and-push-prod.sh wixur.ir latest
|
||||
```
|
||||
|
||||
**On server:**
|
||||
|
||||
```bash
|
||||
cd /opt/dyolink/infrastructure
|
||||
docker compose -f docker-compose.prod.yml --env-file .env pull backend frontend
|
||||
docker compose -f docker-compose.prod.yml --env-file .env up -d
|
||||
```
|
||||
|
||||
Backend runs `prisma migrate deploy` automatically on container start.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Docker install: `get.docker.com` returns 403
|
||||
|
||||
Use `apt install docker.io docker-compose-v2` (see Part 2.2).
|
||||
|
||||
### Docker Hub pull: 403 Forbidden
|
||||
|
||||
```bash
|
||||
docker login
|
||||
```
|
||||
|
||||
If still blocked, transfer images from Mac:
|
||||
|
||||
```bash
|
||||
# Mac
|
||||
docker save dyolink/dyolink-backend:latest dyolink/dyolink-frontend:latest \
|
||||
postgres:15-alpine nginx:alpine certbot/certbot:latest | gzip > images.tar.gz
|
||||
scp images.tar.gz dyolink@SERVER:/tmp/
|
||||
|
||||
# Server
|
||||
gunzip -c /tmp/images.tar.gz | docker load
|
||||
```
|
||||
|
||||
### Backend crash: `JWT_SECRET must be changed from the placeholder value`
|
||||
|
||||
Edit `/opt/dyolink/secrets/backend.env` — replace JWT secrets with `openssl rand -hex 32` output. Restart:
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.prod.yml --env-file .env up -d backend
|
||||
```
|
||||
|
||||
### HTTP shows "obtaining SSL certificate" / HTTPS fails
|
||||
|
||||
Nginx is still on the bootstrap config. Fix:
|
||||
|
||||
```bash
|
||||
cd /opt/dyolink/infrastructure
|
||||
./scripts/render-nginx-ssl.sh
|
||||
docker compose -f docker-compose.prod.yml --env-file .env up -d nginx --force-recreate
|
||||
curl -s https://YOUR_DOMAIN/api/health
|
||||
```
|
||||
|
||||
### Backend `Restarting` — database password mismatch
|
||||
|
||||
If you changed `POSTGRES_PASSWORD` after the first deploy, reset the DB volume (destroys data):
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.prod.yml --env-file .env down
|
||||
docker volume rm dyolink_postgres_data_prod
|
||||
# Fix database.env + backend.env passwords to match
|
||||
./scripts/deploy-prod.sh
|
||||
```
|
||||
|
||||
### View logs
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.prod.yml --env-file .env logs backend --tail 50
|
||||
docker compose -f docker-compose.prod.yml --env-file .env logs nginx --tail 50
|
||||
docker compose -f docker-compose.prod.yml --env-file .env logs frontend --tail 50
|
||||
```
|
||||
|
||||
### Internal health checks (bypass public network)
|
||||
|
||||
```bash
|
||||
docker compose -f docker-compose.prod.yml --env-file .env exec nginx \
|
||||
wget -qO- http://backend:3000/api/health
|
||||
|
||||
docker compose -f docker-compose.prod.yml --env-file .env exec frontend \
|
||||
wget -qO- http://127.0.0.1:3000/ | head -3
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## File reference
|
||||
|
||||
| Path on server | Purpose |
|
||||
|----------------|---------|
|
||||
| `/opt/dyolink/infrastructure/.env` | Domain, Docker Hub user, Let's Encrypt email |
|
||||
| `/opt/dyolink/secrets/database.env` | Postgres credentials |
|
||||
| `/opt/dyolink/secrets/backend.env` | API secrets, DATABASE_URL, JWT, SMS |
|
||||
| `/opt/dyolink/infrastructure/nginx/generated/default.conf` | Auto-generated nginx SSL config |
|
||||
| `/opt/dyolink/infrastructure/scripts/deploy-prod.sh` | Main deploy entry point |
|
||||
| `/opt/dyolink/infrastructure/scripts/build-and-push-prod.sh` | Build & push (run on Mac) |
|
||||
|
||||
---
|
||||
|
||||
## Quick checklist (new server)
|
||||
|
||||
- [ ] DNS A record → server IP
|
||||
- [ ] Docker installed on server
|
||||
- [ ] UFW + cloud firewall: 22, 80, 443 open
|
||||
- [ ] Images built with correct domain and pushed to Docker Hub
|
||||
- [ ] `infrastructure/` copied to `/opt/dyolink/`
|
||||
- [ ] `.env`, `database.env`, `backend.env` configured (real passwords + JWT)
|
||||
- [ ] `./scripts/deploy-prod.sh` completed
|
||||
- [ ] `curl https://DOMAIN/api/health` returns `{"status":"ok",...}`
|
||||
- [ ] App loads in browser
|
||||
|
||||
---
|
||||
|
||||
## Issues encountered on first deploy (wixur.ir) — summary
|
||||
|
||||
| Problem | Cause | Type |
|
||||
|---------|-------|------|
|
||||
| `get.docker.com` 403 | Regional/network block | **Server setup** — use `apt install docker.io` |
|
||||
| Docker Hub pull 403 | Hub blocked without login | **Server setup** — `docker login` |
|
||||
| Backend crash loop | `JWT_SECRET` still had `CHANGE_ME` | **Config** — edit `backend.env` |
|
||||
| HTTP "obtaining SSL" / HTTPS broken | Nginx not recreated after SSL config | **Deploy script** — fixed in `init-letsencrypt.sh` / `deploy-prod.sh` |
|
||||
| Frontend "unhealthy" in `docker ps` | Healthcheck timing; app still served pages | **Cosmetic** — no action needed |
|
||||
|
||||
**No application code changes were required.** The app, migrations, and seed all worked on first deploy once config was correct.
|
||||
19
infrastructure/backend.prod.env.example
Normal file
19
infrastructure/backend.prod.env.example
Normal file
@@ -0,0 +1,19 @@
|
||||
# Copy to secrets/backend.env on the server.
|
||||
# DATABASE_URL must match database.env credentials (host = postgres service name).
|
||||
NODE_ENV=production
|
||||
PORT=3000
|
||||
|
||||
DATABASE_URL=postgresql://dyolink_user:CHANGE_ME_STRONG_DB_PASSWORD@postgres:5432/dyolink_db
|
||||
|
||||
# Must be real random strings (openssl rand -hex 32). Values containing CHANGE_ME will crash the app.
|
||||
JWT_SECRET=replace_with_openssl_rand_hex_32_output
|
||||
JWT_EXPIRES_IN=15m
|
||||
JWT_REFRESH_SECRET=replace_with_a_different_openssl_rand_hex_32_output
|
||||
JWT_REFRESH_EXPIRES_IN=30d
|
||||
|
||||
# Must match DOMAIN in .env — used for CORS, invite links, cookies
|
||||
FRONTEND_URL=https://wixur.ir
|
||||
|
||||
# SMS (sms.ir)
|
||||
SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY
|
||||
SMS_IR_TEMPLATE_ID=123456
|
||||
@@ -11,3 +11,7 @@ JWT_REFRESH_EXPIRES_IN=30d
|
||||
|
||||
# CORS, cookies, and invite links — must match how users open the app (nginx host port)
|
||||
FRONTEND_URL=http://178.131.50.201:8088
|
||||
|
||||
# SMS (sms.ir)
|
||||
SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY
|
||||
SMS_IR_TEMPLATE_ID=123456
|
||||
|
||||
4
infrastructure/database.prod.env.example
Normal file
4
infrastructure/database.prod.env.example
Normal file
@@ -0,0 +1,4 @@
|
||||
# Copy to secrets/database.env on the server (never commit real passwords).
|
||||
POSTGRES_USER=dyolink_user
|
||||
POSTGRES_PASSWORD=CHANGE_ME_STRONG_DB_PASSWORD
|
||||
POSTGRES_DB=dyolink_db
|
||||
18
infrastructure/deploy.prod.env.example
Normal file
18
infrastructure/deploy.prod.env.example
Normal file
@@ -0,0 +1,18 @@
|
||||
# Copy to infrastructure/.env on the server (not committed).
|
||||
# docker compose -f docker-compose.prod.yml --env-file .env ...
|
||||
|
||||
DOMAIN=wixur.ir
|
||||
DOCKER_USERNAME=dyolink
|
||||
TAG=latest
|
||||
|
||||
# Let's Encrypt — certificate issuance and renewal notices
|
||||
LETSENCRYPT_EMAIL=rameen.naghdi@gmail.com
|
||||
|
||||
# Optional: extra hostnames on the same cert (space-separated), e.g. www.wixur.ir
|
||||
# CERTBOT_EXTRA_DOMAINS=www.wixur.ir
|
||||
|
||||
# Optional: use Let's Encrypt staging while testing (avoids rate limits)
|
||||
# LETSENCRYPT_STAGING=1
|
||||
|
||||
# Folder with database.env and backend.env (absolute path on server recommended)
|
||||
DEPLOY_SECRETS_DIR=/opt/dyolink/secrets
|
||||
@@ -1,16 +1,24 @@
|
||||
# Production stack — pull images from Docker Hub, HTTPS via Let's Encrypt (certbot).
|
||||
#
|
||||
# Server setup (minimal):
|
||||
# 1. Copy deploy.prod.env.example → .env (DOMAIN, DOCKER_USERNAME, LETSENCRYPT_EMAIL)
|
||||
# 2. Copy secrets/*.example → ../secrets/ (database.env, backend.env) — outside git
|
||||
# 3. docker login (private Docker Hub images)
|
||||
# 4. ./scripts/init-letsencrypt.sh (first time only)
|
||||
# 5. docker compose -f docker-compose.prod.yml --env-file .env up -d
|
||||
#
|
||||
# Updates: docker compose pull && docker compose up -d
|
||||
|
||||
name: dyolink-prod
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
container_name: dyolink_db_prod
|
||||
env_file:
|
||||
- database.env
|
||||
- ${DEPLOY_SECRETS_DIR:-./secrets}/database.env
|
||||
environment:
|
||||
- POSTGRES_USER=${POSTGRES_USER}
|
||||
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
|
||||
- POSTGRES_DB=${POSTGRES_DB:-dyolink_db}
|
||||
- TZ=UTC
|
||||
ports:
|
||||
- "5433:5432"
|
||||
TZ: UTC
|
||||
volumes:
|
||||
- postgres_data_prod:/var/lib/postgresql/data
|
||||
- ./database/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
|
||||
@@ -19,12 +27,12 @@ services:
|
||||
- dyolink_network
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: "json-file"
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
|
||||
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
@@ -37,18 +45,18 @@ services:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
env_file:
|
||||
- backend.env
|
||||
- ${DEPLOY_SECRETS_DIR:-./secrets}/backend.env
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- TZ=UTC
|
||||
- PORT=3000
|
||||
ports:
|
||||
- "4001:3000"
|
||||
NODE_ENV: production
|
||||
TZ: UTC
|
||||
PORT: "3000"
|
||||
expose:
|
||||
- "3000"
|
||||
networks:
|
||||
- dyolink_network
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: "json-file"
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
@@ -57,26 +65,25 @@ services:
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
start_period: 60s
|
||||
|
||||
frontend:
|
||||
image: ${DOCKER_USERNAME}/dyolink-frontend:${TAG:-latest}
|
||||
container_name: dyolink_frontend_prod
|
||||
depends_on:
|
||||
- backend
|
||||
env_file:
|
||||
- frontend.env
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- TZ=UTC
|
||||
- PORT=3000
|
||||
ports:
|
||||
- "4000:3000"
|
||||
NODE_ENV: production
|
||||
TZ: UTC
|
||||
PORT: "3000"
|
||||
HOSTNAME: "0.0.0.0"
|
||||
expose:
|
||||
- "3000"
|
||||
networks:
|
||||
- dyolink_network
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: "json-file"
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
@@ -85,34 +92,47 @@ services:
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 60s
|
||||
|
||||
nginx:
|
||||
image: nginx:alpine
|
||||
container_name: dyolink_nginx_prod
|
||||
depends_on:
|
||||
- backend
|
||||
- frontend
|
||||
ports:
|
||||
- "80:80"
|
||||
- "443:443"
|
||||
volumes:
|
||||
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
- ./ssl:/etc/nginx/ssl:ro
|
||||
- ./nginx/generated/default.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
- certbot_conf:/etc/letsencrypt:ro
|
||||
- certbot_www:/var/www/certbot:ro
|
||||
- ./logs/nginx:/var/log/nginx
|
||||
networks:
|
||||
- dyolink_network
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: "json-file"
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "10m"
|
||||
max-file: "3"
|
||||
|
||||
certbot:
|
||||
image: certbot/certbot:latest
|
||||
container_name: dyolink_certbot_prod
|
||||
volumes:
|
||||
- certbot_conf:/etc/letsencrypt
|
||||
- certbot_www:/var/www/certbot
|
||||
entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"
|
||||
networks:
|
||||
- dyolink_network
|
||||
restart: unless-stopped
|
||||
|
||||
networks:
|
||||
dyolink_network:
|
||||
driver: bridge
|
||||
name: dyolink_network
|
||||
|
||||
volumes:
|
||||
postgres_data_prod:
|
||||
name: dyolink_postgres_data_prod
|
||||
name: dyolink_postgres_data_prod
|
||||
certbot_conf:
|
||||
name: dyolink_certbot_conf
|
||||
certbot_www:
|
||||
name: dyolink_certbot_www
|
||||
|
||||
17
infrastructure/nginx/nginx.bootstrap.conf
Normal file
17
infrastructure/nginx/nginx.bootstrap.conf
Normal file
@@ -0,0 +1,17 @@
|
||||
# Temporary HTTP-only config used while obtaining the first Let's Encrypt certificate.
|
||||
# Replaced by nginx/generated/default.conf after ./scripts/init-letsencrypt.sh
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name _;
|
||||
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 200 'Dyolink: obtaining SSL certificate. Retry shortly.';
|
||||
add_header Content-Type text/plain;
|
||||
}
|
||||
}
|
||||
97
infrastructure/nginx/nginx.ssl.conf.template
Normal file
97
infrastructure/nginx/nginx.ssl.conf.template
Normal file
@@ -0,0 +1,97 @@
|
||||
# Generated from nginx.ssl.conf.template — do not edit nginx/generated/default.conf by hand.
|
||||
# Re-run: ./scripts/render-nginx-ssl.sh
|
||||
|
||||
upstream dyolink_backend {
|
||||
server backend:3000;
|
||||
keepalive 32;
|
||||
}
|
||||
|
||||
upstream dyolink_frontend {
|
||||
server frontend:3000;
|
||||
keepalive 32;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name ${DOMAIN};
|
||||
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
listen [::]:443 ssl http2;
|
||||
server_name ${DOMAIN};
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
|
||||
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
ssl_prefer_server_ciphers off;
|
||||
ssl_session_cache shared:SSL:10m;
|
||||
ssl_session_timeout 10m;
|
||||
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-XSS-Protection "1; mode=block" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_proxied expired no-cache no-store private auth;
|
||||
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
|
||||
|
||||
client_max_body_size 50M;
|
||||
client_body_timeout 12;
|
||||
client_header_timeout 12;
|
||||
keepalive_timeout 15;
|
||||
send_timeout 10;
|
||||
|
||||
location / {
|
||||
proxy_pass http://dyolink_frontend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_read_timeout 300;
|
||||
proxy_connect_timeout 300;
|
||||
}
|
||||
|
||||
location /api {
|
||||
proxy_pass http://dyolink_backend;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection 'upgrade';
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_cache_bypass $http_upgrade;
|
||||
proxy_read_timeout 300;
|
||||
proxy_connect_timeout 300;
|
||||
}
|
||||
|
||||
location /health {
|
||||
access_log off;
|
||||
return 200 "healthy\n";
|
||||
add_header Content-Type text/plain;
|
||||
}
|
||||
|
||||
location ~ /\. {
|
||||
deny all;
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
}
|
||||
}
|
||||
0
infrastructure/scripts/backup.sh
Normal file → Executable file
0
infrastructure/scripts/backup.sh
Normal file → Executable file
48
infrastructure/scripts/build-and-push-prod.sh
Executable file
48
infrastructure/scripts/build-and-push-prod.sh
Executable file
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
|
||||
INFRA_DIR="$SCRIPT_DIR/.."
|
||||
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m'
|
||||
|
||||
DOMAIN="${1:-wixur.ir}"
|
||||
TAG="${2:-latest}"
|
||||
DOCKER_USERNAME="${DOCKER_USERNAME:-dyolink}"
|
||||
PUBLIC_BASE="https://${DOMAIN}"
|
||||
|
||||
echo -e "${BLUE}Building Dyolink images for ${PUBLIC_BASE}${NC}"
|
||||
echo -e "${YELLOW}Docker Hub: ${DOCKER_USERNAME}/dyolink-*:${TAG}${NC}"
|
||||
|
||||
if ! docker info >/dev/null 2>&1; then
|
||||
echo "Docker is not running."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo -e "${YELLOW}Ensure you are logged in: docker login${NC}"
|
||||
|
||||
docker build \
|
||||
-t "${DOCKER_USERNAME}/dyolink-backend:${TAG}" \
|
||||
-t "${DOCKER_USERNAME}/dyolink-backend:latest" \
|
||||
"${REPO_ROOT}/backend"
|
||||
|
||||
docker build \
|
||||
--build-arg "NEXT_PUBLIC_API_URL=${PUBLIC_BASE}/api" \
|
||||
--build-arg "NEXT_PUBLIC_APP_URL=${PUBLIC_BASE}" \
|
||||
--build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" \
|
||||
-t "${DOCKER_USERNAME}/dyolink-frontend:${TAG}" \
|
||||
-t "${DOCKER_USERNAME}/dyolink-frontend:latest" \
|
||||
"${REPO_ROOT}/frontend"
|
||||
|
||||
docker push "${DOCKER_USERNAME}/dyolink-backend:${TAG}"
|
||||
docker push "${DOCKER_USERNAME}/dyolink-backend:latest"
|
||||
docker push "${DOCKER_USERNAME}/dyolink-frontend:${TAG}"
|
||||
docker push "${DOCKER_USERNAME}/dyolink-frontend:latest"
|
||||
|
||||
echo -e "${GREEN}Pushed:${NC}"
|
||||
echo " ${DOCKER_USERNAME}/dyolink-backend:${TAG}"
|
||||
echo " ${DOCKER_USERNAME}/dyolink-frontend:${TAG}"
|
||||
2
infrastructure/scripts/build-and-push.sh
Normal file → Executable file
2
infrastructure/scripts/build-and-push.sh
Normal file → Executable file
@@ -85,6 +85,8 @@ echo "JWT_SECRET=CHANGE_ME_32_CHARS_MINIMUM" >> $DEPLOY_DIR/backend.env.example
|
||||
echo "DATABASE_URL=postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@postgres:5432/\${POSTGRES_DB}" >> $DEPLOY_DIR/backend.env.example
|
||||
echo "CORS_ORIGIN=https://dyolink.com" >> $DEPLOY_DIR/backend.env.example
|
||||
echo "FRONTEND_URL=https://dyolink.com" >> $DEPLOY_DIR/backend.env.example
|
||||
echo "SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY" >> $DEPLOY_DIR/backend.env.example
|
||||
echo "SMS_IR_TEMPLATE_ID=123456" >> $DEPLOY_DIR/backend.env.example
|
||||
|
||||
echo "# Frontend" > $DEPLOY_DIR/frontend.env.example
|
||||
echo "NEXT_PUBLIC_API_URL=/api" >> $DEPLOY_DIR/frontend.env.example
|
||||
|
||||
57
infrastructure/scripts/deploy-prod.sh
Executable file
57
infrastructure/scripts/deploy-prod.sh
Executable file
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
INFRA_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
cd "$INFRA_DIR"
|
||||
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m'
|
||||
|
||||
echo -e "${BLUE}╔════════════════════════════════════════╗${NC}"
|
||||
echo -e "${BLUE}║ Dyolink — Production Deploy ║${NC}"
|
||||
echo -e "${BLUE}╚════════════════════════════════════════╝${NC}"
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
echo -e "${RED}Missing .env — copy deploy.prod.env.example to .env${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
source .env
|
||||
set +a
|
||||
|
||||
SECRETS_DIR="${DEPLOY_SECRETS_DIR:-./secrets}"
|
||||
if [ ! -f "${SECRETS_DIR}/database.env" ] || [ ! -f "${SECRETS_DIR}/backend.env" ]; then
|
||||
echo -e "${RED}Missing secrets in ${SECRETS_DIR}/${NC}"
|
||||
echo " Need: database.env and backend.env"
|
||||
echo " Copy from database.prod.env.example and backend.prod.env.example"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
COMPOSE=(docker compose -f docker-compose.prod.yml --env-file .env)
|
||||
|
||||
if ! docker volume inspect dyolink_certbot_conf >/dev/null 2>&1 || \
|
||||
! docker run --rm -v dyolink_certbot_conf:/etc/letsencrypt:ro alpine \
|
||||
test -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" 2>/dev/null; then
|
||||
echo -e "${YELLOW}No SSL certificate yet — running init-letsencrypt.sh first...${NC}"
|
||||
./scripts/init-letsencrypt.sh
|
||||
else
|
||||
./scripts/render-nginx-ssl.sh
|
||||
echo -e "${YELLOW}Pulling images...${NC}"
|
||||
"${COMPOSE[@]}" pull backend frontend
|
||||
echo -e "${YELLOW}Starting stack...${NC}"
|
||||
"${COMPOSE[@]}" up -d --force-recreate nginx
|
||||
"${COMPOSE[@]}" up -d
|
||||
fi
|
||||
|
||||
sleep 8
|
||||
echo -e "\n${GREEN}=== Status ===${NC}"
|
||||
"${COMPOSE[@]}" ps
|
||||
|
||||
echo -e "\n${BLUE}App URL: https://${DOMAIN}${NC}"
|
||||
echo -e "${BLUE}API health: https://${DOMAIN}/api/health${NC}"
|
||||
0
infrastructure/scripts/deploy.sh
Normal file → Executable file
0
infrastructure/scripts/deploy.sh
Normal file → Executable file
76
infrastructure/scripts/init-letsencrypt.sh
Executable file
76
infrastructure/scripts/init-letsencrypt.sh
Executable file
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
INFRA_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
cd "$INFRA_DIR"
|
||||
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
RED='\033[0;31m'
|
||||
NC='\033[0m'
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
echo -e "${RED}Missing .env — copy deploy.prod.env.example to .env${NC}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
source .env
|
||||
set +a
|
||||
|
||||
: "${DOMAIN:?Set DOMAIN in .env}"
|
||||
: "${LETSENCRYPT_EMAIL:?Set LETSENCRYPT_EMAIL in .env}"
|
||||
|
||||
COMPOSE=(docker compose -f docker-compose.prod.yml --env-file .env)
|
||||
|
||||
mkdir -p nginx/generated logs/nginx database/backups
|
||||
|
||||
CERT_PATH="certbot_conf/live/${DOMAIN}/fullchain.pem"
|
||||
if docker volume inspect dyolink_certbot_conf >/dev/null 2>&1; then
|
||||
if docker run --rm -v dyolink_certbot_conf:/etc/letsencrypt:ro alpine \
|
||||
test -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem"; then
|
||||
echo -e "${GREEN}Certificate already exists for ${DOMAIN}${NC}"
|
||||
./scripts/render-nginx-ssl.sh
|
||||
"${COMPOSE[@]}" up -d --force-recreate nginx
|
||||
"${COMPOSE[@]}" up -d
|
||||
exit 0
|
||||
fi
|
||||
fi
|
||||
|
||||
echo -e "${YELLOW}Phase 1: bootstrap nginx (HTTP) for ACME challenge...${NC}"
|
||||
cp nginx/nginx.bootstrap.conf nginx/generated/default.conf
|
||||
"${COMPOSE[@]}" up -d nginx
|
||||
|
||||
echo -e "${YELLOW}Phase 2: request Let's Encrypt certificate...${NC}"
|
||||
CERTBOT_ARGS=(
|
||||
certonly
|
||||
--webroot
|
||||
-w /var/www/certbot
|
||||
--email "$LETSENCRYPT_EMAIL"
|
||||
--agree-tos
|
||||
--no-eff-email
|
||||
-d "$DOMAIN"
|
||||
)
|
||||
|
||||
if [ -n "${CERTBOT_EXTRA_DOMAINS:-}" ]; then
|
||||
for extra in $CERTBOT_EXTRA_DOMAINS; do
|
||||
CERTBOT_ARGS+=(-d "$extra")
|
||||
done
|
||||
fi
|
||||
|
||||
if [ "${LETSENCRYPT_STAGING:-0}" = "1" ]; then
|
||||
CERTBOT_ARGS+=(--staging)
|
||||
echo -e "${YELLOW}Using Let's Encrypt staging (test) certificates${NC}"
|
||||
fi
|
||||
|
||||
"${COMPOSE[@]}" run --rm --entrypoint certbot certbot "${CERTBOT_ARGS[@]}"
|
||||
|
||||
echo -e "${YELLOW}Phase 3: enable HTTPS nginx config...${NC}"
|
||||
./scripts/render-nginx-ssl.sh
|
||||
"${COMPOSE[@]}" up -d --force-recreate nginx
|
||||
"${COMPOSE[@]}" up -d
|
||||
|
||||
echo -e "${GREEN}SSL ready for https://${DOMAIN}${NC}"
|
||||
echo -e "${GREEN}Certbot renewal container is running (checks every 12h).${NC}"
|
||||
0
infrastructure/scripts/logs.sh
Normal file → Executable file
0
infrastructure/scripts/logs.sh
Normal file → Executable file
0
infrastructure/scripts/manage.sh
Normal file → Executable file
0
infrastructure/scripts/manage.sh
Normal file → Executable file
0
infrastructure/scripts/monitor.sh
Normal file → Executable file
0
infrastructure/scripts/monitor.sh
Normal file → Executable file
23
infrastructure/scripts/render-nginx-ssl.sh
Executable file
23
infrastructure/scripts/render-nginx-ssl.sh
Executable file
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
INFRA_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
|
||||
cd "$INFRA_DIR"
|
||||
|
||||
if [ ! -f .env ]; then
|
||||
echo "Missing .env — copy deploy.prod.env.example to .env and edit."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
source .env
|
||||
set +a
|
||||
|
||||
: "${DOMAIN:?Set DOMAIN in .env}"
|
||||
|
||||
mkdir -p nginx/generated
|
||||
export DOMAIN
|
||||
envsubst '${DOMAIN}' < nginx/nginx.ssl.conf.template > nginx/generated/default.conf
|
||||
echo "Rendered nginx/generated/default.conf for ${DOMAIN}"
|
||||
Reference in New Issue
Block a user