Example #1
0
 def form_valid(self, form):
     barrido_client = CoreBarridoClient()
     application = form.base_fields["application"].initial
     response = barrido_client.create_buckets_strategy(
         application, form.cleaned_data.get("description"))
     barrido_client.import_buckets_strategy(response.json().get("id"),
                                            form.cleaned_data.get("file"))
     return super().form_valid(form)
Example #2
0
 def form_valid(self, form):
     barrido_client = CoreBarridoClient()
     response = barrido_client.import_buckets_strategy(
         self.kwargs.get("buckets_strategy_id"),
         form.cleaned_data.get("file"))
     if response.status_code == 202:
         messages.add_message(self.request, messages.SUCCESS,
                              "Archivo importado.")
     else:
         messages.add_message(self.request, messages.ERROR,
                              "No fue posible importar el archivo")
     return super().form_valid(form)
Example #3
0
 def get_redirect_url(self, *args, **kwargs):
     barrido_client = CoreBarridoClient()
     response = barrido_client.delete_buckets_strategy(
         kwargs.get("buckets_strategy_id"))
     if response.status_code == 200:
         messages.add_message(self.request, messages.SUCCESS,
                              "Estrategia eliminada.")
     else:
         messages.add_message(self.request, messages.ERROR,
                              "La estrategia no pudo ser eliminada")
     return reverse_lazy("buckets_strategy",
                         kwargs={"application": "debito_directo"})
Example #4
0
def download_snapshot_task(snapshot_id):
    logger.info("starting download_snapshot_task id={}, waiting...".format(
        snapshot_id))
    time.sleep(5)
    logger.info(
        "now yes, starting download_snapshot_task id={}".format(snapshot_id))

    snapshot = Snapshot.objects.get(id=snapshot_id)
    snapshot.status = "downloading"
    snapshot.save()

    barrido_client = CoreBarridoClient()
    status = barrido_client.get_system_status_report()
    if status.status_code == 200:
        blocked_date = status.json(object_hook=datetime_parser)
        diff = datetime.datetime.now(
        ) - blocked_date['last_blocked_accounts_database_datetime']
        days, seconds = diff.days, diff.seconds
        hours = days * 24 + seconds // 3600
        if hours > 24:
            NotificationClient().send_generic(
                "AVISO: Se esta generando una Cartera Activa con las bajas de servicio desactualizadas (mas de 24hs). (Snapshot: {})"
                .format(snapshot_id))
    else:
        NotificationClient().send_generic(
            "AVISO: El proceso de Cartera Activa no pudo verificar la antigüedad de los datos de bajas de servicios (Snapshot: {}). Continuando proceso."
            .format(snapshot_id))

    headers = {
        "Authorization":
        "Basic {}".format(getattr(settings, "MAMBU_API_AUTHORIZATION")),
        "Content-Type":
        "application/json"
    }
    url = getattr(settings, "MAMBU_API_ENDPOINT_BACKUP")
    logger.info("downloading mambu backup:")
    logger.info("headers: {}".format(headers))
    logger.info("url: {}".format(url))
    response = requests.get(url, headers=headers, stream=True)
    logger.info("status code: {}".format(response.status_code))
    logger.info("response headers: {}".format(response.headers))
    local_filename = "dump-{}.zip".format(
        datetime.datetime.now().strftime("%m-%d-%y-%H%M%S"))
    os.makedirs(getattr(settings, "MEDIA_ROOT"), exist_ok=True)
    with open(os.path.join(getattr(settings, "MEDIA_ROOT"), local_filename),
              'wb') as f:
        for chunk in response.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
        snapshot.dump.name = local_filename
        snapshot.status = "finished"
        snapshot.save()
    logger.info("download complete!")
Example #5
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     barrido_client = CoreBarridoClient()
     buckets_strategy = barrido_client.get_buckets_strategy(
         self.kwargs.get("buckets_strategy_id")).json()
     application = buckets_strategy["application"]
     context["buckets_strategy"] = buckets_strategy
     context["application"] = application
     context["application_description"] = get_application_description(
         self.request, application)
     self.form_class.base_fields["application"].initial = application
     return context
