How to recreate the orders context in order to send out emails in Shopware 6 - shopware6

I am creating a console task to ship orders based on XML files (How to add a shipment (tracking code + change status to shipped) programmatically?
) which I import.
Currently I am using
$context = Context::createDefaultContext();
And create a shipment:
$this->deliveryRepository->update([
[
'id' => $deliveryId,
'trackingCodes' => [$trackingCode]
]
], $context);
$context->addExtension(
MailSendSubscriber::MAIL_CONFIG_EXTENSION,
new MailSendSubscriberConfig(false)
);
$this->orderService->orderDeliveryStateTransition(
$deliveryId,
'ship',
new ParameterBag(),
$context
);
This does not send out the shipment confirmation mail.
I am assuming the reason is, because I am in the default context.
Can I / should I recreate the context from the Storefront where the order was placed in? How does this work?
(maybe using \Shopware\Core\System\SalesChannel\Context\BaseContextFactory::create ? but this is tagged as #internal )
Or is it okay to use the default context here (see Shopware 6 get context in scheduled task) and is the problem something else?
EDIT:
$context = $this->baseContextFactory->create($order->getSalesChannelId())->getContext();
does work, but I still do not receive emails.
EDIT2:
The mail problem is unrelated - I am testing this with an Unit test and it does not seem to send out mails in general. This it out of scope of this question.

You can inject the Shopware\Core\Checkout\Cart\Order\OrderConverter service to assemble a SalesChannelContext based on an order. You can then get the Context from the SalesChannelContext.
$salesChannelContext = $this->orderConverter->assembleSalesChannelContext($order, Context::createDefaultContext());
$context = $salesChannelContext->getContext();

Related

User id not coming in get_current_user_id() while running Custom endpoint post request

I am getting this issue while using custom endpoints. My entire functionality is based on get_current_user_id(). So, when I am running endpoint url it's not working through custom endpoint.
Even in init function user id is null. But when I print anything it working fine on site.
I am using this:
register_rest_route('v2', '/product/(?P\d+)/',
array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'wp_get_webhook_product',
)
);

datatables / jquery / session variable / login form

Scenario:
1) login.php verifies the username and password and sets a session with the user id
$_SESSION['id'] = $id;
2) datatables / jquery calls an action.php file to fill the table with data
"ajax":{
url:"action.php",
type:"POST",
data:{action:'listTable'},
dataType:"json"
},
3) the action.php file calls the function listTable()
include('table.php');
$table = new table();
$table->listTable();
4) the listTable function (table.php) returns the whole data which is landing in the datatable
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $numRows,
"recordsFiltered" => $numRows,
"data" => $tableData
);
echo json_encode($output);
5) the data was selected with a sql command and was put into the tableData variable
Everything works fine in that case.
Ideas:
I wanted to acccess the session variable within the sql select command. This is not possible, because of the jquery / action.php api. Those are complete different files and have no access to that session. It is possible to set the user id within a hidden formular field, but this is not secure and easy to manipulate. A cookie file is also user editable. Furthermore Javascript cannot read server side session variables.
Question:
How can i use / access that php session variable in that scenario?
Update:
Thats not working too :/
overview.php
$userID = $_SESSION['id'];
data.js
"ajax":{
url:"action.php",
type:"POST",
data:{userID:userID, action:'listTable'},
dataType:"json"
},
table.php
$userID = $_POST["userID"];
I really don't understand here the problem, because of $_SESSION variable is available across the php files even if an ajax calls the php file. Until you call the AJAX call from the same browser and the ajax call includes the cookies (one of the cookie will be the session ID) then you will be able to reach your user ID in the SQL query on the PHP side, without passing to javascript/jquery your user's ID.
As you wrote in login.php:
$_SESSION['id'] = $id;
In your table.php where the SQL command is living:
echo isset($_SESSION['id']) ? "I'm existing!" : "I'm NOT existing!";
It will print "I'm existing!" if the user logged in and "I'm NOT existing!" if the user didn't log in. All the $_SESSION variables are available across the php files until the server gets the SESSION ID from the browser (which is a cookie). Cookies are automatically sent if you calling the same domain.

