Shopware 6: how to prove if product has variants - shopware6

If I call a product, I will check if the product has variants.
Currently, I make it with an additional request using product.id
const criteria = new Criteria();
criteria.setLimit(1);
criteria.addFilter(
Criteria.equals('product.parentId', this.product.id)
);
this.productRepository
.search(criteria)
.then((result) => {
...
});
I can't find a suitable attribute (field) like e.g. product.hasVariant.
I think this is a simple parent:child relationship. I'm wondering if the only way to achieve this goal is in its children (which have the product.parentId field).
Question:
— Is there an attribute, which define, if product has variants?
— … or how to define, if a product has variants

Yes, there is a field called childCount.
JS:
criteria.addFilter(Criteria.range('childCount', { gt: 0 }));
API:
{
"filter": [
{
"type": "range",
"field": "childCount",
"parameters": {
"gt": 0
}
}
]
}

Related

Shopware 6: how to delete all products via admin api

How to delete all products via admin api?
To achieve the goal i try to use the Bulk Payloads | Deleting entities
The doc says:
[...] To delete entities, the payload of an operation contains the IDs. [...]
Questions:
to delete all products i have to read first all product.id's?
or is there a alternative way with a type of "wildcard"?
My current request body (using Postman) ...:
{
"delete-product": {
"entity": "product",
"action": "delete",
"payload": []
}
}
... response with (products remains in db):
{
"extensions": [],
"success": true,
"data": {
"delete-product": {
"extensions": [],
"result": []
}
},
"deleted": [],
"notFound": []
}
EDIT #1
With id's provided...:
...
const obj = {
"delete-products": {
"entity": "product",
"action": "delete",
"payload": [
{"id": "73af65014974440b95450f471b3afed8"},
{"id": "784f25a29e034fad9a416923f964ba8a"}
]
}
}
apiClient.request({
"url": "/_action/sync",
"method": "POST",
obj
})
...
... the request fails in class Symfony\\Component\\Serializer\\Encoder\\JsonDecode with message:
detail: "Syntax error"
Debugging the request, payload is missing (empty content):
What is wrong with the configuration of the /api/_action/sync call?
Indeed, what it means is that you will need a low impacting query to get all product id's, store it into a variable & delete them. Use includes:["id"] filter to just get the ID's.
Here is an example of me deleting some products in Postman.
Request body:
{
"delete-product": {
"entity": "product",
"action": "delete",
"payload": {{gen_dynamic_products}}
}
}
Pre-request script (you'll need to adjust this sightly to get your ID's):
const map = new Array(30).fill(0).map((val, index) => {
return { id: pm.environment.get('gen_product_list_sub_' + index) };
});
pm.variables.set('gen_dynamic_products', JSON.stringify(map));
to delete all products i have to read first all product.id's?
Yes, that is what you'll have to do. This is necessary to maintain the extendibility of the platform. The core or other plugins may react to the deletion of products by subscribing to an entity lifecycle event. This event includes the id of the deleted entity. Hence why it is necessary to explicitly provide the ids of the entities in the first place.

How not to expose duplicated (normalize?) nodes via GraphQL?

Given "user has many links" (what means a link was created by a user) DB entities relations, I want to develop API to fetch links along with users so that the returned data does not contain duplicated users.
In other words, instead of this request:
query {
links {
id
user {
id email
}
}
}
that returns the following data:
{
"data": {
"links": [
{
"id": 1,
"user": {
"id": 2,
"email": "user2#example.com"
}
},
{
"id": 2,
"user": {
"id": 2,
"email": "user2#example.com"
}
}
]
}
}
I want to make a request like this (note the "references" column):
query {
links {
id
userId
}
references {
users {
id
email
}
}
}
that returns associated users without duplicates:
{
"data": {
"links": [
{
"id": 1,
"userId": 2
},
{
"id": 2,
"userId": 2
},
],
"references": {
"users": [
{
"id": 2,
"email": "user2#example.com"
}
]
}
}
}
That should reduce amount of data transferred between client and server that adds a bit of speed boost.
Is there ready common implementation on any language of that idea? (Ideally, seeking for Ruby)
It's not a query or server role to normalize data.
there are no such possibilities in GraphQL specs;
server must return all asked fields within queried [response] structure;
... but you can implement some:
standarized (commonly used) pagination (relay style edges/nodes, nodes only or better both);
query [complexity] weights to promote this optimized querying style - separate problem;
reference dictionary field within queried type;
links {
egdes {
node {
id
title
url
authorId
# possible but limited usage with heavy weights
# author {
# id
# email
# }
}
}
pageInfo {
hasNextPages
}
referencedUsers {
id
email
}
}
where:
User has id and email props;
referencedUsers is [User!] type;
node.author is User type;
Normalizing Graphql client, like Apollo, can easily access cached user fields without making separate requests.
You can render (react?) some <User/> component (within <Link /> component) passing node.authorId as an argument like <User id={authorId} />. User component can useQuery hook with cache-only policy to read user props/fields.
See Apollo docs for details. You should implement this for yourself and document this to help/guide API users.

Removing join table data in sequelize returned value

