class SwitchTestFlow(Flow): start = flow.StartFunction(create_test_flow).Next(this.switch) switch = flow.Switch().Case(this.task1, cond=lambda process: True).Default(this.task2) task1 = flow.Handler(handler).Next(this.end) task2 = flow.Handler(handler).Next(this.end) end = flow.End()
class IfTestFlow(Flow): start = flow.StartFunction(create_test_flow).Next(this.if_task) if_task = flow.If(cond=lambda process: True).OnTrue(this.on_true).OnFalse( this.on_false) on_true = flow.Handler(handler).Next(this.end) on_false = flow.Handler(handler).Next(this.end) end = flow.End()
class CreatevmFlow(Flow): process_class = models.CreatevmProcess task_class = models.CreatvmTask start = (flow.Start(flow_views.CreateProcessView, fields=[ 'username', 'cpu_cores', 'disk_size', 'memory_size', 'os_type' ]).Permission('createvmflow.can_start_request').Next( this.assign_approve)) assign_approve = (flow.View(views.AssignApproverView).Permission( 'createvmflow.can_assign_approver').Next(this.make_approver_task)) make_approver_task = (nodes.ApproverSplit(this.approvers_handler).Next( this.make_approve)) make_approve = (flow.View( views.ApproveView).Permission('createvmflow.can_approve_request').Next( this.check_approve)) check_approve = (flow.If(this.caculate_approve).Then( this.provision_instance).Else(this.reject)) provision_instance = (flow.Handler(this.provision_fun).Next(this.end)) reject = (flow.Handler(this.reject_fun).Next(this.end)) end = flow.End() def provision_fun(self, activation, *args, **kwargs): print("Provision request sended") def caculate_approve(self, activation): answers = activation.process.processapproverandans_set.all() for ans in answers: if not ans.approve: return False return True def reject_fun(self, activation, **kwargs): print("Provision request reject") def approvers_handler(self, activation): approvers = activation.process.processapproverandans_set.all() users = [] for user in approvers: users.append(user.user) return users
class HelloWorldFlow(Flow): process_class = HelloWorldProcess """ Implementação do evento de inicialização do processo """ start = (flow.Start(CreateProcessView, fields=["text"]).Permission(auto_create=True).Next( this.approve)) """ Implementação da atividade de aprovação da instância de processo """ approve = (flow.View(UpdateProcessView, fields=[ "approved" ]).Permission(auto_create=True).Next(this.check_approve)) """ implementação de elemento de decisão exclusiva """ check_approve = ( flow.If(lambda activation: activation.process.approved).Then( this.send).Else(this.end)) send = (flow.Handler(this.send_hello_world_request).Next(this.end)) end = flow.End() def send_hello_world_request(self, activation): print(activation.process.text)
def test_handler_activation_error_lifecycle(self): def handler(activation): raise ValueError('expected') flow_task = self.init_node(flow.Handler(handler)) act = HandlerActivation() act.initialize(flow_task, TaskStub()) # by default errors are propogated self.assertRaises(ValueError, act.perform) # disable gate error propagation with Context(propagate_exception=False): act.perform() self.assertEqual(act.task.status, STATUS.ERROR) act.retry() self.assertEqual(act.task.status, STATUS.ERROR) # undo act.undo() self.assertEqual(act.task.status, STATUS.NEW) act.cancel() self.assertEqual(act.task.status, STATUS.CANCELED)
class ApplicationFlow(Flow): process_class = ApplicationProcess process_title = 'ApplicationFlow' process_description = 'Process used to apply for a grant.' start = flow.Start(ApplicationView).Next(this.legal_approval) legal_approval = flow.View(UpdateProcessView, fields=['legal_approved' ]).Next(this.finance_approval) finance_approval = flow.View(UpdateProcessView, fields=['finance_approved' ]).Next(this.notify_applicant) notify_applicant = flow.Handler(this.send_applicant_notification).Next( this.end) end = flow.End() def send_applicant_notification(self, activation): subject = 'Application rejected.' message = 'Sorry but your application has been rejected.' approved = all([ activation.process.legal_approved, activation.process.finance_approved ]) if approved: subject = 'Application approved.' message = 'Congratulations, your application has been approved.' logger.info(subject, message)
class DocumentUploadFlow(Flow): process_class = DocumentUploadProcess start = ( flow.Start( views.start_upload_workflow #CreateProcessView, #fields=["text"] ).Permission( #auto_create=True 'munshai.add_helloworldprocess' #'munshai.can_start_helloworldprocess', #'munshai.can_view_helloworldprocess' ).Next(this.approve)) approve = ( flow.View(UpdateProcessView, fields=["approved", "upload"]).Permission( #auto_create=True 'munshai.can_approve_helloworldprocess', #'munshai.can_approve_helloworldprocess' #'munshai.view_helloworldrocess' ).Next(this.check_approve)) check_approve = ( flow.If(lambda activation: activation.process.approved).Then( this.send).Else(this.end)) send = (flow.Handler(this.send_hello_world_request).Next(this.end)) end = flow.End() def send_hello_world_request(self, activation): print(activation.process.text) print(activation.process.upload)
class BaseFlow(Flow): start = flow.StartFunction().Next(this.end) handle = flow.Handler(this.handler_execute) end = flow.End() def handler_execute(self, activation): raise NotImplementedError
class QingJiaFlow(Flow): process_class = QingJiaProcess start = (flow.Start( CreateProcessView, fields=["text", "days", "demo"], ).Permission(auto_create=True).Next(this.submit)) submit = (flow.View(UpdateProcessView, fields=[ "submit", "submit_note" ]).Permission(auto_create=True).Next(this.approve)) approve = (flow.View(UpdateProcessView, fields=[ "approved" ]).Permission(auto_create=True).Next(this.check_approve)) check_approve = ( flow.If(lambda activation: activation.process.approved).Then( this.send).Else(this.end)) send = (flow.Handler(this.send_qing_jia_request).Next(this.end)) end = flow.End() def send_qing_jia_request(self, activation): print(activation.process.text)
class HelloWorldFlow(Flow): """ Hello world This process demonstrates hello world approval request flow. """ process_class = HelloWorldProcess process_title = _('Hello world') process_description = _('This process demonstrates hello world approval request flow.') lock_impl = lock.select_for_update_lock summary_template = _("'{{ process.text }}' message to the world") start = ( flow.Start( flow_views.CreateProcessView, fields=['text'], task_title=_('New message')) .Permission(auto_create=True) .Next(this.approve) ) approve = ( flow.View( flow_views.UpdateProcessView, fields=['approved'], task_title=_('Approve'), task_description=_("Message approvement required"), task_result_summary=_("Messsage was {{ process.approved|yesno:'Approved,Rejected' }}")) .Permission(auto_create=True) .Next(this.check_approve) ) check_approve = ( flow.If( cond=lambda act: act.process.approved, task_title=_('Approvement check'), ) .Then(this.send) .Else(this.end) ) send = ( flow.Handler( this.send_hello_world_request, task_title=_('Send message'), ) .Next(this.end) ) end = flow.End( task_title=_('End'), ) def send_hello_world_request(self, activation): with open(os.devnull, "w") as world: world.write(activation.process.text)
class InSubprocessFlow(Flow): process_class = models.MainProcess task_class = models.MainTask start = (flow.Start(flow_views.CreateProcessView, fields=['text']).Next(this.sub_prorcess)) sub_prorcess = (SubProcess(AddText.start).Next(this.printtext)) printtext = (flow.Handler(this.printfunc).Next(this.end)) end = flow.End() def printfunc(self, activation): print(activation.process.text)
class LeaveFlow(Flow): process_class = LeaveProcess summary_template = "{{ process.leave.req_by.user.username }}的请假" process_title = '请假' start = (flow.Start(LeaveStartView).Permission(auto_create=True).Next( this.dep_approve)) dep_approve = ( flow.View(approve_check).Assign( #提交到自己的manager lambda act: act.process.leave.req_by.Manager.user).Next( this.check_dep_approve)) check_dep_approve = ( flow.If(lambda activation: activation.process.dep_approved == 1).Then( this.hr_approve).Else(this.NG)) hr_approve = ( flow.View(approve_check).Permission( #有权限就可以签收,给特定的人赋权就可以。 auto_create=True).Next(this.check_hr_approve)) check_hr_approve = ( flow.If(lambda activation: activation.process.hr_approved == 1).Then( this.OK).Else(this.NG)) NG = (flow.Handler(this.send_NG_request).Next(this.end)) OK = (flow.Handler(this.send_OK_request).Next(this.end)) end = flow.End() def send_NG_request(self, activation): print('dep_approved==>' + str(activation.process.dep_approved)) print('hr_approved==>' + str(activation.process.hr_approved)) print('NG') def send_OK_request(self, activation): #print(activation.process.leave.user) print('OK')
class FunctionFlow(Flow): start = flow.StartFunction(create_test_flow).Next(this.func_task) default_start = flow.StartFunction().Next(this.func_task) inline_start = flow.StartFunction().Next(this.func_task) func_task = flow.Function(function_task).Next(this.handler_task) handler_task = flow.Handler(handler).Next(this.end) end = flow.End() def inline_start_func(self, activation): activation.prepare() activation.done() self.inline_start_func_called = True return activation
class FunctionFlow(Flow): process_cls = TestProcess start = flow.StartFunction(tasks.start_process) \ .Next(this.task1) task1 = flow.Handler(tasks.do_handler_task) \ .Next(this.task2) task2 = flow.Function(tasks.do_func_task) \ .Next(this.end) end = flow.End()
class MyPizzaFlow(Flow): process_class = MyPizzaProcess start = ( flow.Start(CreateProcessView, fields=['content']) .Available(available_in_group('customers')) .Next(this.order_pizza) ) order_pizza = ( flow.Handler(this.save_content_to_order) .Next(this.external_join) ) # To run this, we need to know which task we are specifically referring to # This can be done by querying the database my_trigger = ( flow.Function(trigger_triggered, task_loader=lambda flow_task, task: task) .Next(this.external_join) ) external_join = ( flow.Join() .Next(this.take_the_order) ) take_the_order = ( flow.View(TakeTheOrderView, fields=['table_location']) .Permission('users.can_take_the_order') .Next(this.prepare_pizza) ) prepare_pizza = ( flow.View( UpdateProcessView ).Next(this.bring_pizza) ) bring_pizza = ( flow.End() # TODO continue ) def save_content_to_order(self, activation): order = Order() order.content = activation.process.content order.save() activation.process.order = order activation.process.save()
class KYCFlow(Flow): """ KYC Flow This process demonstrates KYC Case approval/rejection request flow. """ process_class = KYCSubmitProcess process_title = _('KYC Submission') process_description = _('This process demonstrates KYC Submission flow.') lock_impl = lock.select_for_update_lock summary_template = _("KYC Approval for '{{process.first_name}}'") start = (flow.Start(flow_views.CreateProcessView, fields=['text', 'first_name', 'last_name', 'email'], task_title=_('New KYC Case')).Permission( auto_create=True).Next(this.decide)) decide = (flow.View( flow_views.UpdateProcessView, fields=['approved', 'rejected'], task_title=_('KYC Decision'), task_description=_("KYC Case Decision required"), task_result_summary=_( "KYC Case was {{ process.approved|yesno:'Approved,Rejected' }}")). Permission(auto_create=True).Next(this.check_approve)) check_approve = (flow.If( cond=lambda act: act.process.approved, task_title=_('Approval check'), ).Then(this.send).Else(this.end)) # assign_back = ( # .Assign( lambda act: act.process.created_by), # ) send = (flow.Handler( this.update_block, task_title=_('Process Completed'), ).Next(this.end)) end = flow.End(task_title=_('End'), ) def update_block(self, activation): pass
class HelloWorldFlow(Flow): """ Hello world This process demonstrates hello world approval request flow. """ process_class = HelloWorldProcess process_title = _('Ciao Mondo') process_description = _( "Questo processo è relativo all'approvazine di un messaggio.") lock_impl = lock.select_for_update_lock summary_template = _("Messaggio al mondo: '{{ process.text }}'") start = (flow.Start(flow_views.CreateProcessView, fields=['text'], task_title=_('Nuovo messaggio')).Permission( auto_create=True).Next(this.approve)) approve = (flow.View( flow_views.UpdateProcessView, fields=['approved'], task_title=_('Approvazione'), task_description=_( " E' richiesta l'approvazione {{ process.text }} "), task_result_summary= _("Il messaggio è stato: {{ process.approved|yesno:'Approved,Rejected' }}" )).Permission(auto_create=True).Next(this.check_approve)) check_approve = (flow.If( cond=lambda act: act.process.approved, task_title=_('Verifica approvazione'), ).Then(this.send).Else(this.end)) send = (flow.Handler( this.send_hello_world_request, task_title=_('Spedizione messaggio'), ).Next(this.end)) end = flow.End(task_title=_('End'), ) def send_hello_world_request(self, activation): with open(os.devnull, "w") as world: world.write(activation.process.text)
def test_handler_activation_lifecycle(self): def handler(activation): pass flow_task = self.init_node(flow.Handler(handler)) act = HandlerActivation() act.initialize(flow_task, TaskStub()) # execute act.perform() self.assertEqual(act.task.status, STATUS.DONE) # undo act.undo() self.assertEqual(act.task.status, STATUS.NEW) act.cancel() self.assertEqual(act.task.status, STATUS.CANCELED)
class HelloWorldFlow(Flow): process_class = HelloWorldProcess process_title = _('Hello world') process_description = _('This process demonstrates hello world approval request flow.') lock_impl = lock.select_for_update_lock summary_template = _("'{{ process.text }}' message to the world") start = ( flow.Start( CreateProcessView, fields=["text"] ).Permission( auto_create=True ).Next(this.approve) ) approve = ( flow.View( UpdateProcessView, fields=["approved"] ).Permission( auto_create=True ).Next(this.check_approve) ) check_approve = ( flow.If(lambda activation: activation.process.approved) .Then(this.send) .Else(this.end) ) send = ( flow.Handler( this.send_hello_world_request ).Next(this.end) ) end = flow.End() def send_hello_world_request(self, activation): with open(os.devnull, "w") as world: world.write(activation.process.text)
class HelloWorldFlow(Flow): process_class = HelloWorldProcess flow_id = 2 start = (Start(StartView).Permission(auto_create=True).Next( this.check_start)) check_start = ( flow.If(lambda activation: activation.process.is_terminate).Then( this.end).Else(this.approve)) # approve = ( # flow.View( # UpdateProcessView, # fields=["approved"] # ).Assign(owner=User.objects.filter(username__in=['porter']).first()).Permission(auto_create=True).Next(this.check_approve) # ) approve = (Approval( view_or_class=ApprovalView, wait_all=False, task_title='审批').Assign(owner_list=this.get_approve_user).Permission( auto_create=True).Next(this.check_approve)) check_approve = ( flow.If(lambda activation: activation.process.approved).Then( this.send).Else(this.approve2)) send = (flow.Handler(this.send_hello_world_request).Next(this.end)) approve2 = (Approval( view_or_class=ApprovalView, task_title='审批2').Assign(owner_list=User.objects.filter( username__in=['porter', 'admin', 'wjc']).all()).Permission( auto_create=True).Next(this.end)) end = flow.End() def send_hello_world_request(self, activation): print(activation.process.text) def get_approve_user(self, activation): return User.objects.filter( username__in=['porter', 'admin', 'wjc']).all()
class HelloWorldFlow(Flow): process_class = HelloWorldProcess start = (flow.Start(CreateProcessView, fields=['text']).Permission( auto_create=True, ).Next(this.approve)) approve = (flow.View(UpdateProcessView, fields=[ 'approved' ]).Permission(auto_create=True).Next(this.check_approve)) check_approve = ( flow.If(lambda activation: activation.process.approved).Then( this.send).Else(this.end)) send = (flow.Handler(this.send_hello_world_request).Next(this.end)) end = flow.End() def send_hello_world_request(self, activation): print(activation.process.text)
class Venta(Flow): process_class = Cliente adjunto1 = "adjunto1" Inicial = (flow.Start( CreateProcessView, fields=[adjunto1, "tipo_documento", "numero_documento", adjunto1 ]).Permission(auto_create=True, ).Next(this.Venta_inicial)) Venta_inicial = (flow.View(UpdateProcessView, fields=[ "nombre1", "nombre2", "apellidos", "fecha_documento", "fecha_nacimiento", "departamento", "municipio", "barrio", "direccion", "email", "telefono_mig", "telefono_2", "categoria", "tipo_plan", "plan", "v_total_plan", "observaciones", "adjunto2", "adjunto3", ]).Permission(auto_create=True).Next( this.check_approve)) check_approve = ( flow.If(lambda activation: activation.process.approved).Then( this.send).Else(this.end)) send = (flow.Handler(this.send_hello_world_request).Next(this.end)) end = flow.End() def send_hello_world_request(self, activation): print(activation.process.text)
class LparaFlow(Flow): process_class = LparaProcess start = (flow.Start(CreateProcessView, fields=[ "reason", 'ref_table' ]).Permission(auto_create=True).Next(this.approve)) approve = (flow.View(UpdateProcessView, fields=["approved", "appreciation_text" ]).Permission(auto_create=True).Next( this.check_approve)) check_approve = ( flow.If(lambda activation: activation.process.approved).Then( this.send).Else(this.end)) send = (flow.Handler(this.send_hello_world_request).Next(this.end)) end = flow.End() def send_hello_world_request(self, activation): print(activation.process.id)
class CheckRequestFlow(Flow): process_class = CheckRequestProcess start = ( flow.Start( CreateProcessView, fields=["text", "department"] ).Permission( auto_create=True ).Next(this.approve) ) approve = ( flow.View( UpdateProcessView, fields=["approved"] ).Permission( auto_create=True ).Next(this.check_approve) ) check_approve = ( flow.If(lambda activation: activation.process.approved) .Then(this.send) .Else(this.end) ) send = ( flow.Handler( this.send_check ).Next(this.end) ) end = flow.End() def send_check(self, activation): print(activation.process.text)
class SubmissionFlow(Flow): process_class = SubmissionProcess start = flow.Start( CreateProcessView, fields=['label'] ).Permission( auto_create=True ).Next( this.download ) download = flow.View( views.DownloadXLSXTemplateView, ).Assign( this.start.owner ).Next( this.check_download ) check_download = flow.If( lambda activation: activation.process.downloaded ).Then( this.upload ).Else( this.download ) upload = flow.View( views.UploadArchiveView, ).Assign( this.start.owner ).Next( this.check_upload ) check_upload = flow.If( lambda activation: activation.process.uploaded ).Then( this.meta ).Else( this.upload ) meta = flow.Handler( this.parse_meta, activation_class=NotPropagatedExceptionHandlerActivation, ).Next( this.check_meta ) check_meta = flow.If( lambda activation: activation.process.meta is not None ).Then( this.validation ).Else( this.upload ) validation = flow.View( views.ArchiveValidationView, ).Assign( this.start.owner ).Next( this.check_validation ) check_validation = flow.If( lambda activation: activation.process.validated ).Then( this.tags ).Else( this.validation ) tags = flow.View( views.TagsView, ).Assign( this.start.owner ).Next( this.import_archive ) import_archive = AsyncHandler( this.perform_archive_importation, ).Next( this.check_import ) check_import = flow.If( lambda activation: activation.process.imported ).Then( this.end ).Else( this.validation ) end = flow.End() def get_archive_path(self, activation): return Path( settings.MEDIA_ROOT ) / Path( activation.process.archive.name ) def parse_meta(self, activation): archive_path = self.get_archive_path(activation) archive = PixelArchive(archive_path) archive.parse(serialized=True) activation.process.meta = archive.meta activation.process.save() def perform_archive_importation(self, activation): archive_path = self.get_archive_path(activation) process = activation.process pixeler = process.created_by task = process.get_task(self.import_archive) @background.task def async_import_archive(): logger.debug("Async import started…") archive = PixelArchive(archive_path) logger.debug("Archive instanciated") logger.debug("Saving archive…") return archive.save(pixeler=pixeler, submission=process) @background.callback def importation_callback(future): """ We need to force databases connection closing since the background process (in a separated thread) creates a new connection that would never be closed otherwise. """ logger.debug("Background importation callback started…") e = future.exception() logger.debug("Future exception: {} ({})".format(e, type(e))) if e is not None: task.status = STATUS.ERROR task.comments = str(e) task.finished = now() task.save() # Re-raise the exception for lazy logging try: raise e except Exception: logger.exception( "Importation failed! archive: {} (pixeler: {})".format( archive_path, pixeler ) ) logger.debug( "Closing open database connections " "(background callback exception)" ) db.connections.close_all() raise process.imported = True process.save() logger.debug("Submission process updated (imported: True)") logger.debug("Proceeding with activation callback") activation.callback() logger.debug( "Closing open database connections (background callback)" ) db.connections.close_all() logger.debug("Background importation callback done") async_import_archive()
class Flow(FlowStub): handler_task = flow.Handler(this.task_handler) method_called = False def task_handler(self, activation): Flow.method_called = True
class FlowMixin(object): notify_admins = flow.Handler(this.send_alert).Next(this.notify_users) notify_users = flow.Handler(this.send_alert)
class ShipmentFlow(Flow): """ Delivery process """ process_cls = models.ShipmentProcess start = flow.StartFunction(tasks.start_shipment_process) \ .Next(this.split_clerk_warehouse) # clerk split_clerk_warehouse = flow.Split() \ .Next(this.set_shipment_type) \ .Next(this.package_goods) set_shipment_type = flow.View(views.ShipmentView, fields=["carrier"]) \ .Permission(auto_create=True) \ .Next(this.delivery_mode) delivery_mode = flow.If(cond=lambda p: p.is_normal_post()) \ .OnTrue(this.check_insurance) \ .OnFalse(this.request_quotes) request_quotes = flow.View(views.ShipmentView, fields=["carrier_quote"]) \ .Assign(this.set_shipment_type.owner) \ .Next(this.join_clerk_warehouse) check_insurance = flow.View(views.ShipmentView, fields=["need_insurance"]) \ .Assign(this.set_shipment_type.owner) \ .Next(this.split_on_insurance) split_on_insurance = flow.Split() \ .Next(this.take_extra_insurance, cond=lambda p: p.need_extra_insurance()) \ .Always(this.fill_post_label) fill_post_label = flow.View(views.ShipmentView, fields=["post_label"]) \ .Next(this.join_on_insurance) \ .Assign(this.set_shipment_type.owner) join_on_insurance = flow.Join() \ .Next(this.join_clerk_warehouse) # Logistic manager take_extra_insurance = flow.View(views.InsuranceView) \ .Next(this.join_on_insurance) \ .Permission(auto_create=True) # Warehouse worker package_goods = flow.View(ProcessView) \ .Next(this.join_clerk_warehouse) \ .Permission(auto_create=True) join_clerk_warehouse = flow.Join() \ .Next(this.move_package) move_package = flow.View(ProcessView.as_view()) \ .Assign(this.package_goods.owner) \ .Next(this.mark_order_done) mark_order_done = flow.Handler(tasks.done_order) \ .Next(this.end) end = flow.End()
class GrantManagementFlow(Flow): summary_template = "{{ process.grant_application.company.name" \ "|default:process.grant_application.manual_company_name }} " \ "[{{ process.status }}]" process_class = GrantManagementProcess start = flow.StartFunction(this.start_callback, task_title='Submit your application.').Next( this.send_application_submitted_email) send_application_submitted_email = flow.Handler( this.send_application_submitted_email_callback).Next( this.create_verify_tasks) # Verify Eligibility tasks create_verify_tasks = (flow.Split().Always( this.verify_previous_applications).Always( this.verify_event_commitment).Always( this.verify_business_entity).Always( this.verify_state_aid).Always(this.finish_verify_tasks)) verify_previous_applications = flow.View( BaseGrantManagementView, form_class=VerifyPreviousApplicationsForm, task_title='Verify number of previous grants').Next( this.finish_verify_tasks) verify_event_commitment = flow.View( BaseGrantManagementView, form_class=VerifyEventCommitmentForm, task_title='Verify event commitment').Next(this.finish_verify_tasks) verify_business_entity = flow.View( BaseGrantManagementView, form_class=VerifyBusinessEntityForm, task_title='Verify business eligibility').Next( this.finish_verify_tasks) verify_state_aid = flow.View(BaseGrantManagementView, form_class=VerifyStateAidForm, task_title='Verify event commitment').Next( this.finish_verify_tasks) finish_verify_tasks = flow.Join().Next(this.create_suitability_tasks) # Suitability tasks create_suitability_tasks = (flow.Split().Always( this.products_and_services).Always( this.products_and_services_competitors).Always( this.export_strategy).Always(this.event_is_appropriate).Always( this.finish_suitability_tasks)) products_and_services = flow.View(BaseGrantManagementView, form_class=ProductsAndServicesForm, task_title='Products and services').Next( this.finish_suitability_tasks) products_and_services_competitors = flow.View( BaseGrantManagementView, form_class=ProductsAndServicesCompetitorsForm, task_title='Products and services competitors').Next( this.finish_suitability_tasks) export_strategy = flow.View(BaseGrantManagementView, form_class=ExportStrategyForm, task_title='Export strategy').Next( this.finish_suitability_tasks) event_is_appropriate = flow.View(BaseGrantManagementView, form_class=EventIsAppropriateForm, task_title='Event is appropriate').Next( this.finish_suitability_tasks) finish_suitability_tasks = flow.Join().Next(this.decision) # Decision task decision = flow.View( BaseGrantManagementView, form_class=DecisionForm, task_title='Final review', ).Next(this.send_decision_email) send_decision_email = flow.Handler(this.send_decision_email_callback).Next( this.end) end = flow.End() @method_decorator(flow.flow_start_func) def start_callback(self, activation, grant_application): activation.prepare() activation.process.grant_application = grant_application activation.done() return activation.process def send_application_submitted_email_callback(self, activation): NotifyService().send_application_submitted_email( email_address=activation.process.grant_application.applicant_email, applicant_full_name=activation.process.grant_application. applicant_full_name, application_id=activation.process.grant_application.id_str) def send_decision_email_callback(self, activation): if activation.process.is_approved: NotifyService().send_application_approved_email( email_address=activation.process.grant_application. applicant_email, applicant_full_name=activation.process.grant_application. applicant_full_name, application_id=activation.process.grant_application.id_str) else: NotifyService().send_application_rejected_email( email_address=activation.process.grant_application. applicant_email, applicant_full_name=activation.process.grant_application. applicant_full_name, application_id=activation.process.grant_application.id_str)
class ResearchFlow(Flow): process_class = ResearchProcess process_title = _("Research Assistant Process") process_description = _( "This process helps researchers to find and analyze papers") lock_impl = lock.select_for_update_lock summary_template = ("Research: '{{ process.research.name }}'") start = (flow.Start(views.StartView).Permission(auto_create=True).Next( this.select_bases)) select_bases = (flow.View( views.BasesView).Permission(auto_create=True).Next(this.search_params)) search_params = (flow.View( views.SearchParams).Permission(auto_create=True).Next(this.approve)) approve = (flow.View( flow_views.UpdateProcessView, fields=['approved'], task_title=('Approve'), task_description=("Research {{ process.text }} approvement required"), task_result_summary=( "Messsage was {{ process.approved }}")).Permission( auto_create=True).Next(this.check_approve)) check_approve = (flow.If(cond=lambda act: act.process.approved, task_title=_('Approvement check')).Then( this.get_metadata).Else(this.end)) get_metadata = (flow.Handler(this.get_papers_metadata, task_title="Getting papers metadata").Next( this.paper_review)) paper_review = (flow.View(views.paper_review).Permission( auto_create=True).Next(this.check_papers_for_review)) check_papers_for_review = (flow.If( cond=lambda act: len(act.process.research.papers.all()) == act.process. research.papers_metadata_analized, task_title=_('Approvement check'), ).Then(this.end).Else(this.paper_review)) end = flow.End(task_title=_('End')) def get_papers_metadata(self, activation): #import ipdb; ipdb.set_trace() logger.info("Starting get metadata function") research = activation.process.research search_params = { 'search_string': research.search_params_string, 'date': research.search_params_date } papers = {} try: os.environ["SD_TOKEN"] except KeyError: print( "Please set the environment variable SD_TOKEN as token for ScienceDirect API" ) sys.exit(1) token = os.environ["SD_TOKEN"] search_bases = research.search_bases.iterator() for base in search_bases: if base.name == "ACM Digital Library": logging.info("Getting ACM papers metadata") acm_search = acm.Acm() papers.update(acm_search.search(search_params)) elif base.name == "ScienceDirect": logging.info("Getting ScienceDirect papers metadata") sd_search = science_direct.ScienceDirect(token) papers.update(sd_search.search(search_params)) for doi in papers.keys(): paper = papers[doi] paper.save() logging.info("Adding paper {}".format(paper.title)) research.papers.add(paper)