I am trying to make a functionnality so that a customer will be able to split his order into 2, in case some articles are temporarily unavailable and if they wish that we send them part of their order first. So the idea is to create 2 new orders and cancelling the old one.
Do you have any idee about how to do this programmatically please ?
What you're describing doesn't sound necessary... You're talking about sending part of the order first... Notice in the Magento Admin once an order is place you can create an invoice, take note that you do not have to invoice everything at one time, the same is true when you create a shipment. You'll need to make sure you're merchant / payment gateway supports multiple partial captures against a single authorization.
However, if you really want to split the orders in two, it is a rather complicated process. We've done it, and its very tricky... you need to modify the opcheckout.js file, you'll need to modify the template since you will have to create seperate shipping methods for each order. You'll need to modify the OnePage controller & Model files very significantly. There are tricky areas in terms of re-executing the totals and making sure data on the order and subsequent quote and address models is precisely what is required by Magento. Maintaining the other checkout functionality requires diligence, such as saving the customer's address when checking out. If you're really going down the path of coding something that splits an order into two orders during the checkout process, feel free to send me a message and we can talk more in-depth and I'll send you some code.
Related
CQRS states: command should not query read side.
Ok. Let's take following example:
The user needs to create orders with order lines, each order line contains product_id, price, quantity.
It sends requests to the server with order information and the list of order lines.
The server (command handler) should not trust the client and needs to validate if provided products (product_ids) exist (otherwise, there will be a lot of garbage).
Since command handler is not allowed to query read side, it should somehow validate this information on the write side.
What we have on the write side: Repositories. In terms of DDD, repositories operate only with Aggregate Roots, the repository can only GET BY ID, and SAVE.
In this case, the only option is to load all product aggregates, one by one (repository has only GET BY ID method).
Note: Event sourcing is used as a persistence, so it would be problematic and not efficient to load multiple aggregates at once to avoid multiple requests to the repository).
What is the best solution for this case?
P.S.: One solution is to redesign UI (more like task based UI), e.g.: User first creates order (with general info), then adds products one by one (each addition separate http request), but still I need to support bulk operations (api for third party applications as an example).
The short answer: pass a domain service (see Evans, chapter 5) to the aggregate along with the other command arguments.
CQRS states: command should not query read side.
That's not an absolute -- there are trade offs involved when you include a query in your command handler; that doesn't mean that you cannot do it.
In domain-driven-design, we have the concept of a domain service, which is a stateless mechanism by which the aggregate can learn information from data outside of its own consistency boundary.
So you can define a service that validates whether or not a product exists, and pass that service to the aggregate as an argument when you add the item. The work of computing whether the product exists would be abstracted behind the service interface.
But what you need to keep in mind is this: products, presumably, are defined outside of the order aggregate. That means that they can be changing concurrently with your check to verify the product_id. From the point of view of correctness, there's no real difference between checking the validity of the product_id in the aggregate, or in the application's command handler, or in the client code. In all three places, the product state that you are validating against can be stale.
Udi Dahan shared an interest observation years ago
A microsecond difference in timing shouldn’t make a difference to core business behaviors.
If the client has validated the data one hundred milliseconds ago when composing the command, and the data was valid them, what should the behavior of the aggregate be?
Think about a command to add a product that is composed concurrently with an order of that same product - should the correctness of the system, from a business perspective, depend on the order that those two commands happen to arrive?
Another thing to keep in mind is that, by introducing this check into your aggregate, you are coupling the ability to change the aggregate to the availability of the domain service. What is supposed to happen if the domain service can't reach the data it needs (because the read model is down, or whatever). Does it block? throw an exception? make a guess? Does this choice ripple back into the design of the aggregate, and so on.
I am learning to develop microservices using DDD, CQRS, and ES. It is HTTP RESTful service. The microservices is about online shop. There are several domains like products, orders, suppliers, customers, and so on. The domains built in separate services. How to do the validation if the command payload relates to other domains?
For example, here is the addOrderItemCommand payload in the order service (command-side).
{
"customerId": "CUST111",
"productId": "SKU222",
"orderId":"SO333"
}
How to validate the command above? How to know that the customer is really exists in database (query-side customer service) and still active? How to know that the product is exists in database and the status of the product is published? How to know whether the customer eligible to get the promo price from the related product?
Is it ok to call API directly (like point-to-point / ajax / request promise) to validate this payload in order command-side service? But I think, the performance will get worse if the API called directly just for validation. Because, we have developed an event processor outside the command-service that listen from the event and apply the event to the materalized view.
Thank you.
As there are more than one bounded contexts that need to be queried for the validation to pass you need to consider eventual consistency. That being said, there is always a chance that the process as a whole can be in an invalid state for a "small" amount of time. For example, the user could be deactivated after the command is accepted and before the order is shipped. An online shop is a complex system and exceptions could appear in any of its subsystems. However, being implemented as an event-driven system helps; every time the ordering process enters an invalid state you can take compensatory actions/commands. For example, if the user is deactivated in the meantime you can cancel all its standing orders, release the reserved products, announce the potential customers that have those products in the wishlist that they are not available and so on.
There are many kinds of validation in DDD but I follow the general rule that the validation should be done as early as possible but without compromising data consistency. So, in order to be early you could query the readmodel to reject the commands that couldn't possible be valid and in order for the system to be consistent you need to make another check just before the order is shipped.
Now let's talk about your specific questions:
How to know that the customer is really exists in database (query-side customer service) and still active?
You can query the readmodel to verify that the user exists and it is still active. You should do this as a command that comes from an invalid user is a strong indication of some kind of attack and you don't want those kind of commands passing through your system. However, even if a command passes this check, it does not necessarily mean that the order will be shipped as other exceptions could be raised in between.
How to know that the product is exists in database and the status of the product is published?
Again, you can query the readmodel in order to notify the user that the product is not available at the moment. Or, depending on your business, you could allow the command to pass if you know that those products will be available in less than 24 hours based on some previous statistics (for example you know that TV sets arrive daily in your stock). Or you could let the customer choose whether it waits or not. In this case, if the products are not in stock at the final phase of the ordering (the shipping) you notify the customer that the products are not in stock anymore.
How to know whether the customer eligible to get the promo price from the related product?
You will probably have to query another bounded context like Promotions BC to check this. This depends on how promotions are validated/used.
Is it ok to call API directly (like point-to-point / ajax / request promise) to validate this payload in order command-side service? But I think, the performance will get worse if the API called directly just for validation.
This depends on how resilient you want your system to be and how fast you want to reject invalid commands.
Synchronous call are simpler to implement but they lead to a less resilient system (you should be aware of cascade failures and use technics like circuit breaker to stop them).
Asynchronous (i.e. using events) calls are harder to implement but make you system more resilient. In order to have async calls, the ordering system can subscribe to other systems for events and maintain a private state that can be queried for validation purposes as the commands arrive. In this way, the ordering system continues to work even of the link to inventory or customer management systems are down.
In any case, it really depends on your business and none of us can tell you exaclty what to do.
As always everything depends on the specifics of the domain but as a general principle cross domain validation should be done via the read model.
In this case, I would maintain a read model within each microservice for use in validation. Of course, that brings with it the question of eventual consistency.
How you handle that should come from your understanding of the domain. Factors such as the length of the eventual consistency compared to the frequency of updates should be considered. The cost of getting it wrong for the business compared to the cost of development to minimise the problem. In many cases, just recording the fact there has been a problem is more than adequate for the business.
I have a blog post dedicated to validation which you can find here: How To Validate Commands in a CQRS Application
There is a choice of “SALE” or “AUTHORISATION” in the Magento Paypal settings. We ideally wish to stay with “SALE” as that covers 99.9% of anything we do (we always have goods in stock). The “Authorisation” option worries me with the 3 day limit, plus it adds an extra “capture” step that could go wrong later.
So…….
“SALE" works fine but in Magento it automatically creates an INVOICE in the system. Other payment systems we use such as Sofort AG make this setting optional and for a very good reason.
Magento is set so that once you have produced an INVOICE and a SHIPMENT it automatically marks any order as COMPLETE.
We create UPS labels, with a tracking number which of course is added to the SHIPMENT details. So my problem is:
As soon as we try to create a UPS label (without even printing) Magento sets the Paypal orders to COMPLETE. This is because it has seen an INVOICE
and a SHIPMENT for an order.
We need to disable a Paypal “SALE” from producing an invoice. We can easily produce and send the invoice once the shipment has been produced
and sent, and then set it finally to Complete.
Is there a setting I have missed to disable this forced invoice? I can see a company used to make a module for this purpose but it is out of date for Magento 1.9. (I did try it just in case!!)
http://www.magentocommerce.com/magento-connect/disable-automatic-generation-of-invoice.html
No, there is no setting to fix this: paypal create an object called transaction and this kind of object should be created with the object invoice. It's not a good practice to don't create invoice and I suggest you to stay away to any component that don't create a transaction.
Probably it works well, but in the flow of order creation when you will evalutate to play with order status. Anyway there is not a setting to do this.
I have a subscription service that people pay monthly for, so I’ve setup a “Virtual Product” with a Recurring Profile. At the same time, I want to have it so they can add different one time products. To accomplish this I’ve tried creating a “Bundled Product” with all the different one time products and adding the “Virtual Product” to that “Bundled Product”.
However, when I go to checkout it says “Nominal item can be purchased standalone only. To proceed please remove other items from the quote.” How do I allow people to subscribe to the service and purchase the products at the same time?
Note: I am using Paypal Website Payment Pro as my merchant account.
Here's the comment from Magento code:
/**
* Temporary workaround for purchase process: it is too dangerous to purchase more than one nominal item
* or a mixture of nominal and non-nominal items, although technically possible.
*
* The problem is that currently it is implemented as sequential submission of nominal items and order, by one click.
* It makes logically impossible to make the process of the purchase failsafe.
* Proper solution is to submit items one by one with customer confirmation each time.
*/
Actually you can remove the code below:
if ($item->isNominal() && $this->hasItems() || $this->hasNominalItems()) {
Mage::throwException(Mage::helper('sales')->__('Nominal item can be purchased standalone only. To proceed please remove other items from the quote.'));
}
Magento still handles multiple nominal products, however, you use that with your own risk.
Unfortunately this is a hardcoded restriction in the Mage_Paypal code.
You can see in Mage_Sales_Model_Service_Quote::submitAll() that it executes submitNominalItems() which contains:
$this->_validate();
$this->_submitRecurringPaymentProfiles();
$this->_inactivateQuote();
$this->_deleteNominalItems();
So, it kills the Cart after submitting nominal items. I'm not exactly sure why it does that, but I assume it's due to the way that subscriptions are created at Paypal.
Here is the code that prevents adding items to a cart that contains nominals in Mage_Sales_Model_Quote::addItem():
if ($item->isNominal() && $this->hasItems() || $this->hasNominalItems()) {
Mage::throwException(Mage::helper('sales')->__('Nominal item can be purchased standalone only. To proceed please remove other items from the quote.'));
}
I'm working on using Magento's Recurring Profiles for other payment providers at the moment (its a background task: Magento Recurring Profiles with non-Paypal payment method) and it is possible to checkout both nominal (aka subscription) and real products at the same time, but it does make it quite a bit more complex.
If this is a big deal, it should be possible to refactor the Mage_Paypal code to do this, but it's a complicated task that can't really be answered in a single post.
I have a requirement to be able to accept different forms of payment within the same order - ie not just the usual credit card or paypal for the whole thing, but perhaps paypal for one item, cheque for another. I know this sounds quite crazy, but there is a good business reason for the requirement so I can't just push back.
The best way I can think of implementing it at the moment is to have kind of a hub page, where you can "launch off" into multiple flows for each of the payments by opening new windows. I can't figure out a way of doing this in a linear flow as for example you can't guarantee that a user will come back from paypal, so you'd then lose the user completely.
Is there a neater way of doing this that anyone can think of, or can anyone point me to an example of a site that does somethign similar for inspiration?
Even when opening several windows at once, there is no guarantee that the user will complete all payment methods. So you are most probably going to lose a few users or payments. Be sure to send automated e-mail follow-ups for missing payments to minimize this problem. The e-mails could contain links to your payment providers for easy accesss to their outstanding payment operations.
This is a difficult problem, but how many payment processors do you have to go offsite for? Should only be paypal.
In any case, I'd give the user all their payment options on one page, and let them fill in the amount for each processor or payment type. Then the next page would list those they chose, the amount for each, and a link to "Complete this payment".
The link would open in a new window.
You'll have to have a good back end and javascript, as well as user warnings so that the payment page gets updated as each payment is processed. Consider using popup dialogs to show that a payment has completed, or that the order has sat idle for more than 10-30 minutes without complete payment.
Also, consider sending emails and letting the user complete the payments through links in the emails. Send a new email each time a payment is completed, and a final email if all payments are complete and the order is moving forward.
Send an email one hour, and one day later for uncompleted orders with remaining payments required, that also give them the option of choosing different payment options for the remainder.
Email isn't best (lose more orders that way due to changing minds) but it's good for the type of transactions you're thinking about.
Personally, I'd do it like this:
Let the user fill their basket in the ususal way
Allow them to add payment types and amounts to a list (2nd basket almost)
When the payments balance against the basket, start processing the payments
For external sites, try a frame which has a progress indicator at the top.
In an ideal world it wouldn't be linear. But a lot of users might lose a spawned window, or get confused by the parallelism.
Better to stick to established IxD principals and rely on good feedback instead. Give the user control from the outset and keep it transparent.
Lastly, start the payment process with the most immediate (e.g. paypal) to reduce users giving up. (COD should come last!)
Hope this helps,
Tom
If possible, just separate your order into separate smaller orders based off of the payment selections of the user.
And don't do it linearly. If anything you could open up each payment processor in a separate window so that you maintain presence.
I would take an approach where the whole order is broken down into sub-orders for each of the necessary payment methods. You can load the PayPal portion, the check portion, etc. and process them separately. It's important for the user to know how much is being charged to each of their payment methods, so it makes sense in this case to present the whole order as broken down by payment method (versus displaying as a unified order).
Implementation would be easiest if it's always a certain subset of items that is forced to any payment method. If this differs by user, or if it's when the order reaches a certain amount, the situation could become much more complicated. Can you be more specific about your approach?
Processing Multiple Order Payments
Give the user the option to make a payment for a pending order using any of your payment types.
Let the user specify an (Amount <= [Order Total] - [Payments Received]), if that is part of your requirement.
If the order is still pending after you process the payment (see how below), take them back to step 1 to rinse and repeat.
How to store and process each payment made:
Use a Payments table to store all order payments, the PaymentMethod used and its Amount with its CurrencyCode.
When a payment is received for an order, store the payment and sum all received amounts converted into your base currency as [Payments Received].
If [Payments Received] >= [Order Total], mark the order as Paid. Or, if dealing with double-converted foreign exchange rates, check if it is correct to within a small-enough margin, eg 0.5%.
Optionally, convert any overpayment into prepaid credit for the client.