Git Product home page Git Product logo

syliusshippingexportplugin's Introduction

BitBag SyliusShippingExportPlugin


Slack Support

At BitBag we do believe in open source. However, we are able to do it just because of our awesome clients, who are kind enough to share some parts of our work with the community. Therefore, if you feel like there is a possibility for us to work together, feel free to reach out. You will find out more about our professional services, technologies, and contact details at https://bitbag.io/.

Like what we do? Want to join us? Check out our job listings on our career page. Not familiar with Symfony & Sylius yet, but still want to start with us? Join our academy!

Table of Content


Overview


Managing shipments in any eCommerce app is something that may be tricky. There are many shipping providers and each has its own API format you might want to use to export shipping data and request the pickup. To make this process more simple and generic, we decided to create an abstract layer for Sylius platform based applications for this purpose. This plugin allows you to write simple API calls and configuration form for specific shipping provider. The workflow is quite simple - configure a proper data that's needed to export a shipment, like access key or pickup hour, book a courier for an order with one click and get shipping label file if any was received from the API. The implementation limits to writing a shipping provider gateway configuration form, one event listener and webservice access layer.

If you are curious about the details of this plugin, read this blog post.

Installation

composer require bitbag/shipping-export-plugin

Add plugin dependencies to your config/bundles.php file:

return [
    ...

    BitBag\SyliusShippingExportPlugin\BitBagSyliusShippingExportPlugin::class => ['all' => true],
];

Import required config in your config/packages/_sylius.yaml file:

# config/packages/_sylius.yaml

imports:
    ...

    - { resource: "@BitBagSyliusShippingExportPlugin/Resources/config/config.yml" }

Import routing in your config/routes.yaml file:

# config/routes.yaml

bitbag_shipping_export_plugin:
    resource: "@BitBagSyliusShippingExportPlugin/Resources/config/routing.yml"
    prefix: /admin

Usage

Adding shipping export configuration form

<?php

declare(strict_types=1);

namespace App\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotBlank;

final class FrankMartinShippingGatewayType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('iban', TextType::class, [
                'label' => 'IBAN',
                'constraints' => [
                    new NotBlank([
                        'message' => 'IBAN number cannot be blank.',
                        'groups' => 'bitbag',
                    ]),
                ],
            ])
            ->add('address', TextType::class, [
                'label' => 'Address',
                'constraints' => [
                    new NotBlank([
                        'message' => 'Address cannot be blank.',
                        'groups' => 'bitbag',
                    ]),
                ],
            ])
        ;
    }
}

Service definition

services:
    app.form.type.frank_martin_shipping_gateway:
        class: App\Form\Type\FrankMartinShippingGatewayType
        tags:
            - { name: bitbag.shipping_gateway_configuration_type, type: "frank_martin_shipping_gateway", label: "Transporter Gateway" }

Adding shipping export event listener

<?php

declare(strict_types=1);

namespace App\EventListener;

use BitBag\SyliusShippingExportPlugin\Entity\ShippingExportInterface;
use Doctrine\Persistence\ObjectManager;
use Sylius\Bundle\ResourceBundle\Event\ResourceControllerEvent;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\HttpFoundation\RequestStack;
use Webmozart\Assert\Assert;

final class FrankMartinShippingExportEventListener
{
    /** @var RequestStack */
    private $requestStack;

    /** @var Filesystem */
    private $filesystem;

    /** @var ObjectManager */
    private $shippingExportManager;

    /** @var string */
    private $shippingLabelsPath;

    public function __construct(
        RequestStack $requestStack,
        Filesystem $filesystem,
        ObjectManager $shippingExportManager,
        string $shippingLabelsPath
    ) {
        $this->requestStack = $requestStack;
        $this->filesystem = $filesystem;
        $this->shippingExportManager = $shippingExportManager;
        $this->shippingLabelsPath = $shippingLabelsPath;
    }

    public function exportShipment(ResourceControllerEvent $event): void
    {
        /** @var ShippingExportInterface $shippingExport */
        $shippingExport = $event->getSubject();
        Assert::isInstanceOf($shippingExport, ShippingExportInterface::class);

        $shippingGateway = $shippingExport->getShippingGateway();
        Assert::notNull($shippingGateway);

        if ('frank_martin_shipping_gateway' !== $shippingGateway->getCode()) {
            return;
        }

        $session = $this->requestStack->getSession();
        $flashBag = $session->getBag('flashes');

        if (false) {
            $flashBag->add('error', 'bitbag.ui.shipping_export_error'); // Add an error notification

            return;
        }

        $flashBag->add('success', 'bitbag.ui.shipment_data_has_been_exported'); // Add success notification
        $this->saveShippingLabel($shippingExport, 'Some label content received from external API', 'pdf'); // Save label
        $this->markShipmentAsExported($shippingExport); // Mark shipment as "Exported"
    }

