Example #1
0
 def checkIsActivityValidForStatus(self) -> bool:
     """
     Define, whether this activity is valid for the current status of the current instance. Each instance must
     implement this method
     :return: True if valid/active, False if not valid/activ
     """
     logger.exception(
         f"Activity not properly implemented! Doesn't know if it's valid for status or not! "
         f"{self.__class__}")
     raise NotImplementedError((
         f"Activity not properly implemented! Doesn't know if it's valid for status or not! "
         f"{self.__class__}"))
Example #2
0
    def _updateFieldValue(self, name, value, optional=None):
        """

        :param name: fieldname of the activtiy
        :param value: current field value
        :param optional: True if the field might not exist (and not log message is requested in case it can't be found)
        :return:
        """

        # set parent flag
        if hasattr(self, 'polizze'):
            parent_flag = self.PARENT_POLICY
        elif hasattr(self, 'antrag'):
            parent_flag = self.PARENT_ANTRAG
        else:
            logger.debug(
                f"Activity {self.name} is not assigned to any policy or antrag instance"
            )
            return

        lUpdatedField = self.activityFields.getField(name=name)
        if not lUpdatedField:
            # policy cse
            if parent_flag == self.PARENT_POLICY:
                logger.debug(
                    f"Field provided {name} with value {value}. But not in policy activity"
                )

            # antrag case
            # Maybe field from Antrag, not from activity:
            lUpdatedField = self.antrag.Fields.getField(name=name)
            if not lUpdatedField:
                if not optional:
                    logger.error(
                        f"Field provided {name} with value {value}. But not in activity nor in Antrag"
                    )
                else:
                    logger.debug(
                        f"Field provided {name} with value {value}. But not in activity nor in Antrag. "
                        f"'Optional' is set, so no problem.")
                return

        lUpdatedField.value = value
        try:
            if parent_flag == self.PARENT_ANTRAG:
                self.antrag._updateTechnicalFieldValuesAfterChange(
                    lUpdatedField)
        except Exception as e:
            logger.exception(
                f"Error in _updateTechnicalFieldValuesAfterChange (or Methode doesn't exist). "
                f"Class was {self.__class__.__name__}. Error: {e}. Field: {name}, "
                f"Value: {value}")
Example #3
0
    def setFieldVisible(self, fieldName):
        """

        :param fieldName:
        :return:
        """
        try:
            lField = self.Fields.getField(name=fieldName)
            lField.fieldVisibilityType = FieldVisibilityTypes.visible
        except AttributeError:
            logger.exception(
                f"Field {fieldName} should be set visible. Doesn't exist. Most probaly a typo!"
            )
Example #4
0
    def addFields(self):
        if not hasattr(ManageFieldCatalog, self.__class__.__name__):
            logger.debug(f"There is no field list for {self.__class__.__name__}. Most probably OK")
            return

        ManageFieldCatalog.determineLanguage(self)  # set Translator to proper Language

        # Execute filling the field catalog for either the antrag, Policy or Activity.
        try:
            getattr(ManageFieldCatalog, self.__class__.__name__)(self)
            logger.debug(f"FielCatalog created for {self.__class__.__name__}")
        except AttributeError as e:
            logger.exception(f"Building field catalog for {self.__class__.__name__} failed. Error was: {e}")

        # Now, that the field-catalog is built, check if we have default values from
        self.deriveDefaultsFromUserOrCompany()
Example #5
0
 def getFieldValue(self, fieldName, optional=False):
     """
     Retrieve the field.value from fieldName
     :param fieldName:
     :param optional: Don't write log entry, if the field does not exist
     :return:
     """
     try:
         return self.Fields.getField(name=fieldName).value
     except AttributeError:
         if not optional:
             lFields = ", ".join(
                 sorted([x.name for x in self.Fields.getAllInputFields()]))
             logger.exception(
                 f"Called for fieldname = {fieldName}. Doesn't exist! Existing Field names: {lFields}",
                 stack_info=True)
Example #6
0
    def findActivity(self, activity_name):
        try:
            target_activity = AntragActivity
            lActivity = next(
                filter(lambda x: isinstance(x, target_activity),
                       self.instance.Activities), None)
        except TypeError:
            logger.exception(
                f"Didn't find anything useful for activity {activity_name}. If it's a new activity, then"
                f" make sure you imported it in antrag.py and added it to activity_classes on the top. "
            )
            return None

        logger.debug(
            f"Found existing activity inside Antrag: {lActivity.__class__.__name__}"
        )
        return lActivity
