Skip to content

Commit

Permalink
Merge pull request #7992 from ever-co/develop
Browse files Browse the repository at this point in the history
Release
  • Loading branch information
evereq authored Jul 21, 2024
2 parents 91bbbd4 + f985d4e commit e7eb283
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 66 deletions.
47 changes: 34 additions & 13 deletions packages/core/src/core/seeds/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,24 +6,43 @@ import * as path from 'path';
import * as rimraf from 'rimraf';

/**
* Copy ever icons
* Copy assets from the source directory to the destination directory.
*
* @param fileName
* @param config
* @returns
* @param filename The name of the file to copy.
* @param config The application configuration.
* @param destDir The destination directory.
* @returns The destination file path.
*/
export function copyAssets(filename: string, config: Partial<ApplicationPluginConfig>, destDir: string = 'ever-icons') {
try {
const dir = env.isElectron
? path.join(env.gauzySeedPath, destDir)
: path.join(config.assetOptions.assetPath, ...['seed', destDir]) ||
path.resolve(__dirname, '../../../', ...['apps', 'api', 'src', 'assets', 'seed', destDir]);
// Check if electron
const isElectron = env.isElectron;
// Default public directory for assets
const publicDir = path.resolve(__dirname, '../../../', ...['apps', 'api', 'public']);

// Default seed directory for assets
const defaultSeedDir = path.resolve(
__dirname,
'../../../',
...['apps', 'api', 'src', 'assets', 'seed', destDir]
);

// Custom seed directory for assets
const customSeedDir = path.join(config.assetOptions.assetPath, ...['seed', destDir]);

const baseDir = env.isElectron
? path.resolve(env.gauzyUserPath, ...['public'])
: config.assetOptions.assetPublicPath || path.resolve(__dirname, '../../../', ...['apps', 'api', 'public']);
// Base directory for assets
const dir = isElectron ? path.join(env.gauzySeedPath, destDir) : customSeedDir || defaultSeedDir;

// Custom public directory for assets
const assetPublicPath = config.assetOptions.assetPublicPath;

// Base directory for assets
const baseDir = isElectron ? path.resolve(env.gauzyUserPath, ...['public']) : assetPublicPath || publicDir;

// File path
const filepath = filename.replace(/\\/g, '/');
// create folders all the way down

// Create folders all the way down
const folders = filepath.split('/').slice(0, -1); // remove last item, filename
folders.reduce((acc, folder) => {
const folderPath = path.join(acc, folder);
Expand All @@ -36,6 +55,8 @@ export function copyAssets(filename: string, config: Partial<ApplicationPluginCo
// copy files from source to destination folder
const destFilePath = path.join(destDir, filename);
fs.copyFileSync(path.join(dir, filename), path.join(baseDir, destFilePath));

// Return the destination file path
return destFilePath;
} catch (error) {
console.log('Error while copy ever icons for seeder', error);
Expand All @@ -60,7 +81,7 @@ export async function cleanAssets(config: Partial<ApplicationPluginConfig>, dest
rimraf(
`${dir}/!(rimraf|.gitkeep)`,
() => {
console.log(chalk.green(`CLEANED UP EVER ICONS`));
console.log(chalk.green(`CLEANED UP EVER ICONS: ${dir}`));
resolve(null);
},
() => {
Expand Down
16 changes: 8 additions & 8 deletions packages/core/src/image-asset/image-asset.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,18 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Exclude } from 'class-transformer';
import { IsBoolean, IsNotEmpty, IsNumber, IsOptional, IsString } from 'class-validator';
import { ColumnNumericTransformerPipe } from './../shared/pipes';
import { Product, TenantOrganizationBaseEntity, Equipment, Warehouse } from './../core/entities/internal';
import {
Product,
TenantOrganizationBaseEntity,
Equipment,
Warehouse
} from './../core/entities/internal';
import { MultiORMColumn, MultiORMEntity, MultiORMManyToMany, MultiORMOneToMany, VirtualMultiOrmColumn } from './../core/decorators/entity';
MultiORMColumn,
MultiORMEntity,
MultiORMManyToMany,
MultiORMOneToMany,
VirtualMultiOrmColumn
} from './../core/decorators/entity';
import { MikroOrmImageAssetRepository } from './repository/mikro-orm-image-asset.repository';

@MultiORMEntity('image_asset', { mikroOrmRepository: () => MikroOrmImageAssetRepository })
export class ImageAsset extends TenantOrganizationBaseEntity implements IImageAsset {

@ApiPropertyOptional({ type: () => String })
@IsOptional()
@IsString()
Expand All @@ -25,7 +25,7 @@ export class ImageAsset extends TenantOrganizationBaseEntity implements IImageAs
@IsNotEmpty()
@IsString()
@MultiORMColumn()
url: string
url: string;

@ApiProperty({ type: () => String })
@IsString()
Expand Down
27 changes: 11 additions & 16 deletions packages/core/src/image-asset/image-asset.subscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,18 @@ export class ImageAssetSubscriber extends BaseEntityEventSubscriber<ImageAsset>
* @returns A promise that resolves when the URL updating process is complete.
*/
async afterEntityLoad(entity: ImageAsset): Promise<void> {
return new Promise<void>(async (resolve, reject) => {
try {
if (entity instanceof ImageAsset) {
const { storageProvider, url, thumb } = entity;
const store = new FileStorage().setProvider(storageProvider).getProviderInstance();
try {
if (entity instanceof ImageAsset) {
const { storageProvider, url, thumb } = entity;
const store = new FileStorage().setProvider(storageProvider).getProviderInstance();

// Retrieve full and thumbnail URLs concurrently
const [fullUrl, thumbUrl] = await Promise.all([store.url(url), store.url(thumb)]);
entity.fullUrl = fullUrl;
entity.thumbUrl = thumbUrl;

resolve();
}
} catch (error) {
console.error('ImageAssetSubscriber: Error during the afterEntityLoad process:', error);
reject(null);
// Retrieve full and thumbnail URLs concurrently
const [fullUrl, thumbUrl] = await Promise.all([store.url(url), store.url(thumb)]);
entity.fullUrl = fullUrl;
entity.thumbUrl = thumbUrl;
}
});
} catch (error) {
console.error('ImageAssetSubscriber: Error during the afterEntityLoad process:', error);
}
}
}
8 changes: 4 additions & 4 deletions packages/core/src/tasks/issue-type/issue-type.entity.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { JoinColumn, RelationId } from 'typeorm';
import { IsNotEmpty, IsOptional, IsString, IsUUID } from 'class-validator';
import { IImageAsset, IIssueType, IOrganizationProject, IOrganizationTeam } from '@gauzy/contracts';
import { ID, IImageAsset, IIssueType, IOrganizationProject, IOrganizationTeam } from '@gauzy/contracts';
import {
ImageAsset,
OrganizationProject,
Expand Down Expand Up @@ -87,7 +87,7 @@ export class IssueType extends TenantOrganizationBaseEntity implements IIssueTyp
@RelationId((it: IssueType) => it.image)
@ColumnIndex()
@MultiORMColumn({ nullable: true, relationId: true })
imageId?: IImageAsset['id'];
imageId?: ID;

/**
* Organization Project
Expand All @@ -103,7 +103,7 @@ export class IssueType extends TenantOrganizationBaseEntity implements IIssueTyp
@RelationId((it: IssueType) => it.project)
@ColumnIndex()
@MultiORMColumn({ nullable: true, relationId: true })
projectId?: IOrganizationProject['id'];
projectId?: ID;

/**
* Organization Team
Expand All @@ -119,5 +119,5 @@ export class IssueType extends TenantOrganizationBaseEntity implements IIssueTyp
@RelationId((it: IssueType) => it.organizationTeam)
@ColumnIndex()
@MultiORMColumn({ nullable: true, relationId: true })
organizationTeamId?: IOrganizationTeam['id'];
organizationTeamId?: ID;
}
59 changes: 34 additions & 25 deletions packages/core/src/tasks/issue-type/issue-type.seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ import { DataSource } from 'typeorm';
import * as path from 'path';
import * as fs from 'fs';
import { imageSize } from 'image-size';
import { getConfig } from '@gauzy/config';
import { environment as env, getConfig } from '@gauzy/config';
import { FileStorageProviderEnum, IIssueType } from '@gauzy/contracts';
import { ImageAsset } from './../../core/entities/internal';
import { cleanAssets, copyAssets } from './../../core/seeds/utils';
import { DEFAULT_GLOBAL_ISSUE_TYPES } from './default-global-issue-types';
import { IssueType } from './issue-type.entity';
import { environment as env } from '@gauzy/config';

/**
* Default global system issue types
Expand All @@ -19,36 +18,46 @@ import { environment as env } from '@gauzy/config';
export const createDefaultIssueTypes = async (dataSource: DataSource): Promise<IIssueType[]> => {
await cleanAssets(getConfig(), path.join('ever-icons', 'task-issue-types'));

let issueTypes: IIssueType[] = [];
try {
let issueTypes: IIssueType[] = [];

const isElectron = env.isElectron; // Check if electron
const publicDir = path.resolve(__dirname, '../../../', ...['apps', 'api', 'public']); // Default public directory for assets
const assetPublicPath = getConfig().assetOptions.assetPublicPath || publicDir; // Custom public directory for assets
const baseDir = isElectron ? path.resolve(env.gauzyUserPath, ...['public']) : assetPublicPath; // Base directory for assets

// Copy default issue types icons
for await (const issueType of DEFAULT_GLOBAL_ISSUE_TYPES) {
//Copy issue type icon
const iconPath = copyAssets(issueType.icon, getConfig());
const baseDir = env.isElectron
? path.resolve(env.gauzyUserPath, ...['public'])
: getConfig().assetOptions.assetPublicPath ||
path.resolve(__dirname, '../../../', ...['apps', 'api', 'public']);
const absoluteFilePath = path.join(baseDir, iconPath)

const absoluteFilePath = path.join(baseDir, iconPath);
const { height = 0, width = 0 } = imageSize(absoluteFilePath);
const { size } = fs.statSync(absoluteFilePath);
const icon = new ImageAsset();
icon.name = issueType.name;
icon.url = iconPath;
icon.storageProvider = FileStorageProviderEnum.LOCAL;
icon.height = height;
icon.width = width;
icon.size = size;

const image = await dataSource.manager.save(icon);
issueTypes.push(
new IssueType({
...issueType,
icon: iconPath,
image
})
);

try {
const icon = new ImageAsset();
icon.name = issueType.name;
icon.url = iconPath;
icon.storageProvider = FileStorageProviderEnum.LOCAL;
icon.height = height;
icon.width = width;
icon.size = size;

const image = await dataSource.getRepository(ImageAsset).save(icon);
issueTypes.push(new IssueType({ ...issueType, icon: iconPath, image }));
} catch (error) {
console.error('Error while saving issue type icon', error?.message);
issueTypes.push(new IssueType({ ...issueType, icon: undefined }));
}
}

try {
return await dataSource.manager.save(issueTypes);
} catch (error) {
console.log('Error while saving issue types', error);
}
} catch (error) {
console.log('Error while moving task issue type icons', error);
}
return await dataSource.manager.save(issueTypes);
};

0 comments on commit e7eb283

Please sign in to comment.