Example #6
0
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     barrido_client = CoreBarridoClient()
     agents_data = barrido_client.agents_data()
     if agents_data:
         context["agents_data"] = agents_data.json()
     else:
         messages.add_message(
             self.request, messages.ERROR,
             "Error al leer tabla: [{}] {}".format(agents_data.status_code,
                                                   agents_data.reason))
     return context
Example #7
0
 def get(self, request, buckets_strategy_id, **kwargs):
     barrido_client = CoreBarridoClient()
     response = barrido_client.export_buckets_strategy(buckets_strategy_id)
     if response.status_code == 200:
         file = io.BytesIO(base64.b64decode(response.content))
         http_response = HttpResponse(
             file, content_type='application/octet-stream')
         http_response['Content-Disposition'] = 'filename={}-{}.xls'.format(
             buckets_strategy_id,
             datetime.datetime.now().strftime("%m-%d-%y-%H%M%S"))
         return http_response
     messages.add_message(self.request, messages.ERROR,
                          "No se ha podido exportar la estrategia")
     return HttpResponseRedirect(
         reverse_lazy("buckets_strategy",
                      kwargs={"application": "debito_directo"}))
 def get_context_data(self, **kwargs):
     context = super(OutputsStratergiesDetailView,
                     self).get_context_data(**kwargs)
     barrido_client = CoreBarridoClient()
     outputs_strategy = barrido_client.get_paying_agents_strategies(
         self.kwargs.get("outputs_strategy_id"))
     self.permission_required.append(
         f"core.outputs_strategy_access_{self.kwargs.get('application')}")
     if outputs_strategy:
         context["outputs_strategy"] = outputs_strategy.json()
     else:
         messages.add_message(
             self.request, messages.ERROR,
             "Error al leer tabla: [{}] {}".format(
                 outputs_strategy.status_code, outputs_strategy.reason))
     return context
Example #9
0
def get_applications(request, force_reload):
    if 'applications' in request.session and not force_reload:
        application_list = request.session["applications"]
    else:
        barrido_client = CoreBarridoClient()
        applications = barrido_client.get_applications()
        if applications.status_code == 200:
            application_list = applications.json()
        else:
            messages.add_message(request, messages.ERROR,
                                 f"Error de conexión: [{applications.status_code}]"
                                 f"{applications.text} "
                                 f"{applications.reason}")
            application_list = []
        request.session["applications"] = application_list
    return application_list
Example #10
0
 def get(self, request, strategy_exec_id, **kwargs):
     barrido_client = CoreBarridoClient()
     response = barrido_client.export_strategy_executions(strategy_exec_id)
     if response.status_code == 200:
         file = io.BytesIO(base64.b64decode(response.content))
         http_response = HttpResponse(
             file, content_type='application/octet-stream')
         http_response['Content-Disposition'] = 'filename={}-{}.zip'.format(
             request.GET.get("description", "data"),
             datetime.datetime.now().strftime("%m-%d-%y-%H%M%S"))
         return http_response
     msg = get_response_message(response)
     messages.add_message(self.request, messages.ERROR,
                          "No se ha podido exportar la ejecucion: " + msg)
     return HttpResponseRedirect(
         reverse_lazy("strategy_exec_detail",
                      kwargs={"strategy_exec_id": strategy_exec_id}))
 def get_context_data(self, **kwargs):
     context = super().get_context_data(**kwargs)
     barrido_client = CoreBarridoClient()
     outputs_strategies = barrido_client.outputs_strategies(
         self.kwargs.get("application"))
     self.permission_required.append(
         f"core.outputs_strategy_access_{self.kwargs.get('application')}")
     if outputs_strategies:
         context["outputs_strategies"] = outputs_strategies.json()
     else:
         messages.add_message(
             self.request, messages.ERROR,
             "Error al leer tabla: [{}] {}".format(
                 outputs_strategies.status_code, outputs_strategies.reason))
     context["table_actions"] = []
     context["table_actions"].append(
         ActionButton("DETALLES", "outputs_strategy_detail"))
     return context
