ecommerce

python
from __future__ import annotations

from dataclasses import dataclass, field
from decimal import Decimal, ROUND_HALF_UP
from typing import Optional, Protocol

Composable Order Discount Pipeline With Rule Objects in Python

pipeline strategy-pattern discounts
by codesnips 3 tabs
ruby
class DiscountCode < ApplicationRecord
  has_many :redemptions, dependent: :destroy

  enum discount_type: { percentage: 0, fixed: 1 }

  validates :code, presence: true, uniqueness: { case_sensitive: false }

Redeem Discount Codes in Rails with a Locking Service and Row-Level Guards

rails activerecord discounts
by codesnips 4 tabs
ruby
class Cart < ApplicationRecord
  has_many :cart_items, dependent: :destroy

  EXPIRY_WINDOW = 2.hours

  scope :active, -> { where(state: :active) }

Expire Stale Shopping Carts With a Rails Scope and a Recurring Reaper Job

rails activerecord background-jobs
by codesnips 3 tabs
php
<?php

namespace App\Orders;

enum OrderStatus: string
{

Multi-Step Checkout Order State Machine in Laravel

laravel state-machine checkout
by codesnips 3 tabs
php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

Apply and Validate Coupon Codes with a Cart Totals Service in Laravel

laravel eloquent service-layer
by codesnips 4 tabs
php
<?php

namespace App\Observers;

use App\Models\Product;
use App\Jobs\WarmRelatedProductsCache;

Warm a Related-Products Cache with a Queued Laravel Job on Inventory Change

laravel php caching
by codesnips 3 tabs
javascript
import { useState, useEffect, useCallback } from 'react';

export function useLocalStorage(key, initialValue) {
  const readValue = useCallback(() => {
    if (typeof window === 'undefined') return initialValue;
    try {

Persist a React Shopping Cart to localStorage with a Context Provider

javascript react context
by codesnips 3 tabs
ruby
require 'sinatra/base'
require_relative 'cart'
require_relative 'cart_helpers'

class StoreApp < Sinatra::Base
  enable :sessions

Session-Backed Shopping Cart with Sinatra Helpers and a Cart Value Object

sinatra sessions shopping-cart
by codesnips 3 tabs
ruby
class Cart < ApplicationRecord
  belongs_to :user, optional: true
  has_many :cart_items, dependent: :destroy

  scope :for_session, ->(token) { where(session_token: token) }
  scope :active, -> { where(merged_at: nil) }

Merge a Guest Cart Into a User's Cart on Login With a Rails Service Object

rails service-object devise
by codesnips 3 tabs