diff --git a/.github/workflows/Update_Docker_Images.yml b/.github/workflows/Update_Docker_Images.yml index 30593b584..67ae97e75 100644 --- a/.github/workflows/Update_Docker_Images.yml +++ b/.github/workflows/Update_Docker_Images.yml @@ -39,10 +39,10 @@ jobs: type=ref,event=tag - name: Extract metadata (tags, labels) for Docker (Docker Hub) from Github Release - id: metaDeploy + id: metaSpace uses: docker/metadata-action@v4.3.0 with: - images: ${{ secrets.DOCKERHUB_USERNAME }}/plane-deploy + images: ${{ secrets.DOCKERHUB_USERNAME }}/plane-space tags: | type=ref,event=tag @@ -87,7 +87,7 @@ jobs: file: ./space/Dockerfile.space platforms: linux/amd64 push: true - tags: ${{ steps.metaDeploy.outputs.tags }} + tags: ${{ steps.metaSpace.outputs.tags }} env: DOCKER_BUILDKIT: 1 DOCKER_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6baa0bb07..b25a791d0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -8,8 +8,8 @@ Before submitting a new issue, please search the [issues](https://github.com/mak While we want to fix all the [issues](https://github.com/makeplane/plane/issues), before fixing a bug we need to be able to reproduce and confirm it. Please provide us with a minimal reproduction scenario using a repository or [Gist](https://gist.github.com/). Having a live, reproducible scenario gives us the information without asking questions back & forth with additional questions like: -- 3rd-party libraries being used and their versions -- a use-case that fails +- 3rd-party libraries being used and their versions +- a use-case that fails Without said minimal reproduction, we won't be able to investigate all [issues](https://github.com/makeplane/plane/issues), and the issue might not be resolved. @@ -19,10 +19,10 @@ You can open a new issue with this [issue form](https://github.com/makeplane/pla ### Requirements -- Node.js version v16.18.0 -- Python version 3.8+ -- Postgres version v14 -- Redis version v6.2.7 +- Node.js version v16.18.0 +- Python version 3.8+ +- Postgres version v14 +- Redis version v6.2.7 ### Setup the project @@ -30,6 +30,48 @@ The project is a monorepo, with backend api and frontend in a single repo. The backend is a django project which is kept inside apiserver +1. Clone the repo + +```bash +git clone https://github.com/makeplane/plane +cd plane +chmod +x setup.sh +``` + +2. Run setup.sh + +```bash +./setup.sh +``` + +3. Define `NEXT_PUBLIC_API_BASE_URL=http://localhost` in **web/.env** and **space/.env** file + +```bash +echo "\nNEXT_PUBLIC_API_BASE_URL=http://localhost\n" >> ./web/.env +``` + +```bash +echo "\nNEXT_PUBLIC_API_BASE_URL=http://localhost\n" >> ./space/.env +``` + +4. Run Docker compose up + +```bash +docker compose up -d +``` + +5. Install dependencies + +```bash +yarn install +``` + +6. Run the web app in development mode + +```bash +yarn dev +``` + ## Missing a Feature? If a feature is missing, you can directly _request_ a new one [here](https://github.com/makeplane/plane/issues/new?assignees=&labels=feature&template=feature_request.yml&title=%F0%9F%9A%80+Feature%3A+). You also can do the same by choosing "🚀 Feature" when raising a [New Issue](https://github.com/makeplane/plane/issues/new/choose) on our GitHub Repository. @@ -39,8 +81,8 @@ If you would like to _implement_ it, an issue with your proposal must be submitt To ensure consistency throughout the source code, please keep these rules in mind as you are working: -- All features or bug fixes must be tested by one or more specs (unit-tests). -- We use [Eslint default rule guide](https://eslint.org/docs/rules/), with minor changes. An automated formatter is available using prettier. +- All features or bug fixes must be tested by one or more specs (unit-tests). +- We use [Eslint default rule guide](https://eslint.org/docs/rules/), with minor changes. An automated formatter is available using prettier. ## Need help? Questions and suggestions @@ -48,11 +90,11 @@ Questions, suggestions, and thoughts are most welcome. We can also be reached in ## Ways to contribute -- Try Plane Cloud and the self hosting platform and give feedback -- Add new integrations -- Help with open [issues](https://github.com/makeplane/plane/issues) or [create your own](https://github.com/makeplane/plane/issues/new/choose) -- Share your thoughts and suggestions with us -- Help create tutorials and blog posts -- Request a feature by submitting a proposal -- Report a bug -- **Improve documentation** - fix incomplete or missing [docs](https://docs.plane.so/), bad wording, examples or explanations. +- Try Plane Cloud and the self hosting platform and give feedback +- Add new integrations +- Help with open [issues](https://github.com/makeplane/plane/issues) or [create your own](https://github.com/makeplane/plane/issues/new/choose) +- Share your thoughts and suggestions with us +- Help create tutorials and blog posts +- Request a feature by submitting a proposal +- Report a bug +- **Improve documentation** - fix incomplete or missing [docs](https://docs.plane.so/), bad wording, examples or explanations. diff --git a/apiserver/plane/api/permissions/workspace.py b/apiserver/plane/api/permissions/workspace.py index d01b545ee..66e836614 100644 --- a/apiserver/plane/api/permissions/workspace.py +++ b/apiserver/plane/api/permissions/workspace.py @@ -58,8 +58,17 @@ class WorkspaceEntityPermission(BasePermission): if request.user.is_anonymous: return False + ## Safe Methods -> Handle the filtering logic in queryset + if request.method in SAFE_METHODS: + return WorkspaceMember.objects.filter( + workspace__slug=view.workspace_slug, + member=request.user, + ).exists() + return WorkspaceMember.objects.filter( - member=request.user, workspace__slug=view.workspace_slug + member=request.user, + workspace__slug=view.workspace_slug, + role__in=[Owner, Admin], ).exists() diff --git a/apiserver/plane/api/serializers/cycle.py b/apiserver/plane/api/serializers/cycle.py index 664368033..ad214c52a 100644 --- a/apiserver/plane/api/serializers/cycle.py +++ b/apiserver/plane/api/serializers/cycle.py @@ -34,7 +34,6 @@ class CycleSerializer(BaseSerializer): unstarted_issues = serializers.IntegerField(read_only=True) backlog_issues = serializers.IntegerField(read_only=True) assignees = serializers.SerializerMethodField(read_only=True) - labels = serializers.SerializerMethodField(read_only=True) total_estimates = serializers.IntegerField(read_only=True) completed_estimates = serializers.IntegerField(read_only=True) started_estimates = serializers.IntegerField(read_only=True) @@ -50,11 +49,10 @@ class CycleSerializer(BaseSerializer): members = [ { "avatar": assignee.avatar, - "first_name": assignee.first_name, "display_name": assignee.display_name, "id": assignee.id, } - for issue_cycle in obj.issue_cycle.all() + for issue_cycle in obj.issue_cycle.prefetch_related("issue__assignees").all() for assignee in issue_cycle.issue.assignees.all() ] # Use a set comprehension to return only the unique objects @@ -64,24 +62,6 @@ class CycleSerializer(BaseSerializer): unique_list = [dict(item) for item in unique_objects] return unique_list - - def get_labels(self, obj): - labels = [ - { - "name": label.name, - "color": label.color, - "id": label.id, - } - for issue_cycle in obj.issue_cycle.all() - for label in issue_cycle.issue.labels.all() - ] - # Use a set comprehension to return only the unique objects - unique_objects = {frozenset(item.items()) for item in labels} - - # Convert the set back to a list of dictionaries - unique_list = [dict(item) for item in unique_objects] - - return unique_list class Meta: model = Cycle diff --git a/apiserver/plane/api/views/cycle.py b/apiserver/plane/api/views/cycle.py index 4f895aeba..e84b6dd0a 100644 --- a/apiserver/plane/api/views/cycle.py +++ b/apiserver/plane/api/views/cycle.py @@ -80,7 +80,7 @@ class CycleViewSet(BaseViewSet): issue_id=str(self.kwargs.get("pk", None)), project_id=str(self.kwargs.get("project_id", None)), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_destroy(instance) @@ -102,48 +102,84 @@ class CycleViewSet(BaseViewSet): .select_related("workspace") .select_related("owned_by") .annotate(is_favorite=Exists(subquery)) - .annotate(total_issues=Count("issue_cycle")) + .annotate( + total_issues=Count( + "issue_cycle", + filter=Q( + issue_cycle__issue__archived_at__isnull=True, + issue_cycle__issue__is_draft=False, + ), + ) + ) .annotate( completed_issues=Count( "issue_cycle__issue__state__group", - filter=Q(issue_cycle__issue__state__group="completed"), + filter=Q( + issue_cycle__issue__state__group="completed", + issue_cycle__issue__archived_at__isnull=True, + issue_cycle__issue__is_draft=False, + ), ) ) .annotate( cancelled_issues=Count( "issue_cycle__issue__state__group", - filter=Q(issue_cycle__issue__state__group="cancelled"), + filter=Q( + issue_cycle__issue__state__group="cancelled", + issue_cycle__issue__archived_at__isnull=True, + issue_cycle__issue__is_draft=False, + ), ) ) .annotate( started_issues=Count( "issue_cycle__issue__state__group", - filter=Q(issue_cycle__issue__state__group="started"), + filter=Q( + issue_cycle__issue__state__group="started", + issue_cycle__issue__archived_at__isnull=True, + issue_cycle__issue__is_draft=False, + ), ) ) .annotate( unstarted_issues=Count( "issue_cycle__issue__state__group", - filter=Q(issue_cycle__issue__state__group="unstarted"), + filter=Q( + issue_cycle__issue__state__group="unstarted", + issue_cycle__issue__archived_at__isnull=True, + issue_cycle__issue__is_draft=False, + ), ) ) .annotate( backlog_issues=Count( "issue_cycle__issue__state__group", - filter=Q(issue_cycle__issue__state__group="backlog"), + filter=Q( + issue_cycle__issue__state__group="backlog", + issue_cycle__issue__archived_at__isnull=True, + issue_cycle__issue__is_draft=False, + ), ) ) .annotate(total_estimates=Sum("issue_cycle__issue__estimate_point")) .annotate( completed_estimates=Sum( "issue_cycle__issue__estimate_point", - filter=Q(issue_cycle__issue__state__group="completed"), + filter=Q( + issue_cycle__issue__state__group="completed", + issue_cycle__issue__archived_at__isnull=True, + issue_cycle__issue__is_draft=False, + ), ) ) .annotate( started_estimates=Sum( "issue_cycle__issue__estimate_point", - filter=Q(issue_cycle__issue__state__group="started"), + filter=Q( + issue_cycle__issue__state__group="started", + issue_cycle__issue__archived_at__isnull=True, + issue_cycle__issue__is_draft=False, + ), ) ) .prefetch_related( @@ -196,17 +232,30 @@ class CycleViewSet(BaseViewSet): .annotate(assignee_id=F("assignees__id")) .annotate(avatar=F("assignees__avatar")) .values("display_name", "assignee_id", "avatar") - .annotate(total_issues=Count("assignee_id")) + .annotate( + total_issues=Count( + "assignee_id", + filter=Q(archived_at__isnull=True, is_draft=False), + ), + ) .annotate( completed_issues=Count( "assignee_id", - filter=Q(completed_at__isnull=False), + filter=Q( + completed_at__isnull=False, + archived_at__isnull=True, + is_draft=False, + ), ) ) .annotate( pending_issues=Count( "assignee_id", - filter=Q(completed_at__isnull=True), + filter=Q( + completed_at__isnull=True, + archived_at__isnull=True, + is_draft=False, + ), ) ) .order_by("display_name") @@ -222,17 +271,30 @@ class CycleViewSet(BaseViewSet): .annotate(color=F("labels__color")) .annotate(label_id=F("labels__id")) .values("label_name", "color", "label_id") - .annotate(total_issues=Count("label_id")) + .annotate( + total_issues=Count( + "label_id", + filter=Q(archived_at__isnull=True, is_draft=False), + ) + ) .annotate( completed_issues=Count( "label_id", - filter=Q(completed_at__isnull=False), + filter=Q( + completed_at__isnull=False, + archived_at__isnull=True, + is_draft=False, + ), ) ) .annotate( pending_issues=Count( "label_id", - filter=Q(completed_at__isnull=True), + filter=Q( + completed_at__isnull=True, + archived_at__isnull=True, + is_draft=False, + ), ) ) .order_by("label_name") @@ -385,17 +447,30 @@ class CycleViewSet(BaseViewSet): .values( "first_name", "last_name", "assignee_id", "avatar", "display_name" ) - .annotate(total_issues=Count("assignee_id")) + .annotate( + total_issues=Count( + "assignee_id", + filter=Q(archived_at__isnull=True, is_draft=False), + ), + ) .annotate( completed_issues=Count( "assignee_id", - filter=Q(completed_at__isnull=False), + filter=Q( + completed_at__isnull=False, + archived_at__isnull=True, + is_draft=False, + ), ) ) .annotate( pending_issues=Count( "assignee_id", - filter=Q(completed_at__isnull=True), + filter=Q( + completed_at__isnull=True, + archived_at__isnull=True, + is_draft=False, + ), ) ) .order_by("first_name", "last_name") @@ -412,17 +487,30 @@ class CycleViewSet(BaseViewSet): .annotate(color=F("labels__color")) .annotate(label_id=F("labels__id")) .values("label_name", "color", "label_id") - .annotate(total_issues=Count("label_id")) + .annotate( + total_issues=Count( + "label_id", + filter=Q(archived_at__isnull=True, is_draft=False), + ), + ) .annotate( completed_issues=Count( "label_id", - filter=Q(completed_at__isnull=False), + filter=Q( + completed_at__isnull=False, + archived_at__isnull=True, + is_draft=False, + ), ) ) .annotate( pending_issues=Count( "label_id", - filter=Q(completed_at__isnull=True), + filter=Q( + completed_at__isnull=True, + archived_at__isnull=True, + is_draft=False, + ), ) ) .order_by("label_name") @@ -488,7 +576,7 @@ class CycleIssueViewSet(BaseViewSet): issue_id=str(self.kwargs.get("pk", None)), project_id=str(self.kwargs.get("project_id", None)), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_destroy(instance) @@ -664,7 +752,7 @@ class CycleIssueViewSet(BaseViewSet): ), } ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) # Return all Cycle Issues diff --git a/apiserver/plane/api/views/importer.py b/apiserver/plane/api/views/importer.py index 0a92b3850..18d9a1d69 100644 --- a/apiserver/plane/api/views/importer.py +++ b/apiserver/plane/api/views/importer.py @@ -384,7 +384,7 @@ class BulkImportIssuesEndpoint(BaseAPIView): sort_order=largest_sort_order, start_date=issue_data.get("start_date", None), target_date=issue_data.get("target_date", None), - priority=issue_data.get("priority", None), + priority=issue_data.get("priority", "none"), created_by=request.user, ) ) diff --git a/apiserver/plane/api/views/inbox.py b/apiserver/plane/api/views/inbox.py index 1a0284ea4..4bfc32f01 100644 --- a/apiserver/plane/api/views/inbox.py +++ b/apiserver/plane/api/views/inbox.py @@ -173,12 +173,12 @@ class InboxIssueViewSet(BaseViewSet): ) # Check for valid priority - if not request.data.get("issue", {}).get("priority", None) in [ + if not request.data.get("issue", {}).get("priority", "none") in [ "low", "medium", "high", "urgent", - None, + "none", ]: return Response( {"error": "Invalid priority"}, status=status.HTTP_400_BAD_REQUEST @@ -213,7 +213,7 @@ class InboxIssueViewSet(BaseViewSet): issue_id=str(issue.id), project_id=str(project_id), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) # create an inbox issue InboxIssue.objects.create( @@ -278,7 +278,7 @@ class InboxIssueViewSet(BaseViewSet): IssueSerializer(current_instance).data, cls=DjangoJSONEncoder, ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) issue_serializer.save() else: @@ -370,6 +370,11 @@ class InboxIssueViewSet(BaseViewSet): if project_member.role <= 10 and str(inbox_issue.created_by_id) != str(request.user.id): return Response({"error": "You cannot delete inbox issue"}, status=status.HTTP_400_BAD_REQUEST) + # Check the issue status + if inbox_issue.status in [-2, -1, 0, 2]: + # Delete the issue also + Issue.objects.filter(workspace__slug=slug, project_id=project_id, pk=inbox_issue.issue_id).delete() + inbox_issue.delete() return Response(status=status.HTTP_204_NO_CONTENT) except InboxIssue.DoesNotExist: @@ -480,12 +485,12 @@ class InboxIssuePublicViewSet(BaseViewSet): ) # Check for valid priority - if not request.data.get("issue", {}).get("priority", None) in [ + if not request.data.get("issue", {}).get("priority", "none") in [ "low", "medium", "high", "urgent", - None, + "none", ]: return Response( {"error": "Invalid priority"}, status=status.HTTP_400_BAD_REQUEST @@ -520,7 +525,7 @@ class InboxIssuePublicViewSet(BaseViewSet): issue_id=str(issue.id), project_id=str(project_id), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) # create an inbox issue InboxIssue.objects.create( @@ -585,7 +590,7 @@ class InboxIssuePublicViewSet(BaseViewSet): IssueSerializer(current_instance).data, cls=DjangoJSONEncoder, ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) issue_serializer.save() return Response(issue_serializer.data, status=status.HTTP_200_OK) diff --git a/apiserver/plane/api/views/issue.py b/apiserver/plane/api/views/issue.py index 8d2ed9b96..b5a62dd5d 100644 --- a/apiserver/plane/api/views/issue.py +++ b/apiserver/plane/api/views/issue.py @@ -24,7 +24,6 @@ from django.core.serializers.json import DjangoJSONEncoder from django.utils.decorators import method_decorator from django.views.decorators.gzip import gzip_page from django.db import IntegrityError -from django.conf import settings from django.db import IntegrityError # Third Party imports @@ -58,7 +57,6 @@ from plane.api.serializers import ( IssuePublicSerializer, ) from plane.api.permissions import ( - WorkspaceEntityPermission, ProjectEntityPermission, WorkSpaceAdminPermission, ProjectMemberPermission, @@ -130,7 +128,7 @@ class IssueViewSet(BaseViewSet): current_instance=json.dumps( IssueSerializer(current_instance).data, cls=DjangoJSONEncoder ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_update(serializer) @@ -151,7 +149,7 @@ class IssueViewSet(BaseViewSet): current_instance=json.dumps( IssueSerializer(current_instance).data, cls=DjangoJSONEncoder ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_destroy(instance) @@ -318,7 +316,7 @@ class IssueViewSet(BaseViewSet): issue_id=str(serializer.data.get("id", None)), project_id=str(project_id), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @@ -330,7 +328,12 @@ class IssueViewSet(BaseViewSet): def retrieve(self, request, slug, project_id, pk=None): try: - issue = Issue.issue_objects.get( + issue = Issue.issue_objects.annotate( + sub_issues_count=Issue.issue_objects.filter(parent=OuterRef("id")) + .order_by() + .annotate(count=Func(F("id"), function="Count")) + .values("count") + ).get( workspace__slug=slug, project_id=project_id, pk=pk ) return Response(IssueSerializer(issue).data, status=status.HTTP_200_OK) @@ -572,7 +575,7 @@ class IssueCommentViewSet(BaseViewSet): issue_id=str(self.kwargs.get("issue_id")), project_id=str(self.kwargs.get("project_id")), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) def perform_update(self, serializer): @@ -591,7 +594,7 @@ class IssueCommentViewSet(BaseViewSet): IssueCommentSerializer(current_instance).data, cls=DjangoJSONEncoder, ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_update(serializer) @@ -613,7 +616,7 @@ class IssueCommentViewSet(BaseViewSet): IssueCommentSerializer(current_instance).data, cls=DjangoJSONEncoder, ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_destroy(instance) @@ -709,10 +712,18 @@ class LabelViewSet(BaseViewSet): ProjectMemberPermission, ] - def perform_create(self, serializer): - serializer.save( - project_id=self.kwargs.get("project_id"), - ) + def create(self, request, slug, project_id): + try: + serializer = LabelSerializer(data=request.data) + if serializer.is_valid(): + serializer.save(project_id=project_id) + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + except IntegrityError: + return Response({"error": "Label with the same name already exists in the project"}, status=status.HTTP_400_BAD_REQUEST) + except Exception as e: + capture_exception(e) + return Response({"error": "Something went wrong please try again later"}, status=status.HTTP_400_BAD_REQUEST) def get_queryset(self): return self.filter_queryset( @@ -897,7 +908,7 @@ class IssueLinkViewSet(BaseViewSet): issue_id=str(self.kwargs.get("issue_id")), project_id=str(self.kwargs.get("project_id")), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) def perform_update(self, serializer): @@ -916,7 +927,7 @@ class IssueLinkViewSet(BaseViewSet): IssueLinkSerializer(current_instance).data, cls=DjangoJSONEncoder, ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_update(serializer) @@ -938,7 +949,7 @@ class IssueLinkViewSet(BaseViewSet): IssueLinkSerializer(current_instance).data, cls=DjangoJSONEncoder, ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_destroy(instance) @@ -1017,7 +1028,7 @@ class IssueAttachmentEndpoint(BaseAPIView): serializer.data, cls=DjangoJSONEncoder, ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @@ -1040,7 +1051,7 @@ class IssueAttachmentEndpoint(BaseAPIView): issue_id=str(self.kwargs.get("issue_id", None)), project_id=str(self.kwargs.get("project_id", None)), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return Response(status=status.HTTP_204_NO_CONTENT) @@ -1243,7 +1254,7 @@ class IssueArchiveViewSet(BaseViewSet): issue_id=str(issue.id), project_id=str(project_id), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return Response(IssueSerializer(issue).data, status=status.HTTP_200_OK) @@ -1448,7 +1459,7 @@ class IssueReactionViewSet(BaseViewSet): issue_id=str(self.kwargs.get("issue_id", None)), project_id=str(self.kwargs.get("project_id", None)), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) def destroy(self, request, slug, project_id, issue_id, reaction_code): @@ -1472,7 +1483,7 @@ class IssueReactionViewSet(BaseViewSet): "identifier": str(issue_reaction.id), } ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) issue_reaction.delete() return Response(status=status.HTTP_204_NO_CONTENT) @@ -1521,7 +1532,7 @@ class CommentReactionViewSet(BaseViewSet): issue_id=None, project_id=str(self.kwargs.get("project_id", None)), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) def destroy(self, request, slug, project_id, comment_id, reaction_code): @@ -1546,7 +1557,7 @@ class CommentReactionViewSet(BaseViewSet): "comment_id": str(comment_id), } ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) comment_reaction.delete() return Response(status=status.HTTP_204_NO_CONTENT) @@ -1643,7 +1654,7 @@ class IssueCommentPublicViewSet(BaseViewSet): issue_id=str(issue_id), project_id=str(project_id), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) if not ProjectMember.objects.filter( project_id=project_id, @@ -1693,7 +1704,7 @@ class IssueCommentPublicViewSet(BaseViewSet): IssueCommentSerializer(comment).data, cls=DjangoJSONEncoder, ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @@ -1727,7 +1738,7 @@ class IssueCommentPublicViewSet(BaseViewSet): IssueCommentSerializer(comment).data, cls=DjangoJSONEncoder, ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) comment.delete() return Response(status=status.HTTP_204_NO_CONTENT) @@ -1802,7 +1813,7 @@ class IssueReactionPublicViewSet(BaseViewSet): issue_id=str(self.kwargs.get("issue_id", None)), project_id=str(self.kwargs.get("project_id", None)), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @@ -1847,7 +1858,7 @@ class IssueReactionPublicViewSet(BaseViewSet): "identifier": str(issue_reaction.id), } ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) issue_reaction.delete() return Response(status=status.HTTP_204_NO_CONTENT) @@ -1921,7 +1932,7 @@ class CommentReactionPublicViewSet(BaseViewSet): issue_id=None, project_id=str(self.kwargs.get("project_id", None)), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @@ -1973,7 +1984,7 @@ class CommentReactionPublicViewSet(BaseViewSet): "comment_id": str(comment_id), } ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) comment_reaction.delete() return Response(status=status.HTTP_204_NO_CONTENT) @@ -2037,7 +2048,7 @@ class IssueVotePublicViewSet(BaseViewSet): issue_id=str(self.kwargs.get("issue_id", None)), project_id=str(self.kwargs.get("project_id", None)), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) serializer = IssueVoteSerializer(issue_vote) return Response(serializer.data, status=status.HTTP_201_CREATED) @@ -2072,7 +2083,7 @@ class IssueVotePublicViewSet(BaseViewSet): "identifier": str(issue_vote.id), } ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) issue_vote.delete() return Response(status=status.HTTP_204_NO_CONTENT) @@ -2106,7 +2117,7 @@ class IssueRelationViewSet(BaseViewSet): IssueRelationSerializer(current_instance).data, cls=DjangoJSONEncoder, ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_destroy(instance) @@ -2140,7 +2151,7 @@ class IssueRelationViewSet(BaseViewSet): issue_id=str(issue_id), project_id=str(project_id), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) if relation == "blocking": @@ -2395,27 +2406,6 @@ class IssueDraftViewSet(BaseViewSet): ] serializer_class = IssueFlatSerializer model = Issue - - - def perform_update(self, serializer): - requested_data = json.dumps(self.request.data, cls=DjangoJSONEncoder) - current_instance = ( - self.get_queryset().filter(pk=self.kwargs.get("pk", None)).first() - ) - if current_instance is not None: - issue_activity.delay( - type="issue_draft.activity.updated", - requested_data=requested_data, - actor_id=str(self.request.user.id), - issue_id=str(self.kwargs.get("pk", None)), - project_id=str(self.kwargs.get("project_id", None)), - current_instance=json.dumps( - IssueSerializer(current_instance).data, cls=DjangoJSONEncoder - ), - epoch = int(timezone.now().timestamp()) - ) - - return super().perform_update(serializer) def perform_destroy(self, instance): @@ -2434,6 +2424,7 @@ class IssueDraftViewSet(BaseViewSet): current_instance=json.dumps( IssueSerializer(current_instance).data, cls=DjangoJSONEncoder ), + epoch=int(timezone.now().timestamp()) ) return super().perform_destroy(instance) @@ -2597,7 +2588,7 @@ class IssueDraftViewSet(BaseViewSet): issue_id=str(serializer.data.get("id", None)), project_id=str(project_id), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @@ -2608,6 +2599,47 @@ class IssueDraftViewSet(BaseViewSet): ) + def partial_update(self, request, slug, project_id, pk): + try: + issue = Issue.objects.get( + workspace__slug=slug, project_id=project_id, pk=pk + ) + serializer = IssueSerializer( + issue, data=request.data, partial=True + ) + + if serializer.is_valid(): + if(request.data.get("is_draft") is not None and not request.data.get("is_draft")): + serializer.save(created_at=timezone.now(), updated_at=timezone.now()) + else: + serializer.save() + issue_activity.delay( + type="issue_draft.activity.updated", + requested_data=json.dumps(request.data, cls=DjangoJSONEncoder), + actor_id=str(self.request.user.id), + issue_id=str(self.kwargs.get("pk", None)), + project_id=str(self.kwargs.get("project_id", None)), + current_instance=json.dumps( + IssueSerializer(issue).data, + cls=DjangoJSONEncoder, + ), + epoch=int(timezone.now().timestamp()) + ) + return Response(serializer.data, status=status.HTTP_200_OK) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) + except Issue.DoesNotExist: + return Response( + {"error": "Issue does not exists"}, + status=status.HTTP_400_BAD_REQUEST, + ) + except Exception as e: + capture_exception(e) + return Response( + {"error": "Something went wrong please try again later"}, + status=status.HTTP_400_BAD_REQUEST, + ) + + def retrieve(self, request, slug, project_id, pk=None): try: issue = Issue.objects.get( diff --git a/apiserver/plane/api/views/module.py b/apiserver/plane/api/views/module.py index c2a15da1c..1489edb2d 100644 --- a/apiserver/plane/api/views/module.py +++ b/apiserver/plane/api/views/module.py @@ -40,6 +40,7 @@ from plane.utils.grouper import group_results from plane.utils.issue_filters import issue_filters from plane.utils.analytics_plot import burndown_plot + class ModuleViewSet(BaseViewSet): model = Module permission_classes = [ @@ -78,35 +79,63 @@ class ModuleViewSet(BaseViewSet): queryset=ModuleLink.objects.select_related("module", "created_by"), ) ) - .annotate(total_issues=Count("issue_module")) + .annotate( + total_issues=Count( + "issue_module", + filter=Q( + issue_module__issue__archived_at__isnull=True, + issue_module__issue__is_draft=False, + ), + ), + ) .annotate( completed_issues=Count( "issue_module__issue__state__group", - filter=Q(issue_module__issue__state__group="completed"), + filter=Q( + issue_module__issue__state__group="completed", + issue_module__issue__archived_at__isnull=True, + issue_module__issue__is_draft=False, + ), ) ) .annotate( cancelled_issues=Count( "issue_module__issue__state__group", - filter=Q(issue_module__issue__state__group="cancelled"), + filter=Q( + issue_module__issue__state__group="cancelled", + issue_module__issue__archived_at__isnull=True, + issue_module__issue__is_draft=False, + ), ) ) .annotate( started_issues=Count( "issue_module__issue__state__group", - filter=Q(issue_module__issue__state__group="started"), + filter=Q( + issue_module__issue__state__group="started", + issue_module__issue__archived_at__isnull=True, + issue_module__issue__is_draft=False, + ), ) ) .annotate( unstarted_issues=Count( "issue_module__issue__state__group", - filter=Q(issue_module__issue__state__group="unstarted"), + filter=Q( + issue_module__issue__state__group="unstarted", + issue_module__issue__archived_at__isnull=True, + issue_module__issue__is_draft=False, + ), ) ) .annotate( backlog_issues=Count( "issue_module__issue__state__group", - filter=Q(issue_module__issue__state__group="backlog"), + filter=Q( + issue_module__issue__state__group="backlog", + issue_module__issue__archived_at__isnull=True, + issue_module__issue__is_draft=False, + ), ) ) .order_by(order_by, "name") @@ -130,7 +159,7 @@ class ModuleViewSet(BaseViewSet): issue_id=str(self.kwargs.get("pk", None)), project_id=str(self.kwargs.get("project_id", None)), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_destroy(instance) @@ -179,18 +208,36 @@ class ModuleViewSet(BaseViewSet): .annotate(assignee_id=F("assignees__id")) .annotate(display_name=F("assignees__display_name")) .annotate(avatar=F("assignees__avatar")) - .values("first_name", "last_name", "assignee_id", "avatar", "display_name") - .annotate(total_issues=Count("assignee_id")) + .values( + "first_name", "last_name", "assignee_id", "avatar", "display_name" + ) + .annotate( + total_issues=Count( + "assignee_id", + filter=Q( + archived_at__isnull=True, + is_draft=False, + ), + ) + ) .annotate( completed_issues=Count( "assignee_id", - filter=Q(completed_at__isnull=False), + filter=Q( + completed_at__isnull=False, + archived_at__isnull=True, + is_draft=False, + ), ) ) .annotate( pending_issues=Count( "assignee_id", - filter=Q(completed_at__isnull=True), + filter=Q( + completed_at__isnull=True, + archived_at__isnull=True, + is_draft=False, + ), ) ) .order_by("first_name", "last_name") @@ -206,17 +253,33 @@ class ModuleViewSet(BaseViewSet): .annotate(color=F("labels__color")) .annotate(label_id=F("labels__id")) .values("label_name", "color", "label_id") - .annotate(total_issues=Count("label_id")) + .annotate( + total_issues=Count( + "label_id", + filter=Q( + archived_at__isnull=True, + is_draft=False, + ), + ), + ) .annotate( completed_issues=Count( "label_id", - filter=Q(completed_at__isnull=False), + filter=Q( + completed_at__isnull=False, + archived_at__isnull=True, + is_draft=False, + ), ) ) .annotate( pending_issues=Count( "label_id", - filter=Q(completed_at__isnull=True), + filter=Q( + completed_at__isnull=True, + archived_at__isnull=True, + is_draft=False, + ), ) ) .order_by("label_name") @@ -279,7 +342,7 @@ class ModuleIssueViewSet(BaseViewSet): issue_id=str(self.kwargs.get("pk", None)), project_id=str(self.kwargs.get("project_id", None)), current_instance=None, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return super().perform_destroy(instance) @@ -447,7 +510,7 @@ class ModuleIssueViewSet(BaseViewSet): ), } ), - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) return Response( @@ -494,7 +557,6 @@ class ModuleLinkViewSet(BaseViewSet): class ModuleFavoriteViewSet(BaseViewSet): - serializer_class = ModuleFavoriteSerializer model = ModuleFavorite diff --git a/apiserver/plane/api/views/project.py b/apiserver/plane/api/views/project.py index 093c8ff78..c72b8d423 100644 --- a/apiserver/plane/api/views/project.py +++ b/apiserver/plane/api/views/project.py @@ -1094,7 +1094,7 @@ class ProjectMemberEndpoint(BaseAPIView): project_id=project_id, workspace__slug=slug, member__is_bot=False, - ).select_related("project", "member") + ).select_related("project", "member", "workspace") serializer = ProjectMemberSerializer(project_members, many=True) return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: diff --git a/apiserver/plane/api/views/view.py b/apiserver/plane/api/views/view.py index b6f1d7c4b..435f8725a 100644 --- a/apiserver/plane/api/views/view.py +++ b/apiserver/plane/api/views/view.py @@ -61,7 +61,7 @@ class GlobalViewViewSet(BaseViewSet): .get_queryset() .filter(workspace__slug=self.kwargs.get("slug")) .select_related("workspace") - .order_by("-created_at") + .order_by(self.request.GET.get("order_by", "-created_at")) .distinct() ) diff --git a/apiserver/plane/api/views/workspace.py b/apiserver/plane/api/views/workspace.py index 2d1ee8132..753fd861b 100644 --- a/apiserver/plane/api/views/workspace.py +++ b/apiserver/plane/api/views/workspace.py @@ -1239,13 +1239,21 @@ class WorkspaceUserProfileEndpoint(BaseAPIView): .annotate( created_issues=Count( "project_issue", - filter=Q(project_issue__created_by_id=user_id), + filter=Q( + project_issue__created_by_id=user_id, + project_issue__archived_at__isnull=True, + project_issue__is_draft=False, + ), ) ) .annotate( assigned_issues=Count( "project_issue", - filter=Q(project_issue__assignees__in=[user_id]), + filter=Q( + project_issue__assignees__in=[user_id], + project_issue__archived_at__isnull=True, + project_issue__is_draft=False, + ), ) ) .annotate( @@ -1254,6 +1262,8 @@ class WorkspaceUserProfileEndpoint(BaseAPIView): filter=Q( project_issue__completed_at__isnull=False, project_issue__assignees__in=[user_id], + project_issue__archived_at__isnull=True, + project_issue__is_draft=False, ), ) ) @@ -1267,6 +1277,8 @@ class WorkspaceUserProfileEndpoint(BaseAPIView): "started", ], project_issue__assignees__in=[user_id], + project_issue__archived_at__isnull=True, + project_issue__is_draft=False, ), ) ) @@ -1317,6 +1329,11 @@ class WorkspaceUserProfileIssuesEndpoint(BaseAPIView): def get(self, request, slug, user_id): try: filters = issue_filters(request.query_params, "GET") + + # Custom ordering for priority and state + priority_order = ["urgent", "high", "medium", "low", "none"] + state_order = ["backlog", "unstarted", "started", "completed", "cancelled"] + order_by_param = request.GET.get("order_by", "-created_at") issue_queryset = ( Issue.issue_objects.filter( diff --git a/apiserver/plane/bgtasks/exporter_expired_task.py b/apiserver/plane/bgtasks/exporter_expired_task.py index a77d68b4b..45c53eaca 100644 --- a/apiserver/plane/bgtasks/exporter_expired_task.py +++ b/apiserver/plane/bgtasks/exporter_expired_task.py @@ -32,7 +32,7 @@ def delete_old_s3_link(): else: s3 = boto3.client( "s3", - region_name="ap-south-1", + region_name=settings.AWS_REGION, aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY, config=Config(signature_version="s3v4"), diff --git a/apiserver/plane/bgtasks/issue_activites_task.py b/apiserver/plane/bgtasks/issue_activites_task.py index 733defe69..87c4fa1a4 100644 --- a/apiserver/plane/bgtasks/issue_activites_task.py +++ b/apiserver/plane/bgtasks/issue_activites_task.py @@ -121,36 +121,20 @@ def track_priority( epoch ): if current_instance.get("priority") != requested_data.get("priority"): - if requested_data.get("priority") == None: - issue_activities.append( - IssueActivity( - issue_id=issue_id, - actor=actor, - verb="updated", - old_value=current_instance.get("priority"), - new_value=None, - field="priority", - project=project, - workspace=project.workspace, - comment=f"updated the priority to None", - epoch=epoch, - ) - ) - else: - issue_activities.append( - IssueActivity( - issue_id=issue_id, - actor=actor, - verb="updated", - old_value=current_instance.get("priority"), - new_value=requested_data.get("priority"), - field="priority", - project=project, - workspace=project.workspace, - comment=f"updated the priority to {requested_data.get('priority')}", - epoch=epoch, - ) + issue_activities.append( + IssueActivity( + issue_id=issue_id, + actor=actor, + verb="updated", + old_value=current_instance.get("priority"), + new_value=requested_data.get("priority"), + field="priority", + project=project, + workspace=project.workspace, + comment=f"updated the priority to {requested_data.get('priority')}", + epoch=epoch, ) + ) # Track chnages in state of the issue @@ -1405,7 +1389,7 @@ def issue_activity( ): issue_subscribers = issue_subscribers + [issue.created_by_id] - for subscriber in issue_subscribers: + for subscriber in list(set(issue_subscribers)): for issue_activity in issue_activities_created: bulk_notifications.append( Notification( diff --git a/apiserver/plane/bgtasks/issue_automation_task.py b/apiserver/plane/bgtasks/issue_automation_task.py index f7b06c625..68c64403a 100644 --- a/apiserver/plane/bgtasks/issue_automation_task.py +++ b/apiserver/plane/bgtasks/issue_automation_task.py @@ -58,28 +58,31 @@ def archive_old_issues(): # Check if Issues if issues: + # Set the archive time to current time + archive_at = timezone.now() + issues_to_update = [] for issue in issues: - issue.archived_at = timezone.now() + issue.archived_at = archive_at issues_to_update.append(issue) # Bulk Update the issues and log the activity if issues_to_update: - updated_issues = Issue.objects.bulk_update( + Issue.objects.bulk_update( issues_to_update, ["archived_at"], batch_size=100 ) [ issue_activity.delay( type="issue.activity.updated", - requested_data=json.dumps({"archived_at": str(issue.archived_at)}), + requested_data=json.dumps({"archived_at": str(archive_at)}), actor_id=str(project.created_by_id), issue_id=issue.id, project_id=project_id, current_instance=None, subscriber=False, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) - for issue in updated_issues + for issue in issues_to_update ] return except Exception as e: @@ -139,7 +142,7 @@ def close_old_issues(): # Bulk Update the issues and log the activity if issues_to_update: - updated_issues = Issue.objects.bulk_update(issues_to_update, ["state"], batch_size=100) + Issue.objects.bulk_update(issues_to_update, ["state"], batch_size=100) [ issue_activity.delay( type="issue.activity.updated", @@ -149,9 +152,9 @@ def close_old_issues(): project_id=project_id, current_instance=None, subscriber=False, - epoch = int(timezone.now().timestamp()) + epoch=int(timezone.now().timestamp()) ) - for issue in updated_issues + for issue in issues_to_update ] return except Exception as e: diff --git a/apiserver/plane/db/migrations/0043_alter_analyticview_created_by_and_more.py b/apiserver/plane/db/migrations/0043_alter_analyticview_created_by_and_more.py index 950189c55..5a806c704 100644 --- a/apiserver/plane/db/migrations/0043_alter_analyticview_created_by_and_more.py +++ b/apiserver/plane/db/migrations/0043_alter_analyticview_created_by_and_more.py @@ -33,9 +33,8 @@ def create_issue_relation(apps, schema_editor): def update_issue_priority_choice(apps, schema_editor): IssueModel = apps.get_model("db", "Issue") updated_issues = [] - for obj in IssueModel.objects.all(): - if obj.priority is None: - obj.priority = "none" + for obj in IssueModel.objects.filter(priority=None): + obj.priority = "none" updated_issues.append(obj) IssueModel.objects.bulk_update(updated_issues, ["priority"], batch_size=100) diff --git a/apiserver/plane/db/migrations/0044_auto_20230913_0709.py b/apiserver/plane/db/migrations/0044_auto_20230913_0709.py index f30062371..19a1449af 100644 --- a/apiserver/plane/db/migrations/0044_auto_20230913_0709.py +++ b/apiserver/plane/db/migrations/0044_auto_20230913_0709.py @@ -26,19 +26,19 @@ def workspace_member_props(old_props): "calendar_date_range": old_props.get("calendarDateRange", ""), }, "display_properties": { - "assignee": old_props.get("properties", {}).get("assignee",None), - "attachment_count": old_props.get("properties", {}).get("attachment_count", None), - "created_on": old_props.get("properties", {}).get("created_on", None), - "due_date": old_props.get("properties", {}).get("due_date", None), - "estimate": old_props.get("properties", {}).get("estimate", None), - "key": old_props.get("properties", {}).get("key", None), - "labels": old_props.get("properties", {}).get("labels", None), - "link": old_props.get("properties", {}).get("link", None), - "priority": old_props.get("properties", {}).get("priority", None), - "start_date": old_props.get("properties", {}).get("start_date", None), - "state": old_props.get("properties", {}).get("state", None), - "sub_issue_count": old_props.get("properties", {}).get("sub_issue_count", None), - "updated_on": old_props.get("properties", {}).get("updated_on", None), + "assignee": old_props.get("properties", {}).get("assignee", True), + "attachment_count": old_props.get("properties", {}).get("attachment_count", True), + "created_on": old_props.get("properties", {}).get("created_on", True), + "due_date": old_props.get("properties", {}).get("due_date", True), + "estimate": old_props.get("properties", {}).get("estimate", True), + "key": old_props.get("properties", {}).get("key", True), + "labels": old_props.get("properties", {}).get("labels", True), + "link": old_props.get("properties", {}).get("link", True), + "priority": old_props.get("properties", {}).get("priority", True), + "start_date": old_props.get("properties", {}).get("start_date", True), + "state": old_props.get("properties", {}).get("state", True), + "sub_issue_count": old_props.get("properties", {}).get("sub_issue_count", True), + "updated_on": old_props.get("properties", {}).get("updated_on", True), }, } return new_props diff --git a/apiserver/plane/db/migrations/0045_auto_20230915_0655.py b/apiserver/plane/db/migrations/0045_auto_20230915_0655.py deleted file mode 100644 index a8360c63d..000000000 --- a/apiserver/plane/db/migrations/0045_auto_20230915_0655.py +++ /dev/null @@ -1,24 +0,0 @@ -# Generated by Django 4.2.3 on 2023-09-15 06:55 - -from django.db import migrations - - -def update_issue_activity(apps, schema_editor): - IssueActivityModel = apps.get_model("db", "IssueActivity") - updated_issue_activity = [] - for obj in IssueActivityModel.objects.all(): - if obj.field == "blocks": - obj.field = "blocked_by" - updated_issue_activity.append(obj) - IssueActivityModel.objects.bulk_update(updated_issue_activity, ["field"], batch_size=100) - - -class Migration(migrations.Migration): - - dependencies = [ - ('db', '0044_auto_20230913_0709'), - ] - - operations = [ - migrations.RunPython(update_issue_activity), - ] diff --git a/apiserver/plane/db/migrations/0046_auto_20230919_1421.py b/apiserver/plane/db/migrations/0045_issueactivity_epoch_workspacemember_issue_props_and_more.py similarity index 59% rename from apiserver/plane/db/migrations/0046_auto_20230919_1421.py rename to apiserver/plane/db/migrations/0045_issueactivity_epoch_workspacemember_issue_props_and_more.py index 4005a94d4..4b9c1b1eb 100644 --- a/apiserver/plane/db/migrations/0046_auto_20230919_1421.py +++ b/apiserver/plane/db/migrations/0045_issueactivity_epoch_workspacemember_issue_props_and_more.py @@ -1,28 +1,47 @@ -# Generated by Django 4.2.3 on 2023-09-19 14:21 +# Generated by Django 4.2.5 on 2023-09-29 10:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion +import plane.db.models.workspace import uuid -def update_epoch(apps, schema_editor): - IssueActivity = apps.get_model('db', 'IssueActivity') +def update_issue_activity_priority(apps, schema_editor): + IssueActivity = apps.get_model("db", "IssueActivity") updated_issue_activity = [] - for obj in IssueActivity.objects.all(): - obj.epoch = int(obj.created_at.timestamp()) + for obj in IssueActivity.objects.filter(field="priority"): + # Set the old and new value to none if it is empty for Priority + obj.new_value = obj.new_value or "none" + obj.old_value = obj.old_value or "none" updated_issue_activity.append(obj) - IssueActivity.objects.bulk_update(updated_issue_activity, ["epoch"], batch_size=100) + IssueActivity.objects.bulk_update( + updated_issue_activity, + ["new_value", "old_value"], + batch_size=2000, + ) +def update_issue_activity_blocked(apps, schema_editor): + IssueActivity = apps.get_model("db", "IssueActivity") + updated_issue_activity = [] + for obj in IssueActivity.objects.filter(field="blocks"): + # Set the field to blocked_by + obj.field = "blocked_by" + updated_issue_activity.append(obj) + IssueActivity.objects.bulk_update( + updated_issue_activity, + ["field"], + batch_size=1000, + ) class Migration(migrations.Migration): dependencies = [ - ('db', '0045_auto_20230915_0655'), + ('db', '0044_auto_20230913_0709'), ] operations = [ - migrations.CreateModel( + migrations.CreateModel( name='GlobalView', fields=[ ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Created At')), @@ -33,6 +52,7 @@ class Migration(migrations.Migration): ('query', models.JSONField(verbose_name='View Query')), ('access', models.PositiveSmallIntegerField(choices=[(0, 'Private'), (1, 'Public')], default=1)), ('query_data', models.JSONField(default=dict)), + ('sort_order', models.FloatField(default=65535)), ('created_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Created By')), ('updated_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='%(class)s_updated_by', to=settings.AUTH_USER_MODEL, verbose_name='Last Modified By')), ('workspace', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='global_views', to='db.workspace')), @@ -44,10 +64,16 @@ class Migration(migrations.Migration): 'ordering': ('-created_at',), }, ), + migrations.AddField( + model_name='workspacemember', + name='issue_props', + field=models.JSONField(default=plane.db.models.workspace.get_issue_props), + ), migrations.AddField( model_name='issueactivity', name='epoch', field=models.FloatField(null=True), ), - migrations.RunPython(update_epoch), + migrations.RunPython(update_issue_activity_priority), + migrations.RunPython(update_issue_activity_blocked), ] diff --git a/apiserver/plane/db/models/view.py b/apiserver/plane/db/models/view.py index 6e0a47105..44bc994d0 100644 --- a/apiserver/plane/db/models/view.py +++ b/apiserver/plane/db/models/view.py @@ -17,12 +17,23 @@ class GlobalView(BaseModel): default=1, choices=((0, "Private"), (1, "Public")) ) query_data = models.JSONField(default=dict) + sort_order = models.FloatField(default=65535) class Meta: verbose_name = "Global View" verbose_name_plural = "Global Views" db_table = "global_views" ordering = ("-created_at",) + + def save(self, *args, **kwargs): + if self._state.adding: + largest_sort_order = GlobalView.objects.filter( + workspace=self.workspace + ).aggregate(largest=models.Max("sort_order"))["largest"] + if largest_sort_order is not None: + self.sort_order = largest_sort_order + 10000 + + super(GlobalView, self).save(*args, **kwargs) def __str__(self): """Return name of the View""" diff --git a/apiserver/plane/db/models/workspace.py b/apiserver/plane/db/models/workspace.py index c85268435..d1012f549 100644 --- a/apiserver/plane/db/models/workspace.py +++ b/apiserver/plane/db/models/workspace.py @@ -29,7 +29,7 @@ def get_default_props(): }, "display_filters": { "group_by": None, - "order_by": '-created_at', + "order_by": "-created_at", "type": None, "sub_issue": True, "show_empty_groups": True, @@ -54,6 +54,15 @@ def get_default_props(): } +def get_issue_props(): + return { + "subscribed": True, + "assigned": True, + "created": True, + "all_issues": True, + } + + class Workspace(BaseModel): name = models.CharField(max_length=80, verbose_name="Workspace Name") logo = models.URLField(verbose_name="Logo", blank=True, null=True) @@ -89,6 +98,7 @@ class WorkspaceMember(BaseModel): company_role = models.TextField(null=True, blank=True) view_props = models.JSONField(default=get_default_props) default_props = models.JSONField(default=get_default_props) + issue_props = models.JSONField(default=get_issue_props) class Meta: unique_together = ["workspace", "member"] diff --git a/apiserver/plane/utils/analytics_plot.py b/apiserver/plane/utils/analytics_plot.py index 60e751459..bffbb4c2a 100644 --- a/apiserver/plane/utils/analytics_plot.py +++ b/apiserver/plane/utils/analytics_plot.py @@ -74,10 +74,10 @@ def build_graph_plot(queryset, x_axis, y_axis, segment=None): sorted_data = grouped_data if temp_axis == "priority": - order = ["low", "medium", "high", "urgent", "None"] + order = ["low", "medium", "high", "urgent", "none"] sorted_data = {key: grouped_data[key] for key in order if key in grouped_data} else: - sorted_data = dict(sorted(grouped_data.items(), key=lambda x: (x[0] == "None", x[0]))) + sorted_data = dict(sorted(grouped_data.items(), key=lambda x: (x[0] == "none", x[0]))) return sorted_data diff --git a/apiserver/plane/utils/issue_filters.py b/apiserver/plane/utils/issue_filters.py index 226d909cd..dae301c38 100644 --- a/apiserver/plane/utils/issue_filters.py +++ b/apiserver/plane/utils/issue_filters.py @@ -40,9 +40,6 @@ def filter_priority(params, filter, method): priorities = params.get("priority").split(",") if len(priorities) and "" not in priorities: filter["priority__in"] = priorities - else: - if params.get("priority", None) and len(params.get("priority")): - filter["priority__in"] = params.get("priority") return filter @@ -166,17 +163,17 @@ def filter_target_date(params, filter, method): for query in target_dates: target_date_query = query.split(";") if len(target_date_query) == 2 and "after" in target_date_query: - filter["target_date__gt"] = target_date_query[0] + filter["target_date__gte"] = target_date_query[0] else: - filter["target_date__lt"] = target_date_query[0] + filter["target_date__lte"] = target_date_query[0] else: if params.get("target_date", None) and len(params.get("target_date")): for query in params.get("target_date"): target_date_query = query.split(";") if len(target_date_query) == 2 and "after" in target_date_query: - filter["target_date__gt"] = target_date_query[0] + filter["target_date__gte"] = target_date_query[0] else: - filter["target_date__lt"] = target_date_query[0] + filter["target_date__lte"] = target_date_query[0] return filter diff --git a/docker-compose-hub.yml b/docker-compose-hub.yml index 0014dfe86..498f37b84 100644 --- a/docker-compose-hub.yml +++ b/docker-compose-hub.yml @@ -1,113 +1,61 @@ version: "3.8" -x-api-and-worker-env: - &api-and-worker-env - DEBUG: ${DEBUG} - SENTRY_DSN: ${SENTRY_DSN} - DJANGO_SETTINGS_MODULE: plane.settings.selfhosted - DATABASE_URL: postgres://${PGUSER}:${PGPASSWORD}@${PGHOST}:5432/${PGDATABASE} - REDIS_URL: redis://plane-redis:6379/ - EMAIL_HOST: ${EMAIL_HOST} - EMAIL_HOST_USER: ${EMAIL_HOST_USER} - EMAIL_HOST_PASSWORD: ${EMAIL_HOST_PASSWORD} - EMAIL_PORT: ${EMAIL_PORT} - EMAIL_FROM: ${EMAIL_FROM} - EMAIL_USE_TLS: ${EMAIL_USE_TLS} - EMAIL_USE_SSL: ${EMAIL_USE_SSL} - AWS_REGION: ${AWS_REGION} - AWS_ACCESS_KEY_ID: ${AWS_ACCESS_KEY_ID} - AWS_SECRET_ACCESS_KEY: ${AWS_SECRET_ACCESS_KEY} - AWS_S3_BUCKET_NAME: ${AWS_S3_BUCKET_NAME} - AWS_S3_ENDPOINT_URL: ${AWS_S3_ENDPOINT_URL} - FILE_SIZE_LIMIT: ${FILE_SIZE_LIMIT} - WEB_URL: ${WEB_URL} - GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET} - DISABLE_COLLECTSTATIC: 1 - DOCKERIZED: 1 - OPENAI_API_BASE: ${OPENAI_API_BASE} - OPENAI_API_KEY: ${OPENAI_API_KEY} - GPT_ENGINE: ${GPT_ENGINE} - SECRET_KEY: ${SECRET_KEY} - DEFAULT_EMAIL: ${DEFAULT_EMAIL} - DEFAULT_PASSWORD: ${DEFAULT_PASSWORD} - USE_MINIO: ${USE_MINIO} - ENABLE_SIGNUP: ${ENABLE_SIGNUP} - services: - plane-web: - container_name: planefrontend + web: + container_name: web image: makeplane/plane-frontend:latest restart: always command: /usr/local/bin/start.sh web/server.js web env_file: - - .env - environment: - NEXT_PUBLIC_API_BASE_URL: ${NEXT_PUBLIC_API_BASE_URL} - NEXT_PUBLIC_DEPLOY_URL: ${NEXT_PUBLIC_DEPLOY_URL} - NEXT_PUBLIC_GOOGLE_CLIENTID: "0" - NEXT_PUBLIC_GITHUB_APP_NAME: "0" - NEXT_PUBLIC_GITHUB_ID: "0" - NEXT_PUBLIC_SENTRY_DSN: "0" - NEXT_PUBLIC_ENABLE_OAUTH: "0" - NEXT_PUBLIC_ENABLE_SENTRY: "0" - NEXT_PUBLIC_ENABLE_SESSION_RECORDER: "0" - NEXT_PUBLIC_TRACK_EVENTS: "0" + - ./web/.env depends_on: - - plane-api - - plane-worker + - api + - worker - plane-deploy: - container_name: planedeploy - image: makeplane/plane-deploy:latest + space: + container_name: space + image: makeplane/plane-space:latest restart: always command: /usr/local/bin/start.sh space/server.js space env_file: - - .env - environment: - NEXT_PUBLIC_API_BASE_URL: ${NEXT_PUBLIC_API_BASE_URL} + - ./space/.env depends_on: - - plane-api - - plane-worker - - plane-web + - api + - worker + - web - plane-api: - container_name: planebackend + api: + container_name: api image: makeplane/plane-backend:latest restart: always command: ./bin/takeoff env_file: - - .env - environment: - <<: *api-and-worker-env + - ./apiserver/.env depends_on: - plane-db - plane-redis - plane-worker: - container_name: planebgworker + worker: + container_name: bgworker image: makeplane/plane-backend:latest restart: always command: ./bin/worker env_file: - - .env - environment: - <<: *api-and-worker-env + - ./apiserver/.env depends_on: - - plane-api + - api - plane-db - plane-redis - plane-beat-worker: - container_name: planebeatworker + beat-worker: + container_name: beatworker image: makeplane/plane-backend:latest restart: always command: ./bin/beat env_file: - - .env - environment: - <<: *api-and-worker-env + - ./apiserver/.env depends_on: - - plane-api + - api - plane-db - plane-redis @@ -157,8 +105,8 @@ services: - plane-minio # Comment this if you already have a reverse proxy running - plane-proxy: - container_name: planeproxy + proxy: + container_name: proxy image: makeplane/plane-proxy:latest ports: - ${NGINX_PORT}:80 @@ -168,8 +116,9 @@ services: FILE_SIZE_LIMIT: ${FILE_SIZE_LIMIT:-5242880} BUCKET_NAME: ${AWS_S3_BUCKET_NAME:-uploads} depends_on: - - plane-web - - plane-api + - web + - api + - space volumes: pgdata: diff --git a/docker-compose.yml b/docker-compose.yml index e3c1b37be..0895aa1ae 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,8 +1,8 @@ version: "3.8" services: - plane-web: - container_name: planefrontend + web: + container_name: web build: context: . dockerfile: ./web/Dockerfile.web @@ -11,11 +11,11 @@ services: restart: always command: /usr/local/bin/start.sh web/server.js web depends_on: - - plane-api - - plane-worker + - api + - worker - plane-deploy: - container_name: planedeploy + space: + container_name: space build: context: . dockerfile: ./space/Dockerfile.space @@ -24,12 +24,12 @@ services: restart: always command: /usr/local/bin/start.sh space/server.js space depends_on: - - plane-api - - plane-worker - - plane-web + - api + - worker + - web - plane-api: - container_name: planebackend + api: + container_name: api build: context: ./apiserver dockerfile: Dockerfile.api @@ -43,8 +43,8 @@ services: - plane-db - plane-redis - plane-worker: - container_name: planebgworker + worker: + container_name: bgworker build: context: ./apiserver dockerfile: Dockerfile.api @@ -55,12 +55,12 @@ services: env_file: - ./apiserver/.env depends_on: - - plane-api + - api - plane-db - plane-redis - plane-beat-worker: - container_name: planebeatworker + beat-worker: + container_name: beatworker build: context: ./apiserver dockerfile: Dockerfile.api @@ -71,7 +71,7 @@ services: env_file: - ./apiserver/.env depends_on: - - plane-api + - api - plane-db - plane-redis @@ -118,8 +118,8 @@ services: - plane-minio # Comment this if you already have a reverse proxy running - plane-proxy: - container_name: planeproxy + proxy: + container_name: proxy build: context: ./nginx dockerfile: Dockerfile @@ -130,8 +130,9 @@ services: FILE_SIZE_LIMIT: ${FILE_SIZE_LIMIT:-5242880} BUCKET_NAME: ${AWS_S3_BUCKET_NAME:-uploads} depends_on: - - plane-web - - plane-api + - web + - api + - space volumes: pgdata: diff --git a/nginx/nginx.conf.template b/nginx/nginx.conf.template index 36a68fa55..4775dcbfa 100644 --- a/nginx/nginx.conf.template +++ b/nginx/nginx.conf.template @@ -1,29 +1,36 @@ -events { } +events { +} http { sendfile on; server { - listen 80; - root /www/data/; + listen 80; + root /www/data/; access_log /var/log/nginx/access.log; client_max_body_size ${FILE_SIZE_LIMIT}; + add_header X-Content-Type-Options "nosniff" always; + add_header Referrer-Policy "no-referrer-when-downgrade" always; + add_header Permissions-Policy "interest-cohort=()" always; + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + location / { - proxy_pass http://planefrontend:3000/; + proxy_pass http://web:3000/; } location /api/ { - proxy_pass http://planebackend:8000/api/; + proxy_pass http://api:8000/api/; } location /spaces/ { - proxy_pass http://planedeploy:3000/spaces/; + rewrite ^/spaces/?$ /spaces/login break; + proxy_pass http://space:3000/spaces/; } location /${BUCKET_NAME}/ { proxy_pass http://plane-minio:9000/uploads/; } } -} \ No newline at end of file +} diff --git a/space/.env.example b/space/.env.example index 56e9f1e95..7700ec946 100644 --- a/space/.env.example +++ b/space/.env.example @@ -1,4 +1,2 @@ -# Google Client ID for Google OAuth -NEXT_PUBLIC_GOOGLE_CLIENTID="" # Flag to toggle OAuth NEXT_PUBLIC_ENABLE_OAUTH=0 \ No newline at end of file diff --git a/space/components/accounts/sign-in.tsx b/space/components/accounts/sign-in.tsx index d3c29103d..c6a151d44 100644 --- a/space/components/accounts/sign-in.tsx +++ b/space/components/accounts/sign-in.tsx @@ -33,7 +33,7 @@ export const SignInView = observer(() => { const onSignInSuccess = (response: any) => { const isOnboarded = response?.user?.onboarding_step?.profile_complete || false; - const nextPath = router.asPath.includes("next_path") ? router.asPath.split("/?next_path=")[1] : "/"; + const nextPath = router.asPath.includes("next_path") ? router.asPath.split("/?next_path=")[1] : "/login"; userStore.setCurrentUser(response?.user); @@ -41,7 +41,7 @@ export const SignInView = observer(() => { router.push(`/onboarding?next_path=${nextPath}`); return; } - router.push((nextPath ?? "/").toString()); + router.push((nextPath ?? "/login").toString()); }; const handleGoogleSignIn = async ({ clientId, credential }: any) => { diff --git a/space/components/views/index.ts b/space/components/views/index.ts index 84d36cd29..f54d11bdd 100644 --- a/space/components/views/index.ts +++ b/space/components/views/index.ts @@ -1 +1 @@ -export * from "./home"; +export * from "./login"; diff --git a/space/components/views/home.tsx b/space/components/views/login.tsx similarity index 88% rename from space/components/views/home.tsx rename to space/components/views/login.tsx index 999fce073..d01a22681 100644 --- a/space/components/views/home.tsx +++ b/space/components/views/login.tsx @@ -4,7 +4,7 @@ import { useMobxStore } from "lib/mobx/store-provider"; // components import { SignInView, UserLoggedIn } from "components/accounts"; -export const HomeView = observer(() => { +export const LoginView = observer(() => { const { user: userStore } = useMobxStore(); if (!userStore.currentUser) return ; diff --git a/space/pages/index.tsx b/space/pages/index.tsx deleted file mode 100644 index fe0b7d33a..000000000 --- a/space/pages/index.tsx +++ /dev/null @@ -1,8 +0,0 @@ -import React from "react"; - -// components -import { HomeView } from "components/views"; - -const HomePage = () => ; - -export default HomePage; diff --git a/space/pages/login/index.tsx b/space/pages/login/index.tsx new file mode 100644 index 000000000..a80eff873 --- /dev/null +++ b/space/pages/login/index.tsx @@ -0,0 +1,8 @@ +import React from "react"; + +// components +import { LoginView } from "components/views"; + +const LoginPage = () => ; + +export default LoginPage; \ No newline at end of file diff --git a/web/.env.example b/web/.env.example index 88a2064c5..3868cd834 100644 --- a/web/.env.example +++ b/web/.env.example @@ -1,24 +1,4 @@ -# Extra image domains that need to be added for Next Image -NEXT_PUBLIC_EXTRA_IMAGE_DOMAINS= -# Google Client ID for Google OAuth -NEXT_PUBLIC_GOOGLE_CLIENTID="" -# GitHub App ID for GitHub OAuth -NEXT_PUBLIC_GITHUB_ID="" -# GitHub App Name for GitHub Integration -NEXT_PUBLIC_GITHUB_APP_NAME="" -# Sentry DSN for error monitoring -NEXT_PUBLIC_SENTRY_DSN="" # Enable/Disable OAUTH - default 0 for selfhosted instance NEXT_PUBLIC_ENABLE_OAUTH=0 -# Enable/Disable Sentry -NEXT_PUBLIC_ENABLE_SENTRY=0 -# Enable/Disable session recording -NEXT_PUBLIC_ENABLE_SESSION_RECORDER=0 -# Enable/Disable event tracking -NEXT_PUBLIC_TRACK_EVENTS=0 -# Slack Client ID for Slack Integration -NEXT_PUBLIC_SLACK_CLIENT_ID="" -# For Telemetry, set it to "app.plane.so" -NEXT_PUBLIC_PLAUSIBLE_DOMAIN="" # Public boards deploy URL -NEXT_PUBLIC_DEPLOY_URL="http://localhost:3000/spaces" \ No newline at end of file +NEXT_PUBLIC_DEPLOY_URL="http://localhost/spaces" \ No newline at end of file diff --git a/web/components/analytics/custom-analytics/graph/index.tsx b/web/components/analytics/custom-analytics/graph/index.tsx index 349f9884d..733d17437 100644 --- a/web/components/analytics/custom-analytics/graph/index.tsx +++ b/web/components/analytics/custom-analytics/graph/index.tsx @@ -9,7 +9,6 @@ import { findStringWithMostCharacters } from "helpers/array.helper"; import { generateBarColor } from "helpers/analytics.helper"; // types import { IAnalyticsParams, IAnalyticsResponse } from "types"; -// constants type Props = { analytics: IAnalyticsResponse; diff --git a/web/components/analytics/scope-and-demand/scope.tsx b/web/components/analytics/scope-and-demand/scope.tsx index b01354b93..9231947bd 100644 --- a/web/components/analytics/scope-and-demand/scope.tsx +++ b/web/components/analytics/scope-and-demand/scope.tsx @@ -15,17 +15,19 @@ export const AnalyticsScope: React.FC = ({ defaultAnalytics }) => (
Pending issues
- {defaultAnalytics.pending_issue_user.length > 0 ? ( + {defaultAnalytics.pending_issue_user && defaultAnalytics.pending_issue_user.length > 0 ? ( `#f97316`} - customYAxisTickValues={defaultAnalytics.pending_issue_user.map((d) => d.count)} + customYAxisTickValues={defaultAnalytics.pending_issue_user.map((d) => + d.count > 0 ? d.count : 50 + )} tooltip={(datum) => { const assignee = defaultAnalytics.pending_issue_user.find( - (a) => a.assignees__display_name === `${datum.indexValue}` + (a) => a.assignees__id === `${datum.indexValue}` ); return ( @@ -39,10 +41,9 @@ export const AnalyticsScope: React.FC = ({ defaultAnalytics }) => ( }} axisBottom={{ renderTick: (datum) => { - const avatar = - defaultAnalytics.pending_issue_user[datum.tickIndex]?.assignees__avatar ?? ""; + const assignee = defaultAnalytics.pending_issue_user[datum.tickIndex] ?? ""; - if (avatar && avatar !== "") + if (assignee && assignee?.assignees__avatar && assignee?.assignees__avatar !== "") return ( = ({ defaultAnalytics }) => ( y={10} width={16} height={16} - xlinkHref={avatar} + xlinkHref={assignee?.assignees__avatar} style={{ clipPath: "circle(50%)" }} /> @@ -60,7 +61,7 @@ export const AnalyticsScope: React.FC = ({ defaultAnalytics }) => ( - {datum.value ? `${datum.value}`.toUpperCase()[0] : "?"} + {datum.value ? `${assignee.assignees__display_name}`.toUpperCase()[0] : "?"} ); diff --git a/web/components/core/activity.tsx b/web/components/core/activity.tsx index 7c2798e7a..d5987384c 100644 --- a/web/components/core/activity.tsx +++ b/web/components/core/activity.tsx @@ -1,15 +1,41 @@ import { useRouter } from "next/router"; +import useSWR from "swr"; + +// hook +import useEstimateOption from "hooks/use-estimate-option"; +// services +import issuesService from "services/issues.service"; // icons import { Icon, Tooltip } from "components/ui"; -import { CopyPlus } from "lucide-react"; -import { Squares2X2Icon } from "@heroicons/react/24/outline"; -import { BlockedIcon, BlockerIcon, RelatedIcon } from "components/icons"; +import { + TagIcon, + CopyPlus, + Calendar, + Link2Icon, + RocketIcon, + Users2Icon, + ArchiveIcon, + PaperclipIcon, + ContrastIcon, + TriangleIcon, + LayoutGridIcon, + SignalMediumIcon, + MessageSquareIcon, +} from "lucide-react"; +import { + BlockedIcon, + BlockerIcon, + RelatedIcon, + StackedLayersHorizontalIcon, +} from "components/icons"; // helpers import { renderShortDateWithYearFormat } from "helpers/date-time.helper"; import { capitalizeFirstLetter } from "helpers/string.helper"; // types import { IIssueActivity } from "types"; +// fetch-keys +import { WORKSPACE_LABELS } from "constants/fetch-keys"; const IssueLink = ({ activity }: { activity: IIssueActivity }) => { const router = useRouter(); @@ -30,7 +56,7 @@ const IssueLink = ({ activity }: { activity: IIssueActivity }) => { {activity.issue_detail ? `${activity.project_detail.identifier}-${activity.issue_detail.sequence_id}` : "Issue"} - + ); @@ -52,6 +78,38 @@ const UserLink = ({ activity }: { activity: IIssueActivity }) => { ); }; +const LabelPill = ({ labelId }: { labelId: string }) => { + const router = useRouter(); + const { workspaceSlug } = router.query; + + const { data: labels } = useSWR( + workspaceSlug ? WORKSPACE_LABELS(workspaceSlug.toString()) : null, + workspaceSlug ? () => issuesService.getWorkspaceLabels(workspaceSlug.toString()) : null + ); + + return ( + l.id === labelId)?.color ?? "#000000", + }} + aria-hidden="true" + /> + ); +}; +const EstimatePoint = ({ point }: { point: string }) => { + const { estimateValue, isEstimateActive } = useEstimateOption(Number(point)); + const currentPoint = Number(point) + 1; + + return ( + + {isEstimateActive + ? estimateValue + : `${currentPoint} ${currentPoint > 1 ? "points" : "point"}`} + + ); +}; + const activityDetails: { [key: string]: { message: ( @@ -91,14 +149,14 @@ const activityDetails: { ); }, - icon:
)} -
-

Issue type

-
- option.key === displayFilters.type - )?.name ?? "Select" - } - className="!w-full" - buttonClassName="w-full" - > - {FILTER_ISSUE_OPTIONS.map((option) => ( - - setDisplayFilters({ - type: option.key, - }) - } - > - {option.name} - - ))} - + {!isArchivedIssues && ( +
+

Issue type

+
+ option.key === displayFilters.type + )?.name ?? "Select" + } + className="!w-full" + buttonClassName="w-full" + > + {FILTER_ISSUE_OPTIONS.map((option) => ( + + setDisplayFilters({ + type: option.key, + }) + } + > + {option.name} + + ))} + +
-
+ )} {displayFilters.layout !== "calendar" && displayFilters.layout !== "spreadsheet" && ( @@ -318,7 +325,7 @@ export const IssuesFilterView: React.FC = () => { displayFilters.layout !== "spreadsheet" && displayFilters.layout !== "gantt_chart" && (
-

Show empty states

+

Show empty groups

; + setFilters: (updatedFilter: Partial) => void; + clearAllFilters: (...args: any) => void; + labels: IIssueLabels[] | undefined; + members: IUserLite[] | undefined; + stateGroup: string[] | undefined; + project?: IProject[] | undefined; +}; + +export const WorkspaceFiltersList: React.FC = ({ + filters, + setFilters, + clearAllFilters, + labels, + members, + stateGroup, + project, +}) => { + if (!filters) return <>; + + const nullFilters = Object.keys(filters).filter( + (key) => filters[key as keyof IWorkspaceIssueFilterOptions] === null + ); + + return ( +
+ {Object.keys(filters).map((filterKey) => { + const key = filterKey as keyof typeof filters; + + if (filters[key] === null || (filters[key]?.length ?? 0) <= 0) return null; + + return ( +
+ + {key === "target_date" ? "Due Date" : replaceUnderscoreIfSnakeCase(key)}: + + {filters[key] === null || (filters[key]?.length ?? 0) <= 0 ? ( + None + ) : Array.isArray(filters[key]) ? ( +
+
+ {key === "state_group" + ? filters.state_group?.map((stateGroup) => { + const group = stateGroup as TStateGroups; + + return ( +

+ + + + {group} + + setFilters({ + state_group: filters.state_group?.filter((g) => g !== group), + }) + } + > + + +

+ ); + }) + : key === "priority" + ? filters.priority?.map((priority: any) => ( +

+ + + + {priority === "null" ? "None" : priority} + + setFilters({ + priority: filters.priority?.filter((p: any) => p !== priority), + }) + } + > + + +

+ )) + : key === "assignees" + ? filters.assignees?.map((memberId: string) => { + const member = members?.find((m) => m.id === memberId); + return ( +
+ + {member?.display_name} + + setFilters({ + assignees: filters.assignees?.filter((p: any) => p !== memberId), + }) + } + > + + +
+ ); + }) + : key === "subscriber" + ? filters.subscriber?.map((memberId: string) => { + const member = members?.find((m) => m.id === memberId); + + return ( +
+ + {member?.display_name} + + setFilters({ + assignees: filters.assignees?.filter((p: any) => p !== memberId), + }) + } + > + + +
+ ); + }) + : key === "created_by" + ? filters.created_by?.map((memberId: string) => { + const member = members?.find((m) => m.id === memberId); + + return ( +
+ + {member?.display_name} + + setFilters({ + created_by: filters.created_by?.filter( + (p: any) => p !== memberId + ), + }) + } + > + + +
+ ); + }) + : key === "labels" + ? filters.labels?.map((labelId: string) => { + const label = labels?.find((l) => l.id === labelId); + + if (!label) return null; + const color = label.color !== "" ? label.color : "#0f172a"; + return ( +
+
+ {label.name} + + setFilters({ + labels: filters.labels?.filter((l: any) => l !== labelId), + }) + } + > + + +
+ ); + }) + : key === "start_date" + ? filters.start_date?.map((date: string) => { + if (filters.start_date && filters.start_date.length <= 0) return null; + + const splitDate = date.split(";"); + + return ( +
+
+ + {splitDate[1]} {renderShortDateWithYearFormat(splitDate[0])} + + + setFilters({ + start_date: filters.start_date?.filter((d: any) => d !== date), + }) + } + > + + +
+ ); + }) + : key === "target_date" + ? filters.target_date?.map((date: string) => { + if (filters.target_date && filters.target_date.length <= 0) return null; + + const splitDate = date.split(";"); + + return ( +
+
+ + {splitDate[1]} {renderShortDateWithYearFormat(splitDate[0])} + + + setFilters({ + target_date: filters.target_date?.filter((d: any) => d !== date), + }) + } + > + + +
+ ); + }) + : key === "project" + ? filters.project?.map((projectId) => { + const currentProject = project?.find((p) => p.id === projectId); + return ( +

+ {currentProject?.name} + + setFilters({ + project: filters.project?.filter((p) => p !== projectId), + }) + } + > + + +

+ ); + }) + : (filters[key] as any)?.join(", ")} + +
+
+ ) : ( +
+ {filters[key as keyof typeof filters]} + +
+ )} +
+ ); + })} + {Object.keys(filters).length > 0 && nullFilters.length !== Object.keys(filters).length && ( + + )} +
+ ); +}; diff --git a/web/components/core/views/all-views.tsx b/web/components/core/views/all-views.tsx index 67804e5e6..75038f57b 100644 --- a/web/components/core/views/all-views.tsx +++ b/web/components/core/views/all-views.tsx @@ -12,6 +12,7 @@ import stateService from "services/state.service"; // hooks import useUser from "hooks/use-user"; import { useProjectMyMembership } from "contexts/project-member.context"; +import useSpreadsheetIssuesView from "hooks/use-spreadsheet-issues-view"; // components import { AllLists, @@ -86,6 +87,8 @@ export const AllViews: React.FC = ({ const { groupedIssues, isEmpty, displayFilters } = viewProps; + const { spreadsheetIssues, mutateIssues } = useSpreadsheetIssuesView(); + const { data: stateGroups } = useSWR( workspaceSlug && projectId ? STATES_LIST(projectId as string) : null, workspaceSlug @@ -174,6 +177,8 @@ export const AllViews: React.FC = ({ ) : displayFilters?.layout === "spreadsheet" ? ( = ({ readOnly={disableUserActions} /> {groupedIssues ? ( -
+
{Object.keys(groupedIssues).map((singleGroup, index) => { const currentState = displayFilters?.group_by === "state" diff --git a/web/components/core/views/board-view/board-header.tsx b/web/components/core/views/board-view/board-header.tsx index 9913ce733..1c2bef60f 100644 --- a/web/components/core/views/board-view/board-header.tsx +++ b/web/components/core/views/board-view/board-header.tsx @@ -20,7 +20,7 @@ import { renderEmoji } from "helpers/emoji.helper"; // types import { IIssueViewProps, IState, TIssuePriorities, TStateGroups } from "types"; // fetch-keys -import { PROJECT_ISSUE_LABELS, PROJECT_MEMBERS } from "constants/fetch-keys"; +import { PROJECT_ISSUE_LABELS, PROJECT_MEMBERS, WORKSPACE_LABELS } from "constants/fetch-keys"; // constants import { STATE_GROUP_COLORS } from "constants/state"; @@ -59,6 +59,15 @@ export const BoardHeader: React.FC = ({ : null ); + const { data: workspaceLabels } = useSWR( + workspaceSlug && displayFilters?.group_by === "labels" + ? WORKSPACE_LABELS(workspaceSlug.toString()) + : null, + workspaceSlug && displayFilters?.group_by === "labels" + ? () => issuesService.getWorkspaceLabels(workspaceSlug.toString()) + : null + ); + const { data: members } = useSWR( workspaceSlug && projectId && @@ -82,7 +91,10 @@ export const BoardHeader: React.FC = ({ title = addSpaceIfCamelCase(currentState?.name ?? ""); break; case "labels": - title = issueLabels?.find((label) => label.id === groupTitle)?.name ?? "None"; + title = + [...(issueLabels ?? []), ...(workspaceLabels ?? [])]?.find( + (label) => label.id === groupTitle + )?.name ?? "None"; break; case "project": title = projects?.find((p) => p.id === groupTitle)?.name ?? "None"; @@ -137,7 +149,9 @@ export const BoardHeader: React.FC = ({ break; case "labels": const labelColor = - issueLabels?.find((label) => label.id === groupTitle)?.color ?? "#000000"; + [...(issueLabels ?? []), ...(workspaceLabels ?? [])]?.find( + (label) => label.id === groupTitle + )?.color ?? "#000000"; icon = ( void; + onSuccess?: (data: IIssue) => Promise | void; + prePopulatedData?: Partial; +}; + +const InlineInput = () => { + const { projectDetails } = useProjectDetails(); + + const { register, setFocus } = useFormContext(); + + useEffect(() => { + setFocus("name"); + }, [setFocus]); + + return ( +
+

+ {projectDetails?.identifier ?? "..."} +

+ +
+ ); +}; + +export const BoardInlineCreateIssueForm: React.FC = (props) => ( + <> + + + + {props.isOpen && ( +

+ Press {"'"}Enter{"'"} to add another issue +

+ )} + +); diff --git a/web/components/core/views/board-view/single-board.tsx b/web/components/core/views/board-view/single-board.tsx index 1981e1f7c..bdbfc27c2 100644 --- a/web/components/core/views/board-view/single-board.tsx +++ b/web/components/core/views/board-view/single-board.tsx @@ -6,7 +6,7 @@ import { useRouter } from "next/router"; import StrictModeDroppable from "components/dnd/StrictModeDroppable"; import { Draggable } from "react-beautiful-dnd"; // components -import { BoardHeader, SingleBoardIssue } from "components/core"; +import { BoardHeader, SingleBoardIssue, BoardInlineCreateIssueForm } from "components/core"; // ui import { CustomMenu } from "components/ui"; // icons @@ -34,31 +34,39 @@ type Props = { viewProps: IIssueViewProps; }; -export const SingleBoard: React.FC = ({ - addIssueToGroup, - currentState, - groupTitle, - disableUserActions, - disableAddIssueOption = false, - dragDisabled, - handleIssueAction, - handleDraftIssueAction, - handleTrashBox, - openIssuesListModal, - handleMyIssueOpen, - removeIssue, - user, - userAuth, - viewProps, -}) => { +export const SingleBoard: React.FC = (props) => { + const { + addIssueToGroup, + currentState, + groupTitle, + disableUserActions, + disableAddIssueOption = false, + dragDisabled, + handleIssueAction, + handleDraftIssueAction, + handleTrashBox, + openIssuesListModal, + handleMyIssueOpen, + removeIssue, + user, + userAuth, + viewProps, + } = props; + // collapse/expand const [isCollapsed, setIsCollapsed] = useState(true); + const [isInlineCreateIssueFormOpen, setIsInlineCreateIssueFormOpen] = useState(false); + const { displayFilters, groupedIssues } = viewProps; const router = useRouter(); const { cycleId, moduleId } = router.query; + const isMyIssuesPage = router.pathname.split("/")[3] === "my-issues"; + const isProfileIssuesPage = router.pathname.split("/")[2] === "profile"; + const isDraftIssuesPage = router.pathname.split("/")[4] === "draft-issues"; + const type = cycleId ? "cycle" : moduleId ? "module" : "issue"; // Check if it has at least 4 tickets since it is enough to accommodate the Calendar height @@ -67,6 +75,27 @@ export const SingleBoard: React.FC = ({ const isNotAllowed = userAuth.isGuest || userAuth.isViewer || disableUserActions; + const scrollToBottom = () => { + const boardListElement = document.getElementById(`board-list-${groupTitle}`); + + // timeout is needed because the animation + // takes time to complete & we can scroll only after that + const timeoutId = setTimeout(() => { + if (boardListElement) + boardListElement.scrollBy({ + top: boardListElement.scrollHeight, + left: 0, + behavior: "smooth", + }); + clearTimeout(timeoutId); + }, 10); + }; + + const onCreateClick = () => { + setIsInlineCreateIssueFormOpen(true); + scrollToBottom(); + }; + return (
= ({ )}
= ({ type={type} index={index} issue={issue} + projectId={issue.project_detail.id} groupTitle={groupTitle} editIssue={() => handleIssueAction(issue, "edit")} makeIssueCopy={() => handleIssueAction(issue, "copy")} @@ -169,6 +200,20 @@ export const SingleBoard: React.FC = ({ > <>{provided.placeholder} + + setIsInlineCreateIssueFormOpen(false)} + onSuccess={() => scrollToBottom()} + prePopulatedData={{ + ...(cycleId && { cycle: cycleId.toString() }), + ...(moduleId && { module: moduleId.toString() }), + [displayFilters?.group_by! === "labels" + ? "labels_list" + : displayFilters?.group_by!]: + displayFilters?.group_by === "labels" ? [groupTitle] : groupTitle, + }} + />
{displayFilters?.group_by !== "created_by" && (
@@ -177,7 +222,11 @@ export const SingleBoard: React.FC = ({ + ))}
- +
+ {MONTHS_LIST.map((month) => ( + + ))} +
+ + + + )} + - - -
- {YEARS_LIST.map((year) => ( - - ))} -
-
- {MONTHS_LIST.map((month) => ( - - ))} -
-
-
- - )} - - -
- - -
-
- -
+
+
- } + const nextMonthFirstDate = new Date(nextMonthYear, nextMonthMonth, 1); + + setCurrentDate(nextMonthFirstDate); + }} > - { - setIsMonthlyView(true); - changeDateRange(startOfWeek(currentDate), lastDayOfWeek(currentDate)); - }} - className="w-52 text-sm text-custom-text-200" - > -
- Monthly View - -
-
- { - setIsMonthlyView(false); - changeDateRange( - getCurrentWeekStartDate(currentDate), - getCurrentWeekEndDate(currentDate) - ); - }} - className="w-52 text-sm text-custom-text-200" - > -
- Weekly View - -
-
-
-

