forked from lightward/mechanic-tasks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsync-inventory-across-product-variants.json
53 lines (53 loc) · 14.9 KB
/
sync-inventory-across-product-variants.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
{
"docs": "Useful for multiple price points, or for offering customizations of the same item, this task lets you offer multiple variant listings for what is ultimately the same stock. A purchase of a particular variant results in the inventory for all other variants, for the same product, being lowered by the amount ordered.\n\n### Getting started\n\n1. In the Shopify admin, navigate to the Products > Inventory area. Use the tools here to ensure that all products you wish to monitor have the same \"available\" level for all of their variants at your default location.\n2. In this task, populate the list of product tags or types to monitor (but not both!).\n3. Click the \"Run task\" button. Mechanic will scan your products, and cache the current available inventory level for each one.\n4. Wait! :) Every ten minutes, Mechanic will check your inventory, and make any adjustments necessary to keep everything in sync. For example, if three different inventory items - within the same product - are each sold three different times, Mechanic will ensure that each of those items are lowered by a further 6, and that all others are lowered by 9.\n\n### Notes\n\n* This task only counts and adjusts available inventory at the default location configured for your shop.\n* To manually change inventory levels for a product, adjust _only one_ variant to the desired level. During the next scheduled run, the task will bring the other variants into sync.\n* By default, Mechanic will check your inventory every 10 minutes. Feel free to change that subscription to \"mechanic/scheduler/hourly\", or [something else that suits your needs](https://learn.mechanic.dev/platform/events/topics#scheduler).\n* If this task encounters issues syncing inventory for a product's variants, it will continue processing all other products if possible, and then log out an error with all of the products it cound not sync. You may optionally add the [Error reporter](https://tasks.mechanic.dev/error-reporter) task to your Mechanic instance if you would like to receive email notifications for these errors.\n* If this task encounters products that have not yet had their inventory quantity cached, it will send them collectively to a custom event which runs in the same manner as a manual run, excepting that only these products will be processed to see if their cache entries can be set.",
"halt_action_run_sequence_on_error": false,
"name": "Sync inventory across product variants",
"online_store_javascript": null,
"options": {
"product_tags_to_monitor__array": null,
"product_types_to_monitor__array": null,
"only_sync_active_products__boolean": false
},
"order_status_javascript": null,
"perform_action_runs_in_sequence": false,
"preview_event_definitions": [
{
"description": "Preview data",
"event_attributes": {
"data": {
"products_missing_cache": {
"gid://shopify/Product/1234567890": [
{
"id": "gid://shopify/ProductVariant/1234567890",
"inventoryItem": {
"id": "gid://shopify/InventoryItem/1234567890",
"inventoryLevel": {
"quantities": [
{
"quantity": 30
}
]
}
}
}
]
}
},
"topic": "user/sync_variant_inventory/set_cache"
}
}
],
"script": "{% assign product_tags = options.product_tags_to_monitor__array %}\n{% assign product_types = options.product_types_to_monitor__array %}\n{% assign only_sync_active_products = options.only_sync_active_products__boolean %}\n\n{% assign primary_location = shop.locations[shop.primary_location_id] %}\n\n{% if product_tags == blank and product_types == blank %}\n {% error \"You must choose to monitor products either by tags or types.\" %}\n{% elsif product_tags != blank and product_types != blank %}\n {% error \"Choose to monitor products either by tags or types, but not both.\" %}\n{% endif %}\n\n{% if event.topic == \"mechanic/user/trigger\" or event.topic contains \"mechanic/scheduler/\" %}\n {% comment %}\n -- run query for all variants matched by product tags or types\n {% endcomment %}\n\n {% assign variants_by_product = hash %}\n {% assign cursor = nil %}\n {% assign search_query_parts = array %}\n\n {% for product_type in product_types %}\n {% assign search_query_parts[search_query_parts.size] = product_type | json | prepend: \"product_type:\" %}\n {% endfor %}\n\n {% for product_tag in product_tags %}\n {% assign search_query_parts[search_query_parts.size] = product_tag | json | prepend: \"tag:\" %}\n {% endfor %}\n\n {% capture search_query -%}\n location_id:{{ shop.primary_location_id }} ({{ search_query_parts | join: \" OR \" }}) managed:true\n {%- endcapture %}\n\n {% if only_sync_active_products %}\n {% assign search_query = search_query | append: \" product_status:active\" %}\n {% endif %}\n\n {% for n in (0..200) %}\n {% capture query %}\n query {\n productVariants(\n first: 150\n query: {{ search_query | json }}\n after: {{ cursor | json }}\n ) {\n pageInfo {\n hasNextPage\n endCursor\n }\n nodes {\n id\n inventoryItem {\n id\n inventoryLevel(locationId: {{ primary_location.admin_graphql_api_id | json }}) {\n quantities(names: \"available\") {\n name\n quantity\n }\n }\n }\n product {\n id\n }\n }\n }\n }\n {% endcapture %}\n\n {% assign result = query | shopify %}\n\n {% if event.preview %}\n {% capture result_json %}\n {\n \"data\": {\n \"productVariants\": {\n \"nodes\": [\n {\n \"id\": \"gid://shopify/ProductVariant/1234567890\",\n \"inventoryItem\": {\n \"id\": \"gid://shopify/InventoryItem/1234567890\",\n \"inventoryLevel\": {\n \"quantities\": [\n {\n \"name\": \"available\",\n \"quantity\": 30\n }\n ]\n }\n },\n \"product\": {\n \"id\": \"gid://shopify/Product/1234567890\"\n }\n },\n {\n \"id\": \"gid://shopify/ProductVariant/2345678901\",\n \"inventoryItem\": {\n \"id\": \"gid://shopify/InventoryItem/2345678901\",\n \"inventoryLevel\": {\n \"quantities\": [\n {\n \"name\": \"available\",\n \"quantity\": {% if event.topic == \"mechanic/user/trigger\" %}30{% else %}31{% endif %}\n }\n ]\n }\n },\n \"product\": {\n \"id\": \"gid://shopify/Product/1234567890\"\n }\n }\n ]\n }\n }\n }\n {% endcapture %}\n\n {% assign result = result_json | parse_json %}\n {% endif %}\n\n {% for variant in result.data.productVariants.nodes %}\n {% assign variants_by_product[variant.product.id]\n = variants_by_product[variant.product.id]\n | default: array\n | push: variant\n %}\n {% endfor %}\n\n {% if result.data.productVariants.pageInfo.hasNextPage %}\n {% assign cursor = result.data.productVariants.pageInfo.endCursor %}\n {% else %}\n {% break %}\n {% endif %}\n {% endfor %}\n\n {% if variants_by_product == blank %}\n {% error\n message: \"No matching product variants found! Check your product tag or type settings for this task.\",\n search_query: search_query\n %}\n {% break %}\n {% endif %}\n\n{% elsif event.topic == \"user/sync_variant_inventory/set_cache\" %}\n {% comment %}\n -- this user event is called from the scheduler event, to process any products without a cache entry\n {% endcomment %}\n\n {% if event.data.products_missing_cache == blank %}\n {% error \"No products with missing cache were passed to this event.\" %}\n {% endif %}\n\n {% assign variants_by_product = event.data.products_missing_cache %}\n{% endif %}\n\n{% if event.topic == \"mechanic/user/trigger\" or event.topic == \"user/sync_variant_inventory/set_cache\" %}\n {% comment %}\n -- this event is run manually for initial setup, but will also be triggered via a custom event to handle any products that don't yet have a cache setting (typically new products, but can be existing ones if their cache expires or if the task configuration is changed)\n {% endcomment %}\n\n {% assign products_out_of_sync = array %}\n\n {% for pair in variants_by_product %}\n {% assign product_id = pair[0] %}\n {% assign variants = pair[1] %}\n\n {% assign available_quantites = array %}\n\n {% for variant in variants %}\n {% assign available_quantites = available_quantites | push: variant.inventoryItem.inventoryLevel.quantities.first.quantity %}\n {% endfor %}\n\n {% assign inventory_total = available_quantites | sum %}\n {% assign expected_inventory_total = available_quantites.first | times: available_quantites.size %}\n\n {% if inventory_total != expected_inventory_total %}\n {% assign product_out_of_sync = hash %}\n {% assign product_out_of_sync[\"product_id\"] = product_id %}\n {% assign product_out_of_sync[\"expected_inventory_total\"] = expected_inventory_total %}\n {% assign product_out_of_sync[\"current_inventory_total\"] = inventory_total %}\n {% assign product_out_of_sync[\"available_quantites\"] = available_quantites %}\n {% assign products_out_of_sync = products_out_of_sync | push: product_out_of_sync %}\n\n {% else %}\n {% assign cache_key = \"inventory_by_product:\" | append: product_id %}\n {% action \"cache\", \"set\", cache_key, available_quantites.first %}\n {% endif %}\n {% endfor %}\n\n {% if products_out_of_sync != blank %}\n {% action \"echo\"\n __error: \"Variant inventory levels are not in sync for these products. Manually ensure everything is at the same level so they may be managed by this task.\",\n products_out_of_sync: products_out_of_sync\n %}\n {% endif %}\n\n{% elsif event.topic contains \"mechanic/scheduler/\" %}\n {% assign inventory_adjustments = array %}\n {% assign products_missing_cache = hash %}\n\n {% for pair in variants_by_product %}\n {% assign product_id = pair[0] %}\n {% assign variants = pair[1] %}\n\n {% assign cache_key = \"inventory_by_product:\" | append: product_id %}\n {% assign inventory_old = cache[cache_key] %}\n\n {% if event.preview %}\n {% assign inventory_old = 30 %}\n {% endif %}\n\n {% if inventory_old == blank %}\n {% comment %}\n -- if no cache has been set for this product yet, then save it for later processing and move to next product\n {% endcomment %}\n\n {% assign products_missing_cache[product_id] = variants %}\n {% continue %}\n {% endif %}\n\n {% assign available_quantites = array %}\n\n {% for variant in variants %}\n {% assign available_quantites = available_quantites | push: variant.inventoryItem.inventoryLevel.quantities.first.quantity %}\n {% endfor %}\n\n {% assign inventory_total_old = inventory_old | times: available_quantites.size %}\n {% assign inventory_total_new = available_quantites | sum %}\n {% assign inventory_total_diff = inventory_total_new | minus: inventory_total_old %}\n {% assign inventory_new = inventory_old | plus: inventory_total_diff %}\n\n {% if inventory_new == inventory_old %}\n {% log\n message: \"No inventory adjustments needed for this product.\",\n product_id: product_id\n %}\n {% continue %}\n {% endif %}\n\n {% log\n message: \"Adjusting inventory for this product.\",\n inventory_old: inventory_old,\n inventory_total_old: inventory_total_old,\n inventory_total_new: inventory_total_new,\n inventory_total_diff: inventory_total_diff,\n inventory_new: inventory_new,\n product_id: product_id,\n variants_count: variants.size\n %}\n\n {% action \"cache\", \"set\", cache_key, inventory_new %}\n\n {% for variant in variants %}\n {% assign inventory_adjustment = hash %}\n {% assign inventory_adjustment[\"inventoryItemId\"] = variant.inventoryItem.id %}\n {% assign inventory_adjustment[\"locationId\"] = primary_location.admin_graphql_api_id %}\n {% assign inventory_adjustment[\"delta\"] = inventory_new | minus: variant.inventoryItem.inventoryLevel.quantities.first.quantity %}\n {% assign inventory_adjustments = inventory_adjustments | push: inventory_adjustment %}\n {% endfor %}\n {% endfor %}\n\n {% if inventory_adjustments != blank %}\n {% assign groups_of_inventory_adjustments = inventory_adjustments | in_groups_of: 250, fill_with: false %}\n\n {% for group_of_inventory_adjustments in groups_of_inventory_adjustments %}\n {% action \"shopify\" %}\n mutation {\n inventoryAdjustQuantities(\n input: {\n reason: \"correction\"\n name: \"available\"\n changes: {{ group_of_inventory_adjustments | graphql_arguments }}\n }\n ) {\n inventoryAdjustmentGroup {\n reason\n changes {\n name\n delta\n quantityAfterChange\n item {\n id\n sku\n }\n location {\n name\n }\n }\n }\n userErrors {\n code\n field\n message\n }\n }\n }\n {% endaction %}\n {% endfor %}\n {% endif %}\n\n {% if products_missing_cache != blank %}\n {% assign product_ids = products_missing_cache | keys %}\n\n {% log\n message: \"Found these products without cache entries. Sending them to custom event to set caches if possible.\",\n product_ids: product_ids\n %}\n\n {% action \"event\" %}\n {\n \"topic\": \"user/sync_variant_inventory/set_cache\",\n \"task_id\": {{ task.id | json }},\n \"data\": {\n \"products_missing_cache\": {{ products_missing_cache | json }}\n }\n }\n {% endaction %}\n {% endif %}\n{% endif %}\n",
"subscriptions": [
"mechanic/user/trigger",
"mechanic/scheduler/10min",
"user/sync_variant_inventory/set_cache"
],
"subscriptions_template": "mechanic/user/trigger\nmechanic/scheduler/10min\nuser/sync_variant_inventory/set_cache",
"tags": [
"Inventory",
"Products",
"Sync",
"Variants"
]
}