11import { Argument , Command } from 'commander' ;
2+ import { generate as generatePassword } from 'generate-password' ;
23
34import { getCsvContent } from '../shared/csv' ;
4- import { insertUsers , register } from '../shared/db' ;
5+ import { getUsersByRole , insertUsers , register } from '../shared/db' ;
56import { validateEnv } from '../shared/env' ;
7+ import { createPasswordsList } from '../shared/files' ;
68import { createLogger } from '../shared/logger' ;
79import { ParticipantCsvRow , RegisterDTO , User , userRoles } from '../shared/models' ;
810import { transformToMatchClass } from '../shared/object' ;
@@ -15,34 +17,47 @@ export const registerParticipants = (program: Command) => {
1517 . description ( 'Creates accounts for CodersCamp participants listed in the CSV file' )
1618 . addArgument ( new Argument ( '<csv-path>' , 'Path to the CSV file' ) )
1719 . action ( async ( csvPath : string ) => {
20+ const participants : User [ ] = [ ] ;
21+ const passwords = createPasswordsList ( ) ;
22+
1823 try {
1924 await validateEnv ( ) ;
2025
2126 const rows = await getCsvContent ( csvPath ) ;
2227 const participantsRows = await Promise . all ( rows . map ( transformToMatchClass ( ParticipantCsvRow ) ) ) ;
23-
24- const participants : User [ ] = [ ] ;
28+ const currentParticipants = await getUsersByRole ( userRoles . participant ) ;
29+ const currentParticipantsEmails = currentParticipants . map ( ( { email } ) => email ) ;
2530
2631 logger . debug ( 'Iterating through parsed rows' ) ;
2732
2833 for ( const { email, firstName, lastName } of participantsRows ) {
29- const registerDto = await transformToMatchClass ( RegisterDTO ) ( { email } ) ;
30- const userId = await register ( registerDto ) ;
31- const participant = await transformToMatchClass ( User ) ( {
32- ...registerDto ,
33- id : userId ,
34- name : `${ firstName } ${ lastName } ` ,
35- role : userRoles . participant ,
36- } ) ;
37-
38- participants . push ( participant ) ;
34+ if ( ! currentParticipantsEmails . includes ( email ) ) {
35+ const password = generatePassword ( { length : 16 , numbers : true , symbols : true } ) ;
36+ const registerDto = await transformToMatchClass ( RegisterDTO ) ( { email, password } ) ;
37+ const userId = await register ( registerDto ) ;
38+ const participant = await transformToMatchClass ( User ) ( {
39+ ...registerDto ,
40+ id : userId ,
41+ firstName,
42+ lastName,
43+ role : userRoles . participant ,
44+ } ) ;
45+
46+ participants . push ( participant ) ;
47+ passwords . add ( { email, password } ) ;
48+ } else {
49+ logger . debug ( `Participant with email ${ email } already exists in the database` ) ;
50+ }
3951 }
4052
4153 logger . debug ( 'Iteration through parsed rows finished' ) ;
4254
4355 await insertUsers ( participants ) ;
4456 } catch ( ex ) {
4557 logger . error ( ex ) ;
58+ logger . info ( 'Already registered participants' , participants ) ;
59+ } finally {
60+ await passwords . save ( ) ;
4661 }
4762 } ) ;
4863} ;
0 commit comments