diff --git a/src/routes/files.ts b/src/routes/files.ts index c3bcb846..832ed473 100644 --- a/src/routes/files.ts +++ b/src/routes/files.ts @@ -1,7 +1,7 @@ import _ from 'lodash'; import { FastifyInstance } from 'fastify'; import { stringify } from 'csv/sync'; -import { Config, ContactType } from '../config'; +import { Config } from '../config'; import SessionCache from '../services/session-cache'; import JSZip from 'jszip'; @@ -22,41 +22,38 @@ export default async function files(fastify: FastifyInstance) { fastify.get('/files/credentials', async (req, reply) => { const sessionCache: SessionCache = req.sessionCache; - const results = new Map(); - const places = sessionCache.getPlaces(); - places.forEach(place => { - const parent = Config.getParentProperty(place.type); - const record = [ - place.hierarchyProperties[parent.property_name], + const zip = new JSZip(); + for (const contactType of Config.contactTypes()) { + const places = sessionCache.getPlaces({ type: contactType.name }); + if (!places.length) { + continue; + } + const rows = places.map((place) => [ + ...Object.values(place.hierarchyProperties), place.name, place.contact.properties.name, place.contact.properties.phone, place.creationDetails.username, place.creationDetails.password, - ]; - const result = results.get(place.type) || []; - result.push(record); - results.set(place.type, result); - }); - const zip = new JSZip(); - results.forEach((places, contactType) => { - const parent = Config.getParentProperty(contactType); + ]); + const constraints = Config.getHierarchyWithReplacement(contactType); + const props = Object.keys(places[0].hierarchyProperties).map(prop => constraints.find(c => c.property_name === prop)!.friendly_name); const columns = [ - parent.friendly_name, + ...props, contactType.friendly, 'name', 'phone', 'username', - 'password' + 'password', ]; zip.file( `${contactType.name}.csv`, - stringify(places, { - columns: columns, + stringify(rows, { + columns, header: true, }) ); - }); + } reply.header('Content-Disposition', `attachment; filename="${Date.now()}_${req.chtSession.authInfo.friendly}_users.zip"`); return zip.generateNodeStream(); }); diff --git a/src/services/place.ts b/src/services/place.ts index 2adbb4fb..a65ec255 100644 --- a/src/services/place.ts +++ b/src/services/place.ts @@ -85,10 +85,7 @@ export default class Place { for (const hierarchyLevel of Config.getHierarchyWithReplacement(this.type)) { const propertyName = hierarchyLevel.property_name; - delete this.hierarchyProperties[propertyName]; - if (formData[`${hierarchyPrefix}${propertyName}`]) { - this.hierarchyProperties[propertyName] = formData[`${hierarchyPrefix}${propertyName}`]; - } + this.hierarchyProperties[propertyName] = formData[`${hierarchyPrefix}${propertyName}`] ?? ''; } }