diff --git a/bin/pre b/bin/pre new file mode 100755 index 000000000..fa89ecc79 --- /dev/null +++ b/bin/pre @@ -0,0 +1,11 @@ +#!/usr/bin/env bash + +function error_handler() { + >&2 echo "Exited with BAD EXIT CODE '${2}' in ${0} script at line: ${1}." + exit "$2" +} +trap 'error_handler ${LINENO} $?' ERR +set -o errtrace -o errexit -o nounset -o pipefail + +script_dir="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" +"${script_dir}/run_pyl" pre diff --git a/bin/run_pyl b/bin/run_pyl index d3abd7fc6..64446662a 100755 --- a/bin/run_pyl +++ b/bin/run_pyl @@ -16,6 +16,17 @@ react_projects=( spiffworkflow-frontend ) +subcommand="${1:-}" + +if [[ "$subcommand" == "pre" ]]; then + if [[ -n "$(git status --porcelain SpiffWorkflow)" ]]; then + echo "SpiffWorkflow has uncommitted changes. Running its test suite." + pushd SpiffWorkflow + make tests-par # run tests in parallel + popd + fi +fi + function get_python_dirs() { (git ls-tree -r HEAD --name-only | grep -E '\.py$' | awk -F '/' '{print $1}' | sort | uniq | grep -v '\.' | grep -Ev '^(bin|migrations)$') || echo '' } @@ -50,23 +61,34 @@ function run_pre_commmit() { } for react_project in "${react_projects[@]}" ; do - pushd "$react_project" - npm run lint:fix - popd + # if pre, only do stuff when there are changes + if [[ "$subcommand" != "pre" ]] || [[ -n "$(git status --porcelain "$react_project")" ]]; then + pushd "$react_project" + npm run lint:fix + popd + fi done for python_project in "${python_projects[@]}" ; do - pushd "$python_project" - run_fix_docstrings || run_fix_docstrings - run_autoflake || run_autoflake - popd + if [[ "$subcommand" != "pre" ]] || [[ -n "$(git status --porcelain "$python_project")" ]]; then + pushd "$python_project" + run_fix_docstrings || run_fix_docstrings + run_autoflake || run_autoflake + popd + fi done -run_pre_commmit || run_pre_commmit -for python_project in "${python_projects[@]}"; do - pushd "$python_project" - poetry install - poetry run mypy $(get_python_dirs) - poetry run coverage run --parallel -m pytest - popd +if [[ "$subcommand" != "pre" ]] || [[ -n "$(git status --porcelain "spiffworkflow-backend")" ]]; then + # rune_pre_commit only applies to spiffworkflow-backend at the moment + run_pre_commmit || run_pre_commmit +fi + +for python_project in "${python_projects[@]}"; do + if [[ "$subcommand" != "pre" ]] || [[ -n "$(git status --porcelain "$python_project")" ]]; then + pushd "$python_project" + poetry install + poetry run mypy $(get_python_dirs) + poetry run coverage run --parallel -m pytest + popd + fi done diff --git a/spiffworkflow-backend/conftest.py b/spiffworkflow-backend/conftest.py index c3af94332..b24a7ed1b 100644 --- a/spiffworkflow-backend/conftest.py +++ b/spiffworkflow-backend/conftest.py @@ -9,7 +9,7 @@ from flask_bpmn.models.db import db from flask_bpmn.models.db import SpiffworkflowBaseDBModel from tests.spiffworkflow_backend.helpers.base_test import BaseTest -from spiffworkflow_backend.models.active_task_user import ActiveTaskUserModel +from spiffworkflow_backend.models.human_task_user import HumanTaskUserModel from spiffworkflow_backend.models.process_instance import ProcessInstanceModel from spiffworkflow_backend.models.user import UserModel from spiffworkflow_backend.services.process_instance_processor import ( @@ -47,7 +47,7 @@ def app() -> Flask: @pytest.fixture() def with_db_and_bpmn_file_cleanup() -> None: """Process_group_resource.""" - db.session.query(ActiveTaskUserModel).delete() + db.session.query(HumanTaskUserModel).delete() for model in SpiffworkflowBaseDBModel._all_subclasses(): db.session.query(model).delete() diff --git a/spiffworkflow-backend/migrations/versions/e284612a9778_.py b/spiffworkflow-backend/migrations/versions/b86f7cc3a74b_.py similarity index 94% rename from spiffworkflow-backend/migrations/versions/e284612a9778_.py rename to spiffworkflow-backend/migrations/versions/b86f7cc3a74b_.py index 5ce586adb..30138654e 100644 --- a/spiffworkflow-backend/migrations/versions/e284612a9778_.py +++ b/spiffworkflow-backend/migrations/versions/b86f7cc3a74b_.py @@ -1,8 +1,8 @@ """empty message -Revision ID: e284612a9778 +Revision ID: b86f7cc3a74b Revises: -Create Date: 2022-12-19 11:23:10.567440 +Create Date: 2022-12-19 16:20:27.715487 """ from alembic import op @@ -10,7 +10,7 @@ import sqlalchemy as sa # revision identifiers, used by Alembic. -revision = 'e284612a9778' +revision = 'b86f7cc3a74b' down_revision = None branch_labels = None depends_on = None @@ -176,7 +176,7 @@ def upgrade(): sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('user_id', 'group_id', name='user_group_assignment_unique') ) - op.create_table('active_task', + op.create_table('human_task', sa.Column('id', sa.Integer(), nullable=False), sa.Column('process_instance_id', sa.Integer(), nullable=False), sa.Column('actual_owner_id', sa.Integer(), nullable=True), @@ -191,12 +191,14 @@ def upgrade(): sa.Column('task_type', sa.String(length=50), nullable=True), sa.Column('task_status', sa.String(length=50), nullable=True), sa.Column('process_model_display_name', sa.String(length=255), nullable=True), + sa.Column('completed', sa.Boolean(), nullable=False), sa.ForeignKeyConstraint(['actual_owner_id'], ['user.id'], ), sa.ForeignKeyConstraint(['lane_assignment_id'], ['group.id'], ), sa.ForeignKeyConstraint(['process_instance_id'], ['process_instance.id'], ), sa.PrimaryKeyConstraint('id'), - sa.UniqueConstraint('task_id', 'process_instance_id', name='active_task_unique') + sa.UniqueConstraint('task_id', 'process_instance_id', name='human_task_unique') ) + op.create_index(op.f('ix_human_task_completed'), 'human_task', ['completed'], unique=False) op.create_table('message_correlation', sa.Column('id', sa.Integer(), nullable=False), sa.Column('process_instance_id', sa.Integer(), nullable=False), @@ -263,17 +265,17 @@ def upgrade(): sa.ForeignKeyConstraint(['process_instance_id'], ['process_instance.id'], ), sa.PrimaryKeyConstraint('id') ) - op.create_table('active_task_user', + op.create_table('human_task_user', sa.Column('id', sa.Integer(), nullable=False), - sa.Column('active_task_id', sa.Integer(), nullable=False), + sa.Column('human_task_id', sa.Integer(), nullable=False), sa.Column('user_id', sa.Integer(), nullable=False), - sa.ForeignKeyConstraint(['active_task_id'], ['active_task.id'], ), + sa.ForeignKeyConstraint(['human_task_id'], ['human_task.id'], ), sa.ForeignKeyConstraint(['user_id'], ['user.id'], ), sa.PrimaryKeyConstraint('id'), - sa.UniqueConstraint('active_task_id', 'user_id', name='active_task_user_unique') + sa.UniqueConstraint('human_task_id', 'user_id', name='human_task_user_unique') ) - op.create_index(op.f('ix_active_task_user_active_task_id'), 'active_task_user', ['active_task_id'], unique=False) - op.create_index(op.f('ix_active_task_user_user_id'), 'active_task_user', ['user_id'], unique=False) + op.create_index(op.f('ix_human_task_user_human_task_id'), 'human_task_user', ['human_task_id'], unique=False) + op.create_index(op.f('ix_human_task_user_user_id'), 'human_task_user', ['user_id'], unique=False) op.create_table('message_correlation_message_instance', sa.Column('id', sa.Integer(), nullable=False), sa.Column('message_instance_id', sa.Integer(), nullable=False), @@ -293,9 +295,9 @@ def downgrade(): op.drop_index(op.f('ix_message_correlation_message_instance_message_instance_id'), table_name='message_correlation_message_instance') op.drop_index(op.f('ix_message_correlation_message_instance_message_correlation_id'), table_name='message_correlation_message_instance') op.drop_table('message_correlation_message_instance') - op.drop_index(op.f('ix_active_task_user_user_id'), table_name='active_task_user') - op.drop_index(op.f('ix_active_task_user_active_task_id'), table_name='active_task_user') - op.drop_table('active_task_user') + op.drop_index(op.f('ix_human_task_user_user_id'), table_name='human_task_user') + op.drop_index(op.f('ix_human_task_user_human_task_id'), table_name='human_task_user') + op.drop_table('human_task_user') op.drop_table('spiff_step_details') op.drop_index(op.f('ix_process_instance_metadata_key'), table_name='process_instance_metadata') op.drop_table('process_instance_metadata') @@ -306,7 +308,8 @@ def downgrade(): op.drop_index(op.f('ix_message_correlation_name'), table_name='message_correlation') op.drop_index(op.f('ix_message_correlation_message_correlation_property_id'), table_name='message_correlation') op.drop_table('message_correlation') - op.drop_table('active_task') + op.drop_index(op.f('ix_human_task_completed'), table_name='human_task') + op.drop_table('human_task') op.drop_table('user_group_assignment') op.drop_table('secret') op.drop_table('refresh_token') diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/api.yml b/spiffworkflow-backend/src/spiffworkflow_backend/api.yml index 876b186e4..49419ef95 100755 --- a/spiffworkflow-backend/src/spiffworkflow_backend/api.yml +++ b/spiffworkflow-backend/src/spiffworkflow_backend/api.yml @@ -509,6 +509,119 @@ paths: schema: $ref: "#/components/schemas/OkTrue" + /process-instances/for-me: + parameters: + - name: process_model_identifier + in: query + required: false + description: The unique id of an existing process model. + schema: + type: string + - name: page + in: query + required: false + description: The page number to return. Defaults to page 1. + schema: + type: integer + - name: per_page + in: query + required: false + description: The page number to return. Defaults to page 1. + schema: + type: integer + - name: start_from + in: query + required: false + description: For filtering - beginning of start window - in seconds since epoch + schema: + type: integer + - name: start_to + in: query + required: false + description: For filtering - end of start window - in seconds since epoch + schema: + type: integer + - name: end_from + in: query + required: false + description: For filtering - beginning of end window - in seconds since epoch + schema: + type: integer + - name: end_to + in: query + required: false + description: For filtering - end of end window - in seconds since epoch + schema: + type: integer + - name: process_status + in: query + required: false + description: For filtering - not_started, user_input_required, waiting, complete, error, or suspended + schema: + type: string + - name: initiated_by_me + in: query + required: false + description: For filtering - show instances initiated by me + schema: + type: boolean + - name: with_tasks_completed_by_me + in: query + required: false + description: For filtering - show instances with tasks completed by me + schema: + type: boolean + - name: with_tasks_completed_by_my_group + in: query + required: false + description: For filtering - show instances with tasks completed by my group + schema: + type: boolean + - name: with_relation_to_me + in: query + required: false + description: For filtering - show instances that have something to do with me + schema: + type: boolean + - name: user_filter + in: query + required: false + description: For filtering - indicates the user has manually entered a query + schema: + type: boolean + - name: report_identifier + in: query + required: false + description: Specifies the identifier of a report to use, if any + schema: + type: string + - name: report_id + in: query + required: false + description: Specifies the identifier of a report to use, if any + schema: + type: integer + - name: group_identifier + in: query + required: false + description: The identifier of the group to get the process instances for + schema: + type: string + get: + operationId: spiffworkflow_backend.routes.process_api_blueprint.process_instance_list_for_me + summary: Returns a list of process instances that are associated with me. + tags: + - Process Instances + responses: + "200": + description: Workflow. + content: + application/json: + schema: + type: array + items: + $ref: "#/components/schemas/Workflow" + /process-instances: parameters: - name: process_model_identifier @@ -577,6 +690,12 @@ paths: description: For filtering - show instances with tasks completed by my group schema: type: boolean + - name: with_relation_to_me + in: query + required: false + description: For filtering - show instances that have something to do with me + schema: + type: boolean - name: user_filter in: query required: false @@ -603,7 +722,7 @@ paths: type: string get: operationId: spiffworkflow_backend.routes.process_api_blueprint.process_instance_list - summary: Returns a list of process instances for a given process model + summary: Returns a list of process instances. tags: - Process Instances responses: @@ -726,6 +845,39 @@ paths: items: $ref: "#/components/schemas/Task" + /process-instances/for-me/{modified_process_model_identifier}/{process_instance_id}: + parameters: + - name: modified_process_model_identifier + in: path + required: true + description: The unique id of an existing process model + schema: + type: string + - name: process_instance_id + in: path + required: true + description: The unique id of an existing process instance. + schema: + type: integer + - name: process_identifier + in: query + required: false + description: The identifier of the process to use for the diagram. Useful for displaying the diagram for a call activity. + schema: + type: string + get: + tags: + - Process Instances + operationId: spiffworkflow_backend.routes.process_api_blueprint.process_instance_show_for_me + summary: Show information about a process instance that is associated with me + responses: + "200": + description: One Process Instance + content: + application/json: + schema: + $ref: "#/components/schemas/Workflow" + /process-instances/{modified_process_model_identifier}/{process_instance_id}: parameters: - name: modified_process_model_identifier diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/config/permissions/development.yml b/spiffworkflow-backend/src/spiffworkflow_backend/config/permissions/development.yml index df2839f32..bbd4c46cd 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/config/permissions/development.yml +++ b/spiffworkflow-backend/src/spiffworkflow_backend/config/permissions/development.yml @@ -115,11 +115,11 @@ permissions: users: [] allowed_permissions: [read] uri: /v1.0/process-models/* - read-all-process-instance: + read-all-process-instance-for-me: groups: [everybody] users: [] allowed_permissions: [read] - uri: /v1.0/process-instances/* + uri: /v1.0/process-instances/for-me/* read-process-instance-reports: groups: [everybody] users: [] diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/load_database_models.py b/spiffworkflow-backend/src/spiffworkflow_backend/load_database_models.py index 71adb57c6..bc79a8e39 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/load_database_models.py +++ b/spiffworkflow-backend/src/spiffworkflow_backend/load_database_models.py @@ -17,7 +17,7 @@ from spiffworkflow_backend.models.user_group_assignment import ( from spiffworkflow_backend.models.principal import PrincipalModel # noqa: F401 -from spiffworkflow_backend.models.active_task import ActiveTaskModel # noqa: F401 +from spiffworkflow_backend.models.human_task import HumanTaskModel # noqa: F401 from spiffworkflow_backend.models.spec_reference import ( SpecReferenceCache, ) # noqa: F401 diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/models/active_task.py b/spiffworkflow-backend/src/spiffworkflow_backend/models/human_task.py similarity index 78% rename from spiffworkflow-backend/src/spiffworkflow_backend/models/active_task.py rename to spiffworkflow-backend/src/spiffworkflow_backend/models/human_task.py index ea9e10552..73936e493 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/models/active_task.py +++ b/spiffworkflow-backend/src/spiffworkflow_backend/models/human_task.py @@ -1,4 +1,4 @@ -"""Active_task.""" +"""human_task.""" from __future__ import annotations from dataclasses import dataclass @@ -17,20 +17,18 @@ from spiffworkflow_backend.models.user import UserModel if TYPE_CHECKING: - from spiffworkflow_backend.models.active_task_user import ( # noqa: F401 - ActiveTaskUserModel, + from spiffworkflow_backend.models.human_task_user import ( # noqa: F401 + HumanTaskUserModel, ) @dataclass -class ActiveTaskModel(SpiffworkflowBaseDBModel): - """ActiveTaskModel.""" +class HumanTaskModel(SpiffworkflowBaseDBModel): + """HumanTaskModel.""" - __tablename__ = "active_task" + __tablename__ = "human_task" __table_args__ = ( - db.UniqueConstraint( - "task_id", "process_instance_id", name="active_task_unique" - ), + db.UniqueConstraint("task_id", "process_instance_id", name="human_task_unique"), ) actual_owner: RelationshipProperty[UserModel] = relationship(UserModel) @@ -52,17 +50,18 @@ class ActiveTaskModel(SpiffworkflowBaseDBModel): task_type: str = db.Column(db.String(50)) task_status: str = db.Column(db.String(50)) process_model_display_name: str = db.Column(db.String(255)) + completed: bool = db.Column(db.Boolean, default=False, nullable=False, index=True) - active_task_users = relationship("ActiveTaskUserModel", cascade="delete") + human_task_users = relationship("HumanTaskUserModel", cascade="delete") potential_owners = relationship( # type: ignore "UserModel", viewonly=True, - secondary="active_task_user", - overlaps="active_task_user,users", + secondary="human_task_user", + overlaps="human_task_user,users", ) @classmethod - def to_task(cls, task: ActiveTaskModel) -> Task: + def to_task(cls, task: HumanTaskModel) -> Task: """To_task.""" new_task = Task( task.task_id, @@ -79,7 +78,7 @@ class ActiveTaskModel(SpiffworkflowBaseDBModel): if hasattr(task, "process_model_identifier"): new_task.process_model_identifier = task.process_model_identifier - # active tasks only have status when getting the list on the home page + # human tasks only have status when getting the list on the home page # and it comes from the process_instance. it should not be confused with task_status. if hasattr(task, "status"): new_task.process_instance_status = task.status diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/models/active_task_user.py b/spiffworkflow-backend/src/spiffworkflow_backend/models/human_task_user.py similarity index 55% rename from spiffworkflow-backend/src/spiffworkflow_backend/models/active_task_user.py rename to spiffworkflow-backend/src/spiffworkflow_backend/models/human_task_user.py index f194c38e4..9113ee8e5 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/models/active_task_user.py +++ b/spiffworkflow-backend/src/spiffworkflow_backend/models/human_task_user.py @@ -1,4 +1,4 @@ -"""Active_task_user.""" +"""human_task_user.""" from __future__ import annotations from dataclasses import dataclass @@ -7,26 +7,26 @@ from flask_bpmn.models.db import db from flask_bpmn.models.db import SpiffworkflowBaseDBModel from sqlalchemy import ForeignKey -from spiffworkflow_backend.models.active_task import ActiveTaskModel +from spiffworkflow_backend.models.human_task import HumanTaskModel from spiffworkflow_backend.models.user import UserModel @dataclass -class ActiveTaskUserModel(SpiffworkflowBaseDBModel): - """ActiveTaskUserModel.""" +class HumanTaskUserModel(SpiffworkflowBaseDBModel): + """HumanTaskUserModel.""" - __tablename__ = "active_task_user" + __tablename__ = "human_task_user" __table_args__ = ( db.UniqueConstraint( - "active_task_id", + "human_task_id", "user_id", - name="active_task_user_unique", + name="human_task_user_unique", ), ) id = db.Column(db.Integer, primary_key=True) - active_task_id = db.Column( - ForeignKey(ActiveTaskModel.id), nullable=False, index=True # type: ignore + human_task_id = db.Column( + ForeignKey(HumanTaskModel.id), nullable=False, index=True # type: ignore ) user_id = db.Column(ForeignKey(UserModel.id), nullable=False, index=True) diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/models/process_instance.py b/spiffworkflow-backend/src/spiffworkflow_backend/models/process_instance.py index 7af28170f..f41897fd7 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/models/process_instance.py +++ b/spiffworkflow-backend/src/spiffworkflow_backend/models/process_instance.py @@ -60,7 +60,11 @@ class ProcessInstanceModel(SpiffworkflowBaseDBModel): process_initiator_id: int = db.Column(ForeignKey(UserModel.id), nullable=False) process_initiator = relationship("UserModel") - active_tasks = relationship("ActiveTaskModel", cascade="delete") # type: ignore + human_tasks = relationship( + "HumanTaskModel", + cascade="delete", + primaryjoin="and_(HumanTaskModel.process_instance_id==ProcessInstanceModel.id, HumanTaskModel.completed == False)", + ) # type: ignore message_instances = relationship("MessageInstanceModel", cascade="delete") # type: ignore message_correlations = relationship("MessageCorrelationModel", cascade="delete") # type: ignore diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/routes/process_api_blueprint.py b/spiffworkflow-backend/src/spiffworkflow_backend/routes/process_api_blueprint.py index 349af266d..121404589 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/routes/process_api_blueprint.py +++ b/spiffworkflow-backend/src/spiffworkflow_backend/routes/process_api_blueprint.py @@ -33,16 +33,17 @@ from sqlalchemy import and_ from sqlalchemy import asc from sqlalchemy import desc from sqlalchemy import func +from sqlalchemy import or_ from sqlalchemy.orm import aliased from sqlalchemy.orm import selectinload from spiffworkflow_backend.exceptions.process_entity_not_found_error import ( ProcessEntityNotFoundError, ) -from spiffworkflow_backend.models.active_task import ActiveTaskModel -from spiffworkflow_backend.models.active_task_user import ActiveTaskUserModel from spiffworkflow_backend.models.file import FileSchema from spiffworkflow_backend.models.group import GroupModel +from spiffworkflow_backend.models.human_task import HumanTaskModel +from spiffworkflow_backend.models.human_task_user import HumanTaskUserModel from spiffworkflow_backend.models.message_correlation import MessageCorrelationModel from spiffworkflow_backend.models.message_instance import MessageInstanceModel from spiffworkflow_backend.models.message_model import MessageModel @@ -847,6 +848,38 @@ def message_start( ) +def process_instance_list_for_me( + process_model_identifier: Optional[str] = None, + page: int = 1, + per_page: int = 100, + start_from: Optional[int] = None, + start_to: Optional[int] = None, + end_from: Optional[int] = None, + end_to: Optional[int] = None, + process_status: Optional[str] = None, + user_filter: Optional[bool] = False, + report_identifier: Optional[str] = None, + report_id: Optional[int] = None, + group_identifier: Optional[str] = None, +) -> flask.wrappers.Response: + """Process_instance_list_for_me.""" + return process_instance_list( + process_model_identifier=process_model_identifier, + page=page, + per_page=per_page, + start_from=start_from, + start_to=start_to, + end_from=end_from, + end_to=end_to, + process_status=process_status, + user_filter=user_filter, + report_identifier=report_identifier, + report_id=report_id, + group_identifier=group_identifier, + with_relation_to_me=True, + ) + + def process_instance_list( process_model_identifier: Optional[str] = None, page: int = 1, @@ -859,6 +892,7 @@ def process_instance_list( initiated_by_me: Optional[bool] = None, with_tasks_completed_by_me: Optional[bool] = None, with_tasks_completed_by_my_group: Optional[bool] = None, + with_relation_to_me: Optional[bool] = None, user_filter: Optional[bool] = False, report_identifier: Optional[str] = None, report_id: Optional[int] = None, @@ -868,6 +902,7 @@ def process_instance_list( process_instance_report = ProcessInstanceReportService.report_with_identifier( g.user, report_id, report_identifier ) + print(f"with_relation_to_me: {with_relation_to_me}") if user_filter: report_filter = ProcessInstanceReportFilter( @@ -880,6 +915,7 @@ def process_instance_list( initiated_by_me, with_tasks_completed_by_me, with_tasks_completed_by_my_group, + with_relation_to_me, ) else: report_filter = ( @@ -894,6 +930,7 @@ def process_instance_list( initiated_by_me, with_tasks_completed_by_me, with_tasks_completed_by_my_group, + with_relation_to_me, ) ) @@ -946,6 +983,23 @@ def process_instance_list( ProcessInstanceModel.status.in_(report_filter.process_status) # type: ignore ) + if report_filter.with_relation_to_me is True: + process_instance_query = process_instance_query.outerjoin( + HumanTaskModel + ).outerjoin( + HumanTaskUserModel, + and_( + HumanTaskModel.id == HumanTaskUserModel.human_task_id, + HumanTaskUserModel.user_id == g.user.id, + ), + ) + process_instance_query = process_instance_query.filter( + or_( + HumanTaskUserModel.id.is_not(None), + ProcessInstanceModel.process_initiator_id == g.user.id, + ) + ) + if report_filter.initiated_by_me is True: process_instance_query = process_instance_query.filter( ProcessInstanceModel.status.in_(ProcessInstanceModel.terminal_statuses()) # type: ignore @@ -1120,14 +1174,68 @@ def process_instance_report_column_list() -> flask.wrappers.Response: return make_response(jsonify(table_columns + columns_for_metadata_strings), 200) +def process_instance_show_for_me( + modified_process_model_identifier: str, + process_instance_id: int, + process_identifier: Optional[str] = None, +) -> flask.wrappers.Response: + """Process_instance_show_for_me.""" + process_instance = ( + ProcessInstanceModel.query.filter_by(id=process_instance_id) + .outerjoin(HumanTaskModel) + .outerjoin( + HumanTaskUserModel, + and_( + HumanTaskModel.id == HumanTaskUserModel.human_task_id, + HumanTaskUserModel.user_id == g.user.id, + ), + ) + .filter( + or_( + HumanTaskUserModel.id.is_not(None), + ProcessInstanceModel.process_initiator_id == g.user.id, + ) + ) + .first() + ) + + if process_instance is None: + raise ( + ApiError( + error_code="process_instance_cannot_be_found", + message=f"Process instance with id {process_instance_id} cannot be found that is associated with you.", + status_code=400, + ) + ) + + return _get_process_instance( + process_instance=process_instance, + modified_process_model_identifier=modified_process_model_identifier, + process_identifier=process_identifier, + ) + + def process_instance_show( modified_process_model_identifier: str, process_instance_id: int, process_identifier: Optional[str] = None, ) -> flask.wrappers.Response: """Create_process_instance.""" - process_model_identifier = modified_process_model_identifier.replace(":", "/") process_instance = find_process_instance_by_id_or_raise(process_instance_id) + return _get_process_instance( + process_instance=process_instance, + modified_process_model_identifier=modified_process_model_identifier, + process_identifier=process_identifier, + ) + + +def _get_process_instance( + modified_process_model_identifier: str, + process_instance: ProcessInstanceModel, + process_identifier: Optional[str] = None, +) -> flask.wrappers.Response: + """_get_process_instance.""" + process_model_identifier = modified_process_model_identifier.replace(":", "/") current_version_control_revision = GitService.get_current_revision() process_model_with_diagram = None @@ -1335,35 +1443,36 @@ def process_instance_report_show( def task_list_my_tasks(page: int = 1, per_page: int = 100) -> flask.wrappers.Response: """Task_list_my_tasks.""" principal = find_principal_or_raise() - active_tasks = ( - ActiveTaskModel.query.order_by(desc(ActiveTaskModel.id)) # type: ignore + human_tasks = ( + HumanTaskModel.query.order_by(desc(HumanTaskModel.id)) # type: ignore .join(ProcessInstanceModel) - .join(ActiveTaskUserModel) + .join(HumanTaskUserModel) .filter_by(user_id=principal.user_id) + .filter(HumanTaskModel.completed == False) # noqa: E712 # just need this add_columns to add the process_model_identifier. Then add everything back that was removed. .add_columns( ProcessInstanceModel.process_model_identifier, ProcessInstanceModel.process_model_display_name, ProcessInstanceModel.status, - ActiveTaskModel.task_name, - ActiveTaskModel.task_title, - ActiveTaskModel.task_type, - ActiveTaskModel.task_status, - ActiveTaskModel.task_id, - ActiveTaskModel.id, - ActiveTaskModel.process_model_display_name, - ActiveTaskModel.process_instance_id, + HumanTaskModel.task_name, + HumanTaskModel.task_title, + HumanTaskModel.task_type, + HumanTaskModel.task_status, + HumanTaskModel.task_id, + HumanTaskModel.id, + HumanTaskModel.process_model_display_name, + HumanTaskModel.process_instance_id, ) .paginate(page=page, per_page=per_page, error_out=False) ) - tasks = [ActiveTaskModel.to_task(active_task) for active_task in active_tasks.items] + tasks = [HumanTaskModel.to_task(human_task) for human_task in human_tasks.items] response_json = { "results": tasks, "pagination": { - "count": len(active_tasks.items), - "total": active_tasks.total, - "pages": active_tasks.pages, + "count": len(human_tasks.items), + "total": human_tasks.total, + "pages": human_tasks.pages, }, } @@ -1417,69 +1526,74 @@ def get_tasks( """Get_tasks.""" user_id = g.user.id - # use distinct to ensure we only get one row per active task otherwise - # we can get back multiple for the same active task row which throws off + # use distinct to ensure we only get one row per human task otherwise + # we can get back multiple for the same human task row which throws off # pagination later on # https://stackoverflow.com/q/34582014/6090676 - active_tasks_query = ( - ActiveTaskModel.query.distinct() - .outerjoin(GroupModel, GroupModel.id == ActiveTaskModel.lane_assignment_id) + human_tasks_query = ( + HumanTaskModel.query.distinct() + .outerjoin(GroupModel, GroupModel.id == HumanTaskModel.lane_assignment_id) .join(ProcessInstanceModel) .join(UserModel, UserModel.id == ProcessInstanceModel.process_initiator_id) + .filter(HumanTaskModel.completed == False) # noqa: E712 ) if processes_started_by_user: - active_tasks_query = active_tasks_query.filter( + human_tasks_query = human_tasks_query.filter( ProcessInstanceModel.process_initiator_id == user_id ).outerjoin( - ActiveTaskUserModel, + HumanTaskUserModel, and_( - ActiveTaskUserModel.user_id == user_id, - ActiveTaskModel.id == ActiveTaskUserModel.active_task_id, + HumanTaskUserModel.user_id == user_id, + HumanTaskModel.id == HumanTaskUserModel.human_task_id, ), ) else: - active_tasks_query = active_tasks_query.filter( + human_tasks_query = human_tasks_query.filter( ProcessInstanceModel.process_initiator_id != user_id ).join( - ActiveTaskUserModel, + HumanTaskUserModel, and_( - ActiveTaskUserModel.user_id == user_id, - ActiveTaskModel.id == ActiveTaskUserModel.active_task_id, + HumanTaskUserModel.user_id == user_id, + HumanTaskModel.id == HumanTaskUserModel.human_task_id, ), ) if has_lane_assignment_id: if group_identifier: - active_tasks_query = active_tasks_query.filter( + human_tasks_query = human_tasks_query.filter( GroupModel.identifier == group_identifier ) else: - active_tasks_query = active_tasks_query.filter( - ActiveTaskModel.lane_assignment_id.is_not(None) # type: ignore + human_tasks_query = human_tasks_query.filter( + HumanTaskModel.lane_assignment_id.is_not(None) # type: ignore ) else: - active_tasks_query = active_tasks_query.filter(ActiveTaskModel.lane_assignment_id.is_(None)) # type: ignore + human_tasks_query = human_tasks_query.filter(HumanTaskModel.lane_assignment_id.is_(None)) # type: ignore - active_tasks = active_tasks_query.add_columns( - ProcessInstanceModel.process_model_identifier, - ProcessInstanceModel.status.label("process_instance_status"), # type: ignore - ProcessInstanceModel.updated_at_in_seconds, - ProcessInstanceModel.created_at_in_seconds, - UserModel.username, - GroupModel.identifier.label("group_identifier"), - ActiveTaskModel.task_name, - ActiveTaskModel.task_title, - ActiveTaskModel.process_model_display_name, - ActiveTaskModel.process_instance_id, - ActiveTaskUserModel.user_id.label("current_user_is_potential_owner"), - ).paginate(page=page, per_page=per_page, error_out=False) + human_tasks = ( + human_tasks_query.add_columns( + ProcessInstanceModel.process_model_identifier, + ProcessInstanceModel.status.label("process_instance_status"), # type: ignore + ProcessInstanceModel.updated_at_in_seconds, + ProcessInstanceModel.created_at_in_seconds, + UserModel.username, + GroupModel.identifier.label("group_identifier"), + HumanTaskModel.task_name, + HumanTaskModel.task_title, + HumanTaskModel.process_model_display_name, + HumanTaskModel.process_instance_id, + HumanTaskUserModel.user_id.label("current_user_is_potential_owner"), + ) + .order_by(desc(HumanTaskModel.id)) # type: ignore + .paginate(page=page, per_page=per_page, error_out=False) + ) response_json = { - "results": active_tasks.items, + "results": human_tasks.items, "pagination": { - "count": len(active_tasks.items), - "total": active_tasks.total, - "pages": active_tasks.pages, + "count": len(human_tasks.items), + "total": human_tasks.total, + "pages": human_tasks.pages, }, } return make_response(jsonify(response_json), 200) @@ -1698,14 +1812,14 @@ def task_submit( if terminate_loop and spiff_task.is_looping(): spiff_task.terminate_loop() - active_task = ActiveTaskModel.query.filter_by( - process_instance_id=process_instance_id, task_id=task_id + human_task = HumanTaskModel.query.filter_by( + process_instance_id=process_instance_id, task_id=task_id, completed=False ).first() - if active_task is None: + if human_task is None: raise ( ApiError( - error_code="no_active_task", - message="Cannot find an active task with task id '{task_id}' for process instance {process_instance_id}.", + error_code="no_human_task", + message="Cannot find an human task with task id '{task_id}' for process instance {process_instance_id}.", status_code=500, ) ) @@ -1715,7 +1829,7 @@ def task_submit( spiff_task=spiff_task, data=body, user=g.user, - active_task=active_task, + human_task=human_task, ) # If we need to update all tasks, then get the next ready task and if it a multi-instance with the same @@ -1728,16 +1842,18 @@ def task_submit( # last_index = next_task.task_info()["mi_index"] # next_task = processor.next_task() - next_active_task_assigned_to_me = ( - ActiveTaskModel.query.filter_by(process_instance_id=process_instance_id) - .order_by(asc(ActiveTaskModel.id)) # type: ignore - .join(ActiveTaskUserModel) + next_human_task_assigned_to_me = ( + HumanTaskModel.query.filter_by( + process_instance_id=process_instance_id, completed=False + ) + .order_by(asc(HumanTaskModel.id)) # type: ignore + .join(HumanTaskUserModel) .filter_by(user_id=principal.user_id) .first() ) - if next_active_task_assigned_to_me: + if next_human_task_assigned_to_me: return make_response( - jsonify(ActiveTaskModel.to_task(next_active_task_assigned_to_me)), 200 + jsonify(HumanTaskModel.to_task(next_human_task_assigned_to_me)), 200 ) return Response(json.dumps({"ok": True}), status=202, mimetype="application/json") diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/services/authorization_service.py b/spiffworkflow-backend/src/spiffworkflow_backend/services/authorization_service.py index 9456f8f14..a2f41ac10 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/services/authorization_service.py +++ b/spiffworkflow-backend/src/spiffworkflow_backend/services/authorization_service.py @@ -19,8 +19,8 @@ from SpiffWorkflow.task import Task as SpiffTask # type: ignore from sqlalchemy import or_ from sqlalchemy import text -from spiffworkflow_backend.models.active_task import ActiveTaskModel from spiffworkflow_backend.models.group import GroupModel +from spiffworkflow_backend.models.human_task import HumanTaskModel from spiffworkflow_backend.models.permission_assignment import PermissionAssignmentModel from spiffworkflow_backend.models.permission_target import PermissionTargetModel from spiffworkflow_backend.models.principal import MissingPrincipalError @@ -37,8 +37,8 @@ class PermissionsFileNotSetError(Exception): """PermissionsFileNotSetError.""" -class ActiveTaskNotFoundError(Exception): - """ActiveTaskNotFoundError.""" +class HumanTaskNotFoundError(Exception): + """HumanTaskNotFoundError.""" class UserDoesNotHaveAccessToTaskError(Exception): @@ -429,17 +429,17 @@ class AuthorizationService: user: UserModel, ) -> bool: """Assert_user_can_complete_spiff_task.""" - active_task = ActiveTaskModel.query.filter_by( + human_task = HumanTaskModel.query.filter_by( task_name=spiff_task.task_spec.name, process_instance_id=process_instance_id, ).first() - if active_task is None: - raise ActiveTaskNotFoundError( - f"Could find an active task with task name '{spiff_task.task_spec.name}'" + if human_task is None: + raise HumanTaskNotFoundError( + f"Could find an human task with task name '{spiff_task.task_spec.name}'" f" for process instance '{process_instance_id}'" ) - if user not in active_task.potential_owners: + if user not in human_task.potential_owners: raise UserDoesNotHaveAccessToTaskError( f"User {user.username} does not have access to update task'{spiff_task.task_spec.name}'" f" for process instance '{process_instance_id}'" @@ -485,7 +485,7 @@ class AuthorizationService: cls.import_permissions_from_yaml_file() if is_new_user: - UserService.add_user_to_active_tasks_if_appropriate(user_model) + UserService.add_user_to_human_tasks_if_appropriate(user_model) # this cannot be None so ignore mypy return user_model # type: ignore diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_processor.py b/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_processor.py index 5edc526cf..c06f49a30 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_processor.py +++ b/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_processor.py @@ -65,11 +65,11 @@ from SpiffWorkflow.task import Task as SpiffTask # type: ignore from SpiffWorkflow.task import TaskState from SpiffWorkflow.util.deep_merge import DeepMerge # type: ignore -from spiffworkflow_backend.models.active_task import ActiveTaskModel -from spiffworkflow_backend.models.active_task_user import ActiveTaskUserModel from spiffworkflow_backend.models.file import File from spiffworkflow_backend.models.file import FileType from spiffworkflow_backend.models.group import GroupModel +from spiffworkflow_backend.models.human_task import HumanTaskModel +from spiffworkflow_backend.models.human_task_user import HumanTaskUserModel from spiffworkflow_backend.models.message_correlation import MessageCorrelationModel from spiffworkflow_backend.models.message_correlation_message_instance import ( MessageCorrelationMessageInstanceModel, @@ -573,10 +573,10 @@ class ProcessInstanceProcessor: ) return details_model - def save_spiff_step_details(self, active_task: ActiveTaskModel) -> None: + def save_spiff_step_details(self, human_task: HumanTaskModel) -> None: """SaveSpiffStepDetails.""" details_model = self.spiff_step_details() - details_model.lane_assignment_id = active_task.lane_assignment_id + details_model.lane_assignment_id = human_task.lane_assignment_id db.session.add(details_model) db.session.commit() @@ -637,7 +637,7 @@ class ProcessInstanceProcessor: db.session.add(self.process_instance_model) db.session.commit() - active_tasks = ActiveTaskModel.query.filter_by( + human_tasks = HumanTaskModel.query.filter_by( process_instance_id=self.process_instance_model.id ).all() ready_or_waiting_tasks = self.get_all_ready_or_waiting_tasks() @@ -668,14 +668,14 @@ class ProcessInstanceProcessor: if "formUiSchemaFilename" in properties: ui_form_file_name = properties["formUiSchemaFilename"] - active_task = None - for at in active_tasks: + human_task = None + for at in human_tasks: if at.task_id == str(ready_or_waiting_task.id): - active_task = at - active_tasks.remove(at) + human_task = at + human_tasks.remove(at) - if active_task is None: - active_task = ActiveTaskModel( + if human_task is None: + human_task = HumanTaskModel( process_instance_id=self.process_instance_model.id, process_model_display_name=process_model_display_name, form_file_name=form_file_name, @@ -687,21 +687,22 @@ class ProcessInstanceProcessor: task_status=ready_or_waiting_task.get_state_name(), lane_assignment_id=potential_owner_hash["lane_assignment_id"], ) - db.session.add(active_task) + db.session.add(human_task) db.session.commit() for potential_owner_id in potential_owner_hash[ "potential_owner_ids" ]: - active_task_user = ActiveTaskUserModel( - user_id=potential_owner_id, active_task_id=active_task.id + human_task_user = HumanTaskUserModel( + user_id=potential_owner_id, human_task_id=human_task.id ) - db.session.add(active_task_user) + db.session.add(human_task_user) db.session.commit() - if len(active_tasks) > 0: - for at in active_tasks: - db.session.delete(at) + if len(human_tasks) > 0: + for at in human_tasks: + at.completed = True + db.session.add(at) db.session.commit() @staticmethod @@ -1179,11 +1180,11 @@ class ProcessInstanceProcessor: ) return user_tasks # type: ignore - def complete_task(self, task: SpiffTask, active_task: ActiveTaskModel) -> None: + def complete_task(self, task: SpiffTask, human_task: HumanTaskModel) -> None: """Complete_task.""" self.increment_spiff_step() self.bpmn_process_instance.complete_task_from_id(task.id) - self.save_spiff_step_details(active_task) + self.save_spiff_step_details(human_task) def get_data(self) -> dict[str, Any]: """Get_data.""" diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_report_service.py b/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_report_service.py index 84d5d6752..e0595f3fe 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_report_service.py +++ b/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_report_service.py @@ -24,6 +24,7 @@ class ProcessInstanceReportFilter: initiated_by_me: Optional[bool] = None with_tasks_completed_by_me: Optional[bool] = None with_tasks_completed_by_my_group: Optional[bool] = None + with_relation_to_me: Optional[bool] = None def to_dict(self) -> dict[str, str]: """To_dict.""" @@ -51,6 +52,8 @@ class ProcessInstanceReportFilter: d["with_tasks_completed_by_my_group"] = str( self.with_tasks_completed_by_my_group ).lower() + if self.with_relation_to_me is not None: + d["with_relation_to_me"] = str(self.with_relation_to_me).lower() return d @@ -174,6 +177,7 @@ class ProcessInstanceReportService: with_tasks_completed_by_my_group = bool_value( "with_tasks_completed_by_my_group" ) + with_relation_to_me = bool_value("with_relation_to_me") report_filter = ProcessInstanceReportFilter( process_model_identifier, @@ -185,6 +189,7 @@ class ProcessInstanceReportService: initiated_by_me, with_tasks_completed_by_me, with_tasks_completed_by_my_group, + with_relation_to_me, ) return report_filter @@ -202,6 +207,7 @@ class ProcessInstanceReportService: initiated_by_me: Optional[bool] = None, with_tasks_completed_by_me: Optional[bool] = None, with_tasks_completed_by_my_group: Optional[bool] = None, + with_relation_to_me: Optional[bool] = None, ) -> ProcessInstanceReportFilter: """Filter_from_metadata_with_overrides.""" report_filter = cls.filter_from_metadata(process_instance_report) @@ -226,6 +232,8 @@ class ProcessInstanceReportService: report_filter.with_tasks_completed_by_my_group = ( with_tasks_completed_by_my_group ) + if with_relation_to_me is not None: + report_filter.with_relation_to_me = with_relation_to_me return report_filter diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_service.py b/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_service.py index 5b2781a20..7eee445a5 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_service.py +++ b/spiffworkflow-backend/src/spiffworkflow_backend/services/process_instance_service.py @@ -8,7 +8,7 @@ from flask_bpmn.api.api_error import ApiError from flask_bpmn.models.db import db from SpiffWorkflow.task import Task as SpiffTask # type: ignore -from spiffworkflow_backend.models.active_task import ActiveTaskModel +from spiffworkflow_backend.models.human_task import HumanTaskModel from spiffworkflow_backend.models.process_instance import ProcessInstanceApi from spiffworkflow_backend.models.process_instance import ProcessInstanceModel from spiffworkflow_backend.models.process_instance import ProcessInstanceStatus @@ -196,7 +196,7 @@ class ProcessInstanceService: spiff_task: SpiffTask, data: dict[str, Any], user: UserModel, - active_task: ActiveTaskModel, + human_task: HumanTaskModel, ) -> None: """All the things that need to happen when we complete a form. @@ -210,7 +210,7 @@ class ProcessInstanceService: dot_dct = ProcessInstanceService.create_dot_dict(data) spiff_task.update_data(dot_dct) # ProcessInstanceService.post_process_form(spiff_task) # some properties may update the data store. - processor.complete_task(spiff_task, active_task) + processor.complete_task(spiff_task, human_task) processor.do_engine_steps(save=True) @staticmethod diff --git a/spiffworkflow-backend/src/spiffworkflow_backend/services/user_service.py b/spiffworkflow-backend/src/spiffworkflow_backend/services/user_service.py index 0e8e65c2c..0e6cf1cbe 100644 --- a/spiffworkflow-backend/src/spiffworkflow_backend/services/user_service.py +++ b/spiffworkflow-backend/src/spiffworkflow_backend/services/user_service.py @@ -7,9 +7,9 @@ from flask import g from flask_bpmn.api.api_error import ApiError from flask_bpmn.models.db import db -from spiffworkflow_backend.models.active_task import ActiveTaskModel -from spiffworkflow_backend.models.active_task_user import ActiveTaskUserModel from spiffworkflow_backend.models.group import GroupModel +from spiffworkflow_backend.models.human_task import HumanTaskModel +from spiffworkflow_backend.models.human_task_user import HumanTaskUserModel from spiffworkflow_backend.models.principal import PrincipalModel from spiffworkflow_backend.models.user import UserModel from spiffworkflow_backend.models.user_group_assignment import UserGroupAssignmentModel @@ -192,15 +192,15 @@ class UserService: return None @classmethod - def add_user_to_active_tasks_if_appropriate(cls, user: UserModel) -> None: - """Add_user_to_active_tasks_if_appropriate.""" + def add_user_to_human_tasks_if_appropriate(cls, user: UserModel) -> None: + """Add_user_to_human_tasks_if_appropriate.""" group_ids = [g.id for g in user.groups] - active_tasks = ActiveTaskModel.query.filter( - ActiveTaskModel.lane_assignment_id.in_(group_ids) # type: ignore + human_tasks = HumanTaskModel.query.filter( + HumanTaskModel.lane_assignment_id.in_(group_ids) # type: ignore ).all() - for active_task in active_tasks: - active_task_user = ActiveTaskUserModel( - user_id=user.id, active_task_id=active_task.id + for human_task in human_tasks: + human_task_user = HumanTaskUserModel( + user_id=user.id, human_task_id=human_task.id ) - db.session.add(active_task_user) + db.session.add(human_task_user) db.session.commit() diff --git a/spiffworkflow-backend/tests/spiffworkflow_backend/integration/test_process_api.py b/spiffworkflow-backend/tests/spiffworkflow_backend/integration/test_process_api.py index 1071ee259..9c763b58c 100644 --- a/spiffworkflow-backend/tests/spiffworkflow_backend/integration/test_process_api.py +++ b/spiffworkflow-backend/tests/spiffworkflow_backend/integration/test_process_api.py @@ -15,8 +15,8 @@ from tests.spiffworkflow_backend.helpers.test_data import load_test_spec from spiffworkflow_backend.exceptions.process_entity_not_found_error import ( ProcessEntityNotFoundError, ) -from spiffworkflow_backend.models.active_task import ActiveTaskModel from spiffworkflow_backend.models.group import GroupModel +from spiffworkflow_backend.models.human_task import HumanTaskModel from spiffworkflow_backend.models.process_group import ProcessGroup from spiffworkflow_backend.models.process_instance import ProcessInstanceModel from spiffworkflow_backend.models.process_instance import ProcessInstanceStatus @@ -1462,15 +1462,15 @@ class TestProcessApi(BaseTest): assert response.json is not None assert response.json["next_task"] is not None - active_tasks = ( - db.session.query(ActiveTaskModel) - .filter(ActiveTaskModel.process_instance_id == process_instance_id) + human_tasks = ( + db.session.query(HumanTaskModel) + .filter(HumanTaskModel.process_instance_id == process_instance_id) .all() ) - assert len(active_tasks) == 1 - active_task = active_tasks[0] + assert len(human_tasks) == 1 + human_task = human_tasks[0] response = client.get( - f"/v1.0/tasks/{process_instance_id}/{active_task.task_id}", + f"/v1.0/tasks/{process_instance_id}/{human_task.task_id}", headers=self.logged_in_headers(with_super_admin_user), ) assert response.json is not None diff --git a/spiffworkflow-backend/tests/spiffworkflow_backend/scripts/test_get_localtime.py b/spiffworkflow-backend/tests/spiffworkflow_backend/scripts/test_get_localtime.py index f1834ab3a..8f3864fe8 100644 --- a/spiffworkflow-backend/tests/spiffworkflow_backend/scripts/test_get_localtime.py +++ b/spiffworkflow-backend/tests/spiffworkflow_backend/scripts/test_get_localtime.py @@ -68,9 +68,9 @@ class TestGetLocaltime(BaseTest): processor = ProcessInstanceProcessor(process_instance) processor.do_engine_steps(save=True) - active_task = process_instance.active_tasks[0] + human_task = process_instance.human_tasks[0] spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) ProcessInstanceService.complete_form_task( @@ -78,12 +78,12 @@ class TestGetLocaltime(BaseTest): spiff_task, {"timezone": "US/Pacific"}, initiator_user, - active_task, + human_task, ) - active_task = process_instance.active_tasks[0] + human_task = process_instance.human_tasks[0] spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) assert spiff_task diff --git a/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_authorization_service.py b/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_authorization_service.py index 00622a1f7..05375754d 100644 --- a/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_authorization_service.py +++ b/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_authorization_service.py @@ -90,14 +90,14 @@ class TestAuthorizationService(BaseTest): users["testuser2"], "read", "/v1.0/process-groups/" ) - def test_user_can_be_added_to_active_task_on_first_login( + def test_user_can_be_added_to_human_task_on_first_login( self, app: Flask, client: FlaskClient, with_db_and_bpmn_file_cleanup: None, with_super_admin_user: UserModel, ) -> None: - """Test_user_can_be_added_to_active_task_on_first_login.""" + """Test_user_can_be_added_to_human_task_on_first_login.""" initiator_user = self.find_or_create_user("initiator_user") assert initiator_user.principal is not None # to ensure there is a user that can be assigned to the task @@ -121,21 +121,21 @@ class TestAuthorizationService(BaseTest): ) processor = ProcessInstanceProcessor(process_instance) processor.do_engine_steps(save=True) - active_task = process_instance.active_tasks[0] + human_task = process_instance.human_tasks[0] spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, initiator_user, active_task + processor, spiff_task, {}, initiator_user, human_task ) - active_task = process_instance.active_tasks[0] + human_task = process_instance.human_tasks[0] spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) finance_user = AuthorizationService.create_user_from_sign_in( {"username": "testuser2", "sub": "open_id"} ) ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, finance_user, active_task + processor, spiff_task, {}, finance_user, human_task ) diff --git a/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_dot_notation.py b/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_dot_notation.py index 80b052544..c84ec470c 100644 --- a/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_dot_notation.py +++ b/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_dot_notation.py @@ -47,7 +47,7 @@ class TestDotNotation(BaseTest): processor = ProcessInstanceProcessor(process_instance) processor.do_engine_steps(save=True) - active_task = process_instance.active_tasks[0] + human_task = process_instance.human_tasks[0] user_task = processor.get_ready_user_tasks()[0] form_data = { @@ -58,7 +58,7 @@ class TestDotNotation(BaseTest): "invoice.dueDate": "09/30/2022", } ProcessInstanceService.complete_form_task( - processor, user_task, form_data, with_super_admin_user, active_task + processor, user_task, form_data, with_super_admin_user, human_task ) expected = { diff --git a/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_process_instance_processor.py b/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_process_instance_processor.py index 3e0107957..100651ef5 100644 --- a/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_process_instance_processor.py +++ b/spiffworkflow-backend/tests/spiffworkflow_backend/unit/test_process_instance_processor.py @@ -49,14 +49,14 @@ class TestProcessInstanceProcessor(BaseTest): == "Chuck Norris doesn’t read books. He stares them down until he gets the information he wants." ) - def test_sets_permission_correctly_on_active_task( + def test_sets_permission_correctly_on_human_task( self, app: Flask, client: FlaskClient, with_db_and_bpmn_file_cleanup: None, with_super_admin_user: UserModel, ) -> None: - """Test_sets_permission_correctly_on_active_task.""" + """Test_sets_permission_correctly_on_human_task.""" self.create_process_group( client, with_super_admin_user, "test_group", "test_group" ) @@ -80,63 +80,63 @@ class TestProcessInstanceProcessor(BaseTest): processor = ProcessInstanceProcessor(process_instance) processor.do_engine_steps(save=True) - assert len(process_instance.active_tasks) == 1 - active_task = process_instance.active_tasks[0] - assert active_task.lane_assignment_id is None - assert len(active_task.potential_owners) == 1 - assert active_task.potential_owners[0] == initiator_user + assert len(process_instance.human_tasks) == 1 + human_task = process_instance.human_tasks[0] + assert human_task.lane_assignment_id is None + assert len(human_task.potential_owners) == 1 + assert human_task.potential_owners[0] == initiator_user spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) with pytest.raises(UserDoesNotHaveAccessToTaskError): ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, finance_user, active_task + processor, spiff_task, {}, finance_user, human_task ) ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, initiator_user, active_task + processor, spiff_task, {}, initiator_user, human_task ) - assert len(process_instance.active_tasks) == 1 - active_task = process_instance.active_tasks[0] - assert active_task.lane_assignment_id == finance_group.id - assert len(active_task.potential_owners) == 1 - assert active_task.potential_owners[0] == finance_user + assert len(process_instance.human_tasks) == 1 + human_task = process_instance.human_tasks[0] + assert human_task.lane_assignment_id == finance_group.id + assert len(human_task.potential_owners) == 1 + assert human_task.potential_owners[0] == finance_user spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) with pytest.raises(UserDoesNotHaveAccessToTaskError): ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, initiator_user, active_task + processor, spiff_task, {}, initiator_user, human_task ) ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, finance_user, active_task + processor, spiff_task, {}, finance_user, human_task ) - assert len(process_instance.active_tasks) == 1 - active_task = process_instance.active_tasks[0] - assert active_task.lane_assignment_id is None - assert len(active_task.potential_owners) == 1 - assert active_task.potential_owners[0] == initiator_user + assert len(process_instance.human_tasks) == 1 + human_task = process_instance.human_tasks[0] + assert human_task.lane_assignment_id is None + assert len(human_task.potential_owners) == 1 + assert human_task.potential_owners[0] == initiator_user spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, initiator_user, active_task + processor, spiff_task, {}, initiator_user, human_task ) assert process_instance.status == ProcessInstanceStatus.complete.value - def test_sets_permission_correctly_on_active_task_when_using_dict( + def test_sets_permission_correctly_on_human_task_when_using_dict( self, app: Flask, client: FlaskClient, with_db_and_bpmn_file_cleanup: None, with_super_admin_user: UserModel, ) -> None: - """Test_sets_permission_correctly_on_active_task_when_using_dict.""" + """Test_sets_permission_correctly_on_human_task_when_using_dict.""" self.create_process_group( client, with_super_admin_user, "test_group", "test_group" ) @@ -163,94 +163,94 @@ class TestProcessInstanceProcessor(BaseTest): processor.do_engine_steps(save=True) processor.save() - assert len(process_instance.active_tasks) == 1 - active_task = process_instance.active_tasks[0] - assert active_task.lane_assignment_id is None - assert len(active_task.potential_owners) == 1 - assert active_task.potential_owners[0] == initiator_user + assert len(process_instance.human_tasks) == 1 + human_task = process_instance.human_tasks[0] + assert human_task.lane_assignment_id is None + assert len(human_task.potential_owners) == 1 + assert human_task.potential_owners[0] == initiator_user spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) with pytest.raises(UserDoesNotHaveAccessToTaskError): ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, finance_user_three, active_task + processor, spiff_task, {}, finance_user_three, human_task ) ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, initiator_user, active_task + processor, spiff_task, {}, initiator_user, human_task ) - assert len(process_instance.active_tasks) == 1 - active_task = process_instance.active_tasks[0] - assert active_task.lane_assignment_id is None - assert len(active_task.potential_owners) == 2 - assert active_task.potential_owners == [finance_user_three, finance_user_four] + assert len(process_instance.human_tasks) == 1 + human_task = process_instance.human_tasks[0] + assert human_task.lane_assignment_id is None + assert len(human_task.potential_owners) == 2 + assert human_task.potential_owners == [finance_user_three, finance_user_four] spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) with pytest.raises(UserDoesNotHaveAccessToTaskError): ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, initiator_user, active_task + processor, spiff_task, {}, initiator_user, human_task ) g.user = finance_user_three ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, finance_user_three, active_task + processor, spiff_task, {}, finance_user_three, human_task ) - assert len(process_instance.active_tasks) == 1 - active_task = process_instance.active_tasks[0] - assert active_task.lane_assignment_id is None - assert len(active_task.potential_owners) == 1 - assert active_task.potential_owners[0] == finance_user_four + assert len(process_instance.human_tasks) == 1 + human_task = process_instance.human_tasks[0] + assert human_task.lane_assignment_id is None + assert len(human_task.potential_owners) == 1 + assert human_task.potential_owners[0] == finance_user_four spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) with pytest.raises(UserDoesNotHaveAccessToTaskError): ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, initiator_user, active_task + processor, spiff_task, {}, initiator_user, human_task ) ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, finance_user_four, active_task + processor, spiff_task, {}, finance_user_four, human_task ) - assert len(process_instance.active_tasks) == 1 - active_task = process_instance.active_tasks[0] - assert active_task.lane_assignment_id is None - assert len(active_task.potential_owners) == 1 - assert active_task.potential_owners[0] == initiator_user + assert len(process_instance.human_tasks) == 1 + human_task = process_instance.human_tasks[0] + assert human_task.lane_assignment_id is None + assert len(human_task.potential_owners) == 1 + assert human_task.potential_owners[0] == initiator_user spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, initiator_user, active_task + processor, spiff_task, {}, initiator_user, human_task ) - assert len(process_instance.active_tasks) == 1 - active_task = process_instance.active_tasks[0] + assert len(process_instance.human_tasks) == 1 + human_task = process_instance.human_tasks[0] spiff_task = processor.__class__.get_task_by_bpmn_identifier( - active_task.task_name, processor.bpmn_process_instance + human_task.task_name, processor.bpmn_process_instance ) with pytest.raises(UserDoesNotHaveAccessToTaskError): ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, initiator_user, active_task + processor, spiff_task, {}, initiator_user, human_task ) ProcessInstanceService.complete_form_task( - processor, spiff_task, {}, testadmin1, active_task + processor, spiff_task, {}, testadmin1, human_task ) assert process_instance.status == ProcessInstanceStatus.complete.value - def test_does_not_recreate_active_tasks_on_multiple_saves( + def test_does_not_recreate_human_tasks_on_multiple_saves( self, app: Flask, client: FlaskClient, with_db_and_bpmn_file_cleanup: None, with_super_admin_user: UserModel, ) -> None: - """Test_sets_permission_correctly_on_active_task_when_using_dict.""" + """Test_sets_permission_correctly_on_human_task_when_using_dict.""" self.create_process_group( client, with_super_admin_user, "test_group", "test_group" ) @@ -273,11 +273,11 @@ class TestProcessInstanceProcessor(BaseTest): ) processor = ProcessInstanceProcessor(process_instance) processor.do_engine_steps(save=True) - assert len(process_instance.active_tasks) == 1 - initial_active_task_id = process_instance.active_tasks[0].id + assert len(process_instance.human_tasks) == 1 + initial_human_task_id = process_instance.human_tasks[0].id - # save again to ensure we go attempt to process the active tasks again + # save again to ensure we go attempt to process the human tasks again processor.save() - assert len(process_instance.active_tasks) == 1 - assert initial_active_task_id == process_instance.active_tasks[0].id + assert len(process_instance.human_tasks) == 1 + assert initial_human_task_id == process_instance.human_tasks[0].id diff --git a/spiffworkflow-frontend/src/components/ProcessInstanceListTable.tsx b/spiffworkflow-frontend/src/components/ProcessInstanceListTable.tsx index 06f7793c4..92cec2050 100644 --- a/spiffworkflow-frontend/src/components/ProcessInstanceListTable.tsx +++ b/spiffworkflow-frontend/src/components/ProcessInstanceListTable.tsx @@ -70,6 +70,7 @@ const REFRESH_INTERVAL = 5; const REFRESH_TIMEOUT = 600; type OwnProps = { + apiPath?: string; filtersEnabled?: boolean; processModelFullIdentifier?: string; paginationQueryParamPrefix?: string; @@ -80,6 +81,7 @@ type OwnProps = { paginationClassName?: string; autoReload?: boolean; additionalParams?: string; + variant?: string; }; interface dateParameters { @@ -87,6 +89,7 @@ interface dateParameters { } export default function ProcessInstanceListTable({ + apiPath = '/process-instances', filtersEnabled = true, processModelFullIdentifier, paginationQueryParamPrefix, @@ -97,6 +100,7 @@ export default function ProcessInstanceListTable({ textToShowIfEmpty, paginationClassName, autoReload = false, + variant = 'for-me', }: OwnProps) { const params = useParams(); const [searchParams] = useSearchParams(); @@ -126,6 +130,11 @@ export default function ProcessInstanceListTable({ const setErrorMessage = (useContext as any)(ErrorContext)[1]; + const processInstancePathPrefix = + variant === 'all' + ? '/admin/process-instances' + : '/admin/process-instances/for-me'; + const [processStatusAllOptions, setProcessStatusAllOptions] = useState( [] ); @@ -260,7 +269,7 @@ export default function ProcessInstanceListTable({ } HttpService.makeCallToBackend({ - path: `/process-instances?${queryParamString}`, + path: `${apiPath}?${queryParamString}`, successCallback: setProcessInstancesFromResult, }); } @@ -516,7 +525,7 @@ export default function ProcessInstanceListTable({ setErrorMessage(null); setProcessInstanceReportJustSaved(null); - navigate(`/admin/process-instances?${queryParamString}`); + navigate(`${processInstancePathPrefix}?${queryParamString}`); }; const dateComponent = ( @@ -615,7 +624,7 @@ export default function ProcessInstanceListTable({ setErrorMessage(null); setProcessInstanceReportJustSaved(mode || null); - navigate(`/admin/process-instances${queryParamString}`); + navigate(`${processInstancePathPrefix}${queryParamString}`); }; const reportColumns = () => { @@ -1081,7 +1090,7 @@ export default function ProcessInstanceListTable({ return ( {id} diff --git a/spiffworkflow-frontend/src/hooks/UriListForPermissions.tsx b/spiffworkflow-frontend/src/hooks/UriListForPermissions.tsx index a9895c71c..46be60d54 100644 --- a/spiffworkflow-frontend/src/hooks/UriListForPermissions.tsx +++ b/spiffworkflow-frontend/src/hooks/UriListForPermissions.tsx @@ -9,16 +9,16 @@ export const useUriListForPermissions = () => { messageInstanceListPath: '/v1.0/messages', processGroupListPath: '/v1.0/process-groups', processGroupShowPath: `/v1.0/process-groups/${params.process_group_id}`, - processInstanceCreatePath: `/v1.0/process-instances/${params.process_model_id}`, processInstanceActionPath: `/v1.0/process-instances/${params.process_model_id}/${params.process_instance_id}`, - processInstanceResumePath: `/v1.0/process-instance-resume/${params.process_model_id}/${params.process_instance_id}`, - processInstanceSuspendPath: `/v1.0/process-instance-suspend/${params.process_model_id}/${params.process_instance_id}`, - processInstanceTerminatePath: `/v1.0/process-instance-terminate/${params.process_model_id}/${params.process_instance_id}`, + processInstanceCreatePath: `/v1.0/process-instances/${params.process_model_id}`, processInstanceListPath: '/v1.0/process-instances', processInstanceLogListPath: `/v1.0/logs/${params.process_model_id}/${params.process_instance_id}`, processInstanceReportListPath: '/v1.0/process-instances/reports', - processInstanceTaskListPath: `/v1.0/process-instances/${params.process_model_id}/${params.process_instance_id}/task-info`, + processInstanceResumePath: `/v1.0/process-instance-resume/${params.process_model_id}/${params.process_instance_id}`, + processInstanceSuspendPath: `/v1.0/process-instance-suspend/${params.process_model_id}/${params.process_instance_id}`, processInstanceTaskListDataPath: `/v1.0/task-data/${params.process_model_id}/${params.process_instance_id}`, + processInstanceTaskListPath: `/v1.0/process-instances/${params.process_model_id}/${params.process_instance_id}/task-info`, + processInstanceTerminatePath: `/v1.0/process-instance-terminate/${params.process_model_id}/${params.process_instance_id}`, processModelCreatePath: `/v1.0/process-models/${params.process_group_id}`, processModelFileCreatePath: `/v1.0/process-models/${params.process_model_id}/files`, processModelFileShowPath: `/v1.0/process-models/${params.process_model_id}/files/${params.file_name}`, diff --git a/spiffworkflow-frontend/src/routes/AdminRoutes.tsx b/spiffworkflow-frontend/src/routes/AdminRoutes.tsx index da6cae356..d24c2b6e2 100644 --- a/spiffworkflow-frontend/src/routes/AdminRoutes.tsx +++ b/spiffworkflow-frontend/src/routes/AdminRoutes.tsx @@ -62,21 +62,25 @@ export default function AdminRoutes() { path="process-models/:process_model_id/files/:file_name" element={} /> - } - /> } /> + } + /> + } + /> } + element={} /> } + element={} /> } /> - } /> + } + /> + } + /> + } + /> } /> } /> { const processModelFullIdentifier = getProcessModelFullIdentifierFromSearchParams(searchParams); @@ -33,13 +51,46 @@ export default function ProcessInstanceList() { }; const processInstanceTitleElement = () => { - return