Example #12
0
 def get_context_data(self, **kwargs):
     context = super(BucketsStrategiesDetailView,
                     self).get_context_data(**kwargs)
     barrido_client = CoreBarridoClient()
     buckets_strategy = barrido_client.get_buckets_strategy(
         self.kwargs.get("buckets_strategy_id"))
     if buckets_strategy:
         context["buckets_strategy"] = buckets_strategy.json()
         application = buckets_strategy.json()["application"]
         context["application"] = application
         context["application_description"] = get_application_description(
             self.request, application)
     else:
         messages.add_message(
             self.request, messages.ERROR,
             "Error al leer tabla: [{}] {}".format(
                 buckets_strategy.status_code, buckets_strategy.reason))
     return context
Example #13
0
 def get(self, request, file_storage_key, **kwargs):
     barrido_client = CoreBarridoClient()
     response = barrido_client.download_file_storage(file_storage_key)
     if response.status_code == 200:
         file = io.BytesIO(base64.b64decode(response.content))
         http_response = HttpResponse(
             file, content_type='application/octet-stream')
         http_response['Content-Disposition'] = 'filename={}'.format(
             request.GET.get("file_name", "data"))
         return http_response
     parsed = json.loads(response.content)
     messages.add_message(
         self.request, messages.ERROR,
         "No se ha podido descargar el archivo: " + parsed["message"])
     return HttpResponseRedirect(
         reverse_lazy(
             "strategy_exec",
             kwargs={"application": self.kwargs.get("application")}))
Example #14
0
    def get_redirect_url(self, *args, **kwargs):
        barrido_client = CoreBarridoClient()
        if kwargs.get("action_id") == 'CANCEL':
            response = barrido_client.cancel_strategy_executions_agent(
                kwargs.get("strategy_exec_id"), kwargs.get("agent_code"))
        else:
            response = barrido_client.approve_strategy_executions_agent(
                kwargs.get("strategy_exec_id"), kwargs.get("agent_code"))

        if response.status_code == 200:
            messages.add_message(self.request, messages.SUCCESS,
                                 "Agente aprobado actualizada.")
        else:
            messages.add_message(self.request, messages.ERROR,
                                 "La Ejecución no pudo ser actualizada")

        return reverse_lazy(
            "strategy_exec_detail",
            kwargs={"strategy_exec_id": kwargs.get("strategy_exec_id")})
    def verify_preconditions(self):
        ret = []
        status = CoreBarridoClient().get_system_status_report()
        if status.status_code == 200:
            blocked_date = status.json(object_hook=datetime_parser)
            diff = datetime.datetime.now(
            ) - blocked_date['last_blocked_accounts_database_datetime']
            days, seconds = diff.days, diff.seconds
            hours = days * 24 + seconds // 3600
            if hours > 24:
                ret.append(
                    "La tabla de Bajas de Servicio y Cuentas Cerradas está desactualizada!"
                )
        else:
            ret.append(
                "No fue posible validar la fecha de Bajas de Servicio y Cuentas Cerradas"
            )

        return ret
Example #16
0
 def get_context_data(self, **kwargs):
     context = super(StrategyExecutionsDetailView,
                     self).get_context_data(**kwargs)
     barrido_client = CoreBarridoClient()
     stg_exec = barrido_client.get_strategy_executions(
         self.kwargs.get("strategy_exec_id")).json(
             object_hook=datetime_parser)
     application_name = stg_exec["application"]
     context["strategy_execution_detail"] = stg_exec
     application = applications.create_application(application_name)
     context[
         "modules"] = application.get_strategy_executions_detail_modules(
             stg_exec)
     context["header"] = application.get_strategy_executions_detail_header(
         stg_exec)
     context["application_name"] = application_name
     context["application_description"] = get_application_description(
         self.request, application_name)
     return context
