init
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
import dataBaseConfig from './config/mikro-orm.config';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { UserModule } from './modules/users/user.module';
|
||||
import { UtilsModule } from './modules/utils/utils.module';
|
||||
import { AuthModule } from './modules/auth/auth.module';
|
||||
import { UploaderModule } from './modules/uploader/uploader.module';
|
||||
import { AdminModule } from './modules/admin/admin.module';
|
||||
import { ThrottlerModule } from '@nestjs/throttler';
|
||||
import { ScheduleModule } from '@nestjs/schedule';
|
||||
import { RestaurantsModule } from './modules/restaurants/restaurants.module';
|
||||
import { FoodModule } from './modules/foods/food.module';
|
||||
import { CartModule } from './modules/cart/cart.module';
|
||||
import { RolesModule } from './modules/roles/roles.module';
|
||||
import { PaymentsModule } from './modules/payments/payments.module';
|
||||
import { DeliveryModule } from './modules/delivery/delivery.module';
|
||||
import { OrdersModule } from './modules/orders/orders.module';
|
||||
import { CouponModule } from './modules/coupons/coupon.module';
|
||||
import { ReviewModule } from './modules/review/review.module';
|
||||
import { NotificationsModule } from './modules/notifications/notifications.module';
|
||||
import { EventEmitterModule } from '@nestjs/event-emitter';
|
||||
import { PagerModule } from './modules/pager/pager.module';
|
||||
import { ContactModule } from './modules/contact/contact.module';
|
||||
import { InventoryModule } from './modules/inventory/inventory.module';
|
||||
import { IconsModule } from './modules/icons/icons.module';
|
||||
import { CacheModule } from '@nestjs/cache-manager';
|
||||
import { cacheConfig } from './config/cache.config';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true, cache: true }),
|
||||
CacheModule.registerAsync(cacheConfig()),
|
||||
MikroOrmModule.forRootAsync(dataBaseConfig),
|
||||
UserModule,
|
||||
UtilsModule,
|
||||
AuthModule,
|
||||
UploaderModule,
|
||||
AdminModule,
|
||||
ThrottlerModule.forRoot([
|
||||
{
|
||||
ttl: 60, // time window in seconds
|
||||
limit: 5, // max requests per window
|
||||
},
|
||||
]),
|
||||
ScheduleModule.forRoot(),
|
||||
RestaurantsModule,
|
||||
FoodModule,
|
||||
CartModule,
|
||||
RolesModule,
|
||||
PaymentsModule,
|
||||
DeliveryModule,
|
||||
OrdersModule,
|
||||
CouponModule,
|
||||
ReviewModule,
|
||||
NotificationsModule,
|
||||
EventEmitterModule.forRoot(),
|
||||
PagerModule,
|
||||
ContactModule,
|
||||
InventoryModule,
|
||||
IconsModule,
|
||||
],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
// exports: [CacheService],
|
||||
})
|
||||
export class AppModule {}
|
||||
Executable
+20
@@ -0,0 +1,20 @@
|
||||
// export const AUTH_THROTTLE = "AUTH_THROTTLE";
|
||||
export const AI_CONFIG = 'AI_CONFIG';
|
||||
export const MIKRO_ORM_QUERY_LOGGER = 'MIKRO_ORM_QUERY_LOGGER';
|
||||
export const NAJVA_CONFIG = 'NAJVA_CONFIG';
|
||||
export const AUTH_THROTTLE_TTL = 1 * 60 * 1000;
|
||||
export const AUTH_THROTTLE_LIMIT = 5;
|
||||
export const AUTH__REFRESH_THROTTLE_TTL = 10 * 60 * 1000;
|
||||
export const AUTH__REFRESH_THROTTLE_LIMIT = 10;
|
||||
//
|
||||
export const CONSOLE_JWT_STRATEGY_NAME = 'console_jwt_strategy';
|
||||
export const LOCAL_JWT_STRATEGY_NAME = 'local_jwt_strategy';
|
||||
|
||||
export const API_HEADER_SLUG = {
|
||||
name: 'X-Slug',
|
||||
required: true,
|
||||
schema: {
|
||||
type: 'string',
|
||||
default: 'zhivan',
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createParamDecorator, type ExecutionContext } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* Decorator to extract userId from the authenticated request.
|
||||
* Must be used after AdminAuthGuard or AuthGuard that sets request.userId.
|
||||
*
|
||||
* @example
|
||||
* @Get('/profile')
|
||||
* @UseGuards(AdminAuthGuard)
|
||||
* getProfile(@UserId() userId: string) {
|
||||
* return this.userService.findById(userId);
|
||||
* }
|
||||
*/
|
||||
export const AdminId = createParamDecorator((data: unknown, ctx: ExecutionContext): string => {
|
||||
const request = ctx.switchToHttp().getRequest<Request & { adminId?: string }>();
|
||||
return request.adminId || '';
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
export { UserId } from './user-id.decorator';
|
||||
export { RestId } from './rest-id.decorator';
|
||||
export { RateLimit } from './rate-limit.decorator';
|
||||
@@ -0,0 +1,5 @@
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const PERMISSIONS_KEY = 'permissions';
|
||||
|
||||
export const Permissions = (...permissions: string[]) => SetMetadata(PERMISSIONS_KEY, permissions);
|
||||
@@ -0,0 +1,18 @@
|
||||
import { UseGuards, applyDecorators } from '@nestjs/common';
|
||||
import { Throttle, ThrottlerGuard } from '@nestjs/throttler';
|
||||
|
||||
import {
|
||||
AUTH_THROTTLE_LIMIT,
|
||||
AUTH_THROTTLE_TTL,
|
||||
AUTH__REFRESH_THROTTLE_LIMIT,
|
||||
AUTH__REFRESH_THROTTLE_TTL,
|
||||
} from '../constants';
|
||||
|
||||
export const RateLimit = (limit: number, ttl: number) =>
|
||||
applyDecorators(Throttle({ default: { limit, ttl } }), UseGuards(ThrottlerGuard));
|
||||
|
||||
// Predefined rate limits for common scenarios
|
||||
export const StrictRateLimit = () => RateLimit(AUTH_THROTTLE_LIMIT, AUTH_THROTTLE_TTL); // 5 requests per minute
|
||||
export const StandardRateLimit = () => RateLimit(30, 60000); // 30 requests per minute
|
||||
export const MailSendRateLimit = () => RateLimit(10, 60000); // 10 emails per minute
|
||||
export const RefreshTokenRateLimit = () => RateLimit(AUTH__REFRESH_THROTTLE_LIMIT, AUTH__REFRESH_THROTTLE_TTL); // 10 emails per minute
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createParamDecorator, type ExecutionContext } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* Decorator to extract restId from the authenticated request.
|
||||
* Must be used after AdminAuthGuard or AuthGuard that sets request.restId.
|
||||
*
|
||||
* @example
|
||||
* @Get('/restaurants')
|
||||
* @UseGuards(AdminAuthGuard)
|
||||
* getRestaurants(@RestId() restId: string) {
|
||||
* return this.restaurantService.findById(restId);
|
||||
* }
|
||||
*/
|
||||
export const RestId = createParamDecorator((data: unknown, ctx: ExecutionContext): string => {
|
||||
const request = ctx.switchToHttp().getRequest<Request & { restId?: string }>();
|
||||
return request.restId || '';
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createParamDecorator, type ExecutionContext } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
|
||||
export const RestSlug = createParamDecorator((data: unknown, ctx: ExecutionContext): string => {
|
||||
const request = ctx.switchToHttp().getRequest<Request & { slug?: string }>();
|
||||
return request.slug || '';
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { createParamDecorator, type ExecutionContext } from '@nestjs/common';
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* Decorator to extract userId from the authenticated request.
|
||||
* Must be used after AdminAuthGuard or AuthGuard that sets request.userId.
|
||||
*
|
||||
* @example
|
||||
* @Get('/profile')
|
||||
* @UseGuards(AdminAuthGuard)
|
||||
* getProfile(@UserId() userId: string) {
|
||||
* return this.userService.findById(userId);
|
||||
* }
|
||||
*/
|
||||
export const UserId = createParamDecorator((data: unknown, ctx: ExecutionContext): string => {
|
||||
const request = ctx.switchToHttp().getRequest<Request & { userId?: string }>();
|
||||
return request.userId || '';
|
||||
});
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
import { Index, PrimaryKey, Property, Filter, OptionalProps } from '@mikro-orm/core';
|
||||
import { ulid } from 'ulid';
|
||||
|
||||
@Filter({ name: 'notDeleted', cond: { deletedAt: null }, default: true })
|
||||
@Index({ properties: ['deletedAt'] })
|
||||
@Index({ properties: ['createdAt'] })
|
||||
export abstract class BaseEntity {
|
||||
[OptionalProps]?: 'id' | 'createdAt' | 'updatedAt' | 'deletedAt';
|
||||
|
||||
@PrimaryKey({ type: 'string', columnType: 'char(26)' })
|
||||
id: string = ulid();
|
||||
|
||||
@Property({ defaultRaw: 'now()', columnType: 'timestamptz' })
|
||||
createdAt: Date = new Date();
|
||||
|
||||
@Property({
|
||||
onUpdate: () => new Date(),
|
||||
defaultRaw: 'now()',
|
||||
columnType: 'timestamptz',
|
||||
})
|
||||
updatedAt: Date = new Date();
|
||||
|
||||
@Property({ nullable: true })
|
||||
deletedAt?: Date;
|
||||
}
|
||||
Executable
+780
@@ -0,0 +1,780 @@
|
||||
export const enum AuthMessage {
|
||||
UNAUTHORIZED_ACCESS = 'شما دسترسی لازم برای این عملیات را ندارید.',
|
||||
PHONE_REGISTERED = 'شماره ثبت شد',
|
||||
INVALID_PHONE_FORMAT = 'فرمت شماره تلفن صحیح نیست',
|
||||
OTP_SENT = 'کد یکبار مصرف به شماره شما ارسال شد.',
|
||||
INVALID_PHONE = 'شماره موبایل اشتباه می باشد',
|
||||
INVALID_CREDENTIAL = 'شماره موبایل یا رمز عبور اشتباه می باشد',
|
||||
OTP_FAILED = 'کد یا شماره موبایل اشتباه است',
|
||||
LOGIN_SUCCESS = 'ورود با موفقیت انجام شد',
|
||||
PASSWORD_LOGIN_SUCCESS = 'با موفقیت وارد شدید',
|
||||
FORGOT_PASSWORD_SUCCESS = 'درخواست فراموشی رمز عبور با موفقیت ثبت شد',
|
||||
PASSWORD_SET_SUCCESS = 'پسورد با موفقیت تنظیم شد',
|
||||
PASSWORD_UPDATE_SUCCESS = 'رمز عبور شما تغییر کرد',
|
||||
INVALID_OTP = 'کد صحیح نمیباشد یا منقضی شده است',
|
||||
PASSWORD_MISMATCH = 'رمز عبور یکسان نیست',
|
||||
INVALID_PASSWORD = 'ایمیل یا رمز عبور اشتباه است',
|
||||
INVALID_REPEAT_PASSWORD = 'تکرار رمز عبور اشتباه است',
|
||||
EMAIL_NOT_EMPTY = 'ایمیل نمیتواند خالی باشد.',
|
||||
INVALID_EMAIL_FORMAT = 'فرمت ایمیل صحیح نیست',
|
||||
PasswordNotEmpty = 'پسورد نمیتواند خالی باشد.',
|
||||
USER_NOT_FOUND = 'کاربری با این شماره وجود ندارد',
|
||||
ADMIN_NOT_FOUND = 'ادمینی با این شماره وجود ندارد',
|
||||
USER_EXISTS = 'با این شماره قبلا ثبت نام شده است',
|
||||
USER_REGISTER_SUCCESS = 'ثبت نام موفقیت آمیز بود',
|
||||
INVALID_USER = 'کاربری با این مشخصات یافت نشد',
|
||||
PHONE_NOT_FOUND = 'کاربری با این شماره یافت نشد',
|
||||
TOKEN_EXPIRED = 'توکن منقضی شده است',
|
||||
TOKEN_INVALID = 'توکن نامعتبر است',
|
||||
BANNED = 'در حال حاضر شما امکان دسترسی به این سرویس را ندارید',
|
||||
PHONE_EXISTS = 'شماره تلفن قبلا ثبت شده است',
|
||||
ADMIN_CREATED = 'ادمین با موفقیت ایجاد شد',
|
||||
PERM_NOT_FOUND = 'دسترسی یافت نشد',
|
||||
INVALID_PASS_FORMAT = 'فرمت رمز عبور صحیح نیست',
|
||||
PHONE_NOT_EMPTY = 'شماره تلفن نمیتواند خالی باشد',
|
||||
PASSWORD_FORMAT_INVALID = 'رمز عبور باید به صورت رشته باشد',
|
||||
OTP_FORMAT_INVALID = 'کد یکبار مصرف باید عددی و ۵ رقمی باشد',
|
||||
PHONE_FORMAT_INVALID = 'شماره تلفن باید معتبر و به فرمت ایران باشد',
|
||||
TOKEN_NOT_EMPTY = 'توکن نمیتواند خالی باشد',
|
||||
PASSWORD_NOT_EMPTY = 'رمز عبور نمیتواند خالی باشد',
|
||||
PASSWORD_CHANGED_SUCCESSFULLY = 'رمز عبور با موفقیت تغییر کرد',
|
||||
PASSWORD_CONFIRMATION_NOT_EMPTY = 'تایید رمز عبور نمیتواند خالی باشد',
|
||||
PASSWORD_LENGTH = 'رمز عبور باید حداقل ۸ کاراکتر باشد',
|
||||
OTP_NOT_EMPTY = 'کد یکبار مصرف نمیتواند خالی باشد',
|
||||
LAST_PASSWORD_NOT_EMPTY = 'رمز عبور قبلی نمیتواند خالی باشد',
|
||||
FIRST_NAME_NOT_EMPTY = 'نام نمیتواند خالی باشد',
|
||||
LAST_NAME_NOT_EMPTY = 'نام خانوادگی نمیتواند خالی باشد',
|
||||
FIRST_NAME_SHOULD_BE_BETWEEN_2_AND_50 = 'نام باید بین ۲ تا ۵۰ کاراکتر باشد',
|
||||
LAST_NAME_SHOULD_BE_BETWEEN_2_AND_50 = 'نام خانوادگی باید بین ۲ تا ۵۰ کاراکتر باشد',
|
||||
BIRTH_DATE_NOT_EMPTY = 'تاریخ تولد نمیتواند خالی باشد',
|
||||
NATIONAL_CODE_INCORRECT = 'کد ملی باید ۱۰ رقمی باشد',
|
||||
NATIONAL_NOT_EMPTY = 'کد ملی نمیتواند خالی باشد',
|
||||
OTP_ALREADY_SENT = 'کد یکبار مصرف قبلا ارسال شده است',
|
||||
TOO_MANY_REQUESTS = 'تعداد درخواست های شما بیش از حد مجاز است',
|
||||
NOT_ADMIN = 'شما دسترسی به بخش ادمین ندارید',
|
||||
PHONE_SHOULD_BE_11_DIGIT = 'شماره تلفن باید ۱۱ رقم باشد',
|
||||
TIMESTAMP_NOT_EMPTY = 'زمان نمیتواند خالی باشد',
|
||||
ADMIN_CAN_NOT_LOGIN = 'ادمین نمیتواند وارد شود',
|
||||
NATIONAL_CODE_INVALID = 'کد ملی نامعتبر است',
|
||||
INVALID_REFRESH_TOKEN = 'توکن رفرش نامعتبر است',
|
||||
REFRESH_TOKEN_EXPIRED = 'توکن رفرش منقضی شده است',
|
||||
LOGOUT_SUCCESS = 'خروج با موفقیت انجام شد',
|
||||
CURRENT_PASSWORD_INVALID = 'رمز عبور فعلی نامعتبر است',
|
||||
TOKEN_EXPIRED_OR_INVALID = 'توکن منقضی شده یا نامعتبر است',
|
||||
ACCESS_DENIED = 'دسترسی شما محدود شده است',
|
||||
USER_ACCOUNT_INACTIVE = 'حساب کاربری شما غیر فعال است',
|
||||
TOKEN_MISSED_OR_EXPIRED = 'توکن مفقود یا منقضی شده است',
|
||||
OLD_PASSWORD_REQUIRED = 'رمز عبور قبلی الزامی است',
|
||||
PASSWORD_CHANGE_FAILED = 'تغییر رمز عبور با مشکل روبرد شد',
|
||||
SLUG_REQUIRED = 'اسلاگ الزامی است',
|
||||
INVALID_TOKEN_PAYLOAD = 'محتویات توکن نامعتبر است',
|
||||
INVALID_SLUG = 'اسلاگ نامعتبر است',
|
||||
INVALID_OR_EXPIRED_TOKEN = 'توکن نامعتبر یا منقضی شده است',
|
||||
}
|
||||
export const enum FoodMessage {
|
||||
NOT_FOUND = 'غذایی با این مشخصات یافت نشد',
|
||||
}
|
||||
export const enum CategoryMessage {
|
||||
NOT_FOUND = 'دستهبندی مورد نظر یافت نشد',
|
||||
NOT_CREATED = 'ایجاد دستهبندی با خطا مواجه شد',
|
||||
NOT_UPDATED = 'بهروزرسانی دستهبندی با خطا مواجه شد',
|
||||
NOT_DELETED = 'حذف دستهبندی با خطا مواجه شد',
|
||||
}
|
||||
export const enum UserMessage {
|
||||
USER_NOT_FOUND = 'کاربری با این مشخصات یافت نشد',
|
||||
Rest_NOT_FOUND = 'رستورانی با این مشخصات یافت نشد',
|
||||
USER_EXISTS = 'با این شماره قبلا ثبت نام شده است',
|
||||
USER_REGISTER_SUCCESS = 'ثبت نام موفقیت آمیز بود',
|
||||
EMAIL_ADDRESS_ALREADY_EXISTS = 'ایمیل قبلا ثبت شده است',
|
||||
EMAIL_USER_NOT_FOUND = 'ایمیل یافت نشد',
|
||||
EMAIL_USER_DELETED_SUCCESSFULLY = 'ایمیل با موفقیت حذف شد',
|
||||
FAILED_TO_DELETE_EMAIL_USER = 'خطا در حذف ایمیل',
|
||||
EMAIL_USER_QUOTA_UPDATED_SUCCESSFULLY = 'ایمیل با موفقیت به روز رسانی شد',
|
||||
FAILED_TO_UPDATE_EMAIL_USER_QUOTA = 'خطا در به روز رسانی حجم ایمیل',
|
||||
USERNAME_REQUIRED = 'نام کاربری الزامی است',
|
||||
USERNAME_STRING = 'نام کاربری باید یک رشته باشد',
|
||||
USERNAME_MIN_LENGTH = 'نام کاربری باید حداقل ۲ کاراکتر باشد',
|
||||
USERNAME_MATCHES = 'نام کاربری فقط میتواند شامل حروف، اعداد، نقطه، خط زیر و خط فاصله باشد',
|
||||
PASSWORD_MATCHES = 'رمز عبور باید حداقل ۸ کاراکتر باشد و شامل حروف بزرگ، حروف کوچک، اعداد و علائم خاص باشد',
|
||||
PASSWORD_STRING = 'رمز عبور باید یک رشته باشد',
|
||||
PASSWORD_REQUIRED = 'رمز عبور الزامی است',
|
||||
PASSWORD_MIN_LENGTH = 'رمز عبور باید حداقل ۸ کاراکتر باشد',
|
||||
DOMAIN_ID_STRING = 'شناسه دامنه باید یک رشته باشد',
|
||||
DOMAIN_ID_REQUIRED = 'شناسه دامنه الزامی است',
|
||||
DOMAIN_ID_UUID = 'شناسه دامنه باید یک یو یو آی دی باشد',
|
||||
DISPLAY_NAME_STRING = 'نام نمایشی باید یک رشته باشد',
|
||||
DISPLAY_NAME_OPTIONAL = 'نام نمایشی اختیاری است',
|
||||
QUOTA_NUMBER = 'حجم ایمیل باید یک عدد باشد',
|
||||
QUOTA_OPTIONAL = 'حجم ایمیل اختیاری است',
|
||||
QUOTA_NOT_EMPTY = 'حجم ایمیل نمیتواند خالی باشد',
|
||||
ALIASES_ARRAY = 'الیاس ها باید یک آرایه باشد',
|
||||
ALIASES_STRING = 'الیاس ها باید یک رشته باشد',
|
||||
ALIASES_OPTIONAL = 'الیاس ها اختیاری است',
|
||||
TITLE_STRING = 'عنوان باید یک رشته باشد',
|
||||
TITLE_OPTIONAL = 'عنوان اختیاری است',
|
||||
TITLE_NOT_EMPTY = 'عنوان نمیتواند خالی باشد',
|
||||
EMAIL_USER_CREATED_SUCCESSFULLY = 'ایمیل با موفقیت ایجاد شد',
|
||||
EMAIL_USER_UPDATED_SUCCESSFULLY = 'ایمیل کاربر با موفقیت بهروزرسانی شد',
|
||||
STATUS_UPDATED = 'وضعیت کاربر با موفقیت تغییر کرد',
|
||||
TEMPLATE_UUID = 'شناسه قالب باید یک یو یو آی دی باشد',
|
||||
TEMPLATE_NOT_EMPTY = 'شناسه قالب نمیتواند خالی باشد',
|
||||
ALIASES_EMAIL = 'آدرس ایمیل الیاس باید معتبر باشد',
|
||||
FORWARDERS_EMAIL_VALID = 'آدرس ایمیل فوروارد باید معتبر باشد',
|
||||
FORWARDERS_ARRAY = 'آدرس های فوروارد باید یک آرایه باشد',
|
||||
FORWARDERS_STRING = 'آدرس های فوروارد باید یک رشته باشد',
|
||||
PROFILE_PICTURE_URL = 'آدرس تصویر پروفایل باید یک آدرس اینترنتی معتبر باشد',
|
||||
USER_UPDATED_SUCCESSFULLY = 'کاربر با موفقیت به روز رسانی شد',
|
||||
PROFILE_PICTURE_NOT_EMPTY = 'تصویر پروفایل نمیتواند خالی باشد',
|
||||
PUSH_TOKEN_NOT_FOUND = 'توکن پوش نامعتبر است',
|
||||
PUSH_TOKEN_ADDED_SUCCESSFULLY = 'توکن پوش با موفقیت اضافه شد',
|
||||
NO_PUSH_TOKENS_FOUND = 'توکن پوشی برای این کاربر یافت نشد',
|
||||
PUSH_TOKEN_REMOVED_SUCCESSFULLY = 'توکن پوش با موفقیت حذف شد',
|
||||
}
|
||||
|
||||
export const enum CommonMessage {
|
||||
VALIDITY_TYPE_REQUIRED = 'نوع اعتبار سنجی مورد نیاز است',
|
||||
THIS_FILED_IS_REQUIRED = 'این فیلد الزامی است',
|
||||
VALID_FOR_CHOOSE = 'معتبر برای انتخاب',
|
||||
UPDATE_SUCCESS = 'با موفقیت به روز رسانی شد',
|
||||
CREATED = 'با موفقیت ایجاد شد',
|
||||
DELETED = 'با موفقیت حذف شد',
|
||||
ID_REQUIRED = 'شناسه مورد نیاز است',
|
||||
ID_SHOULD_BE_UUID = 'شناسه باید یک یو یو آی دی باشد',
|
||||
PaymentTypeQueryNotEmpty = 'نوع پرداخت نمیتواند خالی باشد',
|
||||
SEARCH_QUERY_STRING = 'رشته جستجو باید یک رشته باشد',
|
||||
UPDATED = 'با موفقیت آپدیت شد',
|
||||
IS_ACTIVE_SHOULD_BE_1_0 = 'وضعیت باید یکی از مقادیر ۰ و ۱ باشد',
|
||||
DATE_MUST_BE_DATE = 'تاریخ باید یک تاریخ معتبر به صورت رشته باشد',
|
||||
}
|
||||
|
||||
export const enum UploaderMessage {
|
||||
UPLOAD_FILE_INVALID = 'فایل معتبر نیست',
|
||||
UPLOAD_FILE_TOO_LARGE = 'فایل بزرگتر از حد مجاز است . حداکثر حجم فایل [MAX_FILE_SIZE] مگابایت است',
|
||||
UPLOAD_FILE_TYPE_NOT_SUPPORTED = 'نوع فایل معتبر نیست . مجاز است : [MIME_TYPES]',
|
||||
UPLOAD_FILE_SUCCESS = 'فایل با موفقیت آپلود شد',
|
||||
}
|
||||
|
||||
export const enum EmailMessage {
|
||||
EMAIL_VERIFICATION = 'تایید ایمیل',
|
||||
EMAIL_SENDING_FAILED = 'ارسال ایمیل با خطا مواجه شد',
|
||||
LOGIN = 'ورود به سیستم',
|
||||
INVOICE = 'فاکتور',
|
||||
WALLET = 'اعلان کیف پول',
|
||||
TICKET = 'تیکت پشتیبانی',
|
||||
ANNOUNCEMENT = 'اعلان',
|
||||
PAYMENT_REMINDER = 'یادآوری پرداخت',
|
||||
PAYMENT_CANCELLATION = 'لغو پرداخت',
|
||||
EMAIL_SENDING_SUCCESS = 'ارسال ایمیل با موفقیت انجام شد',
|
||||
EMAIL_FORWARD_SUCCESS = 'فوروارد ایمیل با موفقیت انجام شد',
|
||||
EMAIL_STATUS_RETRIEVED_SUCCESSFULLY = 'وضعیت ایمیل با موفقیت دریافت شد',
|
||||
MESSAGES_SEARCHED_SUCCESSFULLY = 'جستجوی ایمیل با موفقیت انجام شد',
|
||||
MESSAGES_LISTED_SUCCESSFULLY = 'لیست ایمیل ها با موفقیت دریافت شد',
|
||||
MESSAGE_RETRIEVED_SUCCESSFULLY = 'ایمیل با موفقیت دریافت شد',
|
||||
MESSAGE_DELETED_SUCCESSFULLY = 'ایمیل با موفقیت حذف شد',
|
||||
USER_ID_REQUIRED = 'شناسه کاربری مورد نیاز است',
|
||||
USER_ID_MUST_BE_STRING = 'شناسه کاربری باید یک رشته باشد',
|
||||
MAILBOX_ID_REQUIRED = 'شناسه میل باکس ایمیل مورد نیاز است',
|
||||
MAILBOX_ID_MUST_BE_STRING = 'شناسه میل باکس ایمیل باید یک رشته باشد',
|
||||
QUEUE_ID_REQUIRED = 'شناسه پیشنویس ایمیل مورد نیاز است',
|
||||
QUEUE_ID_MUST_BE_STRING = 'شناسه پیشنویس ایمیل باید یک رشته باشد',
|
||||
MESSAGE_ID_MUST_BE_NUMBER = 'شناسه ایمیل باید یک عدد باشد',
|
||||
FROM_ADDRESS_REQUIRED = 'آدرس از مورد نیاز است',
|
||||
|
||||
// Validation Messages for Email DTOs
|
||||
FROM_ADDRESS_MUST_BE_EMAIL = 'آدرس فرستنده باید یک ایمیل معتبر باشد',
|
||||
|
||||
// Query validation messages
|
||||
SEARCH_QUERY_PARAMETER_MUST_BE_STRING = 'پارامتر جستجو باید یک رشته باشد',
|
||||
MESSAGE_IDS_MUST_BE_STRING = 'شناسههای پیام باید یک رشته باشد',
|
||||
THREAD_ID_MUST_BE_STRING = 'شناسه رشته گفتگو باید یک رشته باشد',
|
||||
OR_QUERY_MUST_BE_OBJECT = 'پارامتر OR باید یک شیء باشد',
|
||||
DATE_START_MUST_BE_DATE_STRING = 'تاریخ شروع باید یک رشته تاریخ معتبر باشد',
|
||||
DATE_END_MUST_BE_DATE_STRING = 'تاریخ پایان باید یک رشته تاریخ معتبر باشد',
|
||||
TO_ADDRESS_MUST_BE_STRING = 'آدرس گیرنده باید یک رشته باشد',
|
||||
MIN_SIZE_MUST_BE_NUMBER = 'حداقل اندازه باید یک عدد باشد',
|
||||
MIN_SIZE_MUST_BE_NON_NEGATIVE = 'حداقل اندازه نمیتواند منفی باشد',
|
||||
MAX_SIZE_MUST_BE_NUMBER = 'حداکثر اندازه باید یک عدد باشد',
|
||||
MAX_SIZE_MUST_BE_NON_NEGATIVE = 'حداکثر اندازه نمیتواند منفی باشد',
|
||||
ATTACHMENTS_FILTER_MUST_BE_BOOLEAN = 'فیلتر پیوستها باید بولین باشد',
|
||||
FLAGGED_FILTER_MUST_BE_BOOLEAN = 'فیلتر پیامهای علامتدار باید بولین باشد',
|
||||
UNSEEN_FILTER_MUST_BE_BOOLEAN = 'فیلتر پیامهای خواندهنشده باید بولین باشد',
|
||||
INCLUDE_HEADERS_MUST_BE_STRING = 'لیست هدرها باید یک رشته باشد',
|
||||
SEARCHABLE_FILTER_MUST_BE_BOOLEAN = 'فیلتر قابل جستجو باید بولین باشد',
|
||||
THREAD_COUNTERS_MUST_BE_BOOLEAN = 'شمارنده رشته گفتگو باید بولین باشد',
|
||||
ORDER_MUST_BE_VALID = 'ترتیب باید یکی از مقادیر asc یا desc باشد',
|
||||
NEXT_CURSOR_MUST_BE_STRING = 'نشانگر صفحه بعد باید یک رشته باشد',
|
||||
PREVIOUS_CURSOR_MUST_BE_STRING = 'نشانگر صفحه قبل باید یک رشته باشد',
|
||||
|
||||
RECIPIENT_NAME_MUST_BE_STRING = 'نام گیرنده باید یک رشته باشد',
|
||||
RECIPIENT_ADDRESS_REQUIRED = 'آدرس گیرنده مورد نیاز است',
|
||||
RECIPIENT_ADDRESS_MUST_BE_EMAIL = 'آدرس گیرنده باید یک ایمیل معتبر باشد',
|
||||
HEADER_KEY_REQUIRED = 'کلید هدر مورد نیاز است',
|
||||
HEADER_KEY_MUST_BE_STRING = 'کلید هدر باید یک رشته باشد',
|
||||
HEADER_VALUE_REQUIRED = 'مقدار هدر مورد نیاز است',
|
||||
HEADER_VALUE_MUST_BE_STRING = 'مقدار هدر باید یک رشته باشد',
|
||||
ATTACHMENT_FILENAME_MUST_BE_STRING = 'نام فایل پیوست باید یک رشته باشد',
|
||||
ATTACHMENT_CONTENT_TYPE_MUST_BE_STRING = 'نوع محتوای پیوست باید یک رشته باشد',
|
||||
ATTACHMENT_ENCODING_MUST_BE_STRING = 'کدگذاری پیوست باید یک رشته باشد',
|
||||
ATTACHMENT_CONTENT_TRANSFER_ENCODING_MUST_BE_STRING = 'کدگذاری انتقال محتوای پیوست باید یک رشته باشد',
|
||||
ATTACHMENT_CONTENT_DISPOSITION_INVALID = 'نحوه نمایش پیوست باید inline یا attachment باشد',
|
||||
ATTACHMENT_CONTENT_REQUIRED = 'محتوای پیوست مورد نیاز است',
|
||||
ATTACHMENT_CONTENT_MUST_BE_STRING = 'محتوای پیوست باید یک رشته باشد',
|
||||
ATTACHMENT_CID_MUST_BE_STRING = 'شناسه محتوای پیوست باید یک رشته باشد',
|
||||
DRAFT_MAILBOX_REQUIRED = 'شناسه صندوق پیشنویس مورد نیاز است',
|
||||
DRAFT_MAILBOX_MUST_BE_STRING = 'شناسه صندوق پیشنویس باید یک رشته باشد',
|
||||
DRAFT_ID_REQUIRED = 'شناسه پیشنویس مورد نیاز است',
|
||||
DRAFT_ID_MUST_BE_NUMBER = 'شناسه پیشنویس باید یک عدد باشد',
|
||||
ENVELOPE_FROM_REQUIRED = 'آدرس فرستنده در envelope مورد نیاز است',
|
||||
ENVELOPE_TO_REQUIRED = 'آدرس گیرنده در envelope مورد نیاز است',
|
||||
ENVELOPE_TO_MUST_BE_ARRAY = 'آدرس گیرنده در envelope باید یک آرایه باشد',
|
||||
MAILBOX_MUST_BE_STRING = 'شناسه صندوق باید یک رشته باشد',
|
||||
REPLY_TO_MUST_BE_VALID = 'آدرس پاسخ باید معتبر باشد',
|
||||
TO_ADDRESSES_REQUIRED = 'آدرسهای گیرنده مورد نیاز است',
|
||||
TO_ADDRESSES_MUST_BE_ARRAY = 'آدرسهای گیرنده باید یک آرایه باشد',
|
||||
CC_ADDRESSES_MUST_BE_ARRAY = 'آدرسهای کپی کربن باید یک آرایه باشد',
|
||||
BCC_ADDRESSES_MUST_BE_ARRAY = 'آدرسهای کپی مخفی باید یک آرایه باشد',
|
||||
HEADERS_MUST_BE_ARRAY = 'هدرهای سفارشی باید یک آرایه باشد',
|
||||
SUBJECT_MUST_BE_STRING = 'موضوع ایمیل باید یک رشته باشد',
|
||||
TEXT_CONTENT_MUST_BE_STRING = 'محتوای متنی باید یک رشته باشد',
|
||||
HTML_CONTENT_MUST_BE_STRING = 'محتوای HTML باید یک رشته باشد',
|
||||
ATTACHMENTS_MUST_BE_ARRAY = 'پیوستها باید یک آرایه باشد',
|
||||
SESSION_ID_MUST_BE_STRING = 'شناسه جلسه باید یک رشته باشد',
|
||||
IP_ADDRESS_MUST_BE_STRING = 'آدرس IP باید یک رشته باشد',
|
||||
IS_DRAFT_MUST_BE_BOOLEAN = 'وضعیت پیشنویس باید بولین باشد',
|
||||
SEND_TIME_MUST_BE_DATE = 'زمان ارسال باید یک تاریخ معتبر باشد',
|
||||
UPLOAD_ONLY_MUST_BE_BOOLEAN = 'حالت فقط آپلود باید بولین باشد',
|
||||
ENVELOPE_MUST_BE_VALID = 'envelope باید معتبر باشد',
|
||||
|
||||
// Message operations
|
||||
MESSAGE_MARKED_AS_SEEN_SUCCESSFULLY = 'پیام با موفقیت به عنوان خوانده شده علامت گذاری شد',
|
||||
ALL_MESSAGES_MARKED_AS_READ_SUCCESSFULLY = 'تمام پیام ها با موفقیت به عنوان خوانده شده علامت گذاری شدند',
|
||||
MESSAGE_MARK_AS_SEEN_FAILED = 'علامت گذاری پیام با خطا مواجه شد',
|
||||
SENT_MESSAGES_RETRIEVED_SUCCESSFULLY = 'پیام های ارسالی با موفقیت دریافت شد',
|
||||
SENT_MESSAGES_RETRIEVAL_FAILED = 'دریافت پیام های ارسالی با خطا مواجه شد',
|
||||
TRASH_MESSAGES_RETRIEVED_SUCCESSFULLY = 'پیام های حذف شده با موفقیت دریافت شد',
|
||||
TRASH_MESSAGES_RETRIEVAL_FAILED = 'دریافت پیام های حذف شده با خطا مواجه شد',
|
||||
DRAFT_UPDATED_SUCCESSFULLY = 'پیش نویس با موفقیت به روز رسانی شد',
|
||||
DRAFT_SENT_SUCCESSFULLY = 'پیش نویس با موفقیت ارسال شد',
|
||||
DRAFT_DELETED_SUCCESSFULLY = 'پیش نویس با موفقیت حذف شد',
|
||||
MESSAGE_MOVED_TO_ARCHIVE_SUCCESSFULLY = 'پیام با موفقیت به آرشیو منتقل شد',
|
||||
MESSAGE_MOVED_TO_FAVORITE_SUCCESSFULLY = 'پیام با موفقیت به علاقه مندی ها منتقل شد',
|
||||
MESSAGE_MOVED_TO_TRASH_SUCCESSFULLY = 'پیام با موفقیت به سطل زباله منتقل شد',
|
||||
MESSAGE_MOVED_TO_JUNK_SUCCESSFULLY = 'پیام با موفقیت به جانک منتقل شد',
|
||||
MESSAGE_MOVED_TO_INBOX_FROM_ARCHIVE_SUCCESSFULLY = 'پیام با موفقیت از آرشیو به صندوق ورودی منتقل شد',
|
||||
MESSAGE_MOVED_TO_INBOX_FROM_FAVORITE_SUCCESSFULLY = 'پیام با موفقیت از علاقه مندی ها به صندوق ورودی منتقل شد',
|
||||
MESSAGE_MOVED_TO_INBOX_FROM_TRASH_SUCCESSFULLY = 'پیام با موفقیت از سطل زباله به صندوق ورودی منتقل شد',
|
||||
MESSAGE_MOVED_TO_INBOX_FROM_JUNK_SUCCESSFULLY = 'پیام با موفقیت از جانک به صندوق ورودی منتقل شد',
|
||||
MESSAGE_NOT_FOUND = 'پیام یافت نشد',
|
||||
|
||||
// Bulk action messages
|
||||
BULK_ACTION_COMPLETED_SUCCESSFULLY = '[count] پیام با موفقیت [action] شد',
|
||||
BULK_ACTION_PARTIALLY_COMPLETED = '[successful] از [total] پیام [action] شد. [failed] پیام با خطا مواجه شد',
|
||||
BULK_ACTION_FAILED = 'هیچ پیامی [action] نشد. تمام [total] تلاش ناموفق بود',
|
||||
|
||||
// Bulk action display names
|
||||
BULK_ACTION_SEEN = 'خوانده شده علامتگذاری',
|
||||
BULK_ACTION_DELETE = 'حذف',
|
||||
BULK_ACTION_ARCHIVE = 'آرشیو',
|
||||
BULK_ACTION_UNARCHIVE = 'از آرشیو خارج',
|
||||
BULK_ACTION_FAVORITE = 'به علاقه مندی ها منتقل',
|
||||
BULK_ACTION_UNFAVORITE = 'از علاقه مندی ها حذف',
|
||||
BULK_ACTION_JUNK = 'به جانک منتقل',
|
||||
BULK_ACTION_NOTJUNK = 'از جانک از حذف',
|
||||
BULK_ACTION_TRASH = 'به سطل زباله منتقل',
|
||||
BULK_ACTION_RESTORE = 'از سطل زباله بازیابی',
|
||||
BULK_ACTION_PROCESSED = 'پردازش',
|
||||
USER_NOT_FOUND = 'کاربر یافت نشد',
|
||||
PRIORITY_MUST_BE_ONE_OF_HIGH_NORMAL_LOW = 'اولویت باید یکی از مقادیر high, normal, low باشد',
|
||||
SUBJECT_REQUIRED = 'موضوع ایمیل مورد نیاز است',
|
||||
ALL_MESSAGES_DELETED_SUCCESSFULLY = 'همه پیام ها با موفقیت حذف شدند',
|
||||
MAILBOX_ID_MUST_BE_MONGO_ID = 'شناسه میل باکس ایمیل باید یک آی دی معتبر باشد',
|
||||
MESSAGE_MARKED_AS_UNSEEN_SUCCESSFULLY = 'پیام با موفقیت به عنوان خوانده نشده علامت گذاری شد',
|
||||
MESSAGE_MARK_AS_UNSEEN_FAILED = 'علامت گذاری پیام به عنوان خوانده نشده با خطا مواجه شد',
|
||||
ATTACHMENT_ID_MUST_BE_STRING = 'شناسه پیوست باید یک رشته باشد',
|
||||
IS_FORWARD_MUST_BE_BOOLEAN = 'IS_FORWARD_MUST_BE_BOOLEAN',
|
||||
|
||||
// Favorite/Star messages (Gmail-like behavior)
|
||||
MESSAGE_MARKED_AS_FAVORITE_SUCCESSFULLY = 'پیام با موفقیت به عنوان مورد علاقه علامت گذاری شد',
|
||||
MESSAGE_REMOVED_FROM_FAVORITE_SUCCESSFULLY = 'پیام با موفقیت از مورد علاقه حذف شد',
|
||||
TRASH_EMPTYED_SUCCESSFULLY = 'سطل زباله با موفقیت خالی شد',
|
||||
SPAM_EMPTYED_SUCCESSFULLY = 'همه پیام های اسپم با موفقیت حذف شدند',
|
||||
SAVE_DRAFT_SUCCESS = 'پیش نویس با موفقیت ذخیره شد',
|
||||
HTML_CONTENT_REQUIRED = 'محتوای HTML مورد نیاز است',
|
||||
TEXT_CONTENT_REQUIRED = 'TEXT_CONTENT_REQUIRED',
|
||||
}
|
||||
|
||||
export const enum WebSocketMessage {
|
||||
// Connection Messages
|
||||
WS_CONNECTION_ESTABLISHED = 'اتصال وب سوکت با موفقیت برقرار شد',
|
||||
WS_CONNECTION_FAILED = 'اتصال وب سوکت ناموفق بود',
|
||||
WS_AUTHENTICATION_REQUIRED = 'احراز هویت وب سوکت مورد نیاز است',
|
||||
WS_AUTHENTICATION_FAILED = 'احراز هویت وب سوکت ناموفق بود',
|
||||
WS_AUTHENTICATION_SUCCESS = 'احراز هویت وب سوکت با موفقیت انجام شد',
|
||||
WS_INVALID_TOKEN = 'توکن وب سوکت نامعتبر است',
|
||||
WS_TOKEN_EXPIRED = 'توکن وب سوکت منقضی شده است',
|
||||
|
||||
// Room Management Messages
|
||||
JOINED_ROOM_SUCCESS = 'با موفقیت به اتاق متصل شدید',
|
||||
LEFT_ROOM_SUCCESS = 'با موفقیت از اتاق خارج شدید',
|
||||
ROOM_NOT_FOUND = 'اتاق یافت نشد',
|
||||
UNAUTHORIZED_ROOM_ACCESS = 'دسترسی غیرمجاز به اتاق',
|
||||
|
||||
// Session Management Messages
|
||||
WS_SESSION_CREATED = 'جلسه وب سوکت ایجاد شد',
|
||||
WS_SESSION_JOINED = 'به جلسه وب سوکت پیوستید',
|
||||
WS_SESSION_LEFT = 'از جلسه وب سوکت خارج شدید',
|
||||
WS_SESSION_EXPIRED = 'جلسه وب سوکت منقضی شده است',
|
||||
WS_SESSION_NOT_FOUND = 'جلسه وب سوکت یافت نشد',
|
||||
|
||||
// Error Messages
|
||||
WS_CONNECTION_ERROR = 'خطا در اتصال وب سوکت',
|
||||
INVALID_EVENT = 'رویداد نامعتبر',
|
||||
INVALID_DATA = 'داده نامعتبر',
|
||||
WS_RATE_LIMIT_EXCEEDED = 'تعداد درخواستهای وب سوکت از حد مجاز بیشتر است',
|
||||
INTERNAL_ERROR = 'خطای داخلی سرور',
|
||||
|
||||
// Notification Messages
|
||||
NEW_MESSAGE_NOTIFICATION = 'پیام جدید دریافت شد',
|
||||
MESSAGE_STATUS_UPDATED = 'وضعیت پیام بهروزرسانی شد',
|
||||
MESSAGE_MOVED_NOTIFICATION = 'پیام جابجا شد',
|
||||
MESSAGE_DELETED_NOTIFICATION = 'پیام حذف شد',
|
||||
|
||||
// General Messages
|
||||
OPERATION_SUCCESS = 'عملیات با موفقیت انجام شد',
|
||||
OPERATION_FAILED = 'عملیات ناموفق بود',
|
||||
PERMISSION_DENIED = 'مجوز دسترسی ندارید',
|
||||
RESOURCE_NOT_FOUND = 'منبع یافت نشد',
|
||||
|
||||
// Authentication errors
|
||||
AUTHENTICATION_REQUIRED = 'احراز هویت ضروری است',
|
||||
INVALID_TOKEN = 'توکن احراز هویت نامعتبر است',
|
||||
TOKEN_EXPIRED = 'توکن منقضی شده است',
|
||||
UNAUTHORIZED_ACCESS = 'دسترسی غیرمجاز',
|
||||
USER_NOT_AUTHENTICATED = 'کاربر احراز هویت نشده است',
|
||||
|
||||
// Connection errors
|
||||
CONNECTION_FAILED = 'اتصال برقرار نشد',
|
||||
WEBSOCKET_ERROR = 'خطا در ارتباط WebSocket',
|
||||
CONNECTION_TIMEOUT = 'زمان اتصال به پایان رسید',
|
||||
CONNECTION_REFUSED = 'اتصال رد شد',
|
||||
|
||||
// Session errors
|
||||
SESSION_NOT_FOUND = 'جلسه چت یافت نشد',
|
||||
SESSION_CREATION_FAILED = 'ایجاد جلسه چت با شکست مواجه شد',
|
||||
SESSION_ACCESS_DENIED = 'دسترسی به جلسه چت مجاز نیست',
|
||||
SESSION_EXPIRED = 'جلسه چت منقضی شده است',
|
||||
SESSION_ALREADY_EXISTS = 'جلسه چت قبلاً وجود دارد',
|
||||
|
||||
// Message errors
|
||||
MESSAGE_TOO_LONG = 'پیام از حداکثر طول مجاز تجاوز کرده است',
|
||||
MESSAGE_EMPTY = 'پیام نمیتواند خالی باشد',
|
||||
MESSAGE_SEND_FAILED = 'ارسال پیام با شکست مواجه شد',
|
||||
INVALID_MESSAGE_FORMAT = 'فرمت پیام نامعتبر است',
|
||||
|
||||
// Rate limiting
|
||||
RATE_LIMIT_EXCEEDED = 'تعداد پیامهای ارسالی بیش از حد مجاز است',
|
||||
TOO_MANY_CONNECTIONS = 'تعداد اتصالات بیش از حد مجاز است',
|
||||
|
||||
// Service errors
|
||||
LLM_SERVICE_ERROR = 'سرویس هوش مصنوعی موقتاً در دسترس نیست',
|
||||
SERVICE_UNAVAILABLE = 'سرویس موقتاً در دسترس نیست',
|
||||
INTERNAL_SERVER_ERROR = '.خطای داخلی سرور',
|
||||
|
||||
// Validation errors
|
||||
INVALID_SESSION_ID = 'شناسه جلسه نامعتبر است',
|
||||
INVALID_USER_ID = 'شناسه کاربر نامعتبر است',
|
||||
INVALID_MESSAGE_ID = 'شناسه پیام نامعتبر است',
|
||||
REQUIRED_FIELD_MISSING = 'فیلد ضروری موجود نیست',
|
||||
|
||||
// Success messages
|
||||
AUTHENTICATED = 'احراز هویت موفقیتآمیز',
|
||||
SESSION_CREATED = 'جلسه چت با موفقیت ایجاد شد',
|
||||
CHAT_JOINED = 'با موفقیت به چت متصل شدید',
|
||||
MESSAGE_SENT = 'پیام ارسال شد',
|
||||
CONNECTION_ESTABLISHED = 'اتصال برقرار شد',
|
||||
}
|
||||
|
||||
export const enum SmsMessage {
|
||||
SEND_SMS_ERROR = 'خطا در ارسال پیامک',
|
||||
}
|
||||
|
||||
export const enum RestMessage {
|
||||
NOT_FOUND = 'کسب و کار یافت نشد',
|
||||
BUSINESS_ID_REQUIRED = 'شناسه کسب و کار مورد نیاز است',
|
||||
SLUG_REQUIRED = 'اسلاگ مورد نیاز است',
|
||||
SLUG_MUST_BE_STRING = 'اسلاگ باید یک رشته باشد',
|
||||
DOMAIN_INVALID = 'دامنه وارد شده معتبر نیست',
|
||||
DOMAIN_UPDATED = 'دامنه با موفقیت بهروزرسانی شد',
|
||||
DOMAIN_VERIFICATION_INITIATED = 'فرآیند تایید دامنه آغاز شد',
|
||||
DOMAIN_VERIFICATION_FAILED = 'تایید دامنه با خطا مواجه شد',
|
||||
DOMAIN_VERIFICATION_SUCCESS = 'دامنه با موفقیت تایید شد',
|
||||
DOMAIN_VERIFICATION_METHOD_INVALID = 'روش تایید دامنه نامعتبر است',
|
||||
DOMAIN_ALREADY_VERIFIED = 'این دامنه قبلا تایید شده است',
|
||||
DOMAIN_REQUIRED = 'دامنه مورد نیاز است',
|
||||
DOMAIN_MUST_BE_STRING = 'دامنه باید یک رشته باشد',
|
||||
STAFF_NOT_FOUND = 'کاربر ادمین یافت نشد',
|
||||
ZARINPAL_MERCHANT_ID_REQUIRED = 'شناسه مرچنت زرین پال مورد نیاز است',
|
||||
ZARINPAL_MERCHANT_ID_STRING = 'شناسه مرچنت زرین پال باید یک رشته باشد',
|
||||
LOGO_URL_REQUIRED = 'آدرس تصویر لوگو مورد نیاز است',
|
||||
LOGO_URL_STRING = 'آدرس تصویر لوگو باید یک رشته باشد',
|
||||
LOGO_URL_INVALID = 'آدرس تصویر لوگو معتبر نیست',
|
||||
BUSINESS_SETTINGS_UPDATED = 'تنظیمات کسب و کار با موفقیت به روز رسانی شد',
|
||||
NAME_REQUIRED = 'نام کسب و کار مورد نیاز است',
|
||||
NAME_STRING = 'نام کسب و کار باید یک رشته باشد',
|
||||
DOMAIN_CONNECTED = 'دامنه با موفقیت متصل شد',
|
||||
DOMAIN_NOT_CONNECTED = 'دامنه به سرور ما متصل نشد',
|
||||
DOMAIN_NOT_FOUND = 'دامنه یافت نشد',
|
||||
DOMAIN_VERIFICATION_TOKEN_REQUIRED = 'توکن تایید دامنه مورد نیاز است',
|
||||
INSUFFICIENT_QUOTA = 'حجم شما برای ساخت ایمیل کافی نمی باشد، لطفا حجم را افزایش دهید',
|
||||
QUOTA_DOWNGRADE_NOT_ALLOWED = 'کاهش حجم ایمیل مجاز نیست، فقط میتوانید حجم را افزایش دهید',
|
||||
QUOTA_AMOUNT_REQUIRED = 'مقدار حجم مورد نیاز است',
|
||||
QUOTA_AMOUNT_MUST_BE_NUMBER = 'مقدار حجم باید یک عدد باشد',
|
||||
QUOTA_AMOUNT_MUST_BE_POSITIVE = 'مقدار حجم باید مثبت باشد',
|
||||
CALLBACK_URL_MUST_BE_STRING = 'آدرس بازگشت باید یک رشته باشد',
|
||||
CALLBACK_URL_INVALID = 'آدرس بازگشت معتبر نیست',
|
||||
PURCHASE_DESCRIPTION_MUST_BE_STRING = 'توضیحات خرید باید یک رشته باشد',
|
||||
QUOTA_PURCHASE_SUCCESS = 'درخواست خرید حجم با موفقیت ثبت شد',
|
||||
QUOTA_PURCHASE_FAILED = 'خرید حجم با خطا مواجه شد',
|
||||
PAYMENT_GATEWAY_ERROR = 'خطا در اتصال به درگاه پرداخت',
|
||||
QUOTA_UPDATED = 'حجم ایمیل با موفقیت به روز شد',
|
||||
USER_DOES_NOT_HAVE_ACCESS_TO_SERVICE = 'کاربر دسترسی به این سرویس را ندارد',
|
||||
}
|
||||
|
||||
export const enum DomainMessage {
|
||||
// Domain Ownership & Verification
|
||||
NOT_BELONG_TO_BUSINESS = 'دامنه به این کسب و کار تعلق ندارد',
|
||||
NOT_VERIFIED = 'دامنه باید تایید شده باشد',
|
||||
DOMAIN_NOT_FOUND = 'دامنه یافت نشد',
|
||||
DOMAIN_ALREADY_EXISTS = 'دامنه [name] قبلا ثبت شده است',
|
||||
DOMAIN_DELETED_SUCCESSFULLY = 'دامنه با موفقیت حذف شد',
|
||||
VERIFICATION_NOT_FOUND = 'تایید دامنه یافت نشد',
|
||||
NO_DOMAIN_FOUND = 'دامنه ای یافت نشد',
|
||||
DOMAIN_CHECKED = 'دامنه با موفقیت بررسی شد',
|
||||
|
||||
// Domain Creation & Setup
|
||||
DOMAIN_CREATED_WITH_RECORDS = 'دامنه [name] با موفقیت ایجاد شد و تمام رکوردهای مورد نیاز تولید گردید',
|
||||
ALL_REQUIRED_RECORDS_GENERATED = 'تمام رکوردهای مورد نیاز (MX, SPF, DMARC, DKIM) به طور خودکار برای شما تولید شدهاند',
|
||||
ESTIMATED_PROPAGATION_TIME = 'تغییرات DNS معمولاً ۱۵ دقیقه تا ۴۸ ساعت در سراسر جهان منتشر میشود',
|
||||
|
||||
// DNS Records Instructions
|
||||
ADD_MX_RECORD = 'یک رکورد MX با نام [name] که به [value] با اولویت [priority] اشاره کند اضافه کنید',
|
||||
ADD_TXT_RECORD = 'یک رکورد TXT با نام [name] و مقدار [value] اضافه کنید',
|
||||
ADD_DKIM_RECORD = 'یک رکورد TXT با نام [name] و مقدار [value] اضافه کنید (کلید عمومی DKIM)',
|
||||
ADD_DMARC_RECORD = 'یک رکورد TXT با نام [name] و مقدار [value] اضافه کنید (سیاست DMARC)',
|
||||
ADD_CNAME_RECORD = 'یک رکورد CNAME با نام [name] که به [value] اشاره کند اضافه کنید',
|
||||
ADD_GENERIC_RECORD = 'یک رکورد [type] با نام [name] و مقدار [value] اضافه کنید',
|
||||
|
||||
// Domain Setup Steps
|
||||
STEP_LOGIN_DNS_PANEL = 'وارد پنل مدیریت DNS ثبت کننده دامنه خود شوید',
|
||||
STEP_ADD_ALL_RECORDS = 'تمام رکوردهای DNS مورد نیاز لیست شده در بالا را به زون DNS دامنه خود اضافه کنید',
|
||||
STEP_INCLUDE_ALL_TYPES = 'مطمئن شوید که رکوردهای MX، SPF، DMARC و DKIM را برای عملکرد کامل ایمیل شامل کردهاید',
|
||||
STEP_WAIT_PROPAGATION = 'منتظر انتشار DNS بمانید (معمولاً ۱۵ دقیقه تا ۴۸ ساعت)',
|
||||
STEP_USE_CHECK_ENDPOINT = "از نقطه پایانی 'بررسی DNS' برای تایید تنظیم صحیح رکوردهای خود استفاده کنید",
|
||||
STEP_DOMAIN_READY = 'پس از تایید، دامنه شما برای سرویسهای ایمیل آماده خواهد بود!',
|
||||
|
||||
// Status Messages
|
||||
RECORDS_PENDING_VERIFICATION = '[count] رکورد DNS هنوز در انتظار تایید هستند',
|
||||
ALL_REQUIRED_RECORDS_MUST_BE_CONFIGURED = 'تمام [count] رکورد مورد نیاز باید برای کار درست ایمیل تنظیم شوند',
|
||||
DOMAIN_FULLY_VERIFIED = 'دامنه شما به طور کامل تایید شده و برای ایمیل آماده است!',
|
||||
EMAIL_ACCOUNTS_READY = 'اکنون میتوانید حسابهای ایمیل ایجاد کرده و شروع به ارسال/دریافت ایمیل کنید',
|
||||
|
||||
// Verification Status
|
||||
DOMAIN_VERIFICATION_INITIATED = 'فرآیند تایید دامنه آغاز شد',
|
||||
DOMAIN_VERIFICATION_FAILED = 'تایید دامنه با خطا مواجه شد',
|
||||
DOMAIN_VERIFICATION_SUCCESS = 'دامنه با موفقیت تایید شد',
|
||||
DOMAIN_VERIFICATION_PENDING = 'تایید دامنه در انتظار است',
|
||||
|
||||
// DNS Record Status
|
||||
DNS_RECORD_VERIFIED = 'رکورد DNS تایید شد',
|
||||
DNS_RECORD_FAILED = 'رکورد DNS تایید نشد',
|
||||
DNS_RECORD_NOT_FOUND_OR_MISMATCH = 'رکورد DNS یافت نشد یا مقدار مطابقت ندارد',
|
||||
|
||||
// DKIM Messages
|
||||
DKIM_ENABLED_AUTOMATICALLY = 'DKIM به طور خودکار برای دامنه [name] فعال شد',
|
||||
DKIM_FAILED_TO_CREATE = 'ایجاد DKIM برای دامنه [name] ناموفق بود',
|
||||
DKIM_ENABLED_SUCCESSFULLY = 'DKIM برای دامنه [name] با موفقیت فعال شد',
|
||||
|
||||
// Error Messages
|
||||
FAILED_TO_VERIFY_DOMAIN = 'تایید دامنه [name] ناموفق بود',
|
||||
FAILED_TO_SETUP_MAIL_SERVER = 'راهاندازی دامنه [name] در سرور ایمیل ناموفق بود',
|
||||
DOMAIN_CREATION_FAILED = 'ایجاد دامنه ناموفق بود',
|
||||
DNS_VERIFICATION_ATTEMPTS_EXCEEDED = 'تعداد تلاشهای تایید DNS از حد مجاز بیشتر شد',
|
||||
|
||||
// Service Messages
|
||||
DOMAIN_UPDATED_SUCCESSFULLY = 'دامنه بروزرسانی شد',
|
||||
VERIFICATION_TOKEN_PREFIX = 'توکن تایید: [token]',
|
||||
RECORD_NEEDS_FIXING = 'رکورد [type] برای [name] نیاز به اصلاح دارد: [error]',
|
||||
RECORD_PENDING_VERIFICATION_DETAIL = 'رکورد [type] برای [name] هنوز در انتظار تایید است. لطفا مطمئن شوید که انتشار DNS کامل شده است.',
|
||||
RECORD_DESCRIPTION_EMAIL_FUNCTIONALITY = 'رکورد [type] برای عملکرد ایمیل',
|
||||
BUSINESS_ALREADY_HAS_DOMAIN = 'این کسب و کار قبلا دامنه ای دارد',
|
||||
CAN_NOT_USE_THIS_DOMAIN = 'این دامنه نمیتواند ثبت شود',
|
||||
}
|
||||
|
||||
export const enum MailServerMessage {
|
||||
FAILED_TO_CREATE_ACCOUNT = 'خطا در ایجاد ایمیل',
|
||||
FAILED_TO_CREATE_DKIM_KEY = 'خطا در ایجاد کلید DKIM',
|
||||
}
|
||||
|
||||
export const enum DnsRecordMessage {
|
||||
DNS_RECORD_NOT_FOUND = 'رکورد DNS یافت نشد',
|
||||
DNS_RECORD_DELETED = 'رکورد DNS با موفقیت حذف شد',
|
||||
}
|
||||
|
||||
export const enum RoleMessage {
|
||||
NOT_FOUND = 'نقش یافت نشد',
|
||||
}
|
||||
|
||||
export const enum SignatureMessage {
|
||||
NAME_NOT_EMPTY = 'نام امضاء نمیتواند خالی باشد',
|
||||
NAME_MAX_LENGTH = 'نام امضاء نمیتواند بیشتر از حداکثر طول مجاز باشد',
|
||||
NAME_STRING = 'نام امضاء باید یک رشته باشد',
|
||||
TEXT_CONTENT_NOT_EMPTY = 'محتوای متنی امضاء نمیتواند خالی باشد',
|
||||
TEXT_CONTENT_STRING = 'محتوای متنی امضاء باید یک رشته باشد',
|
||||
TEXT_CONTENT_MAX_LENGTH = 'محتوای متنی امضاء نمیتواند بیشتر از حداکثر طول مجاز باشد',
|
||||
IS_ACTIVE_NOT_EMPTY = 'وضعیت فعال بودن نمیتواند خالی باشد',
|
||||
IS_ACTIVE_BOOLEAN = 'وضعیت فعال بودن باید بولین باشد',
|
||||
IS_DEFAULT_NOT_EMPTY = 'وضعیت پیش فرض نمیتواند خالی باشد',
|
||||
IS_DEFAULT_BOOLEAN = 'وضعیت پیش فرض باید بولین باشد',
|
||||
CREATED = 'امضاء با موفقیت ایجاد شد',
|
||||
NOT_FOUND = 'امضاء یافت نشد',
|
||||
DELETED = 'امضاء با موفقیت حذف شد',
|
||||
TOGGLE_ACTIVE = 'وضعیت امضاء با موفقیت تغییر کرد',
|
||||
}
|
||||
|
||||
export const enum TemplateMessage {
|
||||
TEMPLATE_NOT_FOUND = 'قالب یافت نشد',
|
||||
TEMPLATE_CREATED_SUCCESSFULLY = 'قالب با موفقیت ایجاد شد',
|
||||
TEMPLATE_UPDATED_SUCCESSFULLY = 'قالب با موفقیت به روزرسانی شد',
|
||||
TEMPLATE_DELETED_SUCCESSFULLY = 'قالب با موفقیت حذف شد',
|
||||
TEMPLATE_RETRIEVED_SUCCESSFULLY = 'قالب با موفقیت دریافت شد',
|
||||
TEMPLATES_LISTED_SUCCESSFULLY = 'لیست قالب ها با موفقیت دریافت شد',
|
||||
TEMPLATE_NAME_REQUIRED = 'نام قالب الزامی است',
|
||||
TEMPLATE_NAME_STRING = 'نام قالب باید یک رشته باشد',
|
||||
TEMPLATE_NAME_MAX_LENGTH = 'نام قالب نمیتواند بیشتر از ۲۵۵ کاراکتر باشد',
|
||||
TEMPLATE_STRUCTURE_REQUIRED = 'ساختار قالب الزامی است',
|
||||
TEMPLATE_STRUCTURE_VALID = 'ساختار قالب باید معتبر باشد',
|
||||
TEMPLATE_RAW_HTML_STRING = 'HTML خام باید یک رشته باشد',
|
||||
TEMPLATE_BUSINESS_ID_REQUIRED = 'شناسه کسب و کار الزامی است',
|
||||
TEMPLATE_BUSINESS_ID_UUID = 'شناسه کسب و کار باید یک UUID معتبر باشد',
|
||||
TEMPLATE_ID_REQUIRED = 'شناسه قالب الزامی است',
|
||||
TEMPLATE_ID_UUID = 'شناسه قالب باید یک UUID معتبر باشد',
|
||||
TEMPLATE_ACCESS_DENIED = 'شما دسترسی به این قالب را ندارید',
|
||||
TEMPLATE_BUSINESS_NOT_FOUND = 'کسب و کار مالک قالب یافت نشد',
|
||||
SEARCH_STRING = 'نام برای جستجو باید یک رشته باشد',
|
||||
TEMPLATE_SELECTED_SUCCESSFULLY = 'وضعیت قالب با موفقیت تغییر کرد',
|
||||
TEMPLATE_THUMBNAIL_URL_VALID = 'آدرس تصویر قالب باید یک آدرس معتبر باشد',
|
||||
TEMPLATE_RAW_HTML_REQUIRED = 'HTML خام قالب الزامی است',
|
||||
}
|
||||
|
||||
export const enum NotificationMessage {
|
||||
TITLE_IS_REQUIRED = 'عنوان اعلان الزامی است',
|
||||
TITLE_STRING = 'عنوان اعلان باید یک رشته باشد',
|
||||
MESSAGE_IS_REQUIRED = 'متن اعلان الزامی است',
|
||||
MESSAGE_STRING = 'متن اعلان باید یک رشته باشد',
|
||||
USERID_IS_REQUIRED = 'شناسه کاربر الزامی است',
|
||||
USERID_IS_STRING = 'شناسه کاربر باید یک رشته باشد',
|
||||
USERID_IS_UUID = 'شناسه کاربر باید یک UUID معتبر باشد',
|
||||
TYPE_IS_REQUIRED = 'نوع اعلان الزامی است',
|
||||
TYPE_ENUM = 'نوع اعلان باید یک enum معتبر باشد',
|
||||
NOTIFICATION_NOT_FOUND_OR_ACCESS_DENIED = 'اعلان یافت نشد یا دسترسی آن را ندارید',
|
||||
LOGIN_MESSAGE = 'ورود با موفقیت انجام شد در تاریخ [loginDate]',
|
||||
LOGIN = 'ورود',
|
||||
NEW_EMAIL = 'ایمیل جدید',
|
||||
NEW_EMAIL_MESSAGE = 'یک ایمیل جدید با موضوع [subject] دریافت شد',
|
||||
CHANGE_PASSWORD_MESSAGE = 'رمز عبور شما با موفقیت تغییر کرد',
|
||||
CHANGE_PASSWORD = 'تغییر رمز عبور',
|
||||
NOT_FOUND = 'اعلان یافت نشد',
|
||||
READ_SUCCESS = 'اعلان با موفقیت خوانده شد',
|
||||
ORDER_CREATED = 'سفارش جدید ایجاد شد',
|
||||
ORDER_STATUS_CHANGED = 'وضعیت سفارش تغییر کرد',
|
||||
PAYMENT_SUCCESS = 'پرداخت با موفقیت انجام شد',
|
||||
PAGER_CREATED = 'پیج جدید ایجاد شد',
|
||||
}
|
||||
|
||||
export const enum SettingMessageEnum {
|
||||
SMS_MUST_BE_BOOLEAN = 'تنظیمات ارسال پیامک باید یک boolean باشد',
|
||||
EMAIL_MUST_BE_BOOLEAN = 'تنظیمات ارسال ایمیل باید یک boolean باشد',
|
||||
NOTIFICATION_NOT_FOUND_OR_ACCESS_DENIED = 'اعلان یافت نشد یا دسترسی آن را ندارید',
|
||||
}
|
||||
|
||||
export const enum AiMessage {
|
||||
NO_RESPONSE_FROM_AI_MODEL = 'خطا در دریافت پاسخ از مدل AI',
|
||||
MESSAGE_NOT_FOUND_OR_ACCESS_DENIED = 'ایمیل یافت نشد یا دسترسی آن را ندارید',
|
||||
EMAIL_CONTENT_IS_EMPTY_OR_COULD_NOT_BE_EXTRACTED = 'محتوای ایمیل خالی است یا قابل استخراج نیست',
|
||||
DESCRIPTION_IS_REQUIRED = 'شرح و هدف قالب الزامی است',
|
||||
DESCRIPTION_MUST_BE_A_STRING = 'شرح قالب باید یک رشته باشد',
|
||||
DESCRIPTION_MUST_BE_AT_LEAST_10_CHARACTERS = 'شرح قالب باید حداقل ۱۰ کاراکتر باشد',
|
||||
DESCRIPTION_MUST_BE_LESS_THAN_500_CHARACTERS = 'شرح قالب نمیتواند بیشتر از ۵۰۰ کاراکتر باشد',
|
||||
THEME_MUST_BE_A_VALID_VALUE = 'تم قالب باید یکی از مقادیر مجاز باشد',
|
||||
STYLE_MUST_BE_A_VALID_VALUE = 'سبک قالب باید یکی از مقادیر مجاز باشد',
|
||||
PURPOSE_MUST_BE_A_VALID_VALUE = 'هدف قالب باید یکی از مقادیر مجاز باشد',
|
||||
TEMPLATE_NAME_MUST_BE_A_STRING = 'نام قالب باید یک رشته باشد',
|
||||
TEMPLATE_NAME_MUST_BE_LESS_THAN_100_CHARACTERS = 'نام قالب نمیتواند بیشتر از ۱۰۰ کاراکتر باشد',
|
||||
PREFERRED_COLORS_MUST_BE_A_STRING = 'رنگهای ترجیحی باید یک رشته باشد',
|
||||
PREFERRED_COLORS_MUST_BE_LESS_THAN_200_CHARACTERS = 'رنگهای ترجیحی نمیتواند بیشتر از ۲۰۰ کاراکتر باشد',
|
||||
PREFERRED_COLORS_IS_REQUIRED = 'رنگهای ترجیحی الزامی است',
|
||||
}
|
||||
|
||||
export const enum TwoFactorMessage {
|
||||
TWO_FACTOR_SETUP_INITIATED = 'راهاندازی احراز هویت دو مرحلهای با موفقیت آغاز شد',
|
||||
TWO_FACTOR_ENABLED_SUCCESSFULLY = 'احراز هویت دو مرحلهای با موفقیت فعال شد',
|
||||
TWO_FACTOR_DISABLED_SUCCESSFULLY = 'احراز هویت دو مرحلهای با موفقیت غیرفعال شد',
|
||||
TWO_FACTOR_SETUP_FAILED = 'راهاندازی احراز هویت دو مرحلهای ناموفق بود',
|
||||
TWO_FACTOR_ENABLE_FAILED = 'فعالسازی احراز هویت دو مرحلهای ناموفق بود',
|
||||
TWO_FACTOR_TOKEN_VERIFIED_SUCCESSFULLY = 'کد احراز هویت دو مرحلهای با موفقیت تأیید شد',
|
||||
TWO_FACTOR_TOKEN_VERIFIED_FAILED = 'کد احراز هویت دو مرحلهای نامعتبر میباشد',
|
||||
TWO_FACTOR_NOT_ENABLED = 'احراز هویت دو مرحلهای فعال نیست',
|
||||
TWO_FACTOR_BACKUP_CODES_GENERATED_SUCCESSFULLY = 'کدهای پشتیبان با موفقیت تولید شدند',
|
||||
TWO_FACTOR_BACKUP_CODE_VERIFIED_SUCCESSFULLY = 'کد پشتیبان با موفقیت تأیید شد',
|
||||
TWO_FACTOR_BACKUP_CODE_VERIFIED_FAILED = 'کد پشتیبان نامعتبر است',
|
||||
TWO_FACTOR_TOKEN_REQUIRED = 'کد احراز هویت دو مرحلهای الزامی است',
|
||||
TWO_FACTOR_TOKEN_INVALID = 'کد احراز هویت دو مرحلهای نامعتبر است',
|
||||
}
|
||||
|
||||
export const enum CouponMessage {
|
||||
NOT_FOUND = 'کوپن یافت نشد',
|
||||
CODE_ALREADY_EXISTS = 'کد کوپن قبلاً ثبت شده است',
|
||||
END_DATE_MUST_BE_AFTER_START_DATE = 'تاریخ پایان باید بعد از تاریخ شروع باشد',
|
||||
PERCENTAGE_MUST_BE_BETWEEN_0_AND_100 = 'درصد تخفیف باید بین ۰ تا ۱۰۰ باشد',
|
||||
COUPON_INACTIVE = 'کوپن غیرفعال است',
|
||||
COUPON_NOT_STARTED = 'کوپن هنوز شروع نشده است',
|
||||
COUPON_EXPIRED = 'کوپن منقضی شده است',
|
||||
COUPON_MAX_USES_REACHED = 'حداکثر استفاده از کوپن به پایان رسیده است',
|
||||
MIN_ORDER_AMOUNT_NOT_MET = 'مبلغ سفارش کمتر از حداقل مجاز است',
|
||||
COUPON_CREATED = 'کوپن با موفقیت ایجاد شد',
|
||||
COUPON_UPDATED = 'کوپن با موفقیت بهروزرسانی شد',
|
||||
COUPON_DELETED = 'کوپن با موفقیت حذف شد',
|
||||
COUPON_VALID = 'کوپن معتبر است',
|
||||
COUPON_INVALID = 'کوپن نامعتبر است',
|
||||
COUPON_RESTRICTED_TO_USER = 'کوپن فقط برای کاربر مشخصی معتبر است',
|
||||
}
|
||||
|
||||
export const enum ReviewMessage {
|
||||
NOT_FOUND = 'نظر یافت نشد',
|
||||
ALREADY_COMMENTED = 'شما قبلاً برای این غذا نظر دادهاید',
|
||||
CAN_ONLY_UPDATE_OWN = 'شما فقط میتوانید نظرات خود را ویرایش کنید',
|
||||
CAN_ONLY_DELETE_OWN = 'شما فقط میتوانید نظرات خود را حذف کنید',
|
||||
RATING_REQUIRED = 'امتیاز الزامی است',
|
||||
RATING_INVALID = 'امتیاز باید بین ۱ تا ۵ باشد',
|
||||
COMMENT_CREATED = 'نظر با موفقیت ثبت شد',
|
||||
COMMENT_UPDATED = 'نظر با موفقیت بهروزرسانی شد',
|
||||
COMMENT_DELETED = 'نظر با موفقیت حذف شد',
|
||||
}
|
||||
|
||||
export const enum IconMessage {
|
||||
NOT_FOUND = 'آیکون یافت نشد',
|
||||
NOT_CREATED = 'ایجاد آیکون با خطا مواجه شد',
|
||||
NOT_UPDATED = 'بهروزرسانی آیکون با خطا مواجه شد',
|
||||
NOT_DELETED = 'حذف آیکون با خطا مواجه شد',
|
||||
}
|
||||
|
||||
export const enum GroupMessage {
|
||||
NOT_FOUND = 'گروه آیکون یافت نشد',
|
||||
NOT_CREATED = 'ایجاد گروه آیکون با خطا مواجه شد',
|
||||
NOT_UPDATED = 'بهروزرسانی گروه آیکون با خطا مواجه شد',
|
||||
NOT_DELETED = 'حذف گروه آیکون با خطا مواجه شد',
|
||||
}
|
||||
|
||||
export const enum OrderMessage {
|
||||
NOT_FOUND = 'سفارش یافت نشد',
|
||||
PAYMENT_METHOD_MISSING = 'روش پرداخت سفارش مشخص نشده است',
|
||||
INVALID_STATUS_TRANSITION = 'انتقال وضعیت نامعتبر است',
|
||||
CART_EMPTY = 'سبد خرید خالی است. لطفا قبل از ایجاد سفارش، آیتمهایی به سبد اضافه کنید',
|
||||
DELIVERY_METHOD_NOT_FOUND = 'روش ارسال یافت نشد',
|
||||
PAYMENT_METHOD_REQUIRED = 'روش پرداخت الزامی است. لطفا قبل از ایجاد سفارش، روش پرداخت را تنظیم کنید',
|
||||
USER_NOT_FOUND = 'کاربر یافت نشد',
|
||||
RESTAURANT_NOT_FOUND = 'رستوران یافت نشد',
|
||||
DELIVERY_NOT_FOUND = 'روش ارسال یافت نشد',
|
||||
MIN_ORDER_AMOUNT_NOT_MET = 'مبلغ سفارش کمتر از حداقل مجاز برای این روش ارسال است',
|
||||
TABLE_NUMBER_REQUIRED = 'شماره میز برای سفارش در محل الزامی است',
|
||||
ADDRESS_REQUIRED = 'آدرس الزامی است. لطفا قبل از ایجاد سفارش، آدرس تحویل را تنظیم کنید',
|
||||
CAR_ADDRESS_REQUIRED = 'آدرس خودرو الزامی است. لطفا قبل از ایجاد سفارش، آدرس خودرو را تنظیم کنید',
|
||||
PAYMENT_METHOD_NOT_FOUND = 'روش پرداخت یافت نشد',
|
||||
PAYMENT_METHOD_NOT_ENABLED = 'روش پرداخت برای این رستوران فعال نیست',
|
||||
FOOD_NOT_FOUND = 'غذا یافت نشد',
|
||||
FOOD_NOT_BELONGS_TO_RESTAURANT = 'غذا به این رستوران تعلق ندارد',
|
||||
}
|
||||
|
||||
export const enum CartMessage {
|
||||
TABLE_NUMBER_REQUIRED = 'شماره میز برای سفارش در محل الزامی است',
|
||||
CAR_ADDRESS_REQUIRED = 'آدرس خودرو برای تحویل به خودرو الزامی است',
|
||||
ADDRESS_REQUIRED = 'آدرس برای تحویل پیک الزامی است',
|
||||
NOT_FOUND = 'سبد خرید یافت نشد',
|
||||
COUPON_NOT_FOUND = 'کوپن یافت نشد',
|
||||
FOOD_NOT_FOUND = 'غذا یافت نشد',
|
||||
FOOD_NOT_BELONGS_TO_RESTAURANT = 'غذا به این رستوران تعلق ندارد',
|
||||
FOOD_NO_INVENTORY = 'غذا موجودی ندارد',
|
||||
INSUFFICIENT_STOCK = 'موجودی کافی نیست',
|
||||
USER_NOT_FOUND = 'کاربر یافت نشد',
|
||||
ADDRESS_NOT_FOUND = 'آدرس یافت نشد',
|
||||
RESTAURANT_NOT_FOUND = 'رستوران یافت نشد',
|
||||
ADDRESS_NOT_BELONGS_TO_USER = 'آدرس به کاربر فعلی تعلق ندارد',
|
||||
ADDRESS_NO_COORDINATES = 'آدرس مختصات جغرافیایی ندارد',
|
||||
ADDRESS_OUTSIDE_SERVICE_AREA = 'آدرس خارج از محدوده سرویس رستوران است',
|
||||
DELIVERY_METHOD_NOT_FOUND = 'روش ارسال یافت نشد',
|
||||
DELIVERY_METHOD_NOT_ENABLED = 'روش ارسال برای این رستوران فعال نیست',
|
||||
PAYMENT_METHOD_NOT_FOUND = 'روش پرداخت یافت نشد',
|
||||
PAYMENT_METHOD_NOT_ENABLED = 'روش پرداخت برای این رستوران فعال نیست',
|
||||
WALLET_NOT_FOUND = 'کیف پول کاربر یافت نشد',
|
||||
WALLET_INSUFFICIENT = 'موجودی کیف پول کافی نیست',
|
||||
COUPON_MAX_USES_REACHED = 'حداکثر استفاده از کوپن به پایان رسیده است',
|
||||
ITEM_NOT_FOUND = 'آیتم در سبد خرید یافت نشد',
|
||||
DELIVERY_METHOD_NOT_FOUND_FOR_RESTAURANT = 'روش ارسال برای این رستوران یافت نشد',
|
||||
COUPON_CANNOT_BE_APPLIED = 'این کوپن قابل اعمال بر روی آیتمهای سبد خرید شما نیست. لطفا آیتمهایی از دستهبندیها یا غذاهای مشخص شده اضافه کنید',
|
||||
FOODS_MUST_HAVE_PICKUP_SERVE_FOR_COURIER = 'تمام غذاها باید قابلیت تحویل پیک داشته باشند. غذاهای زیر این قابلیت را ندارند: [foodTitles]',
|
||||
FOOD_ONLY_AVAILABLE_DURING_MEAL_TIMES = 'غذا [foodTitle] فقط در ساعات وعدههای غذایی (صبحانه، ناهار، عصرانه یا شام) در دسترس است. زمان فعلی خارج از ساعات وعدههای غذایی است',
|
||||
FOOD_ONLY_AVAILABLE_FOR_MEAL_TYPES = 'غذا [foodTitle] فقط برای [allowedMealTypes] در دسترس است. زمان فعلی [mealType] است که با این غذا سازگار نیست',
|
||||
FOOD_ONLY_AVAILABLE_ON_DAYS = 'غذا [foodTitle] فقط در روزهای [allowedDays] در دسترس است. امروز [currentDay] است که این غذا در دسترس نیست',
|
||||
}
|
||||
|
||||
export const enum PaymentMessage {
|
||||
UNSUPPORTED_PAYMENT_METHOD = 'روش پرداخت پشتیبانی نمیشود',
|
||||
ORDER_NOT_FOUND = 'سفارش یافت نشد',
|
||||
AMOUNT_MUST_BE_GREATER_THAN_ZERO = 'مبلغ باید بیشتر از صفر باشد',
|
||||
PAYMENT_METHOD_NOT_FOUND = 'روش پرداخت یافت نشد',
|
||||
GATEWAY_REQUIRED = 'درگاه پرداخت برای پرداخت آنلاین الزامی است',
|
||||
MERCHANT_ID_REQUIRED = 'شناسه مرچنت برای پرداخت آنلاین الزامی است',
|
||||
RESTAURANT_DOMAIN_REQUIRED = 'دامنه رستوران برای پرداخت آنلاین الزامی است',
|
||||
WALLET_NOT_FOUND = 'کیف پول کاربر یافت نشد',
|
||||
INSUFFICIENT_WALLET_BALANCE = 'موجودی کیف پول کافی نیست',
|
||||
PAYMENT_NOT_FOUND = 'پرداخت یافت نشد',
|
||||
INVALID_PAYMENT_CONFIGURATION = 'پیکربندی پرداخت نامعتبر است',
|
||||
PAYMENT_METHOD_NOT_CASH = 'روش پرداخت نقدی نیست',
|
||||
PAYMENT_ALREADY_PAID = 'پرداخت قبلا انجام شده است',
|
||||
EXISTING_PENDING_PAYMENT_MISMATCH = 'پرداخت در انتظار موجود با روش پرداخت سفارش مطابقت ندارد',
|
||||
ZARINPAL_INVALID_RESPONSE = 'پاسخ نامعتبر از API زرینپال',
|
||||
ZARINPAL_PAYMENT_REQUEST_ERROR = 'خطا در درخواست پرداخت زرینپال',
|
||||
ZARINPAL_VERIFY_ERROR = 'خطا در تایید پرداخت زرینپال',
|
||||
GATEWAY_ERROR = 'خطا در اتصال به درگاه پرداخت',
|
||||
}
|
||||
|
||||
export const enum DeliveryMessage {
|
||||
RESTAURANT_NOT_FOUND = 'رستوران یافت نشد',
|
||||
DELIVERY_METHOD_NOT_FOUND = 'روش ارسال یافت نشد',
|
||||
}
|
||||
|
||||
export const enum InventoryMessage {
|
||||
AVAILABLE_STOCK_EXCEEDS_TOTAL = 'موجودی موجود نمیتواند از موجودی کل بیشتر باشد',
|
||||
FOOD_NOT_FOUND = 'غذا یافت نشد',
|
||||
FOOD_NOT_BELONGS_TO_RESTAURANT = 'غذا به این رستوران تعلق ندارد',
|
||||
RESTAURANT_NOT_FOUND = 'رستوران یافت نشد',
|
||||
FOODS_NOT_FOUND = 'غذاها یافت نشدند',
|
||||
}
|
||||
|
||||
|
||||
export const enum PagerMessage {
|
||||
CREATED_SUCCESS = 'درخواست پیج با موفقیت ایجاد شد',
|
||||
}
|
||||
|
||||
export const enum UserSuccessMessage {
|
||||
ADDRESS_DELETED_SUCCESS = 'آدرس با موفقیت حذف شد',
|
||||
SCORE_CONVERTED_SUCCESS = 'امتیاز با موفقیت به کیف پول تبدیل شد',
|
||||
}
|
||||
|
||||
export const enum ContactMessage {
|
||||
NOT_FOUND = 'تماس یافت نشد',
|
||||
CREATED = 'تماس با موفقیت ثبت شد',
|
||||
UPDATED = 'تماس با موفقیت بهروزرسانی شد',
|
||||
DELETED = 'تماس با موفقیت حذف شد',
|
||||
}
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Permission names enum
|
||||
* All permission names used in the system should be defined here
|
||||
*/
|
||||
export enum Permission {
|
||||
MANAGE_PAGER = 'manage_pager',
|
||||
// Food Management
|
||||
MANAGE_FOODS = 'manage_foods',
|
||||
MANAGE_CATEGORIES = 'manage_categories',
|
||||
|
||||
// Order Management
|
||||
MANAGE_ORDERS = 'manage_orders',
|
||||
|
||||
// User & Admin Management
|
||||
MANAGE_ADMINS = 'manage_admins',
|
||||
MANAGE_USERS = 'manage_users',
|
||||
|
||||
// Reports & Finances
|
||||
VIEW_REPORTS = 'view_reports',
|
||||
|
||||
|
||||
UPDATE_RESTAURANT = 'update_restaurant',
|
||||
|
||||
// Role Management
|
||||
MANAGE_ROLES = 'manage_roles',
|
||||
MANAGE_REVIEWS = 'manage_reviews',
|
||||
MANAGE_COUPONS = 'manage_coupons',
|
||||
MANAGE_PAYMENTS = 'manage_payments',
|
||||
MANAGE_DELIVERY = 'manage_delivery',
|
||||
MANAGE_SETTINGS = 'manage_settings',
|
||||
MANAGE_SCHEDULES = 'manage_schedules',
|
||||
MANAGE_REPORTS = 'manage_reports',
|
||||
MANAGE_CONTACTS = 'manage_contacts',
|
||||
}
|
||||
|
||||
/**
|
||||
* Permission titles mapping (Farsi)
|
||||
* Maps permission names to their Farsi titles
|
||||
*/
|
||||
export const PermissionTitles: Record<Permission, string> = {
|
||||
[Permission.MANAGE_PAGER]: 'مدیریت پیجر',
|
||||
[Permission.MANAGE_FOODS]: 'مدیریت غذاها',
|
||||
[Permission.MANAGE_CATEGORIES]: 'مدیریت دستهبندیها',
|
||||
[Permission.MANAGE_ORDERS]: 'مدیریت سفارشات',
|
||||
[Permission.MANAGE_ADMINS]: 'مدیریت مدیران',
|
||||
[Permission.MANAGE_USERS]: 'مدیریت کاربران',
|
||||
[Permission.VIEW_REPORTS]: 'مشاهده گزارشات',
|
||||
[Permission.UPDATE_RESTAURANT]: 'ویرایش رستوران',
|
||||
[Permission.MANAGE_ROLES]: 'مدیریت نقشها',
|
||||
[Permission.MANAGE_REVIEWS]: 'مدیریت نظرات',
|
||||
[Permission.MANAGE_COUPONS]: 'مدیریت کوپنها',
|
||||
[Permission.MANAGE_PAYMENTS]: 'مدیریت پرداختها',
|
||||
[Permission.MANAGE_DELIVERY]: 'مدیریت تحویل',
|
||||
[Permission.MANAGE_SETTINGS]: 'مدیریت تنظیمات',
|
||||
[Permission.MANAGE_SCHEDULES]: 'مدیریت برنامهها',
|
||||
[Permission.MANAGE_REPORTS]: 'مدیریت گزارشات',
|
||||
[Permission.MANAGE_CONTACTS]: 'مدیریت تماسهای کاربران',
|
||||
};
|
||||
@@ -0,0 +1,9 @@
|
||||
export interface PaginatedResult<T> {
|
||||
data: T[];
|
||||
meta: {
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
totalPages: number;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { ValueProvider } from '@nestjs/common';
|
||||
import { Logger } from '@nestjs/common';
|
||||
|
||||
import { MIKRO_ORM_QUERY_LOGGER } from '../constants';
|
||||
|
||||
export const mikroOrmQueryLoggerProvider: ValueProvider = {
|
||||
provide: MIKRO_ORM_QUERY_LOGGER, //
|
||||
useValue: new Logger('mikro-orm'),
|
||||
};
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
import { Keyv } from 'keyv';
|
||||
import KeyvRedis from '@keyv/redis';
|
||||
import type { CacheModuleAsyncOptions } from '@nestjs/cache-manager';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { CacheableMemory } from 'cacheable';
|
||||
|
||||
export function cacheConfig(): CacheModuleAsyncOptions {
|
||||
return {
|
||||
isGlobal: true,
|
||||
inject: [ConfigService],
|
||||
useFactory: async (configService: ConfigService) => {
|
||||
const redisUri = configService.get('REDIS_URI');
|
||||
const namespace = configService.get('CACHE_NAMESPACE', 'app-cache');
|
||||
const ttl = +configService.get<number>('CACHE_TTL', 3600); //1 hour
|
||||
|
||||
return {
|
||||
stores: [
|
||||
new Keyv({
|
||||
store: new CacheableMemory({ ttl: ttl * 1000, lruSize: 5000 }),
|
||||
namespace: namespace
|
||||
}),
|
||||
new KeyvRedis(redisUri, { namespace: namespace }),
|
||||
],
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
Executable
+16
@@ -0,0 +1,16 @@
|
||||
import type { HttpModuleAsyncOptions } from '@nestjs/axios';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
export function httpConfig(): HttpModuleAsyncOptions {
|
||||
return {
|
||||
inject: [ConfigService],
|
||||
global: true,
|
||||
useFactory: (configService: ConfigService) => {
|
||||
return {
|
||||
timeout: configService.getOrThrow<number>('AXIOS_TIMEOUT'),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
global: true,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { defineConfig, PostgreSqlDriver } from '@mikro-orm/postgresql';
|
||||
import * as dotenv from 'dotenv';
|
||||
|
||||
// 1. Load environment variables from your .env file
|
||||
dotenv.config();
|
||||
|
||||
// 2. Read variables directly from process.env
|
||||
const DB_PASS = process.env.DB_PASS;
|
||||
const DB_USER = process.env.DB_USER;
|
||||
const DB_HOST = process.env.DB_HOST;
|
||||
const DB_PORT = process.env.DB_PORT ? +process.env.DB_PORT : 5432;
|
||||
const DB_NAME = process.env.DB_NAME;
|
||||
const isProduction = process.env.NODE_ENV === 'production';
|
||||
|
||||
// 3. Add checks to ensure variables are loaded
|
||||
if (!DB_PASS || !DB_USER || !DB_HOST || !DB_PORT || !DB_NAME) {
|
||||
throw new Error('One or more database environment variables are not set.');
|
||||
}
|
||||
|
||||
const encodedPassword = encodeURIComponent(DB_PASS);
|
||||
|
||||
// 4. Export the result of defineConfig as the default
|
||||
export default defineConfig({
|
||||
entities: ['dist/**/*.entity.js'],
|
||||
entitiesTs: ['src/**/*.entity.ts'],
|
||||
driver: PostgreSqlDriver,
|
||||
dbName: DB_NAME,
|
||||
debug: false,
|
||||
clientUrl: `postgres://${DB_USER}:${encodedPassword}@${DB_HOST}:${DB_PORT}`,
|
||||
ensureDatabase: isProduction
|
||||
? false
|
||||
: {
|
||||
forceCheck: true,
|
||||
create: true,
|
||||
schema: 'update',
|
||||
},
|
||||
forceUtcTimezone: true,
|
||||
pool: {
|
||||
min: isProduction ? 5 : 2,
|
||||
max: isProduction ? 20 : 10,
|
||||
idleTimeoutMillis: 30000,
|
||||
acquireTimeoutMillis: 30000,
|
||||
reapIntervalMillis: 1000,
|
||||
createTimeoutMillis: 15000,
|
||||
destroyTimeoutMillis: 5000,
|
||||
},
|
||||
// 5. Use console for CLI logging, not the injected Nest logger
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
||||
logger: isProduction ? console.log.bind(console) : console.debug.bind(console),
|
||||
schemaGenerator: {
|
||||
disableForeignKeys: false,
|
||||
},
|
||||
migrations: {
|
||||
path: './database/migrations',
|
||||
pathTs: './database/migrations',
|
||||
tableName: 'migrations',
|
||||
transactional: true,
|
||||
allOrNothing: true,
|
||||
dropTables: false,
|
||||
safe: true,
|
||||
emit: 'ts',
|
||||
},
|
||||
connect: true,
|
||||
allowGlobalContext: true,
|
||||
seeder: {
|
||||
path: './dist/seeders',
|
||||
pathTs: './src/seeders',
|
||||
defaultSeeder: 'DatabaseSeeder',
|
||||
},
|
||||
driverOptions: {
|
||||
connection: {
|
||||
keepAlive: true,
|
||||
keepAliveInitialDelayMillis: 10000,
|
||||
statement_timeout: 60000,
|
||||
query_timeout: 60000,
|
||||
idle_in_transaction_session_timeout: 60000,
|
||||
connectionTimeoutMillis: 10000,
|
||||
application_name: DB_NAME,
|
||||
},
|
||||
connectionRetries: 5,
|
||||
connectionRetryDelay: 3000,
|
||||
validateConnection: (connection: any) => {
|
||||
try {
|
||||
return !!(connection && !connection.closed);
|
||||
} catch (e: unknown) {
|
||||
// Use console.error directly
|
||||
console.error(`Connection validation failed: ${(e as Error).message}`);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
poolErrorHandler: (err: Error) => {
|
||||
// Use console.error directly
|
||||
console.error(`PostgreSQL pool error: ${err.message}`);
|
||||
if (err.message.includes('ECONNRESET') || err.message.includes('Connection terminated unexpectedly')) {
|
||||
console.warn('Connection reset detected, will attempt to reconnect');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { MikroOrmModuleAsyncOptions } from '@mikro-orm/nestjs';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { PostgreSqlDriver } from '@mikro-orm/postgresql';
|
||||
// import { defineConfig } from '@mikro-orm/postgresql';
|
||||
|
||||
import type { Logger } from '@nestjs/common';
|
||||
import { MIKRO_ORM_QUERY_LOGGER } from '../common/constants';
|
||||
import { mikroOrmQueryLoggerProvider } from '../common/providers/mikro-orm-logger.provider';
|
||||
|
||||
const dataBaseConfig: MikroOrmModuleAsyncOptions = {
|
||||
// entities: ['dist/**/*.entity.js'],
|
||||
// entitiesTs: ['src/**/*.entity.ts'],
|
||||
// dbName: 'your_db_name',
|
||||
// type: 'postgresql',
|
||||
// user: 'your_user',
|
||||
// password: 'your_password',
|
||||
// host: 'localhost',
|
||||
// port: 5432,
|
||||
// debug: true,
|
||||
|
||||
inject: [ConfigService, MIKRO_ORM_QUERY_LOGGER],
|
||||
providers: [mikroOrmQueryLoggerProvider],
|
||||
useFactory: (configService: ConfigService, logger: Logger) => {
|
||||
const DB_PASS = configService.getOrThrow<string>('DB_PASS');
|
||||
const DB_USER = configService.getOrThrow<string>('DB_USER');
|
||||
const DB_HOST = configService.getOrThrow<string>('DB_HOST');
|
||||
const DB_PORT = configService.getOrThrow<number>('DB_PORT');
|
||||
const DB_NAME = configService.getOrThrow<string>('DB_NAME');
|
||||
const encodedPassword = encodeURIComponent(DB_PASS);
|
||||
const isProduction = configService.getOrThrow<string>('NODE_ENV') === 'production';
|
||||
|
||||
return {
|
||||
// entities: ['dist/**/*.entity.js'],
|
||||
entitiesTs: ['src/**/*.entity.ts'],
|
||||
driver: PostgreSqlDriver,
|
||||
autoLoadEntities: true,
|
||||
dbName: DB_NAME,
|
||||
debug: false,
|
||||
clientUrl: `postgres://${DB_USER}:${encodedPassword}@${DB_HOST}:${DB_PORT}`,
|
||||
ensureDatabase: isProduction
|
||||
? false
|
||||
: {
|
||||
forceCheck: true,
|
||||
create: true,
|
||||
schema: 'update',
|
||||
},
|
||||
forceUtcTimezone: true,
|
||||
pool: {
|
||||
min: isProduction ? 5 : 2,
|
||||
max: isProduction ? 20 : 10,
|
||||
idleTimeoutMillis: 30000,
|
||||
acquireTimeoutMillis: 30000,
|
||||
reapIntervalMillis: 1000,
|
||||
createTimeoutMillis: 15000,
|
||||
destroyTimeoutMillis: 5000,
|
||||
},
|
||||
logger: isProduction ? message => logger.log(message) : message => logger.debug(message),
|
||||
schemaGenerator: {
|
||||
// createForeignKey: !isProduction,
|
||||
disableForeignKeys: false,
|
||||
// createIndex: true,
|
||||
},
|
||||
migrations: {
|
||||
path: './database/migrations',
|
||||
pathTs: './database/migrations',
|
||||
tableName: 'migrations',
|
||||
transactional: true,
|
||||
allOrNothing: true,
|
||||
dropTables: false,
|
||||
safe: true,
|
||||
emit: 'ts',
|
||||
},
|
||||
connect: true,
|
||||
allowGlobalContext: true,
|
||||
driverOptions: {
|
||||
connection: {
|
||||
keepAlive: true,
|
||||
keepAliveInitialDelayMillis: 10000,
|
||||
statement_timeout: 60000,
|
||||
query_timeout: 60000,
|
||||
idle_in_transaction_session_timeout: 60000,
|
||||
connectionTimeoutMillis: 10000,
|
||||
application_name: configService.getOrThrow<string>('DB_NAME'),
|
||||
},
|
||||
connectionRetries: 5,
|
||||
connectionRetryDelay: 3000,
|
||||
validateConnection: (connection: any) => {
|
||||
try {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
|
||||
return !!(connection && !connection.closed);
|
||||
} catch (e: unknown) {
|
||||
logger.error(`Connection validation failed: ${(e as Error).message}`);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
poolErrorHandler: (err: Error) => {
|
||||
logger.error(`PostgreSQL pool error: ${err.message}`);
|
||||
if (err.message.includes('ECONNRESET') || err.message.includes('Connection terminated unexpectedly')) {
|
||||
logger.warn('Connection reset detected, will attempt to reconnect');
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default dataBaseConfig;
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
|
||||
export function getSwaggerConfig(app: INestApplication) {
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('D-menu API')
|
||||
.setDescription('API documentation for D-menu backend')
|
||||
.setVersion('1.0')
|
||||
.addBearerAuth() // optional: for JWT endpoints
|
||||
.build();
|
||||
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
|
||||
SwaggerModule.setup('docs', app, document, {
|
||||
swaggerOptions: {
|
||||
persistAuthorization: true,
|
||||
displayRequestDuration: true,
|
||||
filter: true,
|
||||
showExtensions: true,
|
||||
docExpansion: 'none',
|
||||
|
||||
// HIDE MODELS / SCHEMAS
|
||||
defaultModelsExpandDepth: -1,
|
||||
defaultModelExpandDepth: -1,
|
||||
},
|
||||
});
|
||||
}
|
||||
Executable
+48
@@ -0,0 +1,48 @@
|
||||
import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common';
|
||||
import { FastifyReply } from 'fastify';
|
||||
|
||||
@Catch(HttpException)
|
||||
export class HttpExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: HttpException, host: ArgumentsHost) {
|
||||
// Handle HTTP/REST context
|
||||
try {
|
||||
const ctx = host.switchToHttp();
|
||||
const reply = ctx.getResponse<FastifyReply>();
|
||||
|
||||
// Safety check: ensure reply has the status method
|
||||
if (!reply || typeof reply.status !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
// const request = ctx.getRequest<FastifyRequest>();
|
||||
const status = exception.getStatus() || HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
|
||||
const exceptionResponse = exception.getResponse();
|
||||
const message = this.extractMessage(exceptionResponse);
|
||||
|
||||
reply.status(status).send({
|
||||
statusCode: status,
|
||||
success: false,
|
||||
error: {
|
||||
message,
|
||||
// timestamp: new Date().toISOString(),
|
||||
// path: request.url,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// If we can't handle it, let it propagate
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private extractMessage(response: string | Record<string, any>): string | string[] {
|
||||
if (typeof response === 'string') {
|
||||
return [response];
|
||||
}
|
||||
if (typeof response === 'object' && 'message' in response) {
|
||||
return Array.isArray(response.message) ? response.message : [response.message];
|
||||
}
|
||||
|
||||
return 'something wrong';
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
// import { CallHandler, ExecutionContext, Injectable, Logger, NestInterceptor } from '@nestjs/common';
|
||||
// import { FastifyRequest } from 'fastify';
|
||||
// import { Observable, map } from 'rxjs';
|
||||
|
||||
// import { IPageFormat } from '../../../../danak_dsc_api/src/common/interfaces/IPagination';
|
||||
|
||||
// @Injectable()
|
||||
// export class PaginationInterceptor implements NestInterceptor {
|
||||
// private readonly logger = new Logger(PaginationInterceptor.name);
|
||||
|
||||
// intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
// const request = context.switchToHttp().getRequest<FastifyRequest>();
|
||||
// const query = request.query as { page: string; limit: string };
|
||||
|
||||
// const page = parseInt(query.page, 10) || 1;
|
||||
// const limit = parseInt(query.limit, 10) || 10;
|
||||
|
||||
// const className = context.getClass().name;
|
||||
// const handlerName = context.getHandler().name;
|
||||
|
||||
// return next.handle().pipe(
|
||||
// map(data => {
|
||||
// if (data && (data.paginate || data.count)) {
|
||||
// const { count, paginate, ...response } = data;
|
||||
// this.logger.log(`paginate response from ${className}.${handlerName}`);
|
||||
// const pager = this.formatPage(page, limit, count, request);
|
||||
|
||||
// return {
|
||||
// pager,
|
||||
// ...response,
|
||||
// };
|
||||
// }
|
||||
|
||||
// return data;
|
||||
// }),
|
||||
// );
|
||||
// }
|
||||
|
||||
// private formatPage(page: number, limit: number, totalItems: number, request: FastifyRequest): IPageFormat {
|
||||
// const totalPages = Math.ceil(totalItems / limit);
|
||||
// const prevPage = page === 1 ? false : page - 1;
|
||||
// const nextPage = page >= totalPages ? false : page + 1;
|
||||
|
||||
// const formatLink = (pageNum: number | boolean): string | boolean => {
|
||||
// if (!pageNum) return false;
|
||||
// const protocol = request.protocol;
|
||||
// const hostname = request.hostname;
|
||||
// const originalUrl = request.url;
|
||||
// return `${protocol}://${hostname}${originalUrl.split('?')[0]}?page=${pageNum}&limit=${limit}`;
|
||||
// };
|
||||
|
||||
// return {
|
||||
// page,
|
||||
// limit,
|
||||
// totalItems,
|
||||
// totalPages,
|
||||
// prevPage: formatLink(prevPage),
|
||||
// nextPage: formatLink(nextPage),
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
|
||||
import { FastifyReply } from 'fastify';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
@Injectable()
|
||||
export class ResponseInterceptor implements NestInterceptor {
|
||||
constructor() { }
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler<Record<string, unknown>>): Observable<unknown> {
|
||||
// For REST endpoints, wrap the response
|
||||
try {
|
||||
const ctx = context.switchToHttp().getResponse<FastifyReply>();
|
||||
const statusCode = ctx.statusCode;
|
||||
|
||||
// If statusCode is undefined, skip wrapping
|
||||
if (statusCode === undefined) {
|
||||
return next.handle();
|
||||
}
|
||||
|
||||
return next.handle().pipe(
|
||||
map(data => {
|
||||
// If data is already wrapped or doesn't need wrapping, return as-is
|
||||
if (data && typeof data === 'object' && 'data' in data && 'success' in data) {
|
||||
console.log('data', data)
|
||||
|
||||
return {
|
||||
data: data,
|
||||
...('nextCursor' in (data as any) && (data as any).nextCursor != null
|
||||
? { nextCursor: (data as any).nextCursor }
|
||||
: {}),
|
||||
}
|
||||
}
|
||||
|
||||
// Check if this is a paginated result (has both data and meta properties)
|
||||
if (data && typeof data === 'object' && 'data' in data && 'meta' in data) {
|
||||
return {
|
||||
statusCode,
|
||||
success: true,
|
||||
data: data.data,
|
||||
meta: data.meta,
|
||||
};
|
||||
}
|
||||
|
||||
if (data && 'data' in data) {
|
||||
|
||||
return {
|
||||
statusCode,
|
||||
success: true,
|
||||
data: data.data,
|
||||
...('nextCursor' in data
|
||||
? { nextCursor: (data as any).nextCursor }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
statusCode,
|
||||
success: true,
|
||||
data,
|
||||
};
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// If we can't get HTTP context, return data as-is
|
||||
return next.handle();
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+26
@@ -0,0 +1,26 @@
|
||||
import { Injectable, Logger, NestMiddleware } from '@nestjs/common';
|
||||
import { FastifyReply, FastifyRequest } from 'fastify';
|
||||
|
||||
@Injectable()
|
||||
export class HTTPLogger implements NestMiddleware {
|
||||
private readonly logger = new Logger(HTTPLogger.name);
|
||||
// use(req: any, res: any, next: (error?: Error | any) => void) {}
|
||||
|
||||
use(req: FastifyRequest, rep: FastifyReply['raw'], next: () => void) {
|
||||
const { ip, method, originalUrl } = req;
|
||||
const userAgent = req.headers['user-agent'] || '';
|
||||
const startAt = process.hrtime();
|
||||
|
||||
rep.on('finish', () => {
|
||||
const { statusCode } = rep;
|
||||
const contentLength = rep.getHeader('content-length') || 0;
|
||||
const dif = process.hrtime(startAt);
|
||||
const responseTime = dif[0] * 1e3 + dif[1] * 1e-6;
|
||||
this.logger.log(
|
||||
`${method} - ${originalUrl} - ${statusCode} - ${contentLength} - ${userAgent} - ${ip} - ${responseTime.toFixed(2)}ms`,
|
||||
);
|
||||
});
|
||||
|
||||
next();
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { AppModule } from './app.module';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Logger, ValidationPipe } from '@nestjs/common';
|
||||
import { getSwaggerConfig } from './config/swagger.config';
|
||||
import multipart from '@fastify/multipart';
|
||||
import fastifyCookie from '@fastify/cookie';
|
||||
|
||||
// 👈 Import the Fastify application type
|
||||
import { type NestFastifyApplication, FastifyAdapter } from '@nestjs/platform-fastify';
|
||||
import { HttpExceptionFilter } from './core/exceptions/http.exceptions';
|
||||
import { ResponseInterceptor } from './core/interceptors/response.interceptor';
|
||||
// import { PaginationInterceptor } from './core/interceptors/pagination.interceptor';
|
||||
|
||||
async function bootstrap() {
|
||||
const logger = new Logger('APP');
|
||||
|
||||
// 1. Create the application using the Fastify adapter
|
||||
const app = await NestFactory.create<NestFastifyApplication>(
|
||||
AppModule,
|
||||
new FastifyAdapter(), // Instantiate the FastifyAdapter
|
||||
// Optional: Pass the custom logger (like your 'APP' logger) to NestFactory
|
||||
{ logger: ['error', 'warn', 'log', 'debug', 'verbose'] },
|
||||
);
|
||||
|
||||
await app.register(fastifyCookie);
|
||||
|
||||
await app.register(multipart);
|
||||
app.useGlobalPipes(new ValidationPipe());
|
||||
|
||||
app.useGlobalInterceptors(
|
||||
new ResponseInterceptor(),
|
||||
// , new PaginationInterceptor()
|
||||
);
|
||||
app.useGlobalFilters(new HttpExceptionFilter());
|
||||
|
||||
const configService = app.get<ConfigService>(ConfigService);
|
||||
// Ensure the port is handled correctly, use 4000 as fallback if needed
|
||||
const APP_PORT = configService.getOrThrow<number>('APP_PORT') ?? 4000;
|
||||
|
||||
// 2. Swagger Integration Note
|
||||
// Since you are using platform-fastify, you must ensure your getSwaggerConfig
|
||||
// function is configured to use the Fastify platform option if necessary.
|
||||
getSwaggerConfig(app);
|
||||
|
||||
app.enableCors({
|
||||
origin: true,
|
||||
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
|
||||
credentials: true,
|
||||
optionsSuccessStatus: 204,
|
||||
});
|
||||
|
||||
// 3. Listen on port using Fastify's listen method
|
||||
// '0.0.0.0' is recommended for Docker/containerized environments
|
||||
await app.listen(APP_PORT, '0.0.0.0', () => {
|
||||
logger.log(`Application is running on: http://localhost:${APP_PORT}`);
|
||||
logger.log(`Swagger documentation: http://localhost:${APP_PORT}/docs`);
|
||||
});
|
||||
}
|
||||
|
||||
bootstrap();
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Module, forwardRef } from '@nestjs/common';
|
||||
import { AdminService } from './providers/admin.service';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Admin } from './entities/admin.entity';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { AdminRepository } from './repositories/admin.repository';
|
||||
import { Role } from '../roles/entities/role.entity';
|
||||
import { Permission } from '../roles/entities/permission.entity';
|
||||
import { RolePermission } from '../roles/entities/rolePermission.entity';
|
||||
import { AdminController } from './controllers/admin.controller';
|
||||
import { UtilsModule } from '../utils/utils.module';
|
||||
import { RestaurantsModule } from '../restaurants/restaurants.module';
|
||||
import { AdminRole } from './entities/adminRole.entity';
|
||||
|
||||
@Module({
|
||||
providers: [AdminService, AdminRepository],
|
||||
controllers: [AdminController],
|
||||
imports: [
|
||||
MikroOrmModule.forFeature([Admin, Role, Permission, RolePermission, AdminRole]),
|
||||
JwtModule,
|
||||
UtilsModule,
|
||||
forwardRef(() => RestaurantsModule),
|
||||
],
|
||||
exports: [AdminService, AdminRepository],
|
||||
})
|
||||
export class AdminModule {}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { Controller, Post, Body, HttpCode, HttpStatus, Get, UseGuards, Patch, Param, Delete } from '@nestjs/common';
|
||||
import { AdminService } from '../providers/admin.service';
|
||||
import { CreateAdminDto } from '../dto/create-admin.dto';
|
||||
import { UpdateAdminDto } from '../dto/update-admin.dto';
|
||||
import { ApiTags, ApiOperation, ApiBody, ApiBearerAuth, ApiParam } from '@nestjs/swagger';
|
||||
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
|
||||
import { SuperAdminAuthGuard } from 'src/modules/auth/guards/superAdminAuth.guard';
|
||||
import { RestId } from 'src/common/decorators';
|
||||
import { AdminId } from 'src/common/decorators/admin-id.decorator';
|
||||
import { Admin } from '../entities/admin.entity';
|
||||
import { Permission } from 'src/common/enums/permission.enum';
|
||||
import { Permissions } from 'src/common/decorators/permissions.decorator';
|
||||
import { CreateMyRestaurantAdminDto } from '../dto/create-my-restaurant-admin.dto';
|
||||
|
||||
@ApiBearerAuth()
|
||||
@ApiTags('admin')
|
||||
@Controller()
|
||||
export class AdminController {
|
||||
constructor(private readonly adminService: AdminService) {}
|
||||
|
||||
@Get('admin/admins')
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@Permissions(Permission.MANAGE_ADMINS)
|
||||
@ApiOperation({ summary: 'admin' })
|
||||
async getAll(@RestId() restId: string) {
|
||||
const admin = await this.adminService.findAllByRestaurantId(restId);
|
||||
return admin;
|
||||
}
|
||||
|
||||
@Get('admin/admins/profile')
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@Permissions(Permission.MANAGE_ADMINS)
|
||||
@ApiOperation({ summary: 'admin' })
|
||||
async getMe(@AdminId() adminId: string, @RestId() restId: string) {
|
||||
const admin = await this.adminService.findById(adminId, restId);
|
||||
return admin;
|
||||
}
|
||||
|
||||
@Post('admin/admins')
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@Permissions(Permission.MANAGE_ADMINS)
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@ApiOperation({ summary: 'Create a new admin' })
|
||||
@ApiBody({ type: CreateAdminDto })
|
||||
async create(@Body() dto: CreateAdminDto, @RestId() restId: string) {
|
||||
const admin = await this.adminService.createAdminForMyRestaurant(restId, dto);
|
||||
return admin;
|
||||
}
|
||||
|
||||
@Patch('admin/admins/:adminId')
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@Permissions(Permission.MANAGE_ADMINS)
|
||||
@ApiOperation({ summary: 'Update an admin' })
|
||||
@ApiParam({ name: 'adminId', description: 'Admin ID' })
|
||||
@ApiBody({ type: UpdateAdminDto })
|
||||
update(@Param('adminId') adminId: string, @Body() dto: UpdateAdminDto, @RestId() restId: string): Promise<Admin> {
|
||||
return this.adminService.update(adminId, restId, dto);
|
||||
}
|
||||
|
||||
@Get('admin/admins/:adminId')
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@Permissions(Permission.MANAGE_ADMINS)
|
||||
@ApiOperation({ summary: 'Get an admin by ID' })
|
||||
@ApiParam({ name: 'id', description: 'Admin ID' })
|
||||
getById(@Param('adminId') adminId: string, @RestId() restId: string): Promise<Admin | null> {
|
||||
return this.adminService.findById(adminId, restId);
|
||||
}
|
||||
|
||||
@Delete('admin/admins/:adminId')
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@Permissions(Permission.MANAGE_ADMINS)
|
||||
@ApiOperation({ summary: 'Delete an admin by ID' })
|
||||
@ApiParam({ name: 'id', description: 'Admin ID' })
|
||||
deleteById(@Param('adminId') adminId: string, @RestId() restId: string): Promise<void> {
|
||||
return this.adminService.remove(adminId, restId);
|
||||
}
|
||||
|
||||
/** Super Admin Endpoints */
|
||||
@UseGuards(SuperAdminAuthGuard)
|
||||
@Get('super-admin/restaurants/:restaurantId/admins')
|
||||
@ApiOperation({ summary: 'Get admins for a specific restaurant (Super Admin only)' })
|
||||
@ApiParam({ name: 'restaurantId', description: 'Restaurant ID' })
|
||||
getAdminForRestaurant(@Param('restaurantId') restaurantId: string): Promise<Admin[]> {
|
||||
return this.adminService.getAdminsForRestaurantBySuperAdmin(restaurantId);
|
||||
}
|
||||
|
||||
@UseGuards(SuperAdminAuthGuard)
|
||||
@Post('super-admin/restaurants/:restaurantId/admins')
|
||||
@ApiOperation({ summary: 'Create admin for a specific restaurant (Super Admin only)' })
|
||||
@ApiParam({ name: 'restaurantId', description: 'Restaurant ID' })
|
||||
@ApiBody({ type: CreateMyRestaurantAdminDto })
|
||||
createAdminForRestaurant(
|
||||
@Param('restaurantId') restaurantId: string,
|
||||
@Body() dto: CreateMyRestaurantAdminDto,
|
||||
): Promise<Admin> {
|
||||
return this.adminService.createAdminForRestaurantBySuperAdmin(restaurantId, dto);
|
||||
}
|
||||
|
||||
@UseGuards(SuperAdminAuthGuard)
|
||||
@Delete('super-admin/restaurants/:restaurantId/admins/:adminId')
|
||||
@ApiOperation({ summary: 'Revoke admin role from a restaurant (Super Admin only)' })
|
||||
@ApiParam({ name: 'restaurantId', description: 'Restaurant ID' })
|
||||
@ApiParam({ name: 'adminId', description: 'Admin ID' })
|
||||
revokeAdminFromRestaurant(
|
||||
@Param('restaurantId') restaurantId: string,
|
||||
@Param('adminId') adminId: string,
|
||||
): Promise<void> {
|
||||
return this.adminService.remove(adminId, restaurantId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class CreateAdminDto {
|
||||
@ApiProperty({ description: 'Mobile phone number' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
phone!: string;
|
||||
|
||||
@ApiProperty({ description: 'First name', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
firstName?: string;
|
||||
|
||||
@ApiProperty({ description: 'Last name', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
lastName?: string;
|
||||
|
||||
@ApiProperty({ description: 'Role id for the admin' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
roleId!: string;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
|
||||
|
||||
export class CreateMyRestaurantAdminDto {
|
||||
@ApiProperty({ description: 'Mobile phone number' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
phone!: string;
|
||||
|
||||
@ApiProperty({ description: 'First name', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
firstName?: string;
|
||||
|
||||
@ApiProperty({ description: 'Last name', required: false })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
lastName?: string;
|
||||
|
||||
@ApiProperty({ description: 'Role id for the admin' })
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
roleId!: string;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateAdminDto } from './create-admin.dto';
|
||||
|
||||
export class UpdateAdminDto extends PartialType(CreateAdminDto) {}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Cascade, Collection, Entity, OneToMany, Property } from '@mikro-orm/core';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { AdminRole } from './adminRole.entity';
|
||||
import { normalizePhone } from '../../utils/phone.util';
|
||||
|
||||
@Entity({ tableName: 'admins' })
|
||||
export class Admin extends BaseEntity {
|
||||
@Property({ nullable: true })
|
||||
firstName?: string;
|
||||
|
||||
@Property({ nullable: true })
|
||||
lastName?: string;
|
||||
|
||||
private _phone!: string;
|
||||
|
||||
@Property({ unique: true })
|
||||
get phone(): string {
|
||||
return this._phone;
|
||||
}
|
||||
|
||||
set phone(value: string) {
|
||||
this._phone = normalizePhone(value);
|
||||
}
|
||||
|
||||
// Add the new role property
|
||||
@OneToMany(() => AdminRole, adminRole => adminRole.admin, {
|
||||
cascade: [Cascade.ALL],
|
||||
orphanRemoval: true,
|
||||
})
|
||||
roles = new Collection<AdminRole>(this);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Entity, Index, ManyToOne, Unique } from '@mikro-orm/core';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { Role } from '../../roles/entities/role.entity';
|
||||
import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity';
|
||||
import { Admin } from './admin.entity';
|
||||
|
||||
@Entity({ tableName: 'admin_roles' })
|
||||
@Unique({ properties: ['admin', 'restaurant'] })
|
||||
@Index({ properties: ['admin', 'restaurant'] })
|
||||
@Index({ properties: ['admin'] })
|
||||
@Index({ properties: ['restaurant'] })
|
||||
export class AdminRole extends BaseEntity {
|
||||
@ManyToOne(() => Admin)
|
||||
admin!: Admin;
|
||||
|
||||
@ManyToOne(() => Role)
|
||||
role!: Role;
|
||||
|
||||
@ManyToOne(() => Restaurant, { nullable: true })
|
||||
restaurant?: Restaurant;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
import { ConflictException, Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { EntityRepository } from '@mikro-orm/core';
|
||||
import { Admin } from '../entities/admin.entity';
|
||||
import { Role } from '../../roles/entities/role.entity';
|
||||
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { CacheService } from '../../utils/cache.service';
|
||||
import { CreateMyRestaurantAdminDto } from '../dto/create-my-restaurant-admin.dto';
|
||||
import { UpdateAdminDto } from '../dto/update-admin.dto';
|
||||
import { AdminRole } from '../entities/adminRole.entity';
|
||||
import { normalizePhone } from '../../utils/phone.util';
|
||||
|
||||
@Injectable()
|
||||
export class AdminService {
|
||||
constructor(
|
||||
@InjectRepository(Admin)
|
||||
private readonly adminRepository: EntityRepository<Admin>,
|
||||
@InjectRepository(AdminRole)
|
||||
private readonly adminRoleRepository: EntityRepository<AdminRole>,
|
||||
private readonly em: EntityManager,
|
||||
private readonly cacheService: CacheService,
|
||||
) {}
|
||||
|
||||
async findByPhone(phone: string): Promise<Admin | null> {
|
||||
const normalizedPhone = normalizePhone(phone);
|
||||
return this.adminRepository.findOne({ phone: normalizedPhone });
|
||||
}
|
||||
|
||||
async findById(adminId: string, restId: string): Promise<Admin | null> {
|
||||
const admin = await this.adminRepository.findOne(
|
||||
{ id: adminId, roles: { restaurant: { id: restId } } },
|
||||
{ populate: ['roles', 'roles.role'] },
|
||||
);
|
||||
return admin;
|
||||
}
|
||||
|
||||
async findAllByRestaurantId(restId: string): Promise<Admin[]> {
|
||||
return this.adminRepository.find({ roles: { restaurant: { id: restId } } }, { populate: ['roles', 'roles.role'] });
|
||||
}
|
||||
|
||||
async createAdminForMyRestaurant(restId: string, dto: CreateMyRestaurantAdminDto) {
|
||||
const { phone, firstName, lastName, roleId } = dto;
|
||||
const normalizedPhone = normalizePhone(phone);
|
||||
let admin: Admin | null = null;
|
||||
admin = await this.adminRepository.findOne({
|
||||
phone: normalizedPhone,
|
||||
});
|
||||
if (!admin) {
|
||||
admin = this.adminRepository.create({
|
||||
phone: normalizedPhone,
|
||||
firstName,
|
||||
lastName,
|
||||
});
|
||||
await this.em.persistAndFlush(admin);
|
||||
}
|
||||
const role = await this.em.findOne(Role, { id: roleId, isSystem: false });
|
||||
if (!role) throw new NotFoundException('Role not found');
|
||||
|
||||
const restaurant = await this.em.findOne(Restaurant, { id: restId });
|
||||
if (!restaurant) throw new NotFoundException('Restaurant not found');
|
||||
|
||||
let adminRole = await this.adminRoleRepository.findOne({
|
||||
admin: admin,
|
||||
restaurant: restaurant,
|
||||
});
|
||||
|
||||
if (!adminRole) {
|
||||
adminRole = this.adminRoleRepository.create({
|
||||
admin: admin,
|
||||
role,
|
||||
restaurant,
|
||||
});
|
||||
} else {
|
||||
adminRole.role = role;
|
||||
}
|
||||
|
||||
await this.em.persistAndFlush(adminRole);
|
||||
return admin;
|
||||
}
|
||||
|
||||
async createAdminForRestaurantBySuperAdmin(restId: string, dto: CreateMyRestaurantAdminDto) {
|
||||
const { phone, firstName, lastName, roleId } = dto;
|
||||
const normalizedPhone = normalizePhone(phone);
|
||||
let admin: Admin | null = null;
|
||||
admin = await this.adminRepository.findOne({
|
||||
phone: normalizedPhone,
|
||||
});
|
||||
if (!admin) {
|
||||
admin = this.adminRepository.create({
|
||||
phone: normalizedPhone,
|
||||
firstName,
|
||||
lastName,
|
||||
});
|
||||
await this.em.persistAndFlush(admin);
|
||||
}
|
||||
const role = await this.em.findOne(Role, { id: roleId });
|
||||
if (!role) throw new NotFoundException('Role* not found' + roleId);
|
||||
|
||||
const restaurant = await this.em.findOne(Restaurant, { id: restId });
|
||||
if (!restaurant) throw new NotFoundException('Restaurant not found');
|
||||
|
||||
let adminRole = await this.adminRoleRepository.findOne({
|
||||
admin: admin,
|
||||
restaurant: restaurant,
|
||||
});
|
||||
|
||||
if (!adminRole) {
|
||||
adminRole = this.adminRoleRepository.create({
|
||||
admin: admin,
|
||||
role,
|
||||
restaurant,
|
||||
});
|
||||
} else {
|
||||
adminRole.role = role;
|
||||
}
|
||||
|
||||
await this.em.persistAndFlush(adminRole);
|
||||
return admin;
|
||||
}
|
||||
|
||||
async getAdminsForRestaurantBySuperAdmin(restId: string): Promise<Admin[]> {
|
||||
const restaurant = await this.em.findOne(Restaurant, { id: restId });
|
||||
if (!restaurant) throw new NotFoundException('Restaurant not found');
|
||||
|
||||
return this.adminRepository.find({ roles: { restaurant: restaurant } }, { populate: ['roles', 'roles.role'] });
|
||||
}
|
||||
|
||||
async update(adminId: string, restId: string, dto: UpdateAdminDto): Promise<Admin> {
|
||||
const admin = await this.adminRepository.findOne(
|
||||
{ id: adminId, roles: { restaurant: { id: restId } } },
|
||||
{ populate: ['roles', 'roles.role', 'roles.restaurant'] },
|
||||
);
|
||||
|
||||
if (!admin) {
|
||||
throw new NotFoundException('Admin not found');
|
||||
}
|
||||
|
||||
const { roleId, ...rest } = dto;
|
||||
|
||||
// Update scalar fields (firstName, lastName, phone)
|
||||
if (rest.firstName !== undefined) {
|
||||
admin.firstName = rest.firstName;
|
||||
}
|
||||
if (rest.lastName !== undefined) {
|
||||
admin.lastName = rest.lastName;
|
||||
}
|
||||
if (rest.phone !== undefined && rest.phone !== admin.phone) {
|
||||
const normalizedPhone = normalizePhone(rest.phone);
|
||||
const exists = await this.adminRepository.findOne({ phone: normalizedPhone });
|
||||
if (exists) {
|
||||
throw new ConflictException('This Phone Number is already taken');
|
||||
}
|
||||
admin.phone = normalizedPhone;
|
||||
}
|
||||
|
||||
// Update role if roleId is provided
|
||||
if (roleId) {
|
||||
const role = await this.em.findOne(Role, { id: roleId, isSystem: false });
|
||||
if (!role) {
|
||||
throw new NotFoundException('Role not found');
|
||||
}
|
||||
|
||||
// Find existing AdminRole for this admin and restaurant
|
||||
const existingAdminRole = await this.em.findOne(AdminRole, {
|
||||
admin: { id: adminId },
|
||||
restaurant: { id: restId },
|
||||
});
|
||||
|
||||
if (existingAdminRole) {
|
||||
// Update existing role
|
||||
existingAdminRole.role = role;
|
||||
} else {
|
||||
const restaurant = await this.em.findOne(Restaurant, { id: restId });
|
||||
if (!restaurant) throw new NotFoundException('Restaurant not found');
|
||||
// Create new AdminRole
|
||||
const newAdminRole = this.em.create(AdminRole, {
|
||||
admin,
|
||||
role,
|
||||
restaurant,
|
||||
});
|
||||
admin.roles.add(newAdminRole);
|
||||
}
|
||||
}
|
||||
|
||||
await this.em.persistAndFlush(admin);
|
||||
return admin;
|
||||
}
|
||||
|
||||
async remove(adminId: string, restId: string): Promise<void> {
|
||||
const adminRole = await this.adminRoleRepository.findOne({ admin: { id: adminId }, restaurant: { id: restId } });
|
||||
if (!adminRole) {
|
||||
throw new NotFoundException('Admin role not found');
|
||||
}
|
||||
return this.em.removeAndFlush(adminRole);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
|
||||
import { Admin } from '../entities/admin.entity';
|
||||
import { AdminRole } from '../entities/adminRole.entity';
|
||||
import { RestRepository } from '../../restaurants/repositories/rest.repository';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { normalizePhone } from '../../utils/phone.util';
|
||||
|
||||
@Injectable()
|
||||
export class AdminRepository extends EntityRepository<Admin> {
|
||||
constructor(
|
||||
readonly em: EntityManager,
|
||||
private readonly restRepository: RestRepository,
|
||||
) {
|
||||
super(em, Admin);
|
||||
}
|
||||
|
||||
async findByPhoneAndRestaurantSlug(phone: string, slug: string): Promise<Admin | null> {
|
||||
console.log('phone', phone);
|
||||
const normalizedPhone = normalizePhone(phone);
|
||||
// First, find the restaurant by slug using the same repository as auth service
|
||||
const restaurant = await this.restRepository.findOne({ slug });
|
||||
if (!restaurant) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Find AdminRole that matches the admin phone and restaurant
|
||||
const adminRole = await this.em.findOne(
|
||||
AdminRole,
|
||||
{
|
||||
admin: { phone: normalizedPhone },
|
||||
restaurant: { id: restaurant.id },
|
||||
},
|
||||
{ populate: ['admin', 'admin.roles', 'role', 'role.permissions', 'restaurant'] },
|
||||
);
|
||||
|
||||
if (!adminRole || !adminRole.admin) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Ensure all roles are populated
|
||||
await adminRole.admin.roles.loadItems();
|
||||
for (const role of adminRole.admin.roles.getItems()) {
|
||||
if (role.role && role.role.permissions && !role.role.permissions.isInitialized()) {
|
||||
await role.role.permissions.loadItems();
|
||||
}
|
||||
}
|
||||
|
||||
return adminRole.admin;
|
||||
}
|
||||
async findAdminsWithPermission(restaurantId: string, permission: string): Promise<Admin[]> {
|
||||
const admins = await this.em.find(
|
||||
Admin,
|
||||
{ roles: { restaurant: { id: restaurantId }, role: { permissions: { name: permission } } } },
|
||||
{ populate: ['roles', 'roles.role', 'roles.role.permissions'] },
|
||||
);
|
||||
return admins;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { Admin } from '../entities/admin.entity';
|
||||
|
||||
export interface AdminDetailResponse {
|
||||
id: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
phone: string;
|
||||
role: {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
permissions: string[];
|
||||
restaurant?: {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class AdminDetailTransformer {
|
||||
static transform(admin: Admin): AdminDetailResponse | null {
|
||||
if (!admin) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Extract role information
|
||||
const role = admin.roles.getItems().find(r => r.role)?.role;
|
||||
if (!role) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
id: admin.id,
|
||||
firstName: admin.firstName,
|
||||
lastName: admin.lastName,
|
||||
phone: admin.phone,
|
||||
role: {
|
||||
id: role.id,
|
||||
name: role.name,
|
||||
},
|
||||
permissions: role.permissions.getItems().map(p => p.name) || [],
|
||||
restaurant: {
|
||||
id: role.restaurant?.id || '',
|
||||
name: role.restaurant?.name || '',
|
||||
slug: role.restaurant?.slug || '',
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Extract permissions - ensure collection is loaded if needed
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Module, forwardRef } from '@nestjs/common';
|
||||
import { AuthService } from './services/auth.service';
|
||||
import { AuthController } from './controllers/auth.controller';
|
||||
import { UtilsModule } from '../utils/utils.module';
|
||||
import { UserModule } from '../users/user.module';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { AdminModule } from '../admin/admin.module';
|
||||
import { TokensService } from './services/tokens.service';
|
||||
import { RestaurantsModule } from '../restaurants/restaurants.module';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { User } from '../users/entities/user.entity';
|
||||
import { AdminAuthGuard } from './guards/adminAuth.guard';
|
||||
import { RefreshToken } from './entities/refresh-token.entity';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
UtilsModule,
|
||||
forwardRef(() => UserModule),
|
||||
JwtModule.registerAsync({
|
||||
useFactory: (configService: ConfigService) => {
|
||||
const expiresIn = configService.getOrThrow<number>('JWT_EXPIRATION_TIME');
|
||||
return {
|
||||
global: true,
|
||||
secret: configService.getOrThrow<string>('JWT_SECRET'),
|
||||
signOptions: {
|
||||
// Use string format with time unit for explicit expiration (value should be in seconds)
|
||||
expiresIn: `${expiresIn}s`,
|
||||
},
|
||||
};
|
||||
},
|
||||
inject: [ConfigService],
|
||||
}),
|
||||
forwardRef(() => AdminModule),
|
||||
forwardRef(() => RestaurantsModule),
|
||||
MikroOrmModule.forFeature([User, RefreshToken]),
|
||||
forwardRef(() => NotificationsModule),
|
||||
|
||||
],
|
||||
controllers: [AuthController],
|
||||
providers: [AuthService, TokensService, AdminAuthGuard],
|
||||
exports: [AdminAuthGuard],
|
||||
})
|
||||
export class AuthModule {}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Controller, Post, Body, UseGuards } from '@nestjs/common';
|
||||
import { AuthService } from '../services/auth.service';
|
||||
import { RequestOtpDto } from '../dto/request-otp.dto';
|
||||
import { DirectLoginDto } from '../dto/direct-login.dto';
|
||||
import { ApiTags, ApiOperation, ApiBody } from '@nestjs/swagger';
|
||||
import { VerifyOtpDto } from '../dto/verify-otp.dto';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { RefreshTokenRateLimit } from 'src/common/decorators/rate-limit.decorator';
|
||||
import { RefreshTokenDto } from '../dto/refresh-token.dto';
|
||||
import { SuperAdminAuthGuard } from '../guards/superAdminAuth.guard';
|
||||
|
||||
@ApiTags('auth')
|
||||
@Controller()
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) { }
|
||||
|
||||
@Throttle({ default: { limit: 3, ttl: 180_000 } })
|
||||
@Post('public/auth/otp/request')
|
||||
@ApiOperation({ summary: 'Request OTP for login or signup' })
|
||||
@ApiBody({ type: RequestOtpDto, description: 'Mobile number to receive OTP' })
|
||||
otpRequest(@Body() dto: RequestOtpDto) {
|
||||
return this.authService.requestOtp(dto, false);
|
||||
}
|
||||
|
||||
@Post('public/auth/otp/verify')
|
||||
@ApiOperation({ summary: 'Verify OTP code' })
|
||||
@ApiBody({ type: VerifyOtpDto, description: 'Mobile number and OTP code' })
|
||||
otpVerify(@Body() dto: VerifyOtpDto) {
|
||||
return this.authService.verifyOtp(dto.phone, dto.slug, dto.otp); // assuming dto has `otp` property
|
||||
}
|
||||
|
||||
@RefreshTokenRateLimit()
|
||||
@ApiOperation({ summary: 'refresh the user access token / refresh token' })
|
||||
@Post('public/auth/refresh')
|
||||
refreshToken(@Body() refreshTokenDto: RefreshTokenDto) {
|
||||
return this.authService.refreshToken(refreshTokenDto.refreshToken);
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 3, ttl: 180_000 } })
|
||||
@Post('admin/auth/otp/request')
|
||||
@ApiOperation({ summary: 'Request OTP for login or signup' })
|
||||
@ApiBody({ type: RequestOtpDto, description: 'Mobile number to receive OTP' })
|
||||
otpRequestAdmin(@Body() dto: RequestOtpDto) {
|
||||
return this.authService.requestOtp(dto, true);
|
||||
}
|
||||
|
||||
@Post('admin/auth/otp/verify')
|
||||
@ApiOperation({ summary: 'Verify OTP code' })
|
||||
@ApiBody({ type: VerifyOtpDto, description: 'Mobile number and OTP code' })
|
||||
otpVerifyAdmin(@Body() dto: VerifyOtpDto) {
|
||||
return this.authService.verifyOtpAdmin(dto.phone, dto.slug, dto.otp);
|
||||
}
|
||||
|
||||
@RefreshTokenRateLimit()
|
||||
@ApiOperation({ summary: 'refresh the admin access token / refresh token' })
|
||||
@Post('admin/auth/refresh')
|
||||
refreshTokenAdmin(@Body() refreshTokenDto: RefreshTokenDto) {
|
||||
return this.authService.refreshToken(refreshTokenDto.refreshToken);
|
||||
}
|
||||
|
||||
//super admin routes
|
||||
|
||||
@UseGuards(SuperAdminAuthGuard)
|
||||
@Post('super-admin/auth/direct-login')
|
||||
@ApiOperation({ summary: 'Direct login for DSC - returns login credentials' })
|
||||
@ApiBody({ type: DirectLoginDto, description: 'Phone number and restaurant slug for direct login' })
|
||||
directloginForDsc(@Body() dto: DirectLoginDto) {
|
||||
return this.authService.loginAdminForDsc(dto.phone, dto.slug);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { IsNotEmpty, IsString, IsMobilePhone } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class DirectLoginDto {
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@ApiProperty({ example: '09362532122', description: 'Mobile number' })
|
||||
@IsMobilePhone('fa-IR')
|
||||
phone: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@ApiProperty({ example: 'zhivan', description: 'Restaurant slug' })
|
||||
slug: string;
|
||||
}
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
|
||||
export class RefreshTokenDto {
|
||||
@ApiProperty({ description: 'Refresh token' })
|
||||
@IsString({ message: 'Refresh token must be a string' })
|
||||
@IsNotEmpty({ message: 'Refresh token is required' })
|
||||
refreshToken: string;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { IsNotEmpty, IsString, IsMobilePhone } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class RequestOtpDto {
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@ApiProperty({ example: '09362532122', description: 'Mobile number' })
|
||||
@IsMobilePhone('fa-IR')
|
||||
phone: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@ApiProperty({ example: 'zhivan', description: 'restaurant slug' })
|
||||
slug: string;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { IsNotEmpty, IsString, Length, IsMobilePhone } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class VerifyOtpDto {
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@ApiProperty({ example: '09362532122', description: 'Mobile number' })
|
||||
@IsMobilePhone('fa-IR')
|
||||
phone: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@ApiProperty({ example: '', description: 'Otp' })
|
||||
@Length(5)
|
||||
otp: string;
|
||||
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@ApiProperty({ example: 'zhivan', description: 'restaurant slug' })
|
||||
slug: string;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Entity, Enum, Index, Property } from '@mikro-orm/core';
|
||||
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
|
||||
export enum RefreshTokenType {
|
||||
USER = 'user',
|
||||
ADMIN = 'admin',
|
||||
}
|
||||
|
||||
@Entity({ tableName: 'refreshtokens' })
|
||||
@Index({ properties: ['ownerId', 'restId', 'type'] })
|
||||
@Index({ properties: ['hashedToken'] })
|
||||
@Index({ properties: ['expiresAt'] })
|
||||
export class RefreshToken extends BaseEntity {
|
||||
@Property({ type: 'varchar', length: 255 })
|
||||
hashedToken!: string;
|
||||
|
||||
@Property()
|
||||
ownerId!: string;
|
||||
|
||||
@Property()
|
||||
restId!: string;
|
||||
|
||||
@Enum(() => RefreshTokenType)
|
||||
type!: RefreshTokenType;
|
||||
|
||||
@Property({ type: 'timestamptz' })
|
||||
expiresAt!: Date;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
Inject,
|
||||
Logger,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { Request } from 'express';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { IAdminTokenPayload } from '../interfaces/IToken-payload';
|
||||
import { PERMISSIONS_KEY } from '../../../common/decorators/permissions.decorator';
|
||||
import { PermissionsService } from 'src/modules/roles/providers/permissions.service';
|
||||
|
||||
export interface AdminAuthRequest extends Request {
|
||||
adminId: string;
|
||||
restId: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AdminAuthGuard implements CanActivate {
|
||||
private readonly logger = new Logger(AdminAuthGuard.name);
|
||||
|
||||
constructor(
|
||||
@Inject(JwtService)
|
||||
private readonly jwtService: JwtService,
|
||||
@Inject(ConfigService)
|
||||
private readonly configService: ConfigService,
|
||||
private readonly permissionsService: PermissionsService,
|
||||
private readonly reflector: Reflector,
|
||||
) { }
|
||||
|
||||
async canActivate(context: ExecutionContext) {
|
||||
const request = context.switchToHttp().getRequest<AdminAuthRequest>();
|
||||
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
if (!token) {
|
||||
this.logger.warn('No token provided', {
|
||||
hasAuthHeader: !!request.headers.authorization,
|
||||
authHeader: request.headers.authorization ? 'present' : 'missing',
|
||||
headers: Object.keys(request.headers),
|
||||
});
|
||||
throw new UnauthorizedException('No token provided');
|
||||
}
|
||||
|
||||
try {
|
||||
// Get the JWT secret from config
|
||||
const secret = this.configService.getOrThrow<string>('JWT_SECRET');
|
||||
|
||||
// Verify token with the secret
|
||||
const payload = await this.jwtService.verifyAsync<IAdminTokenPayload>(token, {
|
||||
secret,
|
||||
});
|
||||
|
||||
if (!payload.adminId || !payload.restId) {
|
||||
this.logger.error('Invalid token payload structure', payload);
|
||||
throw new UnauthorizedException('Invalid token payload');
|
||||
}
|
||||
|
||||
request['adminId'] = payload.adminId;
|
||||
request['restId'] = payload.restId;
|
||||
|
||||
// check if the user has the required permissions
|
||||
const requiredPermissions =
|
||||
this.reflector.getAllAndOverride<string[]>(PERMISSIONS_KEY, [context.getHandler(), context.getClass()]) ?? [];
|
||||
|
||||
if (!requiredPermissions || requiredPermissions.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const adminPermission = await this.permissionsService.getAdminPermissions(payload.adminId, payload.restId);
|
||||
if (!adminPermission || !Array.isArray(adminPermission)) {
|
||||
this.logger.error('No permissions found', { adminId: payload.adminId, restId: payload.restId });
|
||||
throw new ForbiddenException('No permissions found');
|
||||
}
|
||||
|
||||
const hasPermission = requiredPermissions.every(p => adminPermission.includes(p));
|
||||
|
||||
if (!hasPermission) {
|
||||
this.logger.warn('Insufficient permissions', {
|
||||
adminId: payload.adminId,
|
||||
restId: payload.restId,
|
||||
required: requiredPermissions,
|
||||
has: adminPermission,
|
||||
});
|
||||
throw new ForbiddenException('You are not authorized to access this resource');
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (err instanceof ForbiddenException || err instanceof UnauthorizedException) {
|
||||
throw err;
|
||||
}
|
||||
const errorMessage = err instanceof Error ? err.message : 'Unknown error';
|
||||
const errorStack = err instanceof Error ? err.stack : undefined;
|
||||
this.logger.error('Token verification error in AdminAuthGuard', {
|
||||
error: errorMessage,
|
||||
stack: errorStack,
|
||||
});
|
||||
throw new UnauthorizedException('Invalid or expired token');
|
||||
}
|
||||
}
|
||||
|
||||
private extractTokenFromHeader(request: Request): string | undefined {
|
||||
const authHeader = request.headers.authorization || request.headers['authorization'];
|
||||
if (!authHeader) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const [type, token] = authHeader.split(' ');
|
||||
if (type?.toLowerCase() !== 'bearer' || !token) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, Inject, Logger } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { ITokenPayload } from '../interfaces/IToken-payload';
|
||||
|
||||
export interface UserAuthRequest extends Request {
|
||||
userId: string;
|
||||
restId: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthGuard implements CanActivate {
|
||||
private readonly logger = new Logger(AuthGuard.name);
|
||||
|
||||
constructor(
|
||||
@Inject(JwtService)
|
||||
private readonly jwtService: JwtService,
|
||||
@Inject(ConfigService)
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext) {
|
||||
const request = context.switchToHttp().getRequest<UserAuthRequest>();
|
||||
|
||||
try {
|
||||
const secret = this.configService.getOrThrow<string>('JWT_SECRET');
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
const slug = this.extractSlugFromHeader(request);
|
||||
if (!slug) {
|
||||
throw new UnauthorizedException('Slug is required');
|
||||
}
|
||||
if (!token) {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = await this.jwtService.verifyAsync<ITokenPayload>(token, {
|
||||
secret,
|
||||
});
|
||||
if (!payload.userId || !payload.restId) {
|
||||
this.logger.error('Invalid token payload structure', payload);
|
||||
throw new UnauthorizedException('Invalid token payload');
|
||||
}
|
||||
if (payload.slug !== slug) {
|
||||
throw new UnauthorizedException('Invalid slug');
|
||||
}
|
||||
request['userId'] = payload.userId;
|
||||
request['restId'] = payload.restId;
|
||||
} catch {
|
||||
throw new UnauthorizedException();
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (err instanceof UnauthorizedException) {
|
||||
throw err;
|
||||
}
|
||||
this.logger.error('error in AuthGuard', err);
|
||||
throw new UnauthorizedException('Invalid or expired token');
|
||||
}
|
||||
}
|
||||
private extractTokenFromHeader(request: Request): string | undefined {
|
||||
const [type, token] = request.headers.authorization?.split(' ') ?? [];
|
||||
return type === 'Bearer' ? token : undefined;
|
||||
}
|
||||
private extractSlugFromHeader(request: Request): string | undefined {
|
||||
// Fastify normalizes headers to lowercase, so check both cases
|
||||
const slug = (request.headers['x-slug'] || request.headers['X-Slug']) as string;
|
||||
return slug;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { CanActivate, ExecutionContext, Injectable, Inject, Logger } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { ITokenPayload } from '../interfaces/IToken-payload';
|
||||
|
||||
export interface UserOptionalAuthRequest extends Request {
|
||||
userId?: string;
|
||||
restId?: string;
|
||||
slug?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class OptionalAuthGuard implements CanActivate {
|
||||
private readonly logger = new Logger(OptionalAuthGuard.name);
|
||||
|
||||
constructor(
|
||||
@Inject(JwtService)
|
||||
private readonly jwtService: JwtService,
|
||||
@Inject(ConfigService)
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<UserOptionalAuthRequest>();
|
||||
const token = this.extractTokenFromHeader(request);
|
||||
const slug = this.extractSlugFromHeader(request);
|
||||
|
||||
// If no token is provided, allow the request without authentication
|
||||
if (!slug) {
|
||||
console.log('No slug provided');
|
||||
this.logger.warn('No slug provided');
|
||||
return false;
|
||||
}
|
||||
if (!token) {
|
||||
request['slug'] = slug;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Try to verify the token if it exists
|
||||
try {
|
||||
const secret = this.configService.getOrThrow<string>('JWT_SECRET');
|
||||
const payload = await this.jwtService.verifyAsync<ITokenPayload>(token, {
|
||||
secret,
|
||||
});
|
||||
|
||||
// Validate payload structure
|
||||
if (!payload.userId || !payload.restId) {
|
||||
this.logger.warn('Invalid token payload structure', payload);
|
||||
// Allow request but don't set user info
|
||||
request['slug'] = slug;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Validate slug if provided
|
||||
if (slug && payload.slug !== slug) {
|
||||
this.logger.warn('Token slug does not match header slug', {
|
||||
tokenSlug: payload.slug,
|
||||
headerSlug: slug,
|
||||
});
|
||||
// Allow request but don't set user info
|
||||
request['slug'] = slug;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Token is valid, set user info
|
||||
request['userId'] = payload.userId;
|
||||
request['restId'] = payload.restId;
|
||||
request['slug'] = slug;
|
||||
return true;
|
||||
} catch (err) {
|
||||
// Token is invalid or expired, but allow the request anyway
|
||||
this.logger.debug('Token verification failed in OptionalAuthGuard', {
|
||||
error: err instanceof Error ? err.message : 'Unknown error',
|
||||
});
|
||||
// Set restId from slug
|
||||
|
||||
request['slug'] = slug;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
private extractTokenFromHeader(request: Request): string | undefined {
|
||||
const [type, token] = request.headers.authorization?.split(' ') ?? [];
|
||||
return type === 'Bearer' ? token : undefined;
|
||||
}
|
||||
|
||||
private extractSlugFromHeader(request: Request): string | undefined {
|
||||
// Fastify normalizes headers to lowercase, so check both cases
|
||||
const slug = (request.headers['x-slug'] || request.headers['X-Slug']) as string;
|
||||
return slug;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException, Inject, Logger } from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
|
||||
@Injectable()
|
||||
export class SuperAdminAuthGuard implements CanActivate {
|
||||
private readonly logger = new Logger(SuperAdminAuthGuard.name);
|
||||
|
||||
constructor(
|
||||
@Inject(ConfigService)
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
|
||||
try {
|
||||
const credentials = this.extractBasicAuthCredentials(request);
|
||||
if (!credentials) {
|
||||
throw new UnauthorizedException('Basic authentication required');
|
||||
}
|
||||
|
||||
const { username, password } = credentials;
|
||||
const expectedUsername = this.configService.get<string>('SUPER_ADMIN_USERNAME') ?? 'danak@dsc.com';
|
||||
const expectedPassword = this.configService.get<string>('SUPER_ADMIN_PASSWORD') ?? 'DsCdAnAk?@ABC';
|
||||
if (username !== expectedUsername || password !== expectedPassword) {
|
||||
this.logger.warn(`Invalid super admin credentials attempt for username: ${username}`);
|
||||
throw new UnauthorizedException('Invalid credentials');
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
if (err instanceof UnauthorizedException) {
|
||||
throw err;
|
||||
}
|
||||
this.logger.error('error in SuperAdminAuthGuard', err);
|
||||
throw new UnauthorizedException('Authentication failed');
|
||||
}
|
||||
}
|
||||
|
||||
private extractBasicAuthCredentials(request: Request): { username: string; password: string } | null {
|
||||
const authHeader = request.headers.authorization;
|
||||
if (!authHeader) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const [type, encoded] = authHeader.split(' ');
|
||||
if (type?.toLowerCase() !== 'basic' || !encoded) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = Buffer.from(encoded, 'base64').toString('utf-8');
|
||||
const [username, password] = decoded.split(':');
|
||||
|
||||
if (!username || !password) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return { username, password };
|
||||
} catch (error) {
|
||||
this.logger.error('Failed to decode Basic Auth credentials', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
export interface ITokenPayload {
|
||||
userId: string;
|
||||
restId: string;
|
||||
slug: string;
|
||||
}
|
||||
|
||||
export interface IAdminTokenPayload {
|
||||
adminId: string;
|
||||
restId: string;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { Injectable, BadRequestException } from '@nestjs/common';
|
||||
import { RequestOtpDto } from '../dto/request-otp.dto';
|
||||
import { CacheService } from '../../utils/cache.service';
|
||||
import { SmsService } from '../../notifications/services/sms.service';
|
||||
import { UserService } from '../../users/providers/user.service';
|
||||
import { randomInt } from 'crypto';
|
||||
import { TokensService } from './tokens.service';
|
||||
import { RestRepository } from 'src/modules/restaurants/repositories/rest.repository';
|
||||
import { AuthMessage, RestMessage } from 'src/common/enums/message.enum';
|
||||
import { AdminRepository } from 'src/modules/admin/repositories/admin.repository';
|
||||
import { AdminLoginTransformer } from '../transformers/admin-login.transformer';
|
||||
import { UserLoginTransformer } from '../transformers/user-login.transformer';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { normalizePhone } from '../../utils/phone.util';
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
readonly ADMIN_PERMISSIONS_KEY = 'admin-perms';
|
||||
private OTP_EXPIRATION_TIME: number;
|
||||
constructor(
|
||||
private readonly cacheService: CacheService,
|
||||
private readonly smsService: SmsService,
|
||||
private readonly userService: UserService,
|
||||
private readonly tokensService: TokensService,
|
||||
private readonly restRepository: RestRepository,
|
||||
private readonly adminRepository: AdminRepository,
|
||||
private readonly configService: ConfigService,
|
||||
) {
|
||||
this.OTP_EXPIRATION_TIME = this.configService.get<number>('OTP_EXPIRATION_TIME') ?? 240;
|
||||
}
|
||||
|
||||
private userOtpKey(restaurantSlug: string, phone: string) {
|
||||
return `otp:${restaurantSlug}:${phone}`;
|
||||
}
|
||||
|
||||
private adminOtpKey(restaurantSlug: string, phone: string) {
|
||||
return `otp-admin:${restaurantSlug}:${phone}`;
|
||||
}
|
||||
|
||||
async requestOtp(dto: RequestOtpDto, isAdmin: boolean) {
|
||||
const { phone, slug } = dto;
|
||||
const normalizedPhone = normalizePhone(phone);
|
||||
const code = this.generateOtpCode();
|
||||
const key = isAdmin ? this.adminOtpKey(slug, normalizedPhone) : this.userOtpKey(slug, normalizedPhone);
|
||||
await this.cacheService.set(key, code, this.OTP_EXPIRATION_TIME);
|
||||
|
||||
await this.smsService.sendotp(normalizedPhone, code);
|
||||
|
||||
return { code: null };
|
||||
}
|
||||
|
||||
async verifyOtp(phone: string, slug: string, code: string) {
|
||||
const normalizedPhone = normalizePhone(phone);
|
||||
const key = this.userOtpKey(slug, normalizedPhone);
|
||||
const cachedCode = await this.cacheService.get(key);
|
||||
if (!cachedCode) throw new BadRequestException('OTP expired or not found');
|
||||
if (cachedCode !== code) throw new BadRequestException('Invalid OTP');
|
||||
|
||||
await this.cacheService.del(key);
|
||||
|
||||
const user = await this.userService.findOrCreateByPhone(normalizedPhone);
|
||||
|
||||
const rest = await this.restRepository.findOne({ slug });
|
||||
|
||||
if (!rest) {
|
||||
throw new BadRequestException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
const tokens = await this.tokensService.generateAccessAndRefreshToken(user.id, rest.id, false, slug);
|
||||
|
||||
const userResponse = UserLoginTransformer.transform(user, rest);
|
||||
|
||||
return { tokens, user: userResponse };
|
||||
}
|
||||
|
||||
async verifyOtpAdmin(phone: string, slug: string, code: string) {
|
||||
const normalizedPhone = normalizePhone(phone);
|
||||
const key = this.adminOtpKey(slug, normalizedPhone);
|
||||
const cachedCode = await this.cacheService.get(key);
|
||||
|
||||
if (!cachedCode) throw new BadRequestException('OTP expired or not found');
|
||||
|
||||
if (cachedCode !== code) throw new BadRequestException('Invalid OTP');
|
||||
await this.cacheService.del(key);
|
||||
|
||||
const admin = await this.adminRepository.findByPhoneAndRestaurantSlug(normalizedPhone, slug);
|
||||
|
||||
if (!admin) {
|
||||
throw new BadRequestException(AuthMessage.ADMIN_NOT_FOUND);
|
||||
}
|
||||
|
||||
const rest = await this.restRepository.findOne({ slug });
|
||||
|
||||
if (!rest) {
|
||||
throw new BadRequestException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, rest.id, true, slug);
|
||||
|
||||
const adminResponse = await AdminLoginTransformer.transform(admin, rest);
|
||||
|
||||
return { tokens, admin: adminResponse };
|
||||
}
|
||||
/**
|
||||
*
|
||||
to use for login directly from DSC
|
||||
*/
|
||||
async loginAdminForDsc(phone: string, slug: string) {
|
||||
const normalizedPhone = normalizePhone(phone);
|
||||
const admin = await this.adminRepository.findByPhoneAndRestaurantSlug(normalizedPhone, slug);
|
||||
|
||||
if (!admin) {
|
||||
throw new BadRequestException(AuthMessage.ADMIN_NOT_FOUND);
|
||||
}
|
||||
|
||||
const rest = await this.restRepository.findOne({ slug });
|
||||
|
||||
if (!rest) {
|
||||
throw new BadRequestException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
const tokens = await this.tokensService.generateAccessAndRefreshToken(admin.id, rest.id, true, slug);
|
||||
|
||||
const adminResponse = await AdminLoginTransformer.transform(admin, rest);
|
||||
|
||||
return { tokens, admin: adminResponse };
|
||||
}
|
||||
|
||||
private generateOtpCode(): string {
|
||||
const code = randomInt(10000, 100000);
|
||||
return code.toString();
|
||||
}
|
||||
|
||||
refreshToken(oldRefreshToken: string) {
|
||||
return this.tokensService.refreshToken(oldRefreshToken);
|
||||
}
|
||||
}
|
||||
Executable
+145
@@ -0,0 +1,145 @@
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { LockMode } from '@mikro-orm/core';
|
||||
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import dayjs from 'dayjs';
|
||||
|
||||
import { AuthMessage } from '../../../common/enums/message.enum';
|
||||
import { RefreshToken, RefreshTokenType } from '../entities/refresh-token.entity';
|
||||
import { IAdminTokenPayload, ITokenPayload } from '../interfaces/IToken-payload';
|
||||
import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity';
|
||||
|
||||
@Injectable()
|
||||
export class TokensService {
|
||||
private readonly logger = new Logger(TokensService.name);
|
||||
constructor(
|
||||
private readonly configService: ConfigService,
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly em: EntityManager,
|
||||
) {}
|
||||
|
||||
async generateAccessAndRefreshToken(
|
||||
ownerId: string,
|
||||
restaurantId: string,
|
||||
isAdmin: boolean,
|
||||
slug: string,
|
||||
em?: EntityManager,
|
||||
) {
|
||||
const refreshExpire = this.configService.getOrThrow<number>('REFRESH_TOKEN_EXPIRE');
|
||||
const accessExpire = this.configService.getOrThrow<number>('JWT_EXPIRATION_TIME');
|
||||
|
||||
const payload: ITokenPayload | IAdminTokenPayload = isAdmin
|
||||
? { adminId: ownerId, restId: restaurantId }
|
||||
: { userId: ownerId, restId: restaurantId, slug };
|
||||
|
||||
const accessToken = await this.generateAccessToken(payload, accessExpire);
|
||||
const refreshToken = this.generateRefreshToken();
|
||||
const type = isAdmin ? RefreshTokenType.ADMIN : RefreshTokenType.USER;
|
||||
|
||||
// Only pass em if it's a transaction manager (not this.em), otherwise pass undefined to trigger flush
|
||||
await this.storeRefreshToken(ownerId, restaurantId, refreshToken, type, em);
|
||||
|
||||
return {
|
||||
accessToken: { token: accessToken, expire: dayjs().add(accessExpire, 'seconds').valueOf() },
|
||||
refreshToken: { token: refreshToken, expire: dayjs().add(refreshExpire, 'day').valueOf() },
|
||||
};
|
||||
}
|
||||
|
||||
private generateAccessToken(payload: ITokenPayload | IAdminTokenPayload, expiresIn: number) {
|
||||
// Ensure expiresIn is passed as a string with time unit for reliability
|
||||
// JWT library accepts: number (seconds) or string with unit (e.g., "3600s", "1h")
|
||||
// Using string format is more explicit and prevents unit confusion
|
||||
return this.jwtService.signAsync(payload, { expiresIn: `${expiresIn}s` });
|
||||
}
|
||||
|
||||
async storeRefreshToken(
|
||||
ownerId: string,
|
||||
restId: string,
|
||||
refreshToken: string,
|
||||
type: RefreshTokenType,
|
||||
em?: EntityManager,
|
||||
) {
|
||||
const entityManager = em || this.em;
|
||||
const refreshExpire = this.configService.getOrThrow<number>('REFRESH_TOKEN_EXPIRE');
|
||||
const expiresAt = dayjs().add(refreshExpire, 'day').toDate();
|
||||
|
||||
const hashedToken = this.hashToken(refreshToken);
|
||||
|
||||
const token = entityManager.create(RefreshToken, {
|
||||
hashedToken,
|
||||
ownerId,
|
||||
restId,
|
||||
type,
|
||||
expiresAt,
|
||||
});
|
||||
|
||||
if (em) {
|
||||
// Within transaction, just persist (flush will be called by transaction)
|
||||
entityManager.persist(token);
|
||||
} else {
|
||||
// Outside transaction, persist and flush immediately
|
||||
await entityManager.persistAndFlush(token);
|
||||
}
|
||||
}
|
||||
|
||||
async refreshToken(oldRefreshToken: string) {
|
||||
const hashedToken = this.hashToken(oldRefreshToken);
|
||||
|
||||
// Use transaction to ensure atomicity and prevent race conditions
|
||||
return this.em.transactional(async em => {
|
||||
// Lock the token row to prevent concurrent refresh attempts
|
||||
// Using pessimistic write lock (FOR UPDATE) to prevent race conditions
|
||||
const token = await em.findOne(RefreshToken, { hashedToken }, { lockMode: LockMode.PESSIMISTIC_WRITE });
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException(AuthMessage.INVALID_REFRESH_TOKEN);
|
||||
}
|
||||
|
||||
// Check expiration
|
||||
if (dayjs(token.expiresAt).isBefore(dayjs())) {
|
||||
em.remove(token);
|
||||
await em.flush();
|
||||
throw new UnauthorizedException(AuthMessage.REFRESH_TOKEN_EXPIRED);
|
||||
}
|
||||
|
||||
// Store token data before removal
|
||||
const ownerId = token.ownerId;
|
||||
const restId = token.restId;
|
||||
const isAdmin = token.type === RefreshTokenType.ADMIN;
|
||||
|
||||
// Verify restaurant still exists
|
||||
const restaurant = await em.findOne(Restaurant, { id: restId });
|
||||
if (!restaurant) {
|
||||
throw new UnauthorizedException(AuthMessage.INVALID_REFRESH_TOKEN);
|
||||
}
|
||||
|
||||
try {
|
||||
// Generate new tokens first (before removing old token)
|
||||
// Pass the transaction EntityManager to ensure operations are within the transaction
|
||||
const tokens = await this.generateAccessAndRefreshToken(ownerId, restaurant.id, isAdmin, restaurant.slug, em);
|
||||
|
||||
// Remove old token only after new token is created
|
||||
em.remove(token);
|
||||
|
||||
// Persist changes atomically
|
||||
await em.flush();
|
||||
|
||||
return tokens;
|
||||
} catch (error) {
|
||||
this.logger.error('Failed to generate new tokens after refresh', error);
|
||||
// Transaction will rollback automatically, preserving the old token
|
||||
throw new UnauthorizedException('Failed to refresh token');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private generateRefreshToken() {
|
||||
return randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
private hashToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { Admin } from '../../admin/entities/admin.entity';
|
||||
import type { Restaurant } from '../../restaurants/entities/restaurant.entity';
|
||||
|
||||
export interface AdminLoginResponse {
|
||||
id: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
phone: string;
|
||||
role: string;
|
||||
permissions: string[];
|
||||
restaurant?: {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class AdminLoginTransformer {
|
||||
static async transform(admin: Admin, restaurant?: Restaurant): Promise<AdminLoginResponse> {
|
||||
// Find the AdminRole that matches the restaurant (or get the first one)
|
||||
let adminRole = admin.roles.getItems().find(r => (restaurant ? r.restaurant?.id === restaurant.id : true));
|
||||
|
||||
// If no match found, get the first one
|
||||
if (!adminRole && admin.roles.getItems().length > 0) {
|
||||
adminRole = admin.roles.getItems()[0];
|
||||
}
|
||||
|
||||
if (!adminRole) {
|
||||
return {
|
||||
id: admin.id,
|
||||
firstName: admin.firstName,
|
||||
lastName: admin.lastName,
|
||||
phone: admin.phone,
|
||||
role: '',
|
||||
permissions: [],
|
||||
restaurant: restaurant
|
||||
? {
|
||||
id: restaurant.id,
|
||||
name: restaurant.name,
|
||||
slug: restaurant.slug,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// Get the role from AdminRole
|
||||
const role = adminRole.role;
|
||||
if (!role) {
|
||||
return {
|
||||
id: admin.id,
|
||||
firstName: admin.firstName,
|
||||
lastName: admin.lastName,
|
||||
phone: admin.phone,
|
||||
role: '',
|
||||
permissions: [],
|
||||
restaurant: restaurant
|
||||
? {
|
||||
id: restaurant.id,
|
||||
name: restaurant.name,
|
||||
slug: restaurant.slug,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
// Extract permissions - ensure collection is loaded if needed
|
||||
let permissions: string[] = [];
|
||||
if (role.permissions) {
|
||||
if (role.permissions.isInitialized()) {
|
||||
permissions = role.permissions.getItems().map(p => p.name);
|
||||
} else {
|
||||
await role.permissions.loadItems();
|
||||
permissions = role.permissions.getItems().map(p => p.name);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: admin.id,
|
||||
firstName: admin.firstName,
|
||||
lastName: admin.lastName,
|
||||
phone: admin.phone,
|
||||
role: role.name,
|
||||
permissions,
|
||||
restaurant: restaurant
|
||||
? {
|
||||
id: restaurant.id,
|
||||
name: restaurant.name,
|
||||
slug: restaurant.slug,
|
||||
}
|
||||
: undefined,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { User } from '../../users/entities/user.entity';
|
||||
import type { Restaurant } from '../../restaurants/entities/restaurant.entity';
|
||||
|
||||
export interface UserLoginResponse {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName?: string;
|
||||
phone: string;
|
||||
|
||||
isActive?: boolean;
|
||||
restaurant: {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
}
|
||||
|
||||
export class UserLoginTransformer {
|
||||
static transform(user: User, restaurant: Restaurant): UserLoginResponse {
|
||||
return {
|
||||
id: user.id,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
phone: user.phone,
|
||||
isActive: user.isActive,
|
||||
restaurant: {
|
||||
id: restaurant.id,
|
||||
name: restaurant.name,
|
||||
slug: restaurant.slug,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
ApiCreatedResponse,
|
||||
ApiOkResponse,
|
||||
ApiNotFoundResponse,
|
||||
ApiParam,
|
||||
ApiBody,
|
||||
ApiBearerAuth,
|
||||
ApiHeader,
|
||||
} from '@nestjs/swagger';
|
||||
import { DeliveryService } from '../providers/delivery.service';
|
||||
import { CreateDeliveryDto } from '../dto/create-delivery.dto';
|
||||
import { UpdateDeliveryDto } from '../dto/update-delivery.dto';
|
||||
import { RestId } from 'src/common/decorators/rest-id.decorator';
|
||||
import { AuthGuard } from 'src/modules/auth/guards/auth.guard';
|
||||
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
|
||||
import { Delivery } from '../entities/delivery.entity';
|
||||
import { API_HEADER_SLUG } from 'src/common/constants';
|
||||
import { Permission } from 'src/common/enums/permission.enum';
|
||||
import { Permissions } from 'src/common/decorators/permissions.decorator';
|
||||
|
||||
@ApiTags('Delivery')
|
||||
@Controller()
|
||||
export class DeliveryController {
|
||||
constructor(private readonly deliveryService: DeliveryService) {}
|
||||
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('public/delivery-methods/restaurant')
|
||||
@ApiOperation({ summary: 'Get restaurant delivery methods' })
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
findAllDeliveryMethods(@RestId() restId: string) {
|
||||
return this.deliveryService.findAllForRestaurantId(restId);
|
||||
}
|
||||
|
||||
/*** Admin ***/
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_DELIVERY)
|
||||
@Post('admin/delivery-methods/restaurant')
|
||||
@ApiOperation({ summary: 'Create a delivery method for a restaurant' })
|
||||
@ApiBody({ type: CreateDeliveryDto })
|
||||
create(@Body() createDto: CreateDeliveryDto, @RestId() restId: string) {
|
||||
return this.deliveryService.create(restId, createDto);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_DELIVERY)
|
||||
@Get('admin/delivery-methods/restaurant')
|
||||
@ApiOperation({ summary: 'Get the restaurant delivery methods' })
|
||||
findRestaurantDeliveryMethods(@RestId() restId: string) {
|
||||
return this.deliveryService.findAllForRestaurantId(restId);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_DELIVERY)
|
||||
@Get('admin/delivery-methods/restaurant/:deliveryId')
|
||||
@ApiOperation({ summary: 'Get a restaurant delivery method by delivery ID' })
|
||||
@ApiParam({ name: 'deliveryId', description: 'Delivery method ID' })
|
||||
findOne(@Param('deliveryId') deliveryId: string, @RestId() restId: string) {
|
||||
return this.deliveryService.findOne(restId, deliveryId);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_DELIVERY)
|
||||
@Patch('admin/delivery-methods/restaurant/:deliveryId')
|
||||
@ApiOperation({ summary: 'Update a restaurant delivery method' })
|
||||
@ApiParam({ name: 'deliveryId', description: 'Delivery method ID' })
|
||||
@ApiBody({ type: UpdateDeliveryDto })
|
||||
update(@Param('deliveryId') deliveryId: string, @Body() updateDto: UpdateDeliveryDto, @RestId() restId: string) {
|
||||
return this.deliveryService.update(restId, deliveryId, updateDto);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_DELIVERY)
|
||||
@Delete('admin/delivery-methods/restaurant/:deliveryId')
|
||||
@ApiOperation({ summary: 'Delete a restaurant delivery method' })
|
||||
@ApiParam({ name: 'deliveryId', description: 'Delivery method ID' })
|
||||
remove(@Param('deliveryId') deliveryId: string, @RestId() restId: string) {
|
||||
return this.deliveryService.remove(restId, deliveryId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { DeliveryController } from './controllers/delivery.controller';
|
||||
import { DeliveryService } from './providers/delivery.service';
|
||||
import { RestaurantsModule } from '../restaurants/restaurants.module';
|
||||
import { Delivery } from './entities/delivery.entity';
|
||||
import { DeliveryRepository } from './repositories/delivery.repository';
|
||||
|
||||
@Module({
|
||||
controllers: [DeliveryController],
|
||||
providers: [DeliveryService, DeliveryRepository],
|
||||
exports: [DeliveryService, DeliveryRepository],
|
||||
imports: [MikroOrmModule.forFeature([Delivery]), JwtModule, RestaurantsModule],
|
||||
})
|
||||
export class DeliveryModule {}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { IsNumber, IsBoolean, IsOptional, IsString, Min, IsEnum } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
import { DeliveryFeeTypeEnum, DeliveryMethodEnum } from '../interface/delivery';
|
||||
|
||||
export class CreateDeliveryDto {
|
||||
@ApiProperty({ example: 'dineIn', description: 'Delivery method name', enum: DeliveryMethodEnum })
|
||||
@IsEnum(DeliveryMethodEnum)
|
||||
method!: DeliveryMethodEnum;
|
||||
|
||||
@ApiProperty({ example: 5000, description: 'Delivery fee' })
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
deliveryFee!: number;
|
||||
|
||||
@ApiProperty({ example: 100000, description: 'Minimum order price for free delivery' })
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
minOrderPrice!: number;
|
||||
|
||||
@ApiPropertyOptional({ example: 'توضیحات روش ارسال', description: 'Delivery method description' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
description?: string;
|
||||
|
||||
@ApiPropertyOptional({ example: true, description: 'Is this delivery method enabled?' })
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Type(() => Boolean)
|
||||
enabled?: boolean;
|
||||
|
||||
@ApiPropertyOptional({ example: 0, description: 'Display order for sorting delivery methods' })
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Type(() => Number)
|
||||
order?: number;
|
||||
|
||||
@ApiPropertyOptional({ example: 0, description: 'Kilometer number' })
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Type(() => Number)
|
||||
distanceBasedMinCost?: number;
|
||||
|
||||
@ApiPropertyOptional({ example: 0, description: 'Delivery fee per kilometer' })
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Type(() => Number)
|
||||
perKilometerFee?: number;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
example: DeliveryFeeTypeEnum.FIXED,
|
||||
description: 'Delivery fee type',
|
||||
enum: DeliveryFeeTypeEnum,
|
||||
})
|
||||
@IsOptional()
|
||||
@IsEnum(DeliveryFeeTypeEnum)
|
||||
deliveryFeeType!: DeliveryFeeTypeEnum;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateDeliveryDto } from './create-delivery.dto';
|
||||
|
||||
export class UpdateDeliveryDto extends PartialType(CreateDeliveryDto) {}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Entity, Property, Enum, ManyToOne } from '@mikro-orm/core';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
|
||||
import { DeliveryFeeTypeEnum, DeliveryMethodEnum } from '../interface/delivery';
|
||||
|
||||
@Entity({ tableName: 'deliveries' })
|
||||
export class Delivery extends BaseEntity {
|
||||
@Enum(() => DeliveryMethodEnum)
|
||||
method!: DeliveryMethodEnum;
|
||||
|
||||
@ManyToOne(() => Restaurant)
|
||||
restaurant!: Restaurant;
|
||||
|
||||
@Property({ type: 'decimal', precision: 10, scale: 0, default: 0 })
|
||||
deliveryFee: number = 0;
|
||||
|
||||
@Enum(() => DeliveryFeeTypeEnum)
|
||||
deliveryFeeType: DeliveryFeeTypeEnum = DeliveryFeeTypeEnum.FIXED;
|
||||
|
||||
@Property({ type: 'decimal', precision: 10, scale: 0, default: 0 })
|
||||
perKilometerFee: number | null = null;
|
||||
|
||||
@Property({ type: 'decimal', precision: 10, scale: 0, default: 0 })
|
||||
distanceBasedMinCost: number | null = null;
|
||||
|
||||
@Property({ type: 'decimal', precision: 10, scale: 0, default: 0 })
|
||||
minOrderPrice: number = 0;
|
||||
|
||||
@Property({ nullable: true })
|
||||
description?: string;
|
||||
|
||||
@Property({ default: true })
|
||||
enabled: boolean = true;
|
||||
|
||||
@Property({ type: 'integer', default: 0 })
|
||||
order: number = 0;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export enum DeliveryMethodEnum {
|
||||
DineIn = 'dineIn',
|
||||
CustomerPickup = 'customerPickup',
|
||||
DeliveryCar = 'deliveryCar',
|
||||
DeliveryCourier = 'deliveryCourier',
|
||||
}
|
||||
|
||||
export enum DeliveryFeeTypeEnum {
|
||||
FIXED = 'fixed',
|
||||
DISTANCE_BASED = 'distanceBased',
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { Injectable, NotFoundException, ConflictException } from '@nestjs/common';
|
||||
import { EntityManager, RequiredEntityData } from '@mikro-orm/postgresql';
|
||||
import { Delivery } from '../entities/delivery.entity';
|
||||
import { DeliveryRepository } from '../repositories/delivery.repository';
|
||||
import { CreateDeliveryDto } from '../dto/create-delivery.dto';
|
||||
import { UpdateDeliveryDto } from '../dto/update-delivery.dto';
|
||||
import { RestRepository } from '../../restaurants/repositories/rest.repository';
|
||||
import { DeliveryMethodEnum } from '../interface/delivery';
|
||||
import { DeliveryMessage } from 'src/common/enums/message.enum';
|
||||
|
||||
@Injectable()
|
||||
export class DeliveryService {
|
||||
constructor(
|
||||
private readonly deliveryRepository: DeliveryRepository,
|
||||
private readonly restRepository: RestRepository,
|
||||
private readonly em: EntityManager,
|
||||
) {}
|
||||
|
||||
async create(restId: string, createDto: CreateDeliveryDto): Promise<Delivery> {
|
||||
const restaurant = await this.restRepository.findOne({ id: restId });
|
||||
if (!restaurant) {
|
||||
throw new NotFoundException(DeliveryMessage.RESTAURANT_NOT_FOUND);
|
||||
}
|
||||
|
||||
// Check if the delivery method with the same name already exists for this restaurant
|
||||
const existing = await this.deliveryRepository.findOne({
|
||||
restaurant: { id: restId },
|
||||
method: createDto.method,
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
throw new ConflictException('این روش ارسال قبلاً برای این رستوران ثبت شده است.');
|
||||
}
|
||||
|
||||
const data: RequiredEntityData<Delivery> = {
|
||||
restaurant,
|
||||
method: createDto.method,
|
||||
deliveryFee: createDto.deliveryFee,
|
||||
minOrderPrice: createDto.minOrderPrice,
|
||||
description: createDto.description,
|
||||
enabled: createDto.enabled ?? true,
|
||||
order: createDto.order ?? 0,
|
||||
deliveryFeeType: createDto.deliveryFeeType,
|
||||
perKilometerFee: createDto.perKilometerFee ?? null,
|
||||
distanceBasedMinCost: createDto.distanceBasedMinCost ?? null,
|
||||
};
|
||||
|
||||
const delivery = this.deliveryRepository.create(data);
|
||||
await this.em.persistAndFlush(delivery);
|
||||
return delivery;
|
||||
}
|
||||
|
||||
async findAllForRestaurantId(restId: string): Promise<Delivery[]> {
|
||||
return this.deliveryRepository.find({ restaurant: { id: restId } }, { orderBy: { order: 'asc' } });
|
||||
}
|
||||
|
||||
async findOne(restId: string, deliveryId: string): Promise<Delivery> {
|
||||
const delivery = await this.deliveryRepository.findOne({
|
||||
id: deliveryId,
|
||||
restaurant: { id: restId },
|
||||
});
|
||||
|
||||
if (!delivery) {
|
||||
throw new NotFoundException(DeliveryMessage.DELIVERY_METHOD_NOT_FOUND);
|
||||
}
|
||||
|
||||
return delivery;
|
||||
}
|
||||
|
||||
async update(restId: string, deliveryId: string, updateDto: UpdateDeliveryDto): Promise<Delivery> {
|
||||
const delivery = await this.deliveryRepository.findOne({
|
||||
restaurant: { id: restId },
|
||||
id: deliveryId,
|
||||
});
|
||||
|
||||
if (!delivery) {
|
||||
throw new NotFoundException(DeliveryMessage.DELIVERY_METHOD_NOT_FOUND);
|
||||
}
|
||||
|
||||
// If method is being updated, check for conflicts
|
||||
if (updateDto.method !== undefined && updateDto.method !== delivery.method) {
|
||||
const existing = await this.deliveryRepository.findOne({
|
||||
restaurant: { id: restId },
|
||||
method: updateDto.method,
|
||||
id: { $ne: deliveryId },
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
throw new ConflictException('این روش ارسال قبلاً برای این رستوران ثبت شده است.');
|
||||
}
|
||||
}
|
||||
|
||||
this.em.assign(delivery, updateDto);
|
||||
await this.em.persistAndFlush(delivery);
|
||||
|
||||
return delivery;
|
||||
}
|
||||
|
||||
async remove(restId: string, deliveryId: string): Promise<void> {
|
||||
const delivery = await this.deliveryRepository.findOne({
|
||||
restaurant: { id: restId },
|
||||
id: deliveryId,
|
||||
});
|
||||
|
||||
if (!delivery) {
|
||||
throw new NotFoundException(DeliveryMessage.DELIVERY_METHOD_NOT_FOUND);
|
||||
}
|
||||
|
||||
await this.em.removeAndFlush(delivery);
|
||||
}
|
||||
|
||||
findAll(): DeliveryMethodEnum[] {
|
||||
return Object.values(DeliveryMethodEnum);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
|
||||
import { Delivery } from '../entities/delivery.entity';
|
||||
|
||||
@Injectable()
|
||||
export class DeliveryRepository extends EntityRepository<Delivery> {
|
||||
constructor(readonly em: EntityManager) {
|
||||
super(em, Delivery);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete } from '@nestjs/common';
|
||||
import { CategoryService } from '../providers/category.service';
|
||||
import { CreateCategoryDto } from '../dto/create-category.dto';
|
||||
import { UpdateCategoryDto } from '../dto/update-category.dto';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
ApiCreatedResponse,
|
||||
ApiOkResponse,
|
||||
ApiNotFoundResponse,
|
||||
ApiParam,
|
||||
ApiBody,
|
||||
ApiBearerAuth,
|
||||
ApiHeader,
|
||||
} from '@nestjs/swagger';
|
||||
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
|
||||
import { UseGuards } from '@nestjs/common';
|
||||
import { RestId } from 'src/common/decorators';
|
||||
import { Permission } from 'src/common/enums/permission.enum';
|
||||
import { Permissions } from 'src/common/decorators/permissions.decorator';
|
||||
import { API_HEADER_SLUG } from 'src/common/constants';
|
||||
|
||||
@ApiTags('category')
|
||||
@Controller()
|
||||
export class CategoryController {
|
||||
constructor(private readonly categoryService: CategoryService) { }
|
||||
|
||||
@Get('public/categories/restaurant/:slug')
|
||||
@ApiOperation({ summary: 'Get all categories by restaurant slug' })
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiParam({ name: 'slug', required: true, description: 'Restaurant Slug' })
|
||||
@ApiOkResponse({ description: 'List of all categories for the restaurant' })
|
||||
findAllByRestaurant(@Param('slug') slug: string) {
|
||||
return this.categoryService.findAllByRestaurant(slug);
|
||||
}
|
||||
|
||||
/*** Admin ***/
|
||||
|
||||
@ApiOperation({ summary: 'Create category' })
|
||||
@ApiBody({ type: CreateCategoryDto })
|
||||
@Permissions(Permission.MANAGE_CATEGORIES)
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Post('admin/categories')
|
||||
create(@Body() dto: CreateCategoryDto, @RestId() restId: string) {
|
||||
return this.categoryService.create(restId, dto);
|
||||
}
|
||||
@Permissions(Permission.MANAGE_CATEGORIES)
|
||||
@ApiOperation({ summary: 'my restaurant categories' })
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/categories')
|
||||
findAll(@RestId() restId: string) {
|
||||
return this.categoryService.findAllByRestaurantId(restId);
|
||||
}
|
||||
|
||||
@Permissions(Permission.MANAGE_CATEGORIES)
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/categories/:id')
|
||||
@ApiOperation({ summary: 'Get category' })
|
||||
@ApiParam({ name: 'id', required: true, type: String })
|
||||
findOne(@Param('id') id: string, @RestId() restId: string) {
|
||||
return this.categoryService.findOne(restId, id);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_CATEGORIES)
|
||||
@Patch('admin/categories/:id')
|
||||
@ApiOperation({ summary: 'Update category' })
|
||||
@ApiParam({ name: 'id' })
|
||||
@ApiBody({ type: UpdateCategoryDto })
|
||||
update(@Param('id') id: string, @Body() dto: UpdateCategoryDto, @RestId() restId: string) {
|
||||
return this.categoryService.update(restId, id, dto);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_CATEGORIES)
|
||||
@Delete('admin/categories/:id')
|
||||
@ApiOperation({ summary: 'Delete category' })
|
||||
@ApiParam({ name: 'id' })
|
||||
@ApiOkResponse({ description: 'Deleted' })
|
||||
remove(@Param('id') id: string, @RestId() restId: string) {
|
||||
return this.categoryService.remove(restId, id);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import { Controller, Get, Post, Body, Patch, Param, Delete, Query, UseGuards } from '@nestjs/common';
|
||||
import { FoodService } from '../providers/food.service';
|
||||
import { CreateFoodDto } from '../dto/create-food.dto';
|
||||
import { UpdateFoodDto } from '../dto/update-food.dto';
|
||||
import { FindFoodsDto } from '../dto/find-foods.dto';
|
||||
import {
|
||||
ApiTags,
|
||||
ApiOperation,
|
||||
ApiCreatedResponse,
|
||||
ApiOkResponse,
|
||||
ApiNotFoundResponse,
|
||||
ApiQuery,
|
||||
ApiBody,
|
||||
ApiParam,
|
||||
ApiBearerAuth,
|
||||
ApiHeader,
|
||||
} from '@nestjs/swagger';
|
||||
import { AdminAuthGuard } from 'src/modules/auth/guards/adminAuth.guard';
|
||||
import { RestId, UserId } from 'src/common/decorators';
|
||||
import { AuthGuard } from 'src/modules/auth/guards/auth.guard';
|
||||
import { OptionalAuthGuard } from 'src/modules/auth/guards/optinalAuth.guard';
|
||||
import { API_HEADER_SLUG } from 'src/common/constants';
|
||||
import { Permission } from 'src/common/enums/permission.enum';
|
||||
import { Permissions } from 'src/common/decorators/permissions.decorator';
|
||||
|
||||
@ApiTags('foods')
|
||||
@Controller()
|
||||
export class FoodController {
|
||||
constructor(private readonly foodsService: FoodService) { }
|
||||
|
||||
@Get('public/foods/restaurant/:slug')
|
||||
@ApiOperation({ summary: 'Get all foods by restaurant slug' })
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiParam({ name: 'slug', required: true, description: 'Restaurant Slug' })
|
||||
findAllByRestaurant(@Param('slug') slug: string) {
|
||||
return this.foodsService.findByWeekDateAndMealType(slug);
|
||||
}
|
||||
|
||||
@Get('public/foods/:foodId')
|
||||
@UseGuards(OptionalAuthGuard)
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'Get a food by id' })
|
||||
@ApiParam({ name: 'foodId', required: true })
|
||||
findPublicFoodById(@Param('foodId') foodId: string, @UserId() userId?: string): Promise<any> {
|
||||
const a = this.foodsService.findPublicById(foodId, userId);
|
||||
return a;
|
||||
}
|
||||
|
||||
@Post('public/foods/favorite/:foodId')
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'toggle a food as favorite' })
|
||||
@ApiParam({ name: 'foodId', required: true })
|
||||
setAsFavorute(@Param('foodId') foodId: string, @UserId() userId: string) {
|
||||
return this.foodsService.toggleFavorite(userId, foodId);
|
||||
}
|
||||
|
||||
@Get('public/foods/favorite')
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiBearerAuth()
|
||||
@ApiOperation({ summary: 'get my favorites' })
|
||||
getMyFavorites(@UserId() userId: string, @RestId() restId: string) {
|
||||
return this.foodsService.getMyFavorites(userId, restId);
|
||||
}
|
||||
|
||||
/* ---------------------------------- Admin ---------------------------------- */
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_FOODS)
|
||||
@Post('admin/foods')
|
||||
@ApiOperation({ summary: 'Create a new food' })
|
||||
@ApiBody({ type: CreateFoodDto })
|
||||
create(@Body() createFoodDto: CreateFoodDto, @RestId() restId: string) {
|
||||
return this.foodsService.create(restId, createFoodDto);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_FOODS)
|
||||
@Get('admin/foods')
|
||||
@ApiOperation({ summary: 'Get a paginated list of foods' })
|
||||
@ApiQuery({ name: 'page', required: false, type: Number })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number })
|
||||
@ApiQuery({ name: 'search', required: false, type: String })
|
||||
@ApiQuery({ name: 'orderBy', required: false, type: String })
|
||||
@ApiQuery({ name: 'order', required: false, enum: ['asc', 'desc'] })
|
||||
@ApiQuery({ name: 'categoryId', required: false, type: String })
|
||||
@ApiQuery({ name: 'isActive', required: false, type: Boolean })
|
||||
async findAll(@Query() dto: FindFoodsDto, @RestId() restId: string) {
|
||||
const result = await this.foodsService.findAll(restId, dto);
|
||||
return result;
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_FOODS)
|
||||
@Get('admin/foods/:id')
|
||||
@ApiOperation({ summary: 'Get a food by id' })
|
||||
@ApiParam({ name: 'id', required: true })
|
||||
findById(@Param('id') id: string, @RestId() restId: string) {
|
||||
return this.foodsService.findAdminById(restId, id);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_FOODS)
|
||||
@Patch('admin/foods/:id')
|
||||
@ApiOperation({ summary: 'Update a food' })
|
||||
@ApiParam({ name: 'id', required: true })
|
||||
@ApiBody({ type: UpdateFoodDto })
|
||||
update(@Param('id') id: string, @Body() updateFoodDto: UpdateFoodDto, @RestId() restId: string) {
|
||||
return this.foodsService.update(restId, id, updateFoodDto);
|
||||
}
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_FOODS)
|
||||
@Delete('admin/foods/:id')
|
||||
@ApiOperation({ summary: 'Delete (soft) a food' })
|
||||
@ApiParam({ name: 'id', required: true })
|
||||
remove(@Param('id') id: string, @RestId() restId: string) {
|
||||
return this.foodsService.remove(restId, id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron } from '@nestjs/schedule';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { Inventory } from '../../inventory/entities/inventory.entity';
|
||||
|
||||
@Injectable()
|
||||
export class FoodStockCrone {
|
||||
private readonly logger = new Logger(FoodStockCrone.name);
|
||||
|
||||
constructor(private readonly em: EntityManager) {}
|
||||
|
||||
// run every day at 00:03
|
||||
@Cron('3 0 * * *', {
|
||||
name: 'resetAvailableStock',
|
||||
timeZone: 'UTC',
|
||||
})
|
||||
async handleCron() {
|
||||
try {
|
||||
this.logger.debug('Starting daily inventory reset (availableStock = totalStock)');
|
||||
|
||||
const inventories = await this.em.find(Inventory, {});
|
||||
if (!inventories || inventories.length === 0) {
|
||||
this.logger.debug('No inventory records found to reset');
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log(`Resetting available stock for ${inventories.length} inventory records`);
|
||||
|
||||
await this.em.transactional(async em => {
|
||||
for (const inv of inventories) {
|
||||
// reload inside transaction to avoid concurrency issues
|
||||
const record = await em.findOne(Inventory, { id: inv.id });
|
||||
if (!record) continue;
|
||||
record.availableStock = record.totalStock;
|
||||
em.persist(record);
|
||||
}
|
||||
await em.flush();
|
||||
});
|
||||
|
||||
this.logger.log('Daily inventory reset completed');
|
||||
} catch (err) {
|
||||
this.logger.error(`FoodStockCrone failed: ${err?.message}`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { IsString, IsOptional, IsBoolean, IsInt, Min } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class CreateCategoryDto {
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'ایرانی' })
|
||||
title!: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Type(() => Boolean)
|
||||
@ApiPropertyOptional({ example: true })
|
||||
isActive?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'https://cdn.example.com/avatar.png' })
|
||||
avatarUrl?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 1 })
|
||||
order?: number;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import { Type } from 'class-transformer';
|
||||
import {
|
||||
ArrayUnique,
|
||||
IsArray,
|
||||
IsBoolean,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsNotEmpty,
|
||||
IsNumber,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Max,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { MealType } from '../interface/food.interface';
|
||||
|
||||
export class CreateFoodDto {
|
||||
@IsNotEmpty()
|
||||
@IsString()
|
||||
@ApiProperty()
|
||||
categoryId: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'قرمه سبزی' })
|
||||
title?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'توضیحات غذا' })
|
||||
desc?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@ApiPropertyOptional({ type: [String] })
|
||||
content?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ArrayUnique()
|
||||
@IsInt({ each: true })
|
||||
@Min(0, { each: true })
|
||||
@Max(6, { each: true })
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ type: [Number], example: [0, 1, 2, 3, 4, 5, 6] })
|
||||
weekDays?: number[];
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ArrayUnique()
|
||||
@IsEnum(MealType, { each: true })
|
||||
@ApiPropertyOptional({ enum: MealType, isArray: true })
|
||||
mealTypes?: MealType[];
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 120000 })
|
||||
price?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 15 })
|
||||
prepareTime?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@ApiPropertyOptional({ example: true })
|
||||
@Type(() => Boolean)
|
||||
isActive?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@ApiPropertyOptional({ type: [String] })
|
||||
images?: string[];
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@ApiPropertyOptional({ example: false })
|
||||
@Type(() => Boolean)
|
||||
inPlaceServe?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@ApiPropertyOptional({ example: false })
|
||||
@Type(() => Boolean)
|
||||
pickupServe?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 0 })
|
||||
discount?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiProperty({ example: 50 })
|
||||
dailyStock: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@ApiPropertyOptional({ example: false })
|
||||
@Type(() => Boolean)
|
||||
isSpecialOffer?: boolean;
|
||||
|
||||
@IsOptional()
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 1 })
|
||||
order?: number;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { IsOptional, IsNumber, IsString, IsIn, IsBoolean } from 'class-validator';
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { Type } from 'class-transformer';
|
||||
|
||||
export class FindFoodsDto {
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 1 })
|
||||
page?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsNumber()
|
||||
@Type(() => Number)
|
||||
@ApiPropertyOptional({ example: 10 })
|
||||
limit?: number;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional()
|
||||
search?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional({ example: 'createdAt' })
|
||||
orderBy?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsIn(['asc', 'desc'])
|
||||
@ApiPropertyOptional({ example: 'desc' })
|
||||
order?: 'asc' | 'desc';
|
||||
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@ApiPropertyOptional()
|
||||
categoryId?: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsBoolean()
|
||||
@Type(() => Boolean)
|
||||
@ApiPropertyOptional({ example: true })
|
||||
isActive?: boolean;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateCategoryDto } from './create-category.dto';
|
||||
|
||||
export class UpdateCategoryDto extends PartialType(CreateCategoryDto) {}
|
||||
@@ -0,0 +1,4 @@
|
||||
import { PartialType } from '@nestjs/swagger';
|
||||
import { CreateFoodDto } from './create-food.dto';
|
||||
|
||||
export class UpdateFoodDto extends PartialType(CreateFoodDto) {}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Entity, Index, Property, Collection, OneToMany, ManyToOne } from '@mikro-orm/core';
|
||||
import { Food } from './food.entity';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity';
|
||||
|
||||
@Entity({ tableName: 'categories' })
|
||||
@Index({ properties: ['restaurant', 'isActive'] })
|
||||
@Index({ properties: ['isActive'] })
|
||||
export class Category extends BaseEntity {
|
||||
@Property()
|
||||
title!: string;
|
||||
|
||||
@OneToMany(() => Food, food => food.category)
|
||||
foods = new Collection<Food>(this);
|
||||
|
||||
@Property({ default: true })
|
||||
isActive: boolean = true;
|
||||
|
||||
@ManyToOne(() => Restaurant)
|
||||
restaurant!: Restaurant;
|
||||
|
||||
@Property({ nullable: true })
|
||||
avatarUrl?: string;
|
||||
|
||||
@Property({ type: 'int', nullable: true })
|
||||
order?: number;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Entity, ManyToOne, Unique } from '@mikro-orm/core';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { User } from '../../users/entities/user.entity';
|
||||
import { Food } from '../../foods/entities/food.entity';
|
||||
|
||||
@Entity({ tableName: 'favorites' })
|
||||
@Unique({ properties: ['user', 'food'] })
|
||||
export class Favorite extends BaseEntity {
|
||||
@ManyToOne(() => User)
|
||||
user: User;
|
||||
|
||||
@ManyToOne(() => Food)
|
||||
food: Food;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Cascade, Collection, Entity, Index, ManyToOne, OneToMany, Property, OneToOne } from '@mikro-orm/core';
|
||||
import { Category } from './category.entity';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { Restaurant } from '../../../modules/restaurants/entities/restaurant.entity';
|
||||
import { Review } from 'src/modules/review/entities/review.entity';
|
||||
import { Inventory } from 'src/modules/inventory/entities/inventory.entity';
|
||||
import { MealType } from '../interface/food.interface';
|
||||
import { Favorite } from './favorite.entity';
|
||||
|
||||
@Entity({ tableName: 'foods' })
|
||||
@Index({ properties: ['restaurant', 'isActive'] })
|
||||
@Index({ properties: ['category', 'isActive'] })
|
||||
@Index({ properties: ['isActive'] })
|
||||
export class Food extends BaseEntity {
|
||||
@ManyToOne(() => Restaurant)
|
||||
restaurant: Restaurant;
|
||||
|
||||
@ManyToOne(() => Category)
|
||||
category: Category;
|
||||
|
||||
@OneToMany(() => Review, review => review.food, { cascade: [Cascade.ALL], orphanRemoval: true })
|
||||
reviews = new Collection<Review>(this);
|
||||
|
||||
@OneToOne(() => Inventory, {
|
||||
mappedBy: 'food',
|
||||
nullable: true,
|
||||
})
|
||||
inventory?: Inventory;
|
||||
|
||||
@OneToMany(() => Favorite, favorite => favorite.food)
|
||||
favorites = new Collection<Favorite>(this);
|
||||
|
||||
@Property({ nullable: true })
|
||||
title?: string;
|
||||
|
||||
@Property({ type: 'text', nullable: true })
|
||||
desc?: string;
|
||||
|
||||
@Property({ type: 'json', nullable: true })
|
||||
content?: string[];
|
||||
|
||||
@Property({ type: 'decimal', precision: 10, scale: 2, nullable: true })
|
||||
price?: number;
|
||||
|
||||
@Property({ type: 'int', nullable: true })
|
||||
order?: number;
|
||||
|
||||
@Property({ type: 'int', nullable: true })
|
||||
prepareTime?: number; // in minutes
|
||||
|
||||
@Property({ type: 'jsonb', default: [] })
|
||||
weekDays: number[] = [0, 1, 2, 3, 4, 5, 6];
|
||||
|
||||
@Property({ type: 'jsonb', default: [] })
|
||||
mealTypes: MealType[] = [];
|
||||
|
||||
@Property({ type: 'boolean', default: true })
|
||||
isActive: boolean = true;
|
||||
|
||||
@Property({ type: 'json', nullable: true })
|
||||
images?: string[];
|
||||
|
||||
@Property({ type: 'boolean', default: false })
|
||||
inPlaceServe: boolean = false;
|
||||
|
||||
@Property({ type: 'boolean', default: false })
|
||||
pickupServe: boolean = false;
|
||||
|
||||
@Property({ type: 'float', default: null })
|
||||
score?: number | null = null;
|
||||
|
||||
@Property({ type: 'float', default: 0 })
|
||||
discount: number = 0;
|
||||
|
||||
@Property({ type: 'boolean', default: false })
|
||||
isSpecialOffer: boolean = false;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { FoodService } from './providers/food.service';
|
||||
import { FoodStockCrone } from './crone/food.crone';
|
||||
import { FoodController } from './controllers/food.controller';
|
||||
import { CategoryController } from './controllers/category.controller';
|
||||
import { CategoryService } from './providers/category.service';
|
||||
import { FoodRepository } from './repositories/food.repository';
|
||||
import { CategoryRepository } from './repositories/category.repository';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Category } from './entities/category.entity';
|
||||
import { Food } from './entities/food.entity';
|
||||
import { RestaurantsModule } from '../restaurants/restaurants.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { UtilsModule } from '../utils/utils.module';
|
||||
import { Favorite } from './entities/favorite.entity';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
MikroOrmModule.forFeature([Food, Category, Favorite]),
|
||||
RestaurantsModule,
|
||||
AuthModule,
|
||||
JwtModule,
|
||||
UtilsModule,
|
||||
],
|
||||
controllers: [FoodController, CategoryController],
|
||||
providers: [FoodService, CategoryService, FoodRepository, CategoryRepository, FoodStockCrone],
|
||||
exports: [FoodRepository, CategoryRepository],
|
||||
})
|
||||
export class FoodModule {}
|
||||
@@ -0,0 +1,6 @@
|
||||
export enum MealType {
|
||||
BREAKFAST = 'breakfast',
|
||||
LUNCH = 'lunch',
|
||||
DINNER = 'dinner',
|
||||
SNACK = 'snack',
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { CreateCategoryDto } from '../dto/create-category.dto';
|
||||
import { UpdateCategoryDto } from '../dto/update-category.dto';
|
||||
import { CategoryRepository } from '../repositories/category.repository';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { RequiredEntityData } from '@mikro-orm/core';
|
||||
import { Category } from '../entities/category.entity';
|
||||
import { CategoryMessage, RestMessage } from 'src/common/enums/message.enum';
|
||||
import { Restaurant } from 'src/modules/restaurants/entities/restaurant.entity';
|
||||
|
||||
@Injectable()
|
||||
export class CategoryService {
|
||||
constructor(
|
||||
private readonly categoryRepository: CategoryRepository,
|
||||
private readonly em: EntityManager,
|
||||
) { }
|
||||
|
||||
async create(restId: string, dto: CreateCategoryDto): Promise<Category> {
|
||||
const restaurant = await this.em.findOne(Restaurant, { id: restId });
|
||||
if (!restaurant) {
|
||||
throw new NotFoundException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
const data: RequiredEntityData<Category> = {
|
||||
title: dto.title,
|
||||
isActive: dto.isActive ?? true,
|
||||
restaurant: restaurant,
|
||||
avatarUrl: dto.avatarUrl,
|
||||
};
|
||||
|
||||
const category = this.categoryRepository.create(data);
|
||||
await this.em.persistAndFlush(category);
|
||||
return category;
|
||||
}
|
||||
|
||||
async findAllByRestaurant(slug: string): Promise<Category[]> {
|
||||
const restaurant = await this.em.findOne(Restaurant, { slug });
|
||||
if (!restaurant || !restaurant.id) {
|
||||
throw new NotFoundException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
return this.categoryRepository.find({ restaurant: restaurant, isActive: true });
|
||||
}
|
||||
|
||||
async findAllByRestaurantId(restId: string): Promise<Category[]> {
|
||||
return this.categoryRepository.find({ restaurant: { id: restId } });
|
||||
}
|
||||
|
||||
// async findAll(opts?: { restId?: string; isActive?: boolean }): Promise<Category[]> {
|
||||
// const where: FilterQuery<Category> = {};
|
||||
// if (opts?.restId) where.restId = opts.restId;
|
||||
// if (opts && typeof opts.isActive === 'boolean') where.isActive = opts.isActive;
|
||||
// const cats = await this.categoryRepository.find(where, { populate: ['foods'] });
|
||||
|
||||
// // Return plain objects to avoid circular references during JSON serialization
|
||||
// return cats.map(cat => ({
|
||||
// id: cat.id,
|
||||
// title: cat.title,
|
||||
// isActive: cat.isActive,
|
||||
// restId: cat.restId,
|
||||
// avatarUrl: cat.avatarUrl,
|
||||
// createdAt: cat.createdAt,
|
||||
// updatedAt: cat.updatedAt,
|
||||
// foods: cat.foods.getItems().map(f => ({ id: f.id, title: f.title })),
|
||||
// })) as unknown as Category[];
|
||||
// }
|
||||
|
||||
async findOne(restId: string, id: string): Promise<Category> {
|
||||
const cat = await this.categoryRepository.findOne({ id, restaurant: { id: restId } }, { populate: ['foods'] });
|
||||
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
|
||||
return {
|
||||
id: cat.id,
|
||||
title: cat.title,
|
||||
isActive: cat.isActive,
|
||||
restaurant: cat.restaurant,
|
||||
avatarUrl: cat.avatarUrl,
|
||||
createdAt: cat.createdAt,
|
||||
updatedAt: cat.updatedAt,
|
||||
foods: cat.foods.getItems().map(f => ({ id: f.id, title: f.title })),
|
||||
} as unknown as Category;
|
||||
}
|
||||
|
||||
async findRestaurantCategories(restId: string): Promise<Category> {
|
||||
const cat = await this.categoryRepository.findOne({ restaurant: { id: restId } }, { populate: ['foods'] });
|
||||
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
|
||||
return {
|
||||
id: cat.id,
|
||||
title: cat.title,
|
||||
isActive: cat.isActive,
|
||||
restaurant: cat.restaurant,
|
||||
avatarUrl: cat.avatarUrl,
|
||||
createdAt: cat.createdAt,
|
||||
updatedAt: cat.updatedAt,
|
||||
} as unknown as Category;
|
||||
}
|
||||
|
||||
async update(restId: string, id: string, dto: UpdateCategoryDto): Promise<Category> {
|
||||
const cat = await this.categoryRepository.findOne({ id, restaurant: { id: restId } });
|
||||
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
this.em.assign(cat, dto);
|
||||
await this.em.persistAndFlush(cat);
|
||||
return cat;
|
||||
}
|
||||
|
||||
async remove(restId: string, id: string): Promise<void> {
|
||||
const cat = await this.categoryRepository.findOne({ id, restaurant: { id: restId } });
|
||||
if (!cat) throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
cat.deletedAt = new Date();
|
||||
await this.em.persistAndFlush(cat);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { CreateFoodDto } from '../dto/create-food.dto';
|
||||
import { FindFoodsDto } from '../dto/find-foods.dto';
|
||||
import { FoodRepository } from '../repositories/food.repository';
|
||||
import { CategoryRepository } from '../repositories/category.repository';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { RequiredEntityData, FilterQuery } from '@mikro-orm/core';
|
||||
import { Food } from '../entities/food.entity';
|
||||
import { CategoryMessage, FoodMessage, RestMessage } from 'src/common/enums/message.enum';
|
||||
import { RestRepository } from 'src/modules/restaurants/repositories/rest.repository';
|
||||
import { CacheService } from '../../utils/cache.service';
|
||||
import { Favorite } from '../entities/favorite.entity';
|
||||
import { MealType } from '../interface/food.interface';
|
||||
import { Inventory } from 'src/modules/inventory/entities/inventory.entity';
|
||||
|
||||
@Injectable()
|
||||
export class FoodService {
|
||||
private readonly FOODS_BY_RESTAURANT_CACHE_KEY_PREFIX = 'foods:restaurant:';
|
||||
private readonly FOODS_CACHE_TTL = 600; // 10 minutes in seconds
|
||||
|
||||
constructor(
|
||||
private readonly foodRepository: FoodRepository,
|
||||
private readonly categoryRepository: CategoryRepository,
|
||||
private readonly restRepository: RestRepository,
|
||||
private readonly em: EntityManager,
|
||||
private readonly cacheService: CacheService,
|
||||
) { }
|
||||
|
||||
async create(restId: string, createFoodDto: CreateFoodDto) {
|
||||
const { categoryId, dailyStock = 0, ...rest } = createFoodDto;
|
||||
const restaurant = await this.restRepository.findOne({ id: restId });
|
||||
if (!restaurant) {
|
||||
throw new NotFoundException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
const category = await this.categoryRepository.findOne({ id: categoryId, restaurant: { id: restId } });
|
||||
if (!category) {
|
||||
throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
const { food, inventory } = await this.em.transactional(async em => {
|
||||
// prepare data with defaults for required fields so repository.create typing is satisfied
|
||||
const data: RequiredEntityData<Food> = {
|
||||
desc: rest.desc,
|
||||
isActive: rest.isActive ?? true,
|
||||
inPlaceServe: rest.inPlaceServe ?? false,
|
||||
pickupServe: rest.pickupServe ?? false,
|
||||
discount: rest.discount ?? 0,
|
||||
isSpecialOffer: rest.isSpecialOffer ?? false,
|
||||
order: rest.order ?? null,
|
||||
// map single-title/content DTO to localized fields
|
||||
title: rest.title,
|
||||
content: rest.content,
|
||||
// numeric/array fields
|
||||
price: rest.price ?? 0,
|
||||
prepareTime: rest.prepareTime ?? 0,
|
||||
images: rest.images ?? undefined,
|
||||
// new fields
|
||||
weekDays: rest.weekDays ?? [0, 1, 2, 3, 4, 5, 6],
|
||||
mealTypes: rest.mealTypes ?? [],
|
||||
restaurant: restaurant,
|
||||
category: category,
|
||||
};
|
||||
|
||||
const food = em.create(Food, data);
|
||||
const newInventoryRecord = em.create(Inventory, {
|
||||
food: food,
|
||||
availableStock: dailyStock,
|
||||
totalStock: dailyStock,
|
||||
});
|
||||
|
||||
await em.flush();
|
||||
return { food, inventory: newInventoryRecord };
|
||||
});
|
||||
|
||||
// Re-load created entities with the primary EM to ensure they're attached
|
||||
const savedFood = food?.id
|
||||
? await this.foodRepository.findOne({ id: food.id }, { populate: ['category', 'restaurant'] })
|
||||
: null;
|
||||
const savedInventory = inventory?.id ? await this.em.findOne(Inventory, { id: inventory.id }) : inventory;
|
||||
|
||||
return { food: savedFood ?? food, inventory: savedInventory ?? inventory };
|
||||
}
|
||||
|
||||
findAll(restId: string, dto: FindFoodsDto) {
|
||||
return this.foodRepository.findAllPaginated(restId, dto);
|
||||
}
|
||||
|
||||
/**
|
||||
* Public food detail (only active foods are visible).
|
||||
*/
|
||||
async findPublicById(foodId: string, userId?: string): Promise<any> {
|
||||
const food = await this.foodRepository.findOne({ id: foodId, isActive: true }, { populate: ['category', 'inventory'] });
|
||||
if (!food) throw new NotFoundException(FoodMessage.NOT_FOUND);
|
||||
let isFavorite = false;
|
||||
if (userId) {
|
||||
isFavorite = (await this.em.count(Favorite, { user: { id: userId }, food: { id: foodId } })) > 0;
|
||||
}
|
||||
return {
|
||||
...food,
|
||||
isFavorite,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Admin food detail (scoped to the authenticated restaurant).
|
||||
*/
|
||||
async findAdminById(restId: string, id: string): Promise<Food> {
|
||||
const food = await this.foodRepository.findOne({ id, restaurant: { id: restId } }, { populate: ['category','inventory'] });
|
||||
|
||||
if (!food) throw new NotFoundException(FoodMessage.NOT_FOUND);
|
||||
return food;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find active foods for a restaurant based on current week day and meal type in Iran timezone.
|
||||
* @param slug - Restaurant slug identifier
|
||||
* @returns Array of active foods matching current day and meal time
|
||||
*/
|
||||
async findByWeekDateAndMealType(slug: string): Promise<Food[]> {
|
||||
const restaurant = await this.restRepository.findOne({ slug });
|
||||
if (!restaurant) {
|
||||
throw new NotFoundException(RestMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
const { iranWeekDay, mealType } = this.getCurrentIranTimeContext();
|
||||
|
||||
const queryFilter: FilterQuery<Food> = {
|
||||
restaurant: { slug },
|
||||
isActive: true,
|
||||
// weekDays: { $contains: iranWeekDay },
|
||||
// ...(mealType ? { mealTypes: { $contains: mealType } } : {}),
|
||||
} as unknown as FilterQuery<Food>;
|
||||
|
||||
return this.foodRepository.find(queryFilter, { populate: ['category'] });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current Iran timezone context (weekday and meal type).
|
||||
* @returns Object containing Iran weekday (0-6, where 0=Saturday) and current meal type
|
||||
*/
|
||||
private getCurrentIranTimeContext(): { iranWeekDay: number; mealType: MealType | null } {
|
||||
const nowInIran = new Date(new Date().toLocaleString('en-US', { timeZone: 'Asia/Tehran' }));
|
||||
const weekDay = nowInIran.getDay(); // 0 = Sunday, 6 = Saturday
|
||||
const currentHour = nowInIran.getHours();
|
||||
|
||||
// Convert to Iran weekday: Saturday=0, Sunday=1, ..., Friday=6
|
||||
// JavaScript: Sunday=0, Monday=1, ..., Saturday=6
|
||||
// Iran week: Saturday=0, Sunday=1, ..., Friday=6
|
||||
const iranWeekDay = (weekDay + 1) % 7;
|
||||
|
||||
const mealType = this.getMealTypeByHour(currentHour);
|
||||
|
||||
return { iranWeekDay, mealType };
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine meal type based on current hour in Iran timezone.
|
||||
* @param hour - Current hour (0-23)
|
||||
* @returns Meal type or null if outside meal hours
|
||||
*/
|
||||
private getMealTypeByHour(hour: number): MealType | null {
|
||||
const MEAL_TIME_RANGES = {
|
||||
BREAKFAST: { start: 6, end: 11 },
|
||||
LUNCH: { start: 11, end: 15 },
|
||||
SNACK: { start: 15, end: 19 },
|
||||
DINNER: { start: 19, end: 24 },
|
||||
} as const;
|
||||
|
||||
if (hour >= MEAL_TIME_RANGES.BREAKFAST.start && hour < MEAL_TIME_RANGES.BREAKFAST.end) {
|
||||
return MealType.BREAKFAST;
|
||||
}
|
||||
if (hour >= MEAL_TIME_RANGES.LUNCH.start && hour < MEAL_TIME_RANGES.LUNCH.end) {
|
||||
return MealType.LUNCH;
|
||||
}
|
||||
if (hour >= MEAL_TIME_RANGES.SNACK.start && hour < MEAL_TIME_RANGES.SNACK.end) {
|
||||
return MealType.SNACK;
|
||||
}
|
||||
if (hour >= MEAL_TIME_RANGES.DINNER.start && hour < MEAL_TIME_RANGES.DINNER.end) {
|
||||
return MealType.DINNER;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async update(restId: string, id: string, dto: Partial<CreateFoodDto>): Promise<Food> {
|
||||
const { categoryId, dailyStock, ...rest } = dto;
|
||||
const food = await this.foodRepository.findOne({ id, restaurant: { id: restId } }, { populate: ['restaurant'] });
|
||||
if (!food) {
|
||||
throw new NotFoundException(FoodMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
// attach new categories if provided (adds, does not attempt to preserve/remove existing ones)
|
||||
if (categoryId) {
|
||||
const category = await this.categoryRepository.findOne({ id: categoryId, restaurant: { id: restId } });
|
||||
|
||||
if (!category) {
|
||||
throw new NotFoundException(CategoryMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
this.em.assign(food, { category: category });
|
||||
}
|
||||
|
||||
// assign other fields from DTO (excluding dailyStock handled below)
|
||||
this.em.assign(food, rest);
|
||||
|
||||
// Persist food and update/create related inventory atomically
|
||||
await this.em.transactional(async em => {
|
||||
await em.persistAndFlush(food);
|
||||
|
||||
if (typeof dailyStock !== 'undefined') {
|
||||
const inventoryRecord = await em.findOne(Inventory, { food: food });
|
||||
if (inventoryRecord) {
|
||||
inventoryRecord.totalStock = dailyStock;
|
||||
} else {
|
||||
em.create(Inventory, {
|
||||
food: food,
|
||||
availableStock: dailyStock,
|
||||
totalStock: dailyStock,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await em.flush();
|
||||
});
|
||||
|
||||
// Re-load the food to ensure populated relations and stable instance
|
||||
const savedFood = await this.foodRepository.findOne({ id: food.id }, { populate: ['category', 'restaurant'] });
|
||||
|
||||
// Invalidate cache for the restaurant if present (optional)
|
||||
// await this.invalidateRestaurantFoodsCache(savedFood?.restaurant?.slug);
|
||||
|
||||
return savedFood ?? food;
|
||||
}
|
||||
|
||||
async remove(restId: string, id: string): Promise<void> {
|
||||
const food = await this.foodRepository.findOne({ id, restaurant: { id: restId } }, { populate: ['restaurant'] });
|
||||
if (!food) {
|
||||
throw new NotFoundException(FoodMessage.NOT_FOUND);
|
||||
}
|
||||
|
||||
// const restaurantSlug = food.restaurant.slug;
|
||||
food.deletedAt = new Date();
|
||||
await this.em.persistAndFlush(food);
|
||||
|
||||
// Invalidate cache for the restaurant
|
||||
// await this.invalidateRestaurantFoodsCache(restaurantSlug);
|
||||
}
|
||||
|
||||
|
||||
async toggleFavorite(userId: string, foodId: string) {
|
||||
|
||||
const favorite = await this.em.findOne(Favorite, { user: userId, food: foodId });
|
||||
if (favorite) {
|
||||
return this.em.removeAndFlush(favorite);
|
||||
}
|
||||
const newFavorite = this.em.create(Favorite, {
|
||||
user: userId,
|
||||
food: foodId,
|
||||
});
|
||||
return this.em.persistAndFlush(newFavorite);
|
||||
}
|
||||
|
||||
|
||||
async getMyFavorites(userId: string,restId: string) {
|
||||
return this.em.find(Favorite, { user: userId, food: { restaurant: { id: restId } } }, { populate: ['food'] });
|
||||
}
|
||||
/**
|
||||
* Invalidate cache for restaurant foods
|
||||
*/
|
||||
// private async invalidateRestaurantFoodsCache(slug: string): Promise<void> {
|
||||
// const cacheKey = `${this.FOODS_BY_RESTAURANT_CACHE_KEY_PREFIX}${slug}`;
|
||||
// await this.cacheService.del(cacheKey);
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
|
||||
import { Category } from '../entities/category.entity';
|
||||
|
||||
@Injectable()
|
||||
export class CategoryRepository extends EntityRepository<Category> {
|
||||
constructor(readonly em: EntityManager) {
|
||||
super(em, Category);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
|
||||
import { FilterQuery } from '@mikro-orm/core';
|
||||
import { Food } from '../entities/food.entity';
|
||||
import { PaginatedResult } from 'src/common/interfaces/pagination.interface';
|
||||
|
||||
type FindFoodsOpts = {
|
||||
page?: number;
|
||||
limit?: number;
|
||||
search?: string;
|
||||
orderBy?: string;
|
||||
order?: 'asc' | 'desc';
|
||||
categoryId?: string;
|
||||
isActive?: boolean;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
export class FoodRepository extends EntityRepository<Food> {
|
||||
constructor(readonly em: EntityManager) {
|
||||
super(em, Food);
|
||||
}
|
||||
/**
|
||||
* Find foods with pagination and optional filters.
|
||||
* Supports: search (title/content), categoryId, isActive, ordering.
|
||||
*/
|
||||
async findAllPaginated(restId: string, opts: FindFoodsOpts = {}): Promise<PaginatedResult<Food>> {
|
||||
const { page = 1, limit = 10, search, orderBy = 'createdAt', order = 'desc', categoryId, isActive } = opts;
|
||||
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
const where: FilterQuery<Food> = { restaurant: { id: restId } };
|
||||
|
||||
if (typeof isActive === 'boolean') {
|
||||
where.isActive = isActive;
|
||||
}
|
||||
|
||||
if (search) {
|
||||
const pattern = `%${search}%`;
|
||||
where.$or = [{ title: { $ilike: pattern } }, { desc: { $ilike: pattern } }];
|
||||
}
|
||||
|
||||
if (categoryId) {
|
||||
// filter by related category (Food has a single `category` relation)
|
||||
Object.assign(where, { category: { id: categoryId } } as unknown as FilterQuery<Food>);
|
||||
}
|
||||
|
||||
const [data, total] = await this.findAndCount(where, {
|
||||
limit,
|
||||
offset,
|
||||
orderBy: { [orderBy]: order.toLowerCase() as 'asc' | 'desc' },
|
||||
populate: ['category','inventory'],
|
||||
});
|
||||
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages,
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export enum NotificationQueueNameEnum {
|
||||
SMS = 'sms',
|
||||
PUSH = 'push',
|
||||
IN_APP = 'in-app',
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { Controller, Get, Body, Param, UseGuards, Query, Patch, Put, Post } from '@nestjs/common';
|
||||
import { ApiTags, ApiOperation, ApiBearerAuth, ApiParam, ApiQuery, ApiHeader } from '@nestjs/swagger';
|
||||
import { NotificationService } from '../services/notification.service';
|
||||
import { NotificationPreferenceService } from '../services/notification-preference.service';
|
||||
import { AuthGuard } from '../../auth/guards/auth.guard';
|
||||
import { UserId } from '../../../common/decorators/user-id.decorator';
|
||||
import { AdminAuthGuard } from '../../auth/guards/adminAuth.guard';
|
||||
import { RestId } from '../../../common/decorators/rest-id.decorator';
|
||||
import { UpdatePreferenceDto } from '../dto/update-preference.dto';
|
||||
import { CreatePreferenceDto } from '../dto/create-preference.dto';
|
||||
import { AdminId } from 'src/common/decorators/admin-id.decorator';
|
||||
import { API_HEADER_SLUG } from 'src/common/constants/index';
|
||||
import { NotificationMessage } from 'src/common/enums/message.enum';
|
||||
import { SuperAdminAuthGuard } from 'src/modules/auth/guards/superAdminAuth.guard';
|
||||
import { Permissions } from 'src/common/decorators/permissions.decorator';
|
||||
import { Permission } from 'src/common/enums/permission.enum';
|
||||
|
||||
@ApiTags('notifications')
|
||||
@Controller()
|
||||
export class NotificationsController {
|
||||
constructor(
|
||||
private readonly notificationService: NotificationService,
|
||||
private readonly preferenceService: NotificationPreferenceService,
|
||||
) { }
|
||||
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('public/notifications')
|
||||
@ApiOperation({ summary: 'Get user restaurant notifications' })
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number, description: 'Number of items to return (default: 50)' })
|
||||
@ApiQuery({
|
||||
name: 'cursor',
|
||||
required: false,
|
||||
type: String,
|
||||
description: 'Cursor for pagination (ID of the last item from previous page)',
|
||||
})
|
||||
@ApiQuery({ name: 'status', required: false, enum: ['seen', 'unseen'], description: 'Filter by notification status' })
|
||||
async getUserNotifications(
|
||||
@UserId() userId: string,
|
||||
@RestId() restaurantId: string,
|
||||
@Query('limit') limit?: number,
|
||||
@Query('cursor') cursor?: string,
|
||||
@Query('status') status?: 'seen' | 'unseen',
|
||||
) {
|
||||
return await this.notificationService.findByUserAndRestaurant(
|
||||
userId,
|
||||
restaurantId,
|
||||
limit ? parseInt(limit.toString(), 10) : 50,
|
||||
cursor,
|
||||
status,
|
||||
);
|
||||
}
|
||||
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('public/notifications/unseen-count')
|
||||
@ApiOperation({ summary: 'Get unseen notifications count for user' })
|
||||
@ApiHeader(API_HEADER_SLUG)
|
||||
async getUserUnseenCount(@UserId() userId: string, @RestId() restaurantId: string) {
|
||||
const count = await this.notificationService.countUnseenByUserAndRestaurant(userId, restaurantId);
|
||||
return { count };
|
||||
}
|
||||
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Put('public/notifications/:id')
|
||||
@ApiOperation({ summary: 'Read a notification ' })
|
||||
@ApiParam({ name: 'id', description: 'Notification ID' })
|
||||
async readNotificationUser(@RestId() restaurantId: string, @Param('id') id: string, @UserId() userId: string) {
|
||||
await this.notificationService.readNotificationAsUser(id, userId, restaurantId);
|
||||
return { message: NotificationMessage.READ_SUCCESS };
|
||||
}
|
||||
|
||||
@UseGuards(AuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Put('public/notifications/read/all')
|
||||
@ApiOperation({ summary: 'Read all notification ' })
|
||||
async readAllNotificationUser(@RestId() restaurantId: string, @UserId() userId: string) {
|
||||
await this.notificationService.readAllNotifsAsUser(userId, restaurantId);
|
||||
return { message: NotificationMessage.READ_SUCCESS };
|
||||
}
|
||||
/* ***************** Admin Endpoints ***************** */
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/notifications')
|
||||
@ApiOperation({ summary: 'Get Admin notifications' })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number })
|
||||
@ApiQuery({
|
||||
name: 'cursor',
|
||||
required: false,
|
||||
type: String,
|
||||
description: 'Cursor for pagination (ID of the last item from previous page)',
|
||||
})
|
||||
@ApiQuery({ name: 'status', required: false, enum: ['seen', 'unseen'], description: 'Filter by notification status' })
|
||||
async getAdminNotifications(
|
||||
@AdminId() adminId: string,
|
||||
@RestId() restaurantId: string,
|
||||
@Query('limit') limit?: number,
|
||||
@Query('cursor') cursor?: string,
|
||||
@Query('status') status?: 'seen' | 'unseen',
|
||||
) {
|
||||
const parsedLimit = limit ? parseInt(limit.toString(), 10) : 50;
|
||||
return await this.notificationService.findByRestaurant(restaurantId, adminId, parsedLimit, cursor, status);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/notifications/unseen-count')
|
||||
@ApiOperation({ summary: 'Get unseen notifications count for admin' })
|
||||
async getAdminUnseenCount(@AdminId() adminId: string, @RestId() restaurantId: string) {
|
||||
const count = await this.notificationService.countUnseenByRestaurant(adminId, restaurantId);
|
||||
return { count };
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Put('admin/notifications/:id')
|
||||
@ApiOperation({ summary: 'Read a notification ' })
|
||||
@ApiParam({ name: 'id', description: 'Notification ID' })
|
||||
async readNotificationAdmin(@RestId() restaurantId: string, @AdminId() adminId: string, @Param('id') id: string) {
|
||||
await this.notificationService.readNotificationAdmin(id, adminId, restaurantId);
|
||||
return { message: NotificationMessage.READ_SUCCESS };
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Put('admin/notifications/read/all')
|
||||
@ApiOperation({ summary: 'Read all notification ' })
|
||||
async readAllNotificationAdmin(@RestId() restaurantId: string, @AdminId() adminId: string, @Param('id') id: string) {
|
||||
await this.notificationService.readAllNotifsAsAdmin(adminId, restaurantId);
|
||||
return { message: NotificationMessage.READ_SUCCESS };
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_SETTINGS)
|
||||
@Get('admin/notification-preferences')
|
||||
@ApiOperation({ summary: 'Get all notification preferences for a restaurant' })
|
||||
async getPreferences(@RestId() restaurantId: string) {
|
||||
return this.preferenceService.findByRestaurant(restaurantId);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_SETTINGS)
|
||||
@Patch('admin/notification-preferences/:id')
|
||||
@ApiOperation({ summary: 'Update notification channels' })
|
||||
@ApiParam({ name: 'id', description: 'Notification preference ID' })
|
||||
async updatePreference(
|
||||
@RestId() restaurantId: string,
|
||||
@Param('id') preferenceId: string,
|
||||
@Body() dto: UpdatePreferenceDto,
|
||||
) {
|
||||
return this.preferenceService.updatePreference(preferenceId, restaurantId, dto);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Permissions(Permission.MANAGE_SETTINGS)
|
||||
@Post('admin/notification-preferences')
|
||||
@ApiOperation({ summary: 'Create notification preference' })
|
||||
async createPreference(
|
||||
@RestId() restaurantId: string,
|
||||
@Body() dto: CreatePreferenceDto,
|
||||
) {
|
||||
return this.preferenceService.create(restaurantId, dto);
|
||||
}
|
||||
|
||||
@UseGuards(AdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('admin/notifications/sms-usage')
|
||||
@ApiOperation({ summary: 'Get SMS usage for my restaurant' })
|
||||
async getRestaurantSmsUsage(@RestId() restaurantId: string) {
|
||||
const smsCount = await this.notificationService.getSmsCountByRestaurantId(restaurantId);
|
||||
return { smsCount };
|
||||
}
|
||||
|
||||
// super admin endpoints
|
||||
|
||||
@UseGuards(SuperAdminAuthGuard)
|
||||
@ApiBearerAuth()
|
||||
@Get('super-admin/notifications/sms-count')
|
||||
@ApiOperation({ summary: 'Get SMS count for each restaurant with pagination' })
|
||||
@ApiQuery({ name: 'page', required: false, type: Number, description: 'Page number (default: 1)', minimum: 1 })
|
||||
@ApiQuery({ name: 'limit', required: false, type: Number, description: 'Items per page (default: 10)', minimum: 1 })
|
||||
async getSmsCount(
|
||||
@Query('page') page?: number,
|
||||
@Query('limit') limit?: number,
|
||||
) {
|
||||
const parsedPage = page ? parseInt(page.toString(), 10) : 1;
|
||||
const parsedLimit = limit ? parseInt(limit.toString(), 10) : 10;
|
||||
return await this.notificationService.getSmsCountByRestaurant(parsedPage, parsedLimit);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { Cron } from '@nestjs/schedule';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { Notification } from '../entities/notification.entity';
|
||||
|
||||
@Injectable()
|
||||
export class NotificationCrone {
|
||||
private readonly logger = new Logger(NotificationCrone.name);
|
||||
|
||||
constructor(private readonly em: EntityManager) {}
|
||||
|
||||
// run every day at 03:00 (3:00 AM)
|
||||
@Cron('0 3 * * *', {
|
||||
name: 'deleteOldNotifications',
|
||||
timeZone: 'UTC',
|
||||
})
|
||||
async handleCron() {
|
||||
try {
|
||||
this.logger.debug('Starting daily notification cleanup (removing notifications older than 24 hours)');
|
||||
|
||||
// Calculate the date 24 hours ago
|
||||
const twentyFourHoursAgo = new Date();
|
||||
twentyFourHoursAgo.setHours(twentyFourHoursAgo.getHours() - 24);
|
||||
|
||||
// Find all notifications created more than 24 hours ago
|
||||
const oldNotifications = await this.em.find(Notification, {
|
||||
createdAt: { $lt: twentyFourHoursAgo },
|
||||
});
|
||||
|
||||
if (!oldNotifications || oldNotifications.length === 0) {
|
||||
this.logger.debug('No old notifications found to delete');
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log(`Found ${oldNotifications.length} notifications older than 24 hours to delete`);
|
||||
|
||||
// Delete the old notifications
|
||||
await this.em.removeAndFlush(oldNotifications);
|
||||
|
||||
this.logger.log(`Successfully deleted ${oldNotifications.length} old notifications`);
|
||||
} catch (err) {
|
||||
this.logger.error(`NotificationCrone failed: ${err?.message}`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import type { ExecutionContext } from '@nestjs/common';
|
||||
import { createParamDecorator } from '@nestjs/common';
|
||||
import type { AuthenticatedSocket } from '../guards/ws-admin-auth.guard';
|
||||
|
||||
/**
|
||||
* Extract restaurant ID from authenticated WebSocket client
|
||||
* Use this decorator in WebSocket handlers to get the restId from the authenticated admin
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* @SubscribeMessage('get:notifications')
|
||||
* handleGetNotifications(@WsRestId() restId: string) {
|
||||
* // restId is automatically extracted from authenticated admin
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export const WsRestId = createParamDecorator((data: unknown, ctx: ExecutionContext): string => {
|
||||
const client = ctx.switchToWs().getClient<AuthenticatedSocket>();
|
||||
const restId = client.restId;
|
||||
|
||||
if (!restId) {
|
||||
throw new Error('Restaurant ID not found. Ensure WsAdminAuthGuard is applied.');
|
||||
}
|
||||
|
||||
return restId;
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { IsString, IsNotEmpty, IsOptional, IsArray, IsObject } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class CreateNotificationDto {
|
||||
@ApiProperty({ description: 'Notification title' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
title: string;
|
||||
|
||||
@ApiProperty({ description: 'Notification message' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
message: string;
|
||||
|
||||
@ApiProperty({ description: 'Notification type' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
type: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'User ID' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
userId?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Phone number for SMS' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
phoneNumber?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Push notification tokens', type: [String] })
|
||||
@IsArray()
|
||||
@IsString({ each: true })
|
||||
@IsOptional()
|
||||
pushTokens?: string[];
|
||||
|
||||
@ApiPropertyOptional({ description: 'Additional data' })
|
||||
@IsObject()
|
||||
@IsOptional()
|
||||
data?: Record<string, any>;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { IsNotEmpty, IsEnum, IsArray } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { NotifTitleEnum } from '../interfaces/notification.interface';
|
||||
import { NotifChannelEnum } from '../interfaces/notification.interface';
|
||||
|
||||
export class CreatePreferenceDto {
|
||||
@ApiProperty({
|
||||
description: 'Notification title/type (e.g., order.created, review.created)',
|
||||
enum: NotifTitleEnum,
|
||||
example: NotifTitleEnum.ORDER_CREATED,
|
||||
})
|
||||
@IsEnum(NotifTitleEnum)
|
||||
@IsNotEmpty()
|
||||
title!: NotifTitleEnum;
|
||||
|
||||
@ApiProperty({
|
||||
description: 'Notification type (SMS, PUSH, BOTH, or NONE)',
|
||||
enum: NotifChannelEnum,
|
||||
example: NotifChannelEnum.SMS,
|
||||
})
|
||||
@IsArray()
|
||||
@IsEnum(NotifChannelEnum, { each: true })
|
||||
channels!: NotifChannelEnum[];
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { IsString, IsNotEmpty, IsOptional, IsObject } from 'class-validator';
|
||||
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
|
||||
|
||||
export class SendNotificationDto {
|
||||
@ApiProperty({ description: 'Restaurant ID (ULID)' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
restaurantId: string;
|
||||
|
||||
@ApiPropertyOptional({ description: 'User ID (ULID)' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
userId?: string;
|
||||
|
||||
@ApiProperty({ description: 'Notification type (e.g., ORDER_CONFIRMED, PAYMENT_FAILED)' })
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
notificationType: string;
|
||||
|
||||
@ApiProperty({ description: 'Notification payload' })
|
||||
@IsObject()
|
||||
@IsNotEmpty()
|
||||
payload: {
|
||||
title?: string;
|
||||
message: string;
|
||||
body?: string;
|
||||
phoneNumber?: string;
|
||||
pushToken?: string;
|
||||
data?: Record<string, any>;
|
||||
templateId?: string;
|
||||
parameters?: Array<{ name: string; value: string }>;
|
||||
};
|
||||
|
||||
@ApiPropertyOptional({ description: 'Idempotency key to prevent duplicates' })
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
idempotencyKey?: string;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsArray, IsEnum } from 'class-validator';
|
||||
import { NotifChannelEnum } from '../interfaces/notification.interface';
|
||||
|
||||
export class UpdatePreferenceDto {
|
||||
@ApiProperty({
|
||||
description: 'Notification channels (can be empty or contain any enum values)',
|
||||
enum: NotifChannelEnum,
|
||||
isArray: true,
|
||||
example: ['sms', 'push'],
|
||||
})
|
||||
@IsArray()
|
||||
@IsEnum(NotifChannelEnum, { each: true })
|
||||
channels!: NotifChannelEnum[];
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Entity, Property, ManyToOne, Unique } from '@mikro-orm/core';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
|
||||
import { NotifTitleEnum } from '../interfaces/notification.interface';
|
||||
import { NotifChannelEnum } from '../interfaces/notification.interface';
|
||||
|
||||
@Entity({ tableName: 'notification_preferences' })
|
||||
@Unique({ properties: ['restaurant', 'title'] })
|
||||
export class NotificationPreference extends BaseEntity {
|
||||
@ManyToOne(() => Restaurant)
|
||||
restaurant!: Restaurant;
|
||||
|
||||
@Property()
|
||||
title!: NotifTitleEnum;
|
||||
|
||||
@Property({ type: 'json' })
|
||||
channels: NotifChannelEnum[] = [];
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Entity, Property, ManyToOne, Enum } from '@mikro-orm/core';
|
||||
import { BaseEntity } from '../../../common/entities/base.entity';
|
||||
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
|
||||
import { User } from '../../users/entities/user.entity';
|
||||
import { NotifTitleEnum } from '../interfaces/notification.interface';
|
||||
import { Admin } from 'src/modules/admin/entities/admin.entity';
|
||||
|
||||
@Entity({ tableName: 'notifications' })
|
||||
export class Notification extends BaseEntity {
|
||||
@ManyToOne(() => Restaurant)
|
||||
restaurant!: Restaurant;
|
||||
|
||||
@ManyToOne(() => User, { nullable: true })
|
||||
user?: User;
|
||||
|
||||
@ManyToOne(() => Admin, { nullable: true })
|
||||
admin?: Admin;
|
||||
|
||||
@Enum(() => NotifTitleEnum)
|
||||
title!: NotifTitleEnum;
|
||||
|
||||
@Property()
|
||||
content!: string;
|
||||
|
||||
@Property({ nullable: true })
|
||||
seenAt?: Date;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Entity, Property, ManyToOne, PrimaryKey } from '@mikro-orm/core';
|
||||
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
|
||||
|
||||
@Entity({ tableName: 'sms_logs' })
|
||||
export class SmsLog {
|
||||
@PrimaryKey()
|
||||
id!: number;
|
||||
|
||||
@ManyToOne(() => Restaurant)
|
||||
restaurant!: Restaurant;
|
||||
|
||||
@Property()
|
||||
phone!: string;
|
||||
|
||||
@Property()
|
||||
createdAt: Date = new Date();
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export class SmsSentEvent {
|
||||
constructor(
|
||||
public readonly phoneNumber: string,
|
||||
public readonly restaurantId: string,
|
||||
) {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { CanActivate, ExecutionContext, Injectable, Logger, Inject } from '@nestjs/common';
|
||||
import { WsException } from '@nestjs/websockets';
|
||||
import { Socket } from 'socket.io';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { IAdminTokenPayload } from '../../auth/interfaces/IToken-payload';
|
||||
|
||||
export interface AuthenticatedSocket extends Socket {
|
||||
adminId?: string;
|
||||
restId?: string;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class WsAdminAuthGuard implements CanActivate {
|
||||
private readonly logger = new Logger(WsAdminAuthGuard.name);
|
||||
|
||||
constructor(
|
||||
@Inject(JwtService)
|
||||
private readonly jwtService: JwtService,
|
||||
@Inject(ConfigService)
|
||||
private readonly configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const client: Socket = context.switchToWs().getClient<Socket>();
|
||||
|
||||
try {
|
||||
const token = this.extractToken(client);
|
||||
|
||||
if (!token) {
|
||||
this.logger.warn('No token provided in WebSocket connection', {
|
||||
socketId: client.id,
|
||||
auth: client.handshake.auth,
|
||||
query: client.handshake.query,
|
||||
});
|
||||
throw new WsException('Authentication required');
|
||||
}
|
||||
|
||||
const secret = this.configService.getOrThrow<string>('JWT_SECRET');
|
||||
const payload = await this.jwtService.verifyAsync<IAdminTokenPayload>(token, {
|
||||
secret,
|
||||
});
|
||||
|
||||
if (!payload.adminId || !payload.restId) {
|
||||
this.logger.error('Invalid token payload structure', payload);
|
||||
throw new WsException('Invalid token payload');
|
||||
}
|
||||
|
||||
// Attach admin info to socket
|
||||
(client as AuthenticatedSocket).adminId = payload.adminId;
|
||||
(client as AuthenticatedSocket).restId = payload.restId;
|
||||
|
||||
this.logger.log(`Admin authenticated via WebSocket: ${payload.adminId}, restId: ${payload.restId}`);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof WsException) {
|
||||
throw error;
|
||||
}
|
||||
this.logger.error('WebSocket authentication error', {
|
||||
error: error instanceof Error ? error.message : 'Unknown error',
|
||||
socketId: client.id,
|
||||
});
|
||||
throw new WsException('Authentication failed');
|
||||
}
|
||||
}
|
||||
|
||||
private extractToken(client: Socket): string | undefined {
|
||||
// Try to get token from handshake auth (recommended for socket.io)
|
||||
const auth = client.handshake.auth;
|
||||
const authToken = (auth?.token as string | undefined) || (auth?.authorization as string | undefined);
|
||||
|
||||
if (authToken) {
|
||||
// If it's "Bearer <token>", extract just the token
|
||||
if (typeof authToken === 'string' && authToken.startsWith('Bearer ')) {
|
||||
return authToken.substring(7);
|
||||
}
|
||||
return authToken;
|
||||
}
|
||||
|
||||
// Try to get from query parameters (fallback)
|
||||
const queryToken = client.handshake.query?.token || client.handshake.query?.authorization;
|
||||
|
||||
if (queryToken) {
|
||||
if (typeof queryToken === 'string' && queryToken.startsWith('Bearer ')) {
|
||||
return queryToken.substring(7);
|
||||
}
|
||||
return queryToken as string;
|
||||
}
|
||||
|
||||
// Try to get from headers (if available)
|
||||
const headers = client.handshake.headers;
|
||||
const authHeader = headers.authorization || headers['authorization'];
|
||||
|
||||
if (authHeader && typeof authHeader === 'string') {
|
||||
const [type, token] = authHeader.split(' ');
|
||||
if (type?.toLowerCase() === 'bearer' && token) {
|
||||
return token;
|
||||
}
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// private extractToken(client: Socket): string | undefined {
|
||||
// const tryGet = (...values: any[]) => values.find(v => typeof v === 'string' && v.length > 0);
|
||||
|
||||
// let token = tryGet(
|
||||
// client.handshake.auth?.token,
|
||||
// client.handshake.auth?.authorization,
|
||||
// client.handshake.query?.token,
|
||||
// client.handshake.query?.authorization,
|
||||
// client.handshake.headers.authorization,
|
||||
// client.handshake.headers['authorization'],
|
||||
// );
|
||||
|
||||
// if (!token) return undefined;
|
||||
|
||||
// if (token.startsWith('Bearer ')) {
|
||||
// token = token.slice(7);
|
||||
// }
|
||||
|
||||
// return token;
|
||||
// }
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { NotifTitleEnum, recipientType } from './notification.interface';
|
||||
|
||||
export interface SmsNotificationQueueJob {
|
||||
recipient: recipientType;
|
||||
templateId: string;
|
||||
restaurantId: string;
|
||||
parameters?: Record<string, string>;
|
||||
}
|
||||
export interface PushNotificationQueueJob {
|
||||
title: string;
|
||||
content: string;
|
||||
icon: string;
|
||||
action: {
|
||||
type: string; //view order
|
||||
url: string;
|
||||
};
|
||||
pushToken?: string; // FCM token for push notifications
|
||||
pushTokens?: string[]; // Multiple FCM tokens for bulk push notifications
|
||||
}
|
||||
export interface InAppNotificationQueueJob {
|
||||
recipient: { adminId: string; restaurantId: string };
|
||||
subject: NotifTitleEnum;
|
||||
body: string;
|
||||
notificationId: string;
|
||||
}
|
||||
|
||||
export interface SmsNotificationQueueJobResult {
|
||||
success: boolean;
|
||||
notificationId: string;
|
||||
providerResponse?: Record<string, any>;
|
||||
error?: string;
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
export enum NotifChannelEnum {
|
||||
IN_APP = 'in-app',
|
||||
SMS = 'sms',
|
||||
PUSH = 'push',
|
||||
}
|
||||
export enum NotifTypeEnum {
|
||||
TRANSACTIONAL = 'transactional',
|
||||
PROMOTIONAL = 'promotional',
|
||||
SYSTEM = 'system',
|
||||
}
|
||||
export enum NotifTitleEnum {
|
||||
PAGER_CREATED = 'pager.created',
|
||||
ORDER_CREATED = 'order.created',
|
||||
PAYMENT_SUCCESS = 'payment.success',
|
||||
REVIEW_CREATED = 'review.created',
|
||||
ORDER_STATUS_CHANGED = 'order.status.changed',
|
||||
}
|
||||
export type recipientType = { userId: string } | { adminId: string };
|
||||
|
||||
export interface NotifRequestMessage {
|
||||
title: NotifTitleEnum;
|
||||
content: string;
|
||||
sms: {
|
||||
templateId: string;
|
||||
parameters?: Record<string, string>;
|
||||
};
|
||||
pushNotif: {
|
||||
title: string;
|
||||
content: string;
|
||||
icon: string;
|
||||
action: {
|
||||
type: string; //view order
|
||||
url: string;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export interface NotifRequest {
|
||||
// requestId: string;
|
||||
// timestamp: Date;
|
||||
// notifType: NotifTypeEnum;
|
||||
// channels: NotifChannelEnum[];
|
||||
restaurantId: string;
|
||||
recipients: recipientType[];
|
||||
message: NotifRequestMessage;
|
||||
metadata: {
|
||||
priority: number;
|
||||
// retries: number;
|
||||
};
|
||||
}
|
||||
//************************************************ */
|
||||
interface INotifySmsPayload {
|
||||
[key: string]: string | number | Date;
|
||||
}
|
||||
interface INotifySms {
|
||||
phone: string;
|
||||
subject: NotifTitleEnum;
|
||||
}
|
||||
export interface IInAppNotificationPayload {
|
||||
notificationId: string;
|
||||
subject: NotifTitleEnum;
|
||||
body: string;
|
||||
}
|
||||
|
||||
// 2. Payment Success
|
||||
interface IPaymentSuccessSmsNotifyPayload extends INotifySmsPayload {
|
||||
amount: number;
|
||||
date: Date;
|
||||
}
|
||||
|
||||
interface IPaymentSuccessSmsNotify extends INotifySms {
|
||||
subject: NotifTitleEnum.PAYMENT_SUCCESS;
|
||||
payload: IPaymentSuccessSmsNotifyPayload;
|
||||
}
|
||||
|
||||
export type ISmsNotifyPayload = IPaymentSuccessSmsNotify;
|
||||
@@ -0,0 +1,16 @@
|
||||
export interface ISmsResponse {
|
||||
status: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ISmsParams {
|
||||
phone: string;
|
||||
parameters?: Record<string, string | number | Date>;
|
||||
templateId: string;
|
||||
}
|
||||
|
||||
export interface ISmsBodyParameters {
|
||||
Mobile: string;
|
||||
TemplateId: string;
|
||||
Parameters: { name: string; value: string }[];
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { OnEvent } from '@nestjs/event-emitter';
|
||||
import { SmsSentEvent } from '../events/sms.events';
|
||||
import { RestRepository } from '../../restaurants/repositories/rest.repository';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { SmsLog } from '../entities/smsLogs.entity';
|
||||
|
||||
@Injectable()
|
||||
export class SmsListeners {
|
||||
private readonly logger = new Logger(SmsListeners.name);
|
||||
|
||||
constructor(
|
||||
private readonly restRepository: RestRepository,
|
||||
private readonly em: EntityManager,
|
||||
) {
|
||||
}
|
||||
|
||||
@OnEvent(SmsSentEvent.name)
|
||||
async handleSmsSent(event: SmsSentEvent) {
|
||||
try {
|
||||
this.logger.log(
|
||||
`SMS sent event received: phone ${event.phoneNumber} for restaurant: ${event.restaurantId}`,
|
||||
);
|
||||
|
||||
// Get the restaurant entity
|
||||
const restaurant = await this.restRepository.findOne({ id: event.restaurantId });
|
||||
|
||||
if (!restaurant) {
|
||||
this.logger.warn(
|
||||
`Restaurant not found for SMS log: ${event.restaurantId}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Create SMS log record
|
||||
const smsLog = this.em.create(SmsLog, {
|
||||
restaurant: restaurant,
|
||||
phone: event.phoneNumber,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
await this.em.flush();
|
||||
|
||||
this.logger.log(
|
||||
`SMS log created successfully: ${smsLog.id} for phone ${event.phoneNumber}`,
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Failed to create SMS log for event: ${event.restaurantId}`,
|
||||
error instanceof Error ? error.stack : String(error),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import {
|
||||
WebSocketGateway,
|
||||
WebSocketServer,
|
||||
// SubscribeMessage,
|
||||
OnGatewayConnection,
|
||||
OnGatewayDisconnect,
|
||||
// MessageBody,
|
||||
// ConnectedSocket,
|
||||
} from '@nestjs/websockets';
|
||||
import { Server, Socket } from 'socket.io';
|
||||
import { Logger, Inject, forwardRef } from '@nestjs/common';
|
||||
import { NotificationService } from './services/notification.service';
|
||||
import { WsAdminAuthGuard, type AuthenticatedSocket } from './guards/ws-admin-auth.guard';
|
||||
import { ModuleRef } from '@nestjs/core';
|
||||
import { ExecutionContext } from '@nestjs/common';
|
||||
import { IInAppNotificationPayload } from './interfaces/notification.interface';
|
||||
|
||||
@WebSocketGateway({
|
||||
cors: {
|
||||
origin: true,
|
||||
credentials: true,
|
||||
},
|
||||
namespace: '/notifications',
|
||||
transports: ['websocket', 'polling'],
|
||||
})
|
||||
export class NotificationsGateway implements OnGatewayConnection, OnGatewayDisconnect {
|
||||
@WebSocketServer()
|
||||
server!: Server;
|
||||
|
||||
private readonly logger = new Logger(NotificationsGateway.name);
|
||||
private readonly pingIntervals = new Map<string, NodeJS.Timeout>();
|
||||
|
||||
constructor(
|
||||
@Inject(forwardRef(() => NotificationService))
|
||||
private readonly notificationService: NotificationService,
|
||||
private readonly moduleRef: ModuleRef,
|
||||
) {}
|
||||
|
||||
async handleConnection(client: Socket) {
|
||||
try {
|
||||
await this.authenticateConnection(client);
|
||||
const authenticatedClient = client as AuthenticatedSocket;
|
||||
this.logger.log(`Admin connected: ${authenticatedClient.adminId}`);
|
||||
this.handleJoinRoom(authenticatedClient);
|
||||
|
||||
// Start ping interval for this client
|
||||
// const intervalId = setInterval(() => {
|
||||
// void authenticatedClient.emit('ping', { message: 'ping', timestamp: new Date().toISOString() });
|
||||
// }, 2000);
|
||||
|
||||
// this.pingIntervals.set(client.id, intervalId);
|
||||
} catch (error) {
|
||||
this.logger.error(
|
||||
`Connection authentication failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
|
||||
);
|
||||
void client.emit('error', { message: 'Authentication failed' });
|
||||
client.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
handleDisconnect(client: Socket) {
|
||||
this.logger.log(`Client disconnected: ${client.id}`);
|
||||
this.handleLeaveRoom(client);
|
||||
|
||||
// Clear ping interval for this client
|
||||
// const intervalId = this.pingIntervals.get(client.id);
|
||||
// if (intervalId) {
|
||||
// clearInterval(intervalId);
|
||||
// this.pingIntervals.delete(client.id);
|
||||
// }
|
||||
}
|
||||
|
||||
sendInAppNotification(repipient: { adminId: string; restaurantId: string }, payload: IInAppNotificationPayload) {
|
||||
const room = this.getRoom(repipient.adminId, repipient.restaurantId);
|
||||
|
||||
this.logger.log(`Sending in app notification to admin: ${repipient.adminId}`);
|
||||
this.server.to(room).emit('notifications', payload, async () => {
|
||||
// 3. ACK (delivered)
|
||||
// await this.notificationService.markAsDelivered(payload.notificationId);
|
||||
});
|
||||
this.logger.log(`In app notification sent to admin: ${repipient.adminId}`);
|
||||
}
|
||||
|
||||
private getRoom(adminId: string, restaurantId: string) {
|
||||
return `restaurant:${restaurantId}-admin:${adminId}`;
|
||||
}
|
||||
|
||||
handleLeaveRoom(client: AuthenticatedSocket) {
|
||||
const room = this.getRoom(client.adminId!, client.restId!);
|
||||
void client.leave(room);
|
||||
this.logger.log(`Admin ${client.adminId} (Client ${client.id}) left room: ${room}`);
|
||||
void client.emit('left', { room, message: 'Successfully Admin left room' });
|
||||
}
|
||||
|
||||
handleJoinRoom(client: AuthenticatedSocket) {
|
||||
const room = this.getRoom(client.adminId!, client.restId!);
|
||||
void client.join(room);
|
||||
this.logger.log(`Admin ${client.adminId} (Client ${client.id}) joined room: ${room}`);
|
||||
void client.emit('joined', { room, message: 'Successfully Admin joined room' });
|
||||
}
|
||||
|
||||
private async authenticateConnection(client: Socket): Promise<void> {
|
||||
const guard = this.moduleRef.get(WsAdminAuthGuard);
|
||||
const context = {
|
||||
switchToWs: () => ({ getClient: () => client }),
|
||||
getClass: () => NotificationsGateway,
|
||||
getHandler: () => this.handleConnection,
|
||||
} as unknown as ExecutionContext;
|
||||
|
||||
const canActivate = await guard.canActivate(context);
|
||||
if (!canActivate) {
|
||||
throw new Error('Authentication failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Module, forwardRef } from '@nestjs/common';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { BullModule } from '@nestjs/bullmq';
|
||||
import { JwtModule } from '@nestjs/jwt';
|
||||
import { Notification } from './entities/notification.entity';
|
||||
import { NotificationPreference } from './entities/notification-preference.entity';
|
||||
import { NotificationService } from './services/notification.service';
|
||||
import { NotificationPreferenceService } from './services/notification-preference.service';
|
||||
import { NotificationQueueService } from './services/notification-queue.service';
|
||||
import { PushNotificationService } from './services/push-notification.service';
|
||||
import { SmsProcessor } from './processors/sms.processor';
|
||||
import { PushProcessor } from './processors/push.processor';
|
||||
import { NotificationsController } from './controllers/notifications.controller';
|
||||
import { User } from '../users/entities/user.entity';
|
||||
import { Restaurant } from '../restaurants/entities/restaurant.entity';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { NotificationQueueNameEnum } from './constants/queue';
|
||||
import { UtilsModule } from '../utils/utils.module';
|
||||
import { NotificationsGateway } from './notifications.gateway';
|
||||
import { WsAdminAuthGuard } from './guards/ws-admin-auth.guard';
|
||||
import { InAppProcessor } from './processors/in-app.processor';
|
||||
import { AdminModule } from '../admin/admin.module';
|
||||
import { UserModule } from '../users/user.module';
|
||||
import { NotificationCrone } from './crone/notification.crone';
|
||||
import { SmsService } from './services/sms.service';
|
||||
import { SmsLog } from './entities/smsLogs.entity';
|
||||
import { SmsLogRepository } from './repositories/sms-log.repository';
|
||||
import { RestaurantsModule } from '../restaurants/restaurants.module';
|
||||
import { SmsListeners } from './listeners/sms.listeners';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
forwardRef(() => AuthModule),
|
||||
JwtModule,
|
||||
MikroOrmModule.forFeature([Notification, NotificationPreference, User, Restaurant, SmsLog]),
|
||||
BullModule.registerQueue(
|
||||
{ name: NotificationQueueNameEnum.SMS },
|
||||
{ name: NotificationQueueNameEnum.PUSH },
|
||||
{ name: NotificationQueueNameEnum.IN_APP },
|
||||
),
|
||||
BullModule.forRootAsync({
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService) => ({
|
||||
connection: {
|
||||
host: config.get('REDIS_HOST') || 'captain.dev.danakcorp.com',
|
||||
port: config.get('REDIS_PORT') || 50601,
|
||||
password: config.get('REDIS_PASSWORD'), // Pull from .env
|
||||
},
|
||||
}),
|
||||
}),
|
||||
AdminModule,
|
||||
forwardRef(() => UserModule),
|
||||
UtilsModule,
|
||||
forwardRef(() => RestaurantsModule),
|
||||
],
|
||||
controllers: [NotificationsController],
|
||||
providers: [
|
||||
NotificationService,
|
||||
NotificationPreferenceService,
|
||||
NotificationQueueService,
|
||||
PushNotificationService,
|
||||
PushProcessor,
|
||||
SmsProcessor,
|
||||
InAppProcessor,
|
||||
NotificationsGateway,
|
||||
WsAdminAuthGuard,
|
||||
NotificationCrone,
|
||||
SmsService,
|
||||
SmsLogRepository,
|
||||
SmsListeners,
|
||||
],
|
||||
exports: [NotificationService, NotificationPreferenceService,
|
||||
NotificationQueueService, PushNotificationService, SmsService],
|
||||
})
|
||||
export class NotificationsModule { }
|
||||
@@ -0,0 +1,50 @@
|
||||
import { Processor, WorkerHost, OnWorkerEvent } from '@nestjs/bullmq';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { Notification } from '../entities/notification.entity';
|
||||
import { InAppNotificationQueueJob } from '../interfaces/jobs-queue.interface';
|
||||
import { NotificationQueueNameEnum } from '../constants/queue';
|
||||
import { NotificationsGateway } from '../notifications.gateway';
|
||||
|
||||
@Processor(NotificationQueueNameEnum.IN_APP)
|
||||
export class InAppProcessor extends WorkerHost {
|
||||
private readonly logger = new Logger(InAppProcessor.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(Notification)
|
||||
private readonly em: EntityManager,
|
||||
private readonly notificationsGateway: NotificationsGateway,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async process(job: Job<InAppNotificationQueueJob>): Promise<void> {
|
||||
const { recipient, subject, body, notificationId } = job.data;
|
||||
|
||||
this.logger.log(`Processing InApp notification - Recipient: ${JSON.stringify(recipient)}, subject: ${subject}`);
|
||||
|
||||
try {
|
||||
this.notificationsGateway.sendInAppNotification(
|
||||
{ adminId: recipient.adminId, restaurantId: recipient.restaurantId },
|
||||
{ subject, body, notificationId },
|
||||
);
|
||||
|
||||
this.logger.log(`InApp notification sent successfully to ${recipient.adminId}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Error processing InApp notification job ${job.id}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@OnWorkerEvent('completed')
|
||||
onCompleted(job: Job) {
|
||||
this.logger.log(`Notification job ${job.id} completed`);
|
||||
}
|
||||
|
||||
@OnWorkerEvent('failed')
|
||||
onFailed(job: Job, error: Error) {
|
||||
this.logger.error(`Notification job ${job.id} failed:`, error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { Processor, WorkerHost, OnWorkerEvent } from '@nestjs/bullmq';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { EntityRepository, EntityManager } from '@mikro-orm/postgresql';
|
||||
import { Notification } from '../entities/notification.entity';
|
||||
import { PushNotificationQueueJob } from '../interfaces/jobs-queue.interface';
|
||||
import { NotificationQueueNameEnum } from '../constants/queue';
|
||||
import { PushNotificationService } from '../services/push-notification.service';
|
||||
|
||||
@Processor(NotificationQueueNameEnum.PUSH)
|
||||
export class PushProcessor extends WorkerHost {
|
||||
private readonly logger = new Logger(PushProcessor.name);
|
||||
|
||||
constructor(
|
||||
@InjectRepository(Notification)
|
||||
private readonly notificationRepository: EntityRepository<Notification>,
|
||||
private readonly em: EntityManager,
|
||||
private readonly pushNotificationService: PushNotificationService,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async process(job: Job<PushNotificationQueueJob>) {
|
||||
const { title, content, action, pushToken, pushTokens } = job.data;
|
||||
|
||||
this.logger.log(`Processing push notification job: ${job.id} - Title: ${title},`);
|
||||
|
||||
try {
|
||||
// Get push token from job data
|
||||
const pushToken = job.data.pushToken;
|
||||
const pushTokens = job.data.pushTokens;
|
||||
|
||||
if (!pushToken && (!pushTokens || pushTokens.length === 0)) {
|
||||
this.logger.warn(`Push token(s) not provided for notification `);
|
||||
throw new Error('Push token or pushTokens array is required for push notifications');
|
||||
}
|
||||
|
||||
// Send push notification
|
||||
// Convert NotificationTitle enum to a readable string for the notification title
|
||||
const notificationTitle = String(title)
|
||||
.replace(/\./g, ' ')
|
||||
.replace(/\b\w/g, l => l.toUpperCase());
|
||||
|
||||
let pushResult;
|
||||
if (pushTokens && pushTokens.length > 0) {
|
||||
// Send to multiple tokens
|
||||
pushResult = await this.pushNotificationService.sendToMultipleTokens({
|
||||
title: notificationTitle,
|
||||
body: content,
|
||||
tokens: pushTokens,
|
||||
data: {
|
||||
action,
|
||||
},
|
||||
});
|
||||
} else if (pushToken) {
|
||||
// Send to single token
|
||||
pushResult = await this.pushNotificationService.sendToToken({
|
||||
title: notificationTitle,
|
||||
body: content,
|
||||
token: pushToken,
|
||||
data: {
|
||||
action,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
throw new Error('Push token or pushTokens array is required');
|
||||
}
|
||||
|
||||
if (!pushResult.success) {
|
||||
throw new Error(pushResult.error || 'Failed to send push notification');
|
||||
}
|
||||
|
||||
this.logger.log(`Push notification sent successfully`);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
||||
providerResponse: { messageId: pushResult.messageId },
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Error processing push notification job ${job.id}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@OnWorkerEvent('completed')
|
||||
onCompleted(job: Job) {
|
||||
this.logger.log(`Notification job ${job.id} completed`);
|
||||
}
|
||||
|
||||
@OnWorkerEvent('failed')
|
||||
onFailed(job: Job, error: Error) {
|
||||
this.logger.error(`Notification job ${job.id} failed:`, error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Processor, WorkerHost, OnWorkerEvent } from '@nestjs/bullmq';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import { UserRepository } from 'src/modules/users/repositories/user.repository';
|
||||
import { SmsNotificationQueueJob } from '../interfaces/jobs-queue.interface';
|
||||
import { AdminRepository } from 'src/modules/admin/repositories/admin.repository';
|
||||
import { NotificationQueueNameEnum } from '../constants/queue';
|
||||
import { SmsService } from '../services/sms.service';
|
||||
import { SmsSentEvent } from '../events/sms.events';
|
||||
import { EventEmitter2 } from '@nestjs/event-emitter';
|
||||
|
||||
@Processor(NotificationQueueNameEnum.SMS)
|
||||
export class SmsProcessor extends WorkerHost {
|
||||
private readonly logger = new Logger(SmsProcessor.name);
|
||||
|
||||
constructor(
|
||||
private readonly adminRepository: AdminRepository,
|
||||
private readonly userRepository: UserRepository,
|
||||
private readonly smsService: SmsService,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
async process(job: Job<SmsNotificationQueueJob>) {
|
||||
const { recipient, templateId, parameters, restaurantId } = job.data;
|
||||
|
||||
this.logger.log(`Processing SMS notification - Recipient: ${JSON.stringify(recipient)}, templateID: ${templateId}`);
|
||||
|
||||
try {
|
||||
let phone!: string;
|
||||
if ('userId' in recipient) {
|
||||
const user = await this.userRepository.findOne({ id: recipient.userId });
|
||||
if (!user || !user.phone) {
|
||||
this.logger.warn(`User ${recipient.userId} not found or has no phone number`);
|
||||
throw new Error('User phone number is required for SMS notifications');
|
||||
}
|
||||
phone = user.phone;
|
||||
}
|
||||
if ('adminId' in recipient) {
|
||||
const admin = await this.adminRepository.findOne({ id: recipient.adminId });
|
||||
if (!admin || !admin.phone) {
|
||||
this.logger.warn(`Admin ${recipient.adminId} not found or has no phone number`);
|
||||
throw new Error('Admin phone number is required for SMS notifications');
|
||||
}
|
||||
phone = admin.phone;
|
||||
}
|
||||
if (!phone) {
|
||||
this.logger.warn(`Phone number not found for recipient ${JSON.stringify(recipient)}`);
|
||||
throw new Error('Phone number is required for SMS notifications');
|
||||
}
|
||||
// Send SMS notification
|
||||
await this.smsService.sendSms({
|
||||
phone,
|
||||
templateId,
|
||||
parameters,
|
||||
});
|
||||
|
||||
this.logger.log(`SMS notification sent successfully to ${phone}`);
|
||||
|
||||
this.eventEmitter.emit(SmsSentEvent.name, new SmsSentEvent(phone, restaurantId));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error(`Error processing SMS notification job ${job.id}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
@OnWorkerEvent('completed')
|
||||
onCompleted(job: Job) {
|
||||
this.logger.log(`Notification job ${job.id} completed`);
|
||||
}
|
||||
|
||||
@OnWorkerEvent('failed')
|
||||
onFailed(job: Job, error: Error) {
|
||||
this.logger.error(`Notification job ${job.id} failed:`, error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { EntityManager, EntityRepository } from '@mikro-orm/postgresql';
|
||||
import { SmsLog } from '../entities/smsLogs.entity';
|
||||
import { PaginatedResult } from '../../../common/interfaces/pagination.interface';
|
||||
|
||||
@Injectable()
|
||||
export class SmsLogRepository extends EntityRepository<SmsLog> {
|
||||
constructor(readonly em: EntityManager) {
|
||||
super(em, SmsLog);
|
||||
}
|
||||
|
||||
async getSmsCountByRestaurant(
|
||||
page: number = 1,
|
||||
limit: number = 10,
|
||||
): Promise<PaginatedResult<{ restaurantId: string; restaurantName: string; smsCount: number }>> {
|
||||
const offset = (page - 1) * limit;
|
||||
|
||||
// Get total count of unique restaurants with SMS logs
|
||||
const totalResult = await this.em.execute(
|
||||
`
|
||||
SELECT COUNT(DISTINCT sl.restaurant_id) as total
|
||||
FROM sms_logs sl
|
||||
WHERE sl.restaurant_id IS NOT NULL
|
||||
`,
|
||||
);
|
||||
const total = parseInt(totalResult[0]?.total || '0', 10);
|
||||
|
||||
// Get paginated results with SMS counts grouped by restaurant
|
||||
const results = await this.em.execute(
|
||||
`
|
||||
SELECT
|
||||
r.id as "restaurantId",
|
||||
r.name as "restaurantName",
|
||||
COUNT(sl.id)::int as "smsCount"
|
||||
FROM sms_logs sl
|
||||
INNER JOIN restaurants r ON sl.restaurant_id = r.id
|
||||
GROUP BY r.id, r.name
|
||||
ORDER BY "smsCount" DESC, r.name ASC
|
||||
LIMIT ? OFFSET ?
|
||||
`,
|
||||
[limit, offset],
|
||||
);
|
||||
|
||||
const data = results.map((row: any) => ({
|
||||
restaurantId: row.restaurantId,
|
||||
restaurantName: row.restaurantName || 'Unknown',
|
||||
smsCount: parseInt(row.smsCount || '0', 10),
|
||||
}));
|
||||
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
return {
|
||||
data,
|
||||
meta: {
|
||||
total,
|
||||
page,
|
||||
limit,
|
||||
totalPages,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async getSmsCountByRestaurantId(restaurantId: string): Promise<number> {
|
||||
const result = await this.em.execute(
|
||||
`
|
||||
SELECT COUNT(sl.id)::int as "smsCount"
|
||||
FROM sms_logs sl
|
||||
WHERE sl.restaurant_id = ?
|
||||
`,
|
||||
[restaurantId],
|
||||
);
|
||||
|
||||
return parseInt(result[0]?.smsCount || '0', 10);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import { EntityManager } from '@mikro-orm/postgresql';
|
||||
import { NotificationPreference } from '../entities/notification-preference.entity';
|
||||
import { Restaurant } from '../../restaurants/entities/restaurant.entity';
|
||||
import { CreatePreferenceDto } from '../dto/create-preference.dto';
|
||||
import { UpdatePreferenceDto } from '../dto/update-preference.dto';
|
||||
import { NotifTitleEnum } from '../interfaces/notification.interface';
|
||||
|
||||
@Injectable()
|
||||
export class NotificationPreferenceService {
|
||||
constructor(private readonly em: EntityManager) { }
|
||||
|
||||
async create(restaurantId: string, dto: CreatePreferenceDto): Promise<NotificationPreference> {
|
||||
const restaurant = await this.em.findOne(Restaurant, { id: restaurantId });
|
||||
if (!restaurant) {
|
||||
throw new NotFoundException('Restaurant not found');
|
||||
}
|
||||
|
||||
const preference = this.em.create(NotificationPreference, {
|
||||
restaurant,
|
||||
channels: dto.channels,
|
||||
title: dto.title,
|
||||
});
|
||||
|
||||
await this.em.persistAndFlush(preference);
|
||||
return preference;
|
||||
}
|
||||
|
||||
async findByRestaurant(restaurantId: string): Promise<NotificationPreference[]> {
|
||||
return this.em.find(NotificationPreference, {
|
||||
restaurant: { id: restaurantId },
|
||||
});
|
||||
}
|
||||
|
||||
async findByRestaurantAndType(restaurantId: string, title: NotifTitleEnum): Promise<NotificationPreference | null> {
|
||||
return this.em.findOne(NotificationPreference, {
|
||||
restaurant: { id: restaurantId },
|
||||
title,
|
||||
});
|
||||
}
|
||||
|
||||
// async updateEnabled(
|
||||
// restaurantId: string,
|
||||
// notificationType: string,
|
||||
// enabled: boolean,
|
||||
// ): Promise<NotificationPreference> {
|
||||
// const preference = await this.findByRestaurantAndType(restaurantId, notificationType);
|
||||
// if (!preference) {
|
||||
// throw new NotFoundException('Notification preference not found');
|
||||
// }
|
||||
|
||||
// preference.enabled = enabled;
|
||||
// await this.em.persistAndFlush(preference);
|
||||
// return preference;
|
||||
// }
|
||||
|
||||
async updatePreference(
|
||||
preferenceId: string,
|
||||
restaurantId: string,
|
||||
dto: UpdatePreferenceDto,
|
||||
): Promise<NotificationPreference> {
|
||||
const preference = await this.em.findOne(NotificationPreference, {
|
||||
id: preferenceId,
|
||||
restaurant: { id: restaurantId },
|
||||
});
|
||||
if (!preference) {
|
||||
throw new NotFoundException('Notification preference not found');
|
||||
}
|
||||
|
||||
this.em.assign(preference, dto);
|
||||
await this.em.persistAndFlush(preference);
|
||||
return preference;
|
||||
}
|
||||
|
||||
async delete(restaurantId: string, preferenceId: string): Promise<void> {
|
||||
const preference = await this.em.findOne(NotificationPreference, {
|
||||
restaurant: { id: restaurantId },
|
||||
id: preferenceId,
|
||||
});
|
||||
if (!preference) {
|
||||
throw new NotFoundException('Notification preference not found');
|
||||
}
|
||||
await this.em.removeAndFlush(preference);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { InjectQueue } from '@nestjs/bullmq';
|
||||
import { Queue } from 'bullmq';
|
||||
import { NotificationQueueNameEnum } from '../constants/queue';
|
||||
import {
|
||||
InAppNotificationQueueJob,
|
||||
PushNotificationQueueJob,
|
||||
SmsNotificationQueueJob,
|
||||
} from '../interfaces/jobs-queue.interface';
|
||||
|
||||
@Injectable()
|
||||
export class NotificationQueueService {
|
||||
private readonly logger = new Logger(NotificationQueueService.name);
|
||||
|
||||
constructor(
|
||||
@InjectQueue(NotificationQueueNameEnum.SMS) private readonly smsQueue: Queue,
|
||||
@InjectQueue(NotificationQueueNameEnum.PUSH) private readonly pushQueue: Queue,
|
||||
@InjectQueue(NotificationQueueNameEnum.IN_APP) private readonly inAppQueue: Queue,
|
||||
) {}
|
||||
|
||||
async addSmsNotification(job: SmsNotificationQueueJob): Promise<void> {
|
||||
try {
|
||||
const jobId = `${job.templateId}-${this.generateRandomInt()}-${Date.now()}`;
|
||||
|
||||
await this.smsQueue.add('sms-notification', job, {
|
||||
jobId,
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 2000,
|
||||
},
|
||||
removeOnComplete: {
|
||||
age: 24 * 3600, // Keep completed jobs for 24 hours
|
||||
count: 1000,
|
||||
},
|
||||
removeOnFail: {
|
||||
age: 7 * 24 * 3600, // Keep failed jobs for 7 days
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.log(`SMS notification job added to queue: ${jobId}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to add SMS notification to queue:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async addPushNotification(job: PushNotificationQueueJob): Promise<void> {
|
||||
try {
|
||||
const jobId = `${job.title}-${this.generateRandomInt()}-${Date.now()}`;
|
||||
|
||||
await this.pushQueue.add('push-notification', job, {
|
||||
jobId,
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 2000,
|
||||
},
|
||||
removeOnComplete: {
|
||||
age: 24 * 3600, // Keep completed jobs for 24 hours
|
||||
count: 1000,
|
||||
},
|
||||
removeOnFail: {
|
||||
age: 7 * 24 * 3600, // Keep failed jobs for 7 days
|
||||
},
|
||||
});
|
||||
|
||||
this.logger.log(`Push notification job added to queue: ${jobId}`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to add push notification to queue:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async addBulkSmsNotifications(jobs: SmsNotificationQueueJob[]): Promise<void> {
|
||||
try {
|
||||
const queueJobs = jobs.map(job => ({
|
||||
name: 'sms-notification',
|
||||
data: job,
|
||||
opts: {
|
||||
jobId: `${job.templateId}-${this.generateRandomInt()}`,
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 2000,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
await this.smsQueue.addBulk(queueJobs);
|
||||
this.logger.log(`Added ${jobs.length} SMS notification jobs to queue`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to add bulk notifications to queue:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async addBulkPushNotifications(jobs: PushNotificationQueueJob[]): Promise<void> {
|
||||
try {
|
||||
const queueJobs = jobs.map(job => ({
|
||||
name: 'push-notification',
|
||||
data: job,
|
||||
opts: {
|
||||
jobId: `${job.title}-${this.generateRandomInt()}-${Date.now()}`,
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 2000,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
await this.pushQueue.addBulk(queueJobs);
|
||||
this.logger.log(`Added ${jobs.length} Push notification jobs to queue`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to add bulk notifications to queue:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async addBulkInAppNotifications(jobs: InAppNotificationQueueJob[]): Promise<void> {
|
||||
try {
|
||||
const queueJobs = jobs.map(job => ({
|
||||
name: 'in-app-notification',
|
||||
data: job,
|
||||
opts: {
|
||||
jobId: `${job.subject}-${job.notificationId}-${Date.now()}`,
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
type: 'exponential',
|
||||
delay: 2000,
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
await this.inAppQueue.addBulk(queueJobs);
|
||||
this.logger.log(`Added ${jobs.length} InApp notification jobs to queue`);
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to add bulk notifications to queue:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
private generateRandomInt(): string {
|
||||
return Math.random().toString(36).substring(2, 15);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user