When to use this endpoint

This route is an upsert/import workflow, not an append-only creation call. To request a new mapped record without matching, use Stock_createData.

Authentication and permissions

Authenticate with a signed API key or a logged-in CRM session on the account’s routed host. API keys act as their owner; session calls require dispatcher CSRF protection where configured. IDs address the authenticated tenant.

These stock handlers do not add a Stock page-action or CRM2 role check, and the dispatcher has no Stock/Stocks TeamAccess object mapping. CRM2 screen controls are separate from this shared API contract; their roles must not be assumed to apply to CRM1.

Parameters

ParameterTypeRequiredDescription
nameStringYesMust be present; ubertrim whitespace. Blank is not explicitly rejected. At most 80 bytes, unlike mapped UTF-8 character validation.
idInteger-compatibleNoPositive values select an existing undeleted item; missing/deleted targets and negative IDs fail. Omitted/0 enables code-based matching.
codeStringNoTrimmed, at most 182 bytes; defaults blank. New requests can match undeleted nonarchived items case-insensitively.
manual_creationInteger-compatibleNo1 returns the unique-code error on an existing code when duplicate-code imports are disabled.
cost / price / amountFloat-compatibleNoNew cost/price default 0; existing values are preserved if omitted. Explicit zero overwrites. amount defaults 0 and remains a signed warehouse increment.
is_archivedInteger-compatibleNoDefaults 0 on creation; omitted preserves an existing archive value.
supplier_id / supplierID / nameNoA supplied positive supplier ID must exist and be undeleted; otherwise a nonblank name is matched/created. Invalid positive IDs fail before saving.
nominal_code / taxString / float-compatibleNoWhen present set nominal code/tax percentage directly; omitted preserves them. tax is a percentage, not a category ID.
categoriesNative/JSON ID listNoAdds active category memberships inside the save transaction without replacing/clearing the old selection. Legacy import compatibility skips unknown or deleted category IDs.
description / notes / locationTextNoDescription/notes write only when supplied. location stores normalized location tags; location_tags writes raw metadata. When both are supplied, location takes precedence.
metaNative mapNoMerged into existing metadata; encoded JSON text is not decoded by this route. New rows add created=Stock_add.
manufacturer / barcode / manufacturer_part_no / supplier_part_noValuesNoPresent non-null values replace these metadata keys, including blank. Omitted/null values preserve the stored value.
price_bandsJSON textNoJSON text decoding to an array/object; invalid input is rejected rather than silently ignored.
amt_trigger / trigger_amt / trigger_emailLegacy threshold controlsNoTruthy amt_trigger text is stored directly. Fallback trigger_amt requires an actual PHP integer plus a truthy email, which ordinary form-string requests do not satisfy.
user_idInteger-compatibleNoPositive existing user receives amount as an allocation inside the same transaction; preserves the warehouse increment followed by allocation subtraction.
import_idInteger-compatibleNoAdds created_by_import_id on new rows and edited_by_import_id metadata on save.

Example request

$result = FM_api('Stock_add', ['name'=>'Valve', 'code'=>'VALVE-1', 'cost'=>'12.5', 'price'=>'20', 'amount'=>'0', 'manual_creation'=>'1']);

Example response

{
  "ok": 1,
  "id": 18
}

Application errors can use HTTP 200. Inspect error/warning fields; database numeric values can be strings unless this handler explicitly converts them.

Errors and unusual responses

ResponseCondition
{"error":"not logged in"}No authenticated tenant context is available. Invalid signed credentials can be rejected by the dispatcher before the handler runs.
{"error":"missing parameter: name"}name is absent/null.
{"error":"parameter too long. max length 80 characters: name"}Trimmed name exceeds 80 bytes.
{"error":"parameter too long: code"}Trimmed code exceeds 182 bytes.
{"error":"current settings require that stock code be unique"}Manual creation conflicts with unique-code mode.
{"error":"Error updating stock item"}No positive item ID was obtained.

Legacy application errors may be returned with HTTP 200. Check the decoded response for error, not only the HTTP status.

Behaviour and edge cases

  • Remains a code/name-matching upsert: duplicate-code setting and manual_creation=1 behavior are preserved. Legacy name/code limits remain byte-based. A missing explicit item or supplier now returns an error.
  • On matched/explicit existing items, omitted code,cost,price,archive and optional fields are preserved; explicit zero is a real overwrite. amount remains a signed warehouse increment. New optional fields retain their schema defaults when absent.
  • Supplier creation/link writes, metadata, category additions and an optional user allocation now commit with primary stock/history writes. Invalid suppliers or failed child writes roll back the entire save. Categories remain additive; the legacy import path ignores stale positive category IDs while direct membership/full mapped saves validate targets.
  • Native meta maps merge with existing metadata; present manufacturing strings can clear values. price_bands must decode to a JSON array/object. user_id allocation retains the former warehouse/container delta semantics and preserves allocation metadata.
  • Threshold mail is sent after commit only when the final warehouse balance crosses from at/above to below a nonzero threshold. Repeated saves while already below do not resend. Stock_new/Stock_edit run after commit.
  • Primary changes and stock history use a checked transaction. Failed validation/read/write/commit returns an error and rolls back open changes. Configured events/notices run after commit; a post-commit warning means the save succeeded and must not be repeated blindly.

Side effects

  • Transactional stock/supplier/link/category/allocation/history/cache changes, then configured events and threshold mail.

See it in Fieldmotion

CRM1

Open Stock in CRM1. The legacy grid is Stock_getDT and its editor/inline actions use legacy Stock routes. Inspect the exact function name in the browser Network panel. Save the New/Edit stock dialog. It sends manual_creation=1, JSON categories, legacy tax/cost names and manufacturing strings.

CRM2

Normal CRM2 stock layouts use Stock_createData/updateData instead. Stock imports and legacy integration/internal flows can still call Stock_add; do not substitute it for a mapped patch.

Related endpoints

  • Stock_createData — Create a catalogue record from CRM2 layout fields and synchronize category membership.
  • Stock_updateData — Update stock fields, category membership and picker values through the full mapped save.
  • Stock_get — Read the full saved stock row, with selected manufacturing metadata flattened for the legacy editor.
  • Stock_addToCategories — Update category membership and rebuild the stock item’s category mirror.