openforce/frontend/src/stores/crm.js
Goose cbcc16d7e1
Some checks failed
Build, Test, and Deploy / build-and-deploy (push) Failing after 40s
feat(formulas): implement roll-up summary engine and frontend formula editor (Sprint 4.5C & 4.5D)
- Add custom_objects/rollup_engine.py supporting COUNT, SUM, MIN, MAX aggregations across child relationships with optional JSON filter criteria.
- Wire post_save and post_delete reverse relation signal handlers in custom_objects/signals.py for Opportunity, Contact, and Activity relationships.
- Add frontend formula editor & roll-up configurator in CustomObjectsView.vue with insert helpers (fields, operators, functions) and Check Syntax validation.
- Add validateFormula action to frontend/src/stores/crm.js.
- Add unit and integration tests in tests/test_rollup_engine.py with 100% pass rate.
2026-09-27 20:31:27 +00:00

297 lines
10 KiB
JavaScript

import { defineStore } from 'pinia'
import api from '../api'
export const useCrmStore = defineStore('crm', {
state: () => ({
activeTab: 'leads',
currentRecord: null,
leads: [],
opportunities: [],
contacts: [],
accounts: [],
activities: [],
customObjects: [],
customFields: [],
standardFields: {},
allObjectFields: [],
customRecords: {},
flows: [],
campaigns: [],
loading: false,
error: null,
}),
actions: {
setActiveTab(tab) {
this.activeTab = tab
this.currentRecord = null
},
async fetchLeads() {
try {
const res = await api.get('/leads/')
this.leads = res.data.results || res.data
} catch (err) {
console.error(err)
}
},
async createLead(leadData) {
const res = await api.post('/leads/', leadData)
await this.fetchLeads()
return res.data
},
async fetchOpportunities() {
try {
const res = await api.get('/opportunities/')
this.opportunities = res.data.results || res.data
} catch (err) {
console.error(err)
}
},
async createOpportunity(oppData) {
const res = await api.post('/opportunities/', oppData)
await this.fetchOpportunities()
return res.data
},
async fetchContacts() {
try {
const res = await api.get('/contacts/')
this.contacts = res.data.results || res.data
} catch (err) {
console.error(err)
}
},
async createContact(contactData) {
const res = await api.post('/contacts/', contactData)
await this.fetchContacts()
return res.data
},
async fetchAccounts() {
try {
const res = await api.get('/accounts/')
this.accounts = res.data.results || res.data
} catch (err) {
console.error(err)
}
},
async createAccount(accountData) {
const res = await api.post('/accounts/', accountData)
await this.fetchAccounts()
return res.data
},
async fetchActivities() {
try {
const res = await api.get('/activities/')
this.activities = res.data.results || res.data
} catch (err) {
console.error(err)
}
},
async createActivity(activityData) {
const res = await api.post('/activities/', activityData)
await this.fetchActivities()
return res.data
},
async updateActivityStatus(activityId, status) {
const res = await api.patch(`/activities/${activityId}/`, { status })
await this.fetchActivities()
return res.data
},
async fetchCustomObjects() {
try {
const res = await api.get('/custom-objects/')
this.customObjects = res.data.results || res.data
} catch (err) {
console.error(err)
}
},
async createCustomObject(objData) {
const res = await api.post('/custom-objects/', objData)
await this.fetchCustomObjects()
return res.data
},
async fetchCustomFields(objectIdOrEntityName) {
try {
let url = '/custom-fields/'
if (typeof objectIdOrEntityName === 'number') {
url += `?custom_object=${objectIdOrEntityName}`
} else if (typeof objectIdOrEntityName === 'string') {
url += `?entity_name=${objectIdOrEntityName}`
}
const res = await api.get(url)
this.customFields = res.data.results || res.data
return this.customFields
} catch (err) {
console.error(err)
this.customFields = []
return []
}
},
async fetchObjectSchema(entityNameOrId, isCustom = false) {
try {
let standard = []
let custom = []
if (!isCustom) {
const entityName = typeof entityNameOrId === 'string' ? entityNameOrId : entityNameOrId.name
try {
const schemaRes = await api.get(`/schema/objects/${entityName}/fields/`)
standard = (schemaRes.data.standard_fields || []).map(f => ({
...f,
is_custom: false,
origin: 'Standard'
}))
this.standardFields[entityName] = standard
} catch (e) {
console.warn(`Could not load standard schema for ${entityName}:`, e)
}
custom = await this.fetchCustomFields(entityName)
} else {
const customObjId = typeof entityNameOrId === 'number' ? entityNameOrId : entityNameOrId.id
custom = await this.fetchCustomFields(customObjId)
// Standard audit fields for custom objects
standard = [
{ name: 'id', label: 'Record ID', data_type: 'AutoNumber', is_custom: false, is_required: true, is_unique: true, is_indexed: true, origin: 'Standard', editable: false },
{ name: 'name', label: 'Record Name', data_type: 'Text', is_custom: false, is_required: true, is_unique: false, is_indexed: true, origin: 'Standard', editable: true },
{ name: 'owner', label: 'Owner', data_type: 'Lookup', related_to: 'User', is_custom: false, is_required: false, is_unique: false, is_indexed: true, origin: 'Standard', editable: false },
{ name: 'created_at', label: 'Created Date', data_type: 'Date/Time', is_custom: false, is_required: false, is_unique: false, is_indexed: false, origin: 'Standard', editable: false },
{ name: 'updated_at', label: 'Modified Date', data_type: 'Date/Time', is_custom: false, is_required: false, is_unique: false, is_indexed: false, origin: 'Standard', editable: false },
]
}
const normalizedCustom = (custom || []).map(f => {
let displayType = (f.field_type || 'Text').charAt(0).toUpperCase() + (f.field_type || 'Text').slice(1)
if (f.field_type === 'formula') {
displayType = `Formula (${(f.formula_return_type || 'Text').charAt(0).toUpperCase() + (f.formula_return_type || 'Text').slice(1)})`
} else if (f.field_type === 'rollup_summary') {
displayType = `Roll-Up Summary (${(f.rollup_type || 'COUNT').toUpperCase()})`
}
return {
name: f.name,
label: f.label || f.name,
data_type: displayType,
field_type: f.field_type,
formula_expression: f.formula_expression,
formula_return_type: f.formula_return_type,
rollup_summary_object: f.rollup_summary_object,
rollup_field: f.rollup_field,
rollup_type: f.rollup_type,
rollup_filter: f.rollup_filter,
is_custom: true,
is_formula: f.field_type === 'formula',
is_rollup: f.field_type === 'rollup_summary',
is_required: !!f.is_required,
is_unique: !!f.is_unique,
is_indexed: !!f.is_unique,
choices: f.options || f.choices || [],
origin: f.field_type === 'formula' ? 'Custom (Formula)' : (f.field_type === 'rollup_summary' ? 'Custom (Roll-Up)' : 'Custom'),
editable: true,
id: f.id,
raw: f
}
})
this.allObjectFields = [...standard, ...normalizedCustom]
return this.allObjectFields
} catch (err) {
console.error('Error in fetchObjectSchema:', err)
this.allObjectFields = []
return []
}
},
async createCustomField(fieldData) {
const res = await api.post('/custom-fields/', fieldData)
await this.fetchCustomObjects()
return res.data
},
async validateFormula(expression) {
const res = await api.post('/custom-fields/validate-formula/', { expression })
return res.data
},
async fetchCustomRecords(objectName) {
try {
const res = await api.get(`/custom/${objectName}/`)
this.customRecords[objectName] = res.data.results || res.data
return this.customRecords[objectName]
} catch (err) {
console.error(err)
return []
}
},
async insertCustomRecord(objectName, data) {
const res = await api.post(`/custom/${objectName}/`, { data })
await this.fetchCustomRecords(objectName)
return res.data
},
async fetchFlows() {
try {
const res = await api.get('/flows/')
this.flows = res.data.results || res.data
} catch (err) {
console.error(err)
}
},
async fetchCampaigns() {
try {
const res = await api.get('/campaigns/')
this.campaigns = res.data.results || res.data
} catch (err) {
console.error(err)
}
},
async createCampaign(campaignData) {
const res = await api.post('/campaigns/', campaignData)
const campaignId = res.data.id
// Auto-populate recipients from target object (Leads or Contacts) if store has them
let recipients = []
if (campaignData.target_object === 'Lead' && this.leads.length > 0) {
recipients = this.leads.filter(l => l.email).map(l => ({
email: l.email,
first_name: l.first_name || '',
last_name: l.last_name || '',
merge_data: { first_name: l.first_name, company: l.company }
}))
} else if (campaignData.target_object === 'Contact' && this.contacts.length > 0) {
recipients = this.contacts.filter(c => c.email).map(c => ({
email: c.email,
first_name: c.first_name || '',
last_name: c.last_name || '',
merge_data: { first_name: c.first_name }
}))
}
if (recipients.length > 0) {
await api.post(`/campaigns/${campaignId}/add-recipients/`, { recipients })
}
// Auto-dispatch campaign
try {
await api.post(`/campaigns/${campaignId}/dispatch/`)
} catch (err) {
console.warn('Dispatch failed or pending:', err)
}
await this.fetchCampaigns()
return res.data
},
async dispatchCampaign(campaignId) {
const res = await api.post(`/campaigns/${campaignId}/dispatch/`)
await this.fetchCampaigns()
return res.data
},
async convertLead(leadId, payload) {
const res = await api.post(`/leads/${leadId}/convert/`, payload)
await this.fetchLeads()
await this.fetchAccounts()
await this.fetchContacts()
await this.fetchOpportunities()
return res.data
},
async updateOpportunityStage(oppId, stage) {
const res = await api.patch(`/opportunities/${oppId}/`, { stage })
await this.fetchOpportunities()
return res.data
}
}
})