Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Opensalestax Sylius Laravel Package

ejosterberg/opensalestax-sylius

View on GitHub
Deep Wiki
Context7

Getting Started

To integrate opensalestax-sylius into a Sylius-based e-commerce project, follow these minimal steps:

  1. Install the package:

    composer require ejosterberg/opensalestax-sylius
    
  2. Register the bundle in config/bundles.php:

    return [
        OpenSalesTax\Sylius\OpenSalesTaxSyliusBundle::class => ['all' => true],
    ];
    
  3. Configure the bundle in config/packages/opensalestax_sylius.yaml:

    opensalestax_sylius:
        engine_url: '%env(OSTAX_ENGINE_URL)%'
    

    Ensure OSTAX_ENGINE_URL is set in your .env file (e.g., OSTAX_ENGINE_URL=https://your-open-sales-tax-engine/api).

  4. First use case: The bundle replaces Sylius's default tax calculation with destination-based US sales tax. After installation, tax calculations for US orders will automatically route to the OpenSalesTax engine. Test with a US-based shipping address to verify tax rates are applied correctly.


Implementation Patterns

Core Workflow

  1. Tax Calculation Replacement: The bundle implements OstaxCalculator (replacing Sylius's default) and OstaxTaxationStrategy to integrate with Sylius's taxation system. No manual overrides are needed for basic usage—just install and configure.

  2. Order Processing:

    • For US-based orders, the bundle queries the OpenSalesTax engine for destination-based rates.
    • For non-US orders, it falls back to Sylius's default behavior (fail-soft mode).
    • Configure fail-hard mode (opt-in) in config/packages/opensalestax_sylius.yaml if strict validation is required:
      opensalestax_sylius:
          engine_url: '%env(OSTAX_ENGINE_URL)%'
          fail_hard: true  # Throws exceptions on engine failures
      
  3. Nexus Filtering: Use the per-state nexus filter to exclude states where your business has no nexus (sales tax liability). Configure in the YAML:

    opensalestax_sylius:
        nexus_states: ['CA', 'NY', 'TX']  # Only calculate tax for these states
    
  4. Caching: The bundle includes 60-minute PSR-6 cache memoization to reduce API calls. Ensure your project has a PSR-6 cache pool (e.g., cache:pool:app) configured.

Integration Tips

  • Testing: Mock the OstaxCalculator in unit tests to avoid hitting the OpenSalesTax engine. Use Sylius's built-in TaxationContext for test scenarios. Example:

    $calculator = $this->createMock(OstaxCalculator::class);
    $calculator->method('calculate')->willReturn(new TaxItem(...));
    $this->container->set(OstaxCalculator::class, $calculator);
    
  • Admin UI: The bundle does not include an admin panel (deferred to v1.0). For now, validate tax calculations via API or custom admin logic.

  • Multi-Currency: The bundle is USD-only (per constitution §5). For non-USD orders, ensure currency conversion happens upstream (e.g., in the checkout flow).

  • Sylius Events: Listen to sylius.order.complete or sylius.order.cancel to log tax calculations or trigger post-processing (e.g., tax return filings, though these are not handled by the bundle).


Gotchas and Tips

Pitfalls

  1. Engine Dependency: The bundle requires a self-hosted OpenSalesTax engine (v0.14+). Without it, tax calculations will fail (or fall back to Sylius defaults in fail-soft mode). Test locally with a mock engine or Docker setup:

    docker run --rm -p 8000:8000 ejosterberg/opensalestax-engine:latest
    
  2. State-Specific Quirks:

    • Nexus States: Misconfigured nexus_states may lead to incorrect tax calculations. Verify your business's nexus status (e.g., via Sales Tax Institute).
    • Special Districts: OpenSalesTax may not cover all local tax districts (e.g., city-level taxes). Monitor for discrepancies in high-tax areas like NYC or Chicago.
  3. Caching Issues:

    • Clear the cache (php bin/console cache:clear) if tax rates appear stale. The 60-minute TTL is intentional but may need adjustment for testing.
    • Avoid caching TaxationContext objects directly; rely on the bundle's memoization.
  4. Fail-Hard Mode: Enabling fail_hard: true will throw exceptions on engine failures. Use this in production only after validating the engine's reliability.

Debugging

  • Log Tax Calculations: Enable Sylius's tax debug mode in config/packages/sylius_core.yaml:

    sylius_core:
        taxation:
            debug: true
    

    Logs will appear in var/log/dev.log.

  • API Errors: Check the OpenSalesTax engine logs (if self-hosted) for malformed requests. The bundle sends:

    {
        "address": { "state": "CA", "zip": "90210" },
        "amount": 100.00,
        "currency": "USD"
    }
    

    Validate this payload matches the engine's API spec.

  • PHP Errors: Use php bin/console debug:config opensalestax_sylius to verify configuration. Common issues:

    • Missing OSTAX_ENGINE_URL in .env.
    • Incorrect Symfony/Sylius version (bundle supports ^1.13 only).

Extension Points

  1. Custom Tax Categories: Override OstaxTaxationStrategy to map Sylius TaxCategory to OpenSalesTax categories (planned for v0.2). Example:

    // src/OpenSalesTaxSylius/CustomTaxationStrategy.php
    class CustomTaxationStrategy extends OstaxTaxationStrategy
    {
        protected function getOstaxCategory(TaxCategoryInterface $category): string
        {
            return match ($category->getCode()) {
                'digital' => 'DIGITAL',
                default => parent::getOstaxCategory($category),
            };
        }
    }
    

    Register the override in config/services.yaml:

    services:
        OpenSalesTax\Sylius\OpenSalesTaxSyliusBundle\Taxation\OstaxTaxationStrategy:
            class: App\OpenSalesTaxSylius\CustomTaxationStrategy
    
  2. Refund Proration: Extend the AdjustmentFactory to handle tax prorations for refunds (v0.2 feature). Hook into sylius.order_item.refund events.

  3. Non-USD Support: Fork the bundle and modify OstaxCalculator to handle currency conversion if needed. Contribute back for broader adoption!

Configuration Quirks

  • Environment Variables: The bundle expects OSTAX_ENGINE_URL to be prefixed with https://. Use absolute URLs (e.g., https://tax-engine.example.com/api/v1/tax).
  • Symfony Cache: Ensure your cache:pool:app is configured in config/packages/framework.yaml:
    framework:
        cache:
            pools:
                app:
                    adapter: cache.adapter.filesystem
    
  • Sylius Version Lock: The bundle is not compatible with Sylius <1.13 or >1.13.x. Upgrade Sylius first if needed:
    composer require sylius/sylius:"^1.13"
    

Performance Tips

  • Batch Processing: For bulk order adjustments (e.g., tax recalculations), disable memoization temporarily:
    opensalestax_sylius:
        cache_ttl: 0  # Disables caching
    
  • Engine Load: Monitor the OpenSalesTax engine's response times. Consider rate-limiting or queueing tax calculations for high-volume orders.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky