Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support "is" and "contains" condition in issue search #1400

Merged
merged 17 commits into from
Mar 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/api/integration-test/global.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ import { createConnection as connect } from './database-utils';
process.env.NODE_ENV = 'test';
process.env.MYSQL_PRIMARY_URL =
'mysql://root:userfeedback@localhost:13307/integration';
process.env.MYSQL_SECONDARY_URLS = JSON.stringify([
'mysql://root:userfeedback@localhost:13307/integration',
]);
process.env.MASTER_API_KEY = 'master-api-key';
process.env.ENABLE_AUTO_FEEDBACK_DELETION = 'true';
process.env.AUTO_FEEDBACK_DELETION_PERIOD_DAYS = '30';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,8 @@ describe('FeedbackController (integration)', () => {
const findFeedbackDto: FindFeedbacksByChannelIdRequestDtoV2 = {
queries: [
{
[availableFieldKey]: 'test',
key: availableFieldKey,
value: 'test',
condition: QueryV2ConditionsEnum.IS,
},
],
Expand Down Expand Up @@ -382,7 +383,8 @@ describe('FeedbackController (integration)', () => {
const findFeedbackDto: FindFeedbacksByChannelIdRequestDtoV2 = {
queries: [
{
createdAt: {
key: 'createdAt',
value: {
gte: DateTime.fromJSDate(new Date(0)).toFormat('yyyy-MM-dd'),
lt: DateTime.now().toFormat('yyyy-MM-dd'),
},
Expand Down
12 changes: 12 additions & 0 deletions apps/api/integration-test/test-specs/user.integration-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,15 @@ import type { DataSource, Repository } from 'typeorm';
import { AppModule } from '@/app.module';
import { AuthService } from '@/domains/admin/auth/auth.service';
import { RoleEntity } from '@/domains/admin/project/role/role.entity';
import { TenantEntity } from '@/domains/admin/tenant/tenant.entity';
import { TenantService } from '@/domains/admin/tenant/tenant.service';
import type { UserDto } from '@/domains/admin/user/dtos';
import type { GetAllUserResponseDto } from '@/domains/admin/user/dtos/responses/get-all-user-response.dto';
import { UserStateEnum } from '@/domains/admin/user/entities/enums';
import { UserEntity } from '@/domains/admin/user/entities/user.entity';
import {
clearEntities,
createTenant,
getRandomEnumValue,
signInTestUser,
} from '@/test-utils/util-functions';
Expand All @@ -44,6 +47,9 @@ describe('UserController (integration)', () => {
let dataSource: DataSource;
let userRepo: Repository<UserEntity>;
let roleRepo: Repository<RoleEntity>;
let tenantRepo: Repository<TenantEntity>;

let tenantService: TenantService;

let authService: AuthService;
beforeAll(async () => {
Expand All @@ -60,7 +66,13 @@ describe('UserController (integration)', () => {
dataSource = module.get(getDataSourceToken());
userRepo = dataSource.getRepository(UserEntity);
roleRepo = dataSource.getRepository(RoleEntity);
tenantRepo = dataSource.getRepository(TenantEntity);
authService = module.get(AuthService);
tenantService = module.get(TenantService);

await clearEntities([tenantRepo, userRepo, roleRepo]);

await createTenant(tenantService);
});

afterAll(async () => {
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/common/enums/query-v2-conditions.enum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@
export enum QueryV2ConditionsEnum {
CONTAINS = 'CONTAINS',
IS = 'IS',
BETWEEN = 'BETWEEN',
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,9 @@ import type { FieldEntity } from '@/domains/admin/channel/field/field.entity';
export class FindFeedbacksByChannelIdDtoV2 extends PaginationDto {
channelId: number;
queries?: {
createdAt?: TimeRange;
updatedAt?: TimeRange;
ids?: number[];
[key: string]:
| string
| string[]
| TimeRange
| number
| number[]
| undefined;
key: string;
value: string | string[] | TimeRange | number | number[] | undefined;
condition: QueryV2ConditionsEnum;
}[];
sort?: Record<string, SortMethodEnum>;
Expand Down
11 changes: 2 additions & 9 deletions apps/api/src/domains/admin/feedback/dtos/generate-excel.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,9 @@ export class GenerateExcelDto {
projectId: number;
channelId: number;
queries?: {
createdAt?: TimeRange;
updatedAt?: TimeRange;
ids?: number[];
[key: string]:
| string
| string[]
| TimeRange
| number
| number[]
| undefined;
key: string;
value: string | string[] | TimeRange | number | number[] | undefined;
condition: QueryV2ConditionsEnum;
}[];
sort?: Record<string, SortMethodEnum>;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,30 +14,31 @@
* under the License.
*/
import { ApiProperty } from '@nestjs/swagger';
import { IsOptional } from 'class-validator';
import { IsArray, IsEnum, IsOptional, IsString } from 'class-validator';

import { PaginationRequestDto, TimeRange } from '@/common/dtos';
import type { QueryV2ConditionsEnum, SortMethodEnum } from '@/common/enums';
import { QueryV2ConditionsEnum, SortMethodEnum } from '@/common/enums';
import { IsNullable } from '@/domains/admin/user/decorators';

class QueryV2 {
@ApiProperty({
required: false,
type: TimeRange,
example: { gte: '2023-01-01', lt: '2023-12-31' },
})
@ApiProperty({ required: false })
@IsOptional()
createdAt?: TimeRange;
@IsArray()
ids?: number[];

@ApiProperty({
required: false,
type: TimeRange,
example: { gte: '2023-01-01', lt: '2023-12-31' },
})
@IsOptional()
updatedAt?: TimeRange;
@ApiProperty({ required: true })
@IsString()
key: string;

[key: string]: string | string[] | TimeRange | number | number[] | undefined;
@ApiProperty({ required: true })
@IsNullable()
value: string | string[] | TimeRange | number | number[] | undefined;

@ApiProperty({
enum: QueryV2ConditionsEnum,
enumName: 'QueryV2ConditionsEnum',
})
@IsEnum(QueryV2ConditionsEnum)
condition: QueryV2ConditionsEnum;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,9 @@ import type { FieldEntity } from '@/domains/admin/channel/field/field.entity';
export class ScrollFeedbacksDtoV2 {
channelId: number;
queries?: {
createdAt?: TimeRange;
updatedAt?: TimeRange;
ids?: number[];
[key: string]:
| string
| string[]
| TimeRange
| number
| number[]
| undefined;
key: string;
value: string | string[] | TimeRange | number | number[] | undefined;
condition: QueryV2ConditionsEnum;
}[];
sort?: Record<string, SortMethodEnum>;
Expand Down
180 changes: 96 additions & 84 deletions apps/api/src/domains/admin/feedback/feedback.mysql.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,9 +306,11 @@ export class FeedbackMySQLService {
.select('feedbacks')
.where('feedbacks.channel_id = :channelId', { channelId });

const createdAtCondition = queries.find((query) => query.createdAt);
if (createdAtCondition?.createdAt) {
const { gte, lt } = createdAtCondition.createdAt;
const createdAtCondition = queries.find(
(query) => query.key === 'createdAt',
);
if (createdAtCondition?.value) {
const { gte, lt } = createdAtCondition.value as TimeRange;
queryBuilder.andWhere('feedbacks.created_at >= :gte', { gte });
queryBuilder.andWhere('feedbacks.created_at < :lt', { lt });
}
Expand All @@ -321,52 +323,78 @@ export class FeedbackMySQLService {
new Brackets((qb) => {
let paramIndex = 0;
for (const query of queries) {
for (const [fieldKey, value] of Object.entries(query)) {
if (fieldKey === 'condition' || fieldKey === 'createdAt') continue;

const paramName = `value${paramIndex++}`;

if (fieldKey === 'id') {
qb[method](`feedbacks.id = :${paramName}`, {
[paramName]: value,
});
} else if (fieldKey === 'ids') {
qb[method](`feedbacks.id IN(:${paramName})`, {
[paramName]: value,
});
} else if (fieldKey === 'issueIds') {
qb[method]('feedbacks_issues_issues.issues_id IN(:issueIds)', {
issueIds: value,
});
} else if (fieldKey === 'updatedAt') {
const { gte, lt } = value as TimeRange;
qb[method](`feedbacks.updated_at >= :gte${paramName}`, {
[paramName]: gte,
});
qb[method](`feedbacks.updated_at < :lt${paramName}`, {
[paramName]: lt,
});
const fieldKey = query.key;
const value = query.value;

if (fieldKey === 'createdAt') continue;

const paramName = `value${paramIndex++}`;

if (fieldKey === 'id') {
qb[method](`feedbacks.id = :${paramName}`, {
[paramName]: value,
});
} else if (fieldKey === 'ids') {
qb[method](`feedbacks.id IN(:${paramName})`, {
[paramName]: value,
});
} else if (fieldKey === 'issueIds') {
const condition = query.condition;
const issueIds = value as string[];

if (condition === QueryV2ConditionsEnum.IS) {
queryBuilder.having(
"JSON_LENGTH(JSON_ARRAYAGG(feedbacks_issues_issues.issues_id)) = :arrayLength AND JSON_CONTAINS(JSON_ARRAYAGG(feedbacks_issues_issues.issues_id), JSON_ARRAY(:...issueIds), '$')",
{ arrayLength: issueIds.length, issueIds },
);
} else {
const { format }: { format: FieldFormatEnum } = fields.find(
(v) => v.key === fieldKey,
) ?? { format: FieldFormatEnum.date };

if (format === FieldFormatEnum.select) {
const option =
options.find((option) => option.key === value) ??
new OptionEntity();

qb[method](
'feedbacks_issues_issues.issues_id IN (:...issueIds)',
{ issueIds },
);
}
} else if (fieldKey === 'updatedAt') {
const { gte, lt } = value as TimeRange;
qb[method](`feedbacks.updated_at >= :gte${paramName}`, {
[paramName]: gte,
});
qb[method](`feedbacks.updated_at < :lt${paramName}`, {
[paramName]: lt,
});
} else {
const { format }: { format: FieldFormatEnum } = fields.find(
(v) => v.key === fieldKey,
) ?? { format: FieldFormatEnum.date };

if (format === FieldFormatEnum.select) {
const option =
options.find((option) => option.key === value) ??
new OptionEntity();

qb[method](
`JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"') = :optionId`,
{ optionId: option.key },
);
} else if (format === FieldFormatEnum.multiSelect) {
const condition = query.condition;
const values = value as string[];

if (condition === QueryV2ConditionsEnum.IS) {
qb[method](
`JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"') = :optionId`,
{ optionId: option.key },
`JSON_LENGTH(JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"')) = :arrayLength AND JSON_CONTAINS(
(SELECT JSON_ARRAYAGG(jt.value) FROM JSON_TABLE(
JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"'),
'$[*]' COLUMNS(value VARCHAR(255) PATH '$')
) AS jt),
JSON_ARRAY(${values.map((optionKey) => `'${optionKey}'`).join(', ')}),
'$'
)`,
{ arrayLength: values.length },
);
} else if (format === FieldFormatEnum.multiSelect) {
const condition = query.condition;
const values = value as string[];

if (condition === QueryV2ConditionsEnum.IS) {
} else if (condition === QueryV2ConditionsEnum.CONTAINS) {
if (values.length > 0) {
qb[method](
`JSON_LENGTH(JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"')) = :arrayLength AND JSON_CONTAINS(
`JSON_LENGTH(JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"')) >= :arrayLength AND JSON_CONTAINS(
(SELECT JSON_ARRAYAGG(jt.value) FROM JSON_TABLE(
JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"'),
'$[*]' COLUMNS(value VARCHAR(255) PATH '$')
Expand All @@ -377,47 +405,31 @@ export class FeedbackMySQLService {
{ arrayLength: values.length },
);
} else {
if (values.length > 0) {
qb[method](
new Brackets((subQb) => {
for (const optionKey of values) {
subQb.andWhere(
`JSON_CONTAINS(
JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"'),
'"${optionKey}"',
'$'
)`,
);
}
}),
);
} else {
qb[method]('1 = 0');
}
qb[method]('1 = 0');
}
} else if (format === FieldFormatEnum.text) {
qb[method](
`JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"') like :${paramName}`,
{ [paramName]: `%${value as string | number}%` },
);
} else if (format === FieldFormatEnum.date) {
const { gte, lt } = value as TimeRange;
qb[method](
`JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"') >= :gte${paramName}`,
{ [paramName]: gte },
);
qb[method](
`JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"') < :lt${paramName}`,
{ [paramName]: lt },
);
} else {
qb[method](
`JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"') = :${paramName}`,
{
[paramName]: value,
},
);
}
} else if (format === FieldFormatEnum.text) {
qb[method](
`JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"') like :${paramName}`,
{ [paramName]: `%${value as string | number}%` },
);
} else if (format === FieldFormatEnum.date) {
const { gte, lt } = value as TimeRange;
qb[method](
`JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"') >= :gte${paramName}`,
{ [paramName]: gte },
);
qb[method](
`JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"') < :lt${paramName}`,
{ [paramName]: lt },
);
} else {
qb[method](
`JSON_EXTRACT(feedbacks.data, '$."${fieldKey}"') = :${paramName}`,
{
[paramName]: value,
},
);
}
}
}
Expand Down
Loading