Skip to content

Commit

Permalink
user search + midjourney changes
Browse files Browse the repository at this point in the history
  • Loading branch information
ehsan-g committed Feb 16, 2024
1 parent 2e66d92 commit 3834329
Show file tree
Hide file tree
Showing 12 changed files with 124 additions and 38 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ lerna-debug.log*
# images
/uploads
midjourney.json
src/features/midjourney/bad-images-to-remove.json

# OS
.DS_Store
Expand Down
3 changes: 2 additions & 1 deletion nest-cli.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"compilerOptions": {
"assets": [
"features/campaign/templates/**/*",
"features/children/**/*"
"features/children/**/*",
"features/midjourney/**/*"
],
"watchAssets": true
}
Expand Down
4 changes: 0 additions & 4 deletions src/entities/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,4 @@ export class AllUserEntity extends BaseEntity {
@Column({ default: true })
monthlyCampaign: boolean;

@OneToMany(() => CampaignEntity, (e) => e.receivers, {
eager: false,
})
receivedEmails: CampaignEntity[];
}
22 changes: 21 additions & 1 deletion src/features/family/family.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
Get,
Param,
Patch,
Query,
Req,
} from '@nestjs/common';
import { FamilyService } from './family.service';
Expand Down Expand Up @@ -47,7 +48,26 @@ export class FamilyController {
private childrenService: ChildrenService,
private needService: NeedService,
private paymentService: PaymentService,
) { }
) {}

@Get('search')
async searchUsers(
@Req() req: Request,
@Query('q') query: string,
): Promise<any> {
const panelFlaskUserId = req.headers['panelFlaskUserId'];
const panelFlaskTypeId = req.headers['panelFlaskTypeId'];
if (
!isAuthenticated(panelFlaskUserId, panelFlaskTypeId) ||
panelFlaskTypeId !== FlaskUserTypesEnum.SUPER_ADMIN
) {
throw new ForbiddenException('You Are not the Super admin');
}
if (query.length > 3) {
const users = await this.familyService.searchUsers(query);
return { users };
}
}

@Get(`my/children/:familyUserId`)
@ApiOperation({ description: 'Get my children' })
Expand Down
12 changes: 12 additions & 0 deletions src/features/family/family.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ export class FamilyService {
private flaskUserFamilyRepository: Repository<UserFamily>,
) {}

async searchUsers(query: string): Promise<User[]> {
return this.flaskUserRepository
.createQueryBuilder('user')
.where(
'user.userName ILIKE :query OR user.emailAddress ILIKE :query OR user.phone_number ILIKE :query OR user.firstName ILIKE :query',
{
query: `%${query}%`,
},
)
.getMany();
}

async getFamilyMembers(familyId: number): Promise<any> {
return await this.flaskFamilyRepository
.createQueryBuilder('family')
Expand Down
90 changes: 72 additions & 18 deletions src/features/midjourney/midjourney.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ import {
} from 'src/types/interfaces/interface';
import { WalletExceptionFilter } from 'src/filters/wallet-exception.filter';
import { checkIfFileOrDirectoryExists } from 'src/utils/file';
import fs from 'fs';
import path from 'path';

@ApiTags('Midjourney')
@Controller('midjourney')
Expand All @@ -34,7 +36,7 @@ export class MidjourneyController {
private readonly downloadService: DownloadService,
private readonly needService: NeedService,
private readonly familyService: FamilyService,
) { }
) {}

@Get(`db/all`)
@ApiSecurity('flask-access-token')
Expand Down Expand Up @@ -231,8 +233,49 @@ export class MidjourneyController {
});
}

@Delete(`images/:flaskNeedId`)
@Delete(`bad/images`)
@ApiOperation({ description: 'Delete folder of need images' })
async deleteBadImages(@Req() req: Request) {
const panelFlaskUserId = req.headers['panelFlaskUserId'];
const panelFlaskTypeId = req.headers['panelFlaskTypeId'];
if (
!isAuthenticated(panelFlaskUserId, panelFlaskTypeId) ||
panelFlaskTypeId !== FlaskUserTypesEnum.SUPER_ADMIN ||
panelFlaskUserId !== SUPER_ADMIN_ID
) {
throw new WalletExceptionFilter(403, 'You Are not the Super admin');
}
let ids;
const filePath = path.join(__dirname, 'bad-images-to-remove.txt');
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
// Step 2: Parse the data (assuming it's a newline-separated list)
ids = data.trim().split('\n');
});

const list = [];
for await (const id of ids) {
const need = await this.needService.getNeedByFlaskId(id);
if (need) {
await this.needService.updateNeedMidjourney(need.id, '');
}

const path = `../midjourney-bot/main/need-images/need-${id}`;
if (checkIfFileOrDirectoryExists(path)) {
await rimraf(path);
list.push(path);
} else {
console.log(`Folder does not exist. Skipping...`);
}
}
return list;
}

