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: default value for all suitable fields #933

Merged
merged 1 commit into from
Sep 21, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -670,22 +670,29 @@ export class FieldSupplementService {
};
}

private prepareSelectOptions(options: ISelectFieldOptionsRo) {
private prepareSelectOptions(options: ISelectFieldOptionsRo, isMultiple: boolean) {
const optionsRo = (options ?? SelectFieldCore.defaultOptions()) as ISelectFieldOptionsRo;
const nameSet = new Set<string>();
const choices = optionsRo.choices.map((choice) => {
if (nameSet.has(choice.name)) {
throw new BadRequestException(`choice name ${choice.name} is duplicated`);
}
nameSet.add(choice.name);
return {
name: choice.name,
id: choice.id ?? generateChoiceId(),
color: choice.color ?? ColorUtils.randomColor()[0],
};
});

const defaultValue = optionsRo.defaultValue
? [optionsRo.defaultValue].flat().filter((name) => nameSet.has(name))
: undefined;

return {
...optionsRo,
choices: optionsRo.choices.map((choice) => {
if (nameSet.has(choice.name)) {
throw new BadRequestException(`choice name ${choice.name} is duplicated`);
}
nameSet.add(choice.name);
return {
name: choice.name,
id: choice.id ?? generateChoiceId(),
color: choice.color ?? ColorUtils.randomColor()[0],
};
}),
defaultValue: isMultiple ? defaultValue : defaultValue?.[0],
choices,
};
}

Expand All @@ -695,7 +702,7 @@ export class FieldSupplementService {
return {
...field,
name: name ?? 'Select',
options: this.prepareSelectOptions(options as ISelectFieldOptionsRo),
options: this.prepareSelectOptions(options as ISelectFieldOptionsRo, false),
cellValueType: CellValueType.String,
dbFieldType: DbFieldType.Text,
};
Expand All @@ -707,7 +714,7 @@ export class FieldSupplementService {
return {
...field,
name: name ?? 'Tags',
options: this.prepareSelectOptions(options as ISelectFieldOptionsRo),
options: this.prepareSelectOptions(options as ISelectFieldOptionsRo, true),
cellValueType: CellValueType.String,
dbFieldType: DbFieldType.Json,
isMultipleCellValue: true,
Expand All @@ -728,19 +735,27 @@ export class FieldSupplementService {
}

private async prepareUpdateUserField(fieldRo: IFieldRo, oldFieldVo: IFieldVo) {
const mergeObj = merge({}, oldFieldVo, fieldRo);
const mergeObj = {
...oldFieldVo,
...fieldRo,
};

return this.prepareUserField(mergeObj);
}

private prepareUserField(field: IFieldRo) {
const { name, options = UserFieldCore.defaultOptions() } = field;
const { isMultiple } = options as IUserFieldOptions;
const { name } = field;
const options: IUserFieldOptions = field.options || UserFieldCore.defaultOptions();
const { isMultiple } = options;
const defaultValue = options.defaultValue ? [options.defaultValue].flat() : undefined;

return {
...field,
name: name ?? `Collaborator${isMultiple ? 's' : ''}`,
options: options,
options: {
...options,
defaultValue: isMultiple ? defaultValue : defaultValue?.[0],
},
cellValueType: CellValueType.String,
dbFieldType: DbFieldType.Json,
isMultipleCellValue: isMultiple || undefined,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import type { IMakeOptional } from '@teable/core';
import type { IMakeOptional, IUserFieldOptions } from '@teable/core';
import { FieldKeyType, generateRecordId, FieldType } from '@teable/core';
import { PrismaService } from '@teable/db-main-prisma';
import type { ICreateRecordsRo, ICreateRecordsVo, IRecord } from '@teable/openapi';
import { isEmpty, keyBy } from 'lodash';
import { isEmpty, keyBy, uniq } from 'lodash';
import { ClsService } from 'nestjs-cls';
import type { IClsStore } from '../../../types/cls';
import { BatchService } from '../../calculation/batch.service';
import { FieldCalculationService } from '../../calculation/field-calculation.service';
import { LinkService } from '../../calculation/link.service';
Expand All @@ -24,7 +26,8 @@ export class RecordCalculateService {
private readonly recordService: RecordService,
private readonly linkService: LinkService,
private readonly referenceService: ReferenceService,
private readonly fieldCalculationService: FieldCalculationService
private readonly fieldCalculationService: FieldCalculationService,
private readonly clsService: ClsService<IClsStore>
) {}

async multipleCreateRecords(
Expand Down Expand Up @@ -201,30 +204,130 @@ export class RecordCalculateService {
fieldKeyType: FieldKeyType,
fieldRaws: IFieldRaws
) {
return records.map((record) => {
const processedRecords = records.map((record) => {
const fields: { [fieldIdOrName: string]: unknown } = { ...record.fields };
for (const fieldRaw of fieldRaws) {
const { type, options } = fieldRaw;
if (options == null) continue;
const { defaultValue } = JSON.parse(options) || {};
const { type, options, isComputed } = fieldRaw;
if (options == null || isComputed) continue;
const optionsObj = JSON.parse(options) || {};
const { defaultValue } = optionsObj;
if (defaultValue == null) continue;
const fieldIdOrName = fieldRaw[fieldKeyType];
if (fields[fieldIdOrName] != null) continue;
fields[fieldIdOrName] = this.getDefaultValue(type as FieldType, defaultValue);
fields[fieldIdOrName] = this.getDefaultValue(type as FieldType, optionsObj, defaultValue);
}

return {
...record,
fields,
};
});

// After process to handle user field
const userFields = fieldRaws.filter((fieldRaw) => fieldRaw.type === FieldType.User);
if (userFields.length > 0) {
return await this.fillUserInfo(processedRecords, userFields, fieldKeyType);
}

return processedRecords;
}

private async fillUserInfo(
records: { id: string; fields: { [fieldNameOrId: string]: unknown } }[],
userFields: IFieldRaws,
fieldKeyType: FieldKeyType
) {
const userIds = new Set<string>();
records.forEach((record) => {
userFields.forEach((field) => {
const fieldIdOrName = field[fieldKeyType];
const value = record.fields[fieldIdOrName];
if (value) {
if (Array.isArray(value)) {
value.forEach((v) => userIds.add(v.id));
} else {
userIds.add((value as { id: string }).id);
}
}
});
});

const userInfo = await this.getUserInfoFromDatabase(Array.from(userIds));

return records.map((record) => {
const updatedFields = { ...record.fields };
userFields.forEach((field) => {
const fieldIdOrName = field[fieldKeyType];
const value = updatedFields[fieldIdOrName];
if (value) {
if (Array.isArray(value)) {
updatedFields[fieldIdOrName] = value.map((v) => ({
...v,
...userInfo[v.id],
}));
} else {
updatedFields[fieldIdOrName] = {
...value,
...userInfo[(value as { id: string }).id],
};
}
}
});
return {
...record,
fields: updatedFields,
};
});
}

private async getUserInfoFromDatabase(
userIds: string[]
): Promise<{ [id: string]: { id: string; title: string; email: string } }> {
const usersRaw = await this.prismaService.txClient().user.findMany({
where: {
id: { in: userIds },
deletedTime: null,
},
select: {
id: true,
name: true,
email: true,
},
});
return keyBy(
usersRaw.map((user) => ({ id: user.id, title: user.name, email: user.email })),
'id'
);
}

private transformUserDefaultValue(options: IUserFieldOptions, defaultValue: string | string[]) {
const currentUserId = this.clsService.get('user.id');
const defaultIds = uniq([defaultValue].flat().map((id) => (id === 'me' ? currentUserId : id)));

if (options.isMultiple) {
return defaultIds.map((id) => ({ id }));
}
return defaultIds[0] ? { id: defaultIds[0] } : undefined;
}

private getDefaultValue(type: FieldType, defaultValue: unknown) {
if (type === FieldType.Date && defaultValue === 'now') {
return new Date().toISOString();
private getDefaultValue(type: FieldType, options: unknown, defaultValue: unknown) {
switch (type) {
case FieldType.Date:
return defaultValue === 'now' ? new Date().toISOString() : defaultValue;
case FieldType.SingleSelect:
return Array.isArray(defaultValue) ? defaultValue[0] : defaultValue;
case FieldType.MultipleSelect:
return Array.isArray(defaultValue) ? defaultValue : [defaultValue];
case FieldType.User:
return this.transformUserDefaultValue(
options as IUserFieldOptions,
defaultValue as string | string[]
);
case FieldType.Checkbox:
return defaultValue ? true : null;
default:
return defaultValue;
}
return defaultValue;
}

async createRecords(
Expand Down Expand Up @@ -253,6 +356,7 @@ export class RecordCalculateService {
options: true,
unique: true,
notNull: true,
isComputed: true,
isLookup: true,
dbFieldName: true,
},
Expand Down
10 changes: 9 additions & 1 deletion apps/nestjs-backend/src/features/record/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,13 @@ import type { Field } from '@prisma/client';

export type IFieldRaws = Pick<
Field,
'id' | 'name' | 'type' | 'options' | 'unique' | 'notNull' | 'isLookup' | 'dbFieldName'
| 'id'
| 'name'
| 'type'
| 'options'
| 'unique'
| 'notNull'
| 'isComputed'
| 'isLookup'
| 'dbFieldName'
>[];
Loading
Loading