def get(reg_id):
        """GET method handler, returns request documents."""
        if not reg_id.isdigit() or not RegDetails.exists(reg_id):
            return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            schema = RegistrationDocumentsSchema()
            documents = RegDocuments.get_by_reg_id(reg_id)
            documents = schema.dump(documents, many=True).data
            '''if doc_id:
                if not doc_id.isdigit():
                    documents = DOC_NOT_FOUND_MSG
                else:
                    documents = list(filter(lambda doc: int(doc['id']) == int(doc_id), documents))
                    documents = documents[0] if documents else DOC_NOT_FOUND_MSG
            '''
            return Response(json.dumps(documents),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        except Exception as e:  # pragma: no cover
            app.logger.exception(e)
            data = {
                "message": [_("Error retrieving results. Please try later.")]
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get("BAD_REQUEST"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        finally:
            db.session.close()
    def post():
        """POST method handler, creates registration documents."""
        reg_id = request.form.to_dict().get('reg_id', None)
        if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id):
            return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        try:
            schema = RegistrationDocumentsSchema()
            time = datetime.now().strftime('%Y%m%d%H%M%S')
            args = request.form.to_dict()
            args = Utilities.update_args_with_file(request.files, args)
            reg_details = RegDetails.get_by_id(reg_id)
            if reg_details:
                args.update({
                    'reg_details_id': reg_details.id,
                    'status': reg_details.status
                })
            else:
                args.update({'reg_details_id': ''})

            validation_errors = schema.validate(args)
            if validation_errors:
                return Response(app.json_encoder.encode(validation_errors),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            tracking_id = reg_details.tracking_id
            created = RegDocuments.bulk_create(request.files, reg_details,
                                               time)
            response = Utilities.store_files(request.files, tracking_id, time)
            if response:
                return Response(json.dumps(response),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            reg_details.update_status('Pending Review')
            message = schema.dump(created, many=True).data
            db.session.commit()
            return Response(json.dumps(message),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            db.session.rollback()
            app.logger.exception(e)

            data = {
                'message':
                _('request document addition failed, check for valid formats.')
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
Esempio n. 3
0
def create_dummy_documents(files, request_type, request, app=None):
    """Helper method to create dummy documents for a request.
    """
    if request_type == 'Registration':
        current_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        for file in files:
            document = Documents.get_document_by_name(file.get('label'), 1)
            reg_doc = RegDocuments(filename='{0}_{1}'.format(current_time, file.get('file_name')))
            reg_doc.reg_details_id = request.id
            reg_doc.document_id = document.id
            reg_doc.save()

            file_path = '{0}/{1}/{2}'.format(app.config['DRS_UPLOADS'], request.tracking_id, file.get('file_name'))
            if not os.path.exists(os.path.dirname(file_path)):
                os.makedirs(os.path.dirname(file_path))
            with open(file_path, 'wb') as f:
                f.seek(1073741824-1)
                f.write(b"\0")
    else:
        current_time = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        for file in files:
            document = Documents.get_document_by_name(file.get('label'), 2)
            dereg_doc = DeRegDocuments(filename='{0}_{1}'.format(current_time, file.get('file_name')))
            dereg_doc.dereg_id = request.id
            dereg_doc.document_id = document.id
            dereg_doc.save()

            file_path = '{0}/{1}/{2}'.format(app.config['DRS_UPLOADS'], request.tracking_id, file.get('file_name'))
            if not os.path.exists(os.path.dirname(file_path)):
                os.makedirs(os.path.dirname(file_path))
            with open(file_path, 'wb') as f:
                f.seek(1073741824-1)
                f.write(b"\0")
    return request
Esempio n. 4
0
    def get(reg_id):
        """GET method handler, return registration sections."""
        if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id):
            return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        try:
            reg_details = RegDetails.get_by_id(reg_id)
            reg_schema = RegistrationDetailsSchema()
            doc_schema = RegistrationDocumentsSchema()
            device_schema = DeviceDetailsSchema()

            reg_device = RegDevice.get_device_by_registration_id(reg_id)
            reg_documents = RegDocuments.get_by_reg_id(reg_id)

            registration_data = reg_schema.dump(reg_details).data
            device_data = device_schema.dump(
                reg_device).data if reg_device else {}
            document_data = doc_schema.dump(reg_documents, many=True).data

            response = {
                'reg_details': registration_data,
                'reg_device': device_data,
                'reg_docs': document_data
            }

            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            app.logger.exception(e)

            data = {
                'message': [
                    _('Registration request failed, check upload path or database connection'
                      )
                ]
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()
    def put():
        """PUT method handler, updates documents."""
        reg_id = request.form.to_dict().get('reg_id', None)
        if not reg_id or not reg_id.isdigit() or not RegDetails.exists(reg_id):
            return Response(app.json_encoder.encode(REG_NOT_FOUND_MSG),
                            status=CODES.get("UNPROCESSABLE_ENTITY"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))

        try:
            schema = RegistrationDocumentsUpdateSchema()
            time = datetime.now().strftime('%Y%m%d%H%M%S')
            args = request.form.to_dict()
            args = Utilities.update_args_with_file(request.files, args)
            reg_details = RegDetails.get_by_id(reg_id)
            if reg_details:
                args.update({
                    'reg_details_id': reg_details.id,
                    'status': reg_details.status
                })
            else:
                args.update({'reg_details_id': ''})
            validation_errors = schema.validate(args)
            if validation_errors:
                return Response(app.json_encoder.encode(validation_errors),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))

            tracking_id = reg_details.tracking_id
            updated = RegDocuments.bulk_update(request.files, reg_details,
                                               time)
            response = Utilities.store_files(request.files, tracking_id, time)
            if response:
                return Response(json.dumps(response),
                                status=CODES.get("UNPROCESSABLE_ENTITY"),
                                mimetype=MIME_TYPES.get("APPLICATION_JSON"))
            if reg_details.status == Status.get_status_id(
                    'Information Requested'):
                reg_details.update_status('In Review')
                message = 'The request {id} has been updated.'.format(
                    id=reg_details.id)
                notification = Notification(reg_details.reviewer_id,
                                            reg_details.id,
                                            'registration_request',
                                            reg_details.status, message)
                notification.add()
            else:
                reg_details.update_status('Pending Review')
            response = schema.dump(updated, many=True).data
            message = schema.dump(updated, many=True).data

            log = EsLog.new_doc_serialize(
                message,
                request_type="Update Registration Documents",
                regdetails=reg_details,
                reg_status="Pending Review",
                method='Put',
                request='Registration')

            db.session.commit()
            EsLog.insert_log(log)

            return Response(json.dumps(response),
                            status=CODES.get("OK"),
                            mimetype=MIME_TYPES.get("APPLICATION_JSON"))
        except Exception as e:  # pragma: no cover
            db.session.rollback()
            app.logger.exception(e)

            data = {
                'message':
                _('request document updation failed, please try again later.')
            }

            return Response(app.json_encoder.encode(data),
                            status=CODES.get('INTERNAL_SERVER_ERROR'),
                            mimetype=MIME_TYPES.get('APPLICATION_JSON'))
        finally:
            db.session.close()