forked from lightward/mechanic-tasks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsync-order-timeline-comments-to-the-customer-note.json
32 lines (32 loc) · 16.9 KB
/
sync-order-timeline-comments-to-the-customer-note.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
{
"docs": "This task scans all orders (optionally filtering by the query of your choice), and copies any new timeline comments to the customer's note. Useful for getting a snapshot of order activity when looking at the customer's record. Runs manually, hourly, and/or daily.\n\nThis task scans all orders (optionally filtering by the query of your choice), and copies any new timeline comments to the customer's note. Any existing content in the customer note will be preserved; each new comment will be added to the end of the note (or, optionally, to the beginning). Any edited timeline comments will be added as new note lines during the next scan.\r\n\r\nUse the \"Run task\" button to run the scan manually. Or, enable the \"Run daily\" and/or \"Run hourly\" options to have Mechanic run this task automatically.\r\n\r\nNotes:\r\n\r\n* This task uses bulk operations, and therefore operates in two stages: (a) sending the initial query to Shopify, and then (b) processing the results when they come in, as a new event.\r\n* If adding new comments would bring the customer note length past the 5000-character limit, this task will either return an error or ([if configured](https://help.usemechanic.com/en/articles/3297438-can-i-send-messages-to-slack)) send a Slack message with that error message. If it would require trimming less than 1000 characters to bring the new note within the limit, the task will do for that customer, so the next time the task runs.\r\n* Mechanic adds a timestamp to the very end of the customer note, allowing it to skip comments it has already seen during the next run. The task will attempt to avoid duplicates without it, but we don't recommend removing it.",
"halt_action_run_sequence_on_error": false,
"name": "Sync order timeline comments to the customer note",
"online_store_javascript": null,
"options": {
"only_process_customers_matching_this_query": null,
"add_new_comments_to_the_beginning__boolean": true,
"do_not_add_removed_comments_back_in__boolean": null,
"comment_date_format__required": "%d/%m/%y",
"automatically_trim_notes_after_a_one_day_warning__boolean": null,
"send_errors_to_slack__boolean": null,
"slack_incoming_webhook_url": null,
"run_daily__boolean": false,
"run_hourly__boolean": false
},
"order_status_javascript": null,
"perform_action_runs_in_sequence": false,
"script": "{% assign mistaken_order_name_constants = array %}\n{% assign mistaken_order_name_constants[0] = \"\" %}\n{% assign mistaken_order_name_constants[1] = \"N001388836\" %}\n{% assign mistaken_order_name_constants[2] = \"HL244314\" %}\n\n{% if event.topic contains \"mechanic/scheduler/\" or event.topic == \"mechanic/user/trigger\" %}\n {% capture bulk_operation_query %}\n query {\n customers(\n query: {{ options.only_process_customers_matching_this_query | json }}\n ) {\n edges {\n node {\n __typename\n id\n legacyResourceId\n email\n note\n orders {\n edges {\n node {\n __typename\n id\n name\n events(\n query: \"verb:comment\"\n sortKey: CREATED_AT\n ) {\n edges {\n node {\n __typename\n id\n createdAt\n message\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n {% endcapture %}\n\n {% action \"shopify\" %}\n mutation {\n bulkOperationRunQuery(\n query: {{ bulk_operation_query | json }}\n ) {\n bulkOperation {\n id\n status\n }\n userErrors {\n field\n message\n }\n }\n }\n {% endaction %}\n{% elsif event.topic == \"mechanic/shopify/bulk_operation\" %}\n {% assign customers = array %}\n {% assign customer_ids_and_order_comments = hash %}\n {% assign double_newline = newline | append: newline %}\n\n {% for object in bulkOperation.objects %}\n {% case object.__typename %}\n {% when \"CommentEvent\" %}\n {% assign customer = object.__parent.__parent %}\n\n {% if customer_ids_and_order_comments[customer.id] == nil %}\n {% assign customer_ids_and_order_comments[customer.id] = array %}\n {% endif %}\n\n {% assign order_comment = hash %}\n {% assign order_comment[\"created_at\"] = object.createdAt %}\n {% assign order_comment[\"message\"] = object.message %}\n {% assign order_comment[\"order_name\"] = object.__parent.name %}\n\n {% assign _order_comments_count = customer_ids_and_order_comments[customer.id].size %}\n {% assign customer_ids_and_order_comments[customer.id][_order_comments_count] = order_comment %}\n {% when \"Customer\" %}\n {% assign customers[customers.size] = object %}\n {% endcase %}\n {% endfor %}\n\n {% if event.preview %}\n {% assign customers[0] = '{\"id\":\"gid://shopify/Customer/1234567890\",\"note\":\"(existing note content)\"}' | parse_json %}\n\n {% assign order_preview_comment = hash %}\n {% assign order_preview_comment[\"created_at\"] = \"now\" %}\n {% assign order_preview_comment[\"message\"] = \"This is a comment that's been left.\" %}\n {% assign order_preview_comment[\"order_name\"] = \"#1234\" %}\n\n {% assign customer_ids_and_order_comments[\"gid://shopify/Customer/1234567890\"] = array %}\n {% assign customer_ids_and_order_comments[\"gid://shopify/Customer/1234567890\"][0] = order_preview_comment %}\n {% endif %}\n\n {% for customer in customers %}\n {% assign new_order_comments_formatted = array %}\n {% assign reused_note = customer.note %}\n\n {% comment %}\n If we've previously hit the note's max length, there should be a timestamp recorded in the note,\n marking the point in time from which we should start looking for new comments.\n {% endcomment %}\n {% assign minimum_order_comment_created_at_s = nil %}\n {% assign note_lines = customer.note | split: newline %}\n {% for note_line in note_lines %}\n {% assign note_line_parts = note_line | split: \":\" %}\n {% if note_line_parts[0] == \"mechanic\" and note_line_parts[1] == \"timestamp\" %}\n {% assign reused_note = reused_note | replace: note_line, \"\" | strip %}\n\n {% assign minimum_order_comment_created_at_s = note_line_parts[2] | times: 1 %}\n {% if minimum_order_comment_created_at_s == 0 %}\n {% assign minimum_order_comment_created_at_s = nil %}\n {% else %}\n {% break %}\n {% endif %}\n {% endif %}\n {% endfor %}\n\n {% assign newest_order_comment_created_at_s = nil %}\n\n {% assign order_comments_sorted = customer_ids_and_order_comments[customer.id] | sort: \"created_at\" %}\n {% if options.add_new_comments_to_the_beginning__boolean %}\n {% assign order_comments_sorted = order_comments_sorted | reverse %}\n {% endif %}\n\n {% for order_comment in order_comments_sorted %}\n {% assign order_comment_created_at_s = order_comment.created_at | date: \"%s\" | times: 1 %}\n\n {% if options.do_not_add_removed_comments_back_in__boolean %}\n {% if minimum_order_comment_created_at_s != nil and minimum_order_comment_created_at_s >= order_comment_created_at_s %}\n {% continue %}\n {% endif %}\n {% endif %}\n\n {% if newest_order_comment_created_at_s == nil or order_comment_created_at_s > newest_order_comment_created_at_s %}\n {% assign newest_order_comment_created_at_s = order_comment_created_at_s %}\n {% endif %}\n\n {% assign order_comment_message_formatted = order_comment.message | strip | strip_html | prepend: '\"' | append: '\"' %}\n {% assign order_comment_date_formatted = order_comment.created_at | date: options.comment_date_format__required %}\n\n {% assign order_comment_formatted = order_comment_date_formatted | append: \" - \" | append: order_comment_message_formatted | append: \" (\" | append: order_comment.order_name | append: \")\" %}\n\n {% comment %}fix up places where we mistakenly used a constant order name{% endcomment %}\n {% assign tail_with_order_name = '\" (' | append: order_comment.order_name | append: \")\" %}\n {% for mistaken_order_name_constant in mistaken_order_name_constants %}\n {% assign tail_with_constant = '\" (' | append: mistaken_order_name_constant | append: ')' %}\n {% assign order_comment_formatted_with_constant_tail = order_comment_formatted | replace: tail_with_order_name, tail_with_constant %}\n {% assign reused_note = reused_note | replace: order_comment_formatted_with_constant_tail, order_comment_formatted %}\n {% endfor %}\n\n {% if reused_note contains order_comment_formatted %}\n {% assign reused_note_pieces = reused_note | split: order_comment_formatted %}\n\n {% if reused_note_pieces.size > 2 %}\n {% comment %}remove duplicates{% endcomment %}\n {% assign replacement_note_pieces = array %}\n\n {% for piece in reused_note_pieces %}\n {% unless piece == blank %}\n {% assign replacement_note_pieces[replacement_note_pieces.size] = piece | strip %}\n {% endunless %}\n\n {% if options.add_new_comments_to_the_beginning__boolean == true and forloop.last %}\n {% comment %}remove all but the last{% endcomment %}\n {% assign replacement_note_pieces[replacement_note_pieces.size] = order_comment_formatted %}\n {% elsif options.add_new_comments_to_the_beginning__boolean == false and forloop.first %}\n {% comment %}remove all but the first{% endcomment %}\n {% assign replacement_note_pieces[replacement_note_pieces.size] = order_comment_formatted %}\n {% endif %}\n {% endfor %}\n\n {% assign reused_note = replacement_note_pieces | join: double_newline %}\n {% endif %}\n {% else %}\n {% assign new_order_comments_formatted[new_order_comments_formatted.size] = order_comment_formatted | strip %}\n {% endif %}\n {% endfor %}\n\n {% if options.add_new_comments_to_the_beginning__boolean %}\n {% assign updated_note = new_order_comments_formatted | join: double_newline | append: double_newline | append: reused_note | strip %}\n {% else %}\n {% assign updated_note = new_order_comments_formatted | join: double_newline | prepend: double_newline | prepend: reused_note | strip %}\n {% endif %}\n\n {% comment %}\n We perform this check twice. Here, it matters because we've added any new comments we wish to add.\n If none have actually been added, we can safely bail.\n {% endcomment %}\n {% if updated_note == customer.note %}\n {% if options.only_process_customers_matching_this_query != blank %}\n {\"log\": {{ customer.email | append: \": Customer note is unchanged; no new order comments found, and there was no timestamp on the note\" | json }}}\n {% endif %}\n {% continue %}\n {% endif %}\n\n {% assign cache_key = \"flag-customer-for-note-trimming:\" | append: customer.id %}\n {% assign cancel_update = false %}\n\n {% if updated_note.size > 5000 and options.automatically_trim_notes_after_a_one_day_warning__boolean == false %}\n {% comment %}can't handle this automatically; alert slack{% endcomment %}\n {% assign cancel_update = true %}\n {% assign cancel_message = \"could not have new order timeline comments added to their note; the new note would exceed 5000 characters\" %}\n {% elsif updated_note.size > 6000 %}\n {% comment %}can't handle this automatically; alert slack{% endcomment %}\n {% assign cancel_update = true %}\n {% assign cancel_message = \"could not have new order timeline comments added to their note; will not retry with trimming, since trimming would remove more than 1000 characters\" %}\n {% elsif updated_note.size > 5000 and cache[cache_key] != true %}\n {% assign two_days_s = 60 | times: 60 | times: 24 | times: 2 %}\n {% action \"cache\", \"setex\", cache_key, two_days_s, true %}\n {% assign cancel_update = true %}\n {% comment %}will attempt to handle this automatically next time; alert slack{% endcomment %}\n {% assign cancel_message = \"could not have new order timeline comments added to their note; will trim down to 5000 characters during the next scan\" %}\n {% else %}\n {% comment %}\n If we're here, we're either under the character limit, or we're over it *and* we're clear to\n trim it. We add a timestamp noting the creation time of the newest comment; the next time we\n scan, we'll only look at comments that arrive after this timestamp.\n {% endcomment %}\n {% assign timestamp_line = newest_order_comment_created_at_s | default: minimum_order_comment_created_at_s | prepend: \"mechanic:timestamp:\" %}\n\n {% comment %}\n Perform slicing if necessary, but only if necessary - this action is destructive for strings\n under the limit, too.\n {% endcomment %}\n {% if updated_note.size > 5000 %}\n {% comment %}\n The timestamp line is 29 characters, plus a double newline is 31. From 5000, that leaves 4969.\n We trim *away* from the spot where new comments are added.\n {% endcomment %}\n {% if options.add_new_comments_to_the_beginning__boolean %}\n {% assign updated_note = updated_note | slice: 0, 4969 %}\n {% else %}\n {% assign updated_note = updated_note | slice: -4969, 4969 %}\n {% endif %}\n {% endif %}\n\n {% assign updated_note = updated_note | append: double_newline | append: timestamp_line %}\n\n {% if cache[cache_key] %}\n {% comment %}\n This approval is only good once. If we're here, and this approval exists, we've used it and\n should clear it at this time.\n {% endcomment %}\n {% action \"cache\", \"del\", cache_key %}\n {% endif %}\n {% endif %}\n\n {% comment %}\n The second check. Here, it matters because we've executed on any trimming-related activity\n necessary, and the result may not actually differ from the original note, rendering an update moot.\n {% endcomment %}\n {% if updated_note == customer.note %}\n {% if options.only_process_customers_matching_this_query != blank %}\n {\"log\": {{ customer.email | append: \": Customer note is unchanged\" | json }}}\n {% endif %}\n {% continue %}\n {% endif %}\n\n {% if cancel_update %}\n {\n \"log\": {\n \"customer_id\": {{ customer.id | json }},\n \"order_comments\": {{ order_comments_sorted | json }},\n \"existing_note\": {{ customer.note | json }},\n \"existing_note_size\": {{ customer.note.size | json }},\n \"updated_note\": {{ updated_note | json }},\n \"updated_note_size\": {{ updated_note.size | json }}\n }\n }\n\n {% assign message = \"Notice for \" | append: customer.email | append: \": \" | append: cancel_message | append: newline | append: newline | append: \"Manage this customer in Shopify: https://\" | append: shop.domain | append: \"/admin/customers/\" | append: customer.legacyResourceId %}\n\n {% if options.send_errors_to_slack__boolean and options.slack_incoming_webhook_url != blank %}\n {% action \"http\" %}\n {\n \"method\": \"post\",\n \"url\": {{ options.slack_incoming_webhook_url | json }},\n \"body\": {\n \"text\": {{ message | json }}\n }\n }\n {% endaction %}\n {% else %}\n {% action \"echo\" %}\n {\"error\": {{ message | json }}}\n {% endaction %}\n {% endif %}\n {% else %}\n {% comment %}\n Just in case something goes horribly wrong, we record the existing customer note. :)\n {% endcomment %}\n {\"log\": {\"customer_id\": {{ customer.id | json }}, \"existing_note\": {{ customer.note | json }}}}\n\n {% action \"shopify\" %}\n mutation {\n customerUpdate(\n input: {\n id: {{ customer.id | json }}\n note: {{ updated_note | json }}\n }\n ) {\n customer {\n note\n }\n userErrors{\n field\n message\n }\n }\n }\n {% endaction %}\n {% endif %}\n {% endfor %}\n{% endif %}",
"subscriptions": [
"mechanic/user/trigger",
"mechanic/shopify/bulk_operation"
],
"subscriptions_template": "{% if options.run_daily__boolean %}mechanic/scheduler/daily{% endif %}\n{% if options.run_hourly__boolean %}mechanic/scheduler/hourly{% endif %}\nmechanic/user/trigger\nmechanic/shopify/bulk_operation",
"tags": [
"Comments",
"Customer Notes",
"Orders",
"Sync",
"Timeline"
]
}