Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

16.2 KB
Raw Blame

Store and Seller Policies

Status: Implemented — everything for 6.0 is in; the two Open Questions below are explicitly later releases Target: Spree 6.0 Depends on: 6.0-admin-api.md (Policies CRUD checklist; its body_html write contract is corrected here), 6.0-seller-onboarding-requirements.md (requirement kind pattern), 6.0-multi-vendor-marketplace.md (seller API branch), 6.0-rich-text-descriptions.md (sanitized HTML bodies) Author: Damian Legawiec Last updated: 2026-08-27

Summary

Spree::Policy (legal/policy documents: terms of service, privacy policy, returns policy, shipping policy, and any other document a merchant wants) already ships with a polymorphic owner, prefixed IDs, FriendlyId slugs, Mobility translations and sanitized HTML bodies, and is fully readable through the Store API, SDK and storefront. What is missing is every back-office surface: there is no Admin API CRUD, no dashboard page, and no way for a merchant to edit the four policies each store is seeded with. This plan ships that surface — and extends policy ownership to marketplace sellers: sellers manage their own policies in the seller panel, operators can require specific policies as part of seller onboarding (a new Spree::SellerRequirements::Policy kind), and a seller's policies are published on the Store API sellers surface so storefronts can show them on seller pages.

Key Decisions (do not deviate without discussion)

  • The Policy.for_store override is deleted; policies are always read through their owner association (2026-08-27). Today's override returns the store's policies plus every non-store-owned policy on the installation — a cross-tenant leak the moment any other owner type gets policies. Deleting it lets the generic Spree::Base.for_store resolve to store.policies automatically. This is a prerequisite for seller-owned policies, not a cleanup afterwards: with the override in place, the first seller-created policy would appear in GET /api/v3/store/policies for every store. All new code reads store.policies / seller.policies; nothing calls Policy.for_store by name.
  • Admin API manages store-owned policies only (2026-08-27). The admin CRUD scope is current_store.policies. Sellers manage their own policies through the seller branch; operators do not edit seller policies through the Admin API in 6.0.
  • Plain CRUD, no workflow (2026-08-27). Policy writes have no side effects, external I/O or hooks — per the service-workflows doctrine they stay controller-level CRUD.
  • Rich-text writes use the plain body attribute (2026-08-27, corrects 6.0-admin-api.md:294). Reads expose body (rendered as plain text) + body_html (sanitized markup); writes go to body, which Spree::RichTextSanitizer sanitizes on save. This is what Spree::SanitizableRichText actually documents and what every shipped rich-text controller does (Admin::CategoriesController permits :description, not :description_html); body_html is a read-only reader with no writer. The "writes accept body_html, plain body rejected 422" line in 6.0-admin-api.md was never implemented — following it here would have made policies the only model with an inverted contract.
  • updated_at joins the store policy serializer (2026-08-27). A deliberate, recorded exception to the no-timestamps rule for store serializers: when a legal document was last updated is customer-facing information, not operational leakage. created_at stays admin-only.
  • The policy set stays open — no kind enum, no fixed list (2026-08-27). The four seeded store policies remain name conventions. Merchants and sellers can create any number of policies. No position column either; listings order by name.
  • Sellers get no seeded policies (2026-08-27). Stores keep their four seeded defaults; a new seller starts with none. What a seller must provide is expressed by the Policy requirement kind, which also tells the seller panel what to prompt for. Marketplaces that require nothing get no clutter.
  • The Policy requirement kind asks for exactly one document per row (2026-08-27, revised the same day). allow_multiple? is true, so the base already requires a per-row name — and that name is the document required. A marketplace asking for two policies adds the kind twice, and the seller sees two separately-tracked lines, each going complete on its own. The first cut put a list of names in an array preference; that rendered as the generic comma-separated text box (a control the preferences form documents as being for "IDs or short tokens"), made progress all-or-nothing, and introduced a second vocabulary to keep in step with the row's own name. Not added to DEFAULT_KINDS — operators opt in.
  • Seller policies on the Store API load through ?expand=policies (2026-08-27). The store seller serializer embeds them behind the standard expand guard (if: proc { expand?('policies') }), the same convention products use for seller/variants/media. Clients opt in per request, so the sellers index stays light by default and a storefront seller page requests GET /store/sellers/:id?expand=policies — no separate endpoint, no index/show payload divergence.
  • Checkout consent capture and policy body templates are out of scope (2026-08-27). The storefront consent checkbox stays UI-only; persisting acceptance (timestamp + policy version) belongs with 5.4-6.0-eu-legal-compliance.md. Templates are a possible 6.1+ nicety.
  • Storefront policy links stay hardcoded for now (2026-08-27). The follow-up is a store/info-style endpoint whose store serializer embeds the policy list so storefront footers become dynamic — deferred, see Open Questions.

