BOB Docs
APIApplication

Store

API

The application is available under the path: /api/store/* and is divided into the following parts:

  • Cart Management (cart_router.py): Manages cart operations such as adding, removing, and summarizing items.
  • Store Operations (store_router.py): Manages product display, orders, purchase workflows, and order archives.

Anonymous User Support

To enable shopping for both logged-in and anonymous users, the action of adding items to the cart sets a special cookie containing the anonymous user's ID. This ID is used to persist the cart across sessions.

@cart_router.post('add', auth=AuthorizedOrAnonymousUser(),
                  response={200: CartSummaryOut, 400: ApiExceptionOut},
                  tags=["store", "cart"])
async def add_to_cart(request, body: AddToCartIn, response: HttpResponse):
    """
    Allow to add products to cart.
    """
 
    cart = await store_interactor.add_to_cart(request.auth, body.pricing_id, body.quantity)
    if isinstance(request.auth, AnonymousUserBoB):
        response.set_cookie(
            key="ANONYMOUS_USER_EXTERNAL_ID",
            value=request.auth.id,
            httponly=False
        )
    return 200, cart

Note: Cookies are also set when creating billing information for anonymous users (via the billing router in the Payment App).


StoreInteractor

The StoreInteractor is the central business logic layer for the e-commerce functionalities of the store application. It facilitates seamless cart management, order processing, and payment handling for both anonymous and logged-in users.


Key Features

  • Cart Management:
  • Add, remove, and summarize cart contents.
  • Merge carts when transitioning from anonymous to logged-in users.
  • Order Processing:
  • Convert carts to orders, validate billing, and initiate payments.
  • Payment Handling:
  • Support both one-time and subscription payments.
  • Customer Management:
  • Manage customer records, associate customers with users or organizations, and validate billing data.
  • Anonymous User Transition:
  • Handle data merging from anonymous to logged-in users.

Methods

  1. Cart Management:
  • get_cart_summarized: Retrieve summarized cart data.
  • add_to_cart: Add products to the cart.
  • remove_line_from_cart: Remove items from the cart.
  1. Order Handling:
  • prepare_order: Convert a cart into an immutable order.
  • checkout: Validate billing, prepare an order, and initiate a payment session.
  • pay_for_order: Process payment for existing unpaid orders.
  1. Payment Processing:
  • _pay_for_order: Handle the payment process, including currency retrieval and checkout session initiation.
  1. Customer Management:
  • get_customers_for_user: Retrieve customers associated with a user.
  • get_customers_for_organization: Retrieve customers for an organization.
  • delete_customer: Remove a customer.
  • set_default_customer: Mark a customer as the default.
  1. Anonymous User Transition:
  • anonymous_to_user: Merge data from an anonymous user to a logged-in user.
  1. Order Retrieval:
  • get_user_orders: Fetch orders for logged-in and anonymous users.

Example Workflow

  1. Add a Product to Cart:
cart_summary = await store_interactor.add_to_cart(user, pricing_id=123, quantity=2)
  1. Checkout:
checkout_url = await store_interactor.checkout(user)
  1. Pay for an Order:
payment_url = await store_interactor.pay_for_order(user, order_id=456)

Dependencies

  • Services Used:
  • CustomerService: Manages customer records and associations.
  • CartService: Handles cart-related operations.
  • OrderService: Manages order creation and updates.
  • PaymentService: Initiates and manages payment sessions.
  • BillingService: Validates and manages billing information.
  • ProductService: Provides product and pricing data.

Commands

setupproducts

The setupproducts command automates the creation of initial products and their associated data, including pricing, images, and translations. It uses predefined configuration to streamline the setup process.

Key Features

  • Product Initialization: Automatically sets up products, pricing, and metadata based on ONE_OFF_PRODUCTS_AVAILABLE.
  • Currency Configuration: Uses the project's ISO_ALPHA_3_CURRENCY_CODE for pricing.
  • Batch Processing: Efficiently processes multiple products in a single execution.

Workflow

  1. Load Product Configuration:

    • Reads details from ONE_OFF_PRODUCTS_AVAILABLE.
  2. Create Products and Pricing:

    • Adds products and pricing models using ProductService.
  3. Attach Images:

    • Links product images from the configuration.
  4. Add Translations:

    • Provides multilingual support via ProductTranslation.
  5. Output Status:

    • Displays success or error messages for each step.

Configuration Example

ONE_OFF_PRODUCTS_AVAILABLE = [
    {
        "key": "product_1",
        "tax_code": "tax001",
        "pricing": [
            {"unit_amount": 1000, "interval": "ONE_OFF"},
        ],
        "images": [
            {"title": "Main Image", "image_path": "/path/to/image1.jpg"}
        ],
        "translation": {
            "en": {
                "name": "Product 1",
                "checkout_description": "Short description",
                "description": "Detailed product description",
                "statement_descriptor": "Statement Descriptor",
            }
        }
    },
]

Execution

Run the command using:

$ python manage.py setupproducts

Dependencies

  • Services:
  • ProductService: Manages product creation and operations.
  • Settings:
  • ONE_OFF_PRODUCTS_AVAILABLE: Predefined product data.
  • ISO_ALPHA_3_CURRENCY_CODE: Default currency for pricing.

Models

Cart

  • Represents a shopping cart for registered and anonymous users.
  • Fields:
  • external_id: Unique identifier for integrations.
  • order: Links to the Order upon checkout (optional).
  • User association: Supports ownership and efficient retrieval.

CartLine

  • Represents individual items in a cart.
  • Fields:
  • cart: Links to the parent cart.
  • pricing: Connects to product pricing.
  • quantity: Specifies item count.

Customer

  • Tracks customers for logged-in, anonymous, and organization-linked users.
  • Features:
  • Default customer designation.
  • Automatic creation for anonymous users on first interaction.

Order

  • Represents completed transactions.
  • Fields:
  • paid: Timestamp of payment.
  • details: Immutable JSON storing order information at purchase time.

OrderPaymentAttempt

  • Tracks payment attempts for an order.
  • Fields:
  • order: Links to the associated order.
  • status: Status of the payment attempt (e.g., Paid, Unpaid).
  • total, currency: Specifies the amount and currency.

Pricing

  • Defines pricing structures for products.
  • Fields:
  • unit_amount: Price in the smallest currency unit.
  • currency: Follows ISO 4217 standards.
  • interval: Specifies recurring or one-off pricing.

Product

  • Represents items available for purchase.
  • Fields:
  • key: Unique identifier.
  • tax_code: Ensures tax compliance.
  • shippable: Indicates if the product requires delivery.

ProductImage

  • Manages product images.
  • Features:
  • Supports thumbnail generation.
  • Prioritizes the image with the lowest order as the primary image.

ProductTranslation

  • Provides localized translations for products.
  • Fields:
  • name: Localized product name.
  • checkout_description: Brief description for checkout.
  • description: Detailed product description.
  • statement_descriptor: Bank statement descriptor.

TaxRate

  • Defines tax rates for products.
  • Fields:
  • percentage: Specifies the tax rate (e.g., 20 for 20%).
  • country_code: ISO country code for jurisdiction.
  • inclusive: Indicates if the tax is included in the price.

This streamlined setup process ensures a robust foundation for managing e-commerce operations, from product initialization to cart and order management.

On this page