የSmartERP መመሪያ የAshewa Technology Solutions መድረክ
ይህ ገጽ ገና ወደ አማርኛ አልተተረጎመም። የእንግሊዝኛው ጽሑፍ ቀርቧል።

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#

NameTypeDefaultNotes
nameCharrequiredUnique within company.
sequenceInteger10Sort order in list.
activeBooleanTrueStandard archive flag.
role_titleChar—Shown in UI as Role.
categorySelection'marketing'sales, marketing, content, support, brand, intelligence. Required.
descriptionText—Plain-text description.
responsibilitiesText—One item per line.
stateSelection'draft'draft (Not Deployed), active, paused. Tracked. Not copied.
autonomy_levelSelection'approval_required'approval_required, assisted, semi_autonomous, autonomous. Tracked.
autonomy_explanationCharcomputedPlain-English meaning of the current level.
max_posts_per_dayInteger100 = no cap. Negative values are rejected.
requires_approval_with_imageBooleanTrueForces human approval for any post with attachments.
odoo_model_accessChar—Declarative only; not enforced by the module.
channel_ids_textChar—Declarative only; not enforced by the module.
activity_log_idsOne2many → social.ai.activity—Entries for this agent.
post_countIntegercomputedPosts whose ai_agent_id is this agent.
pending_approval_countIntegercomputedPosts in pending_approval state for this agent.
activity_countIntegercomputedEntries in social.ai.activity for this agent.
company_idMany2one → res.companycurrent companyRequired.

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:

  1. state == 'active' — paused or not-deployed agents are refused.
  2. autonomy_level ≥ semi_autonomous — agents below this level require human approval.
  3. If requires_approval_with_image and post.attachment_ids — media without a human is refused.
  4. If max_posts_per_day > 0 and _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#

NameTypeNotes
agent_idMany2one → social.ai.agentondelete='set null'. Indexed.
agent_name_snapshotCharCopied from agent.name at write time. Survives agent rename/delete.
post_idMany2one → telegram.postondelete='set null'. Indexed.
action_typeSelectionSee action types below. Required, indexed.
triggerChare.g. "User action by Alem".
data_usedCharWhat the agent consulted.
decisionCharRequired. Short statement of the outcome.
action_takenCharWhat was done.
resultTextFull outcome text or error.
approval_statusSelectionnot_required, auto_approved, human_approved, blocked. Default not_required. Indexed.
autonomy_at_timeCharAgent's autonomy level at the moment of writing.
user_idMany2one → res.usersondelete='set null'. Defaults to current user.
odoo_recordChare.g. "telegram.post#42".
company_idMany2one → res.companyRequired.

Action types#

KeyLabelWritten when
generateContent GeneratedAI content was requested or applied.
submitSubmitted for ApprovalPost moved to pending_approval.
approveApprovedManager approved the post.
rejectRejectedManager rejected the post.
scheduleScheduledPost was scheduled.
publishPublishedPost was published successfully.
publish_blockedPublish BlockedGate refused the publish.
publish_retryPublish Retry ScheduledCron will retry after backoff.
publish_failedPublish FailedPublish raised an error.
autonomy_changeAutonomy ChangedReserved for future use.
syncData SyncedReserved 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.

ParameterTypeNotes
action_typestrRequired. Must be a valid action_type key.
decisionstrRequired. Short statement of what happened.
agentsocial.ai.agent or NoneThe acting agent. Sets agent_id and agent_name_snapshot.
posttelegram.post or NoneThe post concerned. Sets post_id.
**kwargsAny 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#

NameTypeDefaultNotes
stateSelection (extend)—Adds pending_approval, approved, scheduled, failed, cancelled around the base draft/posted.
ai_agent_idMany2one → social.ai.agent—Handled By. Tracked.
is_ai_generatedBooleanFalseNot copied on duplicate.
approved_by_idMany2one → res.users—Read-only, not copied.
approved_dateDatetime—Read-only, not copied.
rejection_reasonText—Read-only, not copied.
failure_reasonText—Read-only, not copied.
publish_attemptsInteger0Read-only, not copied. Reset to 0 on success or reset-to-draft.
next_retry_atDatetime—Read-only, not copied. Cron skips this post until this time passes.
ai_activity_idsOne2many → social.ai.activity—
ai_activity_countIntegercomputed
char_countIntegercomputedLength of message + "\n\n" + hashtags.
char_limit_warningCharcomputedNon-empty when over a platform limit. Limits: X 280, Instagram 2,200, Telegram 4,096. Facebook (63,206) is not warned.
ai_briefText—What to write about. Falls back to message if empty.
ai_content_statusSelection'none'none, requested, received, failed. Not copied.
ai_error_messageText—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:

  1. state == 'posted' → pass through (base module handles it).
  2. Current user is a Manager → allowed.
  3. state in ('approved', 'scheduled') → allowed.
  4. ai_agent_id set → calls agent.check_can_publish(self). Allowed or refused-and-logged.
  5. 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#

