Skip to content

Torgash 0.5.13

Choose a tag to compare

@extago extago released this 14 Nov 23:55
· 2 commits to main since this release

What's new

In short: two new modules count the shop's visitors — Yandex Metrica and Google Analytics — and tell them what was viewed, put into the basket and bought. A backup can be cut into volumes, so a site bigger than the server's free disk is backed up all the same. A CRM can mark an order's payment through the API, and orders are no longer imported from files.

Yandex Metrica (new module)

  • Install it in Modules → Yandex Metrica and fill in "Counter number" — the number inside ym(…) in the counter's code. Webvisor, the click map, external links and downloads, the accurate bounce rate and changes after # are on, as in Metrica's own code; each can be switched off.
  • E-commerce: a product viewed, put into and taken out of the basket, an order placed — with the brand, the category and the price. Switch e-commerce on in the counter's settings in Metrica too, with the container dataLayerYM. Metrica does not convert currencies, so every sum goes in "Currency of the counter", converted at the shop's rate.
  • Goals under the identifiers shops already use: basket, order (its sum is the goal's revenue), wishlist, buy_with_one_click_form_opened, call_request. In Metrica they are goals of the "JavaScript event" kind with these identifiers.
  • "Show more" under a list is counted as a view of the page it opened.
  • The click map and Webvisor recordings show the storefront inside Metrica with nothing to set up. The admin is never shown there.

Google Analytics (new module)

  • Install it in Modules → Google Analytics and fill in the measurement ID (G-…) or a Google Tag Manager container (GTM-…).
  • GA4's recommended e-commerce events: a product viewed, put into and taken out of the basket, added to the wishlist, a checkout begun, a purchase — with delivery, the coupon and the order's number.
  • "Forms that are a lead" chooses which forms count as a lead; a call back and a question about a product are ticked.
  • A product is named in the events by its code (SKU) or by its number in the shop.

Both counters

  • Consent. Where the shop asks visitors for consent (the Personal data module), a counter starts only for visitors who allowed "Statistics". It starts on the same page the moment they agree, so that visit is counted too.
  • To count everyone, as a counter in Code snippets under "Necessary" does: untick "Wait for the visitor's consent" (Metrica) or choose "Do not wait — count everyone" (Google).
  • Google can also load at once under Google Consent Mode, while "Google Consent Mode v2" is on in Personal data.
  • Whether the law where the shop sells allows counting without consent is the shop's decision.
  • The visitor's ClientID on the order, for a CRM: tick "Yandex Metrica ClientID" or "Google Analytics client ID" in Settings → Checkout → "What an order writes down about the buyer's browser" (for enquiries, in the Enquiries settings). It is shown on the order's page, given by the API and exported as a column of its own.
  • A manager looking at the shop as a customer is not counted.

Backups in volumes

  • "Volumes" in a backup plan (System → Backups, the plan's form; tar and tar.gz): one file, 512 MB, 1 GB or your own size. Each volume goes to every storage of the plan as soon as it is full and is deleted from the server before the next one is begun. The server needs room for one volume, not for the whole backup, and a dropped connection costs one volume.
  • Put together, the volumes are an ordinary tar.gz (encrypted, if the plan encrypts): cat name.tar.gz.* > name.tar.gz, copy /b on Windows, or open the .001 in 7-Zip.
  • Restoring, checking, "Send again", the download (volume by volume) and the installer on a new server know a set by any of its files.
  • A backup the server's disk cannot hold is refused before packing, saying how much room it needs and how much is free.
  • An encrypted tar no longer needs room for a second copy while it is encrypted, checked or restored.

Orders and a CRM

  • A CRM can mark an order's payment through the API, the way the payment control on the order's page does: paid, partially paid, a payment marked by mistake taken back off, money refunded outside the site.
  • The order's history names the API key. The same state sent again changes nothing, so a CRM can send its whole state as often as it likes.
  • Orders are exported, not imported. The Import screen and the console no longer offer orders, and an unfinished import of orders is dropped when opened.
  • Why: written from a file, the columns broke orders. The morning's export loaded in the evening put its total over a product added at noon; an empty cell made the total 0 and erased the number and the e-mail; "1500.00" became 15.00.
  • A CRM changes statuses and payments through the API, which does it the way the order's page does.

Fixed

  • A status change through the API to a status that does not exist, or of a merged order, is answered with an explanation instead of an error.

Good to know

  • If the counter is already in Code snippets, delete it there after installing the module, or every visit is counted twice. To keep counting everyone, as now, untick "Wait for the visitor's consent" (Metrica) or choose "Do not wait — count everyone" (Google).
  • The click map and Webvisor stay empty if the web server adds its own X-Frame-Options header. Remove it from the server's settings; the shop sends what Metrica needs itself.
  • For developers: the storefront announces what happens on it as browser events — torgash:cart-changed, torgash:checkout-started, torgash:order-placed and others (docs/architecture/storefront.md). A pixel of another service in Code snippets can listen to them.

Что нового

Главное: два новых модуля считают посетителей магазина — Яндекс Метрика и Google Analytics — и сообщают им, что смотрели, клали в корзину и купили. Резервную копию можно резать на тома, поэтому сайт больше свободного места на сервере всё равно копируется. CRM может отмечать оплату заказа через API, а заказы больше не загружаются из файлов.

Яндекс Метрика (новый модуль)

  • Установите его в Модули → Яндекс Метрика и заполните «Номер счётчика» — число внутри ym(…) в коде счётчика. Вебвизор, карта кликов, внешние ссылки и загрузки файлов, точный показатель отказов и изменения после # включены, как в коде самой Метрики; каждое можно выключить.
  • Электронная коммерция: просмотр товара, добавление в корзину и удаление из неё, оформленный заказ — с брендом, категорией и ценой. Включите электронную коммерцию и в настройках счётчика в Метрике, с контейнером dataLayerYM. Метрика не пересчитывает валюты, поэтому все суммы уходят в «Валюте счётчика» по курсу магазина.
  • Цели с идентификаторами, к которым магазины привыкли: basket, order (сумма заказа — доход цели), wishlist, buy_with_one_click_form_opened, call_request. В Метрике это цели типа «JavaScript-событие» с этими идентификаторами.
  • «Показать ещё» под списком считается просмотром открытой им страницы.
  • Карта кликов и записи Вебвизора показывают витрину внутри Метрики без всякой настройки. Админка там не показывается никогда.

Google Analytics (новый модуль)

  • Установите его в Модули → Google Analytics и заполните идентификатор потока (G-…) или контейнер Google Tag Manager (GTM-…).
  • Рекомендованные события электронной коммерции GA4: просмотр товара, добавление в корзину и удаление из неё, добавление в избранное, начало оформления, покупка — с доставкой, купоном и номером заказа.
  • «Какие формы считать лидом» — выбор форм, которые считаются лидом; обратный звонок и вопрос о товаре отмечены.
  • Товар в событиях называется артикулом (SKU) или номером в магазине.

Оба счётчика

  • Согласие. Где магазин спрашивает согласие посетителей (модуль «Персональные данные»), счётчик запускается только у тех, кто разрешил «Статистику». Запускается на той же странице в момент согласия, так что и этот визит посчитан.
  • Чтобы считать всех — как счётчик в «Коде на страницах» в категории «Необходимые», — снимите «Ждать согласия посетителя» (Метрика) или выберите «Не ждать — считать всех» (Google).
  • Google может ещё загружаться сразу в режиме Google Consent Mode, пока в «Персональных данных» включён «Google Consent Mode v2».
  • Позволяет ли закон там, где продаёт магазин, считать без согласия, решает магазин.
  • ClientID посетителя в заказе — для CRM: отметьте «ClientID Яндекс Метрики» или «Client ID Google Analytics» в Настройки → Оформление заказа → «Что заказ запоминает о браузере покупателя» (для обращений — в настройках «Заявок»). Он виден на странице заказа, отдаётся через API и выгружается отдельной колонкой.
  • Менеджер, который смотрит магазин глазами покупателя, не считается.

Резервные копии томами

  • «Тома» в задании копии (Система → Резервные копии, форма задания; tar и tar.gz): одним файлом, 512 МБ, 1 ГБ или свой размер. Каждый том уходит во все хранилища задания, как только набран, и удаляется с сервера до начала следующего. Серверу нужно место на один том, а не на всю копию, а оборванное соединение стоит одного тома.
  • Склеенные тома — обычный tar.gz (зашифрованный, если задание шифрует): cat name.tar.gz.* > name.tar.gz, copy /b в Windows или откройте .001 в 7-Zip.
  • Восстановление, проверка, «Отправить ещё раз», скачивание (по тому) и установщик на новом сервере узнают набор по любому его файлу.
  • Копия, которая не поместится на диск сервера, отклоняется до упаковки — с тем, сколько места нужно и сколько свободно.
  • Зашифрованному tar больше не нужно место на вторую копию при шифровании, проверке и восстановлении.

Заказы и CRM

  • CRM может отмечать оплату заказа через API — как это делает блок оплаты на странице заказа: оплачен, оплачен частично, ошибочно отмеченная оплата снята, деньги возвращены вне сайта.
  • В истории заказа указан ключ API. То же состояние, присланное повторно, ничего не меняет, так что CRM может присылать всё своё состояние сколько угодно часто.
  • Заказы выгружаются, но не загружаются. Экран импорта и консоль больше не предлагают заказы, а незаконченный импорт заказов при открытии удаляется.
  • Почему: записанные из файла колонки ломали заказы. Утренняя выгрузка, загруженная вечером, писала свой итог поверх товара, добавленного днём; пустая ячейка делала итог 0 и стирала номер и e-mail; «1500.00» становилось 15,00.
  • Статусы и оплату CRM меняет через API, который делает это так же, как страница заказа.

Исправлено

  • Смена статуса через API на несуществующий статус или у объединённого заказа отвечает объяснением, а не ошибкой.

Полезно знать

  • Если счётчик уже стоит в «Коде на страницах», после установки модуля удалите его оттуда, иначе каждый визит посчитается дважды. Чтобы и дальше считать всех, как сейчас, снимите «Ждать согласия посетителя» (Метрика) или выберите «Не ждать — считать всех» (Google).
  • Карта кликов и Вебвизор остаются пустыми, если веб-сервер добавляет свой заголовок X-Frame-Options. Уберите его из настроек сервера: всё, что нужно Метрике, магазин отправляет сам.
  • Разработчикам: витрина сообщает о том, что на ней происходит, событиями браузера — torgash:cart-changed, torgash:checkout-started, torgash:order-placed и другими (docs/architecture/storefront.md). Пиксель другого сервиса в «Коде на страницах» может их слушать.