ExtJs 4 Store's AJAX proxy is not called on Store add — what is missing?

I have a Grid, a Store and Model for its data and AJAX proxy for the Store that is pointing to my self-written PHP back-end. The PHP backend writes to log each time it is called.
The system works OK for Read, Update and Delete calls. However now I need to add new field to Store, which I do in such a way:
(here, some new data were generated...)
var newEntry=Ext.ModelManager.create({
id:id,
title: title,
url: '/php/'+fname,
minithumb: '/php/'+small,
thumb:'/php/'+thumb
}, 'MyApp.model.fileListModel');
var store=Ext.getCmp('currGallery').getStore();
store.add(newEntry);
store.sync();
I have the new line appearing in the Grid.
But with or withour sync() call, I have no calls going to my PHP back end. It however reads one more time. Store has parameter autoSync :true and does great updating data automatically when I edit existing line in the Grid.
What am I missing?
Try not to set id when creating new record.
In fact I was missing a
newEntry.phantom = true;
flag. After I set it before adding to store, Store and its Proxy started to send data to server.
Maybe ID solution also works, dunno.

Magento API Data Type: CartCustomerEntity

While trying to create a cart via the Magento API, I am having trouble adding an existing user as the owner of the cart. I am working with the documentation they provide here:
http://www.magentocommerce.com/wiki/doc/webservices-api/api/cart#cart_customer.set
I called "customer.info" using my specific customerId, then just passed the results to that cart_customer.set method, praying that was what it was asking for. It returned (from PHP)
Fatal error: Uncaught SoapFault exception: [1045] Customer's mode is unknown in ...
I looked at the example at the bottom of the above referenced page and they only had an example for a new guest user, 'mode' set to 'guest'. I was wondering if anyone knew what the other options were for that 'mode' key? Documentation on that data structure in general would be a great help.
Thanks.
Via my own comment:
Ah ha! Found buried in their forum:
$customer = array( 'entity_id' => 6, 'mode' => 'customer' ); via http://www.magentocommerce.com/boards/viewthread/232778 I guess that is all you need to pass. This isn't really a great explanation but it does solve the original problem.
Just gonna flag this one as done.

Send an email via MailChimp

I think problem is around $api->listSubscribers()
include('../libs/mailchimp/MCAPI.class.php');
$options = array('list_id' => '$list_id', 'subject' => 'Prova', 'from_name' => 'name', 'from_email' => 'info#example.com');
$content = array('html' => '<p>Testo di prova</p>');
$api = new MCAPI($apikey);
$campaignId = $api->campaignCreate('trans', $options, $content);
$api->listSubscribe($options['list_id']);
$api->campaignSendNow($campaignId);
if ($api->errorCode){
echo "Unable to Create New Campaign!";
echo "\n\tCode=".$api->errorCode;
echo "\n\tMsg=".$api->errorMessage."\n";
} else {
echo "New Campaign ID:".$campaignId ."\n";
}
Why does'nt it send an email?
You have a several issues here:
The first one is that you are not doing error checking after each API call. If you take the error checking code from the bottom and stick it after the listSubscribe() call, you'll immediately get an error because you aren't passing any sort of subscriber data (at the very least you need the email address). The docs for listSubscribe are here
Once you do that - unless you've thoroughly read and considered the options in the listSubscribe docs - your second issue is going to be that you are running listSubscribe with the double_optin parameter set to true (the default), which means they won't be subscribed until clicking a link in the confirmation email.
Next, that code is just going to get you in trouble, and probably quickly. If you are going to use psuedo-transcational campaigns it is imperrative that you only create ONE psuedo-trans campaign per type of email and then send that campaign over and over. That's how they are intended to work. Not doing that is going to cause you to fill up your account with a whole bunch of trash campaigns at which point there's no point in using a psuedo-trans campaign since that's the same as creating/sending a regular campaign to a single user over and over.
Do you get any errors?
It seems you are not including the api key, it should look like:
$api = new MCAPI($apikey);
Instead of:
$api = new MCAPI('apikey');
You get the API Key from your api dashboard: http://admin.mailchimp.com/account/api