    public function saveShippingLabel(
        ShippingExportInterface $shippingExport,
        string $labelContent,
        string $labelExtension
    ): void {
        $labelPath = $this->shippingLabelsPath
            . '/' . $this->getFilename($shippingExport)
            . '.' . $labelExtension;

        $this->filesystem->dumpFile($labelPath, $labelContent);
        $shippingExport->setLabelPath($labelPath);

        $this->shippingExportManager->persist($shippingExport);
        $this->shippingExportManager->flush();
    }

    private function getFilename(ShippingExportInterface $shippingExport): string
    {
        $shipment = $shippingExport->getShipment();
        Assert::notNull($shipment);

        $order = $shipment->getOrder();
        Assert::notNull($order);

        $orderNumber = $order->getNumber();

        $shipmentId = $shipment->getId();

        return implode(
            '_',
            [
                $shipmentId,
                preg_replace('~[^A-Za-z0-9]~', '', $orderNumber),
            ]
        );
    }

    private function markShipmentAsExported(ShippingExportInterface $shippingExport): void
    {
        $shippingExport->setState(ShippingExportInterface::STATE_EXPORTED);
        $shippingExport->setExportedAt(new \DateTime());

        $this->shippingExportManager->persist($shippingExport);
        $this->shippingExportManager->flush();
    }
}

Service definition

services:
    app.event_listener.frank_martin_shipping_export:
        class: App\EventListener\FrankMartinShippingExportEventListener
        arguments:
            - '@request_stack'
            - '@filesystem'
            - '@bitbag.manager.shipping_export'
            - '%bitbag.shipping_labels_path%'
        tags:
            - { name: kernel.event_listener, event: 'bitbag.shipping_export.export_shipment', method: exportShipment }

Plugin parameters

parameters:
    bitbag.shipping_gateway.validation_groups: ['bitbag']
    bitbag.shipping_labels_path: '%kernel.project_dir%/shipping_labels'

Available services you can decorate and forms you can extend

$ bin/console debug:container | grep bitbag

Parameters you can override in your parameters.yml(.dist) file

$ bin/console debug:container --parameters | grep bitbag

Testing

$ composer install
$ APP_ENV=test symfony server:start --port=8080 --dir=tests/Application/public --daemon
$ cd tests/Application
$ yarn install
$ yarn run gulp
$ bin/console assets:install public -e test
$ bin/console doctrine:schema:create -e test
$ shipping-export
$ open http://localhost:8080
$ vendor/bin/behat
$ vendor/bin/phpspec run
$ vendor/bin/phpstan analyse -c phpstan.neon -l max src/
$ vendor/bin/ecs check src

We are here to help

This open-source plugin was developed to help the Sylius community. If you have any additional questions, would like help with installing or configuring the plugin, or need any assistance with your Sylius project - let us know!

Read more about BitBag Sylius Shipping Export Plugin

About us


BitBag is a company of people who love what they do and do it right. We fulfill the eCommerce technology stack with Sylius, Shopware, Akeneo, and Pimcore for PIM, eZ Platform for CMS, and VueStorefront for PWA. Our goal is to provide real digital transformation with an agile solution that scales with the clients’ needs. Our main area of expertise includes eCommerce consulting and development for B2C, B2B, and Multi-vendor Marketplaces.
We are advisers in the first place. We start each project with a diagnosis of problems, and an analysis of the needs and goals that the client wants to achieve.
We build unforgettable, consistent digital customer journeys on top of the best technologies. Based on a detailed analysis of the goals and needs of a given organization, we create dedicated systems and applications that let businesses grow.
Our team is fluent in Polish, English, German and, French. That is why our cooperation with clients from all over the world is smooth.

Some numbers from BitBag regarding Sylius:

  • 50+ experts including consultants, UI/UX designers, Sylius trained front-end and back-end developers,
  • 120+ projects delivered on top of Sylius,
  • 25+ countries of BitBag’s customers,
  • 4+ years in the Sylius ecosystem.

Our services:

  • Business audit/Consulting in the field of strategy development,
  • Data/shop migration,
  • Headless eCommerce,
  • Personalized software development,
  • Project maintenance and long term support,
  • Technical support.

Key clients: Mollie, Guave, P24, Folkstar, i-LUNCH, Elvi Project, WestCoast Gifts.


If you need some help with Sylius development, don't be hesitated to contact us directly. You can fill the form on this site or send us an e-mail at [email protected]!


Community


For online communication, we invite you to chat with us & other users on Sylius Slack.

Demo Sylius Shop