I am currently trying to remove a joint table data added when retrieving an association data.
The query is done by sequelize using a method added to the model through specifying model relationships(sequelize magic methods), for some reason, I'm not able to do that.
I have currently tried passing in attributes: {exclude: ['...']} to the method but the field still persists.
Current association
// Class sequelize model
Class.belongsToMany(models.Subject, {
through: 'ClassSubject',
foreignKey: 'class_id',
otherKey: 'subject_id',
as: 'subjects'
})
// Subject sequelize model
Subject.belongsToMany(models.Class, {
through: 'ClassSubject',
foreignKey: 'subject_id',
otherKey: 'class_id',
as: 'classes'
});
Query and Response
const subjects = await dbClass.getSubjects(); // dbClass is a Class model instance
// Response
[
{
"id": "1b89d44c-2caa-452d-a1f8-7faa11970917",
"name": "Mathematics",
"code": "MATHS",
"summary": "Mathematics for class 1",
"ClassSubject": {
"class_id": "637afc7b-40f6-478e-b35e-859ca462e2e7",
"subject_id": "1b89d44c-2caa-452d-a1f8-7faa11970917"
}
}
]
Desired output
// Response
[
{
"id": "1b89d44c-2caa-452d-a1f8-7faa11970917",
"name": "Mathematics",
"code": "MATHS",
"summary": "Mathematics for class 1"
}
]
I have tried passing options to the method as specified below but to no avail
const subjects = await dbClass.getSubjects({
attributes: { exclude: ['ClassSubject'] }
});
But it still doesn't work.
Try using the joinTableAttributes option and pass empty array to exclude everything in joint table.
const subjects = await dbClass.getSubjects({ joinTableAttributes: [] });

updating inventory quantity with PUT returns error

Here is the body
{
"product": {
"id": 1202316036,
"title": "cricket bat for sale",
"variants":[
{
"inventory_quantity": 500
}
]
}
}
This returns the following error
{
"errors": {
"base": [
"The variant 'Default Title' already exists."
]
}
}
But where as the updating the title seems to be working fine. Here is the body
{
"product": {
"id": 1202316036,
"title": "cricket bat for sale"
}
}
I am sure that PUT header(Content-Type: application/json) are set properly. Because updating title does work. How should I go about updating inventory management
ps: I am using POSTMAN for using shopify API
So you do need the variant id otherwise Shopify thinks you are creating a new variant. Also your variants need to have been set up for Shopify to manage their inventory. e.g.
var product = {
product:{
id: productId,
variants: [
{
id:5991257025,
inventory_management : "shopify",
inventory_quantity:20
},
{
id:5991257089,
inventory_management : "shopify",
inventory_quantity:26
}
]
}
};
I'm not sure if you can do multiple variants per call but to update a single variant's inventory quantity you'd do it like:
var payload = JSON.stringify({
variant: {
id: variantId,
inventory_quantity: qty
}
});
and then put that to "https://myshopifydomain/admin/variants/" +variantId + ".json";
possibly all you need to do is add the variant id for each variant you are updating. Your variant ids can be gotten by GETting the json for your items.

Ember-data hasMany relationship not working (JSONAPIAdapter)

I'm using Ember-Data v.1.13.9 with Ember-CLI v.1.13.8. I'm using the JSONAPIAdapter adapter.
I have a problem with a hasMany relationship. I can see from the Ember inspector that both the main record and the related record are being loaded into the store. However, the relationship doesn't seem to be there since I cannot access the related records details in my template.
models/invoice.js
export default DS.Model.extend(
{
invNum : DS.attr('string'),
created : DS.attr('date', {defaultValue: function() { return new Date(); }}),
clientId : DS.attr('number'),
userId : DS.attr('number'),
details : DS.hasMany('invoice-detail', {async : true}),
});
models/invoice-detail.js
export default DS.Model.extend(
{
invoice : DS.belongsTo('invoice', {async : true}),
detail : DS.attr('string'),
amount : DS.attr('number'),
vat : DS.attr('number'),
});
my JSON data: (URL: /accounts/invoices/1)
{
"data": {
"id": 1,
"attributes": {
"inv-num": "A0011000001",
"created": "November, 01 2000 00:00:00",
"user-id": 2,
"client-id": 14,
"relationships": {
"details": {
"data": [
{
"id": 1,
"type": "invoice-detail"
}
]
}
}
},
"type": "invoice"
},
"included": [
{
"id": 1,
"attributes": {
"amount": 3000,
"detail": "Stage 1 delivery of 3Com Reseller Locator to\r\nFoundation Network LTD",
"vat": 525
},
"type": "invoice-detail"
}
]
}
I've tried accessing the details related array directly:
{{#each model.details as |detail index|}}
{{index}} : {{detail.detail}} £{{detail.amount}} (£{{detail.vat}} vat)
{{/each}}
And by using a controller: invoice/controller.js
export default Ember.Controller.extend({
invoiceDetails : function()
{
var invoice = this.get("model");
var details = invoice.get("details");
Ember.Logger.log("invoiceDetails",invoice,details);
return details;
}.property('model.details'),
});
and
{{#each invoiceDetails as |detail index|}}
{{index}} : {{detail.detail}} £{{detail.amount}} (£{{detail.vat}} vat)
{{/each}}
Neither is providing me with the data that I require.
What am I doing wrong?
A second related issue I am having is that I can't get it to reload data from the server. the {reload:true} makes no difference. Looking at the network traffic I can see that no call to the server is made for second and subsequent visits to this route.
invoice/route.js
export default Ember.Route.extend({
model: function(params) {
return this.store.findRecord('invoice', params.id, { reload: true });
}
})
What I actually want to do here is have one route which retrieves a list of invoices (without the details part - so it's quick to retrieve since I do not need the details on the list page). Then, when I drill down to a specific invoice, make a call to the server to get the full details for that invoice. My plan was to use the shouldReloadRecord function to check if I have details attached to this record or not. If so, use the copy from the store, if not, go to the server and then overwrite the limited "list" record I got initially. As a stepping stone in that direction I figured that just setting {reload:true} in the route would force all requests to go back to the server.
I guess I've misunderstood something somewhere...?