Skip to content

Commit

Permalink
Merge pull request #1805 from openoereb/fix_pdf_archive_timestamp
Browse files Browse the repository at this point in the history
Fix pdf archive timestamp
  • Loading branch information
marionb authored Sep 6, 2023
2 parents ecb0905 + 2cd43e8 commit e8d0880
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 12 deletions.
1 change: 1 addition & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ services:
- oereb-db
user: "${LOCAL_UID}:${LOCAL_GID}"
environment:
TZ: Europe/Zurich
PGHOST: ${PGHOST:-oereb-db}
PGPORT: ${PGPORT:-5432}
PGUSER: ${PGUSER:-postgres}
Expand Down
40 changes: 30 additions & 10 deletions pyramid_oereb/contrib/print_proxy/mapfish_print/mapfish_print.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from datetime import datetime
import io
import json
import logging
Expand Down Expand Up @@ -28,6 +28,11 @@

class Renderer(JsonRenderer):

def __init__(self, info):
super(Renderer, self).__init__(info)
self.global_datetime = None
self.global_datetime_format = '%Y-%m-%dT%H:%M:%S'

def __call__(self, value, system):
"""
Implements a subclass of pyramid_oereb.core.renderer.extract.json_.Renderer to create a print result
Expand Down Expand Up @@ -73,6 +78,8 @@ def __call__(self, value, system):
else:
extract_as_dict['nbTocPages'] = 1

# set the global_datetime variable so that it can be used later for the archive
self.set_global_datetime(extract_as_dict['CreationDate'])
self.convert_to_printable_extract(extract_as_dict, feature_geometry)

print_config = Config.get('print', {})
Expand Down Expand Up @@ -154,8 +161,7 @@ def __call__(self, value, system):
del response.headers['Connection']
return content

@staticmethod
def archive_pdf_file(pdf_archive_path, binary_content, extract_as_dict):
def archive_pdf_file(self, pdf_archive_path, binary_content, extract_as_dict):
"""
Writes the static extract (pdf) into a dedicated file; this functionality can thus be used
for archiving.
Expand All @@ -171,8 +177,7 @@ def archive_pdf_file(pdf_archive_path, binary_content, extract_as_dict):
"""
pdf_archive_path = pdf_archive_path if pdf_archive_path[-1:] == '/' else pdf_archive_path + '/'
log.debug('Start to archive pdf file at path: ' + pdf_archive_path)

time_info = (datetime.utcnow() + timedelta(hours=2)).strftime('%Y%m%d%H%M%S') # UTC+2
time_info = self.global_datetime.strftime('%Y%m%d%H%M%S')
egrid = extract_as_dict.get('RealEstate_EGRID', 'no_egrid')

if egrid == 'no_egrid' or egrid is None:
Expand Down Expand Up @@ -239,14 +244,15 @@ def convert_to_printable_extract(self, extract_dict, feature_geometry):
"""
log.debug("Starting transformation, extract_dict is {}".format(extract_dict))
log.debug("Parameter feature_geometry is {}".format(feature_geometry))

creation_date = datetime.strptime(extract_dict['CreationDate'], '%Y-%m-%dT%H:%M:%S')
if self.global_datetime is None:
# make sure this is set i.e when running tests
self.set_global_datetime(extract_dict['CreationDate'])
extract_dict['Footer'] = ' '.join([
creation_date.strftime('%d.%m.%Y'),
creation_date.strftime('%H:%M:%S'),
self.global_datetime.strftime('%d.%m.%Y'),
self.global_datetime.strftime('%H:%M:%S'),
extract_dict['ExtractIdentifier']
])
extract_dict['CreationDate'] = creation_date.strftime('%d.%m.%Y')
extract_dict['CreationDate'] = self.global_datetime.strftime('%d.%m.%Y')

for attr_name in ['ConcernedTheme', 'NotConcernedTheme', 'ThemeWithoutData']:
for theme in extract_dict[attr_name]:
Expand Down Expand Up @@ -857,3 +863,17 @@ def string_check(value):
(str): converted value
"""
return value if isinstance(value, str) else ','.join(value)

def set_global_datetime(self, date_time):
"""
Set/initialize the class variable global_datetime with a given date-time
Args:
value (str): date value of the format Y-m-dTH:M:S'
"""
try:
self.global_datetime = datetime.strptime(date_time, self.global_datetime_format)
except PdfReadError as e:
err_msg = f'Not able to set the datetime. Expected date-time format is: \
{self.global_datetime_format}. Given date-time value is: {date_time}'
log.error(err_msg + ': ' + str(e))
raise HTTPInternalServerError(self._static_error_message)
20 changes: 18 additions & 2 deletions tests/contrib.print_proxy.mapfish_print/test_mapfish_print.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
from datetime import datetime
import os
import io
import re
Expand Down Expand Up @@ -722,9 +723,21 @@ def test_group_legal_provisions(DummyRenderInfo):
assert expected_results == renderer.group_legal_provisions(test_legal_provisions)


def test_set_global_datetime(DummyRenderInfo):
renderer = Renderer(DummyRenderInfo())
date_time = '2023-08-21T13:48:07'
renderer.set_global_datetime(date_time)
assert renderer.global_datetime is not None
assert renderer.global_datetime == datetime.strptime(date_time, renderer.global_datetime_format)


def test_archive_pdf(DummyRenderInfo):
renderer = Renderer(DummyRenderInfo())
extract = {'RealEstate_EGRID': 'CH113928077734'}
extract = {
'RealEstate_EGRID': 'CH113928077734',
'CreationDate': '2023-08-21T13:48:07'
}
renderer.set_global_datetime(extract['CreationDate'])
path_and_filename = renderer.archive_pdf_file('/tmp', bytes(), extract)
partial_filename = str('_') + extract['RealEstate_EGRID'] + '.pdf'
assert partial_filename in path_and_filename
Expand All @@ -735,7 +748,10 @@ def test_archive_pdf_identdn(DummyRenderInfo):
renderer = Renderer(DummyRenderInfo())
extract = {
'RealEstate_IdentDN': 'BL0200002771',
'RealEstate_Number': '70'}
'RealEstate_Number': '70',
'CreationDate': '2023-08-21T13:48:07'
}
renderer.set_global_datetime(extract['CreationDate'])
path_and_filename = renderer.archive_pdf_file('/tmp', bytes(), extract)
partial_filename = extract['RealEstate_IdentDN'] + str('_') + extract['RealEstate_Number'] + '.pdf'
assert partial_filename in path_and_filename
Expand Down

0 comments on commit e8d0880

Please sign in to comment.