Hooks and registry reference¶
Everything the core offers an extension to plug into. Anything not on this page is internal and can change in any release. The lint refuses any top-level name in an extension's hooks.py that is not a Frappe metadata key, an allowed Frappe hook (Rules) or a gunshop_* hook below.
The Python SDK¶
ffl_core.extensions (present since core 0.1.0):
import frappe
from ffl_core.extensions import extension_hook, require_enabled, is_enabled
from ffl_core.roles import COUNTER_ROLES
APP = "acme_layaway"
@extension_hook(APP) # not effective: returns None without running
def on_sales_invoice_submit(doc, method=None):
...
@frappe.whitelist(methods=["POST"])
def start_plan(customer: str, item: str):
"""Start a layaway plan.
Args:
customer: Customer name.
item: Item code.
Returns:
dict: {"plan": name}
"""
require_enabled(APP, roles=COUNTER_ROLES) # first executable statement
...
| Function | Behaviour |
|---|---|
extension_hook(app) |
Decorator for doc_events and scheduler_events handlers. While the extension is not effective the wrapper returns None and the function does not run. |
require_enabled(app, *, roles=None) |
Raises frappe.PermissionError when the extension is not effective, or when the user holds none of roles. Must be the first executable statement of every endpoint; the gate audit counts it only with roles=. |
is_enabled(app) |
True when effective. For templates and branches; never instead of require_enabled. One cache read. |
title_of(app) |
The extension's title from the registry. |
clear_enabled_cache() |
Drops the desk boot cache. Call it in tests after writing the row (frappe.db.set_value("POS Extension", APP, "enabled", 0)). |
Roles: ffl_core.roles.COUNTER_ROLES, STOCK_ROLES, SYSTEM_ROLES, or your own role.
Boot: frappe.boot.gunshop_extensions[id] = {enabled, version, title} for every extension installed on the site; enabled is the effective state.
The stable surface¶
Besides the hooks on this page, an extension may call: ffl_core.extensions.*, ffl_core.roles.*, ffl_core.workspace_shortcuts.ensure_shortcut / remove_shortcut, ffl_core.setup.sidebar.mirror_gun_shop_sidebar, ffl_core.utils.single_flag, ffl_core.agreements.require_agreement, ffl_core.signing_terminal.deliver_page / terminal_for_secret / active_terminals (send a paired signing tablet to a page of your own, and check its device key there), ffl_core.ffl_core.doctype.mcp_settings.mcp_settings.SURFACES / surface_enabled (the POS's own MCP surfaces, cpa and full, and whether one is switched on; the website surface is never in SURFACES), the endpoints in the API reference, ffl_integrations.distributor.base.DistributorProvider, ffl_integrations.distributor.freight.estimate_orders, ffl_integrations.payments.base (CardProcessor, CardResult, CardProcessorError), customer memory's ffl_core.crm.sensitive.memory_problems / redact and ffl_core.crm.memory.refresh_layout / queue_recent(days=30, limit=100) (mark the open leads and deals with recent customer mail for an update, once per site) / batch_for(doc) and apply(doc, memory_for(doc, write=True), batch, answer) (what gunshop_crm_memory_update is given for a record, and writing an answer to it: for your tests), and the ffl_core.pricing functions below. Everything else is internal.
counter_list_price(item_code) -> float: the Item-level list price the register charges today: the selling Item Price of the default price list, except a uniform-priced firearm model in stock, priced from its cheapest priced gun; 0.0 for a gun priced one by one.counter_price_for(item_code, serial_no=None) -> float: a quote line's price: a gun priced one by one from that serial (refused unless it is an in-stock serial of the Item), or the cheapest one in stock without a serial; anything elsecounter_list_price.price_readonly_reason(item_code) -> str | None: why the regular price cannot be changed outside the POS (a gun priced one by one, a sale running today, a drop-ship listing, the transfer fee), translated for staff; None when it can.set_regular_price(item_code, price) -> None: a price approver (roles.PRICE_APPROVER_ROLES) sets the regular price; saves the Item (validate, website pushes, the Version trail) and the selling Item Price, and notes the old and new register price on the Item. RaisesPermissionErrorfor anyone else andValidationErrorwhileprice_readonly_reasonanswers or when the price is not above 0.
Member prices, ffl_core.membership_benefits (a Membership Plan's Benefits; the register prices every line with them on save):
member_price(customer, item_code, qty=1, on_date=None, *, exclude_invoice=None) -> dict: what customer (the member who uses the benefit, not necessarily the payer) pays for qty stock units on on_date (store-local day, default today). Returns{"list_rate", "rate", "benefit", "membership", "reason", "uses_left", "notice"}. With no benefit (not a member that day, item not covered, too few uses left, a sale price already lower)rate == list_rateandbenefitis None.uses_left: the benefit's uses left that day before this line, None without a limit.notice: why a member price was not given (no uses left, naming the member's sales that took them, drafts marked not completed), else None.exclude_invoice: a POS Invoice / Sales Invoice whose own lines must not count as used (the ticket you are pricing again).benefit_usage(customer, benefit, on_date=None) -> dict:{"limit", "used", "left"}for a benefit (member_price'sbenefit);limit0 andleftNone mean no limit. Uses count stock units (qty × conversion factor) on lines carrying the benefit for that member that day, drafts included; a line returned in full gives its uses back.membership_badge(customer) -> dict | None:{"text": "Premium · to 2027-04 · Range 1/2 today", "memberships": [{"membership", "plan", "status", "until", "uses": [{"benefit", "label", "used", "limit"}]}]}for a customer with a membership giving benefits today (Active, or Past Due within its grace), else None. The counter's customer panel showstext.
Build a ticket with ffl_core.api.pos_ticket.build_ticket(customer, items, company=None) (Python, same answer as open_ticket) to price a line for someone other than the payer: a line may carry benefit_customer, the member whose benefits price it (a guest checked in at your counter). The API endpoint open_ticket ignores that key. On either, a member price lower than the line's rate replaces it, and a rate you send below the member price stays without the benefit (the better of the two, never both).
Named hooks¶
Declare them in hooks.py like any Frappe hook. The value is a dotted path to a function unless the entry says otherwise. The core calls every provider inside try/except; On failure says what it assumes then (logged to Error Log unless stated). Contract tests: ffl_core/tests/test_extension_hooks.py.
gunshop_counter_holds¶
- Signature:
(item_code) -> [{serial, source, ref, kind, tooltip, url}] - Purpose: serials of that Item the extension holds for something not yet disposed (a draft outbound consignment, a layaway). Merged into
ffl_core.reservations.counter_holdsafter the counter's own sources, and enforced wherever holds are (POS picker, web stock, a second consignment). - On failure: contributes nothing.
gunshop_required_agreements¶
- Signature:
(sales_doc) -> [template, …] - Purpose: Agreement Templates the customer of this POS / Sales Invoice must have signed before submit, on top of the Items' own. Checked in
before_submit; never on a return, a POS consolidation invoice or a web / GunBroker sale. Switched-off templates are dropped. For a signature on your own record, callffl_core.agreements.require_agreement(customer, template)in your ownvalidate(raisesAgreementRequired). - On failure: contributes nothing; the sale goes on.
gunshop_firearm_transfer_refusal¶
- Signature:
(sales_doc) -> str | None. Wrap it in@extension_hook. - Purpose: the reason this firearm sale must not be submitted yet, or
None. Asked at submit of a POS / Sales Invoice with a regulated firearm, after the core's own gate has passed (4473 Completed, NICS Proceed, a committed disposition per serial); never for a draft, a sale to an FFL dealer, a shipment to a destination FFL or a consolidation invoice. The first reason stops the submit and is shown to staff as it is, so say what to do next. - On failure: logged; counts as no objection, so the sale goes on.
gunshop_4473_record_checks¶
- Signature:
(logs) -> {log name: {"label": str, "indicator": "green" | "orange" | "red" | "gray", "route": str | None}}.logsis a list of{"name", "pos_invoices": [str], "source": "FastBound" | "Paper / override"}, the Form 4473 Log rows the report is about to show. Leave out a record you have nothing to say about. - Purpose: the Check column of Compliance → 4473 Records: where your own check of that signed 4473 stands.
labelis shown as an indicator pill (40 characters at most);route(a path under/app/or/desk/) makes it a link to your page for that record, for example to run the check again. The column shows only when a provider answers for a listed record. Called on every run of the report for all its rows: one query, no network call. The first provider to answer for a record wins. - On failure: logged; the column stays blank for that provider.
gunshop_pending_queue_exclusion_fields¶
- Value: a fieldname (string): a Sales Invoice Link custom field you own.
- Purpose: invoices with it set are fulfilled on your record: they stay out of the Pending Order queue, the counter-hold registry and the counter-order marker, and the core does not auto-book their dealer-transfer dispositions. Tax, receipt and Sales Report rules still apply. A site without the column ignores the entry.
gunshop_disposition_stock_handled¶
- Signature:
(ffl_disposition_doc) -> bool - Purpose:
True= the extension already moved this gun's stock; the core must not Material-Issue it on submit. - On failure: treated as
True(a second stock move is the worse error).
gunshop_website_user_home_page¶
- Signature:
(user) -> route | None, for a signed-in Website User only. - Purpose: first non-None answer is the home page. Answer a Website route even while switched off (
ffl_core.WEBSITE_USER_FALLBACK_HOME_PAGE):Nonesends the user to the Desk, which a Website User cannot open. - On failure: skipped.
gunshop_woo_product_meta¶
- Signature:
(doctype, name) -> {meta_key: value};doctypeis"Item"or"Serial No". - Purpose: appended to the WooCommerce product's
meta_dataon every full push. Keys match^_[a-z0-9_]{2,60}$; a key the core emits wins. Declare permissionwoo_product_meta, and pair withgunshop_woo_product_meta_keysandgunshop_woo_push_fields. - On failure: skipped; the listing publishes without your values.
gunshop_woo_product_meta_keys¶
- Value: a meta key (string).
- Purpose: declares a key
gunshop_woo_product_metamay write, so it survives a lean push (pos_fields_only=True, which drops everything not POS-owned). Emitted but undeclared = lost on the next lean push.
gunshop_woo_push_fields¶
- Value:
{"Item": [fieldname, …], "Serial No": [fieldname, …]} - Purpose: custom fields whose change queues a (lean) WooCommerce push, like the core's price and status fields. List every field your
gunshop_woo_product_metaprovider reads. Fires while switched off too (hooks are static); your provider then contributes nothing.
gunshop_extension_toggled¶
- Signature:
(app, effective: bool) - Purpose: once per change of the effective state of
appwhile installed (switch flip, or a compatibility change after a core update); not on install or uninstall. Every provider is called, including the extension that just stopped: do not wrap it in@extension_hook. Use it for workspace shortcuts. - On failure: logged; the change is already saved.
gunshop_sidebar_items¶
- Value: a list of
Sidebar Itemdicts (type,label,link_type,link_to,icon,child,indent,collapsible,keep_closed, …); normally aSection Breakfirst and its links withchild: 1. ASection Breakwhose label is a shipped section's (Compliance,Inventory, …) adds nothing: its links go to the end of that section. - Purpose: while effective, the core writes the rows into the Gun Shop sidebar's site layer (
Custom Sidebar) before Settings, and removes them when off or uninstalled (rebuilt on toggle, install, uninstall and every migrate). Modules that mirror the Gun Shop sidebar get the same layer. - On failure: rows skipped; no section for the extension.
gunshop_dropship_listing¶
- Signature:
(item_code, distributor | None, fields: tuple) -> dict | None - Purpose: the Item's website drop-ship listing at that distributor (any house when
None), as a dict offields; read by the counter's quote, fulfilment matrix and drop-ship routing. First non-None wins. Its presence (from an effective extension) also switches on the Catalog Service / Drop-ship Center buttons. - On failure: raises into the caller (never a silent "not listed").
gunshop_dropship_suggested_price¶
- Signature:
(distributor_doc, catalog_row, listing) -> number | None - Purpose: the counter's suggested price for a catalog product under drop-ship pricing. First non-None wins; without a provider: MAP, else MSRP, else cost.
- On failure: raises into the quote.
gunshop_distributor_source_settled¶
- Signature:
(source_doctype, source_name) - Purpose: every distributor order of a non-counter source (a web order) has settled; complete the source. Enqueue after commit: the call can come from inside the last order's save. Every provider is called.
- On failure: raises into that distributor order's save (it rolls back).
gunshop_distributor_feed_stale¶
- Signature:
(distributor, *, aged: bool) -> bool - Purpose: a distributor's quantity feed is stale (
aged: it had a heartbeat and aged out; a cold start is not). Zero what you publish from it only whenaged; returnTruewhen your zero-stock interlock is on. - On failure: raises into the watchdog run.
gunshop_distributor_hub_rows¶
- Signature:
(rows); onefrappe._dictper house, edited in place. - Purpose: add display columns to the Distributors hub.
- On failure: the column stays blank.
gunshop_ai_connected¶
- Signature:
() -> bool, no network call (read at every desk boot). Wrap it in@extension_hook. - Purpose: any truthy answer makes
ffl_integrations.data_service.capabilities()["ai"]"connected"(frappe.boot.ffl_capabilities.ai). - On failure: not connected; logged at most once an hour.
gunshop_card_processors¶
- Signature:
() -> CardProcessor(anffl_integrations.payments.base.CardProcessor). - Purpose: one card gateway: start / poll / cancel a charge on the device, void, refund, list terminals, a read-only probe for Settings → Payments, answering
CardResultand raisingCardProcessorErrorwith an honestoutcome_known. The core keeps every money fact (charge rows, refund locks, the split across cards, terminal payments and their Payment Entries); the adapter writes no document. At most one processor may be on and configured (ready()); each charge row records the processor'scode, and void / refund / poll go back to that processor. Optional card on file:supports_card_on_file = True, acceptsave_cardinstart_charge, answer the token inCardResult.stored_credential(+card_expiry, MMYY), implementcharge_stored,find_stored_charge(order_reference),delete_stored(merchant_reference)andorder_reference(document, attempt). Never put the token inraw. Optional card readers: give the settings Single acard_readerstable (child doctype Card Reader: name, device serial number, enabled) and acceptdevice(that serial number) instart_charge; the core passes it only when the store lists readers, and the handlestart_chargereturns must poll / cancel the charge on whichever device took it. - On failure: that processor counts as not installed: no new charges; a refund of its charge waits for a manager's Confirm Portal Refund.
gunshop_crm_mail_screen¶
- Signature:
(mail: dict) -> {"customer": bool, "reason": str, "category": str} | None.mailis{"communication": name, "sender": address, "sender_name": str, "to": [addresses], "subject": str, "body": plain text, 4000 characters at most, "team_address": the team address it came to}. - Purpose: judge mail to a team address (Lead Mail Settings) from someone with no lead and no customer contact yet. With at least one provider registered, such mail does not become a lead while it is pulled: a short background job asks the providers first. The first
customer: Falsemakes it other mail: a lead with the status Other mail and the answer's category, with a Comment "Not a customer inquiry (category): reason" on the mail;Noneis no opinion. Any other outcome makes an ordinary lead and shares it as without the hook. The job checks again before it asks: if the mail was linked or the sender has become a lead or a customer, the mail goes by the normal rules and no provider is asked. Later mail from that sender goes on the same lead and is not screened. Category rules, blocked domains, automated senders, known customers and known leads run before this and are not screened. With Lead Mail Settings › Spam folder set, the same providers also judge that folder's mail before anything is stored (communicationis empty):category: "spam"leaves no record,Nonetries the mail again on the next run. Blocking network calls are fine (background job); wrap in@extension_hook. - On failure: logged; counts as no opinion, so the lead is made.
gunshop_crm_reply_draft_ready¶
- Signature:
() -> bool, no network call (asked on every Lead and Deal page load). Wrap it in@extension_hook. - Purpose: any truthy answer shows Draft reply on CRM Lead and Deal pages (
ffl_core.crm.reply_draft). - On failure: logged; counts as not ready.
gunshop_crm_reply_draft¶
- Signature:
(context: dict) -> {"body": str, "handoff": str | None, "refs": [str]} | {"refused": str} | None.contextis{"channel": "email" or "gunbroker", "store_name", "latest": {"subject", "body" (plain text, 4000 characters at most), "at"}, "thread": [{"direction": "in" or "out", "at", "body"}] (the five other newest messages, newest first, 1500 characters each and 8000 in all), "customer": {"first_name", "state" (two letters or empty), "is_customer"}, "memory": {"summary": str, "items": [{"kind", "text", "amount", "said": "customer" | "staff" | "order", "on": "YYYY-MM-DD"}]}, "facts": [fact], "find_stock": callable}.memoryis what the customer's memory holds (gunshop_crm_memory_update): the record's summary and its rows, throughffl_core.crm.sensitive.redact; acustomerrow is what the customer said, unchecked, astaffrow what an employee wrote; empty when there is none. A fact is{"ref", "name", "brand", "model", "caliber", "condition": "new" or "used", "price" (the register's today), "sale_price", "sale_ends", "available", "units": [{"ref", "price"}]}, 12 at most: the record's product lines, what its open wants fit in stock, then what the memory's wants fit (nearest the memory's budget first).find_stock(wants)takes[{"keywords": str, "budget": float | None}], finds Items in stock by the want list's keyword rule, adds them to the facts (still 12 at most) and returns the new facts. No serial number, ID, address beyond the state, phone, email address or internal note is in the context. - Purpose: write the plain-text reply to
latestwhen an employee clicks Draft reply, and, with Lead Mail Settings › Draft replies as mail arrives on, from a background job a few minutes after a customer's message arrives on a lead or deal (ffl_core.crm.arrival_draft; the same context, built as Administrator). That draft is stored on the record and given to an employee instead of a new one only while it answers the message they reply to and the context their own click would build is the same, facts with today's price and stock included (the onesfind_stockadded too); otherwise the hook is asked again. In the background a refusal, a deferral ({"deferred": …}counts as no answer here), no answer, or abodyorhandoffwith somethingffl_core.crm.sensitiveblanks stores nothing, and the record is not asked about again until the next customer message. The core turnsbodyinto paragraphs and puts it in CRM's composer above the quoted mail, or in a dialog with Send; the employee edits and sends it, nothing is sent by the hook.handoffshows as "Needs a person: …".refusedis shown to the employee as written (for example a spending limit);Noneis no answer. Providers are asked in turn and the firstbodyorrefusedwins. Blocking network calls are fine (the employee is waiting); keep your own timeout. - On failure: logged; counts as
None. With no answer the employee sees "Couldn't write a draft. Reply as usual."
gunshop_crm_memory_ready¶
- Signature:
() -> bool, no network call (asked on every Lead and Deal page load, and for every customer mail filed). Wrap it in@extension_hook. - Purpose: any truthy answer turns customer memory on (
ffl_core.crm.memory): a customer's mail filed on a lead or deal, a website inquiry and a deal turning Won mark the record due, and every five minutes the records quiet for three minutes are updated throughgunshop_crm_memory_update. When your answer changes (a store switches memory on or off), callffl_core.crm.memory.refresh_layout(): the Memory section of the Lead and Deal side panels is there while memory is on or anything is kept. A record shows its card, with Edit memory and Clear memory in the "…" menu, while memory is on or it has something kept; Update memory (a manual update) only while memory is on. With no provider nothing is marked and the memory fields stay empty. - On failure: logged; counts as off.
gunshop_crm_memory_update¶
- Signature:
(context: dict) -> answer | {"refused": str} | {"deferred": str | None} | None.contextis{"trigger": "mail" | "won" | "manual", "store_name", "record": {"type": "lead" | "deal", "stage", "closed": None | "won" | "lost", "sell_request": bool, "products": [str], "wants": [str]}, "summary": str, "memory": [row], "new": [message], "thread": [{"direction": "in" | "out", "at", "body"}], "bought": None | {"ref": "O1", "lines": [{"name", "qty"}]}}. A row is{"ref": "M1", "kind", "text", "keywords", "amount", "said": "customer" | "staff" | "order", "on": "YYYY-MM-DD", "locked": bool}; a message is{"ref": "E1", "kind": "mail" | "inquiry", "at", "subject" (500 characters at most), "body" (plain text, 2000 at most)}, the five oldest unread at most, oldest first (a longer backlog is read five at a time, one sweep apart);threadis the four messages before the first new one, newest first, 1000 characters each.kindis one ofwant,budget,state,trade_in,preference,question. Every subject and body has been throughffl_core.crm.sensitive.redact: ID, card and background-check numbers and dates of birth are[removed], and so is each sentence about something that can bar a purchase. No price, stock, name, phone, email address or internal note is in the context. Refs are valid for this call only. - Answer:
{"add": [{"kind", "text", "keywords", "amount", "source": "E1"}], "update": [{"ref": "M2", "text", "keywords", "amount", "source": "E2"}], "remove": ["M3"], "summary": str | None}. Every add and update names the new message it comes from;nullfields in an update keep the row's value;summary(one or two sentences, 300 characters at most)Nonekeeps the current one. A want needskeywords(words every one of which must appear in a matching product); a budget goes inamountonly; a state is a US state. The core drops, entry by entry, anything that breaks a rule: a ref that is not a row or is a locked one (staff wrote it), a source that is not a new message, ID numbers, eligibility details, prices or stock in the text, a legal question.ffl_core.crm.sensitive.memory_problems(answer, context)returns those problems ([{"part", "index", "problem"}]) so you can ask your model again before answering. - Purpose: keep the customer's memory and the record's summary. The core builds the context, checks the answer and writes it; a provider writes nothing itself. Called from a background job (from the employee's request for a manual update): blocking network calls are fine, keep your own timeout. Providers are asked in turn and the first dict wins.
refusedis shown to the employee on a manual update (for example a spending limit); in the background it skips the batch, which is not asked about again (an answer your model cannot give).{"deferred": when}says you cannot answer before when for a passing reason, such as a daily spending limit that resets at midnight: when is a site-time datetime string, orNonefor the next site midnight; the record is due again then (two days at most), and the wait does not count toward the six hours below. On a manual update a deferral is no answer. AnswerNonefor a short failure (the network, the model's service), which is retried an hour later. - On failure: logged; counts as
None. With no answer, or one the core could not write, the record is tried again an hour later; six hours after the first failure the batch is skipped.
gunshop_serial_hold_changed¶
- Signature:
(serial_no) -> None - Purpose: a gun was held for a CRM deal, or its hold was extended or ended (
ffl_core.crm.holds). Re-read the gun's state (ffl_core.reservations.serial_shelf_state) and update what you publish; a held gun is a counter hold of kindcrm_deal. Called inside the hold's transaction: enqueue after commit, no network call here.ffl_woo_syncregisters the website's listing reconcile. - On failure: logged; the hold stands.
gunshop_deal_hold_refusal¶
- Signature:
(serial_no) -> str | None - Purpose: the reason this gun must not be held for a CRM deal (it is on sale where your app sells it), or
None. The first reason refuses the hold and is shown to staff as it is. Asked before the hold is written, under the gun's lock: read your own records, no network call.ffl_integrationsrefuses a gun listed on GunBroker. - On failure: the hold is refused ("Couldn't check the other sales channels").
gunshop_catalog_change_cursors¶
- Value:
"DocType.field"(string): a product change-feed cursor on one of your Singles. - Purpose: while any registered cursor holds a value, Data Service Settings refuses to change Catalog source. Moving from a Local catalog to a Data Service clears every registered cursor directly in
tabSingles, so a blank cursor must mean "start over". A malformed entry is skipped.
Core-integration only: gunshop_extension_updates¶
Not declarable by an extension: it is not on the lint's whitelist, so an extension that declares it fails the lint ("not on the whitelist"). Only the core apps register it; ffl_integrations registers the Data Service's /v1/extensions source.
- Signature:
() -> source | None;source.latest() -> {ext_id: {version, sha256, size, requires_core}},source.fetch(ext_id, version) -> bytes, optional attributepublisher_id. - Purpose: feeds Update to {version} on the Extensions page. The first non-None source is used;
ffl_core.extensions.updates.checkruns daily and on Refresh.fetch_updaterefuses bytes whose sha256 differs fromlatest's, a package from another publisher, or one whoserequires_corethis core does not meet, then hands it to the upload pipeline. - On failure:
source: next provider;latest: rows keep their last answer;fetch: the page says the download failed.
First-party only¶
Declarable only by an extension whose manifest has first_party (lint). They decide what the website sells and at what price, or let an app answer another app's endpoints or authenticate requests.
| Hook | Signature | Without a provider / on failure |
|---|---|---|
distributor_stock_source |
(item_code) -> int \| None: website quantity of a drop-ship listed product; first non-None wins |
the store's own stock |
distributor_stock_batch |
(item_codes: list) -> context manager \| None: held open around the WooCommerce reconcile's Pass 1 so distributor_stock_source can batch reads; must not change answers |
logged, pass runs unbatched |
dropship_source_for_item |
(item_code, *, lead=True) -> {distributor, sku, fulfillment_mode, lead_days} \| None |
the store ships it (lane local) |
distributor_web_price |
(item_code) -> float \| None: website price |
Item.standard_rate |
map_mode_for_item |
(item_code, brand) -> str; the answer Always show in cart also rides an Item with no MAP (empty _osa_map_price), so the storefront hides its price |
MAP is minimum price |
distributor_listing_push_failed |
(item_code, site, error) |
logged |
woo_order_cancelled |
(woo_online_order_name) |
logged; the order stays cancelled |
override_whitelisted_methods |
Frappe's hook, {old path: new path}: only to keep an endpoint that moved from the core into the extension answering at its old path |
— |
auth_hooks |
Frappe's hook: authenticates a request | — |
The JavaScript registry¶
The bundle registers once; the core decides where things render, orders them, de-duplicates them and hides them while the extension is not effective.
// public/js/acme_layaway.bundle.js
gunstore.extensions.register('acme_layaway', {
posActions: [{
id: 'acme-layaway-start',
label: __('Layaway'),
icon: 'calendar',
condition: (ctx) => ctx.invoice && ctx.invoice.customer && !ctx.invoice.is_return,
onClick: (ctx) => gunstore.ext.acme_layaway.openDialog(ctx),
}],
serialActions: [{ id, label, onClick({ frm }) }],
customerActions: [{ id, label, onClick({ frm }) }],
pendingOrderActions: [{ id, label, stages: ['to_place'], condition: ({ row }) => row.source === 'woo', onClick({ row, reload }) }],
settingsLinks: [{ label: __('Layaway'), doctype: 'Acme Layaway Settings' }],
onDeskReady() { /* once per page load */ },
});
| Entry | Renders | Notes |
|---|---|---|
posActions |
Sale-screen buttons, after the core's | condition(ctx) synchronous and O(1); ctx is a read-only snapshot (invoice, customer, selected serial, POS Profile). |
serialActions |
Serial No form, Extensions group | onClick({ frm }) |
customerActions |
Customer form, Extensions group | onClick({ frm }) |
pendingOrderActions |
Pending Order cards, first among the card's buttons | row is the queue row as the server sent it (source is sales_invoice, woo or gunbroker; stage is the card's section). condition({ row }) synchronous and O(1). stages lists the sections where the button is the card's primary one. Call reload() after changing the order. |
settingsLinks |
Settings on the extension's card | One per Settings Single. |
onDeskReady() |
— | Once after the desk is ready, per effective extension. A throw is logged to the console and does not stop the others. |
Send a ticket to the register from your own page. Build the draft on the server with ffl_core.api.pos_ticket.build_ticket (the caller's open shift; your rates are the ticket's and are not asked for a manager's approval — the HTTP endpoint open_ticket judges a caller's typed rates like the register does), then:
frappe.route_options = { ffl_pos_invoice: name }; // the draft POS Invoice
frappe.set_route('point-of-sale');
The register opens it in the cart the way Recent Orders › Draft does (a sale already in the cart is parked first, after asking); the clerk adds lines and takes payment as usual. A name that is not an open draft is refused with a notice.
A rate you put on the ticket is your code's price (unless the line's member price is lower): the register does not ask a manager to approve it afterwards. When a person chose a price below list on your page, take the manager's approval in your own flow before you build the ticket.
Also available: gunstore.extensions.isEnabled(id, boot), ffl.featureOffPage(page, featureTitle, whereToTurnOn) for your own Desk pages, gunstore.renderReleaseNotes(entries).
Shared front-end helpers¶
Loaded on every Desk page (app_include_js). Read them through window.ffl and fall back when absent, as a core older than your extension may not have them.
ffl.aamva.parse(raw, { ids }): reads the text a license scanner typed (the PDF417 barcode on a US driver license or ID card). Returnsnullwhen the text is not a license, else{first, middle, last, suffix, address1, address2, city, state, zip, country}, with{idNumber, dob, expiry}(datesYYYY-MM-DD,''when unreadable) added only whenidsis true. Passids: !!frappe.boot.ffl_store_customer_id_numbers, the store's choice to keep ID numbers.ffl.customerFlags.check(customer, { key }): the counter's customer check, as the register runs it. ReturnsPromise<boolean>:falsewhen the customer is Banned and no manager overrode it in the box shown; otherwisetrue, after showing the customer's active alerts once perkey. An empty customer or a failed read resolvestrue(the server still refuses a sale to a Banned customer).ffl.customerQuickEntry.newFromScan(raw): opens the New Customer dialog for an individual, filled from that scan by the dialog's own Scan ID (name and address; the license number and birth date only while the store keeps ID numbers). ReturnsPromise<string | null>: the customer's name once the clerk saves it, or picks an existing customer at the duplicate check;nullwhen the dialog is closed without one, when the clerk moves to Edit in full page, or when the site opens the full Customer form instead of the dialog. Called again before it has answered, it returns the same promise and fills that same dialog from the new scan (from the newest one, if the dialog is still loading).
Desk pages, sidebar, shortcuts¶
- List your pages in the Gun Shop sidebar and the Dashboard's All records with
gunshop_sidebar_items. - To give your module's pages the Gun Shop sidebar, call
ffl_core.setup.sidebar.mirror_gun_shop_sidebar(<name>, module=<module>, extra_items=[...])fromafter_install/after_migrate. Frappe lets it write a sidebar only during install, migrate, a patch or developer mode. - Declare
add_to_apps_screenwith ahas_permissionthat returnsFalse, so the extension does not appear as a separate app. ffl_core.workspace_shortcuts.ensure_shortcut(label, link_to, *, anchor, block_id, color="Blue", shortcut_type="DocType", workspace="Settings")/remove_shortcut(label, *, workspace="Settings");shortcut_typeisDocType,Page,ReportorURL. Call them fromgunshop_extension_toggled.