Show weekends

- setShowWeekEnds(!showWeekEnds)} /> -
- + +
- ); -}; + +
+ + + + Options +
+ } + > +
+

Show weekends

+ setShowWeekEnds(!showWeekEnds)} /> +
+ +
+
+); export default CalendarHeader; diff --git a/web/components/core/views/calendar-view/calendar.tsx b/web/components/core/views/calendar-view/calendar.tsx index 030f8b747..7758f64cd 100644 --- a/web/components/core/views/calendar-view/calendar.tsx +++ b/web/components/core/views/calendar-view/calendar.tsx @@ -1,10 +1,6 @@ import React, { useEffect, useState } from "react"; - import { useRouter } from "next/router"; - import { mutate } from "swr"; - -// react-beautiful-dnd import { DragDropContext, DropResult } from "react-beautiful-dnd"; // services import issuesService from "services/issues.service"; @@ -50,31 +46,27 @@ export const CalendarView: React.FC = ({ userAuth, }) => { const [showWeekEnds, setShowWeekEnds] = useState(false); - const [currentDate, setCurrentDate] = useState(new Date()); - const [isMonthlyView, setIsMonthlyView] = useState(true); + + const { calendarIssues, mutateIssues, params, activeMonthDate, setActiveMonthDate } = + useCalendarIssuesView(); const [calendarDates, setCalendarDates] = useState({ - startDate: startOfWeek(currentDate), - endDate: lastDayOfWeek(currentDate), + startDate: startOfWeek(activeMonthDate), + endDate: lastDayOfWeek(activeMonthDate), }); const router = useRouter(); const { workspaceSlug, projectId, cycleId, moduleId, viewId } = router.query; - const { calendarIssues, mutateIssues, params, displayFilters, setDisplayFilters } = - useCalendarIssuesView(); - - const totalDate = eachDayOfInterval({ - start: calendarDates.startDate, - end: calendarDates.endDate, - }); - - const onlyWeekDays = weekDayInterval({ - start: calendarDates.startDate, - end: calendarDates.endDate, - }); - - const currentViewDays = showWeekEnds ? totalDate : onlyWeekDays; + const currentViewDays = showWeekEnds + ? eachDayOfInterval({ + start: calendarDates.startDate, + end: calendarDates.endDate, + }) + : weekDayInterval({ + start: calendarDates.startDate, + end: calendarDates.endDate, + }); const currentViewDaysData = currentViewDays.map((date: Date) => { const filterIssue = @@ -148,27 +140,12 @@ export const CalendarView: React.FC = ({ .then(() => mutate(fetchKey)); }; - const changeDateRange = (startDate: Date, endDate: Date) => { - setCalendarDates({ - startDate, - endDate, - }); - - setDisplayFilters({ - calendar_date_range: `${renderDateFormat(startDate)};after,${renderDateFormat( - endDate - )};before`, - }); - }; - useEffect(() => { - if (!displayFilters || displayFilters.calendar_date_range === "") - setDisplayFilters({ - calendar_date_range: `${renderDateFormat( - startOfWeek(currentDate) - )};after,${renderDateFormat(lastDayOfWeek(currentDate))};before`, - }); - }, [currentDate, displayFilters, setDisplayFilters]); + setCalendarDates({ + startDate: startOfWeek(activeMonthDate), + endDate: lastDayOfWeek(activeMonthDate), + }); + }, [activeMonthDate]); const isNotAllowed = userAuth.isGuest || userAuth.isViewer || disableUserActions; @@ -183,15 +160,15 @@ export const CalendarView: React.FC = ({ {calendarIssues ? (
-
+
= ({ {weeks.map((date, index) => (
- - {isMonthlyView - ? formatDate(date, "eee").substring(0, 3) - : formatDate(date, "eee")} - - {!isMonthlyView && {formatDate(date, "d")}} + {formatDate(date, "eee").substring(0, 3)}
))}
@@ -236,7 +198,6 @@ export const CalendarView: React.FC = ({ date={date} handleIssueAction={handleIssueAction} addIssueToDate={addIssueToDate} - isMonthlyView={isMonthlyView} showWeekEnds={showWeekEnds} user={user} isNotAllowed={isNotAllowed} diff --git a/web/components/core/views/calendar-view/index.ts b/web/components/core/views/calendar-view/index.ts index 625ff1fb4..75d8a3a1e 100644 --- a/web/components/core/views/calendar-view/index.ts +++ b/web/components/core/views/calendar-view/index.ts @@ -2,3 +2,4 @@ export * from "./calendar-header"; export * from "./calendar"; export * from "./single-date"; export * from "./single-issue"; +export * from "./inline-create-issue-form"; diff --git a/web/components/core/views/calendar-view/inline-create-issue-form.tsx b/web/components/core/views/calendar-view/inline-create-issue-form.tsx new file mode 100644 index 000000000..51b6c518b --- /dev/null +++ b/web/components/core/views/calendar-view/inline-create-issue-form.tsx @@ -0,0 +1,102 @@ +import { useEffect, useRef, useState } from "react"; + +// next +import { useRouter } from "next/router"; + +// react hook form +import { useFormContext } from "react-hook-form"; + +import { InlineCreateIssueFormWrapper } from "components/core"; + +// hooks +import useProjectDetails from "hooks/use-project-details"; + +// types +import { IIssue } from "types"; + +type Props = { + isOpen: boolean; + handleClose: () => void; + onSuccess?: (data: IIssue) => Promise | void; + prePopulatedData?: Partial; + dependencies: any[]; +}; + +const useCheckIfThereIsSpaceOnRight = (ref: React.RefObject, deps: any[]) => { + const [isThereSpaceOnRight, setIsThereSpaceOnRight] = useState(true); + + const router = useRouter(); + const { moduleId, cycleId, viewId } = router.query; + + const container = document.getElementById(`calendar-view-${cycleId ?? moduleId ?? viewId}`); + + useEffect(() => { + if (!ref.current) return; + + const { right } = ref.current.getBoundingClientRect(); + + const width = right; + + const innerWidth = container?.getBoundingClientRect().width ?? window.innerWidth; + + if (width > innerWidth) setIsThereSpaceOnRight(false); + else setIsThereSpaceOnRight(true); + }, [ref, deps, container]); + + return isThereSpaceOnRight; +}; + +const InlineInput = () => { + const { projectDetails } = useProjectDetails(); + + const { register, setFocus } = useFormContext(); + + useEffect(() => { + setFocus("name"); + }, [setFocus]); + + return ( + <> +

+ {projectDetails?.identifier ?? "..."} +

+ + + ); +}; + +export const CalendarInlineCreateIssueForm: React.FC = (props) => { + const { isOpen, dependencies } = props; + + const ref = useRef(null); + + const isSpaceOnRight = useCheckIfThereIsSpaceOnRight(ref, dependencies); + + return ( + <> +
+ + + +
+ {/* Added to make any other element as outside click. This will make input also to be outside. */} + {isOpen &&
} + + ); +}; diff --git a/web/components/core/views/calendar-view/single-date.tsx b/web/components/core/views/calendar-view/single-date.tsx index ae1c018aa..a67ca762b 100644 --- a/web/components/core/views/calendar-view/single-date.tsx +++ b/web/components/core/views/calendar-view/single-date.tsx @@ -1,10 +1,14 @@ import React, { useState } from "react"; +// next +import { useRouter } from "next/router"; + // react-beautiful-dnd import { Draggable } from "react-beautiful-dnd"; // component import StrictModeDroppable from "components/dnd/StrictModeDroppable"; import { SingleCalendarIssue } from "./single-issue"; +import { CalendarInlineCreateIssueForm } from "./inline-create-issue-form"; // icons import { PlusSmallIcon } from "@heroicons/react/24/outline"; // helper @@ -20,23 +24,21 @@ type Props = { issues: IIssue[]; }; addIssueToDate: (date: string) => void; - isMonthlyView: boolean; showWeekEnds: boolean; user: ICurrentUserResponse | undefined; isNotAllowed: boolean; }; -export const SingleCalendarDate: React.FC = ({ - handleIssueAction, - date, - index, - addIssueToDate, - isMonthlyView, - showWeekEnds, - user, - isNotAllowed, -}) => { +export const SingleCalendarDate: React.FC = (props) => { + const { handleIssueAction, date, index, showWeekEnds, user, isNotAllowed } = props; + + const router = useRouter(); + const { cycleId, moduleId } = router.query; + const [showAllIssues, setShowAllIssues] = useState(false); + const [isCreateIssueFormOpen, setIsCreateIssueFormOpen] = useState(false); + + const [formPosition, setFormPosition] = useState({ x: 0, y: 0 }); const totalIssues = date.issues.length; @@ -48,8 +50,6 @@ export const SingleCalendarDate: React.FC = ({ ref={provided.innerRef} {...provided.droppableProps} className={`group relative flex min-h-[150px] flex-col gap-1.5 border-t border-custom-border-200 p-2.5 text-left text-sm font-medium hover:bg-custom-background-90 ${ - isMonthlyView ? "" : "pt-9" - } ${ showWeekEnds ? (index + 1) % 7 === 0 ? "" @@ -59,48 +59,66 @@ export const SingleCalendarDate: React.FC = ({ : "border-r" }`} > - {isMonthlyView && {formatDate(new Date(date.date), "d")}} - {totalIssues > 0 && - date.issues.slice(0, showAllIssues ? totalIssues : 4).map((issue: IIssue, index) => ( - - {(provided, snapshot) => ( - handleIssueAction(issue, "edit")} - handleDeleteIssue={() => handleIssueAction(issue, "delete")} - user={user} - isNotAllowed={isNotAllowed} - /> - )} - - ))} - {totalIssues > 4 && ( - - )} + <> + {formatDate(new Date(date.date), "d")} + {totalIssues > 0 && + date.issues.slice(0, showAllIssues ? totalIssues : 4).map((issue: IIssue, index) => ( + + {(provided, snapshot) => ( + handleIssueAction(issue, "edit")} + handleDeleteIssue={() => handleIssueAction(issue, "delete")} + user={user} + isNotAllowed={isNotAllowed} + /> + )} + + ))} -
- -
+ setIsCreateIssueFormOpen(false)} + prePopulatedData={{ + target_date: date.date, + ...(cycleId && { cycle: cycleId.toString() }), + ...(moduleId && { module: moduleId.toString() }), + }} + /> - {provided.placeholder} + {totalIssues > 4 && ( + + )} + +
+ +
+ + {provided.placeholder} +
)} diff --git a/web/components/core/views/calendar-view/single-issue.tsx b/web/components/core/views/calendar-view/single-issue.tsx index 81d6f631f..e0e9aa2a5 100644 --- a/web/components/core/views/calendar-view/single-issue.tsx +++ b/web/components/core/views/calendar-view/single-issue.tsx @@ -41,6 +41,7 @@ type Props = { provided: DraggableProvided; snapshot: DraggableStateSnapshot; issue: IIssue; + projectId: string; user: ICurrentUserResponse | undefined; isNotAllowed: boolean; }; @@ -52,11 +53,12 @@ export const SingleCalendarIssue: React.FC = ({ provided, snapshot, issue, + projectId, user, isNotAllowed, }) => { const router = useRouter(); - const { workspaceSlug, projectId, cycleId, moduleId, viewId } = router.query; + const { workspaceSlug, cycleId, moduleId, viewId } = router.query; const { setToastAlert } = useToast(); @@ -310,6 +312,7 @@ export const SingleCalendarIssue: React.FC = ({ {properties.state && ( = ({ {properties.labels && issue.labels.length > 0 && ( = ({ {properties.assignee && ( void; + onSuccess?: (data: IIssue) => Promise | void; + prePopulatedData?: Partial; +}; + +const InlineInput = () => { + const { projectDetails } = useProjectDetails(); + + const { register, setFocus } = useFormContext(); + + useEffect(() => { + setFocus("name"); + }, [setFocus]); + + return ( + <> +
+

{projectDetails?.identifier ?? "..."}

+ + + ); +}; + +export const GanttInlineCreateIssueForm: React.FC = (props) => ( + <> + + + + {props.isOpen && ( +

+ Press {"'"}Enter{"'"} to add another issue +

+ )} + +); diff --git a/web/components/core/views/index.ts b/web/components/core/views/index.ts index 8b2dc87cb..13da90d8e 100644 --- a/web/components/core/views/index.ts +++ b/web/components/core/views/index.ts @@ -5,3 +5,4 @@ export * from "./list-view"; export * from "./spreadsheet-view"; export * from "./all-views"; export * from "./issues-view"; +export * from "./inline-issue-create-wrapper"; diff --git a/web/components/core/views/inline-issue-create-wrapper.tsx b/web/components/core/views/inline-issue-create-wrapper.tsx new file mode 100644 index 000000000..ec5d8e79e --- /dev/null +++ b/web/components/core/views/inline-issue-create-wrapper.tsx @@ -0,0 +1,273 @@ +import { useEffect, useRef } from "react"; + +// next +import { useRouter } from "next/router"; + +// swr +import { mutate } from "swr"; + +// react hook form +import { useForm, FormProvider } from "react-hook-form"; + +// headless ui +import { Transition } from "@headlessui/react"; + +// services +import modulesService from "services/modules.service"; +import issuesService from "services/issues.service"; + +// hooks +import useToast from "hooks/use-toast"; +import useUser from "hooks/use-user"; +import useKeypress from "hooks/use-keypress"; +import useIssuesView from "hooks/use-issues-view"; +import useMyIssues from "hooks/my-issues/use-my-issues"; +import useGanttChartIssues from "hooks/gantt-chart/issue-view"; +import useCalendarIssuesView from "hooks/use-calendar-issues-view"; +import useOutsideClickDetector from "hooks/use-outside-click-detector"; +import useSpreadsheetIssuesView from "hooks/use-spreadsheet-issues-view"; + +// helpers +import { getFetchKeysForIssueMutation } from "helpers/string.helper"; + +// fetch-keys +import { + USER_ISSUE, + SUB_ISSUES, + CYCLE_ISSUES_WITH_PARAMS, + MODULE_ISSUES_WITH_PARAMS, + CYCLE_DETAILS, + MODULE_DETAILS, + PROJECT_ISSUES_LIST_WITH_PARAMS, + PROJECT_DRAFT_ISSUES_LIST_WITH_PARAMS, +} from "constants/fetch-keys"; + +// types +import { IIssue } from "types"; + +const defaultValues: Partial = { + name: "", +}; + +type Props = { + isOpen: boolean; + handleClose: () => void; + onSuccess?: (data: IIssue) => Promise | void; + prePopulatedData?: Partial; + className?: string; + children?: React.ReactNode; +}; + +export const addIssueToCycle = async ( + workspaceSlug: string, + projectId: string, + issueId: string, + cycleId: string, + user: any, + params: any +) => { + if (!workspaceSlug || !projectId) return; + + await issuesService + .addIssueToCycle( + workspaceSlug as string, + projectId.toString(), + cycleId, + { + issues: [issueId], + }, + user + ) + .then(() => { + if (cycleId) { + mutate(CYCLE_ISSUES_WITH_PARAMS(cycleId, params)); + mutate(CYCLE_DETAILS(cycleId as string)); + } + }); +}; + +export const addIssueToModule = async ( + workspaceSlug: string, + projectId: string, + issueId: string, + moduleId: string, + user: any, + params: any +) => { + await modulesService + .addIssuesToModule( + workspaceSlug as string, + projectId.toString(), + moduleId as string, + { + issues: [issueId], + }, + user + ) + .then(() => { + if (moduleId) { + mutate(MODULE_ISSUES_WITH_PARAMS(moduleId as string, params)); + mutate(MODULE_DETAILS(moduleId as string)); + } + }); +}; + +export const InlineCreateIssueFormWrapper: React.FC = (props) => { + const { isOpen, handleClose, onSuccess, prePopulatedData, children, className } = props; + + const ref = useRef(null); + + const router = useRouter(); + const { workspaceSlug, projectId, cycleId, moduleId, viewId } = router.query; + + const isDraftIssues = router.pathname?.split("/")?.[4] === "draft-issues"; + + const { user } = useUser(); + + const { setToastAlert } = useToast(); + + const { displayFilters, params } = useIssuesView(); + const { params: calendarParams } = useCalendarIssuesView(); + const { ...viewGanttParams } = params; + const { params: spreadsheetParams } = useSpreadsheetIssuesView(); + const { groupedIssues, mutateMyIssues } = useMyIssues(workspaceSlug?.toString()); + const { params: ganttParams } = useGanttChartIssues( + workspaceSlug?.toString(), + projectId?.toString() + ); + + const method = useForm({ defaultValues }); + const { + reset, + handleSubmit, + getValues, + formState: { errors, isSubmitting }, + } = method; + + useOutsideClickDetector(ref, handleClose); + useKeypress("Escape", handleClose); + + useEffect(() => { + const values = getValues(); + + if (prePopulatedData) reset({ ...defaultValues, ...values, ...prePopulatedData }); + }, [reset, prePopulatedData, getValues]); + + useEffect(() => { + if (!isOpen) reset({ ...defaultValues }); + }, [isOpen, reset]); + + useEffect(() => { + if (!errors) return; + + Object.keys(errors).forEach((key) => { + const error = errors[key as keyof IIssue]; + + setToastAlert({ + type: "error", + title: "Error!", + message: error?.message?.toString() || "Some error occurred. Please try again.", + }); + }); + }, [errors, setToastAlert]); + + const { calendarFetchKey, ganttFetchKey, spreadsheetFetchKey } = getFetchKeysForIssueMutation({ + cycleId: cycleId, + moduleId: moduleId, + viewId: viewId, + projectId: projectId?.toString() ?? "", + calendarParams, + spreadsheetParams, + viewGanttParams, + ganttParams, + }); + + const onSubmitHandler = async (formData: IIssue) => { + if (!workspaceSlug || !projectId || !user || isSubmitting) return; + + reset({ ...defaultValues }); + + await (!isDraftIssues + ? issuesService.createIssues(workspaceSlug.toString(), projectId.toString(), formData, user) + : issuesService.createDraftIssue( + workspaceSlug.toString(), + projectId.toString(), + formData, + user + ) + ) + .then(async (res) => { + await mutate(PROJECT_ISSUES_LIST_WITH_PARAMS(projectId.toString(), params)); + if (formData.cycle && formData.cycle !== "") + await addIssueToCycle( + workspaceSlug.toString(), + projectId.toString(), + res.id, + formData.cycle, + user, + params + ); + if (formData.module && formData.module !== "") + await addIssueToModule( + workspaceSlug.toString(), + projectId.toString(), + res.id, + formData.module, + user, + params + ); + + if (isDraftIssues) + await mutate(PROJECT_DRAFT_ISSUES_LIST_WITH_PARAMS(projectId.toString() ?? "", params)); + if (displayFilters.layout === "calendar") await mutate(calendarFetchKey); + if (displayFilters.layout === "gantt_chart") await mutate(ganttFetchKey); + if (displayFilters.layout === "spreadsheet") await mutate(spreadsheetFetchKey); + if (groupedIssues) await mutateMyIssues(); + + setToastAlert({ + type: "success", + title: "Success!", + message: "Issue created successfully.", + }); + + if (onSuccess) await onSuccess(res); + + if (formData.assignees_list?.some((assignee) => assignee === user?.id)) + mutate(USER_ISSUE(workspaceSlug as string)); + + if (formData.parent && formData.parent !== "") mutate(SUB_ISSUES(formData.parent)); + }) + .catch((err) => { + Object.keys(err || {}).forEach((key) => { + const error = err?.[key]; + const errorTitle = error ? (Array.isArray(error) ? error.join(", ") : error) : null; + + setToastAlert({ + type: "error", + title: "Error!", + message: errorTitle || "Some error occurred. Please try again.", + }); + }); + }); + }; + + return ( + <> + + +
+ {children} +
+
+
+ + ); +}; diff --git a/web/components/core/views/issues-view.tsx b/web/components/core/views/issues-view.tsx index 9a2d482fa..3c123c2ac 100644 --- a/web/components/core/views/issues-view.tsx +++ b/web/components/core/views/issues-view.tsx @@ -81,7 +81,9 @@ export const IssuesView: React.FC = ({ const router = useRouter(); const { workspaceSlug, projectId, cycleId, moduleId, viewId } = router.query; - const isDraftIssues = router.asPath.includes("draft-issues"); + + const isDraftIssues = router.pathname?.split("/")?.[4] === "draft-issues"; + const isArchivedIssues = router.pathname?.split("/")?.[4] === "archived-issues"; const { user } = useUserAuth(); @@ -624,6 +626,7 @@ export const IssuesView: React.FC = ({ params, properties, }} + disableAddIssueOption={isArchivedIssues} /> ); diff --git a/web/components/core/views/list-view/index.ts b/web/components/core/views/list-view/index.ts index c515ed1c2..4d59be165 100644 --- a/web/components/core/views/list-view/index.ts +++ b/web/components/core/views/list-view/index.ts @@ -1,3 +1,4 @@ export * from "./all-lists"; export * from "./single-issue"; export * from "./single-list"; +export * from "./inline-create-issue-form"; diff --git a/web/components/core/views/list-view/inline-create-issue-form.tsx b/web/components/core/views/list-view/inline-create-issue-form.tsx new file mode 100644 index 000000000..b61420fc8 --- /dev/null +++ b/web/components/core/views/list-view/inline-create-issue-form.tsx @@ -0,0 +1,62 @@ +import { useEffect } from "react"; +// react hook form +import { useFormContext } from "react-hook-form"; + +// hooks +import useProjectDetails from "hooks/use-project-details"; + +// components +import { InlineCreateIssueFormWrapper } from "../inline-issue-create-wrapper"; + +// types +import { IIssue } from "types"; + +type Props = { + isOpen: boolean; + handleClose: () => void; + onSuccess?: (data: IIssue) => Promise | void; + prePopulatedData?: Partial; +}; + +const InlineInput = () => { + const { projectDetails } = useProjectDetails(); + + const { register, setFocus } = useFormContext(); + + useEffect(() => { + setFocus("name"); + }, [setFocus]); + + return ( + <> +

+ {projectDetails?.identifier ?? "..."} +

+ + + ); +}; + +export const ListInlineCreateIssueForm: React.FC = (props) => ( + <> + + + + {props.isOpen && ( +

+ Press {"'"}Enter{"'"} to add another issue +

+ )} + +); diff --git a/web/components/core/views/list-view/single-issue.tsx b/web/components/core/views/list-view/single-issue.tsx index 5c2eadf0a..7fa54b852 100644 --- a/web/components/core/views/list-view/single-issue.tsx +++ b/web/components/core/views/list-view/single-issue.tsx @@ -51,6 +51,7 @@ import { type Props = { type?: string; issue: IIssue; + projectId: string; groupTitle?: string; editIssue: () => void; index: number; @@ -69,6 +70,7 @@ type Props = { export const SingleListIssue: React.FC = ({ type, issue, + projectId, editIssue, index, makeIssueCopy, @@ -88,7 +90,7 @@ export const SingleListIssue: React.FC = ({ const [contextMenuPosition, setContextMenuPosition] = useState(null); const router = useRouter(); - const { workspaceSlug, projectId, cycleId, moduleId, userId } = router.query; + const { workspaceSlug, cycleId, moduleId, userId } = router.query; const isArchivedIssues = router.pathname.includes("archived-issues"); const isDraftIssues = router.pathname?.split("/")?.[4] === "draft-issues"; @@ -326,7 +328,7 @@ export const SingleListIssue: React.FC = ({
{ e.preventDefault(); setContextMenu(true); @@ -350,6 +352,7 @@ export const SingleListIssue: React.FC = ({ type="button" className="truncate text-[0.825rem] text-custom-text-100" onClick={() => { + if (isArchivedIssues) return router.push(issuePath); if (!isDraftIssues) openPeekOverview(issue); if (isDraftIssues && handleDraftIssueSelect) handleDraftIssueSelect(issue); }} @@ -376,6 +379,7 @@ export const SingleListIssue: React.FC = ({ {properties.state && ( = ({ {properties.labels && ( = ({ {properties.assignee && ( = ({ - currentState, - groupTitle, - addIssueToGroup, - handleIssueAction, - openIssuesListModal, - handleDraftIssueAction, - handleMyIssueOpen, - removeIssue, - disableUserActions, - disableAddIssueOption = false, - user, - userAuth, - viewProps, -}) => { +export const SingleList: React.FC = (props) => { + const { + currentState, + groupTitle, + handleIssueAction, + openIssuesListModal, + handleDraftIssueAction, + handleMyIssueOpen, + addIssueToGroup, + removeIssue, + disableUserActions, + disableAddIssueOption = false, + user, + userAuth, + viewProps, + } = props; + const router = useRouter(); const { workspaceSlug, projectId, cycleId, moduleId } = router.query; + const [isCreateIssueFormOpen, setIsCreateIssueFormOpen] = useState(false); + + const isMyIssuesPage = router.pathname.split("/")[3] === "my-issues"; + const isProfileIssuesPage = router.pathname.split("/")[2] === "profile"; + const isDraftIssuesPage = router.pathname.split("/")[4] === "draft-issues"; + const isArchivedIssues = router.pathname.includes("archived-issues"); const type = cycleId ? "cycle" : moduleId ? "module" : "issue"; const { displayFilters, groupedIssues } = viewProps; - const { data: issueLabels } = useSWR( - workspaceSlug && projectId ? PROJECT_ISSUE_LABELS(projectId as string) : null, - workspaceSlug && projectId - ? () => issuesService.getIssueLabels(workspaceSlug as string, projectId as string) + const { data: issueLabels } = useSWR( + workspaceSlug && projectId && displayFilters?.group_by === "labels" + ? PROJECT_ISSUE_LABELS(projectId.toString()) + : null, + workspaceSlug && projectId && displayFilters?.group_by === "labels" + ? () => issuesService.getIssueLabels(workspaceSlug.toString(), projectId.toString()) + : null + ); + + const { data: workspaceLabels } = useSWR( + workspaceSlug && displayFilters?.group_by === "labels" + ? WORKSPACE_LABELS(workspaceSlug.toString()) + : null, + workspaceSlug && displayFilters?.group_by === "labels" + ? () => issuesService.getWorkspaceLabels(workspaceSlug.toString()) : null ); const { data: members } = useSWR( - workspaceSlug && projectId ? PROJECT_MEMBERS(projectId as string) : null, - workspaceSlug && projectId + workspaceSlug && + projectId && + (displayFilters?.group_by === "created_by" || displayFilters?.group_by === "assignees") + ? PROJECT_MEMBERS(projectId as string) + : null, + workspaceSlug && + projectId && + (displayFilters?.group_by === "created_by" || displayFilters?.group_by === "assignees") ? () => projectService.projectMembers(workspaceSlug as string, projectId as string) : null ); @@ -99,7 +127,10 @@ export const SingleList: React.FC = ({ title = addSpaceIfCamelCase(currentState?.name ?? ""); break; case "labels": - title = issueLabels?.find((label) => label.id === groupTitle)?.name ?? "None"; + title = + [...(issueLabels ?? []), ...(workspaceLabels ?? [])]?.find( + (label) => label.id === groupTitle + )?.name ?? "None"; break; case "project": title = projects?.find((p) => p.id === groupTitle)?.name ?? "None"; @@ -153,7 +184,9 @@ export const SingleList: React.FC = ({ break; case "labels": const labelColor = - issueLabels?.find((label) => label.id === groupTitle)?.color ?? "#000000"; + [...(issueLabels ?? []), ...(workspaceLabels ?? [])]?.find( + (label) => label.id === groupTitle + )?.color ?? "#000000"; icon = ( = ({ !disableAddIssueOption && ( @@ -224,7 +261,9 @@ export const SingleList: React.FC = ({ position="right" noBorder > - Create new + setIsCreateIssueFormOpen(true)}> + Create new + {openIssuesListModal && ( Add an existing issue @@ -250,6 +289,7 @@ export const SingleList: React.FC = ({ key={issue.id} type={type} issue={issue} + projectId={issue.project_detail.id} groupTitle={groupTitle} index={index} editIssue={() => handleIssueAction(issue, "edit")} @@ -284,6 +324,34 @@ export const SingleList: React.FC = ({ ) : (
Loading...
)} + + setIsCreateIssueFormOpen(false)} + prePopulatedData={{ + ...(cycleId && { cycle: cycleId.toString() }), + ...(moduleId && { module: moduleId.toString() }), + [displayFilters?.group_by!]: groupTitle, + }} + /> + + {!disableAddIssueOption && !isCreateIssueFormOpen && ( + // TODO: add border here +
+ +
+ )}
diff --git a/web/components/core/views/spreadsheet-view/assignee-column/assignee-column.tsx b/web/components/core/views/spreadsheet-view/assignee-column/assignee-column.tsx new file mode 100644 index 000000000..745083d5f --- /dev/null +++ b/web/components/core/views/spreadsheet-view/assignee-column/assignee-column.tsx @@ -0,0 +1,72 @@ +import React from "react"; + +import { useRouter } from "next/router"; + +// components +import { MembersSelect } from "components/project"; +// services +import trackEventServices from "services/track-event.service"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const AssigneeColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + properties, + user, + isNotAllowed, +}) => { + const router = useRouter(); + + const { workspaceSlug } = router.query; + + const handleAssigneeChange = (data: any) => { + const newData = issue.assignees ?? []; + + if (newData.includes(data)) newData.splice(newData.indexOf(data), 1); + else newData.push(data); + + partialUpdateIssue({ assignees_list: data }, issue); + + trackEventServices.trackIssuePartialPropertyUpdateEvent( + { + workspaceSlug, + workspaceId: issue.workspace, + projectId: issue.project_detail.id, + projectIdentifier: issue.project_detail.identifier, + projectName: issue.project_detail.name, + issueId: issue.id, + }, + "ISSUE_PROPERTY_UPDATE_ASSIGNEE", + user + ); + }; + + return ( +
+ + {properties.assignee && ( + + )} + +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/assignee-column/index.ts b/web/components/core/views/spreadsheet-view/assignee-column/index.ts new file mode 100644 index 000000000..8750550be --- /dev/null +++ b/web/components/core/views/spreadsheet-view/assignee-column/index.ts @@ -0,0 +1,2 @@ +export * from "./spreadsheet-assignee-column"; +export * from "./assignee-column"; diff --git a/web/components/core/views/spreadsheet-view/assignee-column/spreadsheet-assignee-column.tsx b/web/components/core/views/spreadsheet-view/assignee-column/spreadsheet-assignee-column.tsx new file mode 100644 index 000000000..a864126c6 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/assignee-column/spreadsheet-assignee-column.tsx @@ -0,0 +1,62 @@ +import React from "react"; + +// components +import { AssigneeColumn } from "components/core"; +// hooks +import useSubIssue from "hooks/use-sub-issue"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + expandedIssues: string[]; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const SpreadsheetAssigneeColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + expandedIssues, + properties, + user, + isNotAllowed, +}) => { + const isExpanded = expandedIssues.indexOf(issue.id) > -1; + + const { subIssues, isLoading } = useSubIssue(issue.project_detail.id, issue.id, isExpanded); + + return ( +
+ + + {isExpanded && + !isLoading && + subIssues && + subIssues.length > 0 && + subIssues.map((subIssue: IIssue) => ( + + ))} +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/created-on-column/created-on-column.tsx b/web/components/core/views/spreadsheet-view/created-on-column/created-on-column.tsx new file mode 100644 index 000000000..cff1f99aa --- /dev/null +++ b/web/components/core/views/spreadsheet-view/created-on-column/created-on-column.tsx @@ -0,0 +1,34 @@ +import React from "react"; + +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; +// helper +import { renderLongDetailDateFormat } from "helpers/date-time.helper"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const CreatedOnColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + properties, + user, + isNotAllowed, +}) => ( +
+ + {properties.created_on && ( +
+ {renderLongDetailDateFormat(issue.created_at)} +
+ )} +
+
+); diff --git a/web/components/core/views/spreadsheet-view/created-on-column/index.ts b/web/components/core/views/spreadsheet-view/created-on-column/index.ts new file mode 100644 index 000000000..28781aa17 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/created-on-column/index.ts @@ -0,0 +1,2 @@ +export * from "./spreadsheet-created-on-column"; +export * from "./created-on-column"; diff --git a/web/components/core/views/spreadsheet-view/created-on-column/spreadsheet-created-on-column.tsx b/web/components/core/views/spreadsheet-view/created-on-column/spreadsheet-created-on-column.tsx new file mode 100644 index 000000000..3ce3f2dbe --- /dev/null +++ b/web/components/core/views/spreadsheet-view/created-on-column/spreadsheet-created-on-column.tsx @@ -0,0 +1,62 @@ +import React from "react"; + +// components +import { CreatedOnColumn } from "components/core"; +// hooks +import useSubIssue from "hooks/use-sub-issue"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + expandedIssues: string[]; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const SpreadsheetCreatedOnColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + expandedIssues, + properties, + user, + isNotAllowed, +}) => { + const isExpanded = expandedIssues.indexOf(issue.id) > -1; + + const { subIssues, isLoading } = useSubIssue(issue.project_detail.id, issue.id, isExpanded); + + return ( +
+ + + {isExpanded && + !isLoading && + subIssues && + subIssues.length > 0 && + subIssues.map((subIssue: IIssue) => ( + + ))} +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/due-date-column/due-date-column.tsx b/web/components/core/views/spreadsheet-view/due-date-column/due-date-column.tsx new file mode 100644 index 000000000..e2d09ae0a --- /dev/null +++ b/web/components/core/views/spreadsheet-view/due-date-column/due-date-column.tsx @@ -0,0 +1,38 @@ +import React from "react"; + +// components +import { ViewDueDateSelect } from "components/issues"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const DueDateColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + properties, + user, + isNotAllowed, +}) => ( +
+ + {properties.due_date && ( + + )} + +
+); diff --git a/web/components/core/views/spreadsheet-view/due-date-column/index.ts b/web/components/core/views/spreadsheet-view/due-date-column/index.ts new file mode 100644 index 000000000..64b454877 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/due-date-column/index.ts @@ -0,0 +1,2 @@ +export * from "./spreadsheet-due-date-column"; +export * from "./due-date-column"; diff --git a/web/components/core/views/spreadsheet-view/due-date-column/spreadsheet-due-date-column.tsx b/web/components/core/views/spreadsheet-view/due-date-column/spreadsheet-due-date-column.tsx new file mode 100644 index 000000000..1cd2eac26 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/due-date-column/spreadsheet-due-date-column.tsx @@ -0,0 +1,62 @@ +import React from "react"; + +// components +import { DueDateColumn } from "components/core"; +// hooks +import useSubIssue from "hooks/use-sub-issue"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + expandedIssues: string[]; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const SpreadsheetDueDateColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + expandedIssues, + properties, + user, + isNotAllowed, +}) => { + const isExpanded = expandedIssues.indexOf(issue.id) > -1; + + const { subIssues, isLoading } = useSubIssue(issue.project_detail.id, issue.id, isExpanded); + + return ( +
+ + + {isExpanded && + !isLoading && + subIssues && + subIssues.length > 0 && + subIssues.map((subIssue: IIssue) => ( + + ))} +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/estimate-column/estimate-column.tsx b/web/components/core/views/spreadsheet-view/estimate-column/estimate-column.tsx new file mode 100644 index 000000000..bb44cefa3 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/estimate-column/estimate-column.tsx @@ -0,0 +1,38 @@ +import React from "react"; + +// components +import { ViewEstimateSelect } from "components/issues"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const EstimateColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + properties, + user, + isNotAllowed, +}) => ( +
+ + {properties.estimate && ( + + )} + +
+); diff --git a/web/components/core/views/spreadsheet-view/estimate-column/index.ts b/web/components/core/views/spreadsheet-view/estimate-column/index.ts new file mode 100644 index 000000000..31f07e6a7 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/estimate-column/index.ts @@ -0,0 +1,2 @@ +export * from "./spreadsheet-estimate-column"; +export * from "./estimate-column"; diff --git a/web/components/core/views/spreadsheet-view/estimate-column/spreadsheet-estimate-column.tsx b/web/components/core/views/spreadsheet-view/estimate-column/spreadsheet-estimate-column.tsx new file mode 100644 index 000000000..a1cc74ad0 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/estimate-column/spreadsheet-estimate-column.tsx @@ -0,0 +1,62 @@ +import React from "react"; + +// components +import { EstimateColumn } from "components/core"; +// hooks +import useSubIssue from "hooks/use-sub-issue"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + expandedIssues: string[]; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const SpreadsheetEstimateColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + expandedIssues, + properties, + user, + isNotAllowed, +}) => { + const isExpanded = expandedIssues.indexOf(issue.id) > -1; + + const { subIssues, isLoading } = useSubIssue(issue.project_detail.id, issue.id, isExpanded); + + return ( +
+ + + {isExpanded && + !isLoading && + subIssues && + subIssues.length > 0 && + subIssues.map((subIssue: IIssue) => ( + + ))} +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/index.ts b/web/components/core/views/spreadsheet-view/index.ts index 7729d5e93..9bf8ed1b0 100644 --- a/web/components/core/views/spreadsheet-view/index.ts +++ b/web/components/core/views/spreadsheet-view/index.ts @@ -1,4 +1,13 @@ +export * from "./assignee-column"; +export * from "./created-on-column"; +export * from "./due-date-column"; +export * from "./estimate-column"; +export * from "./issue-column"; +export * from "./label-column"; +export * from "./priority-column"; +export * from "./start-date-column"; +export * from "./state-column"; +export * from "./updated-on-column"; export * from "./spreadsheet-view"; -export * from "./single-issue"; -export * from "./spreadsheet-columns"; -export * from "./spreadsheet-issues"; +export * from "./issue-column/issue-column"; +export * from "./issue-column/spreadsheet-issue-column"; diff --git a/web/components/core/views/spreadsheet-view/issue-column/index.ts b/web/components/core/views/spreadsheet-view/issue-column/index.ts new file mode 100644 index 000000000..b8d09d1df --- /dev/null +++ b/web/components/core/views/spreadsheet-view/issue-column/index.ts @@ -0,0 +1,2 @@ +export * from "./spreadsheet-issue-column"; +export * from "./issue-column"; diff --git a/web/components/core/views/spreadsheet-view/issue-column/issue-column.tsx b/web/components/core/views/spreadsheet-view/issue-column/issue-column.tsx new file mode 100644 index 000000000..c00f085b2 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/issue-column/issue-column.tsx @@ -0,0 +1,180 @@ +import React, { useState } from "react"; + +import { useRouter } from "next/router"; + +// components +import { Popover2 } from "@blueprintjs/popover2"; +// icons +import { Icon } from "components/ui"; +import { + EllipsisHorizontalIcon, + LinkIcon, + PencilIcon, + TrashIcon, +} from "@heroicons/react/24/outline"; +// hooks +import useToast from "hooks/use-toast"; +// types +import { IIssue, Properties, UserAuth } from "types"; +// helper +import { copyTextToClipboard } from "helpers/string.helper"; + +type Props = { + issue: IIssue; + projectId: string; + expanded: boolean; + handleToggleExpand: (issueId: string) => void; + properties: Properties; + handleEditIssue: (issue: IIssue) => void; + handleDeleteIssue: (issue: IIssue) => void; + setCurrentProjectId: React.Dispatch>; + disableUserActions: boolean; + userAuth: UserAuth; + nestingLevel: number; +}; + +export const IssueColumn: React.FC = ({ + issue, + projectId, + expanded, + handleToggleExpand, + properties, + handleEditIssue, + handleDeleteIssue, + setCurrentProjectId, + disableUserActions, + userAuth, + nestingLevel, +}) => { + const [isOpen, setIsOpen] = useState(false); + + const router = useRouter(); + + const { workspaceSlug } = router.query; + + const { setToastAlert } = useToast(); + + const openPeekOverview = () => { + const { query } = router; + setCurrentProjectId(issue.project_detail.id); + router.push({ + pathname: router.pathname, + query: { ...query, peekIssue: issue.id }, + }); + }; + + const handleCopyText = () => { + const originURL = + typeof window !== "undefined" && window.location.origin ? window.location.origin : ""; + copyTextToClipboard( + `${originURL}/${workspaceSlug}/projects/${projectId}/issues/${issue.id}` + ).then(() => { + setToastAlert({ + type: "success", + title: "Link Copied!", + message: "Issue link copied to clipboard.", + }); + }); + }; + + const paddingLeft = `${nestingLevel * 54}px`; + + const isNotAllowed = userAuth.isGuest || userAuth.isViewer; + + return ( +
+ {properties.key && ( +
+
+ + {issue.project_detail?.identifier}-{issue.sequence_id} + + + {!isNotAllowed && !disableUserActions && ( +
+ setIsOpen(nextOpenState)} + content={ +
+ + + + + +
+ } + placement="bottom-start" + > + +
+
+ )} +
+ + {issue.sub_issues_count > 0 && ( +
+ +
+ )} +
+ )} + + + +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/spreadsheet-issues.tsx b/web/components/core/views/spreadsheet-view/issue-column/spreadsheet-issue-column.tsx similarity index 73% rename from web/components/core/views/spreadsheet-view/spreadsheet-issues.tsx rename to web/components/core/views/spreadsheet-view/issue-column/spreadsheet-issue-column.tsx index 6677e8849..966852a5b 100644 --- a/web/components/core/views/spreadsheet-view/spreadsheet-issues.tsx +++ b/web/components/core/views/spreadsheet-view/issue-column/spreadsheet-issue-column.tsx @@ -1,36 +1,34 @@ -import React, { useState } from "react"; +import React from "react"; // components -import { SingleSpreadsheetIssue } from "components/core"; +import { IssueColumn } from "components/core"; // hooks import useSubIssue from "hooks/use-sub-issue"; // types -import { ICurrentUserResponse, IIssue, Properties, UserAuth } from "types"; +import { IIssue, Properties, UserAuth } from "types"; type Props = { issue: IIssue; - index: number; + projectId: string; expandedIssues: string[]; setExpandedIssues: React.Dispatch>; properties: Properties; handleIssueAction: (issue: IIssue, action: "copy" | "delete" | "edit") => void; - gridTemplateColumns: string; + setCurrentProjectId: React.Dispatch>; disableUserActions: boolean; - user: ICurrentUserResponse | undefined; userAuth: UserAuth; nestingLevel?: number; }; -export const SpreadsheetIssues: React.FC = ({ - index, +export const SpreadsheetIssuesColumn: React.FC = ({ issue, + projectId, expandedIssues, setExpandedIssues, - gridTemplateColumns, properties, handleIssueAction, + setCurrentProjectId, disableUserActions, - user, userAuth, nestingLevel = 0, }) => { @@ -49,21 +47,20 @@ export const SpreadsheetIssues: React.FC = ({ const isExpanded = expandedIssues.indexOf(issue.id) > -1; - const { subIssues, isLoading } = useSubIssue(issue.id, isExpanded); + const { subIssues, isLoading } = useSubIssue(issue.project_detail.id, issue.id, isExpanded); return (
- handleIssueAction(issue, "edit")} handleDeleteIssue={() => handleIssueAction(issue, "delete")} + setCurrentProjectId={setCurrentProjectId} disableUserActions={disableUserActions} - user={user} userAuth={userAuth} nestingLevel={nestingLevel} /> @@ -73,17 +70,16 @@ export const SpreadsheetIssues: React.FC = ({ subIssues && subIssues.length > 0 && subIssues.map((subIssue: IIssue) => ( - diff --git a/web/components/core/views/spreadsheet-view/label-column/index.ts b/web/components/core/views/spreadsheet-view/label-column/index.ts new file mode 100644 index 000000000..a1b69c1a9 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/label-column/index.ts @@ -0,0 +1,2 @@ +export * from "./spreadsheet-label-column"; +export * from "./label-column"; diff --git a/web/components/core/views/spreadsheet-view/label-column/label-column.tsx b/web/components/core/views/spreadsheet-view/label-column/label-column.tsx new file mode 100644 index 000000000..1d1355eec --- /dev/null +++ b/web/components/core/views/spreadsheet-view/label-column/label-column.tsx @@ -0,0 +1,47 @@ +import React from "react"; + +// components +import { LabelSelect } from "components/project"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const LabelColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + properties, + user, + isNotAllowed, +}) => { + const handleLabelChange = (data: any) => { + partialUpdateIssue({ labels_list: data }, issue); + }; + + return ( +
+ + {properties.labels && ( + + )} + +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/label-column/spreadsheet-label-column.tsx b/web/components/core/views/spreadsheet-view/label-column/spreadsheet-label-column.tsx new file mode 100644 index 000000000..5ab77e909 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/label-column/spreadsheet-label-column.tsx @@ -0,0 +1,62 @@ +import React from "react"; + +// components +import { LabelColumn } from "components/core"; +// hooks +import useSubIssue from "hooks/use-sub-issue"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + expandedIssues: string[]; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const SpreadsheetLabelColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + expandedIssues, + properties, + user, + isNotAllowed, +}) => { + const isExpanded = expandedIssues.indexOf(issue.id) > -1; + + const { subIssues, isLoading } = useSubIssue(issue.project_detail.id, issue.id, isExpanded); + + return ( +
+ + + {isExpanded && + !isLoading && + subIssues && + subIssues.length > 0 && + subIssues.map((subIssue: IIssue) => ( + + ))} +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/priority-column/index.ts b/web/components/core/views/spreadsheet-view/priority-column/index.ts new file mode 100644 index 000000000..fc542331e --- /dev/null +++ b/web/components/core/views/spreadsheet-view/priority-column/index.ts @@ -0,0 +1,2 @@ +export * from "./spreadsheet-priority-column"; +export * from "./priority-column"; diff --git a/web/components/core/views/spreadsheet-view/priority-column/priority-column.tsx b/web/components/core/views/spreadsheet-view/priority-column/priority-column.tsx new file mode 100644 index 000000000..eca140df1 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/priority-column/priority-column.tsx @@ -0,0 +1,64 @@ +import React from "react"; + +import { useRouter } from "next/router"; + +// components +import { PrioritySelect } from "components/project"; +// services +import trackEventServices from "services/track-event.service"; +// types +import { ICurrentUserResponse, IIssue, Properties, TIssuePriorities } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const PriorityColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + properties, + user, + isNotAllowed, +}) => { + const router = useRouter(); + + const { workspaceSlug } = router.query; + + const handlePriorityChange = (data: TIssuePriorities) => { + partialUpdateIssue({ priority: data }, issue); + trackEventServices.trackIssuePartialPropertyUpdateEvent( + { + workspaceSlug, + workspaceId: issue.workspace, + projectId: issue.project_detail.id, + projectIdentifier: issue.project_detail.identifier, + projectName: issue.project_detail.name, + issueId: issue.id, + }, + "ISSUE_PROPERTY_UPDATE_PRIORITY", + user + ); + }; + + return ( +
+ + {properties.priority && ( + + )} + +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/priority-column/spreadsheet-priority-column.tsx b/web/components/core/views/spreadsheet-view/priority-column/spreadsheet-priority-column.tsx new file mode 100644 index 000000000..f0b84fb59 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/priority-column/spreadsheet-priority-column.tsx @@ -0,0 +1,62 @@ +import React from "react"; + +// components +import { PriorityColumn } from "components/core"; +// hooks +import useSubIssue from "hooks/use-sub-issue"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + expandedIssues: string[]; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const SpreadsheetPriorityColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + expandedIssues, + properties, + user, + isNotAllowed, +}) => { + const isExpanded = expandedIssues.indexOf(issue.id) > -1; + + const { subIssues, isLoading } = useSubIssue(issue.project_detail.id, issue.id, isExpanded); + + return ( +
+ + + {isExpanded && + !isLoading && + subIssues && + subIssues.length > 0 && + subIssues.map((subIssue: IIssue) => ( + + ))} +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/single-issue.tsx b/web/components/core/views/spreadsheet-view/single-issue.tsx index 7a309f728..32cb4ba77 100644 --- a/web/components/core/views/spreadsheet-view/single-issue.tsx +++ b/web/components/core/views/spreadsheet-view/single-issue.tsx @@ -49,6 +49,7 @@ import { renderLongDetailDateFormat } from "helpers/date-time.helper"; type Props = { issue: IIssue; + projectId: string; index: number; expanded: boolean; handleToggleExpand: (issueId: string) => void; @@ -64,6 +65,7 @@ type Props = { export const SingleSpreadsheetIssue: React.FC = ({ issue, + projectId, index, expanded, handleToggleExpand, @@ -80,7 +82,7 @@ export const SingleSpreadsheetIssue: React.FC = ({ const router = useRouter(); - const { workspaceSlug, projectId, cycleId, moduleId, viewId } = router.query; + const { workspaceSlug, cycleId, moduleId, viewId } = router.query; const { params } = useSpreadsheetIssuesView(); @@ -96,7 +98,7 @@ export const SingleSpreadsheetIssue: React.FC = ({ ? MODULE_ISSUES_WITH_PARAMS(moduleId.toString(), params) : viewId ? VIEW_ISSUES(viewId.toString(), params) - : PROJECT_ISSUES_LIST_WITH_PARAMS(projectId.toString(), params); + : PROJECT_ISSUES_LIST_WITH_PARAMS(projectId, params); if (issue.parent) mutate( @@ -136,13 +138,7 @@ export const SingleSpreadsheetIssue: React.FC = ({ ); issuesService - .patchIssue( - workspaceSlug as string, - projectId as string, - issue.id as string, - formData, - user - ) + .patchIssue(workspaceSlug as string, projectId, issue.id as string, formData, user) .then(() => { if (issue.parent) { mutate(SUB_ISSUES(issue.parent as string)); @@ -368,6 +364,7 @@ export const SingleSpreadsheetIssue: React.FC = ({
= ({
= ({
= ({ columnData, gridTemplateColumns }) => { - const { storedValue: selectedMenuItem, setValue: setSelectedMenuItem } = useLocalStorage( - "spreadsheetViewSorting", - "" - ); - const { storedValue: activeSortingProperty, setValue: setActiveSortingProperty } = - useLocalStorage("spreadsheetViewActiveSortingProperty", ""); - - const { displayFilters, setDisplayFilters } = useSpreadsheetIssuesView(); - - const handleOrderBy = (order: TIssueOrderByOptions, itemKey: string) => { - setDisplayFilters({ order_by: order }); - setSelectedMenuItem(`${order}_${itemKey}`); - setActiveSortingProperty(order === "-created_at" ? "" : itemKey); - }; - - return ( -
- {columnData.map((col: any) => { - if (col.isActive) { - return ( -
- {col.propertyName === "title" ? ( -
- {col.colName} -
- ) : ( - - {activeSortingProperty === col.propertyName && ( -
- -
- )} - - {col.icon ? ( -
- } - width="xl" - > - { - handleOrderBy(col.ascendingOrder, col.propertyName); - }} - > -
-
- {col.propertyName === "assignee" || col.propertyName === "labels" ? ( - <> - - - - - A - - Z - - ) : col.propertyName === "due_date" || - col.propertyName === "created_on" || - col.propertyName === "updated_on" ? ( - <> - - - - - New - - Old - - ) : ( - <> - - - - - First - - Last - - )} -
- - -
-
- { - handleOrderBy(col.descendingOrder, col.propertyName); - }} - > -
-
- {col.propertyName === "assignee" || col.propertyName === "labels" ? ( - <> - - - - - Z - - A - - ) : col.propertyName === "due_date" ? ( - <> - - - - - Old - - New - - ) : ( - <> - - - - - Last - - First - - )} -
- - -
-
- {selectedMenuItem && - selectedMenuItem !== "" && - displayFilters?.order_by !== "-created_at" && - selectedMenuItem.includes(col.propertyName) && ( - { - handleOrderBy("-created_at", col.propertyName); - }} - > -
-
- - - - - Clear sorting -
-
-
- )} - - )} -
- ); - } - })} -
- ); -}; diff --git a/web/components/core/views/spreadsheet-view/spreadsheet-view.tsx b/web/components/core/views/spreadsheet-view/spreadsheet-view.tsx index 1076f30d0..0d9214a36 100644 --- a/web/components/core/views/spreadsheet-view/spreadsheet-view.tsx +++ b/web/components/core/views/spreadsheet-view/spreadsheet-view.tsx @@ -1,23 +1,61 @@ -import React, { useState } from "react"; +import React, { useCallback, useEffect, useRef, useState } from "react"; // next import { useRouter } from "next/router"; +import { KeyedMutator, mutate } from "swr"; + // components -import { SpreadsheetColumns, SpreadsheetIssues } from "components/core"; -import { CustomMenu, Spinner } from "components/ui"; +import { + ListInlineCreateIssueForm, + SpreadsheetAssigneeColumn, + SpreadsheetCreatedOnColumn, + SpreadsheetDueDateColumn, + SpreadsheetEstimateColumn, + SpreadsheetIssuesColumn, + SpreadsheetLabelColumn, + SpreadsheetPriorityColumn, + SpreadsheetStartDateColumn, + SpreadsheetStateColumn, + SpreadsheetUpdatedOnColumn, +} from "components/core"; +import { CustomMenu, Icon, Spinner } from "components/ui"; import { IssuePeekOverview } from "components/issues"; // hooks import useIssuesProperties from "hooks/use-issue-properties"; -import useSpreadsheetIssuesView from "hooks/use-spreadsheet-issues-view"; +import useLocalStorage from "hooks/use-local-storage"; +import { useWorkspaceView } from "hooks/use-workspace-view"; // types -import { ICurrentUserResponse, IIssue, Properties, UserAuth } from "types"; -// constants -import { SPREADSHEET_COLUMN } from "constants/spreadsheet"; +import { + ICurrentUserResponse, + IIssue, + ISubIssueResponse, + TIssueOrderByOptions, + UserAuth, +} from "types"; +import { + CYCLE_DETAILS, + CYCLE_ISSUES_WITH_PARAMS, + MODULE_DETAILS, + MODULE_ISSUES_WITH_PARAMS, + PROJECT_ISSUES_LIST_WITH_PARAMS, + SUB_ISSUES, + VIEW_ISSUES, + WORKSPACE_VIEW_ISSUES, +} from "constants/fetch-keys"; +import useSpreadsheetIssuesView from "hooks/use-spreadsheet-issues-view"; +import projectIssuesServices from "services/issues.service"; // icon -import { PlusIcon } from "@heroicons/react/24/outline"; +import { CheckIcon, ChevronDownIcon, PlusIcon } from "lucide-react"; type Props = { + spreadsheetIssues: IIssue[]; + mutateIssues: KeyedMutator< + | IIssue[] + | { + [key: string]: IIssue[]; + } + >; handleIssueAction: (issue: IIssue, action: "copy" | "delete" | "edit") => void; openIssuesListModal?: (() => void) | null; disableUserActions: boolean; @@ -26,6 +64,8 @@ type Props = { }; export const SpreadsheetView: React.FC = ({ + spreadsheetIssues, + mutateIssues, handleIssueAction, openIssuesListModal, disableUserActions, @@ -33,99 +73,588 @@ export const SpreadsheetView: React.FC = ({ userAuth, }) => { const [expandedIssues, setExpandedIssues] = useState([]); + const [currentProjectId, setCurrentProjectId] = useState(null); + + const [isInlineCreateIssueFormOpen, setIsInlineCreateIssueFormOpen] = useState(false); + + const [isScrolled, setIsScrolled] = useState(false); + + const containerRef = useRef(null); const router = useRouter(); - const { workspaceSlug, projectId, cycleId, moduleId } = router.query; + const { workspaceSlug, projectId, cycleId, moduleId, viewId, globalViewId } = router.query; const type = cycleId ? "cycle" : moduleId ? "module" : "issue"; - const { spreadsheetIssues, mutateIssues } = useSpreadsheetIssuesView(); - const [properties] = useIssuesProperties(workspaceSlug as string, projectId as string); - const columnData = SPREADSHEET_COLUMN.map((column) => ({ - ...column, - isActive: properties - ? column.propertyName === "labels" - ? properties[column.propertyName as keyof Properties] - : column.propertyName === "title" - ? true - : properties[column.propertyName as keyof Properties] - : false, - })); + const { storedValue: selectedMenuItem, setValue: setSelectedMenuItem } = useLocalStorage( + "spreadsheetViewSorting", + "" + ); + const { storedValue: activeSortingProperty, setValue: setActiveSortingProperty } = + useLocalStorage("spreadsheetViewActiveSortingProperty", ""); - const gridTemplateColumns = columnData - .filter((column) => column.isActive) - .map((column) => column.colSize) - .join(" "); + const workspaceIssuesPath = [ + { + params: { + sub_issue: false, + }, + path: "workspace-views/all-issues", + }, + { + params: { + assignees: user?.id ?? undefined, + sub_issue: false, + }, + path: "workspace-views/assigned", + }, + { + params: { + created_by: user?.id ?? undefined, + sub_issue: false, + }, + path: "workspace-views/created", + }, + { + params: { + subscriber: user?.id ?? undefined, + sub_issue: false, + }, + path: "workspace-views/subscribed", + }, + ]; + + const currentWorkspaceIssuePath = workspaceIssuesPath.find((path) => + router.pathname.includes(path.path) + ); + + const { + params: workspaceViewParams, + filters: workspaceViewFilters, + handleFilters, + } = useWorkspaceView(); + + const workspaceViewProperties = workspaceViewFilters.display_properties; + + const isWorkspaceView = globalViewId || currentWorkspaceIssuePath; + + const currentViewProperties = isWorkspaceView ? workspaceViewProperties : properties; + + const { params, displayFilters, setDisplayFilters } = useSpreadsheetIssuesView(); + + const partialUpdateIssue = useCallback( + (formData: Partial, issue: IIssue) => { + if (!workspaceSlug || !issue) return; + + const fetchKey = cycleId + ? CYCLE_ISSUES_WITH_PARAMS(cycleId.toString(), params) + : moduleId + ? MODULE_ISSUES_WITH_PARAMS(moduleId.toString(), params) + : viewId + ? VIEW_ISSUES(viewId.toString(), params) + : globalViewId + ? WORKSPACE_VIEW_ISSUES(globalViewId.toString(), workspaceViewParams) + : currentWorkspaceIssuePath + ? WORKSPACE_VIEW_ISSUES(workspaceSlug.toString(), currentWorkspaceIssuePath?.params) + : PROJECT_ISSUES_LIST_WITH_PARAMS(issue.project_detail.id, params); + + if (issue.parent) + mutate( + SUB_ISSUES(issue.parent.toString()), + (prevData) => { + if (!prevData) return prevData; + + return { + ...prevData, + sub_issues: (prevData.sub_issues ?? []).map((i) => { + if (i.id === issue.id) { + return { + ...i, + ...formData, + }; + } + return i; + }), + }; + }, + false + ); + else + mutate( + fetchKey, + (prevData) => + (prevData ?? []).map((p) => { + if (p.id === issue.id) { + return { + ...p, + ...formData, + }; + } + return p; + }), + false + ); + + projectIssuesServices + .patchIssue( + workspaceSlug as string, + issue.project_detail.id, + issue.id as string, + formData, + user + ) + .then(() => { + if (issue.parent) { + mutate(SUB_ISSUES(issue.parent as string)); + } else { + mutate(fetchKey); + + if (cycleId) mutate(CYCLE_DETAILS(cycleId as string)); + if (moduleId) mutate(MODULE_DETAILS(moduleId as string)); + } + }) + .catch((error) => { + console.log(error); + }); + }, + [ + workspaceSlug, + cycleId, + moduleId, + viewId, + globalViewId, + workspaceViewParams, + currentWorkspaceIssuePath, + params, + user, + ] + ); + + const isNotAllowed = userAuth.isGuest || userAuth.isViewer; + + const handleOrderBy = (order: TIssueOrderByOptions, itemKey: string) => { + if (globalViewId) handleFilters("display_filters", { order_by: order }); + else setDisplayFilters({ order_by: order }); + setSelectedMenuItem(`${order}_${itemKey}`); + setActiveSortingProperty(order === "-created_at" ? "" : itemKey); + }; + + const renderColumn = ( + header: string, + propertyName: string, + Component: React.ComponentType, + ascendingOrder: TIssueOrderByOptions, + descendingOrder: TIssueOrderByOptions + ) => ( +
+
+ {currentWorkspaceIssuePath ? ( + {header} + ) : ( + + {activeSortingProperty === propertyName && ( +
+ +
+ )} + + {header} +
+ } + width="xl" + > + { + handleOrderBy(ascendingOrder, propertyName); + }} + > +
+
+ {propertyName === "assignee" || propertyName === "labels" ? ( + <> + + + + + A + + Z + + ) : propertyName === "due_date" || + propertyName === "created_on" || + propertyName === "updated_on" ? ( + <> + + + + + New + + Old + + ) : ( + <> + + + + + First + + Last + + )} +
+ + +
+
+ { + handleOrderBy(descendingOrder, propertyName); + }} + > +
+
+ {propertyName === "assignee" || propertyName === "labels" ? ( + <> + + + + + Z + + A + + ) : propertyName === "due_date" ? ( + <> + + + + + Old + + New + + ) : ( + <> + + + + + Last + + First + + )} +
+ + +
+
+ {selectedMenuItem && + selectedMenuItem !== "" && + displayFilters?.order_by !== "-created_at" && + selectedMenuItem.includes(propertyName) && ( + { + handleOrderBy("-created_at", propertyName); + }} + > +
+
+ + + + + Clear sorting +
+
+
+ )} + + )} +
+
+ {spreadsheetIssues.map((issue: IIssue, index) => ( + + ))} +
+
+ ); + + const handleScroll = () => { + if (containerRef.current) { + const scrollLeft = containerRef.current.scrollLeft; + setIsScrolled(scrollLeft > 0); + } + }; + + useEffect(() => { + const currentContainerRef = containerRef.current; + + if (currentContainerRef) { + currentContainerRef.addEventListener("scroll", handleScroll); + } + + return () => { + if (currentContainerRef) { + currentContainerRef.removeEventListener("scroll", handleScroll); + } + }; + }, []); return ( <> mutateIssues()} - projectId={projectId?.toString() ?? ""} + projectId={currentProjectId ?? ""} workspaceSlug={workspaceSlug?.toString() ?? ""} readOnly={disableUserActions} /> -
-
- -
- {spreadsheetIssues ? ( -
- {spreadsheetIssues.map((issue: IIssue, index) => ( - +
+
+ {spreadsheetIssues ? ( + <> +
+
+
+ {currentViewProperties.key && ( + + ID + + )} + + Issue + +
+ + {spreadsheetIssues.map((issue: IIssue, index) => ( + + ))} +
+
+ {currentViewProperties.state && + renderColumn( + "State", + "state", + SpreadsheetStateColumn, + "state__name", + "-state__name" + )} + + {currentViewProperties.priority && + renderColumn( + "Priority", + "priority", + SpreadsheetPriorityColumn, + "priority", + "-priority" + )} + {currentViewProperties.assignee && + renderColumn( + "Assignees", + "assignee", + SpreadsheetAssigneeColumn, + "assignees__first_name", + "-assignees__first_name" + )} + {currentViewProperties.labels && + renderColumn( + "Label", + "labels", + SpreadsheetLabelColumn, + "labels__name", + "-labels__name" + )} + {currentViewProperties.start_date && + renderColumn( + "Start Date", + "start_date", + SpreadsheetStartDateColumn, + "-start_date", + "start_date" + )} + {currentViewProperties.due_date && + renderColumn( + "Due Date", + "due_date", + SpreadsheetDueDateColumn, + "-target_date", + "target_date" + )} + {currentViewProperties.estimate && + renderColumn( + "Estimate", + "estimate", + SpreadsheetEstimateColumn, + "estimate_point", + "-estimate_point" + )} + {currentViewProperties.created_on && + renderColumn( + "Created On", + "created_on", + SpreadsheetCreatedOnColumn, + "-created_at", + "created_at" + )} + {currentViewProperties.updated_on && + renderColumn( + "Updated On", + "updated_on", + SpreadsheetUpdatedOnColumn, + "-updated_at", + "updated_at" + )} + + ) : ( +
+ +
+ )} +
+ +
+
+ setIsInlineCreateIssueFormOpen(false)} + prePopulatedData={{ + ...(cycleId && { cycle: cycleId.toString() }), + ...(moduleId && { module: moduleId.toString() }), + }} /> - ))} -
- {type === "issue" ? ( - - ) : ( - !disableUserActions && ( +
+ + {type === "issue" + ? !disableUserActions && + !isInlineCreateIssueFormOpen && ( + + ) + : !disableUserActions && + !isInlineCreateIssueFormOpen && ( - Add Issue + New Issue } position="left" + verticalPosition="top" optionsClassName="left-5 !w-36" noBorder > - { - const e = new KeyboardEvent("keydown", { key: "c" }); - document.dispatchEvent(e); - }} - > + setIsInlineCreateIssueFormOpen(true)}> Create new {openIssuesListModal && ( @@ -134,13 +663,9 @@ export const SpreadsheetView: React.FC = ({ )} - ) - )} -
+ )}
- ) : ( - - )} +
); diff --git a/web/components/core/views/spreadsheet-view/start-date-column/index.ts b/web/components/core/views/spreadsheet-view/start-date-column/index.ts new file mode 100644 index 000000000..94f229498 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/start-date-column/index.ts @@ -0,0 +1,2 @@ +export * from "./spreadsheet-start-date-column"; +export * from "./start-date-column"; diff --git a/web/components/core/views/spreadsheet-view/start-date-column/spreadsheet-start-date-column.tsx b/web/components/core/views/spreadsheet-view/start-date-column/spreadsheet-start-date-column.tsx new file mode 100644 index 000000000..064506ca2 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/start-date-column/spreadsheet-start-date-column.tsx @@ -0,0 +1,62 @@ +import React from "react"; + +// components +import { StartDateColumn } from "components/core"; +// hooks +import useSubIssue from "hooks/use-sub-issue"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + expandedIssues: string[]; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const SpreadsheetStartDateColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + expandedIssues, + properties, + user, + isNotAllowed, +}) => { + const isExpanded = expandedIssues.indexOf(issue.id) > -1; + + const { subIssues, isLoading } = useSubIssue(issue.project_detail.id, issue.id, isExpanded); + + return ( +
+ + + {isExpanded && + !isLoading && + subIssues && + subIssues.length > 0 && + subIssues.map((subIssue: IIssue) => ( + + ))} +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/start-date-column/start-date-column.tsx b/web/components/core/views/spreadsheet-view/start-date-column/start-date-column.tsx new file mode 100644 index 000000000..6774ce1b9 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/start-date-column/start-date-column.tsx @@ -0,0 +1,38 @@ +import React from "react"; + +// components +import { ViewStartDateSelect } from "components/issues"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const StartDateColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + properties, + user, + isNotAllowed, +}) => ( +
+ + {properties.due_date && ( + + )} + +
+); diff --git a/web/components/core/views/spreadsheet-view/state-column/index.ts b/web/components/core/views/spreadsheet-view/state-column/index.ts new file mode 100644 index 000000000..f3cbef871 --- /dev/null +++ b/web/components/core/views/spreadsheet-view/state-column/index.ts @@ -0,0 +1,2 @@ +export * from "./spreadsheet-state-column"; +export * from "./state-column"; diff --git a/web/components/core/views/spreadsheet-view/state-column/spreadsheet-state-column.tsx b/web/components/core/views/spreadsheet-view/state-column/spreadsheet-state-column.tsx new file mode 100644 index 000000000..606f3e28a --- /dev/null +++ b/web/components/core/views/spreadsheet-view/state-column/spreadsheet-state-column.tsx @@ -0,0 +1,62 @@ +import React from "react"; + +// components +import { StateColumn } from "components/core"; +// hooks +import useSubIssue from "hooks/use-sub-issue"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + expandedIssues: string[]; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const SpreadsheetStateColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + expandedIssues, + properties, + user, + isNotAllowed, +}) => { + const isExpanded = expandedIssues.indexOf(issue.id) > -1; + + const { subIssues, isLoading } = useSubIssue(issue.project_detail.id, issue.id, isExpanded); + + return ( +
+ + + {isExpanded && + !isLoading && + subIssues && + subIssues.length > 0 && + subIssues.map((subIssue: IIssue) => ( + + ))} +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/state-column/state-column.tsx b/web/components/core/views/spreadsheet-view/state-column/state-column.tsx new file mode 100644 index 000000000..04c833b1d --- /dev/null +++ b/web/components/core/views/spreadsheet-view/state-column/state-column.tsx @@ -0,0 +1,87 @@ +import React from "react"; + +import { useRouter } from "next/router"; + +// components +import { StateSelect } from "components/states"; +// services +import trackEventServices from "services/track-event.service"; +// types +import { ICurrentUserResponse, IIssue, IState, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const StateColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + properties, + user, + isNotAllowed, +}) => { + const router = useRouter(); + + const { workspaceSlug } = router.query; + + const handleStateChange = (data: string, states: IState[] | undefined) => { + const oldState = states?.find((s) => s.id === issue.state); + const newState = states?.find((s) => s.id === data); + + partialUpdateIssue( + { + state: data, + state_detail: newState, + }, + issue + ); + trackEventServices.trackIssuePartialPropertyUpdateEvent( + { + workspaceSlug, + workspaceId: issue.workspace, + projectId: issue.project_detail.id, + projectIdentifier: issue.project_detail.identifier, + projectName: issue.project_detail.name, + issueId: issue.id, + }, + "ISSUE_PROPERTY_UPDATE_STATE", + user + ); + if (oldState?.group !== "completed" && newState?.group !== "completed") { + trackEventServices.trackIssueMarkedAsDoneEvent( + { + workspaceSlug: issue.workspace_detail.slug, + workspaceId: issue.workspace_detail.id, + projectId: issue.project_detail.id, + projectIdentifier: issue.project_detail.identifier, + projectName: issue.project_detail.name, + issueId: issue.id, + }, + user + ); + } + }; + + return ( +
+ + {properties.state && ( + + )} + +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/updated-on-column/index.ts b/web/components/core/views/spreadsheet-view/updated-on-column/index.ts new file mode 100644 index 000000000..af1337a7f --- /dev/null +++ b/web/components/core/views/spreadsheet-view/updated-on-column/index.ts @@ -0,0 +1,2 @@ +export * from "./spreadsheet-updated-on-column"; +export * from "./updated-on-column"; diff --git a/web/components/core/views/spreadsheet-view/updated-on-column/spreadsheet-updated-on-column.tsx b/web/components/core/views/spreadsheet-view/updated-on-column/spreadsheet-updated-on-column.tsx new file mode 100644 index 000000000..bb29e460d --- /dev/null +++ b/web/components/core/views/spreadsheet-view/updated-on-column/spreadsheet-updated-on-column.tsx @@ -0,0 +1,62 @@ +import React from "react"; + +// components +import { UpdatedOnColumn } from "components/core"; +// hooks +import useSubIssue from "hooks/use-sub-issue"; +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + expandedIssues: string[]; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const SpreadsheetUpdatedOnColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + expandedIssues, + properties, + user, + isNotAllowed, +}) => { + const isExpanded = expandedIssues.indexOf(issue.id) > -1; + + const { subIssues, isLoading } = useSubIssue(issue.project_detail.id, issue.id, isExpanded); + + return ( +
+ + + {isExpanded && + !isLoading && + subIssues && + subIssues.length > 0 && + subIssues.map((subIssue: IIssue) => ( + + ))} +
+ ); +}; diff --git a/web/components/core/views/spreadsheet-view/updated-on-column/updated-on-column.tsx b/web/components/core/views/spreadsheet-view/updated-on-column/updated-on-column.tsx new file mode 100644 index 000000000..087d589fc --- /dev/null +++ b/web/components/core/views/spreadsheet-view/updated-on-column/updated-on-column.tsx @@ -0,0 +1,34 @@ +import React from "react"; + +// types +import { ICurrentUserResponse, IIssue, Properties } from "types"; +// helper +import { renderLongDetailDateFormat } from "helpers/date-time.helper"; + +type Props = { + issue: IIssue; + projectId: string; + partialUpdateIssue: (formData: Partial, issue: IIssue) => void; + properties: Properties; + user: ICurrentUserResponse | undefined; + isNotAllowed: boolean; +}; + +export const UpdatedOnColumn: React.FC = ({ + issue, + projectId, + partialUpdateIssue, + properties, + user, + isNotAllowed, +}) => ( +
+ + {properties.updated_on && ( +
+ {renderLongDetailDateFormat(issue.updated_at)} +
+ )} +
+
+); diff --git a/web/components/custom-attributes/objects-select.tsx b/web/components/custom-attributes/objects-select.tsx index 716cbb12c..c6f3e237a 100644 --- a/web/components/custom-attributes/objects-select.tsx +++ b/web/components/custom-attributes/objects-select.tsx @@ -1,14 +1,15 @@ import { useEffect } from "react"; - import { useRouter } from "next/router"; - -// mobx import { observer } from "mobx-react-lite"; + +// mobx store import { useMobxStore } from "lib/mobx/store-provider"; // ui import { CustomSearchSelect } from "components/ui"; -import { renderEmoji } from "helpers/emoji.helper"; +// icons import { TableProperties } from "lucide-react"; +// helpers +import { renderEmoji } from "helpers/emoji.helper"; type Props = { onChange: (val: string | null) => void; diff --git a/web/components/cycles/single-cycle-list.tsx b/web/components/cycles/single-cycle-list.tsx index ec01da9e7..a4c21128a 100644 --- a/web/components/cycles/single-cycle-list.tsx +++ b/web/components/cycles/single-cycle-list.tsx @@ -149,6 +149,10 @@ export const SingleCycleList: React.FC = ({ color: group.color, })); + const completedIssues = cycle.completed_issues + cycle.cancelled_issues; + + const percentage = cycle.total_issues > 0 ? (completedIssues / cycle.total_issues) * 100 : 0; + return (
@@ -307,7 +311,7 @@ export const SingleCycleList: React.FC = ({ ) : cycleStatus === "completed" ? ( - {100} % + {Math.round(percentage)} % ) : ( diff --git a/web/components/gantt-chart/chart/index.tsx b/web/components/gantt-chart/chart/index.tsx index aa79ae19c..61e3078d6 100644 --- a/web/components/gantt-chart/chart/index.tsx +++ b/web/components/gantt-chart/chart/index.tsx @@ -1,4 +1,6 @@ import { FC, useEffect, useState } from "react"; +// next +import { useRouter } from "next/router"; // icons import { ArrowsPointingInIcon, ArrowsPointingOutIcon } from "@heroicons/react/20/solid"; // components @@ -11,6 +13,8 @@ import { GanttSidebar } from "../sidebar"; import { MonthChartView } from "./month"; // import { QuarterChartView } from "./quarter"; // import { YearChartView } from "./year"; +// icons +import { PlusIcon } from "lucide-react"; // views import { // generateHourChart, @@ -25,6 +29,7 @@ import { getNumberOfDaysBetweenTwoDatesInYear, getMonthChartItemPositionWidthInMonth, } from "../views"; +import { GanttInlineCreateIssueForm } from "components/core/views/gantt-chart-view/inline-create-issue-form"; // types import { ChartDataType, IBlockUpdateData, IGanttBlock, TGanttViews } from "../types"; // data @@ -64,12 +69,17 @@ export const ChartViewRoot: FC = ({ const [itemsContainerWidth, setItemsContainerWidth] = useState(0); const [fullScreenMode, setFullScreenMode] = useState(false); + const [isCreateIssueFormOpen, setIsCreateIssueFormOpen] = useState(false); + // blocks state management starts const [chartBlocks, setChartBlocks] = useState(null); const { currentView, currentViewData, renderView, dispatch, allViews, updateScrollLeft } = useChart(); + const router = useRouter(); + const { cycleId, moduleId } = router.query; + const renderBlockStructure = (view: any, blocks: IGanttBlock[] | null) => blocks && blocks.length > 0 ? blocks.map((block: any) => ({ @@ -294,9 +304,12 @@ export const ChartViewRoot: FC = ({ >
-
+
+
{title}
+
Duration
+
= ({ SidebarBlockRender={SidebarBlockRender} enableReorder={enableReorder} /> + {chartBlocks && ( +
+ setIsCreateIssueFormOpen(false)} + onSuccess={() => { + const ganttSidebar = document.getElementById(`gantt-sidebar-${cycleId}`); + + const timeoutId = setTimeout(() => { + if (ganttSidebar) + ganttSidebar.scrollBy({ + top: ganttSidebar.scrollHeight, + left: 0, + behavior: "smooth", + }); + clearTimeout(timeoutId); + }, 10); + }} + prePopulatedData={{ + start_date: new Date(Date.now()).toISOString().split("T")[0], + target_date: new Date(Date.now() + 86400000).toISOString().split("T")[0], + ...(cycleId && { cycle: cycleId.toString() }), + ...(moduleId && { module: moduleId.toString() }), + }} + /> + + {!isCreateIssueFormOpen && ( + + )} +
+ )}
= ({ if (e.button !== 0) return; - e.preventDefault(); - e.stopPropagation(); - - setIsMoving(true); - const resizableDiv = resizableRef.current; const columnWidth = currentViewData.data.width; @@ -193,6 +188,8 @@ export const ChartDraggable: React.FC = ({ let initialMarginLeft = parseInt(resizableDiv.style.marginLeft); const handleMouseMove = (e: MouseEvent) => { + setIsMoving(true); + let delWidth = 0; delWidth = checkScrollEnd(e); @@ -295,7 +292,9 @@ export const ChartDraggable: React.FC = ({ )}
diff --git a/web/components/gantt-chart/sidebar.tsx b/web/components/gantt-chart/sidebar.tsx index 92e7a603d..2aec274d9 100644 --- a/web/components/gantt-chart/sidebar.tsx +++ b/web/components/gantt-chart/sidebar.tsx @@ -1,3 +1,4 @@ +import { useRouter } from "next/router"; // react-beautiful-dnd import { DragDropContext, Draggable, DropResult } from "react-beautiful-dnd"; import StrictModeDroppable from "components/dnd/StrictModeDroppable"; @@ -7,6 +8,8 @@ import { useChart } from "./hooks"; import { Loader } from "components/ui"; // icons import { EllipsisVerticalIcon } from "@heroicons/react/24/outline"; +// helpers +import { findTotalDaysInRange } from "helpers/date-time.helper"; // types import { IBlockUpdateData, IGanttBlock } from "./types"; @@ -18,13 +21,12 @@ type Props = { enableReorder: boolean; }; -export const GanttSidebar: React.FC = ({ - title, - blockUpdateHandler, - blocks, - SidebarBlockRender, - enableReorder, -}) => { +export const GanttSidebar: React.FC = (props) => { + const { title, blockUpdateHandler, blocks, SidebarBlockRender, enableReorder } = props; + + const router = useRouter(); + const { cycleId } = router.query; + const { activeBlock, dispatch } = useChart(); // update the active block on hover @@ -85,14 +87,21 @@ export const GanttSidebar: React.FC = ({ {(droppableProvided) => (
<> {blocks ? ( - blocks.length > 0 ? ( - blocks.map((block, index) => ( + blocks.map((block, index) => { + const duration = findTotalDaysInRange( + block.start_date ?? "", + block.target_date ?? "", + true + ); + + return ( = ({ )} -
- +
+
+ +
+
+ {duration} day{duration > 1 ? "s" : ""} +
)} - )) - ) : ( -
- No {title} found -
- ) + ); + }) ) : ( diff --git a/web/components/issues/activity.tsx b/web/components/issues/activity.tsx index fe322afe9..e6f54f512 100644 --- a/web/components/issues/activity.tsx +++ b/web/components/issues/activity.tsx @@ -7,9 +7,9 @@ import { useRouter } from "next/router"; import { ActivityIcon, ActivityMessage } from "components/core"; import { CommentCard } from "components/issues/comment"; // ui -import { Icon, Loader } from "components/ui"; +import { Icon, Loader, Tooltip } from "components/ui"; // helpers -import { timeAgo } from "helpers/date-time.helper"; +import { render24HourFormatTime, renderLongDateFormat, timeAgo } from "helpers/date-time.helper"; // types import { IIssueActivity, IIssueComment } from "types"; @@ -120,9 +120,15 @@ export const IssueActivitySection: React.FC = ({ )}{" "} {message}{" "} - - {timeAgo(activityItem.created_at)} - + + + {timeAgo(activityItem.created_at)} + +
diff --git a/web/components/issues/delete-draft-issue-modal.tsx b/web/components/issues/delete-draft-issue-modal.tsx index 6fc4f4218..8347f555b 100644 --- a/web/components/issues/delete-draft-issue-modal.tsx +++ b/web/components/issues/delete-draft-issue-modal.tsx @@ -4,6 +4,8 @@ import { useRouter } from "next/router"; import { mutate } from "swr"; +import useUser from "hooks/use-user"; + // headless ui import { Dialog, Transition } from "@headlessui/react"; // services @@ -16,7 +18,7 @@ import { ExclamationTriangleIcon } from "@heroicons/react/24/outline"; // ui import { SecondaryButton, DangerButton } from "components/ui"; // types -import type { IIssue, ICurrentUserResponse } from "types"; +import type { IIssue } from "types"; // fetch-keys import { PROJECT_DRAFT_ISSUES_LIST_WITH_PARAMS } from "constants/fetch-keys"; @@ -24,12 +26,11 @@ type Props = { isOpen: boolean; handleClose: () => void; data: IIssue | null; - user?: ICurrentUserResponse; onSubmit?: () => Promise | void; }; export const DeleteDraftIssueModal: React.FC = (props) => { - const { isOpen, handleClose, data, user, onSubmit } = props; + const { isOpen, handleClose, data, onSubmit } = props; const [isDeleteLoading, setIsDeleteLoading] = useState(false); @@ -40,6 +41,8 @@ export const DeleteDraftIssueModal: React.FC = (props) => { const { setToastAlert } = useToast(); + const { user } = useUser(); + useEffect(() => { setIsDeleteLoading(false); }, [isOpen]); diff --git a/web/components/issues/delete-issue-modal.tsx b/web/components/issues/delete-issue-modal.tsx index d76e5ddd2..62fc04723 100644 --- a/web/components/issues/delete-issue-modal.tsx +++ b/web/components/issues/delete-issue-modal.tsx @@ -35,6 +35,7 @@ type Props = { data: IIssue | null; user: ICurrentUserResponse | undefined; onSubmit?: () => Promise; + redirection?: boolean; }; export const DeleteIssueModal: React.FC = ({ @@ -43,6 +44,7 @@ export const DeleteIssueModal: React.FC = ({ data, user, onSubmit, + redirection = true, }) => { const [isDeleteLoading, setIsDeleteLoading] = useState(false); @@ -132,7 +134,7 @@ export const DeleteIssueModal: React.FC = ({ message: "Issue deleted successfully", }); - if (issueId) router.back(); + if (issueId && redirection) router.back(); }) .catch((error) => { console.log(error); diff --git a/web/components/issues/draft-issue-form.tsx b/web/components/issues/draft-issue-form.tsx index aac5dede7..7433da82c 100644 --- a/web/components/issues/draft-issue-form.tsx +++ b/web/components/issues/draft-issue-form.tsx @@ -66,6 +66,7 @@ interface IssueFormProps { createMore: boolean; setCreateMore: React.Dispatch>; handleClose: () => void; + handleDiscard: () => void; status: boolean; user: ICurrentUserResponse | undefined; fieldsToShow: ( @@ -97,6 +98,7 @@ export const DraftIssueForm: FC = (props) => { status, user, fieldsToShow, + handleDiscard, } = props; const [stateModal, setStateModal] = useState(false); @@ -569,7 +571,7 @@ export const DraftIssueForm: FC = (props) => { {}} size="md" />
- Discard + Discard diff --git a/web/components/issues/draft-issue-modal.tsx b/web/components/issues/draft-issue-modal.tsx index c060c72f6..b6479d067 100644 --- a/web/components/issues/draft-issue-modal.tsx +++ b/web/components/issues/draft-issue-modal.tsx @@ -97,6 +97,11 @@ export const CreateUpdateDraftIssueModal: React.FC = (props) = setActiveProject(null); }; + const onDiscard = () => { + clearDraftIssueLocalStorage(); + onClose(); + }; + useEffect(() => { setPreloadedData(prePopulateDataProps ?? {}); @@ -141,7 +146,7 @@ export const CreateUpdateDraftIssueModal: React.FC = (props) = if (prePopulateData && prePopulateData.project && !activeProject) return setActiveProject(prePopulateData.project); - if (prePopulateData && prePopulateData.project) + if (prePopulateData && prePopulateData.project && !activeProject) return setActiveProject(prePopulateData.project); // if data is not present, set active project to the project @@ -180,16 +185,8 @@ export const CreateUpdateDraftIssueModal: React.FC = (props) = await issuesService .createDraftIssue(workspaceSlug as string, activeProject ?? "", payload, user) .then(async () => { - mutate(PROJECT_ISSUES_LIST_WITH_PARAMS(activeProject ?? "", params)); mutate(PROJECT_DRAFT_ISSUES_LIST_WITH_PARAMS(activeProject ?? "", params)); - if (displayFilters.layout === "calendar") mutate(calendarFetchKey); - if (displayFilters.layout === "gantt_chart") - mutate(ganttFetchKey, { - start_target_date: true, - order_by: "sort_order", - }); - if (displayFilters.layout === "spreadsheet") mutate(spreadsheetFetchKey); if (groupedIssues) mutateMyIssues(); setToastAlert({ @@ -200,8 +197,6 @@ export const CreateUpdateDraftIssueModal: React.FC = (props) = if (payload.assignees_list?.some((assignee) => assignee === user?.id)) mutate(USER_ISSUE(workspaceSlug as string)); - - if (payload.parent && payload.parent !== "") mutate(SUB_ISSUES(payload.parent)); }) .catch(() => { setToastAlert({ @@ -396,6 +391,7 @@ export const CreateUpdateDraftIssueModal: React.FC = (props) = createMore={createMore} setCreateMore={setCreateMore} handleClose={onClose} + handleDiscard={onDiscard} projectId={activeProject ?? ""} setActiveProject={setActiveProject} status={data ? true : false} diff --git a/web/components/issues/gantt-chart/blocks.tsx b/web/components/issues/gantt-chart/blocks.tsx index ef4919780..3364565a3 100644 --- a/web/components/issues/gantt-chart/blocks.tsx +++ b/web/components/issues/gantt-chart/blocks.tsx @@ -5,7 +5,7 @@ import { Tooltip } from "components/ui"; // icons import { StateGroupIcon } from "components/icons"; // helpers -import { findTotalDaysInRange, renderShortDate } from "helpers/date-time.helper"; +import { renderShortDate } from "helpers/date-time.helper"; // types import { IIssue } from "types"; @@ -52,8 +52,6 @@ export const IssueGanttBlock = ({ data }: { data: IIssue }) => { export const IssueGanttSidebarBlock = ({ data }: { data: IIssue }) => { const router = useRouter(); - const duration = findTotalDaysInRange(data?.start_date ?? "", data?.target_date ?? "", true); - const openPeekOverview = () => { const { query } = router; @@ -72,12 +70,7 @@ export const IssueGanttSidebarBlock = ({ data }: { data: IIssue }) => {
{data?.project_detail?.identifier} {data?.sequence_id}
-
-
{data?.name}
- - {duration} day{duration > 1 ? "s" : ""} - -
+
{data?.name}
); }; diff --git a/web/components/issues/index.ts b/web/components/issues/index.ts index 7785ecd94..9ad0a5867 100644 --- a/web/components/issues/index.ts +++ b/web/components/issues/index.ts @@ -13,7 +13,6 @@ export * from "./main-content"; export * from "./modal"; export * from "./parent-issues-list-modal"; export * from "./sidebar"; -export * from "./sub-issues-list"; export * from "./label"; export * from "./issue-reaction"; export * from "./peek-overview"; diff --git a/web/components/issues/main-content.tsx b/web/components/issues/main-content.tsx index b7b154ce2..c4c9a780a 100644 --- a/web/components/issues/main-content.tsx +++ b/web/components/issues/main-content.tsx @@ -18,9 +18,9 @@ import { IssueAttachmentUpload, IssueAttachments, IssueDescriptionForm, - SubIssuesList, IssueReaction, } from "components/issues"; +import { SubIssuesRoot } from "./sub-issues"; // ui import { CustomMenu } from "components/ui"; // icons @@ -43,7 +43,7 @@ export const IssueMainContent: React.FC = ({ uneditable = false, }) => { const router = useRouter(); - const { workspaceSlug, projectId, issueId, archivedIssueId } = router.query; + const { workspaceSlug, projectId, issueId } = router.query; const { setToastAlert } = useToast(); @@ -206,7 +206,7 @@ export const IssueMainContent: React.FC = ({
- +
diff --git a/web/components/issues/modal.tsx b/web/components/issues/modal.tsx index 5106bb84f..f8c66041d 100644 --- a/web/components/issues/modal.tsx +++ b/web/components/issues/modal.tsx @@ -23,6 +23,7 @@ import useSpreadsheetIssuesView from "hooks/use-spreadsheet-issues-view"; import useProjects from "hooks/use-projects"; import useMyIssues from "hooks/my-issues/use-my-issues"; import useLocalStorage from "hooks/use-local-storage"; +import { useWorkspaceView } from "hooks/use-workspace-view"; // components import { IssueForm, ConfirmIssueDiscard } from "components/issues"; // types @@ -40,6 +41,7 @@ import { VIEW_ISSUES, INBOX_ISSUES, PROJECT_DRAFT_ISSUES_LIST_WITH_PARAMS, + WORKSPACE_VIEW_ISSUES, } from "constants/fetch-keys"; // constants import { INBOX_ISSUE_SOURCE } from "constants/inbox"; @@ -89,9 +91,9 @@ export const CreateUpdateIssueModal: React.FC = observer( const [customAttributesList, setCustomAttributesList] = useState<{ [key: string]: string[] }>( {} ); - const router = useRouter(); - const { workspaceSlug, projectId, cycleId, moduleId, viewId, inboxId } = router.query; + const { workspaceSlug, projectId, cycleId, moduleId, viewId, globalViewId, inboxId } = + router.query; const { customAttributeValues } = useMobxStore(); @@ -106,6 +108,8 @@ export const CreateUpdateIssueModal: React.FC = observer( const { groupedIssues, mutateMyIssues } = useMyIssues(workspaceSlug?.toString()); + const { params: globalViewParams } = useWorkspaceView(); + const { setValue: setValueInLocalStorage, clearValue: clearLocalStorageValue } = useLocalStorage("draftedIssue", {}); @@ -291,6 +295,40 @@ export const CreateUpdateIssueModal: React.FC = observer( }); }; + const workspaceIssuesPath = [ + { + params: { + sub_issue: false, + }, + path: "workspace-views/all-issues", + }, + { + params: { + assignees: user?.id ?? undefined, + sub_issue: false, + }, + path: "workspace-views/assigned", + }, + { + params: { + created_by: user?.id ?? undefined, + sub_issue: false, + }, + path: "workspace-views/created", + }, + { + params: { + subscriber: user?.id ?? undefined, + sub_issue: false, + }, + path: "workspace-views/subscribed", + }, + ]; + + const currentWorkspaceIssuePath = workspaceIssuesPath.find((path) => + router.pathname.includes(path.path) + ); + const calendarFetchKey = cycleId ? CYCLE_ISSUES_WITH_PARAMS(cycleId.toString(), calendarParams) : moduleId @@ -392,6 +430,14 @@ export const CreateUpdateIssueModal: React.FC = observer( mutate(USER_ISSUE(workspaceSlug as string)); if (payload.parent && payload.parent !== "") mutate(SUB_ISSUES(payload.parent)); + + if (globalViewId) + mutate(WORKSPACE_VIEW_ISSUES(globalViewId.toString(), globalViewParams)); + + if (currentWorkspaceIssuePath) + mutate( + WORKSPACE_VIEW_ISSUES(workspaceSlug.toString(), currentWorkspaceIssuePath?.params) + ); }) .catch(() => { setToastAlert({ diff --git a/web/components/issues/my-issues/my-issues-view-options.tsx b/web/components/issues/my-issues/my-issues-view-options.tsx index 90d9b8971..69cfa1909 100644 --- a/web/components/issues/my-issues/my-issues-view-options.tsx +++ b/web/components/issues/my-issues/my-issues-view-options.tsx @@ -2,25 +2,20 @@ import React from "react"; import { useRouter } from "next/router"; -// headless ui -import { Popover, Transition } from "@headlessui/react"; // hooks import useMyIssuesFilters from "hooks/my-issues/use-my-issues-filter"; -import useEstimateOption from "hooks/use-estimate-option"; // components import { MyIssuesSelectFilters } from "components/issues"; // ui -import { CustomMenu, ToggleSwitch, Tooltip } from "components/ui"; +import { Tooltip } from "components/ui"; // icons -import { ChevronDownIcon } from "@heroicons/react/24/outline"; -import { FormatListBulletedOutlined, GridViewOutlined } from "@mui/icons-material"; +import { FormatListBulletedOutlined } from "@mui/icons-material"; +import { CreditCard } from "lucide-react"; // helpers import { replaceUnderscoreIfSnakeCase } from "helpers/string.helper"; import { checkIfArraysHaveSameElements } from "helpers/array.helper"; // types -import { Properties, TIssueViewOptions } from "types"; -// constants -import { GROUP_BY_OPTIONS, ORDER_BY_OPTIONS, FILTER_ISSUE_OPTIONS } from "constants/issue"; +import { TIssueViewOptions } from "types"; const issueViewOptions: { type: TIssueViewOptions; Icon: any }[] = [ { @@ -28,19 +23,26 @@ const issueViewOptions: { type: TIssueViewOptions; Icon: any }[] = [ Icon: FormatListBulletedOutlined, }, { - type: "kanban", - Icon: GridViewOutlined, + type: "spreadsheet", + Icon: CreditCard, }, ]; export const MyIssuesViewOptions: React.FC = () => { const router = useRouter(); - const { workspaceSlug } = router.query; + const { workspaceSlug, globalViewId } = router.query; - const { displayFilters, setDisplayFilters, properties, setProperty, filters, setFilters } = - useMyIssuesFilters(workspaceSlug?.toString()); + const { displayFilters, setDisplayFilters, filters, setFilters } = useMyIssuesFilters( + workspaceSlug?.toString() + ); - const { isEstimateActive } = useEstimateOption(); + const workspaceViewPathName = ["workspace-views/all-issues"]; + + const isWorkspaceViewPath = workspaceViewPathName.some((pathname) => + router.pathname.includes(pathname) + ); + + const showFilters = isWorkspaceViewPath || globalViewId; return (
@@ -55,244 +57,59 @@ export const MyIssuesViewOptions: React.FC = () => { > ))}
- { - const key = option.key as keyof typeof filters; + {showFilters && ( + { + const key = option.key as keyof typeof filters; - if (key === "start_date" || key === "target_date") { - const valueExists = checkIfArraysHaveSameElements(filters?.[key] ?? [], option.value); + if (key === "start_date" || key === "target_date") { + const valueExists = checkIfArraysHaveSameElements(filters?.[key] ?? [], option.value); - setFilters({ - [key]: valueExists ? null : option.value, - }); - } else { - const valueExists = filters[key]?.includes(option.value); - - if (valueExists) setFilters({ - [option.key]: ((filters[key] ?? []) as any[])?.filter( - (val) => val !== option.value - ), + [key]: valueExists ? null : option.value, }); - else - setFilters({ - [option.key]: [...((filters[key] ?? []) as any[]), option.value], - }); - } - }} - direction="left" - height="rg" - /> - - {({ open }) => ( - <> - - Display - + } else { + const valueExists = filters[key]?.includes(option.value); - - -
-
- {displayFilters?.layout !== "calendar" && - displayFilters?.layout !== "spreadsheet" && ( - <> -
-

Group by

-
- option.key === displayFilters?.group_by - )?.name ?? "Select" - } - className="!w-full" - buttonClassName="w-full" - > - {GROUP_BY_OPTIONS.map((option) => { - if (displayFilters?.layout === "kanban" && option.key === null) - return null; - if ( - option.key === "state" || - option.key === "created_by" || - option.key === "assignees" - ) - return null; - - return ( - setDisplayFilters({ group_by: option.key })} - > - {option.name} - - ); - })} - -
-
-
-

Order by

-
- option.key === displayFilters?.order_by - )?.name ?? "Select" - } - className="!w-full" - buttonClassName="w-full" - > - {ORDER_BY_OPTIONS.map((option) => { - if ( - displayFilters?.group_by === "priority" && - option.key === "priority" - ) - return null; - if (option.key === "sort_order") return null; - - return ( - { - setDisplayFilters({ order_by: option.key }); - }} - > - {option.name} - - ); - })} - -
-
- - )} -
-

Issue type

-
- option.key === displayFilters?.type - )?.name ?? "Select" - } - className="!w-full" - buttonClassName="w-full" - > - {FILTER_ISSUE_OPTIONS.map((option) => ( - - setDisplayFilters({ - type: option.key, - }) - } - > - {option.name} - - ))} - -
-
- - {displayFilters?.layout !== "calendar" && - displayFilters?.layout !== "spreadsheet" && ( - <> -
-

Show empty states

-
- - setDisplayFilters({ - show_empty_groups: !displayFilters?.show_empty_groups, - }) - } - /> -
-
- - )} -
- -
-

Display Properties

-
- {Object.keys(properties).map((key) => { - if (key === "estimate" && !isEstimateActive) return null; - - if ( - displayFilters?.layout === "spreadsheet" && - (key === "attachment_count" || - key === "link" || - key === "sub_issue_count") - ) - return null; - - if ( - displayFilters?.layout !== "spreadsheet" && - (key === "created_on" || key === "updated_on") - ) - return null; - - return ( - - ); - })} -
-
-
-
-
- - )} -
+ if (valueExists) + setFilters({ + [option.key]: ((filters[key] ?? []) as any[])?.filter( + (val) => val !== option.value + ), + }); + else + setFilters({ + [option.key]: [...((filters[key] ?? []) as any[]), option.value], + }); + } + }} + direction="left" + height="rg" + /> + )}
); }; diff --git a/web/components/issues/sub-issues-list.tsx b/web/components/issues/sub-issues-list.tsx deleted file mode 100644 index 9ba920ff5..000000000 --- a/web/components/issues/sub-issues-list.tsx +++ /dev/null @@ -1,251 +0,0 @@ -import { FC, useState } from "react"; - -import Link from "next/link"; -import { useRouter } from "next/router"; - -import useSWR, { mutate } from "swr"; - -// headless ui -import { Disclosure, Transition } from "@headlessui/react"; -// services -import issuesService from "services/issues.service"; -// contexts -import { useProjectMyMembership } from "contexts/project-member.context"; -// components -import { ExistingIssuesListModal } from "components/core"; -import { CreateUpdateIssueModal } from "components/issues"; -// ui -import { CustomMenu } from "components/ui"; -// icons -import { ChevronRightIcon, PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; -// types -import { ICurrentUserResponse, IIssue, ISearchIssueResponse, ISubIssueResponse } from "types"; -// fetch-keys -import { SUB_ISSUES } from "constants/fetch-keys"; - -type Props = { - parentIssue: IIssue; - user: ICurrentUserResponse | undefined; - disabled?: boolean; -}; - -export const SubIssuesList: FC = ({ parentIssue, user, disabled = false }) => { - // states - const [createIssueModal, setCreateIssueModal] = useState(false); - const [subIssuesListModal, setSubIssuesListModal] = useState(false); - const [preloadedData, setPreloadedData] = useState | null>(null); - - const router = useRouter(); - const { workspaceSlug } = router.query; - - const { memberRole } = useProjectMyMembership(); - - const { data: subIssuesResponse } = useSWR( - workspaceSlug && parentIssue ? SUB_ISSUES(parentIssue.id) : null, - workspaceSlug && parentIssue - ? () => issuesService.subIssues(workspaceSlug as string, parentIssue.project, parentIssue.id) - : null - ); - - const addAsSubIssue = async (data: ISearchIssueResponse[]) => { - if (!workspaceSlug || !parentIssue) return; - - const payload = { - sub_issue_ids: data.map((i) => i.id), - }; - - await issuesService - .addSubIssues(workspaceSlug as string, parentIssue.project, parentIssue.id, payload) - .finally(() => mutate(SUB_ISSUES(parentIssue.id))); - }; - - const handleSubIssueRemove = (issue: IIssue) => { - if (!workspaceSlug || !parentIssue) return; - - mutate( - SUB_ISSUES(parentIssue.id), - (prevData) => { - if (!prevData) return prevData; - - const stateDistribution = { ...prevData.state_distribution }; - - const issueGroup = issue.state_detail.group; - stateDistribution[issueGroup] = stateDistribution[issueGroup] - 1; - - return { - state_distribution: stateDistribution, - sub_issues: prevData.sub_issues.filter((i) => i.id !== issue.id), - }; - }, - false - ); - - issuesService - .patchIssue(workspaceSlug.toString(), issue.project, issue.id, { parent: null }, user) - .finally(() => mutate(SUB_ISSUES(parentIssue.id))); - }; - - const handleCreateIssueModal = () => { - setCreateIssueModal(true); - - setPreloadedData({ - parent: parentIssue.id, - }); - }; - - const completedSubIssue = subIssuesResponse?.state_distribution.completed ?? 0; - const cancelledSubIssue = subIssuesResponse?.state_distribution.cancelled ?? 0; - - const totalCompletedSubIssues = completedSubIssue + cancelledSubIssue; - - const totalSubIssues = subIssuesResponse ? subIssuesResponse.sub_issues.length : 0; - - const completionPercentage = (totalCompletedSubIssues / totalSubIssues) * 100; - - const isNotAllowed = memberRole.isGuest || memberRole.isViewer || disabled; - - return ( - <> - setCreateIssueModal(false)} - /> - setSubIssuesListModal(false)} - searchParams={{ sub_issue: true, issue_id: parentIssue?.id }} - handleOnSubmit={addAsSubIssue} - workspaceLevelToggle - /> - {subIssuesResponse && subIssuesResponse.sub_issues.length > 0 ? ( - - {({ open }) => ( - <> -
-
- - - Sub-issues{" "} - - {subIssuesResponse.sub_issues.length} - - -
-
-
100 - ? 100 - : completionPercentage.toFixed(0) - }%`, - }} - /> -
- - {isNaN(completionPercentage) - ? 0 - : completionPercentage > 100 - ? 100 - : completionPercentage.toFixed(0)} - % Done - -
-
- - {open && !isNotAllowed ? ( -
- - - - setSubIssuesListModal(true)}> - Add an existing issue - - -
- ) : null} -
- - - {subIssuesResponse.sub_issues.map((issue) => ( - - -
- - - {issue.project_detail.identifier}-{issue.sequence_id} - - {issue.name} -
- - {!isNotAllowed && ( - - )} -
- - ))} -
-
- - )} - - ) : ( - !isNotAllowed && ( - - - Add sub-issue - - } - buttonClassName="whitespace-nowrap" - position="left" - noBorder - noChevron - > - Create new - setSubIssuesListModal(true)}> - Add an existing issue - - - ) - )} - - ); -}; diff --git a/web/components/issues/sub-issues/index.ts b/web/components/issues/sub-issues/index.ts new file mode 100644 index 000000000..1efe34c51 --- /dev/null +++ b/web/components/issues/sub-issues/index.ts @@ -0,0 +1 @@ +export * from "./root"; diff --git a/web/components/issues/sub-issues/issue.tsx b/web/components/issues/sub-issues/issue.tsx new file mode 100644 index 000000000..d9c6fd303 --- /dev/null +++ b/web/components/issues/sub-issues/issue.tsx @@ -0,0 +1,207 @@ +import React from "react"; +// next imports +import Link from "next/link"; +import { useRouter } from "next/router"; +// lucide icons +import { + ChevronDown, + ChevronRight, + X, + Pencil, + Trash, + Link as LinkIcon, + Loader, +} from "lucide-react"; +// components +import { SubIssuesRootList } from "./issues-list"; +import { IssueProperty } from "./properties"; +// ui +import { Tooltip, CustomMenu } from "components/ui"; +// types +import { ICurrentUserResponse, IIssue } from "types"; +import { ISubIssuesRootLoaders, ISubIssuesRootLoadersHandler } from "./root"; + +export interface ISubIssues { + workspaceSlug: string; + projectId: string; + parentIssue: IIssue; + issue: any; + spacingLeft?: number; + user: ICurrentUserResponse | undefined; + editable: boolean; + removeIssueFromSubIssues: (parentIssueId: string, issue: IIssue) => void; + issuesLoader: ISubIssuesRootLoaders; + handleIssuesLoader: ({ key, issueId }: ISubIssuesRootLoadersHandler) => void; + copyText: (text: string) => void; + handleIssueCrudOperation: ( + key: "create" | "existing" | "edit" | "delete", + issueId: string, + issue?: IIssue | null + ) => void; + setPeekParentId: (id: string) => void; +} + +export const SubIssues: React.FC = ({ + workspaceSlug, + projectId, + parentIssue, + issue, + spacingLeft = 0, + user, + editable, + removeIssueFromSubIssues, + issuesLoader, + handleIssuesLoader, + copyText, + handleIssueCrudOperation, + setPeekParentId, +}) => { + const router = useRouter(); + + const openPeekOverview = (issue_id: string) => { + const { query } = router; + + setPeekParentId(parentIssue?.id); + router.push({ + pathname: router.pathname, + query: { ...query, peekIssue: issue_id }, + }); + }; + + return ( +
+ {issue && ( +
+
+ {issue?.sub_issues_count > 0 && ( + <> + {issuesLoader.sub_issues.includes(issue?.id) ? ( +
+ +
+ ) : ( +
handleIssuesLoader({ key: "visibility", issueId: issue?.id })} + > + {issuesLoader && issuesLoader.visibility.includes(issue?.id) ? ( + + ) : ( + + )} +
+ )} + + )} +
+ +
openPeekOverview(issue?.id)} + > +
+
+ {issue.project_detail.identifier}-{issue?.sequence_id} +
+ +
{issue?.name}
+
+
+ +
+ +
+ +
+ + {editable && ( + handleIssueCrudOperation("edit", parentIssue?.id, issue)} + > +
+ + Edit issue +
+
+ )} + + {editable && ( + handleIssueCrudOperation("delete", parentIssue?.id, issue)} + > +
+ + Delete issue +
+
+ )} + + + copyText(`${workspaceSlug}/projects/${issue.project}/issues/${issue.id}`) + } + > +
+ + Copy issue link +
+
+
+
+ + {editable && ( + <> + {issuesLoader.delete.includes(issue?.id) ? ( +
+ +
+ ) : ( +
{ + handleIssuesLoader({ key: "delete", issueId: issue?.id }); + removeIssueFromSubIssues(parentIssue?.id, issue); + }} + > + +
+ )} + + )} +
+ )} + + {issuesLoader.visibility.includes(issue?.id) && issue?.sub_issues_count > 0 && ( + + )} +
+ ); +}; diff --git a/web/components/issues/sub-issues/issues-list.tsx b/web/components/issues/sub-issues/issues-list.tsx new file mode 100644 index 000000000..a713d6fb8 --- /dev/null +++ b/web/components/issues/sub-issues/issues-list.tsx @@ -0,0 +1,98 @@ +import React from "react"; +// swr +import useSWR from "swr"; +// components +import { SubIssues } from "./issue"; +// types +import { ICurrentUserResponse, IIssue } from "types"; +import { ISubIssuesRootLoaders, ISubIssuesRootLoadersHandler } from "./root"; +// services +import issuesService from "services/issues.service"; +// fetch keys +import { SUB_ISSUES } from "constants/fetch-keys"; + +export interface ISubIssuesRootList { + workspaceSlug: string; + projectId: string; + parentIssue: IIssue; + spacingLeft?: number; + user: ICurrentUserResponse | undefined; + editable: boolean; + removeIssueFromSubIssues: (parentIssueId: string, issue: IIssue) => void; + issuesLoader: ISubIssuesRootLoaders; + handleIssuesLoader: ({ key, issueId }: ISubIssuesRootLoadersHandler) => void; + copyText: (text: string) => void; + handleIssueCrudOperation: ( + key: "create" | "existing" | "edit" | "delete", + issueId: string, + issue?: IIssue | null + ) => void; + setPeekParentId: (id: string) => void; +} + +export const SubIssuesRootList: React.FC = ({ + workspaceSlug, + projectId, + parentIssue, + spacingLeft = 10, + user, + editable, + removeIssueFromSubIssues, + issuesLoader, + handleIssuesLoader, + copyText, + handleIssueCrudOperation, + setPeekParentId, +}) => { + const { data: issues, isLoading } = useSWR( + workspaceSlug && projectId && parentIssue && parentIssue?.id + ? SUB_ISSUES(parentIssue?.id) + : null, + workspaceSlug && projectId && parentIssue && parentIssue?.id + ? () => issuesService.subIssues(workspaceSlug, projectId, parentIssue.id) + : null + ); + + React.useEffect(() => { + if (isLoading) { + handleIssuesLoader({ key: "sub_issues", issueId: parentIssue?.id }); + } else { + if (issuesLoader.sub_issues.includes(parentIssue?.id)) { + handleIssuesLoader({ key: "sub_issues", issueId: parentIssue?.id }); + } + } + }, [isLoading]); + + return ( +
+ {issues && + issues.sub_issues && + issues.sub_issues.length > 0 && + issues.sub_issues.map((issue: IIssue) => ( + + ))} + +
10 ? `border-l border-custom-border-100` : `` + }`} + style={{ left: `${spacingLeft - 12}px` }} + /> +
+ ); +}; diff --git a/web/components/issues/sub-issues/progressbar.tsx b/web/components/issues/sub-issues/progressbar.tsx new file mode 100644 index 000000000..dee91263b --- /dev/null +++ b/web/components/issues/sub-issues/progressbar.tsx @@ -0,0 +1,25 @@ +export interface IProgressBar { + total: number; + done: number; +} + +export const ProgressBar = ({ total = 0, done = 0 }: IProgressBar) => { + const calPercentage = (doneValue: number, totalValue: number): string => { + if (doneValue === 0 || totalValue === 0) return (0).toFixed(0); + return ((100 * doneValue) / totalValue).toFixed(0); + }; + + return ( +
+
+
+
+
+
+
{calPercentage(done, total)}% Done
+
+ ); +}; diff --git a/web/components/issues/sub-issues/properties.tsx b/web/components/issues/sub-issues/properties.tsx new file mode 100644 index 000000000..e2caefffa --- /dev/null +++ b/web/components/issues/sub-issues/properties.tsx @@ -0,0 +1,208 @@ +import React from "react"; +// swr +import { mutate } from "swr"; +// components +import { ViewDueDateSelect, ViewStartDateSelect } from "components/issues"; +import { MembersSelect, PrioritySelect } from "components/project"; +import { StateSelect } from "components/states"; +// hooks +import useIssuesProperties from "hooks/use-issue-properties"; +// types +import { ICurrentUserResponse, IIssue, IState } from "types"; +// fetch-keys +import { SUB_ISSUES } from "constants/fetch-keys"; +// services +import issuesService from "services/issues.service"; +import trackEventServices from "services/track-event.service"; + +export interface IIssueProperty { + workspaceSlug: string; + projectId: string; + parentIssue: IIssue; + issue: IIssue; + user: ICurrentUserResponse | undefined; + editable: boolean; +} + +export const IssueProperty: React.FC = ({ + workspaceSlug, + projectId, + parentIssue, + issue, + user, + editable, +}) => { + const [properties] = useIssuesProperties(workspaceSlug, projectId); + + const handlePriorityChange = (data: any) => { + partialUpdateIssue({ priority: data }); + trackEventServices.trackIssuePartialPropertyUpdateEvent( + { + workspaceSlug, + workspaceId: issue.workspace, + projectId: issue.project_detail.id, + projectIdentifier: issue.project_detail.identifier, + projectName: issue.project_detail.name, + issueId: issue.id, + }, + "ISSUE_PROPERTY_UPDATE_PRIORITY", + user + ); + }; + + const handleStateChange = (data: string, states: IState[] | undefined) => { + const oldState = states?.find((s) => s.id === issue.state); + const newState = states?.find((s) => s.id === data); + + partialUpdateIssue({ + state: data, + state_detail: newState, + }); + trackEventServices.trackIssuePartialPropertyUpdateEvent( + { + workspaceSlug, + workspaceId: issue.workspace, + projectId: issue.project_detail.id, + projectIdentifier: issue.project_detail.identifier, + projectName: issue.project_detail.name, + issueId: issue.id, + }, + "ISSUE_PROPERTY_UPDATE_STATE", + user + ); + if (oldState?.group !== "completed" && newState?.group !== "completed") { + trackEventServices.trackIssueMarkedAsDoneEvent( + { + workspaceSlug: issue.workspace_detail.slug, + workspaceId: issue.workspace_detail.id, + projectId: issue.project_detail.id, + projectIdentifier: issue.project_detail.identifier, + projectName: issue.project_detail.name, + issueId: issue.id, + }, + user + ); + } + }; + + const handleAssigneeChange = (data: any) => { + let newData = issue.assignees ?? []; + + if (newData && newData.length > 0) { + if (newData.includes(data)) newData = newData.splice(newData.indexOf(data), 1); + else newData = [...newData, data]; + } else newData = [...newData, data]; + + partialUpdateIssue({ assignees_list: data, assignees: data }); + + trackEventServices.trackIssuePartialPropertyUpdateEvent( + { + workspaceSlug, + workspaceId: issue.workspace, + projectId: issue.project_detail.id, + projectIdentifier: issue.project_detail.identifier, + projectName: issue.project_detail.name, + issueId: issue.id, + }, + "ISSUE_PROPERTY_UPDATE_ASSIGNEE", + user + ); + }; + + const partialUpdateIssue = async (data: Partial) => { + mutate( + workspaceSlug && parentIssue ? SUB_ISSUES(parentIssue.id) : null, + (elements: any) => { + const _elements = { ...elements }; + const _issues = _elements.sub_issues.map((element: IIssue) => + element.id === issue.id ? { ...element, ...data } : element + ); + _elements["sub_issues"] = [..._issues]; + return _elements; + }, + false + ); + + const issueResponse = await issuesService.patchIssue( + workspaceSlug as string, + issue.project, + issue.id, + data, + user + ); + + mutate( + SUB_ISSUES(parentIssue.id), + (elements: any) => { + const _elements = elements.sub_issues.map((element: IIssue) => + element.id === issue.id ? issueResponse : element + ); + elements["sub_issues"] = _elements; + return elements; + }, + true + ); + }; + + return ( +
+ {properties.priority && ( +
+ +
+ )} + + {properties.state && ( +
+ +
+ )} + + {properties.start_date && issue.start_date && ( +
+ +
+ )} + + {properties.due_date && issue.target_date && ( +
+ +
+ )} + + {properties.assignee && ( +
+ +
+ )} +
+ ); +}; diff --git a/web/components/issues/sub-issues/root.tsx b/web/components/issues/sub-issues/root.tsx new file mode 100644 index 000000000..352546eab --- /dev/null +++ b/web/components/issues/sub-issues/root.tsx @@ -0,0 +1,375 @@ +import React from "react"; +// next imports +import { useRouter } from "next/router"; +// swr +import useSWR, { mutate } from "swr"; +// lucide icons +import { Plus, ChevronRight, ChevronDown } from "lucide-react"; +// components +import { ExistingIssuesListModal } from "components/core"; +import { CreateUpdateIssueModal, DeleteIssueModal } from "components/issues"; +import { SubIssuesRootList } from "./issues-list"; +import { ProgressBar } from "./progressbar"; +import { IssuePeekOverview } from "components/issues/peek-overview"; +// ui +import { CustomMenu } from "components/ui"; +// hooks +import { useProjectMyMembership } from "contexts/project-member.context"; +import useToast from "hooks/use-toast"; +// helpers +import { copyTextToClipboard } from "helpers/string.helper"; +// types +import { ICurrentUserResponse, IIssue, ISearchIssueResponse } from "types"; +// services +import issuesService from "services/issues.service"; +// fetch keys +import { SUB_ISSUES } from "constants/fetch-keys"; + +export interface ISubIssuesRoot { + parentIssue: IIssue; + user: ICurrentUserResponse | undefined; +} + +export interface ISubIssuesRootLoaders { + visibility: string[]; + delete: string[]; + sub_issues: string[]; +} +export interface ISubIssuesRootLoadersHandler { + key: "visibility" | "delete" | "sub_issues"; + issueId: string; +} + +export const SubIssuesRoot: React.FC = ({ parentIssue, user }) => { + const router = useRouter(); + const { workspaceSlug, projectId, peekIssue } = router.query as { + workspaceSlug: string; + projectId: string; + peekIssue: string; + }; + + const { memberRole } = useProjectMyMembership(); + const { setToastAlert } = useToast(); + + const { data: issues, isLoading } = useSWR( + workspaceSlug && projectId && parentIssue && parentIssue?.id + ? SUB_ISSUES(parentIssue?.id) + : null, + workspaceSlug && projectId && parentIssue && parentIssue?.id + ? () => issuesService.subIssues(workspaceSlug, projectId, parentIssue.id) + : null + ); + + const [peekParentId, setPeekParentId] = React.useState(""); + + const [issuesLoader, setIssuesLoader] = React.useState({ + visibility: [parentIssue?.id], + delete: [], + sub_issues: [], + }); + const handleIssuesLoader = ({ key, issueId }: ISubIssuesRootLoadersHandler) => { + setIssuesLoader((previousData: ISubIssuesRootLoaders) => ({ + ...previousData, + [key]: previousData[key].includes(issueId) + ? previousData[key].filter((i: string) => i !== issueId) + : [...previousData[key], issueId], + })); + }; + + const [issueCrudOperation, setIssueCrudOperation] = React.useState<{ + create: { toggle: boolean; issueId: string | null }; + existing: { toggle: boolean; issueId: string | null }; + edit: { toggle: boolean; issueId: string | null; issue: IIssue | null }; + delete: { toggle: boolean; issueId: string | null; issue: IIssue | null }; + }>({ + create: { + toggle: false, + issueId: null, + }, + existing: { + toggle: false, + issueId: null, + }, + edit: { + toggle: false, + issueId: null, // parent issue id for mutation + issue: null, + }, + delete: { + toggle: false, + issueId: null, // parent issue id for mutation + issue: null, + }, + }); + const handleIssueCrudOperation = ( + key: "create" | "existing" | "edit" | "delete", + issueId: string | null, + issue: IIssue | null = null + ) => { + setIssueCrudOperation({ + ...issueCrudOperation, + [key]: { + toggle: !issueCrudOperation[key].toggle, + issueId: issueId, + issue: issue, + }, + }); + }; + + const addAsSubIssueFromExistingIssues = async (data: ISearchIssueResponse[]) => { + if (!workspaceSlug || !parentIssue || issueCrudOperation?.existing?.issueId === null) return; + const issueId = issueCrudOperation?.existing?.issueId; + const payload = { + sub_issue_ids: data.map((i) => i.id), + }; + await issuesService.addSubIssues(workspaceSlug, projectId, issueId, payload).finally(() => { + if (issueId) mutate(SUB_ISSUES(issueId)); + }); + }; + + const removeIssueFromSubIssues = async (parentIssueId: string, issue: IIssue) => { + if (!workspaceSlug || !parentIssue || !issue?.id) return; + issuesService + .patchIssue(workspaceSlug, projectId, issue.id, { parent: null }, user) + .then(async () => { + if (parentIssueId) await mutate(SUB_ISSUES(parentIssueId)); + handleIssuesLoader({ key: "delete", issueId: issue?.id }); + setToastAlert({ + type: "success", + title: `Issue removed!`, + message: `Issue removed successfully.`, + }); + }) + .catch(() => { + handleIssuesLoader({ key: "delete", issueId: issue?.id }); + setToastAlert({ + type: "warning", + title: `Error!`, + message: `Error, Please try again later.`, + }); + }); + }; + + const copyText = (text: string) => { + const originURL = + typeof window !== "undefined" && window.location.origin ? window.location.origin : ""; + copyTextToClipboard(`${originURL}/${text}`).then(() => { + setToastAlert({ + type: "success", + title: "Link Copied!", + message: "Issue link copied to clipboard.", + }); + }); + }; + + const isEditable = memberRole?.isGuest || memberRole?.isViewer ? false : true; + + const mutateSubIssues = (parentIssueId: string | null) => { + if (parentIssueId) mutate(SUB_ISSUES(parentIssueId)); + }; + + return ( +
+ {!issues && isLoading ? ( +
Loading...
+ ) : ( + <> + {issues && issues?.sub_issues && issues?.sub_issues?.length > 0 ? ( + <> + {/* header */} +
+
+ handleIssuesLoader({ key: "visibility", issueId: parentIssue?.id }) + } + > +
+ {issuesLoader.visibility.includes(parentIssue?.id) ? ( + + ) : ( + + )} +
+
Sub-issues
+
({issues?.sub_issues?.length || 0})
+
+ +
+ +
+ + {isEditable && issuesLoader.visibility.includes(parentIssue?.id) && ( +
+
handleIssueCrudOperation("create", parentIssue?.id)} + > + Add sub-issue +
+
handleIssueCrudOperation("existing", parentIssue?.id)} + > + Add an existing issue +
+
+ )} +
+ + {/* issues */} + {issuesLoader.visibility.includes(parentIssue?.id) && ( +
+ +
+ )} + +
+ + + Add sub-issue + + } + buttonClassName="whitespace-nowrap" + position="left" + noBorder + noChevron + > + { + mutateSubIssues(parentIssue?.id); + handleIssueCrudOperation("create", parentIssue?.id); + }} + > + Create new + + { + mutateSubIssues(parentIssue?.id); + handleIssueCrudOperation("existing", parentIssue?.id); + }} + > + Add an existing issue + + +
+ + ) : ( + isEditable && ( +
+
No Sub-Issues yet
+
+ + + Add sub-issue + + } + buttonClassName="whitespace-nowrap" + position="left" + noBorder + noChevron + > + { + mutateSubIssues(parentIssue?.id); + handleIssueCrudOperation("create", parentIssue?.id); + }} + > + Create new + + { + mutateSubIssues(parentIssue?.id); + handleIssueCrudOperation("existing", parentIssue?.id); + }} + > + Add an existing issue + + +
+
+ ) + )} + {isEditable && issueCrudOperation?.create?.toggle && ( + { + mutateSubIssues(issueCrudOperation?.create?.issueId); + handleIssueCrudOperation("create", null); + }} + /> + )} + {isEditable && + issueCrudOperation?.existing?.toggle && + issueCrudOperation?.existing?.issueId && ( + handleIssueCrudOperation("existing", null)} + searchParams={{ sub_issue: true, issue_id: issueCrudOperation?.existing?.issueId }} + handleOnSubmit={addAsSubIssueFromExistingIssues} + workspaceLevelToggle + /> + )} + {isEditable && issueCrudOperation?.edit?.toggle && issueCrudOperation?.edit?.issueId && ( + <> + { + mutateSubIssues(issueCrudOperation?.edit?.issueId); + handleIssueCrudOperation("edit", null, null); + }} + data={issueCrudOperation?.edit?.issue} + /> + + )} + {isEditable && + issueCrudOperation?.delete?.toggle && + issueCrudOperation?.delete?.issueId && ( + { + mutateSubIssues(issueCrudOperation?.delete?.issueId); + handleIssueCrudOperation("delete", null, null); + }} + data={issueCrudOperation?.delete?.issue} + user={user} + redirection={false} + /> + )} + + )} + + peekParentId && peekIssue && mutateSubIssues(peekParentId)} + projectId={projectId ?? ""} + workspaceSlug={workspaceSlug ?? ""} + readOnly={!isEditable} + /> +
+ ); +}; diff --git a/web/components/issues/workspace-views/workpace-view-issues.tsx b/web/components/issues/workspace-views/workpace-view-issues.tsx new file mode 100644 index 000000000..78a12f807 --- /dev/null +++ b/web/components/issues/workspace-views/workpace-view-issues.tsx @@ -0,0 +1,232 @@ +import React, { useCallback, useState } from "react"; + +import useSWR from "swr"; + +import { useRouter } from "next/router"; + +// context +import { useProjectMyMembership } from "contexts/project-member.context"; +// service +import projectIssuesServices from "services/issues.service"; +// hooks +import useProjects from "hooks/use-projects"; +import useUser from "hooks/use-user"; +import { useWorkspaceView } from "hooks/use-workspace-view"; +import useWorkspaceMembers from "hooks/use-workspace-members"; +import useToast from "hooks/use-toast"; +// components +import { WorkspaceViewsNavigation } from "components/workspace/views/workpace-view-navigation"; +import { EmptyState, PrimaryButton } from "components/ui"; +import { SpreadsheetView, WorkspaceFiltersList } from "components/core"; +import { CreateUpdateIssueModal, DeleteIssueModal } from "components/issues"; +import { CreateUpdateWorkspaceViewModal } from "components/workspace/views/modal"; +// icon +import { PlusIcon } from "components/icons"; +// image +import emptyView from "public/empty-state/view.svg"; +// constants +import { WORKSPACE_LABELS } from "constants/fetch-keys"; +import { STATE_GROUP } from "constants/project"; +// types +import { IIssue, IWorkspaceIssueFilterOptions } from "types"; + +export const WorkspaceViewIssues = () => { + const router = useRouter(); + const { workspaceSlug, globalViewId } = router.query; + + const { setToastAlert } = useToast(); + + const { memberRole } = useProjectMyMembership(); + const { user } = useUser(); + const { isGuest, isViewer } = useWorkspaceMembers( + workspaceSlug?.toString(), + Boolean(workspaceSlug) + ); + const { filters, viewIssues, mutateViewIssues, handleFilters } = useWorkspaceView(); + + const [createViewModal, setCreateViewModal] = useState(null); + + // create issue modal + const [createIssueModal, setCreateIssueModal] = useState(false); + const [preloadedData, setPreloadedData] = useState< + (Partial & { actionType: "createIssue" | "edit" | "delete" }) | undefined + >(undefined); + + // update issue modal + const [editIssueModal, setEditIssueModal] = useState(false); + const [issueToEdit, setIssueToEdit] = useState< + (IIssue & { actionType: "edit" | "delete" }) | undefined + >(undefined); + + // delete issue modal + const [deleteIssueModal, setDeleteIssueModal] = useState(false); + const [issueToDelete, setIssueToDelete] = useState(null); + + const { projects: allProjects } = useProjects(); + const joinedProjects = allProjects?.filter((p) => p.is_member); + + const { data: workspaceLabels } = useSWR( + workspaceSlug ? WORKSPACE_LABELS(workspaceSlug.toString()) : null, + workspaceSlug ? () => projectIssuesServices.getWorkspaceLabels(workspaceSlug.toString()) : null + ); + + const { workspaceMembers } = useWorkspaceMembers(workspaceSlug?.toString() ?? ""); + + const makeIssueCopy = useCallback( + (issue: IIssue) => { + setCreateIssueModal(true); + + setPreloadedData({ ...issue, name: `${issue.name} (Copy)`, actionType: "createIssue" }); + }, + [setCreateIssueModal, setPreloadedData] + ); + + const handleEditIssue = useCallback( + (issue: IIssue) => { + setEditIssueModal(true); + setIssueToEdit({ + ...issue, + actionType: "edit", + cycle: issue.issue_cycle ? issue.issue_cycle.cycle : null, + module: issue.issue_module ? issue.issue_module.module : null, + }); + }, + [setEditIssueModal, setIssueToEdit] + ); + + const handleDeleteIssue = useCallback( + (issue: IIssue) => { + setDeleteIssueModal(true); + setIssueToDelete(issue); + }, + [setDeleteIssueModal, setIssueToDelete] + ); + + const handleIssueAction = useCallback( + (issue: IIssue, action: "copy" | "edit" | "delete" | "updateDraft") => { + if (action === "copy") makeIssueCopy(issue); + else if (action === "edit") handleEditIssue(issue); + else if (action === "delete") handleDeleteIssue(issue); + }, + [makeIssueCopy, handleEditIssue, handleDeleteIssue] + ); + + const nullFilters = + filters.filters && + Object.keys(filters.filters).filter( + (key) => + filters.filters[key as keyof IWorkspaceIssueFilterOptions] === null || + (filters.filters[key as keyof IWorkspaceIssueFilterOptions]?.length ?? 0) <= 0 + ); + + const areFiltersApplied = + filters.filters && + Object.keys(filters.filters).length > 0 && + nullFilters.length !== Object.keys(filters.filters).length; + + const isNotAllowed = isGuest || isViewer; + return ( + <> + setCreateIssueModal(false)} + prePopulateData={{ + ...preloadedData, + }} + onSubmit={async () => mutateViewIssues()} + /> + setEditIssueModal(false)} + data={issueToEdit} + onSubmit={async () => mutateViewIssues()} + /> + setDeleteIssueModal(false)} + isOpen={deleteIssueModal} + data={issueToDelete} + user={user} + onSubmit={async () => mutateViewIssues()} + /> + setCreateViewModal(null)} + preLoadedData={createViewModal} + /> +
+
+ setCreateViewModal(true)} /> + {false ? ( + router.push(`/${workspaceSlug}/workspace-views`), + }} + /> + ) : ( +
+ {areFiltersApplied && ( + <> +
+ handleFilters("filters", updatedFilter)} + labels={workspaceLabels} + members={workspaceMembers?.map((m) => m.member)} + stateGroup={STATE_GROUP} + project={joinedProjects} + clearAllFilters={() => + handleFilters("filters", { + assignees: null, + created_by: null, + labels: null, + priority: null, + state_group: null, + start_date: null, + target_date: null, + subscriber: null, + project: null, + }) + } + /> + { + if (globalViewId) { + handleFilters("filters", filters.filters, true); + setToastAlert({ + title: "View updated", + message: "Your view has been updated", + type: "success", + }); + } else + setCreateViewModal({ + query: filters.filters, + }); + }} + className="flex items-center gap-2 text-sm" + > + {!globalViewId && } + {globalViewId ? "Update" : "Save"} view + +
+ {
} + + )} + +
+ )} +
+
+ + ); +}; diff --git a/web/components/issues/workspace-views/workspace-all-issue.tsx b/web/components/issues/workspace-views/workspace-all-issue.tsx new file mode 100644 index 000000000..4618c331d --- /dev/null +++ b/web/components/issues/workspace-views/workspace-all-issue.tsx @@ -0,0 +1,236 @@ +import { useCallback, useState } from "react"; +import { useRouter } from "next/router"; + +import useSWR from "swr"; + +// hook +import useUser from "hooks/use-user"; +import useWorkspaceMembers from "hooks/use-workspace-members"; +import useProjects from "hooks/use-projects"; +import { useWorkspaceView } from "hooks/use-workspace-view"; +// context +import { useProjectMyMembership } from "contexts/project-member.context"; +// services +import workspaceService from "services/workspace.service"; +import projectIssuesServices from "services/issues.service"; +// components +import { SpreadsheetView, WorkspaceFiltersList } from "components/core"; +import { WorkspaceViewsNavigation } from "components/workspace/views/workpace-view-navigation"; +import { CreateUpdateIssueModal, DeleteIssueModal } from "components/issues"; +import { CreateUpdateWorkspaceViewModal } from "components/workspace/views/modal"; +// ui +import { PrimaryButton } from "components/ui"; +// icons +import { PlusIcon } from "@heroicons/react/24/outline"; +// fetch-keys +import { WORKSPACE_LABELS, WORKSPACE_VIEW_ISSUES } from "constants/fetch-keys"; +// constants +import { STATE_GROUP } from "constants/project"; +// types +import { IIssue, IWorkspaceIssueFilterOptions } from "types"; + +export const WorkspaceAllIssue = () => { + const router = useRouter(); + const { workspaceSlug, globalViewId } = router.query; + + const [createViewModal, setCreateViewModal] = useState(null); + + // create issue modal + const [createIssueModal, setCreateIssueModal] = useState(false); + const [preloadedData, setPreloadedData] = useState< + (Partial & { actionType: "createIssue" | "edit" | "delete" }) | undefined + >(undefined); + + // update issue modal + const [editIssueModal, setEditIssueModal] = useState(false); + const [issueToEdit, setIssueToEdit] = useState< + (IIssue & { actionType: "edit" | "delete" }) | undefined + >(undefined); + + // delete issue modal + const [deleteIssueModal, setDeleteIssueModal] = useState(false); + const [issueToDelete, setIssueToDelete] = useState(null); + + const { user } = useUser(); + const { memberRole } = useProjectMyMembership(); + + const { workspaceMembers } = useWorkspaceMembers(workspaceSlug?.toString() ?? ""); + + const { data: workspaceLabels } = useSWR( + workspaceSlug ? WORKSPACE_LABELS(workspaceSlug.toString()) : null, + workspaceSlug ? () => projectIssuesServices.getWorkspaceLabels(workspaceSlug.toString()) : null + ); + + const { filters, handleFilters } = useWorkspaceView(); + + const params: any = { + assignees: filters?.filters?.assignees ? filters?.filters?.assignees.join(",") : undefined, + subscriber: filters?.filters?.subscriber ? filters?.filters?.subscriber.join(",") : undefined, + state_group: filters?.filters?.state_group + ? filters?.filters?.state_group.join(",") + : undefined, + priority: filters?.filters?.priority ? filters?.filters?.priority.join(",") : undefined, + labels: filters?.filters?.labels ? filters?.filters?.labels.join(",") : undefined, + created_by: filters?.filters?.created_by ? filters?.filters?.created_by.join(",") : undefined, + start_date: filters?.filters?.start_date ? filters?.filters?.start_date.join(",") : undefined, + target_date: filters?.filters?.target_date + ? filters?.filters?.target_date.join(",") + : undefined, + project: filters?.filters?.project ? filters?.filters?.project.join(",") : undefined, + sub_issue: false, + type: undefined, + }; + + const { data: viewIssues, mutate: mutateViewIssues } = useSWR( + workspaceSlug ? WORKSPACE_VIEW_ISSUES(workspaceSlug.toString(), params) : null, + workspaceSlug ? () => workspaceService.getViewIssues(workspaceSlug.toString(), params) : null + ); + + const makeIssueCopy = useCallback( + (issue: IIssue) => { + setCreateIssueModal(true); + + setPreloadedData({ ...issue, name: `${issue.name} (Copy)`, actionType: "createIssue" }); + }, + [setCreateIssueModal, setPreloadedData] + ); + + const handleEditIssue = useCallback( + (issue: IIssue) => { + setEditIssueModal(true); + setIssueToEdit({ + ...issue, + actionType: "edit", + cycle: issue.issue_cycle ? issue.issue_cycle.cycle : null, + module: issue.issue_module ? issue.issue_module.module : null, + }); + }, + [setEditIssueModal, setIssueToEdit] + ); + + const handleDeleteIssue = useCallback( + (issue: IIssue) => { + setDeleteIssueModal(true); + setIssueToDelete(issue); + }, + [setDeleteIssueModal, setIssueToDelete] + ); + + const handleIssueAction = useCallback( + (issue: IIssue, action: "copy" | "edit" | "delete" | "updateDraft") => { + if (action === "copy") makeIssueCopy(issue); + else if (action === "edit") handleEditIssue(issue); + else if (action === "delete") handleDeleteIssue(issue); + }, + [makeIssueCopy, handleEditIssue, handleDeleteIssue] + ); + + const nullFilters = + filters.filters && + Object.keys(filters.filters).filter( + (key) => + filters.filters[key as keyof IWorkspaceIssueFilterOptions] === null || + (filters.filters[key as keyof IWorkspaceIssueFilterOptions]?.length ?? 0) <= 0 + ); + + const areFiltersApplied = + filters.filters && + Object.keys(filters.filters).length > 0 && + nullFilters.length !== Object.keys(filters.filters).length; + + const { projects: allProjects } = useProjects(); + const joinedProjects = allProjects?.filter((p) => p.is_member); + + return ( + <> + setCreateIssueModal(false)} + prePopulateData={{ + ...preloadedData, + }} + onSubmit={async () => { + mutateViewIssues(); + }} + /> + setEditIssueModal(false)} + data={issueToEdit} + onSubmit={async () => { + mutateViewIssues(); + }} + /> + setDeleteIssueModal(false)} + isOpen={deleteIssueModal} + data={issueToDelete} + user={user} + onSubmit={async () => { + mutateViewIssues(); + }} + /> + setCreateViewModal(null)} + preLoadedData={createViewModal} + /> +
+
+ setCreateViewModal(true)} /> +
+ {areFiltersApplied && ( + <> +
+ handleFilters("filters", updatedFilter)} + labels={workspaceLabels} + members={workspaceMembers?.map((m) => m.member)} + stateGroup={STATE_GROUP} + project={joinedProjects} + clearAllFilters={() => + handleFilters("filters", { + assignees: null, + created_by: null, + labels: null, + priority: null, + state_group: null, + start_date: null, + target_date: null, + subscriber: null, + project: null, + }) + } + /> + { + if (globalViewId) handleFilters("filters", filters.filters, true); + else + setCreateViewModal({ + query: filters.filters, + }); + }} + className="flex items-center gap-2 text-sm" + > + {!globalViewId && } + {globalViewId ? "Update" : "Save"} view + +
+ {
} + + )} + +
+
+
+ + ); +}; diff --git a/web/components/issues/workspace-views/workspace-assigned-issue.tsx b/web/components/issues/workspace-views/workspace-assigned-issue.tsx new file mode 100644 index 000000000..4469804ac --- /dev/null +++ b/web/components/issues/workspace-views/workspace-assigned-issue.tsx @@ -0,0 +1,148 @@ +import React, { useCallback, useState } from "react"; +import { useRouter } from "next/router"; + +import useSWR from "swr"; + +// hook +import useUser from "hooks/use-user"; +// context +import { useProjectMyMembership } from "contexts/project-member.context"; +// services +import workspaceService from "services/workspace.service"; +// components +import { SpreadsheetView } from "components/core"; +import { WorkspaceViewsNavigation } from "components/workspace/views/workpace-view-navigation"; +import { CreateUpdateIssueModal, DeleteIssueModal } from "components/issues"; +import { CreateUpdateWorkspaceViewModal } from "components/workspace/views/modal"; +// fetch-keys +import { WORKSPACE_VIEW_ISSUES } from "constants/fetch-keys"; +// types +import { IIssue } from "types"; + +export const WorkspaceAssignedIssue = () => { + const [createViewModal, setCreateViewModal] = useState(null); + + // create issue modal + const [createIssueModal, setCreateIssueModal] = useState(false); + const [preloadedData, setPreloadedData] = useState< + (Partial & { actionType: "createIssue" | "edit" | "delete" }) | undefined + >(undefined); + + // update issue modal + const [editIssueModal, setEditIssueModal] = useState(false); + const [issueToEdit, setIssueToEdit] = useState< + (IIssue & { actionType: "edit" | "delete" }) | undefined + >(undefined); + + // delete issue modal + const [deleteIssueModal, setDeleteIssueModal] = useState(false); + const [issueToDelete, setIssueToDelete] = useState(null); + + const router = useRouter(); + const { workspaceSlug } = router.query; + + const { user } = useUser(); + + const { memberRole } = useProjectMyMembership(); + + const params: any = { + assignees: user?.id ?? undefined, + sub_issue: false, + }; + + const { data: viewIssues, mutate: mutateIssues } = useSWR( + workspaceSlug ? WORKSPACE_VIEW_ISSUES(workspaceSlug.toString(), params) : null, + workspaceSlug ? () => workspaceService.getViewIssues(workspaceSlug.toString(), params) : null + ); + + const makeIssueCopy = useCallback( + (issue: IIssue) => { + setCreateIssueModal(true); + + setPreloadedData({ ...issue, name: `${issue.name} (Copy)`, actionType: "createIssue" }); + }, + [setCreateIssueModal, setPreloadedData] + ); + + const handleEditIssue = useCallback( + (issue: IIssue) => { + setEditIssueModal(true); + setIssueToEdit({ + ...issue, + actionType: "edit", + cycle: issue.issue_cycle ? issue.issue_cycle.cycle : null, + module: issue.issue_module ? issue.issue_module.module : null, + }); + }, + [setEditIssueModal, setIssueToEdit] + ); + + const handleDeleteIssue = useCallback( + (issue: IIssue) => { + setDeleteIssueModal(true); + setIssueToDelete(issue); + }, + [setDeleteIssueModal, setIssueToDelete] + ); + + const handleIssueAction = useCallback( + (issue: IIssue, action: "copy" | "edit" | "delete" | "updateDraft") => { + if (action === "copy") makeIssueCopy(issue); + else if (action === "edit") handleEditIssue(issue); + else if (action === "delete") handleDeleteIssue(issue); + }, + [makeIssueCopy, handleEditIssue, handleDeleteIssue] + ); + return ( + <> + setCreateIssueModal(false)} + prePopulateData={{ + ...preloadedData, + }} + onSubmit={async () => { + mutateIssues(); + }} + /> + setEditIssueModal(false)} + data={issueToEdit} + onSubmit={async () => { + mutateIssues(); + }} + /> + setDeleteIssueModal(false)} + isOpen={deleteIssueModal} + data={issueToDelete} + user={user} + onSubmit={async () => { + mutateIssues(); + }} + /> + setCreateViewModal(null)} + preLoadedData={createViewModal} + /> +
+
+ setCreateViewModal(true)} /> + +
+ +
+
+
+ + ); +}; diff --git a/web/components/issues/workspace-views/workspace-created-issues.tsx b/web/components/issues/workspace-views/workspace-created-issues.tsx new file mode 100644 index 000000000..bcc83c38b --- /dev/null +++ b/web/components/issues/workspace-views/workspace-created-issues.tsx @@ -0,0 +1,147 @@ +import React, { useCallback, useState } from "react"; + +import { useRouter } from "next/router"; + +import useSWR from "swr"; + +// hook +import useUser from "hooks/use-user"; +// context +import { useProjectMyMembership } from "contexts/project-member.context"; +// services +import workspaceService from "services/workspace.service"; +// components +import { SpreadsheetView } from "components/core"; +import { WorkspaceViewsNavigation } from "components/workspace/views/workpace-view-navigation"; +import { CreateUpdateIssueModal, DeleteIssueModal } from "components/issues"; +import { CreateUpdateWorkspaceViewModal } from "components/workspace/views/modal"; +// fetch-keys +import { WORKSPACE_VIEW_ISSUES } from "constants/fetch-keys"; +// types +import { IIssue } from "types"; + +export const WorkspaceCreatedIssues = () => { + const [createViewModal, setCreateViewModal] = useState(null); + + // create issue modal + const [createIssueModal, setCreateIssueModal] = useState(false); + const [preloadedData, setPreloadedData] = useState< + (Partial & { actionType: "createIssue" | "edit" | "delete" }) | undefined + >(undefined); + + // update issue modal + const [editIssueModal, setEditIssueModal] = useState(false); + const [issueToEdit, setIssueToEdit] = useState< + (IIssue & { actionType: "edit" | "delete" }) | undefined + >(undefined); + + // delete issue modal + const [deleteIssueModal, setDeleteIssueModal] = useState(false); + const [issueToDelete, setIssueToDelete] = useState(null); + + const router = useRouter(); + const { workspaceSlug } = router.query; + + const { user } = useUser(); + const { memberRole } = useProjectMyMembership(); + + const params: any = { + created_by: user?.id ?? undefined, + sub_issue: false, + }; + + const { data: viewIssues, mutate: mutateIssues } = useSWR( + workspaceSlug ? WORKSPACE_VIEW_ISSUES(workspaceSlug.toString(), params) : null, + workspaceSlug ? () => workspaceService.getViewIssues(workspaceSlug.toString(), params) : null + ); + + const makeIssueCopy = useCallback( + (issue: IIssue) => { + setCreateIssueModal(true); + + setPreloadedData({ ...issue, name: `${issue.name} (Copy)`, actionType: "createIssue" }); + }, + [setCreateIssueModal, setPreloadedData] + ); + + const handleEditIssue = useCallback( + (issue: IIssue) => { + setEditIssueModal(true); + setIssueToEdit({ + ...issue, + actionType: "edit", + cycle: issue.issue_cycle ? issue.issue_cycle.cycle : null, + module: issue.issue_module ? issue.issue_module.module : null, + }); + }, + [setEditIssueModal, setIssueToEdit] + ); + + const handleDeleteIssue = useCallback( + (issue: IIssue) => { + setDeleteIssueModal(true); + setIssueToDelete(issue); + }, + [setDeleteIssueModal, setIssueToDelete] + ); + + const handleIssueAction = useCallback( + (issue: IIssue, action: "copy" | "edit" | "delete" | "updateDraft") => { + if (action === "copy") makeIssueCopy(issue); + else if (action === "edit") handleEditIssue(issue); + else if (action === "delete") handleDeleteIssue(issue); + }, + [makeIssueCopy, handleEditIssue, handleDeleteIssue] + ); + return ( + <> + setCreateIssueModal(false)} + prePopulateData={{ + ...preloadedData, + }} + onSubmit={async () => { + mutateIssues(); + }} + /> + setEditIssueModal(false)} + data={issueToEdit} + onSubmit={async () => { + mutateIssues(); + }} + /> + setDeleteIssueModal(false)} + isOpen={deleteIssueModal} + data={issueToDelete} + user={user} + onSubmit={async () => { + mutateIssues(); + }} + /> + setCreateViewModal(null)} + preLoadedData={createViewModal} + /> +
+
+ setCreateViewModal(true)} /> +
+ +
+
+
+ + ); +}; diff --git a/web/components/issues/workspace-views/workspace-issue-view-option.tsx b/web/components/issues/workspace-views/workspace-issue-view-option.tsx new file mode 100644 index 000000000..25ddc338a --- /dev/null +++ b/web/components/issues/workspace-views/workspace-issue-view-option.tsx @@ -0,0 +1,116 @@ +import React from "react"; + +import { useRouter } from "next/router"; + +// hooks +import { useWorkspaceView } from "hooks/use-workspace-view"; +// components +import { GlobalSelectFilters } from "components/workspace/views/global-select-filters"; +// ui +import { Tooltip } from "components/ui"; +// icons +import { FormatListBulletedOutlined } from "@mui/icons-material"; +import { CreditCard } from "lucide-react"; +// helpers +import { replaceUnderscoreIfSnakeCase } from "helpers/string.helper"; +import { checkIfArraysHaveSameElements } from "helpers/array.helper"; +// types +import { TIssueViewOptions } from "types"; + +const issueViewOptions: { type: TIssueViewOptions; Icon: any }[] = [ + { + type: "list", + Icon: FormatListBulletedOutlined, + }, + { + type: "spreadsheet", + Icon: CreditCard, + }, +]; + +export const WorkspaceIssuesViewOptions: React.FC = () => { + const router = useRouter(); + const { workspaceSlug, globalViewId } = router.query; + + const { filters, handleFilters } = useWorkspaceView(); + + const isWorkspaceViewPath = router.pathname.includes("workspace-views/all-issues"); + + const showFilters = isWorkspaceViewPath || globalViewId; + + return ( +
+
+ {issueViewOptions.map((option) => ( + {replaceUnderscoreIfSnakeCase(option.type)} View + } + position="bottom" + > + + + ))} +
+ + {showFilters && ( + <> + { + const key = option.key as keyof typeof filters.filters; + + if (key === "start_date" || key === "target_date") { + const valueExists = checkIfArraysHaveSameElements( + filters.filters?.[key] ?? [], + option.value + ); + + handleFilters("filters", { + ...filters, + [key]: valueExists ? null : option.value, + }); + } else { + if (!filters?.filters?.[key]?.includes(option.value)) + handleFilters("filters", { + ...filters, + [key]: [...((filters?.filters?.[key] as any[]) ?? []), option.value], + }); + else { + handleFilters("filters", { + ...filters, + [key]: (filters?.filters?.[key] as any[])?.filter( + (item) => item !== option.value + ), + }); + } + } + }} + direction="left" + /> + + )} +
+ ); +}; diff --git a/web/components/issues/workspace-views/workspace-subscribed-issue.tsx b/web/components/issues/workspace-views/workspace-subscribed-issue.tsx new file mode 100644 index 000000000..d9db2f347 --- /dev/null +++ b/web/components/issues/workspace-views/workspace-subscribed-issue.tsx @@ -0,0 +1,148 @@ +import React, { useCallback, useState } from "react"; + +import { useRouter } from "next/router"; + +import useSWR from "swr"; + +// hook +import useUser from "hooks/use-user"; +// context +import { useProjectMyMembership } from "contexts/project-member.context"; +// services +import workspaceService from "services/workspace.service"; +// components +import { SpreadsheetView } from "components/core"; +import { WorkspaceViewsNavigation } from "components/workspace/views/workpace-view-navigation"; +import { CreateUpdateIssueModal, DeleteIssueModal } from "components/issues"; +import { CreateUpdateWorkspaceViewModal } from "components/workspace/views/modal"; +// fetch-keys +import { WORKSPACE_VIEW_ISSUES } from "constants/fetch-keys"; +// types +import { IIssue } from "types"; + +export const WorkspaceSubscribedIssues = () => { + const [createViewModal, setCreateViewModal] = useState(null); + + // create issue modal + const [createIssueModal, setCreateIssueModal] = useState(false); + const [preloadedData, setPreloadedData] = useState< + (Partial & { actionType: "createIssue" | "edit" | "delete" }) | undefined + >(undefined); + + // update issue modal + const [editIssueModal, setEditIssueModal] = useState(false); + const [issueToEdit, setIssueToEdit] = useState< + (IIssue & { actionType: "edit" | "delete" }) | undefined + >(undefined); + + // delete issue modal + const [deleteIssueModal, setDeleteIssueModal] = useState(false); + const [issueToDelete, setIssueToDelete] = useState(null); + + const router = useRouter(); + const { workspaceSlug } = router.query; + + const { user } = useUser(); + const { memberRole } = useProjectMyMembership(); + + const params: any = { + subscriber: user?.id ?? undefined, + sub_issue: false, + }; + + const { data: viewIssues, mutate: mutateIssues } = useSWR( + workspaceSlug ? WORKSPACE_VIEW_ISSUES(workspaceSlug.toString(), params) : null, + workspaceSlug ? () => workspaceService.getViewIssues(workspaceSlug.toString(), params) : null + ); + + const makeIssueCopy = useCallback( + (issue: IIssue) => { + setCreateIssueModal(true); + + setPreloadedData({ ...issue, name: `${issue.name} (Copy)`, actionType: "createIssue" }); + }, + [setCreateIssueModal, setPreloadedData] + ); + + const handleEditIssue = useCallback( + (issue: IIssue) => { + setEditIssueModal(true); + setIssueToEdit({ + ...issue, + actionType: "edit", + cycle: issue.issue_cycle ? issue.issue_cycle.cycle : null, + module: issue.issue_module ? issue.issue_module.module : null, + }); + }, + [setEditIssueModal, setIssueToEdit] + ); + + const handleDeleteIssue = useCallback( + (issue: IIssue) => { + setDeleteIssueModal(true); + setIssueToDelete(issue); + }, + [setDeleteIssueModal, setIssueToDelete] + ); + + const handleIssueAction = useCallback( + (issue: IIssue, action: "copy" | "edit" | "delete" | "updateDraft") => { + if (action === "copy") makeIssueCopy(issue); + else if (action === "edit") handleEditIssue(issue); + else if (action === "delete") handleDeleteIssue(issue); + }, + [makeIssueCopy, handleEditIssue, handleDeleteIssue] + ); + return ( + <> + setCreateIssueModal(false)} + prePopulateData={{ + ...preloadedData, + }} + onSubmit={async () => { + mutateIssues(); + }} + /> + setEditIssueModal(false)} + data={issueToEdit} + onSubmit={async () => { + mutateIssues(); + }} + /> + setDeleteIssueModal(false)} + isOpen={deleteIssueModal} + data={issueToDelete} + user={user} + onSubmit={async () => { + mutateIssues(); + }} + /> + setCreateViewModal(null)} + preLoadedData={createViewModal} + /> +
+
+ setCreateViewModal(true)} /> + +
+ +
+
+
+ + ); +}; diff --git a/web/components/labels/single-label.tsx b/web/components/labels/single-label.tsx index be981e510..c163a3735 100644 --- a/web/components/labels/single-label.tsx +++ b/web/components/labels/single-label.tsx @@ -1,11 +1,13 @@ -import React from "react"; +import React, { useRef, useState } from "react"; +//hook +import useOutsideClickDetector from "hooks/use-outside-click-detector"; // ui import { CustomMenu } from "components/ui"; // types import { IIssueLabels } from "types"; //icons -import { RectangleGroupIcon, PencilIcon } from "@heroicons/react/24/outline"; +import { PencilIcon } from "@heroicons/react/24/outline"; import { Component, X } from "lucide-react"; type Props = { @@ -20,9 +22,14 @@ export const SingleLabel: React.FC = ({ addLabelToGroup, editLabel, handleLabelDelete, -}) => ( -
-
+}) => { + const [isMenuActive, setIsMenuActive] = useState(false); + const actionSectionRef = useRef(null); + + useOutsideClickDetector(actionSectionRef, () => setIsMenuActive(false)); + + return ( +
= ({ />
{label.name}
-
-
- - -
- } +
+ setIsMenuActive(!isMenuActive)}> + +
+ } + > + addLabelToGroup(label)}> + + + Convert to group + + + editLabel(label)}> + + + Edit label + + + +
+
- -
-
-
-); + ); +}; diff --git a/web/components/onboarding/invite-members.tsx b/web/components/onboarding/invite-members.tsx index fee1cb252..8f1b1fa41 100644 --- a/web/components/onboarding/invite-members.tsx +++ b/web/components/onboarding/invite-members.tsx @@ -1,15 +1,27 @@ -import React, { useEffect } from "react"; +import React, { useEffect, useRef, useState } from "react"; +// headless ui +import { Listbox, Transition } from "@headlessui/react"; // react-hook-form -import { Controller, useFieldArray, useForm } from "react-hook-form"; +import { + Control, + Controller, + FieldArrayWithId, + UseFieldArrayRemove, + useFieldArray, + useForm, +} from "react-hook-form"; // services import workspaceService from "services/workspace.service"; // hooks import useToast from "hooks/use-toast"; // ui -import { CustomSelect, Input, PrimaryButton, SecondaryButton } from "components/ui"; +import { Input, PrimaryButton, SecondaryButton } from "components/ui"; +// hooks +import useDynamicDropdownPosition from "hooks/use-dynamic-dropdown"; // icons -import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline"; +import { ChevronDownIcon } from "@heroicons/react/20/solid"; +import { PlusIcon, XMarkIcon, CheckIcon } from "@heroicons/react/24/outline"; // types import { ICurrentUserResponse, IWorkspace, TOnboardingSteps } from "types"; // constants @@ -31,12 +43,136 @@ type FormValues = { emails: EmailRole[]; }; -export const InviteMembers: React.FC = ({ - finishOnboarding, - stepChange, - user, - workspace, -}) => { +type InviteMemberFormProps = { + index: number; + remove: UseFieldArrayRemove; + control: Control; + field: FieldArrayWithId; + fields: FieldArrayWithId[]; + errors: any; +}; + +const InviteMemberForm: React.FC = (props) => { + const { control, index, fields, remove, errors } = props; + + const buttonRef = useRef(null); + const dropdownRef = useRef(null); + + const [isDropdownOpen, setIsDropdownOpen] = useState(false); + + useDynamicDropdownPosition( + isDropdownOpen, + () => setIsDropdownOpen(false), + buttonRef, + dropdownRef + ); + + return ( +
+
+ ( + <> + + {errors.emails?.[index]?.email && ( + + {errors.emails?.[index]?.email?.message} + + )} + + )} + /> +
+
+ ( + { + onChange(val); + setIsDropdownOpen(false); + }} + className="flex-shrink-0 text-left w-full" + > + setIsDropdownOpen((prev) => !prev)} + className="flex items-center px-2.5 py-2 text-xs justify-between gap-1 w-full rounded-md border border-custom-border-300 shadow-sm duration-300 focus:outline-none" + > + {ROLE[value]} + + + + +
+ {Object.entries(ROLE).map(([key, value]) => ( + + `cursor-pointer select-none truncate rounded px-1 py-1.5 ${ + active || selected ? "bg-custom-background-80" : "" + } ${selected ? "text-custom-text-100" : "text-custom-text-200"}` + } + > + {({ selected }) => ( +
+
{value}
+ {selected && } +
+ )} +
+ ))} +
+
+
+
+ )} + /> +
+ {fields.length > 1 && ( + + )} +
+ ); +}; + +export const InviteMembers: React.FC = (props) => { + const { finishOnboarding, stepChange, user, workspace } = props; + const { setToastAlert } = useToast(); const { @@ -109,66 +245,15 @@ export const InviteMembers: React.FC = ({
{fields.map((field, index) => ( -
-
- ( - <> - - {errors.emails?.[index]?.email && ( - - {errors.emails?.[index]?.email?.message} - - )} - - )} - /> -
-
- ( - {ROLE[value]}} - onChange={onChange} - width="w-full" - input - > - {Object.entries(ROLE).map(([key, value]) => ( - - {value} - - ))} - - )} - /> -
- {fields.length > 1 && ( - - )} -
+ ))}
- ); - })} + return ( + + ); + })}
diff --git a/web/components/profile/profile-issues-view.tsx b/web/components/profile/profile-issues-view.tsx index b0337ecd4..9d6a53ffe 100644 --- a/web/components/profile/profile-issues-view.tsx +++ b/web/components/profile/profile-issues-view.tsx @@ -51,7 +51,6 @@ export const ProfileIssuesView = () => { groupedIssues, mutateProfileIssues, displayFilters, - setDisplayFilters, isEmpty, filters, setFilters, @@ -228,7 +227,8 @@ export const ProfileIssuesView = () => { router.pathname.includes("my-issues")) ?? false; - const disableAddIssueOption = isSubscribedIssuesRoute || isMySubscribedIssues; + const disableAddIssueOption = + isSubscribedIssuesRoute || isMySubscribedIssues || user?.id !== userId; return ( <> diff --git a/web/components/project/label-select.tsx b/web/components/project/label-select.tsx index b4cc6da06..c155dea14 100644 --- a/web/components/project/label-select.tsx +++ b/web/components/project/label-select.tsx @@ -24,6 +24,7 @@ import { PROJECT_ISSUE_LABELS } from "constants/fetch-keys"; type Props = { value: string[]; + projectId: string; onChange: (data: any) => void; labelsDetails: any[]; className?: string; @@ -37,6 +38,7 @@ type Props = { export const LabelSelect: React.FC = ({ value, + projectId, onChange, labelsDetails, className = "", @@ -54,15 +56,15 @@ export const LabelSelect: React.FC = ({ const [labelModal, setLabelModal] = useState(false); const router = useRouter(); - const { workspaceSlug, projectId } = router.query; + const { workspaceSlug } = router.query; const dropdownBtn = useRef(null); const dropdownOptions = useRef(null); const { data: issueLabels } = useSWR( - projectId && fetchStates ? PROJECT_ISSUE_LABELS(projectId.toString()) : null, + projectId && fetchStates ? PROJECT_ISSUE_LABELS(projectId) : null, workspaceSlug && projectId && fetchStates - ? () => issuesService.getIssueLabels(workspaceSlug as string, projectId as string) + ? () => issuesService.getIssueLabels(workspaceSlug as string, projectId) : null ); @@ -150,7 +152,7 @@ export const LabelSelect: React.FC = ({ setLabelModal(false)} - projectId={projectId.toString()} + projectId={projectId} user={user} /> )} diff --git a/web/components/project/members-select.tsx b/web/components/project/members-select.tsx index f99d85174..57523df8d 100644 --- a/web/components/project/members-select.tsx +++ b/web/components/project/members-select.tsx @@ -18,6 +18,7 @@ import { IUser } from "types"; type Props = { value: string | string[]; + projectId: string; onChange: (data: any) => void; membersDetails: IUser[]; renderWorkspaceMembers?: boolean; @@ -30,6 +31,7 @@ type Props = { export const MembersSelect: React.FC = ({ value, + projectId, onChange, membersDetails, renderWorkspaceMembers = false, @@ -44,14 +46,14 @@ export const MembersSelect: React.FC = ({ const [fetchStates, setFetchStates] = useState(false); const router = useRouter(); - const { workspaceSlug, projectId } = router.query; + const { workspaceSlug } = router.query; const dropdownBtn = useRef(null); const dropdownOptions = useRef(null); const { members } = useProjectMembers( workspaceSlug?.toString(), - projectId?.toString(), + projectId, fetchStates && !renderWorkspaceMembers ); @@ -82,7 +84,7 @@ export const MembersSelect: React.FC = ({ 0 + membersDetails && membersDetails.length > 0 ? membersDetails.map((assignee) => assignee?.display_name).join(", ") : "No Assignee" } diff --git a/web/components/project/single-project-card.tsx b/web/components/project/single-project-card.tsx index 547211c53..eb88e7381 100644 --- a/web/components/project/single-project-card.tsx +++ b/web/components/project/single-project-card.tsx @@ -149,7 +149,7 @@ export const SingleProjectCard: React.FC = ({ ) : ( - Member + Joined )} {project.is_favorite && ( diff --git a/web/components/states/state-select.tsx b/web/components/states/state-select.tsx index ed37e97b5..9f6b40d04 100644 --- a/web/components/states/state-select.tsx +++ b/web/components/states/state-select.tsx @@ -25,6 +25,7 @@ import { getStatesList } from "helpers/state.helper"; type Props = { value: IState; onChange: (data: any, states: IState[] | undefined) => void; + projectId: string; className?: string; buttonClassName?: string; optionsClassName?: string; @@ -35,6 +36,7 @@ type Props = { export const StateSelect: React.FC = ({ value, onChange, + projectId, className = "", buttonClassName = "", optionsClassName = "", @@ -50,12 +52,12 @@ export const StateSelect: React.FC = ({ const [fetchStates, setFetchStates] = useState(false); const router = useRouter(); - const { workspaceSlug, projectId } = router.query; + const { workspaceSlug } = router.query; const { data: stateGroups } = useSWR( - workspaceSlug && projectId && fetchStates ? STATES_LIST(projectId as string) : null, + workspaceSlug && projectId && fetchStates ? STATES_LIST(projectId) : null, workspaceSlug && projectId && fetchStates - ? () => stateService.getStates(workspaceSlug as string, projectId as string) + ? () => stateService.getStates(workspaceSlug as string, projectId) : null ); diff --git a/web/components/ui/dropdowns/custom-menu.tsx b/web/components/ui/dropdowns/custom-menu.tsx index c451d4432..41450b2b3 100644 --- a/web/components/ui/dropdowns/custom-menu.tsx +++ b/web/components/ui/dropdowns/custom-menu.tsx @@ -19,6 +19,7 @@ export type CustomMenuProps = DropdownProps & { const CustomMenu = ({ buttonClassName = "", + customButtonClassName = "", children, className = "", customButton, @@ -40,7 +41,12 @@ const CustomMenu = ({ {({ open }) => ( <> {customButton ? ( - + {customButton} ) : ( diff --git a/web/components/ui/dropdowns/types.d.ts b/web/components/ui/dropdowns/types.d.ts index aace1858a..b368a7ed8 100644 --- a/web/components/ui/dropdowns/types.d.ts +++ b/web/components/ui/dropdowns/types.d.ts @@ -1,5 +1,6 @@ export type DropdownProps = { buttonClassName?: string; + customButtonClassName?: string; className?: string; customButton?: JSX.Element; disabled?: boolean; diff --git a/web/components/ui/product-updates-modal.tsx b/web/components/ui/product-updates-modal.tsx index b142f8325..4f5bad7b3 100644 --- a/web/components/ui/product-updates-modal.tsx +++ b/web/components/ui/product-updates-modal.tsx @@ -1,15 +1,16 @@ import React from "react"; + import useSWR from "swr"; // headless ui import { Dialog, Transition } from "@headlessui/react"; -// component -import { MarkdownRenderer, Spinner } from "components/ui"; -// icons -import { XMarkIcon } from "@heroicons/react/20/solid"; // services import workspaceService from "services/workspace.service"; -// helper +// components +import { Loader, MarkdownRenderer } from "components/ui"; +// icons +import { XMarkIcon } from "@heroicons/react/20/solid"; +// helpers import { renderLongDateFormat } from "helpers/date-time.helper"; type Props = { @@ -34,8 +35,8 @@ export const ProductUpdatesModal: React.FC = ({ isOpen, setIsOpen }) => {
-
-
+
+
= ({ isOpen, setIsOpen }) => { leaveFrom="opacity-100 translate-y-0 sm:scale-100" leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95" > - -
-
-
- - Product Updates - - - - - {updates && updates.length > 0 ? ( - updates.map((item, index) => ( - -
- - {item.tag_name} + +
+ + Product Updates + + + + + {updates && updates.length > 0 ? ( +
+ {updates.map((item, index) => ( + +
+ + {item.tag_name} + + {renderLongDateFormat(item.published_at)} + {index === 0 && ( + + New - {renderLongDateFormat(item.published_at)} - {index === 0 && ( - - New - - )} -
- -
- )) - ) : ( -
- - Loading... -
- )} + )} +
+ + + ))}
-
+ ) : ( +
+ +
+ + + +
+
+ + + +
+
+ + + +
+
+
+ )}
diff --git a/web/components/ui/toggle-switch.tsx b/web/components/ui/toggle-switch.tsx index e52ff26c9..d6c512ad7 100644 --- a/web/components/ui/toggle-switch.tsx +++ b/web/components/ui/toggle-switch.tsx @@ -35,7 +35,7 @@ export const ToggleSwitch: React.FC = (props) => { : size === "md" ? "translate-x-4" : "translate-x-5") + " bg-white" - : "translate-x-1 bg-custom-background-90" + : "translate-x-0.5 bg-custom-background-90" }`} /> diff --git a/web/components/views/delete-view-modal.tsx b/web/components/views/delete-view-modal.tsx index c65f7ba29..61c627430 100644 --- a/web/components/views/delete-view-modal.tsx +++ b/web/components/views/delete-view-modal.tsx @@ -46,9 +46,8 @@ export const DeleteViewModal: React.FC = ({ isOpen, data, setIsOpen, user await viewsService .deleteView(workspaceSlug as string, projectId as string, data.id, user) .then(() => { - mutate( - VIEWS_LIST(projectId as string), - (views) => views?.filter((view) => view.id !== data.id) + mutate(VIEWS_LIST(projectId as string), (views) => + views?.filter((view) => view.id !== data.id) ); handleClose(); diff --git a/web/components/views/select-filters.tsx b/web/components/views/select-filters.tsx index 52671f41f..c3aadc33d 100644 --- a/web/components/views/select-filters.tsx +++ b/web/components/views/select-filters.tsx @@ -18,7 +18,7 @@ import { PriorityIcon, StateGroupIcon } from "components/icons"; import { getStatesList } from "helpers/state.helper"; import { checkIfArraysHaveSameElements } from "helpers/array.helper"; // types -import { IIssueFilterOptions, IQuery } from "types"; +import { IIssueFilterOptions } from "types"; // fetch-keys import { PROJECT_ISSUE_LABELS, PROJECT_MEMBERS, STATES_LIST } from "constants/fetch-keys"; // constants @@ -26,7 +26,7 @@ import { PRIORITIES } from "constants/project"; import { DATE_FILTER_OPTIONS } from "constants/filters"; type Props = { - filters: Partial | IQuery; + filters: Partial; onSelect: (option: any) => void; direction?: "left" | "right"; height?: "sm" | "md" | "rg" | "lg"; @@ -72,6 +72,185 @@ export const SelectFilters: React.FC = ({ : null ); + const projectFilterOption = [ + { + id: "priority", + label: "Priority", + value: PRIORITIES, + hasChildren: true, + children: PRIORITIES.map((priority) => ({ + id: priority === null ? "null" : priority, + label: ( +
+ + {priority ?? "None"} +
+ ), + value: { + key: "priority", + value: priority === null ? "null" : priority, + }, + selected: filters?.priority?.includes(priority === null ? "null" : priority), + })), + }, + { + id: "state", + label: "State", + value: statesList, + hasChildren: true, + children: statesList?.map((state) => ({ + id: state.id, + label: ( +
+ + {state.name} +
+ ), + value: { + key: "state", + value: state.id, + }, + selected: filters?.state?.includes(state.id), + })), + }, + { + id: "assignees", + label: "Assignees", + value: members, + hasChildren: true, + children: members?.map((member) => ({ + id: member.member.id, + label: ( +
+ + {member.member.display_name} +
+ ), + value: { + key: "assignees", + value: member.member.id, + }, + selected: filters?.assignees?.includes(member.member.id), + })), + }, + { + id: "created_by", + label: "Created by", + value: members, + hasChildren: true, + children: members?.map((member) => ({ + id: member.member.id, + label: ( +
+ + {member.member.display_name} +
+ ), + value: { + key: "created_by", + value: member.member.id, + }, + selected: filters?.created_by?.includes(member.member.id), + })), + }, + { + id: "labels", + label: "Labels", + value: issueLabels, + hasChildren: true, + children: issueLabels?.map((label) => ({ + id: label.id, + label: ( +
+
+ {label.name} +
+ ), + value: { + key: "labels", + value: label.id, + }, + selected: filters?.labels?.includes(label.id), + })), + }, + { + id: "start_date", + label: "Start date", + value: DATE_FILTER_OPTIONS, + hasChildren: true, + children: [ + ...DATE_FILTER_OPTIONS.map((option) => ({ + id: option.name, + label: option.name, + value: { + key: "start_date", + value: option.value, + }, + selected: checkIfArraysHaveSameElements(filters?.start_date ?? [], option.value), + })), + { + id: "custom", + label: "Custom", + value: "custom", + element: ( + + ), + }, + ], + }, + { + id: "target_date", + label: "Due date", + value: DATE_FILTER_OPTIONS, + hasChildren: true, + children: [ + ...DATE_FILTER_OPTIONS.map((option) => ({ + id: option.name, + label: option.name, + value: { + key: "target_date", + value: option.value, + }, + selected: checkIfArraysHaveSameElements(filters?.target_date ?? [], option.value), + })), + { + id: "custom", + label: "Custom", + value: "custom", + element: ( + + ), + }, + ], + }, + ]; return ( <> {isDateFilterModalOpen && ( @@ -89,185 +268,7 @@ export const SelectFilters: React.FC = ({ onSelect={onSelect} direction={direction} height={height} - options={[ - { - id: "priority", - label: "Priority", - value: PRIORITIES, - hasChildren: true, - children: PRIORITIES.map((priority) => ({ - id: priority === null ? "null" : priority, - label: ( -
- - {priority ?? "None"} -
- ), - value: { - key: "priority", - value: priority === null ? "null" : priority, - }, - selected: filters?.priority?.includes(priority === null ? "null" : priority), - })), - }, - { - id: "state", - label: "State", - value: statesList, - hasChildren: true, - children: statesList?.map((state) => ({ - id: state.id, - label: ( -
- - {state.name} -
- ), - value: { - key: "state", - value: state.id, - }, - selected: filters?.state?.includes(state.id), - })), - }, - { - id: "assignees", - label: "Assignees", - value: members, - hasChildren: true, - children: members?.map((member) => ({ - id: member.member.id, - label: ( -
- - {member.member.display_name} -
- ), - value: { - key: "assignees", - value: member.member.id, - }, - selected: filters?.assignees?.includes(member.member.id), - })), - }, - { - id: "created_by", - label: "Created by", - value: members, - hasChildren: true, - children: members?.map((member) => ({ - id: member.member.id, - label: ( -
- - {member.member.display_name} -
- ), - value: { - key: "created_by", - value: member.member.id, - }, - selected: filters?.created_by?.includes(member.member.id), - })), - }, - { - id: "labels", - label: "Labels", - value: issueLabels, - hasChildren: true, - children: issueLabels?.map((label) => ({ - id: label.id, - label: ( -
-
- {label.name} -
- ), - value: { - key: "labels", - value: label.id, - }, - selected: filters?.labels?.includes(label.id), - })), - }, - { - id: "start_date", - label: "Start date", - value: DATE_FILTER_OPTIONS, - hasChildren: true, - children: [ - ...DATE_FILTER_OPTIONS.map((option) => ({ - id: option.name, - label: option.name, - value: { - key: "start_date", - value: option.value, - }, - selected: checkIfArraysHaveSameElements(filters?.start_date ?? [], option.value), - })), - { - id: "custom", - label: "Custom", - value: "custom", - element: ( - - ), - }, - ], - }, - { - id: "target_date", - label: "Due date", - value: DATE_FILTER_OPTIONS, - hasChildren: true, - children: [ - ...DATE_FILTER_OPTIONS.map((option) => ({ - id: option.name, - label: option.name, - value: { - key: "target_date", - value: option.value, - }, - selected: checkIfArraysHaveSameElements(filters?.target_date ?? [], option.value), - })), - { - id: "custom", - label: "Custom", - value: "custom", - element: ( - - ), - }, - ], - }, - ]} + options={projectFilterOption} /> ); diff --git a/web/components/views/single-view-item.tsx b/web/components/views/single-view-item.tsx index a6f81912c..70f07a416 100644 --- a/web/components/views/single-view-item.tsx +++ b/web/components/views/single-view-item.tsx @@ -5,9 +5,9 @@ import { useRouter } from "next/router"; // icons import { TrashIcon, StarIcon, PencilIcon } from "@heroicons/react/24/outline"; -import { StackedLayersIcon } from "components/icons"; +import { PhotoFilterOutlined } from "@mui/icons-material"; //components -import { CustomMenu, Tooltip } from "components/ui"; +import { CustomMenu } from "components/ui"; // services import viewsService from "services/views.service"; // types @@ -18,7 +18,6 @@ import { VIEWS_LIST } from "constants/fetch-keys"; import useToast from "hooks/use-toast"; // helpers import { truncateText } from "helpers/string.helper"; -import { renderShortDateWithYearFormat, render24HourFormatTime } from "helpers/date-time.helper"; type Props = { view: IView; @@ -82,94 +81,92 @@ export const SingleViewItem: React.FC = ({ view, handleEditView, handleDe }); }; + const viewRedirectionUrl = `/${workspaceSlug}/projects/${projectId}/views/${view.id}`; + return ( -
- - -
-
-
- -

{truncateText(view.name, 75)}

+
+ + +
+
+
+
-
-
-

- {Object.keys(view.query_data) - .map((key: string) => - view.query_data[key as keyof typeof view.query_data] !== null - ? (view.query_data[key as keyof typeof view.query_data] as any).length - : 0 - ) - .reduce((curr, prev) => curr + prev, 0)}{" "} - filters -

- -

- {render24HourFormatTime(view.updated_at)} -

-
- {view.is_favorite ? ( - - ) : ( - - )} - - { - e.preventDefault(); - e.stopPropagation(); - handleEditView(); - }} - > - - - Edit View - - - { - e.preventDefault(); - e.stopPropagation(); - handleDeleteView(); - }} - > - - - Delete View - - - -
+
+

+ {truncateText(view.name, 75)} +

+ {view?.description && ( +

{view.description}

+ )} +
+
+
+
+

+ {Object.keys(view.query_data) + .map((key: string) => + view.query_data[key as keyof typeof view.query_data] !== null + ? (view.query_data[key as keyof typeof view.query_data] as any).length + : 0 + ) + .reduce((curr, prev) => curr + prev, 0)}{" "} + filters +

+ + {view.is_favorite ? ( + + ) : ( + + )} + + { + e.preventDefault(); + e.stopPropagation(); + handleEditView(); + }} + > + + + Edit View + + + { + e.preventDefault(); + e.stopPropagation(); + handleDeleteView(); + }} + > + + + Delete View + + +
- {view?.description && ( -

- {view.description} -

- )}
diff --git a/web/components/workspace/sidebar-menu.tsx b/web/components/workspace/sidebar-menu.tsx index 946f4b708..d6c6ee3f9 100644 --- a/web/components/workspace/sidebar-menu.tsx +++ b/web/components/workspace/sidebar-menu.tsx @@ -34,8 +34,8 @@ const workspaceLinks = (workspaceSlug: string) => [ }, { Icon: TaskAltOutlined, - name: "My Issues", - href: `/${workspaceSlug}/me/my-issues`, + name: "All Issues", + href: `/${workspaceSlug}/workspace-views/all-issues`, }, ]; diff --git a/web/components/workspace/sidebar-quick-action.tsx b/web/components/workspace/sidebar-quick-action.tsx index 8923abc14..1c614f694 100644 --- a/web/components/workspace/sidebar-quick-action.tsx +++ b/web/components/workspace/sidebar-quick-action.tsx @@ -44,7 +44,9 @@ export const WorkspaceSidebarQuickAction = () => { > -
+