NameTypeDefaultNotes
nameCharrequired
activeBooleanTrue
colorInteger—Kanban colour index.
utm_campaign_idMany2one → utm.campaign—Created by _ensure_utm_campaign(). ondelete='restrict'.
utm_source_idMany2one → utm.source—
utm_medium_idMany2one → utm.medium—
objectiveSelection'awareness'awareness, engagement, traffic, leads, sales, retention.
stateSelection'draft'draft (Planning), running, done (Finished), cancelled. Tracked. Not copied.
date_startDate—
date_endDate—Must be ≥ date_start.
user_idMany2one → res.userscurrent user
ai_agent_idMany2one → social.ai.agent—Default agent inherited by new posts.
briefHtml—
budgetMonetary—Currency from currency_id.
currency_idMany2one → res.currencycompany currency
target_postsInteger—
target_engagementInteger—
target_leadsInteger—
post_idsOne2many → telegram.post—Via campaign_id.
post_countIntegercomputed
published_countIntegercomputed
pending_countIntegercomputed
scheduled_countIntegercomputed
total_viewsIntegercomputed
total_likesIntegercomputed
total_commentsIntegercomputed
total_engagementIntegercomputed
engagement_rateFloatcomputedPercentage, 2dp.
progress_postsFloatcomputedpost_count / target_posts * 100. 0 if no target.
progress_engagementFloatcomputedtotal_engagement / target_engagement * 100. 0 if no target.
company_idMany2one → res.companycurrent companyRequired.

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#

NameTypeDefaultNotes
campaign_idMany2one → social.campaign—ondelete='set null', indexed, tracked.
track_linksBooleanTrueAppend UTM parameters to every URL in message.
tracked_messageTextcomputedmessage with UTM parameters applied.
link_countIntegercomputedNumber of URLs found in message.
total_viewsIntegercomputed, stored
total_engagementIntegercomputed, stored
engagement_rateFloatcomputed, stored2dp.
metric_idsOne2many → 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.

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#

NameTypeNotes
post_idMany2one → telegram.postRequired, ondelete='cascade', indexed.
campaign_idMany2one → social.campaignondelete='set null', indexed.
captured_atDatetimeDefault: now. Indexed.
capture_dateDateComputed from captured_at in the user's timezone. Stored, indexed.
viewsInteger
likesInteger
commentsInteger
sharesInteger
engagementInteger
views_deltaIntegerChange since previous snapshot. Negative values are valid.
engagement_deltaIntegerChange since previous snapshot.
company_idMany2one → res.companyRequired.

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#

NameTypeNotes
nameCharAccount name from the source table.
platformSelectiontelegram, facebook, instagram, twitter, whatsapp.
stateSelectionconnected, disconnected, error. Normalised across five different platform vocabularies.
health_signalSelection2_healthy (Healthy), 1_attention (Not Connected), 0_critical (Needs Attention). Sort direction is descending, so the most critical appear first.
error_messageTextPlatform error text, if any.
activeBooleanWhether the source account is enabled.
last_updatedDatetimewrite_date of the source row.
res_modelCharThe source model name ('telegram.bot', 'facebook.account', etc.).
res_idIntegerThe source record's ID.
company_idMany2one → 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.

MethodPathHandlerPurpose
GET/social_ai/webhook/posts/dueSocialAiWebhookController.posts_dueScheduled posts ready for an external publisher.
POST/social_ai/webhook/posts/<int:post_id>/contentSocialAiWebhookController.post_contentReceive AI-generated copy.
POST/social_ai/webhook/posts/<int:post_id>/resultSocialAiWebhookController.post_resultReport 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.

KeyPurposeDefault
social_media_ai_workforce.api_keyShared secret for all webhook routes.— (must be set)
social_media_ai_workforce.ai_webhook_urln8n URL that receives AI generation requests.—
social_media_ai_workforce.max_publish_attemptsMax cron attempts before a post becomes Failed.4

Groups#

XML IDLabelImplies
social_media_ai_workforce.group_social_media_userAI Growth Workforce / User—
social_media_ai_workforce.group_social_media_managerAI Growth Workforce / ManagerUser

Default rules: every internal user → User; every Settings user → Manager.

መጨረሻ የተሻሻለው: 2026-11-15