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β
- Confirm the pipeline exists for the account.
- Build a query scoped to
module: 'DEAL'plus optional regex filters. - Count and fetch automations concurrently.
- 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
qreturns all matching automations.
searchAutomation β Error Handlingβ
- Returns
{ success:false, errno:400, message:'INVALID_PIPELINE' }when validation fails. - Other failures bubble as
INTERNAL_ERRORpayloads.
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β
- Validate pipeline ownership.
- Retrieve stages via
pipeline.getStages(). - Query automations tied to the pipeline.
- For each automation, run
toCountJSON()and place it under the matching stage. - Return cleaned stage records with populated
automationsarrays.
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
cleanRecordprocessed 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β
- Validate pipeline.
- Call
pipeline.updateStageswith account context for ownership enforcement. - Clean each returned stage and automation.
- 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_FOUNDwhen 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β
- Validate pipeline.
- Query deals in the stage; block deletion when any exist.
- 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_UPDATEso 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.