We created a demo app with some useful use-cases of plugins! Visit sylius-demo.bitbag.io to take a look at it. The admin can be accessed under sylius-demo.bitbag.io/admin/login link and bitbag: bitbag credentials. Plugins that we have used in the demo:

BitBag's Plugin GitHub Sylius' Store
ACL Plugin Private. Available after the purchasing. https://plugins.sylius.com/plugin/access-control-layer-plugin/
Braintree Plugin https://github.com/BitBagCommerce/SyliusBraintreePlugin https://plugins.sylius.com/plugin/braintree-plugin/
CMS Plugin https://github.com/BitBagCommerce/SyliusCmsPlugin https://plugins.sylius.com/plugin/cmsplugin/
Elasticsearch Plugin https://github.com/BitBagCommerce/SyliusElasticsearchPlugin https://plugins.sylius.com/plugin/2004/
Mailchimp Plugin https://github.com/BitBagCommerce/SyliusMailChimpPlugin https://plugins.sylius.com/plugin/mailchimp/
Multisafepay Plugin https://github.com/BitBagCommerce/SyliusMultiSafepayPlugin
Wishlist Plugin https://github.com/BitBagCommerce/SyliusWishlistPlugin https://plugins.sylius.com/plugin/wishlist-plugin/
Sylius' Plugin GitHub Sylius' Store
Admin Order Creation Plugin https://github.com/Sylius/AdminOrderCreationPlugin https://plugins.sylius.com/plugin/admin-order-creation-plugin/
Invoicing Plugin https://github.com/Sylius/InvoicingPlugin https://plugins.sylius.com/plugin/invoicing-plugin/
Refund Plugin https://github.com/Sylius/RefundPlugin https://plugins.sylius.com/plugin/refund-plugin/

If you need an overview of Sylius' capabilities, schedule a consultation with our expert.

Additional resources for developers


To learn more about our contribution workflow and more, we encourage you to use the following resources:

License


This plugin's source code is completely free and released under the terms of the MIT license.

Contact


If you want to contact us, the best way is to fill the form on our website or send us an e-mail to [email protected] with your question(s). We guarantee that we answer as soon as we can!

syliusshippingexportplugin's People

Contributors

arunsathiya avatar bartoszwojdalowicz avatar bitbager avatar damonsson avatar devfive avatar ehibes avatar fabulouspuppet avatar gracjanjozefczyk avatar krisflorq avatar lchrusciel avatar leszczuu avatar liszkapawel avatar m0sviatoslav avatar marek-pietrzak-tg avatar marekrzytki avatar markiewiczl avatar milwoz avatar mpysiak avatar pamil avatar patrick477 avatar pbalcerzak avatar piotrkardasz avatar pjedrzejewski avatar senghe avatar shinoks avatar stefandoorn avatar szymonfilipek avatar szymonkostrubiec avatar xnordo avatar zales0123 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

syliusshippingexportplugin's Issues

Issue with configuration

Hello i would like to use this plugin and i am facing errors, i was facing this error :

Compile Error: Type of BitBag\SyliusShippingExportPlugin\Controller\ShippingExportController::$repository must be Sylius\Component\Resource\Repository\RepositoryInterface (as in class Sylius\Bundle\ResourceBundle\Controller\ResourceController)

So i followed the solution in this issue : #36

So i decided to override the Controller and add protected RepositoryInterface $repository; instead of protected $repository;.

Now i added this controller to my services.yaml :

    bitbag.shipping_export_plugin.controller.shipping_export:
        class: 'BitBag\OpenMarketplace\SyliusShippingExportPlugin\Controller\ShippingExportController'
        tags:
            - { name: 'controller.service_arguments' }

And i am facing this new error now :

Class "BitBag\OpenMarketplace\SyliusShippingExportPlugin\Controller\ShippingExportController" used for service "bitbag.shipping_export_plugin.controller.shipping_export" cannot be found.

The file is in src/Controller, the namespace is correct i don't really understand why it's not working and i was wondering if anyone delt with this same error or if it's maybe the fact that i'm overiding the Controller.

I am using Sylius v1.11.15, Plugin v1.7.0 and PHP 8.0.26, if i can provide any extra information i will.

I am following this article : https://bitbag.io/blog/bitbag-shipping-export-plugin-simple-way-to-control-shipments-in-your-online-store

And starting facing the errors here :

Import routing in you app/config/routing.yml:

bitbag_shipping_export_plugin:
    resource: "@BitBagSyliusShippingExportPlugin/Resources/config/routing.yml"
    prefix: /admin

Obsolete documentation

This article needs some updates:

new \BitBag\ShippingExportPlugin\ShippingExportPlugin(),

is actually now

