Skip to main content

Automation

πŸ“– Overview​

internal/api/v1/crm/services/automation.service.js keeps pipeline stage automations consistent. It validates pipeline ownership, hydrates stage metadata with automation payloads, and exposes focused helpers for creating, updating, or deleting workflow rules without leaking cross-account data.

πŸ—„οΈ Collections Used​

πŸ“š Full Schema: See Database Collections Documentation

crm.pipeline​

  • Operations: Reads pipeline definition, mutates stages through helper methods
  • Model: shared/models/pipeline.js
  • Usage Context: Source of truth for stage ordering; exposes addStage, updateStage, getStageWithAutomations, removeStage

crm.automations​

  • Operations: Query, insert, update, and delete automation documents
  • Model: shared/models/automation.js
  • Usage Context: Stores workflow configuration per stage with trigger data and status flags

crm.deals​

  • Operations: Read (guarding stage deletion when deals still exist)
  • Model: shared/models/deal.js
  • Usage Context: Prevents removal of stages containing active deals

πŸ”„ Data Flow​

flowchart TD
A[Controller Request] --> B{Validate Pipeline}
B -->|missing| Z[400 INVALID_PIPELINE]
B -->|ok| C[Load Stages]
C --> D[Fetch Automations]
D --> E[automationUtils.cleanRecord]
E --> F[Attach to Stages]
F --> G[Service Response]

subgraph Stage Mutations
H[Stage Payload] --> I[Pipeline.addStage/updateStage]
I --> J[Clean Output]
J --> G
end

subgraph Deletion Guard
K[deleteByStageAutomation] --> L[Check Deals]
L -->|has deals| Y[STAGE_NOT_EMPTY]
L -->|empty| M[Pipeline.removeStage]
M --> G
end

πŸ”§ Business Logic & Functions​


searchAutomation({ id, limit, page, q, account_id })​

searchAutomation – Purpose​

Paginated list of automations for a pipeline.

searchAutomation – Parameters​

  • id (ObjectId string) – Pipeline identifier.
  • limit, page (string/number) – Pagination controls (parsed to integers).
  • q (string, optional) – Regex search across description and status.
  • account_id (ObjectId string) – Account scope.

searchAutomation – Returns​

Promise<{ success, data, pagination }> with automations run through toCountJSON() and pagination metadata.

searchAutomation – Flow​

  1. Confirm the pipeline exists for the account.
  2. Build a query scoped to module: 'DEAL' plus optional regex filters.
  3. Count and fetch automations concurrently.
  4. Normalise results via toCountJSON() for response consumption.

searchAutomation – Key Business Rules​

  • Access is denied when the pipeline does not exist or belongs to another account.
  • Search is optional; absence of q returns all matching automations.

searchAutomation – Error Handling​

  • Returns { success:false, errno:400, message:'INVALID_PIPELINE' } when validation fails.
  • Other failures bubble as INTERNAL_ERROR payloads.

searchAutomation – Side Effects​

None.


getAutomation({ id, account_id })​

getAutomation – Purpose​

Fetch all stages for a pipeline with their automations attached for dashboard rendering.

getAutomation – Flow​

  1. Validate pipeline ownership.
  2. Retrieve stages via pipeline.getStages().
  3. Query automations tied to the pipeline.
  4. For each automation, run toCountJSON() and place it under the matching stage.
  5. Return cleaned stage records with populated automations arrays.

getAutomation – Key Business Rules​

  • Unexpected absence of stages yields an internal error instructing support follow-up.
  • Automations are grouped by stage id to match UI expectations.

getAutomation – Side Effects​

None.


postAutomation({ body, account_id, id, auth })​

postAutomation – Purpose​

Add a new automation (or stage + automation) to a pipeline.

postAutomation – Highlights​

  • Pipeline existence is guaranteed before mutation.
  • Delegates to pipeline.addStage, which persists the automation and returns the updated stage.
  • Response is cleanRecord processed to strip Mongo internals.

postAutomation – Side Effects​

Creates an automation document and may append a stage.


putAutomation({ id, account_id, uid, body })​

putAutomation – Purpose​

Bulk update stages and automations using the payload produced by the UI editor.

putAutomation – Flow​

  1. Validate pipeline.
  2. Call pipeline.updateStages with account context for ownership enforcement.
  3. Clean each returned stage and automation.
  4. Translate domain errors into user-friendly messages (INVALID_STAGE_UPDATE, INVALID_AUTOMATION_UPDATE, INVALID_STAGE_DELETE, MINIMUM_ONE_STAGE_REQUIRED, STAGE_NOT_EMPTY).

putAutomation – Side Effects​

Adds, updates, or removes automations and can reorder stages.


getByStageAutomation({ id, stage_id, account_id })​

getByStageAutomation – Purpose​

Load a specific stage (and its automations) for edit forms.

getByStageAutomation – Behaviour​

  • Leverages pipeline.getStageWithAutomations.
  • Returns RESOURCE_NOT_FOUND when the stage id is invalid for the pipeline.

updateByStageAutomation({ id, stage_id, account_id, uid, body })​

updateByStageAutomation – Purpose​

Update automations for one stage without touching others.

updateByStageAutomation – Characteristics​

  • Calls pipeline.updateStage, which enforces ownership and automation id validity.
  • Distinguishes invalid automation ids from generic failures.

deleteByStageAutomation({ id, stage_id, account_id })​

deleteByStageAutomation – Purpose​

Remove a stage/automation combination after ensuring no deals remain in that stage.

deleteByStageAutomation – Flow​

  1. Validate pipeline.
  2. Query deals in the stage; block deletion when any exist.
  3. Delegate removal to pipeline.removeStage.

deleteByStageAutomation – Error Handling​

Returns STAGE_NOT_EMPTY with guidance to move deals first.

deleteByStageAutomation – Side Effects​

Deletes the stage record and attached automations.

πŸ”€ Integration Points​

Internal Dependencies​

  • ../utils/automation (cleanRecord) – normalises stage/automation payloads.
  • shared/models/pipeline – exposes stage helper methods used for CRUD operations.
  • shared/models/deal – deletion guard when stages are in use.

External Services​

  • None – operations are purely within MongoDB.

πŸ§ͺ Edge Cases & Special Handling​

  • Invalid Pipeline: Every entry point fails fast to prevent cross-account access.
  • Stage Not Empty: Deletion short-circuits with STAGE_NOT_EMPTY; controllers relay the friendly copy surfaced by the service.
  • Automation ID Drift: Bulk updates detect unknown automation ids and respond with INVALID_AUTOMATION_UPDATE so the UI can refresh its state.

⚠️ Important Notes​

  • 🚨 Module scope: Automations here are hardcoded to module: 'DEAL'; other modules require separate services.
  • πŸ’‘ Use helper outputs: Always return the cleaned stage data supplied by the serviceβ€”manual formatting risks leaking internal fields.
πŸ’¬

Documentation Assistant

Ask me anything about the docs

Hi! I'm your documentation assistant. Ask me anything about the docs!

I can help you with:
- Code examples
- Configuration details
- Troubleshooting
- Best practices

Try asking: How do I configure the API?
09:31 AM