Example #17
0
 def form_valid(self, form):
     data = form.cleaned_data
     barrido_client = CoreBarridoClient()
     response = barrido_client.process_active_wallet(
         data.get("application"), data.get("data_source_reader_settings"),
         data.get("buckets_strategy"), data.get("paying_agents_strategy"),
         data.get("outputs_strategy"), data.get("active_wallet"),
         data.get("expired_date"), data.get("pay_date"),
         data.get("process_date"), data.get("start_collection_date"),
         data.get("middle_collection_date"),
         data.get("end_collection_date"), self.request.user.username)
     if response.status_code == 202:
         messages.add_message(
             self.request, messages.SUCCESS,
             "La cartera activa se estara procesando brevemente")
     else:
         messages.add_message(self.request, messages.ERROR,
                              "No fue posible procesar la cartera activa")
     return super(StrategyExecutionsNewView, self).form_valid(form)
Example #18
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        barrido_client = CoreBarridoClient()
        application_name = self.kwargs.get("application")
        context["application_name"] = application_name
        context["application_description"] = get_application_description(
            self.request, application_name)
        strategy_exec = barrido_client.strategy_executions(application_name)
        self.permission_required.append(
            f"core.strategy_exec_access_{application_name}")
        if strategy_exec:
            context["strategy_executions"] = strategy_exec.json(
                object_hook=datetime_parser)
        else:
            messages.add_message(
                self.request, messages.ERROR,
                "Error al leer tabla: [{}] {}".format(
                    strategy_exec.status_code, strategy_exec.reason))

        return context
Example #19
0
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        barrido_client = CoreBarridoClient()
        application = self.kwargs.get("application")
        data_source_reader_settings = barrido_client.data_source_reader_settings(
            application)
        context["application_description"] = get_application_description(
            self.request, application)
        self.permission_required.append(
            f"core.data_source_reader_settings_access_{self.kwargs.get('application')}"
        )
        if data_source_reader_settings:
            context[
                "data_source_reader_settings"] = data_source_reader_settings.json(
                )
        else:
            messages.add_message(
                self.request, messages.ERROR,
                "Error al leer tabla: [{}] {}".format(
                    data_source_reader_settings.status_code,
                    data_source_reader_settings.reason))

        return context
Example #20
0
    def __init__(self, *args, **kwargs):
        super(StrategyExecutionsNewForm, self).__init__(*args, **kwargs)
        barrido_client = CoreBarridoClient()

        application = self.fields["application"].initial
        self.fields['data_source_reader_settings'].choices = [
            (dsr_setting.get("id"), dsr_setting.get("description"))
            for dsr_setting in barrido_client.data_source_reader_settings(
                application).json()
        ]

        self.fields['buckets_strategy'].choices = [('', '-Seleccionar-')] + [
            (buckets_strategy.get("id"), buckets_strategy.get("description"))
            for buckets_strategy in barrido_client.buckets_strategies(
                application).json()
        ]

        self.fields['paying_agents_strategy'].choices = [
            ('', '-Seleccionar-')
        ] + [(pa_strategy.get("id"), pa_strategy.get("description"))
             for pa_strategy in barrido_client.paying_agents_strategies(
                 application).json()]

        self.fields['outputs_strategy'].choices = [
            (output_strategy.get("id"), output_strategy.get("description"))
            for output_strategy in barrido_client.outputs_strategies(
                application).json()
        ]

        collection = CollectionCycle.objects.filter(
            start_date__lte=datetime.date.today(),
            end_date__gte=datetime.date.today()).first()

        if not collection is None:
            self.fields[
                "start_collection_date"].initial = collection.start_date.strftime(
                    '%Y-%m-%d')
            self.fields[
                "middle_collection_date"].initial = collection.middle_date.strftime(
                    '%Y-%m-%d')
            self.fields[
                "end_collection_date"].initial = collection.end_date.strftime(
                    '%Y-%m-%d')
        else:
            self.fields[
                "validation_message"].initial = "No es posible crear una nueva ejecución debido a que no se encontró ningún Ciclo de Cobranza dado de alta"