Browse Source

refactor: rename uChannelId to channelId across the application for consistency

Dave 3 tháng trước cách đây
mục cha
commit
7701030092
25 tập tin đã thay đổi với 56 bổ sung56 xóa
  1. 2 2
      apps/box-app-api/src/feature/ads/ad.service.ts
  2. 1 1
      apps/box-app-api/src/feature/ads/dto/ad-click.dto.ts
  3. 1 1
      apps/box-app-api/src/feature/ads/dto/ad-impression.dto.ts
  4. 1 1
      apps/box-app-api/src/feature/auth/auth.controller.ts
  5. 10 10
      apps/box-app-api/src/feature/auth/auth.service.ts
  6. 4 4
      apps/box-app-api/src/feature/auth/decorators/current-user.decorator.ts
  7. 2 2
      apps/box-app-api/src/feature/auth/interfaces/app-jwt-payload.ts
  8. 2 2
      apps/box-app-api/src/feature/auth/jwt-utils.ts
  9. 2 2
      apps/box-app-api/src/feature/auth/strategies/jwt.strategy.ts
  10. 1 1
      apps/box-app-api/src/feature/stats/dto/ad-click.dto.ts
  11. 1 1
      apps/box-app-api/src/feature/stats/dto/ad-impression.dto.ts
  12. 3 3
      apps/box-app-api/src/feature/stats/stats-events.service.ts
  13. 2 2
      apps/box-app-api/src/rabbitmq/rabbitmq-publisher.service.ts
  14. 4 0
      apps/box-mgnt-api/src/mgnt-backend/core/auth/auth.service.ts
  15. 0 2
      apps/box-mgnt-api/src/mgnt-backend/core/logging/login-log/login-log.service.ts
  16. 0 2
      apps/box-mgnt-api/src/mgnt-backend/core/logging/operation-log/operation-log.service.ts
  17. 1 1
      apps/box-mgnt-api/src/mgnt-backend/core/menu/menu.service.ts
  18. 1 1
      apps/box-stats-api/src/feature/stats-events/stats-events.consumer.ts
  19. 3 3
      apps/box-stats-api/src/feature/user-login/user-login.service.ts
  20. 2 2
      libs/common/src/events/user-login-event.dto.ts
  21. 2 2
      prisma/mongo-stats/schema/ads-click-history.prisma
  22. 6 6
      prisma/mongo-stats/schema/events.prisma
  23. 2 2
      prisma/mongo-stats/schema/user-login-history.prisma
  24. 2 2
      prisma/mongo-stats/schema/user.prisma
  25. 1 1
      prisma/mongo/schema/sys-operation-log.prisma

+ 2 - 2
apps/box-app-api/src/feature/ads/ad.service.ts

@@ -718,7 +718,7 @@ export class AdService {
       adType: body.adType,
       clickedAt,
       ip,
-      uChannelId: body.uChannelId,
+      channelId: body.channelId,
       machine: body.machine,
     };
 
@@ -763,7 +763,7 @@ export class AdService {
       impressionAt,
       visibleDurationMs: body.visibleDurationMs,
       ip,
-      uChannelId: body.uChannelId,
+      channelId: body.channelId,
       machine: body.machine,
     };
 

+ 1 - 1
apps/box-app-api/src/feature/ads/dto/ad-click.dto.ts

@@ -19,7 +19,7 @@ export class AdClickDto {
   })
   @IsNotEmpty()
   @IsString()
