|
1 | 1 | import csv |
2 | 2 | import os |
3 | 3 | import tempfile |
| 4 | +from datetime import datetime |
4 | 5 | from http import HTTPStatus |
5 | 6 | from typing import List, Union |
6 | 7 |
|
|
13 | 14 | from model.konfhub.konfhub import KonfHubCaptureRegistrationIn, RegistrationDetail |
14 | 15 | from model.registrations.registration import ( |
15 | 16 | PreRegistrationToRegistrationIn, |
| 17 | + Registration, |
16 | 18 | RegistrationIn, |
17 | 19 | RegistrationOut, |
18 | 20 | ) |
@@ -387,24 +389,37 @@ def get_registration_csv(self, event_id: str) -> FileDownloadOut: |
387 | 389 | if status != HTTPStatus.OK: |
388 | 390 | return JSONResponse(status_code=status, content={'message': message}) |
389 | 391 |
|
| 392 | + if not registrations: |
| 393 | + return JSONResponse( |
| 394 | + status_code=HTTPStatus.NOT_FOUND, content={'message': 'No registrations found for this event'} |
| 395 | + ) |
| 396 | + |
390 | 397 | try: |
391 | 398 | with tempfile.TemporaryDirectory() as tmpdir: |
392 | 399 | csv_path = os.path.join(tmpdir, 'registrations.csv') |
393 | 400 |
|
394 | 401 | with open(csv_path, 'w') as temp: |
395 | 402 | writer = csv.writer(temp) |
396 | 403 |
|
397 | | - # make the first row csv for the keys using the dict keys of the first entry |
398 | | - first_entry = self.__convert_data_entry_to_dict(registrations[0]) |
399 | | - writer.writerow(first_entry.keys()) |
| 404 | + # Get headers from Registration DynamoDB model attributes |
| 405 | + headers = [ |
| 406 | + attr_name |
| 407 | + for attr_name in dir(Registration) |
| 408 | + if not attr_name.startswith('_') |
| 409 | + and not callable(getattr(Registration, attr_name)) |
| 410 | + and attr_name not in ['Meta', 'DoesNotExist', 'registrationIdGSI', 'emailLSI'] |
| 411 | + ] |
| 412 | + headers.sort() |
| 413 | + logger.info(f'Headers for CSV export: {headers}') |
| 414 | + writer.writerow(headers) |
400 | 415 |
|
401 | | - # the remaining rows consist of the values of the attributes |
402 | 416 | for entry in registrations: |
403 | 417 | entry_dict = self.__convert_data_entry_to_dict(entry) |
404 | | - writer.writerow(entry_dict.values()) |
| 418 | + row_values = [entry_dict.get(header, '') for header in headers] |
| 419 | + writer.writerow(row_values) |
405 | 420 |
|
406 | 421 | # upload the file to s3 |
407 | | - csv_object_key = f'csv/registrations/{event_id}.csv' |
| 422 | + csv_object_key = f'csv/registrations/{event_id}-{datetime.now().strftime("%Y%m%d%H%M%S")}.csv' |
408 | 423 | self.__file_s3_usecase.upload_file(file_name=csv_path, object_name=csv_object_key) |
409 | 424 |
|
410 | 425 | return self.__file_s3_usecase.create_download_url(csv_object_key) |
|
0 commit comments