Example #7
0
    def setFieldInvisible(self, fieldName, optional=False):
        """

        :param fieldName:
        :param optional: Don't write log, if field doesn't exist in the field catalog
        :return:
        """
        try:
            lField = self.Fields.getField(name=fieldName)
            lField.fieldVisibilityType = FieldVisibilityTypes.hidden
            if lField.value and lField.fieldDataType == FieldDataType(
                    InputFieldTypes.TYPEBOOLEAN):
                lField.value = False
        except Exception:
            if optional:
                logger.debug(
                    f"Field {fieldName} should be set invisible. Doesn't exist. "
                    f"'Optional' is set, so most likely Ok")
            else:
                logger.exception(
                    f"Field {fieldName} should be set invisible. Doesn't exist. Most probaly typo!"
                )
Example #8
0
def run_loop(db, models, seconds=0):
    exceptions = 0
    excpetion_threshold = 100
    while True:
        try:
            update_statistics(db, models)
            exceptions = 0
        except Exception as ex:
            exceptions += 1
            print(f"Exception {str(exceptions)}: {str(ex)}")
            logger.exception(f"Exception {str(exceptions)}: {str(ex)}")
            if exceptions >= excpetion_threshold:
                print(
                    f'Exiting loop as total continuous exceptions has reached threshold {str(excpetion_threshold)}'
                )
                sys.exit()
        if not seconds:  # if seconds is 0 then we not need to run this program in loop
            break
        else:
            print(
                f"Sleeping for {str(seconds)} seconds. Statistics database updated at",
                datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
            sleep(seconds)
Example #9
0
    def executeActivity(self, data):
        #
        # executes antrag activity defined in data
        #
        # update values of Antragsinstance for Frontend display after the activity was executed.
        #
        # We have a long list of IF-conditions because many activities have different return parameters.

        current_activity = self.findActivity(data['activity'])
        if not current_activity:
            print(
                f"Activity couldn't be found. Something weird going on. data from Frontend: {data}"
            )
            current_app.logger.critical(
                f"Activity couldn't be found. Something weird going on. data from Frontend: {data}"
            )

        if data['activity'] == 'Berechnen':  # calculate
            # In Berechnen we get the data for the antrag, so we must provide it to Antags-Instance
            self.instance.updateFieldValues(data.get('values'))
            current_activity.executeActivity()
            self.instance.fillCurrentlyPossibleActivities()
            return self.get()

        current_activity.updateFieldValues(data.get('values'))
        lResult = current_activity.executeActivity()

        if data["activity"] in [
                "Eurotax Vollsuche", "Empfehlung!", "Dokumente",
                'Antrag erzeugen PM+'
        ]:
            self.instance.fillCurrentlyPossibleActivities()
            return self.get()

        if data['activity'] == 'Drucken':  # print
            if not lResult:
                raise ValueError('Unable to create PDF')
            return {
                "link":
                url_for(
                    'support.downloads',
                    filename=current_activity.getFolderAndPath(),
                    _external=True,
                ),
            }
        elif data['activity'] == 'Antrag erzeugen':  # save to VNG
            return {"link": current_activity.getLinkOfRealApplication()}

        elif data['activity'] == "Deckungsuebersicht":
            return {
                "link":
                url_for(
                    'support.downloads',
                    filename=current_activity.getFolderAndPath(),
                    _external=True,
                ),
            }

        elif data['activity'] == "VN festlegen":
            # Update VN-Fields inside the antrags instance with the latest values.
            self.instance.updateFieldValues(data.get('values'))
            current_activity.setStatusOfAntragAfterPartnerAssignment()

            self.instance.fillCurrentlyPossibleActivities()
            return self.get()

        elif data["activity"] in ["Partner festlegen", "Antragsfragen BUFT"]:
            if lResult:
                self.instance.fillCurrentlyPossibleActivities()
            else:
                # Execution of activity was not successful, activity should stay open
                current_activity.postExecuteBehavior = Activity.POSTEXECUTION_ACTIVE
            return self.get()

        else:
            logger.exception(
                f'Activity was {data.get("activity")}. No logic implemented for that'
            )
            raise ValueError(f'Antrag activiy {data.get("activity")} failed')