@Delete(`bad/images/:flaskNeedId`)
@ApiOperation({ description: 'Add need Id to list of delete candidate' })
async deleteSignature(
@Req() req: Request,
@Param('flaskNeedId') flaskNeedId: number,
Expand All @@ -246,23 +289,34 @@ export class MidjourneyController {
) {
throw new WalletExceptionFilter(403, 'You Are not the Super admin');
}
const filePath = 'src/features/midjourney/bad-images-to-remove.json';

const path = `../midjourney-bot/main/need-images/need-${flaskNeedId}`;
if (checkIfFileOrDirectoryExists(path)) {
const result = await rimraf(path);
const need = await this.needService.getNeedByFlaskId(flaskNeedId);
await this.needService.updateNeedMidjourney(need.id, '');
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:', err);
return;
}
try {
// Parse the JSON data
const jsonData = JSON.parse(data);

return {
result,
flaskNeedId,
message: `${flaskNeedId} is deleted`,
};
} else {
return {
flaskNeedId,
message: `Folder does not exist`,
};
}
// Add a new element to the list
jsonData.push(Number(flaskNeedId));

// Convert the updated data back to JSON format
const updatedJsonData = JSON.stringify(jsonData, null, 2);

// Write the updated JSON data back to the file
fs.writeFile(filePath, updatedJsonData, 'utf8', (err) => {
if (err) {
console.error('Error writing file:', err);
} else {
console.log('File updated successfully!');
}
});
} catch (parseError) {
console.error('Error parsing JSON:', parseError);
}
});
}
}
1 change: 1 addition & 0 deletions src/features/midjourney/midjourney.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ export class MidjourneyModule implements NestModule {
consumer
.apply(MidjourneyMiddleware)
.exclude('midjourney/images/:flaskNeedId/:index')
.exclude('midjourney/bad/images/')
.forRoutes(MidjourneyController);
}
}
6 changes: 3 additions & 3 deletions src/features/midjourney/midjourney.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,17 +66,17 @@ export class MidjourneyService {
flaskId: n.id,
needRetailerImg: n.img,
prompt:
'write word "SAY" over an unbearably cute, 3d isometric ' +
'write word "SAY" over a cute, 3d isometric ' +
n.name_translations.en +
',cartoon soft pastel colors illustration, clay render, blender 3d, physically based rendering, soft and light background, pastel background, colorful, toy like proportions --fast',
',cartoon soft pastel colors illustration, clay render, blender 3d, physically based rendering, soft and light background, pastel background, colorful, toy like proportions',
};
list.push(data);
listOfIds.push(n.id);
} else {
console.log(listOfIds);
}
});
config().dataCache.storeMidjourny(list);
config().dataCache.storeMidjourney(list);
if (checkIfFileOrDirectoryExists('../midjourney-bot/midjourney.json')) {
deleteFile('../midjourney-bot/midjourney.json');
}
Expand Down
15 changes: 8 additions & 7 deletions src/features/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class UserController {
private walletService: WalletService,
private ipfsService: IpfsService,
private ngoService: NgoService,
) { }
) {}

@Get(`all`)
@ApiOperation({ description: 'Get all users' })
Expand Down Expand Up @@ -259,7 +259,9 @@ export class UserController {

// to avoid seeing an SW created need by the NGO supervisor in the fourth column / Could not find ypu role / when signing
socialWorkerId =
role === SAYPlatformRoles.NGO_SUPERVISOR ? panelFlaskUserId : socialWorkerId;
role === SAYPlatformRoles.NGO_SUPERVISOR
? panelFlaskUserId
: socialWorkerId;

delivered = await this.needService.getDeliveredNeeds(
{
Expand Down Expand Up @@ -370,10 +372,10 @@ export class UserController {
paidCount === max
? paidCount
: notPaidCount === max
? notPaidCount
: purchasedCount === max
? purchasedCount
: deliveredCount,
? notPaidCount
: purchasedCount === max
? purchasedCount
: deliveredCount,
meta: {
paid: paidCount,
notPaid: notPaidCount,
Expand Down Expand Up @@ -416,5 +418,4 @@ export class UserController {
theUser.contributions.forEach((c) => list.push(c.id));
return await this.userService.deleteOneContributor(theUser.id, list);
}

}
3 changes: 2 additions & 1 deletion src/features/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ export class UserService {
private flaskSocialWorkerRepository: Repository<SocialWorker>,
@InjectRepository(User, 'flaskPostgres')
private flaskUserRepository: Repository<User>,
) { }
) {}


getFlaskSwIds(): Promise<SocialWorker[]> {
return this.flaskSocialWorkerRepository.find({
Expand Down
2 changes: 1 addition & 1 deletion src/utils/dataCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export default class DataCache {
};
};

storeMidjourny = (list: any[]) => {
storeMidjourney = (list: any[]) => {
list.forEach((e) => this.midjourneyList.push(e));
};

Expand Down
3 changes: 1 addition & 2 deletions src/utils/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,6 @@ export function persianDay(value: Date) {
);
}


export function persianMonth(value: Date) {
if (!value) {
return null;
Expand Down Expand Up @@ -923,7 +922,7 @@ export function fetchCampaginCode(
type: CampaignTypeEnum,
) {
const today = new Date();
const englishMonth = today.getMonth();
const englishMonth = today.getMonth(); // If it is January, getMonth() will return 0
const englishYear = today.getFullYear();
return `${type}:${name}-${englishMonth}/${englishYear}`;
}

0 comments on commit 3834329

Please sign in to comment.