AI Workforce API reference
Complete field and method reference for every model in social_media_ai_workforce, for developers and integrators.
This page covers the Python API — model names, field signatures, method signatures and return values — for social_media_ai_workforce. For HTTP webhooks see Webhook API. For user-facing behaviour see the AI Workforce section.
social.ai.agent#
Module: social_media_ai_workforce
Inherits: mail.thread
Order: sequence, name
Constraint: unique(name, company_id) — duplicate name per company is rejected.
Fields#
| Name | Type | Default | Notes |
|---|---|---|---|
name | Char | required | Unique within company. |
sequence | Integer | 10 | Sort order in list. |
active | Boolean | True | Standard archive flag. |
role_title | Char | — | Shown in UI as Role. |
category | Selection | 'marketing' | sales, marketing, content, support, brand, intelligence. Required. |
description | Text | — | Plain-text description. |
responsibilities | Text | — | One item per line. |
state | Selection | 'draft' | draft (Not Deployed), active, paused. Tracked. Not copied. |
autonomy_level | Selection | 'approval_required' | approval_required, assisted, semi_autonomous, autonomous. Tracked. |
autonomy_explanation | Char | computed | Plain-English meaning of the current level. |
max_posts_per_day | Integer | 10 | 0 = no cap. Negative values are rejected. |
requires_approval_with_image | Boolean | True | Forces human approval for any post with attachments. |
odoo_model_access | Char | — | Declarative only; not enforced by the module. |
channel_ids_text | Char | — | Declarative only; not enforced by the module. |
activity_log_ids | One2many → social.ai.activity | — | Entries for this agent. |
post_count | Integer | computed | Posts whose ai_agent_id is this agent. |
pending_approval_count | Integer | computed | Posts in pending_approval state for this agent. |
activity_count | Integer | computed | Entries in social.ai.activity for this agent. |
company_id | Many2one → res.company | current company | Required. |
Methods#
action_activate()#
Sets state = 'active'. Managers only (enforced in the view; not in Python).
action_pause()#
Sets state = 'paused'.
action_view_activity()#
Returns an ir.actions.act_window opening social.ai.activity filtered to this agent.
check_can_publish(post) → (bool, str)#
The central guardrail. Evaluates whether this agent may publish post without a prior human approval. Returns (True, '') on success, or (False, reason) on refusal.
Checks in order:
state == 'active'— paused or not-deployed agents are refused.autonomy_level≥semi_autonomous— agents below this level require human approval.- If
requires_approval_with_imageandpost.attachment_ids— media without a human is refused. - If
max_posts_per_day > 0and_posts_published_today() >= max_posts_per_day— daily cap exceeded.
The caller is responsible for logging the refusal and raising the error.
_autonomy_at_least(level) → bool#
Returns True when this agent's autonomy rank is ≥ the given level. level is a key from the autonomy_level selection ('approval_required', 'assisted', 'semi_autonomous', 'autonomous'). Rank order is ascending: approval_required=0, assisted=1, semi_autonomous=2, autonomous=3.
_posts_published_today() → int#
Counts social.ai.activity entries for this agent with action_type == 'publish' and create_date ≥ start of today (UTC). Used by the daily-cap check in check_can_publish.
social.ai.activity#
Module: social_media_ai_workforce
Order: create_date desc, id desc
Record name: decision
The audit trail. Created only through log(); no user group has create, write or delete rights.
Fields#
| Name | Type | Notes |
|---|---|---|
agent_id | Many2one → social.ai.agent | ondelete='set null'. Indexed. |
agent_name_snapshot | Char | Copied from agent.name at write time. Survives agent rename/delete. |
post_id | Many2one → telegram.post | ondelete='set null'. Indexed. |
action_type | Selection | See action types below. Required, indexed. |
trigger | Char | e.g. "User action by Alem". |
data_used | Char | What the agent consulted. |
decision | Char | Required. Short statement of the outcome. |
action_taken | Char | What was done. |
result | Text | Full outcome text or error. |
approval_status | Selection | not_required, auto_approved, human_approved, blocked. Default not_required. Indexed. |
autonomy_at_time | Char | Agent's autonomy level at the moment of writing. |
user_id | Many2one → res.users | ondelete='set null'. Defaults to current user. |
odoo_record | Char | e.g. "telegram.post#42". |
company_id | Many2one → res.company | Required. |
Action types#
| Key | Label | Written when |
|---|---|---|
generate | Content Generated | AI content was requested or applied. |
submit | Submitted for Approval | Post moved to pending_approval. |
approve | Approved | Manager approved the post. |
reject | Rejected | Manager rejected the post. |
schedule | Scheduled | Post was scheduled. |
publish | Published | Post was published successfully. |
publish_blocked | Publish Blocked | Gate refused the publish. |
publish_retry | Publish Retry Scheduled | Cron will retry after backoff. |
publish_failed | Publish Failed | Publish raised an error. |
autonomy_change | Autonomy Changed | Reserved for future use. |
sync | Data Synced | Reserved for metric sync events. |
Methods#
log(action_type, decision, agent=None, post=None, **kwargs) → social.ai.activity (classmethod)#
Creates one log entry. Always uses sudo() so logging never fails on permission checks.
| Parameter | Type | Notes |
|---|---|---|
action_type | str | Required. Must be a valid action_type key. |
decision | str | Required. Short statement of what happened. |
agent | social.ai.agent or None | The acting agent. Sets agent_id and agent_name_snapshot. |
post | telegram.post or None | The post concerned. Sets post_id. |
**kwargs | Any additional field values: trigger, data_used, action_taken, result, approval_status, autonomy_at_time, user_id, odoo_record, company_id. |
company_id is resolved via _resolve_company(agent, post) if not supplied — this handles webhook calls where env.company is empty.
_resolve_company(agent=None, post=None) → res.company#
Falls back through post.company_id, agent.company_id, env.company, and finally a sudo() search for any company. Ensures the required company_id field can always be satisfied in webhook (no-user) context.
telegram.post (extended fields and methods)#
social_media_ai_workforce inherits telegram.post from the base module. New fields and methods only; base fields are unchanged.
Added fields#
| Name | Type | Default | Notes |
|---|---|---|---|
state | Selection (extend) | — | Adds pending_approval, approved, scheduled, failed, cancelled around the base draft/posted. |
ai_agent_id | Many2one → social.ai.agent | — | Handled By. Tracked. |
is_ai_generated | Boolean | False | Not copied on duplicate. |
approved_by_id | Many2one → res.users | — | Read-only, not copied. |
approved_date | Datetime | — | Read-only, not copied. |
rejection_reason | Text | — | Read-only, not copied. |
failure_reason | Text | — | Read-only, not copied. |
publish_attempts | Integer | 0 | Read-only, not copied. Reset to 0 on success or reset-to-draft. |
next_retry_at | Datetime | — | Read-only, not copied. Cron skips this post until this time passes. |
ai_activity_ids | One2many → social.ai.activity | — | |
ai_activity_count | Integer | computed | |
char_count | Integer | computed | Length of message + "\n\n" + hashtags. |
char_limit_warning | Char | computed | Non-empty when over a platform limit. Limits: X 280, Instagram 2,200, Telegram 4,096. Facebook (63,206) is not warned. |
ai_brief | Text | — | What to write about. Falls back to message if empty. |
ai_content_status | Selection | 'none' | none, requested, received, failed. Not copied. |
ai_error_message | Text | — | Read-only, not copied. |
Approval and state methods#
action_submit_for_approval()#
Moves draft, failed, or cancelled → pending_approval. Clears rejection_reason. Logs submit.
Raises UserError if the post is in any other state.
action_approve()#
Manager only. Moves pending_approval → approved. Sets approved_by_id and approved_date. Logs approve with approval_status='human_approved'.
Raises AccessError if the caller is not a Manager. Raises UserError if the post is not pending_approval.
action_reject()#
Manager only. Moves pending_approval → draft. Logs reject.
Raises AccessError if the caller is not a Manager. Raises UserError if the post is not pending_approval.
action_schedule()#
Moves approved (or draft for Managers) → scheduled. Resets publish_attempts and next_retry_at.
Requires scheduled_date to be set and in the future. A non-Manager can only schedule an already-approved post.
action_reset_to_draft()#
Moves any non-posted state → draft. Clears failure_reason, publish_attempts, next_retry_at.
Raises UserError for a posted post (use delete to remove it from platforms).
action_retry_now()#
Manager only. Clears next_retry_at on a scheduled post that is in backoff, so the next cron tick picks it up immediately.
action_cancel()#
Moves any non-posted state → cancelled.
Publishing methods#
action_publish_post()#
Wraps the base module's publisher behind _check_publish_allowed(). Logs publish on success and publish_failed on error (re-raising the exception).
approval_status in the log is 'auto_approved' when the post was published by an agent without prior human approval, 'human_approved' otherwise.
_check_publish_allowed()#
Raises UserError if the post may not be published. Evaluates in order:
state == 'posted'→ pass through (base module handles it).- Current user is a Manager → allowed.
state in ('approved', 'scheduled')→ allowed.ai_agent_idset → callsagent.check_can_publish(self). Allowed or refused-and-logged.- Anything else → refused.
AI content methods#
action_request_ai_content()#
Sends the post's brief to the configured n8n webhook URL. Sets ai_content_status = 'requested'. Returns a client-side notification action.
Requires social_media_ai_workforce.ai_webhook_url and social_media_ai_workforce.api_key to be set. Raises UserError on missing config, HTTP error, or network failure.
The payload sent to n8n:
{
"post_id": 42,
"brief": "…",
"hashtags": "…",
"agent": "AI Content Creator",
"platforms": { "telegram": true, "facebook": false, "instagram": false, "twitter": false },
"callback_url": "https://your-odoo.example.com/social_ai/webhook/posts/42/content",
"api_key": "…"
}
apply_ai_content(message=None, hashtags=None)#
Applies AI-generated content to the post. Called from the /content webhook. Sets is_ai_generated = True and ai_content_status = 'received'.
Raises UserError if ai_content_status != 'requested' (refuses to overwrite content that is not waiting on a request) or if state is not draft or pending_approval (refuses to modify an approved or published post).
Scheduled action methods#
_cron_publish_scheduled_posts() (classmethod)#
Selects up to 50 scheduled posts whose scheduled_date ≤ now and next_retry_at is unset or past. Publishes each one in its own transaction.
Retry backoff: on failure, the post is not immediately set to failed. Instead, publish_attempts increments and next_retry_at is set using the backoff schedule (5, 15, 45) minutes. Only after _max_publish_attempts() attempts (default 4) does the post move to failed.
_max_publish_attempts() reads social_media_ai_workforce.max_publish_attempts from system parameters; default is len(_RETRY_BACKOFF_MINUTES) + 1 = 4.
Logs publish, publish_retry, or publish_failed for each post.
_cron_update_views_safe() (classmethod)#
Calls action_update_views() on each posted post that has a telegram_message_id, one at a time. Replaces the base module's broken cron that called ensure_one() on a whole recordset.
Internal helpers#
_log_ai(action_type, decision, **kwargs)#
Delegates to social.ai.activity.log() with agent=self.ai_agent_id and post=self. The odoo_record is always set to "telegram.post#<id>".
_is_manager() → bool#
Returns True if the current user has the social_media_ai_workforce.group_social_media_manager group.
_require_manager(action_label)#
Calls _is_manager() and raises AccessError(_("Only a Social Media Manager can %s.") % action_label) if it returns False.
social.campaign#
Module: social_media_ai_workforce
Inherits: mail.thread
Order: date_start desc, id desc
Constraint: unique(name, company_id).
Fields#
| Name | Type | Default | Notes |
|---|---|---|---|
name | Char | required | |
active | Boolean | True | |
color | Integer | — | Kanban colour index. |
utm_campaign_id | Many2one → utm.campaign | — | Created by _ensure_utm_campaign(). ondelete='restrict'. |
utm_source_id | Many2one → utm.source | — | |
utm_medium_id | Many2one → utm.medium | — | |
objective | Selection | 'awareness' | awareness, engagement, traffic, leads, sales, retention. |
state | Selection | 'draft' | draft (Planning), running, done (Finished), cancelled. Tracked. Not copied. |
date_start | Date | — | |
date_end | Date | — | Must be ≥ date_start. |
user_id | Many2one → res.users | current user | |
ai_agent_id | Many2one → social.ai.agent | — | Default agent inherited by new posts. |
brief | Html | — | |
budget | Monetary | — | Currency from currency_id. |
currency_id | Many2one → res.currency | company currency | |
target_posts | Integer | — | |
target_engagement | Integer | — | |
target_leads | Integer | — | |
post_ids | One2many → telegram.post | — | Via campaign_id. |
post_count | Integer | computed | |
published_count | Integer | computed | |
pending_count | Integer | computed | |
scheduled_count | Integer | computed | |
total_views | Integer | computed | |
total_likes | Integer | computed | |
total_comments | Integer | computed | |
total_engagement | Integer | computed | |
engagement_rate | Float | computed | Percentage, 2dp. |
progress_posts | Float | computed | post_count / target_posts * 100. 0 if no target. |
progress_engagement | Float | computed | total_engagement / target_engagement * 100. 0 if no target. |
company_id | Many2one → res.company | current company | Required. |
Methods#
action_start()#
Calls _ensure_utm_campaign() then sets state = 'running'.
action_finish()#
Sets state = 'done'.
action_cancel()#
Sets state = 'cancelled'.
action_reset_to_draft()#
Sets state = 'draft'.
action_view_posts()#
Returns an ir.actions.act_window on telegram.post filtered to this campaign, with default_campaign_id and default_ai_agent_id in context.
_ensure_utm_campaign() → utm.campaign#
Creates the utm.campaign record on first call (lazy). Also sets default utm_source_id (utm_source_smarterp_social) and utm_medium_id (utm_medium_social_media) if unset and the XML IDs exist. Returns the campaign. Idempotent: safe to call multiple times.
telegram.post (campaign and metrics extension)#
social_media_ai_workforce adds a second inheritance block for campaign membership, link tracking and metrics. These fields are on telegram.post.
Added fields#
| Name | Type | Default | Notes |
|---|---|---|---|
campaign_id | Many2one → social.campaign | — | ondelete='set null', indexed, tracked. |
track_links | Boolean | True | Append UTM parameters to every URL in message. |
tracked_message | Text | computed | message with UTM parameters applied. |
link_count | Integer | computed | Number of URLs found in message. |
total_views | Integer | computed, stored | |
total_engagement | Integer | computed, stored | |
engagement_rate | Float | computed, stored | 2dp. |
metric_ids | One2many → social.post.metric | — | The snapshot history. |
Methods#
_social_metric_totals() → dict#
Returns a dict with keys views, likes, comments, shares, engagement, engagement_rate, summing across the recordset. Aggregates from all platform-specific fields defined in METRIC_FIELDS.
_utm_parameters() → dict#
Returns the UTM key/value pairs for this post, derived from its campaign. Returns {} if there is no campaign, or if the campaign has no utm_campaign_id yet. Safe to call at compute time.
_tag_url(url, params) → str#
Adds params to url without overwriting existing query parameters. Existing utm_* keys win.
action_apply_tracked_links()#
Writes tracked_message into message for any post in the recordset where they differ.
_snapshot_metrics()#
Creates one social.post.metric row for each post that has non-zero metrics. Called by _cron_snapshot_metrics.
_cron_snapshot_metrics() (classmethod)#
Daily. Selects posted posts with write_date ≥ 90 days ago (limit 500) and calls _snapshot_metrics.
social.post.metric#
Module: social_media_ai_workforce
Order: captured_at desc, id desc
Record name: captured_at
Append-only snapshot table. Each row is a dated reading of one post's numbers.
Fields#
| Name | Type | Notes |
|---|---|---|
post_id | Many2one → telegram.post | Required, ondelete='cascade', indexed. |
campaign_id | Many2one → social.campaign | ondelete='set null', indexed. |
captured_at | Datetime | Default: now. Indexed. |
capture_date | Date | Computed from captured_at in the user's timezone. Stored, indexed. |
views | Integer | |
likes | Integer | |
comments | Integer | |
shares | Integer | |
engagement | Integer | |
views_delta | Integer | Change since previous snapshot. Negative values are valid. |
engagement_delta | Integer | Change since previous snapshot. |
company_id | Many2one → res.company | Required. |
Methods#
create() calls _compute_deltas() automatically on every new record.
_compute_deltas()#
Finds the previous snapshot for each new record (same post_id, earlier or equal captured_at, excluding self) and sets views_delta and engagement_delta as the difference. If there is no previous snapshot, the absolute values are used.
social.connection.health#
Module: social_media_ai_workforce
Auto: False (SQL view, not a stored table)
Order: health_signal desc, platform, name
Read-only. Backed by a CREATE OR REPLACE VIEW that unions all five platform account tables. No create, write or delete on this model.
Fields#
| Name | Type | Notes |
|---|---|---|
name | Char | Account name from the source table. |
platform | Selection | telegram, facebook, instagram, twitter, whatsapp. |
state | Selection | connected, disconnected, error. Normalised across five different platform vocabularies. |
health_signal | Selection | 2_healthy (Healthy), 1_attention (Not Connected), 0_critical (Needs Attention). Sort direction is descending, so the most critical appear first. |
error_message | Text | Platform error text, if any. |
active | Boolean | Whether the source account is enabled. |
last_updated | Datetime | write_date of the source row. |
res_model | Char | The source model name ('telegram.bot', 'facebook.account', etc.). |
res_id | Integer | The source record's ID. |
company_id | Many2one → res.company |
Methods#
action_open_account()#
Returns an ir.actions.act_window for res_model / res_id. Opens the actual source account record.
init()#
Drops and recreates the view. The id column uses ROW_NUMBER() OVER () rather than the source table's id, because the five source tables each have their own sequence starting at 1 and a simple union would collide.
twitter.account (extended)#
social_media_ai_workforce inherits twitter.account to add automated token refresh.
Methods#
_cron_refresh_tokens() (classmethod)#
Finds all connected accounts with a refresh_token and calls _refresh_access_token() on each, committing per account. Logs a warning for each failure without aborting the loop. Used by the Social: Refresh X Access Tokens hourly scheduled action.
HTTP routes#
All routes use auth='none'. Authentication is via the X-Api-Key header. A missing or incorrect key returns 401 {"error": "unauthorized"}. The key is compared in constant time via hmac.compare_digest. See Webhook API for full request/response documentation.
| Method | Path | Handler | Purpose |
|---|---|---|---|
GET | /social_ai/webhook/posts/due | SocialAiWebhookController.posts_due | Scheduled posts ready for an external publisher. |
POST | /social_ai/webhook/posts/<int:post_id>/content | SocialAiWebhookController.post_content | Receive AI-generated copy. |
POST | /social_ai/webhook/posts/<int:post_id>/result | SocialAiWebhookController.post_result | Report the outcome of an external publish. |
The /posts/due route applies the same check_can_publish guardrails as the internal cron, so a paused or over-cap agent's posts are excluded and the exclusion is logged as publish_blocked.
The /content route calls apply_ai_content() and returns 409 if that method raises UserError (post is not waiting on a request, or is already approved/published).
System parameters#
Set at Settings → Technical → Parameters → System Parameters.
| Key | Purpose | Default |
|---|---|---|
social_media_ai_workforce.api_key | Shared secret for all webhook routes. | — (must be set) |
social_media_ai_workforce.ai_webhook_url | n8n URL that receives AI generation requests. | — |
social_media_ai_workforce.max_publish_attempts | Max cron attempts before a post becomes Failed. | 4 |
Groups#
| XML ID | Label | Implies |
|---|---|---|
social_media_ai_workforce.group_social_media_user | AI Growth Workforce / User | — |
social_media_ai_workforce.group_social_media_manager | AI Growth Workforce / Manager | User |
Default rules: every internal user → User; every Settings user → Manager.