Design Details

Model changes

  • spree/core/app/models/spree/policy.rb: delete the self.for_store override (and its comment). Spree::Base.for_store then resolves store.policies via the existing Store has_many :policies, as: :owner. No writer to add — has_spree_rich_text :body already sanitizes plain-body writes and defines the body_html reader. Update policy_spec.rb — the context asserting the cross-owner leak is deleted; the two-store isolation example stays and now also excludes non-store owners.

  • spree/core/app/models/spree/seller.rb: add

    has_many :policies, class_name: 'Spree::Policy', dependent: :destroy, as: :owner
    

    matching the store's declaration. Spree::Policy is not paranoid, so a seller's soft delete hard-destroys its policies — same behavior the store association has today.

  • No migrations. The spree_policies schema already carries everything needed.

Admin API v3 (store policies)

  • Routes: resources :policies in the admin namespace — the five endpoints from the 6.0-admin-api.md checklist.
  • Admin::PoliciesController < Admin::ResourceController: model_class Spree::Policy, scope resolves to current_store.policies through the base for_store path, resource_permitted_attributes = [:name, :slug, :body]. Lookup by prefixed ID (pol_…).
  • Admin::PolicySerializer < V3::PolicySerializer adding created_at / updated_at.
  • Permissions: Spree::Policy is already registered under the settings resource group — read_settings / write_settings scopes and the matching catalog keys apply with no catalog change.
  • Destroy is a real destroy (no soft delete on the model); the seeded four can be deleted and recreated freely — they are conventions, not fixtures.

Store API v3

  • V3::PolicySerializer gains updated_at (typelized). No other store-facing change to the policies endpoints.

  • V3::SellerSerializer (store) gains the seller's policies behind the expand guard:

    many :policies,
         resource: proc { Spree.api.policy_serializer },
         if: proc { expand?('policies') }
    

    Requested with ?expand=policies (index or show); the store policy serializer renders each (id, name, slug, body, body_html, updated_at). Storefront seller pages read them from the seller payload; nothing embeds by default. Nested expansion composes for free: a product detail page fetches GET /store/products/:id?expand=seller.policies — the product serializer's existing expandable seller association passes the nested expand through, no additional code.

Seller API v3 (/api/v3/seller)

  • Routes: resources :policies in the seller namespace.
  • Seller::PoliciesController < Seller::ResourceController. The base controller already derives the scope from current_seller.policies (seller_association maps spree_policies → :policies), so the controller declares only model_class, serializer_class, permitted params (:name, :slug, :body) and slug-or-prefix lookup (copied from the store policies controller). scoped_resource :seller_profile — seller policies ride the existing seller-audience resource, matching the onboarding and requirement-submission controllers; they are part of the seller's own profile surface, and OSS has no per-member roles to differentiate.
  • Seller::PolicySerializer < V3::PolicySerializer adding created_at / updated_at (idiomatic seller-branch shape: extend the store serializer).
  • Register seller_policy_serializer in spree/api/lib/spree/api/dependencies.rb.

Spree::SellerRequirements::Policy

A computed-from-seller-data requirement kind (no submissions, no operator review):

module Spree
  module SellerRequirements
    class Policy < Spree::SellerRequirement
      # The row's name IS the document required.
      def self.allow_multiple?
        true
      end

      def met_by_seller?(seller)
        required = required_policy_name
        return true if required.blank?

        seller.policies.any? do |policy|
          policy.name.to_s.strip.casecmp?(required) && policy.with_body?
        end
      end

      def required_policy_name
        display_name.to_s.strip
      end
    end
  end
end
  • Registered in the engine's seller_requirements concat list; not in DEFAULT_KINDS.
  • i18n: seller_requirement_types.policy.{name,description} in en.yml.
  • The requirement status exposes required_policy_name (following the custom_fields extension-point pattern on SellerRequirementStatus), so the seller panel can offer to create exactly that document. The onboarding card needs no special rendering — each row is already its own line with its own name and status, which is the point of one-row-per-document.
  • The admin seller-requirements types-discovery endpoint picks the kind up automatically. The kind declares no preferences, so the operator's form is just the row's name and description — no custom editor needed.
  • Body presence is checked through the Mobility fallback reader in Ruby (seller policy sets are small); a body written only in a translation locale still counts. Both sides of the name comparison are trimmed at compare time, since the preference/attribute readers hand back whatever is stored.

