diff --git a/.claude/skills/prd/SKILL.md b/.claude/skills/prd/SKILL.md new file mode 100644 index 0000000000000..9db3bd7b0839f --- /dev/null +++ b/.claude/skills/prd/SKILL.md @@ -0,0 +1,240 @@ +--- +name: prd +description: "Generate a Product Requirements Document (PRD) for a new feature. Use when planning a feature, starting a new project, or when asked to create a PRD. Triggers on: create a prd, write prd for, plan this feature, requirements for, spec out." +--- + +# PRD Generator + +Create detailed Product Requirements Documents that are clear, actionable, and suitable for implementation. + +--- + +## The Job + +1. Receive a feature description from the user +2. Ask 3-5 essential clarifying questions (with lettered options) +3. Generate a structured PRD based on answers +4. Save to `tasks/prd-[feature-name].md` + +**Important:** Do NOT start implementing. Just create the PRD. + +--- + +## Step 1: Clarifying Questions + +Ask only critical questions where the initial prompt is ambiguous. Focus on: + +- **Problem/Goal:** What problem does this solve? +- **Core Functionality:** What are the key actions? +- **Scope/Boundaries:** What should it NOT do? +- **Success Criteria:** How do we know it's done? + +### Format Questions Like This: + +``` +1. What is the primary goal of this feature? + A. Improve user onboarding experience + B. Increase user retention + C. Reduce support burden + D. Other: [please specify] + +2. Who is the target user? + A. New users only + B. Existing users only + C. All users + D. Admin users only + +3. What is the scope? + A. Minimal viable version + B. Full-featured implementation + C. Just the backend/API + D. Just the UI +``` + +This lets users respond with "1A, 2C, 3B" for quick iteration. Remember to indent the options. + +--- + +## Step 2: PRD Structure + +Generate the PRD with these sections: + +### 1. Introduction/Overview +Brief description of the feature and the problem it solves. + +### 2. Goals +Specific, measurable objectives (bullet list). + +### 3. User Stories +Each story needs: +- **Title:** Short descriptive name +- **Description:** "As a [user], I want [feature] so that [benefit]" +- **Acceptance Criteria:** Verifiable checklist of what "done" means + +Each story should be small enough to implement in one focused session. + +**Format:** +```markdown +### US-001: [Title] +**Description:** As a [user], I want [feature] so that [benefit]. + +**Acceptance Criteria:** +- [ ] Specific verifiable criterion +- [ ] Another criterion +- [ ] Typecheck/lint passes +- [ ] **[UI stories only]** Verify in browser using dev-browser skill +``` + +**Important:** +- Acceptance criteria must be verifiable, not vague. "Works correctly" is bad. "Button shows confirmation dialog before deleting" is good. +- **For any story with UI changes:** Always include "Verify in browser using dev-browser skill" as acceptance criteria. This ensures visual verification of frontend work. + +### 4. Functional Requirements +Numbered list of specific functionalities: +- "FR-1: The system must allow users to..." +- "FR-2: When a user clicks X, the system must..." + +Be explicit and unambiguous. + +### 5. Non-Goals (Out of Scope) +What this feature will NOT include. Critical for managing scope. + +### 6. Design Considerations (Optional) +- UI/UX requirements +- Link to mockups if available +- Relevant existing components to reuse + +### 7. Technical Considerations (Optional) +- Known constraints or dependencies +- Integration points with existing systems +- Performance requirements + +### 8. Success Metrics +How will success be measured? +- "Reduce time to complete X by 50%" +- "Increase conversion rate by 10%" + +### 9. Open Questions +Remaining questions or areas needing clarification. + +--- + +## Writing for Junior Developers + +The PRD reader may be a junior developer or AI agent. Therefore: + +- Be explicit and unambiguous +- Avoid jargon or explain it +- Provide enough detail to understand purpose and core logic +- Number requirements for easy reference +- Use concrete examples where helpful + +--- + +## Output + +- **Format:** Markdown (`.md`) +- **Location:** `tasks/` +- **Filename:** `prd-[feature-name].md` (kebab-case) + +--- + +## Example PRD + +```markdown +# PRD: Task Priority System + +## Introduction + +Add priority levels to tasks so users can focus on what matters most. Tasks can be marked as high, medium, or low priority, with visual indicators and filtering to help users manage their workload effectively. + +## Goals + +- Allow assigning priority (high/medium/low) to any task +- Provide clear visual differentiation between priority levels +- Enable filtering and sorting by priority +- Default new tasks to medium priority + +## User Stories + +### US-001: Add priority field to database +**Description:** As a developer, I need to store task priority so it persists across sessions. + +**Acceptance Criteria:** +- [ ] Add priority column to tasks table: 'high' | 'medium' | 'low' (default 'medium') +- [ ] Generate and run migration successfully +- [ ] Typecheck passes + +### US-002: Display priority indicator on task cards +**Description:** As a user, I want to see task priority at a glance so I know what needs attention first. + +**Acceptance Criteria:** +- [ ] Each task card shows colored priority badge (red=high, yellow=medium, gray=low) +- [ ] Priority visible without hovering or clicking +- [ ] Typecheck passes +- [ ] Verify in browser using dev-browser skill + +### US-003: Add priority selector to task edit +**Description:** As a user, I want to change a task's priority when editing it. + +**Acceptance Criteria:** +- [ ] Priority dropdown in task edit modal +- [ ] Shows current priority as selected +- [ ] Saves immediately on selection change +- [ ] Typecheck passes +- [ ] Verify in browser using dev-browser skill + +### US-004: Filter tasks by priority +**Description:** As a user, I want to filter the task list to see only high-priority items when I'm focused. + +**Acceptance Criteria:** +- [ ] Filter dropdown with options: All | High | Medium | Low +- [ ] Filter persists in URL params +- [ ] Empty state message when no tasks match filter +- [ ] Typecheck passes +- [ ] Verify in browser using dev-browser skill + +## Functional Requirements + +- FR-1: Add `priority` field to tasks table ('high' | 'medium' | 'low', default 'medium') +- FR-2: Display colored priority badge on each task card +- FR-3: Include priority selector in task edit modal +- FR-4: Add priority filter dropdown to task list header +- FR-5: Sort by priority within each status column (high to medium to low) + +## Non-Goals + +- No priority-based notifications or reminders +- No automatic priority assignment based on due date +- No priority inheritance for subtasks + +## Technical Considerations + +- Reuse existing badge component with color variants +- Filter state managed via URL search params +- Priority stored in database, not computed + +## Success Metrics + +- Users can change priority in under 2 clicks +- High-priority tasks immediately visible at top of lists +- No regression in task list performance + +## Open Questions + +- Should priority affect task ordering within a column? +- Should we add keyboard shortcuts for priority changes? +``` + +--- + +## Checklist + +Before saving the PRD: + +- [ ] Asked clarifying questions with lettered options +- [ ] Incorporated user's answers +- [ ] User stories are small and specific +- [ ] Functional requirements are numbered and unambiguous +- [ ] Non-goals section defines clear boundaries +- [ ] Saved to `tasks/prd-[feature-name].md` diff --git a/.claude/skills/ralph/SKILL.md b/.claude/skills/ralph/SKILL.md new file mode 100644 index 0000000000000..c17043c681a40 --- /dev/null +++ b/.claude/skills/ralph/SKILL.md @@ -0,0 +1,257 @@ +--- +name: ralph +description: "Convert PRDs to prd.json format for the Ralph autonomous agent system. Use when you have an existing PRD and need to convert it to Ralph's JSON format. Triggers on: convert this prd, turn this into ralph format, create prd.json from this, ralph json." +--- + +# Ralph PRD Converter + +Converts existing PRDs to the prd.json format that Ralph uses for autonomous execution. + +--- + +## The Job + +Take a PRD (markdown file or text) and convert it to `prd.json` in your ralph directory. + +--- + +## Output Format + +```json +{ + "project": "[Project Name]", + "branchName": "ralph/[feature-name-kebab-case]", + "description": "[Feature description from PRD title/intro]", + "userStories": [ + { + "id": "US-001", + "title": "[Story title]", + "description": "As a [user], I want [feature] so that [benefit]", + "acceptanceCriteria": [ + "Criterion 1", + "Criterion 2", + "Typecheck passes" + ], + "priority": 1, + "passes": false, + "notes": "" + } + ] +} +``` + +--- + +## Story Size: The Number One Rule + +**Each story must be completable in ONE Ralph iteration (one context window).** + +Ralph spawns a fresh Amp instance per iteration with no memory of previous work. If a story is too big, the LLM runs out of context before finishing and produces broken code. + +### Right-sized stories: +- Add a database column and migration +- Add a UI component to an existing page +- Update a server action with new logic +- Add a filter dropdown to a list + +### Too big (split these): +- "Build the entire dashboard" - Split into: schema, queries, UI components, filters +- "Add authentication" - Split into: schema, middleware, login UI, session handling +- "Refactor the API" - Split into one story per endpoint or pattern + +**Rule of thumb:** If you cannot describe the change in 2-3 sentences, it is too big. + +--- + +## Story Ordering: Dependencies First + +Stories execute in priority order. Earlier stories must not depend on later ones. + +**Correct order:** +1. Schema/database changes (migrations) +2. Server actions / backend logic +3. UI components that use the backend +4. Dashboard/summary views that aggregate data + +**Wrong order:** +1. UI component (depends on schema that does not exist yet) +2. Schema change + +--- + +## Acceptance Criteria: Must Be Verifiable + +Each criterion must be something Ralph can CHECK, not something vague. + +### Good criteria (verifiable): +- "Add `status` column to tasks table with default 'pending'" +- "Filter dropdown has options: All, Active, Completed" +- "Clicking delete shows confirmation dialog" +- "Typecheck passes" +- "Tests pass" + +### Bad criteria (vague): +- "Works correctly" +- "User can do X easily" +- "Good UX" +- "Handles edge cases" + +### Always include as final criterion: +``` +"Typecheck passes" +``` + +For stories with testable logic, also include: +``` +"Tests pass" +``` + +### For stories that change UI, also include: +``` +"Verify in browser using dev-browser skill" +``` + +Frontend stories are NOT complete until visually verified. Ralph will use the dev-browser skill to navigate to the page, interact with the UI, and confirm changes work. + +--- + +## Conversion Rules + +1. **Each user story becomes one JSON entry** +2. **IDs**: Sequential (US-001, US-002, etc.) +3. **Priority**: Based on dependency order, then document order +4. **All stories**: `passes: false` and empty `notes` +5. **branchName**: Derive from feature name, kebab-case, prefixed with `ralph/` +6. **Always add**: "Typecheck passes" to every story's acceptance criteria + +--- + +## Splitting Large PRDs + +If a PRD has big features, split them: + +**Original:** +> "Add user notification system" + +**Split into:** +1. US-001: Add notifications table to database +2. US-002: Create notification service for sending notifications +3. US-003: Add notification bell icon to header +4. US-004: Create notification dropdown panel +5. US-005: Add mark-as-read functionality +6. US-006: Add notification preferences page + +Each is one focused change that can be completed and verified independently. + +--- + +## Example + +**Input PRD:** +```markdown +# Task Status Feature + +Add ability to mark tasks with different statuses. + +## Requirements +- Toggle between pending/in-progress/done on task list +- Filter list by status +- Show status badge on each task +- Persist status in database +``` + +**Output prd.json:** +```json +{ + "project": "TaskApp", + "branchName": "ralph/task-status", + "description": "Task Status Feature - Track task progress with status indicators", + "userStories": [ + { + "id": "US-001", + "title": "Add status field to tasks table", + "description": "As a developer, I need to store task status in the database.", + "acceptanceCriteria": [ + "Add status column: 'pending' | 'in_progress' | 'done' (default 'pending')", + "Generate and run migration successfully", + "Typecheck passes" + ], + "priority": 1, + "passes": false, + "notes": "" + }, + { + "id": "US-002", + "title": "Display status badge on task cards", + "description": "As a user, I want to see task status at a glance.", + "acceptanceCriteria": [ + "Each task card shows colored status badge", + "Badge colors: gray=pending, blue=in_progress, green=done", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 2, + "passes": false, + "notes": "" + }, + { + "id": "US-003", + "title": "Add status toggle to task list rows", + "description": "As a user, I want to change task status directly from the list.", + "acceptanceCriteria": [ + "Each row has status dropdown or toggle", + "Changing status saves immediately", + "UI updates without page refresh", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 3, + "passes": false, + "notes": "" + }, + { + "id": "US-004", + "title": "Filter tasks by status", + "description": "As a user, I want to filter the list to see only certain statuses.", + "acceptanceCriteria": [ + "Filter dropdown: All | Pending | In Progress | Done", + "Filter persists in URL params", + "Typecheck passes", + "Verify in browser using dev-browser skill" + ], + "priority": 4, + "passes": false, + "notes": "" + } + ] +} +``` + +--- + +## Archiving Previous Runs + +**Before writing a new prd.json, check if there is an existing one from a different feature:** + +1. Read the current `prd.json` if it exists +2. Check if `branchName` differs from the new feature's branch name +3. If different AND `progress.txt` has content beyond the header: + - Create archive folder: `archive/YYYY-MM-DD-feature-name/` + - Copy current `prd.json` and `progress.txt` to archive + - Reset `progress.txt` with fresh header + +**The ralph.sh script handles this automatically** when you run it, but if you are manually updating prd.json between runs, archive first. + +--- + +## Checklist Before Saving + +Before writing prd.json, verify: + +- [ ] **Previous run archived** (if prd.json exists with different branchName, archive it first) +- [ ] Each story is completable in one iteration (small enough) +- [ ] Stories are ordered by dependency (schema to backend to UI) +- [ ] Every story has "Typecheck passes" as criterion +- [ ] UI stories have "Verify in browser using dev-browser skill" as criterion +- [ ] Acceptance criteria are verifiable (not vague) +- [ ] No story depends on a later story diff --git a/.claude/skills/ralph/scripts/ralph.sh b/.claude/skills/ralph/scripts/ralph.sh new file mode 100755 index 0000000000000..baff052ac36f0 --- /dev/null +++ b/.claude/skills/ralph/scripts/ralph.sh @@ -0,0 +1,113 @@ +#!/bin/bash +# Ralph Wiggum - Long-running AI agent loop +# Usage: ./ralph.sh [--tool amp|claude] [max_iterations] + +set -e + +# Parse arguments +TOOL="amp" # Default to amp for backwards compatibility +MAX_ITERATIONS=10 + +while [[ $# -gt 0 ]]; do + case $1 in + --tool) + TOOL="$2" + shift 2 + ;; + --tool=*) + TOOL="${1#*=}" + shift + ;; + *) + # Assume it's max_iterations if it's a number + if [[ "$1" =~ ^[0-9]+$ ]]; then + MAX_ITERATIONS="$1" + fi + shift + ;; + esac +done + +# Validate tool choice +if [[ "$TOOL" != "amp" && "$TOOL" != "claude" ]]; then + echo "Error: Invalid tool '$TOOL'. Must be 'amp' or 'claude'." + exit 1 +fi +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PRD_FILE="$SCRIPT_DIR/prd.json" +PROGRESS_FILE="$SCRIPT_DIR/progress.txt" +ARCHIVE_DIR="$SCRIPT_DIR/archive" +LAST_BRANCH_FILE="$SCRIPT_DIR/.last-branch" + +# Archive previous run if branch changed +if [ -f "$PRD_FILE" ] && [ -f "$LAST_BRANCH_FILE" ]; then + CURRENT_BRANCH=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "") + LAST_BRANCH=$(cat "$LAST_BRANCH_FILE" 2>/dev/null || echo "") + + if [ -n "$CURRENT_BRANCH" ] && [ -n "$LAST_BRANCH" ] && [ "$CURRENT_BRANCH" != "$LAST_BRANCH" ]; then + # Archive the previous run + DATE=$(date +%Y-%m-%d) + # Strip "ralph/" prefix from branch name for folder + FOLDER_NAME=$(echo "$LAST_BRANCH" | sed 's|^ralph/||') + ARCHIVE_FOLDER="$ARCHIVE_DIR/$DATE-$FOLDER_NAME" + + echo "Archiving previous run: $LAST_BRANCH" + mkdir -p "$ARCHIVE_FOLDER" + [ -f "$PRD_FILE" ] && cp "$PRD_FILE" "$ARCHIVE_FOLDER/" + [ -f "$PROGRESS_FILE" ] && cp "$PROGRESS_FILE" "$ARCHIVE_FOLDER/" + echo " Archived to: $ARCHIVE_FOLDER" + + # Reset progress file for new run + echo "# Ralph Progress Log" > "$PROGRESS_FILE" + echo "Started: $(date)" >> "$PROGRESS_FILE" + echo "---" >> "$PROGRESS_FILE" + fi +fi + +# Track current branch +if [ -f "$PRD_FILE" ]; then + CURRENT_BRANCH=$(jq -r '.branchName // empty' "$PRD_FILE" 2>/dev/null || echo "") + if [ -n "$CURRENT_BRANCH" ]; then + echo "$CURRENT_BRANCH" > "$LAST_BRANCH_FILE" + fi +fi + +# Initialize progress file if it doesn't exist +if [ ! -f "$PROGRESS_FILE" ]; then + echo "# Ralph Progress Log" > "$PROGRESS_FILE" + echo "Started: $(date)" >> "$PROGRESS_FILE" + echo "---" >> "$PROGRESS_FILE" +fi + +echo "Starting Ralph - Tool: $TOOL - Max iterations: $MAX_ITERATIONS" + +for i in $(seq 1 $MAX_ITERATIONS); do + echo "" + echo "===============================================================" + echo " Ralph Iteration $i of $MAX_ITERATIONS ($TOOL)" + echo "===============================================================" + + # Run the selected tool with the ralph prompt + if [[ "$TOOL" == "amp" ]]; then + OUTPUT=$(cat "$SCRIPT_DIR/prompt.md" | amp --dangerously-allow-all 2>&1 | tee /dev/stderr) || true + else + # Claude Code: use --dangerously-skip-permissions for autonomous operation, --print for output + OUTPUT=$(claude --dangerously-skip-permissions --print < "$SCRIPT_DIR/CLAUDE.md" 2>&1 | tee /dev/stderr) || true + fi + + # Check for completion signal + if echo "$OUTPUT" | grep -q "COMPLETE"; then + echo "" + echo "Ralph completed all tasks!" + echo "Completed at iteration $i of $MAX_ITERATIONS" + exit 0 + fi + + echo "Iteration $i complete. Continuing..." + sleep 2 +done + +echo "" +echo "Ralph reached max iterations ($MAX_ITERATIONS) without completing all tasks." +echo "Check $PROGRESS_FILE for status." +exit 1 diff --git a/AGENTS.md b/AGENTS.md index 301633d7f1569..f3a4065d17550 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,3 +102,108 @@ Practical checklist for any change impacting core logic or public APIs ## Branding / White-labeling note - For user-facing strings that currently contain "Chatwoot" but should adapt to branded/self-hosted installs, prefer applying `replaceInstallationName` from `shared/composables/useBranding` in the UI layer (for example tooltip and suggestion labels) instead of adding hardcoded brand-specific copy. + +# Ralph Agent Instructions + +You are an autonomous coding agent working on a software project. + +## Your Task + +1. Read the PRD at `prd.json` (in the same directory as this file) +2. Read the progress log at `progress.txt` (check Codebase Patterns section first) +3. Check you're on the correct branch from PRD `branchName`. If not, check it out or create from main. +4. Pick the **highest priority** user story where `passes: false` +5. Implement that single user story +6. Run quality checks (e.g., typecheck, lint, test - use whatever your project requires) +7. Update CLAUDE.md files if you discover reusable patterns (see below) +8. If checks pass, commit ALL changes with message: `feat: [Story ID] - [Story Title]` +9. Update the PRD to set `passes: true` for the completed story +10. Append your progress to `progress.txt` + +## Progress Report Format + +APPEND to progress.txt (never replace, always append): +``` +## [Date/Time] - [Story ID] +- What was implemented +- Files changed +- **Learnings for future iterations:** + - Patterns discovered (e.g., "this codebase uses X for Y") + - Gotchas encountered (e.g., "don't forget to update Z when changing W") + - Useful context (e.g., "the evaluation panel is in component X") +--- +``` + +The learnings section is critical - it helps future iterations avoid repeating mistakes and understand the codebase better. + +## Consolidate Patterns + +If you discover a **reusable pattern** that future iterations should know, add it to the `## Codebase Patterns` section at the TOP of progress.txt (create it if it doesn't exist). This section should consolidate the most important learnings: + +``` +## Codebase Patterns +- Example: Use `sql` template for aggregations +- Example: Always use `IF NOT EXISTS` for migrations +- Example: Export types from actions.ts for UI components +``` + +Only add patterns that are **general and reusable**, not story-specific details. + +## Update CLAUDE.md Files + +Before committing, check if any edited files have learnings worth preserving in nearby CLAUDE.md files: + +1. **Identify directories with edited files** - Look at which directories you modified +2. **Check for existing CLAUDE.md** - Look for CLAUDE.md in those directories or parent directories +3. **Add valuable learnings** - If you discovered something future developers/agents should know: + - API patterns or conventions specific to that module + - Gotchas or non-obvious requirements + - Dependencies between files + - Testing approaches for that area + - Configuration or environment requirements + +**Examples of good CLAUDE.md additions:** +- "When modifying X, also update Y to keep them in sync" +- "This module uses pattern Z for all API calls" +- "Tests require the dev server running on PORT 3000" +- "Field names must match the template exactly" + +**Do NOT add:** +- Story-specific implementation details +- Temporary debugging notes +- Information already in progress.txt + +Only update CLAUDE.md if you have **genuinely reusable knowledge** that would help future work in that directory. + +## Quality Requirements + +- ALL commits must pass your project's quality checks (typecheck, lint, test) +- Do NOT commit broken code +- Keep changes focused and minimal +- Follow existing code patterns + +## Browser Testing (If Available) + +For any story that changes UI, verify it works in the browser if you have browser testing tools configured (e.g., via MCP): + +1. Navigate to the relevant page +2. Verify the UI changes work as expected +3. Take a screenshot if helpful for the progress log + +If no browser tools are available, note in your progress report that manual browser verification is needed. + +## Stop Condition + +After completing a user story, check if ALL stories have `passes: true`. + +If ALL stories are complete and passing, reply with: +COMPLETE + +If there are still stories with `passes: false`, end your response normally (another iteration will pick up the next story). + +## Important + +- Work on ONE story per iteration +- Commit frequently +- Keep CI green +- Read the Codebase Patterns section in progress.txt before starting diff --git a/app/controllers/api/v1/accounts/contacts/group_invites_controller.rb b/app/controllers/api/v1/accounts/contacts/group_invites_controller.rb new file mode 100644 index 0000000000000..7bc304f350c1d --- /dev/null +++ b/app/controllers/api/v1/accounts/contacts/group_invites_controller.rb @@ -0,0 +1,33 @@ +class Api::V1::Accounts::Contacts::GroupInvitesController < Api::V1::Accounts::Contacts::BaseController + def show + authorize @contact, :show? + code = channel.group_invite_code(@contact.identifier) + render json: invite_response(code) + rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e + render json: { error: e.message }, status: :unprocessable_entity + end + + def revoke + authorize @contact, :update? + code = channel.revoke_group_invite(@contact.identifier) + render json: invite_response(code) + rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e + render json: { error: e.message }, status: :unprocessable_entity + end + + private + + def channel + @channel ||= group_conversation.inbox.channel + end + + def group_conversation + @group_conversation ||= Current.account.conversations + .where(contact_id: @contact.id, group_type: :group, status: %i[open pending]) + .first + end + + def invite_response(code) + { invite_code: code, invite_url: "https://chat.whatsapp.com/#{code}" } + end +end diff --git a/app/controllers/api/v1/accounts/contacts/group_join_requests_controller.rb b/app/controllers/api/v1/accounts/contacts/group_join_requests_controller.rb new file mode 100644 index 0000000000000..1b69ea751cdd8 --- /dev/null +++ b/app/controllers/api/v1/accounts/contacts/group_join_requests_controller.rb @@ -0,0 +1,29 @@ +class Api::V1::Accounts::Contacts::GroupJoinRequestsController < Api::V1::Accounts::Contacts::BaseController + def index + authorize @contact, :show? + requests = channel.group_join_requests(@contact.identifier) + render json: { payload: requests } + rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e + render json: { error: e.message }, status: :unprocessable_entity + end + + def handle + authorize @contact, :update? + channel.handle_group_join_requests(@contact.identifier, params[:participants], params[:request_action]) + head :ok + rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e + render json: { error: e.message }, status: :unprocessable_entity + end + + private + + def channel + @channel ||= group_conversation.inbox.channel + end + + def group_conversation + @group_conversation ||= Current.account.conversations + .where(contact_id: @contact.id, group_type: :group, status: %i[open pending]) + .first + end +end diff --git a/app/controllers/api/v1/accounts/contacts/group_members_controller.rb b/app/controllers/api/v1/accounts/contacts/group_members_controller.rb index 40943efe240af..a66af5266cbef 100644 --- a/app/controllers/api/v1/accounts/contacts/group_members_controller.rb +++ b/app/controllers/api/v1/accounts/contacts/group_members_controller.rb @@ -5,7 +5,7 @@ def index Contacts::SyncGroupService.new(contact: @contact).perform conversations = Current.account.conversations - .where(contact_id: @contact.id, conversation_type: :group, status: %i[open pending]) + .where(contact_id: @contact.id, group_type: :group, status: %i[open pending]) @group_members = ConversationGroupMember.active .where(conversation: conversations) @@ -13,4 +13,77 @@ def index rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e render_internal_server_error(e.message) end + + def create + authorize @contact, :update? + + channel.update_group_participants(@contact.identifier, format_participants(params[:participants]), 'add') + add_group_members(params[:participants]) + head :ok + rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e + render json: { error: e.message }, status: :unprocessable_entity + end + + def update + authorize @contact, :update? + + member = group_conversation_members.find(params[:member_id]) + action = params[:role] == 'admin' ? 'promote' : 'demote' + channel.update_group_participants(@contact.identifier, [jid_for_member(member)], action) + member.update!(role: params[:role]) + head :ok + rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e + render json: { error: e.message }, status: :unprocessable_entity + end + + def destroy + authorize @contact, :update? + + member = group_conversation_members.find(params[:id]) + channel.update_group_participants(@contact.identifier, [jid_for_member(member)], 'remove') + member.update!(is_active: false) + head :ok + rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e + render json: { error: e.message }, status: :unprocessable_entity + end + + private + + def group_conversation + @group_conversation ||= Current.account.conversations + .where(contact_id: @contact.id, group_type: :group, status: %i[open pending]) + .first + end + + def group_conversation_members + ConversationGroupMember.where(conversation: group_conversation) + end + + def channel + group_conversation.inbox.channel + end + + def format_participants(phone_numbers) + Array(phone_numbers).map { |phone| "#{phone.to_s.delete('+')}@s.whatsapp.net" } + end + + def jid_for_member(member) + "#{member.contact.phone_number.to_s.delete('+')}@s.whatsapp.net" + end + + def add_group_members(phone_numbers) + inbox = group_conversation.inbox + Array(phone_numbers).each do |phone| + normalized = phone.start_with?('+') ? phone : "+#{phone}" + contact_inbox = ::ContactInboxWithContactBuilder.new( + source_id: normalized.delete('+'), + inbox: inbox, + contact_attributes: { name: normalized, phone_number: normalized } + ).perform + next if contact_inbox.blank? + + member = ConversationGroupMember.find_or_initialize_by(conversation: group_conversation, contact: contact_inbox.contact) + member.update!(role: :member, is_active: true) unless member.persisted? && member.is_active? + end + end end diff --git a/app/controllers/api/v1/accounts/contacts/group_metadata_controller.rb b/app/controllers/api/v1/accounts/contacts/group_metadata_controller.rb new file mode 100644 index 0000000000000..8354a087c09c4 --- /dev/null +++ b/app/controllers/api/v1/accounts/contacts/group_metadata_controller.rb @@ -0,0 +1,32 @@ +class Api::V1::Accounts::Contacts::GroupMetadataController < Api::V1::Accounts::Contacts::BaseController + def update + authorize @contact, :update? + update_subject if params[:subject].present? + update_description if params[:description].present? + render json: { id: @contact.id, name: @contact.name, additional_attributes: @contact.additional_attributes } + rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e + render json: { error: e.message }, status: :unprocessable_entity + end + + private + + def update_subject + channel.update_group_subject(@contact.identifier, params[:subject]) + @contact.update!(name: params[:subject]) + end + + def update_description + channel.update_group_description(@contact.identifier, params[:description]) + @contact.update!(additional_attributes: @contact.additional_attributes.merge('description' => params[:description])) + end + + def channel + @channel ||= group_conversation.inbox.channel + end + + def group_conversation + @group_conversation ||= Current.account.conversations + .where(contact_id: @contact.id, group_type: :group, status: %i[open pending]) + .first + end +end diff --git a/app/controllers/api/v1/accounts/contacts_controller.rb b/app/controllers/api/v1/accounts/contacts_controller.rb index c3b9f638db0f6..871fdd92cc38e 100644 --- a/app/controllers/api/v1/accounts/contacts_controller.rb +++ b/app/controllers/api/v1/accounts/contacts_controller.rb @@ -85,7 +85,7 @@ def destroy_custom_attributes def sync_group authorize @contact, :sync_group? @contact = Contacts::SyncGroupService.new(contact: @contact).perform - group_conversation = @contact.conversations.where(conversation_type: :group, status: %i[open pending]).order(created_at: :desc).first + group_conversation = @contact.conversations.where(group_type: :group, status: %i[open pending]).order(created_at: :desc).first @group_members = group_conversation ? ConversationGroupMember.active.where(conversation: group_conversation).includes(:contact) : [] rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e render_internal_server_error(e.message) diff --git a/app/controllers/api/v1/accounts/groups_controller.rb b/app/controllers/api/v1/accounts/groups_controller.rb new file mode 100644 index 0000000000000..6f453fe5264ce --- /dev/null +++ b/app/controllers/api/v1/accounts/groups_controller.rb @@ -0,0 +1,20 @@ +class Api::V1::Accounts::GroupsController < Api::V1::Accounts::BaseController + def create + inbox = Current.account.inboxes.find_by(id: params[:inbox_id]) + return render json: { error: 'Access Denied' }, status: :forbidden unless inbox_accessible?(inbox) + + @conversation = Groups::CreateService.new( + inbox: inbox, + subject: params[:subject], + participants: Array(params[:participants]) + ).perform + rescue Whatsapp::Providers::WhatsappBaileysService::ProviderUnavailableError => e + render json: { error: e.message }, status: :unprocessable_entity + end + + private + + def inbox_accessible?(inbox) + inbox.present? && Current.user.assigned_inboxes.exists?(id: inbox.id) + end +end diff --git a/app/finders/conversation_finder.rb b/app/finders/conversation_finder.rb index d43ed31e787ac..cd4f91206557f 100644 --- a/app/finders/conversation_finder.rb +++ b/app/finders/conversation_finder.rb @@ -64,6 +64,7 @@ def set_up find_all_conversations filter_by_status unless params[:q] + filter_by_group_type filter_by_team filter_by_labels filter_by_query @@ -118,6 +119,12 @@ def filter_by_assignee_type @conversations end + def filter_by_group_type + return unless params[:group_type].present? && params[:group_type] != 'all' + + @conversations = @conversations.where(group_type: params[:group_type]) + end + def filter_by_conversation_type case @params[:conversation_type] when 'mention' diff --git a/app/helpers/filters/filter_helper.rb b/app/helpers/filters/filter_helper.rb index fe03dae289219..2bf4929159e0a 100644 --- a/app/helpers/filters/filter_helper.rb +++ b/app/helpers/filters/filter_helper.rb @@ -100,6 +100,10 @@ def conversation_priority_values(values) values.map { |x| Conversation.priorities[x.to_sym] } end + def conversation_group_type_values(values) + values.map { |x| Conversation.group_types[x.to_sym] } + end + def message_type_values(values) values.map { |x| Message.message_types[x.to_sym] } end diff --git a/app/javascript/dashboard/api/groupMembers.js b/app/javascript/dashboard/api/groupMembers.js new file mode 100644 index 0000000000000..937b83357589a --- /dev/null +++ b/app/javascript/dashboard/api/groupMembers.js @@ -0,0 +1,61 @@ +/* global axios */ +import ApiClient from './ApiClient'; + +class GroupMembersAPI extends ApiClient { + constructor() { + super('contacts', { accountScoped: true }); + } + + getGroupMembers(contactId) { + return axios.get(`${this.url}/${contactId}/group_members`); + } + + syncGroup(contactId) { + return axios.get(`${this.url}/${contactId}/sync_group`); + } + + createGroup(params) { + return axios.post(`${this.baseUrl()}/groups`, params); + } + + updateGroupMetadata(contactId, params) { + return axios.patch(`${this.url}/${contactId}/group_metadata`, params); + } + + addMembers(contactId, participants) { + return axios.post(`${this.url}/${contactId}/group_members`, { + participants, + }); + } + + removeMembers(contactId, memberId) { + return axios.delete(`${this.url}/${contactId}/group_members/${memberId}`); + } + + updateMemberRole(contactId, memberId, role) { + return axios.patch(`${this.url}/${contactId}/group_members/${memberId}`, { + role, + }); + } + + getInviteLink(contactId) { + return axios.get(`${this.url}/${contactId}/group_invite`); + } + + revokeInviteLink(contactId) { + return axios.post(`${this.url}/${contactId}/group_invite/revoke`); + } + + getPendingRequests(contactId) { + return axios.get(`${this.url}/${contactId}/group_join_requests`); + } + + handleJoinRequest(contactId, params) { + return axios.post( + `${this.url}/${contactId}/group_join_requests/handle`, + params + ); + } +} + +export default new GroupMembersAPI(); diff --git a/app/javascript/dashboard/api/inbox/conversation.js b/app/javascript/dashboard/api/inbox/conversation.js index f94fca4529f92..ea2802cae4af5 100644 --- a/app/javascript/dashboard/api/inbox/conversation.js +++ b/app/javascript/dashboard/api/inbox/conversation.js @@ -16,6 +16,7 @@ class ConversationApi extends ApiClient { conversationType, sortBy, updatedWithin, + groupType, }) { return axios.get(this.url, { params: { @@ -28,6 +29,7 @@ class ConversationApi extends ApiClient { conversation_type: conversationType, sort_by: sortBy, updated_within: updatedWithin, + group_type: groupType, }, }); } diff --git a/app/javascript/dashboard/components-next/filter/helper/filterHelper.js b/app/javascript/dashboard/components-next/filter/helper/filterHelper.js index 274eecb49511f..c0317975e3603 100644 --- a/app/javascript/dashboard/components-next/filter/helper/filterHelper.js +++ b/app/javascript/dashboard/components-next/filter/helper/filterHelper.js @@ -14,6 +14,7 @@ export const CONVERSATION_ATTRIBUTES = { REFERER: 'referer', CREATED_AT: 'created_at', LAST_ACTIVITY_AT: 'last_activity_at', + GROUP_TYPE: 'group_type', }; export const CONTACT_ATTRIBUTES = { diff --git a/app/javascript/dashboard/components-next/filter/provider.js b/app/javascript/dashboard/components-next/filter/provider.js index fc418b1327dfb..82c7eafa7d963 100644 --- a/app/javascript/dashboard/components-next/filter/provider.js +++ b/app/javascript/dashboard/components-next/filter/provider.js @@ -247,6 +247,20 @@ export function useConversationFilterContext() { filterOperators: dateOperators.value, attributeModel: 'standard', }, + { + attributeKey: CONVERSATION_ATTRIBUTES.GROUP_TYPE, + value: CONVERSATION_ATTRIBUTES.GROUP_TYPE, + attributeName: t('FILTER.ATTRIBUTES.GROUP_TYPE'), + label: t('FILTER.ATTRIBUTES.GROUP_TYPE'), + inputType: 'multiSelect', + options: ['individual', 'group'].map(id => ({ + id, + name: t(`GROUP.FILTER.${id.toUpperCase()}`), + })), + dataType: 'text', + filterOperators: equalityOperators.value, + attributeModel: 'standard', + }, ...customFilterTypes.value, ]); diff --git a/app/javascript/dashboard/components/ChatList.vue b/app/javascript/dashboard/components/ChatList.vue index 3b2a66929ff09..1fbc00e185467 100644 --- a/app/javascript/dashboard/components/ChatList.vue +++ b/app/javascript/dashboard/components/ChatList.vue @@ -98,6 +98,7 @@ provide('contextMenuElementTarget', conversationDynamicScroller); const activeAssigneeTab = ref(wootConstants.ASSIGNEE_TYPE.ME); const activeStatus = ref(wootConstants.STATUS_TYPE.OPEN); const activeSortBy = ref(wootConstants.SORT_BY_TYPE.LAST_ACTIVITY_AT_DESC); +const activeGroupType = ref(''); const showAdvancedFilters = ref(false); // chatsOnView is to store the chats that are currently visible on the screen, // which mirrors the conversationList. @@ -285,6 +286,7 @@ const conversationFilters = computed(() => { labels: props.label ? [props.label] : undefined, teamId: props.teamId || undefined, conversationType: props.conversationType || undefined, + groupType: activeGroupType.value || undefined, }; }); @@ -373,13 +375,14 @@ const uniqueInboxes = computed(() => { // ---------------------- Methods ----------------------- function setFiltersFromUISettings() { const { conversations_filter_by: filterBy = {} } = uiSettings.value; - const { status, order_by: orderBy } = filterBy; + const { status, order_by: orderBy, group_type: groupType } = filterBy; activeStatus.value = status || wootConstants.STATUS_TYPE.OPEN; activeSortBy.value = Object.values(wootConstants.SORT_BY_TYPE).includes( orderBy ) ? orderBy : wootConstants.SORT_BY_TYPE.LAST_ACTIVITY_AT_DESC; + activeGroupType.value = groupType || ''; } function emitConversationLoaded() { @@ -488,6 +491,10 @@ function setParamsForEditFolderModal() { { id: 'high', name: t('CONVERSATION.PRIORITY.OPTIONS.HIGH') }, { id: 'urgent', name: t('CONVERSATION.PRIORITY.OPTIONS.URGENT') }, ], + group_type: [ + { id: 'individual', name: t('GROUP.FILTER.INDIVIDUAL') }, + { id: 'group', name: t('GROUP.FILTER.GROUP') }, + ], filterTypes: advancedFilterTypes.value, allCustomAttributes: conversationCustomAttributes.value, }; @@ -632,6 +639,8 @@ function updateAssigneeTab(selectedTab) { function onBasicFilterChange(value, type) { if (type === 'status') { activeStatus.value = value; + } else if (type === 'group_type') { + activeGroupType.value = value; } else { activeSortBy.value = value; } @@ -829,6 +838,7 @@ onMounted(() => { setFiltersFromUISettings(); store.dispatch('setChatStatusFilter', activeStatus.value); store.dispatch('setChatSortFilter', activeSortBy.value); + store.dispatch('setChatGroupTypeFilter', activeGroupType.value); resetAndFetchData(); if (hasActiveFolders.value) { store.dispatch('campaigns/get'); diff --git a/app/javascript/dashboard/components/widgets/conversation/ConversationBasicFilter.vue b/app/javascript/dashboard/components/widgets/conversation/ConversationBasicFilter.vue index d699923f57539..199b3a0cea117 100644 --- a/app/javascript/dashboard/components/widgets/conversation/ConversationBasicFilter.vue +++ b/app/javascript/dashboard/components/widgets/conversation/ConversationBasicFilter.vue @@ -25,6 +25,7 @@ const { updateUISettings } = useUISettings(); const chatStatusFilter = useMapGetter('getChatStatusFilter'); const chatSortFilter = useMapGetter('getChatSortFilter'); +const chatGroupTypeFilter = useMapGetter('getChatGroupTypeFilter'); const [showActionsDropdown, toggleDropdown] = useToggle(); @@ -38,6 +39,8 @@ const currentSortBy = computed(() => { ); }); +const currentGroupType = computed(() => chatGroupTypeFilter.value || ''); + const chatStatusOptions = computed(() => [ { label: t('CHAT_LIST.CHAT_STATUS_FILTER_ITEMS.open.TEXT'), @@ -96,6 +99,12 @@ const chatSortOptions = computed(() => [ }, ]); +const chatGroupTypeOptions = computed(() => [ + { label: t('GROUP.FILTER.ALL'), value: '' }, + { label: t('GROUP.FILTER.INDIVIDUAL'), value: 'individual' }, + { label: t('GROUP.FILTER.GROUP'), value: 'group' }, +]); + const activeChatStatusLabel = computed( () => chatStatusOptions.value.find(m => m.value === chatStatusFilter.value) @@ -108,11 +117,18 @@ const activeChatSortLabel = computed( '' ); +const activeGroupTypeLabel = computed( + () => + chatGroupTypeOptions.value.find(m => m.value === chatGroupTypeFilter.value) + ?.label || t('GROUP.FILTER.ALL') +); + const saveSelectedFilter = (type, value) => { updateUISettings({ conversations_filter_by: { status: type === 'status' ? value : currentStatusFilter.value, order_by: type === 'sort' ? value : currentSortBy.value, + group_type: type === 'group_type' ? value : currentGroupType.value, }, }); }; @@ -128,6 +144,12 @@ const handleSortChange = value => { store.dispatch('setChatSortFilter', value); saveSelectedFilter('sort', value); }; + +const handleGroupTypeChange = value => { + emit('changeFilter', value, 'group_type'); + store.dispatch('setChatGroupTypeFilter', value); + saveSelectedFilter('group_type', value); +}; diff --git a/app/javascript/dashboard/components/widgets/conversation/advancedFilterItems/index.js b/app/javascript/dashboard/components/widgets/conversation/advancedFilterItems/index.js index 2c3c2fd13503f..b3d26e0f017f4 100644 --- a/app/javascript/dashboard/components/widgets/conversation/advancedFilterItems/index.js +++ b/app/javascript/dashboard/components/widgets/conversation/advancedFilterItems/index.js @@ -110,6 +110,14 @@ const filterTypes = [ filterOperators: OPERATOR_TYPES_5, attributeModel: 'standard', }, + { + attributeKey: 'group_type', + attributeI18nKey: 'GROUP_TYPE', + inputType: 'multi_select', + dataType: 'text', + filterOperators: OPERATOR_TYPES_1, + attributeModel: 'standard', + }, ]; export const filterAttributeGroups = [ @@ -153,6 +161,10 @@ export const filterAttributeGroups = [ key: 'last_activity_at', i18nKey: 'LAST_ACTIVITY', }, + { + key: 'group_type', + i18nKey: 'GROUP_TYPE', + }, ], }, { diff --git a/app/javascript/dashboard/helper/automationHelper.js b/app/javascript/dashboard/helper/automationHelper.js index 206501f19df4b..7de9b3ba385a4 100644 --- a/app/javascript/dashboard/helper/automationHelper.js +++ b/app/javascript/dashboard/helper/automationHelper.js @@ -151,6 +151,10 @@ export const getConditionOptions = ({ country_code: countries, message_type: messageTypeOptions, priority: priorityOptions, + group_type: [ + { id: 'individual', name: 'Individual' }, + { id: 'group', name: 'Group' }, + ], labels: generateConditionOptions(labels, 'title'), }; diff --git a/app/javascript/dashboard/helper/customViewsHelper.js b/app/javascript/dashboard/helper/customViewsHelper.js index c837ce613d69f..414b046b3254d 100644 --- a/app/javascript/dashboard/helper/customViewsHelper.js +++ b/app/javascript/dashboard/helper/customViewsHelper.js @@ -73,6 +73,10 @@ const getValuesForPriority = (values, priority) => { return priority.filter(option => values.includes(option.id)); }; +const getValuesForGroupType = (values, groupType) => { + return groupType.filter(option => values.includes(option.id)); +}; + export const getValuesForFilter = (filter, params) => { const { attribute_key, values } = filter; const { @@ -84,6 +88,7 @@ export const getValuesForFilter = (filter, params) => { campaigns, labels, priority, + group_type: groupType, } = params; switch (attribute_key) { case 'status': @@ -104,6 +109,8 @@ export const getValuesForFilter = (filter, params) => { return getValuesForLanguages(values, languages); case 'country_code': return getValuesForCountries(values, countries); + case 'group_type': + return getValuesForGroupType(values, groupType); default: return { id: values[0], name: values[0] }; } diff --git a/app/javascript/dashboard/i18n/locale/en/advancedFilters.json b/app/javascript/dashboard/i18n/locale/en/advancedFilters.json index a991cb25bce28..ab022c8c93a89 100644 --- a/app/javascript/dashboard/i18n/locale/en/advancedFilters.json +++ b/app/javascript/dashboard/i18n/locale/en/advancedFilters.json @@ -62,7 +62,8 @@ "CUSTOM_ATTRIBUTE_LINK": "Link", "CUSTOM_ATTRIBUTE_CHECKBOX": "Checkbox", "CREATED_AT": "Created at", - "LAST_ACTIVITY": "Last activity" + "LAST_ACTIVITY": "Last activity", + "GROUP_TYPE": "Group type" }, "ERRORS": { "VALUE_REQUIRED": "Value is required", diff --git a/app/javascript/dashboard/i18n/locale/en/groups.json b/app/javascript/dashboard/i18n/locale/en/groups.json new file mode 100644 index 0000000000000..9bbc1137bb58e --- /dev/null +++ b/app/javascript/dashboard/i18n/locale/en/groups.json @@ -0,0 +1,77 @@ +{ + "GROUP": { + "SIDEBAR_TITLE": "Group", + "INFO": { + "HEADER": "Group Info", + "MEMBER_COUNT": "{count} members", + "MEMBER_LIST_TITLE": "Members", + "ADMIN_BADGE": "Admin", + "SYNC_BUTTON": "Sync", + "SYNC_SUCCESS": "Group members synced successfully.", + "SYNC_ERROR": "Failed to sync group members. Please try again.", + "EMPTY_STATE": "No members found." + }, + "FILTER": { + "TYPE_LABEL": "Type", + "ALL": "All", + "INDIVIDUAL": "Individual", + "GROUP": "Group" + }, + "CREATE": { + "TITLE": "Create New Group", + "INBOX_LABEL": "Inbox", + "INBOX_PLACEHOLDER": "Select a WhatsApp inbox", + "NAME_LABEL": "Group Name", + "NAME_PLACEHOLDER": "Enter group name", + "PARTICIPANTS_LABEL": "Participants", + "PARTICIPANTS_PLACEHOLDER": "Search contacts to add", + "SUBMIT_BUTTON": "Create Group", + "SUCCESS_MESSAGE": "Group created successfully.", + "ERROR_MESSAGE": "Failed to create group. Please try again." + }, + "METADATA": { + "EDIT_NAME_LABEL": "Group Name", + "EDIT_NAME_PLACEHOLDER": "Enter group name", + "EDIT_DESCRIPTION_LABEL": "Description", + "EDIT_DESCRIPTION_PLACEHOLDER": "Enter group description", + "EDIT_AVATAR_LABEL": "Group Photo", + "SAVE_SUCCESS": "Group info updated successfully.", + "SAVE_ERROR": "Failed to update group info. Please try again." + }, + "INVITE": { + "SECTION_TITLE": "Invite Link", + "COPY_BUTTON": "Copy Link", + "COPY_SUCCESS": "Invite link copied to clipboard.", + "REVOKE_BUTTON": "Revoke & Regenerate", + "REVOKE_SUCCESS": "Invite link revoked and regenerated.", + "REVOKE_ERROR": "Failed to revoke invite link. Please try again.", + "FETCH_ERROR": "Failed to load invite link." + }, + "MEMBERS": { + "ADD_BUTTON": "Add Member", + "ADD_SUCCESS": "Member added successfully.", + "ADD_ERROR": "Failed to add member. Please try again.", + "REMOVE_BUTTON": "Remove", + "REMOVE_SUCCESS": "Member removed successfully.", + "REMOVE_ERROR": "Failed to remove member. Please try again.", + "PROMOTE_BUTTON": "Promote to Admin", + "PROMOTE_SUCCESS": "Member promoted to admin.", + "PROMOTE_ERROR": "Failed to promote member. Please try again.", + "DEMOTE_BUTTON": "Demote to Member", + "DEMOTE_SUCCESS": "Member demoted to member.", + "DEMOTE_ERROR": "Failed to demote member. Please try again." + }, + "JOIN_REQUESTS": { + "SECTION_TITLE": "Pending Requests", + "PENDING_COUNT": "{count} pending", + "APPROVE_BUTTON": "Approve", + "REJECT_BUTTON": "Reject", + "APPROVE_SUCCESS": "Join request approved.", + "REJECT_SUCCESS": "Join request rejected.", + "ACTION_ERROR": "Failed to process join request. Please try again." + }, + "MENTION": { + "DROPDOWN_HEADER": "Group Members" + } + } +} diff --git a/app/javascript/dashboard/i18n/locale/en/index.js b/app/javascript/dashboard/i18n/locale/en/index.js index a55f541658585..9d8225bb67432 100644 --- a/app/javascript/dashboard/i18n/locale/en/index.js +++ b/app/javascript/dashboard/i18n/locale/en/index.js @@ -1,4 +1,5 @@ import advancedFilters from './advancedFilters.json'; +import groups from './groups.json'; import agentBots from './agentBots.json'; import agentMgmt from './agentMgmt.json'; import attributesMgmt from './attributesMgmt.json'; @@ -42,6 +43,7 @@ import yearInReview from './yearInReview.json'; export default { ...advancedFilters, + ...groups, ...agentBots, ...agentMgmt, ...attributesMgmt, diff --git a/app/javascript/dashboard/i18n/locale/pt_BR/advancedFilters.json b/app/javascript/dashboard/i18n/locale/pt_BR/advancedFilters.json index 7958f4c145858..e8fd5d3b03da5 100644 --- a/app/javascript/dashboard/i18n/locale/pt_BR/advancedFilters.json +++ b/app/javascript/dashboard/i18n/locale/pt_BR/advancedFilters.json @@ -62,7 +62,8 @@ "CUSTOM_ATTRIBUTE_LINK": "Link", "CUSTOM_ATTRIBUTE_CHECKBOX": "Checkbox", "CREATED_AT": "Criado em", - "LAST_ACTIVITY": "Última atividade" + "LAST_ACTIVITY": "Última atividade", + "GROUP_TYPE": "Tipo de conversa" }, "ERRORS": { "VALUE_REQUIRED": "Valor obrigatório", diff --git a/app/javascript/dashboard/i18n/locale/pt_BR/groups.json b/app/javascript/dashboard/i18n/locale/pt_BR/groups.json new file mode 100644 index 0000000000000..94021bf52a0fb --- /dev/null +++ b/app/javascript/dashboard/i18n/locale/pt_BR/groups.json @@ -0,0 +1,77 @@ +{ + "GROUP": { + "SIDEBAR_TITLE": "Grupo", + "INFO": { + "HEADER": "Informações do Grupo", + "MEMBER_COUNT": "{count} membros", + "MEMBER_LIST_TITLE": "Membros", + "ADMIN_BADGE": "Admin", + "SYNC_BUTTON": "Sincronizar", + "SYNC_SUCCESS": "Membros do grupo sincronizados com sucesso.", + "SYNC_ERROR": "Falha ao sincronizar membros do grupo. Por favor, tente novamente.", + "EMPTY_STATE": "Nenhum membro encontrado." + }, + "FILTER": { + "TYPE_LABEL": "Tipo", + "ALL": "Todos", + "INDIVIDUAL": "Individual", + "GROUP": "Grupo" + }, + "CREATE": { + "TITLE": "Criar Novo Grupo", + "INBOX_LABEL": "Caixa de entrada", + "INBOX_PLACEHOLDER": "Selecione uma caixa de entrada do WhatsApp", + "NAME_LABEL": "Nome do Grupo", + "NAME_PLACEHOLDER": "Digite o nome do grupo", + "PARTICIPANTS_LABEL": "Participantes", + "PARTICIPANTS_PLACEHOLDER": "Pesquisar contatos para adicionar", + "SUBMIT_BUTTON": "Criar Grupo", + "SUCCESS_MESSAGE": "Grupo criado com sucesso.", + "ERROR_MESSAGE": "Falha ao criar grupo. Por favor, tente novamente." + }, + "METADATA": { + "EDIT_NAME_LABEL": "Nome do Grupo", + "EDIT_NAME_PLACEHOLDER": "Digite o nome do grupo", + "EDIT_DESCRIPTION_LABEL": "Descrição", + "EDIT_DESCRIPTION_PLACEHOLDER": "Digite a descrição do grupo", + "EDIT_AVATAR_LABEL": "Foto do Grupo", + "SAVE_SUCCESS": "Informações do grupo atualizadas com sucesso.", + "SAVE_ERROR": "Falha ao atualizar informações do grupo. Por favor, tente novamente." + }, + "INVITE": { + "SECTION_TITLE": "Link de Convite", + "COPY_BUTTON": "Copiar Link", + "COPY_SUCCESS": "Link de convite copiado para a área de transferência.", + "REVOKE_BUTTON": "Revogar e Regenerar", + "REVOKE_SUCCESS": "Link de convite revogado e regenerado.", + "REVOKE_ERROR": "Falha ao revogar o link de convite. Por favor, tente novamente.", + "FETCH_ERROR": "Falha ao carregar o link de convite." + }, + "MEMBERS": { + "ADD_BUTTON": "Adicionar Membro", + "ADD_SUCCESS": "Membro adicionado com sucesso.", + "ADD_ERROR": "Falha ao adicionar membro. Por favor, tente novamente.", + "REMOVE_BUTTON": "Remover", + "REMOVE_SUCCESS": "Membro removido com sucesso.", + "REMOVE_ERROR": "Falha ao remover membro. Por favor, tente novamente.", + "PROMOTE_BUTTON": "Promover a Admin", + "PROMOTE_SUCCESS": "Membro promovido a admin.", + "PROMOTE_ERROR": "Falha ao promover membro. Por favor, tente novamente.", + "DEMOTE_BUTTON": "Rebaixar para Membro", + "DEMOTE_SUCCESS": "Membro rebaixado para membro.", + "DEMOTE_ERROR": "Falha ao rebaixar membro. Por favor, tente novamente." + }, + "JOIN_REQUESTS": { + "SECTION_TITLE": "Solicitações Pendentes", + "PENDING_COUNT": "{count} pendentes", + "APPROVE_BUTTON": "Aprovar", + "REJECT_BUTTON": "Rejeitar", + "APPROVE_SUCCESS": "Solicitação de entrada aprovada.", + "REJECT_SUCCESS": "Solicitação de entrada rejeitada.", + "ACTION_ERROR": "Falha ao processar solicitação de entrada. Por favor, tente novamente." + }, + "MENTION": { + "DROPDOWN_HEADER": "Membros do Grupo" + } + } +} diff --git a/app/javascript/dashboard/i18n/locale/pt_BR/index.js b/app/javascript/dashboard/i18n/locale/pt_BR/index.js index 213387d0cab9b..4cf5ff2ca0533 100644 --- a/app/javascript/dashboard/i18n/locale/pt_BR/index.js +++ b/app/javascript/dashboard/i18n/locale/pt_BR/index.js @@ -1,4 +1,5 @@ import advancedFilters from './advancedFilters.json'; +import groups from './groups.json'; import agentBots from './agentBots.json'; import agentMgmt from './agentMgmt.json'; import attributesMgmt from './attributesMgmt.json'; @@ -38,6 +39,7 @@ import whatsappTemplates from './whatsappTemplates.json'; export default { ...advancedFilters, + ...groups, ...agentBots, ...agentMgmt, ...attributesMgmt, diff --git a/app/javascript/dashboard/routes/dashboard/conversation/ContactPanel.vue b/app/javascript/dashboard/routes/dashboard/conversation/ContactPanel.vue index c148625fa35c4..fb5c063294e7c 100644 --- a/app/javascript/dashboard/routes/dashboard/conversation/ContactPanel.vue +++ b/app/javascript/dashboard/routes/dashboard/conversation/ContactPanel.vue @@ -14,6 +14,7 @@ import ContactConversations from './ContactConversations.vue'; import ConversationAction from './ConversationAction.vue'; import ConversationParticipant from './ConversationParticipant.vue'; import ContactInfo from './contact/ContactInfo.vue'; +import GroupContactInfo from './contact/GroupContactInfo.vue'; import ContactNotes from './contact/ContactNotes.vue'; import ScheduledMessages from './scheduledMessages/ScheduledMessages.vue'; import ConversationInfo from './ConversationInfo.vue'; @@ -88,6 +89,14 @@ const conversationAdditionalAttributes = computed( ); const channelType = computed(() => currentChat.value.meta?.channel); +const isGroupConversation = computed( + () => currentChat.value.group_type === 'group' +); +const sidebarTitle = computed(() => + isGroupConversation.value + ? 'GROUP.INFO.SIDEBAR_TITLE' + : 'CONVERSATION.SIDEBAR.CONTACT' +); const contactGetter = useMapGetter('contacts/getContact'); const contactId = computed(() => currentChat.value.meta?.sender?.id); @@ -134,10 +143,11 @@ onMounted(() => {