-  uChannelId: string;
+  channelId: string;
 
   @ApiProperty({
     description: '设备信息(品牌、系统版本等)',

+ 1 - 1
apps/box-app-api/src/feature/ads/dto/ad-impression.dto.ts

@@ -31,7 +31,7 @@ export class AdImpressionDto {
   })
   @IsNotEmpty()
   @IsString()
-  uChannelId: string;
+  channelId: string;
 
   @ApiProperty({
     description: '设备信息(品牌、系统版本等)',

+ 1 - 1
apps/box-app-api/src/feature/auth/auth.controller.ts

@@ -42,7 +42,7 @@ export class AuthController {
       userAgent,
       appVersion: body.appVersion,
       os: body.os,
-      uChannelId: body.channelId,
+      channelId: body.channelId,
       machine: body.machine,
       // add any other auth-related fields as needed
     });

+ 10 - 10
apps/box-app-api/src/feature/auth/auth.service.ts

@@ -23,11 +23,11 @@ export class AuthService {
     userAgent?: string;
     appVersion?: string;
     os?: string;
-    uChannelId?: string;
+    channelId?: string;
     machine?: string;
     // plus whatever you need like account, password, etc.
   }): Promise<any> {
-    const { uid, ip, userAgent, appVersion, os, uChannelId, machine } = params;
+    const { uid, ip, userAgent, appVersion, os, channelId, machine } = params;
 
     // 1) Your existing auth logic (validate user, etc.)
     // const user = await this.validateUser(...);
@@ -38,25 +38,25 @@ export class AuthService {
     const now = Date.now(); // number (ms since epoch)
 
     const user = await this.getUserByUid(uid);
-    const firstChannel = await this.getChannelById(uChannelId || '');
-    // if user does not exist, uChannelId = firstChannel.channelId
-    let finalUChannelId = uChannelId;
+    const firstChannel = await this.getChannelById(channelId || '');
+    // if user does not exist, channelId = firstChannel.channelId
+    let finalchannelId = channelId;
     if (!user && firstChannel) {
-      finalUChannelId = firstChannel.channelId;
+      finalchannelId = firstChannel.channelId;
     }
     // if user exists, take firstChannel.channelId
     else if (user && firstChannel) {
-      finalUChannelId = firstChannel.channelId;
+      finalchannelId = firstChannel.channelId;
     }
 
     // Build JWT payload with required and optional tracking fields.
-    // Tracking fields (uChannelId, machine, ip, userAgent, appVersion, os) are optional
+    // Tracking fields (channelId, machine, ip, userAgent, appVersion, os) are optional
     // to preserve backward compatibility with older tokens and minimize JWT size for stability.
     const payload: AppJwtPayload = {
       sub: uid,
       uid,
       jti: tokenId,
-      uChannelId: finalUChannelId,
+      channelId: finalchannelId,
       machine,
       ip,
       userAgent,
@@ -74,7 +74,7 @@ export class AuthService {
       userAgent,
       appVersion,
       os,
-      uChannelId: finalUChannelId,
+      channelId: finalchannelId,
       machine,
       tokenId,
       loginAt: now,

+ 4 - 4
apps/box-app-api/src/feature/auth/decorators/current-user.decorator.ts

@@ -6,7 +6,7 @@
  *
  * The payload includes:
  * - Core claims: sub, uid, jti
- * - Optional tracking fields: uChannelId, machine, ip, userAgent, appVersion, os, iat
+ * - Optional tracking fields: channelId, machine, ip, userAgent, appVersion, os, iat
  *
  * Usage Example:
  * ```typescript
@@ -18,9 +18,9 @@
  * export class UserController {
  *   @Get('profile')
  *   async getProfile(@CurrentUser() user: CurrentAppUser) {
- *     const { uid, uChannelId, appVersion, os } = user;
+ *     const { uid, channelId, appVersion, os } = user;
  *     // All fields are strongly typed
- *     console.log(`User ${uid} from channel ${uChannelId} on ${os} v${appVersion}`);
+ *     console.log(`User ${uid} from channel ${channelId} on ${os} v${appVersion}`);
  *   }
  * }
  * ```
@@ -29,7 +29,7 @@
  * - ip and userAgent are for analytics purposes only, not security enforcement
  * - appVersion helps track client version usage
  * - os enables platform-specific behavior
- * - uChannelId tracks traffic source
+ * - channelId tracks traffic source
  * - machine identifies repeat visitors
  */
 import { createParamDecorator, ExecutionContext } from '@nestjs/common';

+ 2 - 2
apps/box-app-api/src/feature/auth/interfaces/app-jwt-payload.ts

@@ -6,7 +6,7 @@
  * a successful login, enabling stateless verification and tracking across requests.
  *
  * Backward Compatibility:
- * All non-critical tracking fields (ip, userAgent, appVersion, os, uChannelId, machine)
+ * All non-critical tracking fields (ip, userAgent, appVersion, os, channelId, machine)
  * are optional to support tokens issued before this interface was standardized and
  * allow graceful upgrades.
  */
@@ -43,7 +43,7 @@ export interface AppJwtPayload {
    * Used for analytics and conversion tracking.
    * Example: "organic", "campaign_abc", "referrer_xyz"
    */
-  uChannelId?: string;
+  channelId?: string;
 
   /**
    * Optional: Device/Machine identifier.

+ 2 - 2
apps/box-app-api/src/feature/auth/jwt-utils.ts

@@ -26,7 +26,7 @@ import { AppJwtPayload } from './interfaces/app-jwt-payload';
  *   async getProfile(@Req() req: Request) {
  *     const claims = getAppJwtPayloadFromRequest(req);
  *     if (claims) {
- *       console.log(`User ${claims.uid} from channel ${claims.uChannelId} on ${claims.os} v${claims.appVersion}`);
+ *       console.log(`User ${claims.uid} from channel ${claims.channelId} on ${claims.os} v${claims.appVersion}`);
  *       // Use claims for logging, analytics, or business logic
  *     } else {
  *       // Payload missing or invalid
@@ -42,7 +42,7 @@ import { AppJwtPayload } from './interfaces/app-jwt-payload';
  * if (claims) {
  *   logger.info('User login analytics', {
  *     uid: claims.uid,
- *     channel: claims.uChannelId,
+ *     channel: claims.channelId,
  *     appVersion: claims.appVersion,
  *     os: claims.os,
  *     machine: claims.machine,

+ 2 - 2
apps/box-app-api/src/feature/auth/strategies/jwt.strategy.ts

@@ -28,13 +28,13 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
    * Usage in controllers:
    *   @Get('profile')
    *   async getProfile(@CurrentUser() user: CurrentAppUser) {
-   *     const { uid, uChannelId, appVersion, os, machine, ip, userAgent } = user;
+   *     const { uid, channelId, appVersion, os, machine, ip, userAgent } = user;
    *     // All fields are now strongly typed
    *   }
    */
   async validate(payload: AppJwtPayload): Promise<CurrentAppUser> {
     // Return the entire payload as the current user object.
-    // This preserves all tracking fields (uChannelId, machine, ip, userAgent, appVersion, os)
+    // This preserves all tracking fields (channelId, machine, ip, userAgent, appVersion, os)
     // for use in controllers and services throughout the app.
     return payload;
   }

+ 1 - 1
apps/box-app-api/src/feature/stats/dto/ad-click.dto.ts

@@ -18,7 +18,7 @@ export class AdClickDto {
   @ApiProperty({ description: '渠道 ID', example: '652e7bcf4f1a2b4f98ad7777' })
   @IsNotEmpty()
   @IsString()
-  uChannelId: string;
+  channelId: string;
 
   @ApiProperty({ description: '业务场景(如 home, detail)', example: 'home' })
   @IsNotEmpty()

+ 1 - 1
apps/box-app-api/src/feature/stats/dto/ad-impression.dto.ts

@@ -19,7 +19,7 @@ export class AdImpressionDto {
   @ApiProperty({ description: '渠道 ID', example: '652e7bcf4f1a2b4f98ad7777' })
   @IsNotEmpty()
   @IsString()
-  uChannelId: string;
+  channelId: string;
 
   @ApiProperty({ description: '业务场景(如 home, detail)', example: 'home' })
   @IsNotEmpty()

+ 3 - 3
apps/box-app-api/src/feature/stats/stats-events.service.ts

@@ -11,7 +11,7 @@ export interface AdClickEvent {
   uid: string;
   adId: string;
   adsModuleId: string;
-  uChannelId: string;
+  channelId: string;
   scene: string;
   slot: string;
   adType: string;
@@ -27,7 +27,7 @@ export interface AdClickEvent {
 export interface VideoClickEvent {
   uid: string;
   videoId: string;
-  // uChannelId: string;
+  // channelId: string;
   categoryId?: string;
   scene: string;
   clickedAt: bigint;
@@ -43,7 +43,7 @@ export interface AdImpressionEvent {
   uid: string;
   adId: string;
   adsModuleId: string;
-  // uChannelId: string;
+  // channelId: string;
   scene: string;
   slot: string;
   adType: string;

+ 2 - 2
apps/box-app-api/src/rabbitmq/rabbitmq-publisher.service.ts

@@ -24,7 +24,7 @@ export interface StatsAdClickEventPayload {
   adType: string;
   clickedAt: bigint;
   ip: string;
-  uChannelId?: string;
+  channelId?: string;
   machine?: string;
 }
 
@@ -44,7 +44,7 @@ export interface StatsAdImpressionEventPayload {
   impressionAt: bigint;
   visibleDurationMs?: number;
   ip: string;
-  uChannelId?: string;
+  channelId?: string;
   machine?: string;
 }
 

+ 4 - 0
apps/box-mgnt-api/src/mgnt-backend/core/auth/auth.service.ts

@@ -594,8 +594,12 @@ export class AuthService {
   async getUserAccessPermission(authUser: SysUser) {
     const user = await this.requirePersistedUser(authUser);
     const roleIds = await this.userService.getUserRoleIds(user.id, true);
+    this.logger.log(`User ${user.username} has roles: ${roleIds.join(', ')}`);
     const userMenus = await this.menuService.listByRoleIds(roleIds);
 
+    this.logger.log(
+      `User ${user.username} has ${userMenus.length} accessible menus.`,
+    );
     return userMenus;
   }
 

+ 0 - 2
apps/box-mgnt-api/src/mgnt-backend/core/logging/login-log/login-log.service.ts

@@ -2,7 +2,6 @@ import { Injectable } from '@nestjs/common';
 import { LoginStatus, LoginType, Prisma } from '@prisma/mongo/client';
 import Bowser from 'bowser';
 import type { FastifyRequest } from 'fastify';
-import { ulid } from '../ulid.util';
 import { MongoPrismaService } from '@box/db/prisma/mongo-prisma.service';
 import { UtilsService } from '@box/db/utils.service';
 import { UserService } from '../../user/user.service';
@@ -25,7 +24,6 @@ export class LoginLogService {
 
     await this.mongoPrismaService.sysLoginLog.create({
       data: {
-        id: ulid(),
         type,
         status,
         username,

+ 0 - 2
apps/box-mgnt-api/src/mgnt-backend/core/logging/operation-log/operation-log.service.ts

@@ -7,7 +7,6 @@ import { IOperationLogger } from '@box/common/interfaces/operation-logger.interf
 import { MongoPrismaService } from '@box/db/prisma/mongo-prisma.service';
 import { UtilsService } from '@box/db/utils.service';
 import { MenuService } from '../../menu/menu.service';
-import { ulid } from '../ulid.util';
 
 @Injectable()
 export class OperationLogService implements IOperationLogger {
@@ -51,7 +50,6 @@ export class OperationLogService implements IOperationLogger {
 
     await this.mongoPrismaService.sysOperationLog.create({
       data: {
-        id: ulid(),
         username: req.user.username,
         menuId,
         description: options.description,

+ 1 - 1
apps/box-mgnt-api/src/mgnt-backend/core/menu/menu.service.ts

@@ -93,7 +93,7 @@ type MetaInput = Prisma.InputJsonValue | null;
 
 @Injectable()
 export class MenuService {
-  private static readonly SUPER_ADMIN_ROLE_ID = '';
+  private static readonly SUPER_ADMIN_ROLE_ID = '6946c613ea4266475e73d074';
   private static readonly TRI_NA: CrudTri = {
     view: 2,
     create: 2,

+ 1 - 1
apps/box-stats-api/src/feature/stats-events/stats-events.consumer.ts

@@ -401,7 +401,7 @@ export class StatsEventsConsumer implements OnModuleInit, OnModuleDestroy {
             ? BigInt(payload.visibleDurationMs)
             : null,
           ip: payload.ip,
-          // uChannelId: payload.uChannelId ?? null,
+          // channelId: payload.channelId ?? null,
           machine: payload.machine,
           createAt: this.toBigInt(payload.createAt),
           updateAt: this.toBigInt(payload.updateAt),

+ 3 - 3
apps/box-stats-api/src/feature/user-login/user-login.service.ts

@@ -22,13 +22,13 @@ export class UserLoginService {
               : BigInt(event.loginAt),
           ip: event.ip,
           os: event.os ?? null,
-          uChannelId: event.uChannelId ?? null,
+          channelId: event.channelId ?? null,
           machine: event.machine,
         },
         create: {
           uid: event.uid,
           os: event.os ?? null,
-          uChannelId: event.uChannelId ?? null,
+          channelId: event.channelId ?? null,
           machine: event.machine,
           createAt:
             typeof event.loginAt === 'bigint'
@@ -67,7 +67,7 @@ export class UserLoginService {
           userAgent: event.userAgent ?? null,
           appVersion: event.appVersion ?? null,
           os: event.os ?? null,
-          uChannelId: event.uChannelId ?? null,
+          channelId: event.channelId ?? null,
           machine: event.machine,
           createAt,
           tokenId: event.tokenId ?? null,

+ 2 - 2
libs/common/src/events/user-login-event.dto.ts

@@ -6,8 +6,8 @@ export interface UserLoginEventPayload {
   userAgent?: string; // optional, but useful
   appVersion?: string; // optional
   os?: string; // iOS / Android / Browser / Web
-  uChannelId: string; // required channel ID
-  machine: string; // required machine model
+  channelId?: string; // required channel ID
+  machine?: string; // required machine model
 
   tokenId?: string; // JWT jti or session token ID (optional for now)
 

+ 2 - 2
prisma/mongo-stats/schema/ads-click-history.prisma

@@ -8,7 +8,7 @@ model AdsClickHistory {
   ip           String                                   // 点击 IP
   appVersion   String?                                  // 客户端版本 (optional)
   os           String?                                  // iOS / Android / Web (optional)
-  uChannelId   String                                   // 用户自带渠道 Id (required)
+  channelId   String                                   // 用户自带渠道 Id (required)
   machine      String                                   // 客户端提供 : 设备的信息,品牌及系统版本什么的 (required)
 
   clickAt      BigInt                                   // 点击时间 (epoch millis)
@@ -21,7 +21,7 @@ model AdsClickHistory {
   @@index([uid, clickAt])
   
   // 3. Query clicks by channel + user (for reporting)
-  @@index([uChannelId, uid, clickAt])
+  @@index([channelId, uid, clickAt])
   
   // 4. Query clicks by IP (fraud detection)
   @@index([ip, clickAt])

+ 6 - 6
prisma/mongo-stats/schema/events.prisma

@@ -7,7 +7,7 @@ model AdClickEvents {
 
   clickedAt    BigInt                          // 点击时间 (epoch)
   ip           String                          // 点击 IP
-  uChannelId   String                          // 用户自带渠道 Id (required)
+  channelId   String                          // 用户自带渠道 Id (required)
   machine      String                          // 客户端提供 : 设备的信息,品牌及系统版本什么的 (required)
 
   createAt     BigInt                          // 记录创建时间
@@ -19,7 +19,7 @@ model AdClickEvents {
   // 2. 查某设备的点击轨迹
   @@index([uid, clickedAt])
   // 3. 按渠道+设备分析(报表)
-  @@index([uChannelId, uid, clickedAt])
+  @@index([channelId, uid, clickedAt])
   // 4. 按广告类型/时间分析
   @@index([adType, clickedAt])
   // 5. 全局按时间片
@@ -36,7 +36,7 @@ model VideoClickEvents {
 
   clickedAt   BigInt                          // 点击时间 (epoch)
   ip          String                          // 点击 IP
-  uChannelId  String                          // 用户自带渠道 Id (required)
+  channelId  String                          // 用户自带渠道 Id (required)
   machine     String                          // 客户端提供 : 设备的信息,品牌及系统版本什么的 (required)
 
   createAt    BigInt                          // 记录创建时间
@@ -48,7 +48,7 @@ model VideoClickEvents {
   // 2. 查设备点击
   @@index([uid, clickedAt])
   // 3. 按渠道+设备分析(报表)
-  @@index([uChannelId, uid, clickedAt])
+  @@index([channelId, uid, clickedAt])
   // 4. 全局时间窗口
   @@index([clickedAt])
 
@@ -65,7 +65,7 @@ model AdImpressionEvents {
   impressionAt      BigInt                          // 曝光时间 (epoch)
   visibleDurationMs BigInt?                         // 可见时长(毫秒,optional)
   ip                String                          // IP
-  uChannelId        String                          // 用户自带渠道 Id (required)
+  channelId        String                          // 用户自带渠道 Id (required)
   machine           String                          // 客户端提供 : 设备的信息,品牌及系统版本什么的 (required)
 
   createAt          BigInt                          // 记录创建时间
@@ -77,7 +77,7 @@ model AdImpressionEvents {
   // 2. 设备曝光轨迹
   @@index([uid, impressionAt])
   // 3. 按渠道+设备分析(报表)
-  @@index([uChannelId, uid, impressionAt])
+  @@index([channelId, uid, impressionAt])
   // 4. 按广告类型
   @@index([adType, impressionAt])
   // 5. 时间片

+ 2 - 2
prisma/mongo-stats/schema/user-login-history.prisma

@@ -6,7 +6,7 @@ model UserLoginHistory {
   userAgent   String?                         // UA (optional but useful)
   appVersion  String?                         // 客户端版本 (optional)
   os          String?                         // iOS / Android / Browser
-  uChannelId  String                          // 用户自带渠道 Id (required)
+  channelId  String                          // 用户自带渠道 Id (required)
   machine     String                          // 客户端提供 : 设备的信息,品牌及系统版本什么的 (required)
 
   createAt    BigInt                          // 登录时间 (epoch)
@@ -18,7 +18,7 @@ model UserLoginHistory {
   @@index([uid, createAt])
   
   // 2. 按渠道查登陆情况
-  @@index([uChannelId, createAt])
+  @@index([channelId, createAt])
   
   // 3. 查某 IP 的登陆情况(反刷)
   @@index([ip, createAt])

+ 2 - 2
prisma/mongo-stats/schema/user.prisma

@@ -3,7 +3,7 @@ model User {
   uid           String      @unique         // 唯一设备码
   ip            String                      // 最近登录 IP
   os            String?                     // iOS / Android / Browser
-  uChannelId    String                      // 用户自带渠道 Id (required)
+  channelId     String                      // 用户自带渠道 Id (required)
   machine       String                      // 客户端提供 : 设备的信息,品牌及系统版本什么的 (required)
 
   createAt      BigInt      @default(0)     // 注册/创建时间
@@ -13,7 +13,7 @@ model User {
   // 1. 查某设备的登录情况
   @@index([uid, createAt])
   // 2. 按渠道分组统计
-  @@index([uChannelId, createAt])
+  @@index([channelId, createAt])
   // 3. 全局统计(按时间分片)
   @@index([createAt])
 

+ 1 - 1
prisma/mongo/schema/sys-operation-log.prisma

@@ -6,7 +6,7 @@ enum OperationType {
 }
 
 model SysOperationLog {
-  id          String        @id @map("_id")
+  id          String      @id @map("_id") @default(auto()) @db.ObjectId
   username    String?
   menuId      String?          @map("menu_id") @db.ObjectId
   description String