@@ -154,35 +154,52 @@ router.post('/send', async (req, res) => {
154154 try {
155155 /** @todo allow for passing entity and contact arrays */
156156 const emails = [ ]
157- const { entityIds, contactIds, relationshipTitle} = req . body
157+ const { entityIds, contactIds, relationshipTitle, entityType } = req . body
158158
159159 if ( entityIds === undefined && contactIds === undefined ) {
160- const whereClause = ( relationshipTitle !== undefined ) ? { where : { relationshipTitle} } : { }
161- const associations = await models . EntityContact . findAll ( whereClause )
160+ const whereClause = {
161+ include : [ {
162+ model : models . Entity ,
163+ as : 'entities' ,
164+ required : true ,
165+ through : {
166+ model : models . EntityContact ,
167+ as : 'entityContacts' ,
168+ }
169+ } ]
170+ }
171+
172+ if ( relationshipTitle ) {
173+ whereClause . include [ 0 ] . through . where = { relationshipTitle : relationshipTitle }
174+ }
175+
176+ if ( entityType ) {
177+ whereClause . include [ 0 ] . where = { type : entityType }
178+ }
179+
180+ const contacts = await models . Contact . findAll ( whereClause )
162181
163- if ( associations . length < 1 ) {
182+ if ( contacts . length < 1 ) {
164183 response . setCode ( 400 )
165184 response . setMessage ( 'No contacts to email' )
166185 return res . status ( response . getCode ( ) ) . send ( response . getMessage ( ) )
167186 }
168187
169- for ( const association of associations ) {
170- const contact = await models . Contact . findById ( association . contactId )
171-
172- if ( contact . email !== null ) {
173- const entity = await models . Entity . findById ( association . entityId )
174- // short-lived temporary token that only lasts one hour
175- const temporaryToken = await utils . getToken ( contact . id , contact . email [ 0 ] . address , 'contact' )
176-
177- emails . push ( {
178- email : contact . email [ 0 ] . address ,
179- name : contact . name ,
180- entityName : entity . name ,
181- entityId : association . entityId ,
182- entityType : entity . type ,
183- relationshipTitle : association . relationshipTitle ,
184- token : temporaryToken
185- } )
188+ for ( const contact of contacts ) {
189+ for ( const entity of contact . entities ) {
190+ if ( contact . email !== null ) {
191+ // short-lived temporary token that only lasts one hour
192+ const temporaryToken = await utils . getToken ( contact . id , contact . email [ 0 ] . address , 'contact' )
193+ emails . push ( {
194+ email : contact . email [ 0 ] . address ,
195+ name : contact . name ,
196+ entityName : entity . name ,
197+ entityId : entity . id ,
198+ entityType : entity . type ,
199+ relationshipTitle : entity . entityContacts . dataValues . relationshipTitle ,
200+ token : temporaryToken
201+ } )
202+ }
186203 }
187204 }
188205 }
0 commit comments