new \BitBag\SyliusShippingExportPlugin\BitBagShippingExportPlugin(),

same for

- { resource: "@ShippingExportPlugin/Resources/config/config.yml" }

and

resource: "@ShippingExportPlugin/Resources/config/routing.yml"

Also, I think these should be included in the repo, as an installation guideline. With a potential read more on the blog.

Error in profile for entity mapping


BitBag\SyliusShippingExportPlugin\Entity\ShippingGateway | The field BitBag\SyliusShippingExportPlugin\Entity\ShippingGateway#shippingExports is on the inverse side of a bi-directional relationship, but the specified mappedBy association on the target-entity BitBag\SyliusShippingExportPlugin\Entity\ShippingExport#shippingGateway does not contain the required 'inversedBy="shippingExports"' attribute.
-- | --

$repository must be Sylius\Component\Resource\Repository\RepositoryInterface

Hi,

I encounter this error when installing the plugin on version 1.11 of sylius & php 8.1 :

Compile Error: Type of BitBag\SyliusShippingExportPlugin\Controller\ShippingExportController::$repository must be Sylius\Component\Resource\Repository\RepositoryInterface (as in class Sylius\Bundle\ResourceBundle\Controller\ResourceController)

To solve this, either delete the $repository declaration in the controller or type $repository like this:

use Sylius\Component\Resource\Repository\RepositoryInterface;
...
    /** @var ShippingExportRepositoryInterface */
    protected RepositoryInterface $repository;

Validator is not called on configuration

Hi @bitbager,

After completing the shipping gateway configuration, the validator service is not called to validate the configuration form even if it has contraints defined.
Is it normal or should it be fixed ?

Migrations missing

Shouldn't this plugin have also a migration file ?

I'm having an error on /admin/shipping-exports/ page. Some missing tables.

After a while I've executed doctrine:schema:update --dump-sql and indeed I was missing some tables:
CREATE TABLE bitbag_shipping_gateway (id INT AUTO_INCREMENT NOT NULL, code VARCHAR(255) NOT NULL, config JSON NOT NULL COMMENT '(DC2Type:json_array)', name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET UTF8 COLLATE UTF8_unicode_ci ENGINE = InnoDB;
CREATE TABLE bitbag_shipping_gateway_method (shipping_gateway_id INT NOT NULL, shipping_method_id INT NOT NULL, INDEX IDX_8606B9CBEF84DE5E (shipping_gateway_id), INDEX IDX_8606B9CB5F7D6850 (shipping_method_id), PRIMARY KEY(shipping_gateway_id, shipping_method_id)) DEFAULT CHARACTER SET UTF8 COLLATE UTF8_unicode_ci ENGINE = InnoDB;
CREATE TABLE bitbag_shipping_export (id INT AUTO_INCREMENT NOT NULL, shipment_id INT DEFAULT NULL, shipping_gateway_id INT DEFAULT NULL, exported_at DATETIME DEFAULT NULL, label_path VARCHAR(255) DEFAULT NULL, state VARCHAR(255) NOT NULL, external_id VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_20E62D9F7BE036FC (shipment_id), INDEX IDX_20E62D9FEF84DE5E (shipping_gateway_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET UTF8 COLLATE UTF8_unicode_ci ENGINE = InnoDB;
ALTER TABLE bitbag_shipping_gateway_method ADD CONSTRAINT FK_8606B9CBEF84DE5E FOREIGN KEY (shipping_gateway_id) REFERENCES bitbag_shipping_gateway (id);
ALTER TABLE bitbag_shipping_gateway_method ADD CONSTRAINT FK_8606B9CB5F7D6850 FOREIGN KEY (shipping_method_id) REFERENCES sylius_shipping_method (id);
ALTER TABLE bitbag_shipping_export ADD CONSTRAINT FK_20E62D9F7BE036FC FOREIGN KEY (shipment_id) REFERENCES sylius_shipment (id);
ALTER TABLE bitbag_shipping_export ADD CONSTRAINT FK_20E62D9FEF84DE5E FOREIGN KEY (shipping_gateway_id) REFERENCES bitbag_shipping_gateway (id);

Prepare for 1.0.0

The plugin needs to support 7.1 PHP only with strict types and require Sylius 1.0.*+.

Issue with sorting by shipping method

Hello,

I've found a bug while an admin user wants to sort by Shipping method in grid bitbag_admin_shipping_export.
In file grids/bitbag_shipping_export.yml On line 38 there should be sotable: shipment.method

Export are removed when gateway is removed

Hi,

I created a new gateway for a specific carrier and removed the old one. The shipping export created with the old gateway has been removed.
2 solutions:
Invalidate deletion of the gateway.
Set gateway_id to null if the gateway is removed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.