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: export members of organization #730

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
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
100 changes: 50 additions & 50 deletions src/modules/organisations/organisations.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,58 +204,58 @@ export class OrganisationsController {
// async getById(@Param('org_id') org_id: string) {
// return this.organisationsService.getOrganizationDetailsById(org_id);
// }
// @ApiOperation({ summary: 'Export members of an Organisation to a CSV file' })
// @ApiResponse({
// status: 200,
// })
// @ApiResponse({
// status: 200,
// description: 'The CSV file containing organisation members is returned.',
// headers: {
// 'Content-Type': {
// description: 'The content type of the response, which is text/csv.',
// schema: {
// type: 'string',
// example: 'text/csv',
// },
// },
// 'Content-Disposition': {
// description: 'Indicates that the content is an attachment with a filename.',
// schema: {
// type: 'string',
// example: 'attachment; filename="organisation-members-{orgId}.csv"',
// },
// },
// },
// })

// @UseGuards(OwnershipGuard)
// @Get(':org_id/members/export')
// async exportOrganisationMembers(
// @Param('org_id', ParseUUIDPipe) orgId: string,
// @Req() req: Request,
// @Res() res: Response
// ) {
// const userId = req['user'].id;
// const filePath = await this.organisationsService.exportOrganisationMembers(orgId, userId);
@ApiOperation({ summary: 'Export members of an Organisation to a CSV file' })
@ApiResponse({
status: 200,
})
@ApiResponse({
status: 200,
description: 'The CSV file containing organisation members is returned.',
headers: {
'Content-Type': {
description: 'The content type of the response, which is text/csv.',
schema: {
type: 'string',
example: 'text/csv',
},
},
'Content-Disposition': {
description: 'Indicates that the content is an attachment with a filename.',
schema: {
type: 'string',
example: 'attachment; filename="organisation-members-{orgId}.csv"',
},
},
},
})
@UseGuards(OwnershipGuard)
@Get(':org_id/members/export')
async exportOrganisationMembers(
@Param('org_id', ParseUUIDPipe) orgId: string,
@Req() req: Request,
@Res() res: Response
) {
const userId = req['user'].id;
const filePath = await this.organisationsService.exportOrganisationMembers(orgId, userId);

// res.set({
// 'Content-Type': 'text/csv',
// 'Content-Disposition': `attachment; filename="organisation-members-${orgId}.csv"`,
// });
res.set({
'Content-Type': 'text/csv',
'Content-Disposition': `attachment; filename="organisation-members-${orgId}.csv"`,
});

// const fileStream = createReadStream(filePath);
const fileStream = createReadStream(filePath);

// pipeline(fileStream, res)
// .then(() => unlink(filePath))
// .catch(error => {
// this.logger.error('Pipeline failed:', error.stack);
// if (!res.headersSent) {
// res.status(500).send('Internal Server Error');
// }
// return unlink(filePath).catch(unlinkError => {
// this.logger.error(`Failed to delete file: ${unlinkError.message}`, unlinkError.stack);
// });
// });
// }
pipeline(fileStream, res)
.then(() => unlink(filePath))
.catch(error => {
this.logger.error('Pipeline failed:', error.stack);
if (!res.headersSent) {
res.status(500).send('Internal Server Error');
}
return unlink(filePath).catch(unlinkError => {
this.logger.error(`Failed to delete file: ${unlinkError.message}`, unlinkError.stack);
});
});
}
}
34 changes: 18 additions & 16 deletions src/modules/organisations/organisations.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ import CreateOrganisationType from './dto/create-organisation-options';
import { CustomHttpException } from '../../helpers/custom-http-filter';
import { ORG_NOT_FOUND, ORG_UPDATE } from '../../helpers/SystemMessages';
import { OrganisationMemberMapper } from './mapper/org-members.mapper';
import { createObjectCsvStringifier } from 'csv-writer';
import { join } from 'path';
import * as fs from 'fs';

@Injectable()
export class OrganisationsService {
Expand Down Expand Up @@ -53,7 +56,7 @@ export class OrganisationsService {
if (!members.length) {
return { status_code: HttpStatus.OK, message: 'members retrieved successfully', data: [] };
}
let organisationMembers = members.map(instance => instance.user);
const organisationMembers = members.map(instance => instance.user);

const isMember = organisationMembers.find(member => member.id === sub);
if (!isMember) throw new ForbiddenException('User does not have access to the organisation');
Expand Down Expand Up @@ -293,23 +296,22 @@ export class OrganisationsService {
// return { message: 'Fetched Organization Details Successfully', data: orgDetails };
// }

// async exportOrganisationMembers(orgId: string, userId: string): Promise<string> {
// const membersResponse = await this.getOrganisationMembers(orgId, 1, Number.MAX_SAFE_INTEGER, userId);
async exportOrganisationMembers(orgId: string, userId: string): Promise<string> {
const membersResponse = await this.getOrganisationMembers(orgId, 1, Number.MAX_SAFE_INTEGER, userId);

// const csvStringifier = createObjectCsvStringifier({
// header: [
// { id: 'id', title: 'ID' },
// { id: 'name', title: 'Name' },
// { id: 'email', title: 'Email' },
// { id: 'role', title: 'Role' },
// ],
// });
const csvStringifier = createObjectCsvStringifier({
header: [
{ id: 'id', title: 'ID' },
{ id: 'name', title: 'Name' },
{ id: 'email', title: 'Email' },
],
});

// const csvData = csvStringifier.getHeaderString() + csvStringifier.stringifyRecords(membersResponse.data);
const csvData = csvStringifier.getHeaderString() + csvStringifier.stringifyRecords(membersResponse.data);

// const filePath = join(__dirname, `organisation-members-${orgId}.csv`);
// fs.writeFileSync(filePath, csvData);
const filePath = join(__dirname, `organisation-members-${orgId}.csv`);
fs.writeFileSync(filePath, csvData);

// return filePath;
// }
return filePath;
}
}
Loading