Dashboard (admin)

  • New Settings → Policies page (/settings/policies): list (name, slug, updated date) + editor sheet or page with name, slug and body via MediaRichTextEditor (the wired description-field component). Delete goes through useConfirm with the policy name. No drag ordering (no position column).
  • admin-sdk: policies resource + generated AdminPolicy type.
  • Translations management arrives with 5.5-6.0-resource-translations-api.md (Policy is already in the translatable registry) — this page does not build its own translation UI.
  • New i18n keys land in every locale file (en/de/fr/zh-CN/ar/pl), dashboard and dashboard-core as appropriate.

Seller panel

  • New settings nav entry + page (/settings/policies) mirroring the admin page: list + editor. The body editor is the plain RichTextEditor from @spree/dashboard-ui — the media-enabled editor is admin-only and the media library is store-scoped, so seller policy bodies ship without image embedding in 6.0.
  • When the store has an active Policy requirement, the page surfaces the required-but-missing names and offers one-click creation pre-filled with the required name (this is what makes name matching reliable).
  • The onboarding page's requirement card for the policy kind lists the missing names and links to the policies page via action_url.
  • seller-sdk: policies resource group + generated Policy type.

Type generation / OpenAPI

Standard pipeline: typelizer → Zod → integration specs → swaggerize → SDK tests. New integration specs for admin and seller policies endpoints generate the OpenAPI examples; the store sellers spec regenerates with embedded policies.

Migration Path

No schema changes and no data migration. Sequencing inside the release:

  1. Core: delete the for_store override + leak spec; add Seller has_many :policies.
  2. Admin API CRUD + serializer + specs; store serializer updated_at.
  3. Seller API CRUD + serializer + specs; store seller serializer embeds policies on show.
  4. SellerRequirements::Policy kind + registration + i18n + status exposure.
  5. admin-sdk / seller-sdk resources + generated types; OpenAPI regeneration.
  6. Dashboard Settings → Policies page.
  7. Seller panel Settings → Policies page + onboarding card handling.

Step 1 must land before or with step 3 (the leak becomes real the moment a seller policy row exists).

Constraints on Current Work

  • Never call Policy.for_store or reintroduce an override of it — read policies through store.policies / seller.policies only. More generally, prefer the owner association over for_store for any owner-scoped model.
  • New policy-owning models declare has_many :policies, as: :owner and get their own controller on their own API branch; the Admin API policies controller stays store-scoped.
  • Do not add a kind enum, position column, or fixed policy vocabulary — the open set is the design.
  • Policy write endpoints permit the plain body attribute; body_html is read-only. Do not add *_html writers — SanitizableRichText sanitizes plain-attribute writes.
  • Acceptance records are 5.4-6.0-eu-legal-compliance.md scope and shipped 2026-09-02: Spree::ConsentRecord snapshots each policy's slug, name, locale and body digest at the moment of agreement, so editing a policy never rewrites the evidence of what someone accepted.
  • A serializer that inherits many :policies from the store seller serializer must rebind or drop it — an admin or seller response must never render a store serializer. Admin::SellerSerializer drops it (_attributes.delete(:policies)); Seller::ProfileSerializer rebinds it to the seller serializer. Both were caught only because the generated types disagreed with the OpenAPI schema.
  • A controller outside ResourceController gets no expand plumbing: an optional association on its serializer is unreachable unless the controller passes expand: itself (Seller::ProfileController#expand_list).
  • Requirement kinds that check seller content follow the Policy kind's shape: configuration in preferences, computation in met_by_seller?, structured "what's missing" exposure through the status object — never a new column on spree_sellers.

Open Questions

  • Dynamic storefront policy links. The storefront hardcodes the four seeded slugs. The intended fix is a store/info-style endpoint whose serializer embeds the policy list (id, name, slug) so footers and consent links become data-driven. Deferred until the store-info endpoint is designed; unblocked by deciding that endpoint's shape.
  • Operator visibility into seller policies. 6.0 ships no admin read of a seller's policies. If moderation needs arise (a seller publishing abusive content in a policy body), an admin read-only nested index (/admin/sellers/:id/policies) is the likely shape. Unblocked by a real moderation requirement.

References

  • docs/plans/6.0-admin-api.md — Policies CRUD checklist (its body_html write-contract line is corrected by this plan)
  • docs/plans/6.0-rich-text-descriptions.md — sanitized rich text; Policy already migrated off ActionText
  • docs/plans/6.0-seller-onboarding-requirements.md — requirement kind pattern, evaluation, status objects
  • docs/plans/6.0-multi-vendor-marketplace.md — seller principal + /api/v3/seller branch conventions
  • docs/plans/5.5-6.0-resource-translations-api.md — future policy translation management
  • docs/plans/5.4-6.0-eu-legal-compliance.md — home of any future consent-capture work