import Constants from "~/application/Constants"; import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes"; import { DefaultVisibility } from "~/application/dtos/shared/DefaultVisibility"; import { PropertyType } from "~/application/enums/entities/PropertyType"; import { EntitiesTemplateDto, TemplateEntityDto, TemplateEntityViewDto } from "~/modules/templates/EntityTemplateDto"; import getMaxEntityOrder, { createEntity, EntityWithDetails, findEntityByName, getEntityByName } from "../../db/entities/entities.db.server"; import { createEntityRelationship, EntityRelationshipWithDetails } from "../../db/entities/entityRelationships.db.server"; import { createEntityView, updateEntityViewProperties, updateEntityViewFilters, updateEntityViewSort } from "../../db/entities/entityViews.db.server"; import { createProperty, updatePropertyOptions, updatePropertyAttributes, getEntityPropertyByName } from "../../db/entities/properties.db.server"; import { createEntityPermissions } from "../../db/permissions/permissions.db.server"; import EntityViewHelper from "../../helpers/EntityViewHelper"; import OrderHelper from "../../helpers/OrderHelper"; import { mapToEntityTemplateType } from "../../helpers/PropertyHelper"; export async function validateEntitiesFromTemplate(template: EntitiesTemplateDto) { if (template.entities.length === 0) { throw Error("Invalid configuration"); } await Promise.all( template.entities.map(async (entity) => { const existingEntity = await findEntityByName({ tenantId: null, name: entity.name }); if (existingEntity) { throw Error("Entity already exists: " + entity.name); } if (!entity.properties || entity.properties.length === 0) { throw Error("Entity has no properties: " + entity.name); } entity.properties.forEach((property) => { if (property.name.includes(" ")) { throw Error("Property names cannot contain spaces: " + property.name); } if (property.name.includes("-")) { throw Error("Property names cannot contain '-': " + property.name); } }); }) ); } export async function importEntitiesFromTemplate({ template, createdByUserId }: { template: EntitiesTemplateDto; createdByUserId: string }) { const maxEntityOrder = await getMaxEntityOrder(); const createdEntities = await Promise.all( template.entities.map(async (entity, idx) => { const createdEntity = await createEntity( { name: entity.name, slug: entity.slug, prefix: entity.prefix, title: entity.title, titlePlural: entity.titlePlural, isAutogenerated: entity.isAutogenerated ?? true, hasApi: entity.hasApi ?? true, icon: entity.icon ?? "", active: entity.active ?? true, type: entity.type ?? DefaultEntityTypes.All, showInSidebar: entity.showInSidebar ?? true, hasTags: entity.hasTags ?? true, hasComments: entity.hasComments ?? true, hasTasks: entity.hasTasks ?? false, hasActivity: entity.hasActivity !== undefined ? entity.hasActivity : true, hasBulkDelete: entity.hasBulkDelete !== undefined ? entity.hasBulkDelete : false, hasViews: entity.hasViews !== undefined ? entity.hasViews : true, defaultVisibility: entity.defaultVisibility ?? DefaultVisibility.Tenant, onCreated: entity.onCreated ?? "redirectToOverview", onEdit: entity.onEdit ?? "editRoute", }, maxEntityOrder + idx + 1 ); // eslint-disable-next-line no-console console.log("Entity created", createdEntity.name); if (!createdEntity) { throw new Error("Unable to create entity: " + JSON.stringify(entity)); } await createEntityPermissions(createdEntity); const newEntity = await getEntityByName({ tenantId: null, name: createdEntity.name }); const propertyOrder = OrderHelper.getNextOrder(newEntity.properties); const properties = await Promise.all( entity.properties.map(async (property, idxProperty) => { let type: PropertyType | undefined = undefined; if (property.type === "string") { type = PropertyType.TEXT; } else if (property.type === "number") { type = PropertyType.NUMBER; } else if (property.type === "boolean") { type = PropertyType.BOOLEAN; } else if (property.type === "date") { type = PropertyType.DATE; } else if (property.type === "media") { type = PropertyType.MEDIA; } else if (property.type === "select") { type = PropertyType.SELECT; } else if (property.type === "multiSelect") { type = PropertyType.MULTI_SELECT; } else if (property.type === "multiText") { type = PropertyType.MULTI_TEXT; } else if (property.type === "rangeNumber") { type = PropertyType.RANGE_NUMBER; } else if (property.type === "rangeDate") { type = PropertyType.RANGE_DATE; } else if (property.type === "formula") { type = PropertyType.FORMULA; } else { throw new Error("Invalid property type: " + property.type); } const createdProperty = await createProperty({ entityId: createdEntity.id, name: property.name, title: property.title, type, subtype: property.subtype ?? null, order: propertyOrder + idxProperty, isDefault: false, isRequired: property.isRequired ?? false, isHidden: false, isDisplay: property.isDisplay ?? false, isReadOnly: property.isReadOnly ?? false, canUpdate: property.canUpdate !== undefined ? property.canUpdate : true, showInCreate: property.showInCreate ?? true, formulaId: null, tenantId: property.tenantId ?? null, }); if (property.options) { await updatePropertyOptions( createdProperty.id, property.options.map((item, idxOption) => { return { order: idxOption + 1, value: item.value, name: item.name, color: item.color === undefined ? undefined : item.color, }; }) ); } if (property.attributes) { await updatePropertyAttributes( createdProperty.id, property.attributes.map((item) => { return { value: item.value, name: item.name, }; }) ); } return createdProperty; }) ); // Views if (entity.views) { await Promise.all( entity.views.map(async (view, idx) => { const groupByProperty = properties.find((f) => f.name === view.groupByProperty); if (view.tenantId) { return; } const entityView = await createEntityView({ order: idx + 1, entityId: createdEntity.id, layout: view.layout, name: view.name, title: view.title, isDefault: view.isDefault ?? false, tenantId: null, userId: view.userId ?? null, createdByUserId, isSystem: view.isSystem ?? false, pageSize: view.pageSize ?? Constants.DEFAULT_PAGE_SIZE, groupByPropertyId: groupByProperty?.id ?? null, }); let viewProperties: { propertyId: string | null; order: number; name: string }[] = view.properties ? await Promise.all( view.properties.map(async (prop, idxProp) => { const property = await getEntityPropertyByName(createdEntity.id, prop); return { order: idxProp + 1, propertyId: property?.id ?? null, name: prop, }; }) ) : []; if (viewProperties.length === 0) { viewProperties = newEntity.properties.map((item) => { return { propertyId: item.id, order: item.order, name: item.name, }; }); } const viewFilters: { name: string; condition: string; value: string; match: "and" | "or" }[] = view.filters?.map((filter) => { return { match: filter.match ?? "and", name: filter.name, condition: filter.condition, value: filter.value, }; }) ?? []; const viewSort: { name: string; asc: boolean; order: number }[] = view.sort?.map((sort, idxSort) => { return { name: sort.name, asc: sort.asc, order: idxSort + 1, }; }) ?? []; await updateEntityViewProperties(entityView.id, viewProperties); await updateEntityViewFilters(entityView.id, viewFilters); await updateEntityViewSort(entityView.id, viewSort); }) ); } return createdEntity; }) ); if (createdEntities.length > 0 && template.relationships) { await Promise.all( template.relationships.map(async (relationship) => { const fromEntity = await getEntityByName({ tenantId: null, name: relationship.parent }); const toEntity = await getEntityByName({ tenantId: null, name: relationship.child }); return await createEntityRelationship({ parentId: fromEntity.id, childId: toEntity.id, order: relationship.order ?? 0, title: relationship.title ?? null, type: relationship.type ?? "one-to-many", required: relationship.required ?? false, cascade: false, readOnly: relationship.readOnly ?? false, hiddenIfEmpty: relationship.hiddenIfEmpty !== undefined ? relationship.hiddenIfEmpty : false, childEntityViewId: null, parentEntityViewId: null, }); }) ); } return createdEntities; }