Process Instances

; + if (variant === 'all') { + return

All Process Instances

; + } + return

My Process Instances

; }; + + let apiPath = '/process-instances/for-me'; + let selectedTabIndex = 0; + if (variant === 'all') { + apiPath = '/process-instances'; + selectedTabIndex = 1; + } return ( <> + + + { + navigate('/admin/process-instances/for-me'); + }} + > + For Me + + + { + navigate('/admin/process-instances/all'); + }} + > + All + + + + +
{processInstanceBreadcrumbElement()} {processInstanceTitleElement()} - + ); } diff --git a/spiffworkflow-frontend/src/routes/ProcessInstanceShow.tsx b/spiffworkflow-frontend/src/routes/ProcessInstanceShow.tsx index db89bee87..37b515482 100644 --- a/spiffworkflow-frontend/src/routes/ProcessInstanceShow.tsx +++ b/spiffworkflow-frontend/src/routes/ProcessInstanceShow.tsx @@ -47,7 +47,11 @@ import { import { usePermissionFetcher } from '../hooks/PermissionService'; import ProcessInstanceClass from '../classes/ProcessInstanceClass'; -export default function ProcessInstanceShow() { +type OwnProps = { + variant: string; +}; + +export default function ProcessInstanceShow({ variant }: OwnProps) { const navigate = useNavigate(); const params = useParams(); const [searchParams] = useSearchParams(); @@ -99,8 +103,12 @@ export default function ProcessInstanceShow() { if (processIdentifier) { queryParams = `?process_identifier=${processIdentifier}`; } + let apiPath = '/process-instances/for-me'; + if (variant === 'all') { + apiPath = '/process-instances'; + } HttpService.makeCallToBackend({ - path: `/process-instances/${modifiedProcessModelId}/${params.process_instance_id}${queryParams}`, + path: `${apiPath}/${modifiedProcessModelId}/${params.process_instance_id}${queryParams}`, successCallback: setProcessInstance, }); let taskParams = '?all_tasks=true'; diff --git a/spiffworkflow-frontend/src/routes/TaskShow.tsx b/spiffworkflow-frontend/src/routes/TaskShow.tsx index 3412dcef8..2fc6ffcc0 100644 --- a/spiffworkflow-frontend/src/routes/TaskShow.tsx +++ b/spiffworkflow-frontend/src/routes/TaskShow.tsx @@ -171,7 +171,6 @@ export default function TaskShow() { } else if (taskToUse.form_ui_schema) { formUiSchema = JSON.parse(taskToUse.form_ui_schema); } - if (taskToUse.state !== 'READY') { formUiSchema = Object.assign(formUiSchema || {}, { 'ui:readonly': true, @@ -184,7 +183,7 @@ export default function TaskShow() { reactFragmentToHideSubmitButton =
; } - if (taskToUse.type === 'Manual Task') { + if (taskToUse.type === 'Manual Task' && taskToUse.state === 'READY') { reactFragmentToHideSubmitButton = (