Как реализовать отправку клиентских документов через Telegram в 1С:УНФ 3?

База знаний Одина — Одинэсника › Форумы › ODIN — Форум по 1С Предприятию › Как реализовать отправку клиентских документов через Telegram в 1С:УНФ 3?

Просмотр 1 ветки ответов
  • Автор
    Записи
    • #38966
      Фото аватараOdineski
      Участник

        In UNF version 3, we need to add the ability to send customer documents via Telegram, similar to how it works via email. It’s also necessary to include the ability to send receivables when sending documents. The ability to receive a price list and place orders should be added.

      • #38967
        bot_avaOdin — Одинэсник
        Участник

          For 1C:UNF 3, this should be implemented as a separate Telegram integration in an extension, without modifying the typical configuration. The solution should reuse the existing logic for sending customer documents by email, but Telegram requires its own queue, customer identification and message delivery status.

          ## 1. Main functionality

          The integration should provide four independent scenarios:

          1. Sending documents to a customer via Telegram.
          2. Sending information about the customer’s receivables.
          3. Sending a price list at the customer’s request.
          4. Receiving and processing customer orders through Telegram.

          The recommended architecture is:

          The integration should work through a Telegram bot created in BotFather.

          ## 2. Customer identification in Telegram

          The most important issue is linking a Telegram user to a customer in 1C.

          A Telegram bot does not know which customer is writing to it. The customer must be identified by one of the following methods.

          ### Recommended method: authorization code

          The customer receives a unique code from the manager or from the customer portal, for example:

          The customer sends this code to the Telegram bot. 1C finds the customer and saves the Telegram identifier.

          The following information should be stored:

          — Customer;
          — Telegram user ID;
          — Telegram chat ID;
          — Telegram username;
          — Date of authorization;
          — Authorization status;
          — Code expiration date;
          — Date of the last message;
          — Blocking or deactivation flag.

          It is better to store this data in a separate information register, for example:

          Possible dimensions:

          — Customer;
          — TelegramUserID;
          — TelegramChatID.

          Possible resources and attributes:

          — Username;
          — FirstName;
          — LastName;
          — IsActive;
          — AuthorizedAt;
          — LastMessageDate;
          — AuthorizationCode;
          — CodeExpirationDate.

          The main identifier for sending messages is chat_id, not the username. The username can change, while the chat ID normally remains unchanged.

          ### Alternative method

          The customer can send the phone number registered in 1C. The bot then sends a confirmation code. This is more secure, but it requires an additional confirmation procedure.

          The bot cannot start a conversation with a customer until the customer has first pressed Start or sent a message to the bot.

          ## 3. Telegram bot settings in 1C

          Create a settings form, preferably in the section:

          The settings should include:

          — Bot token;
          — Bot name;
          — Telegram API URL;
          — Webhook or polling mode;
          — Proxy parameters, if required;
          — Maximum file size;
          — Message sending interval;
          — Number of attempts;
          — Default document format;
          — Default price list format;
          — Whether to send debt information automatically;
          — Organization used for customer documents;
          — Message templates.

          The bot token must not be stored in ordinary open application parameters. It should be stored in a protected setting, for example using standard secure storage mechanisms available in the particular UNF 3 release.

          Telegram API requests are sent to:

          Examples of methods:

          ## 4. Sending customer documents via Telegram

          The existing email mechanism should be extended rather than duplicated completely.

          The document sending process should be separated into three stages:

          1. Formation of the document file.
          2. Creation of a Telegram outgoing message.
          3. Actual sending through Telegram.

          For example, when the user selects a customer document, the form should contain additional commands:

          — Send by email;
          — Send via Telegram;
          — Send by email and Telegram;
          — Send receivables;
          — Send document and receivables.

          The integration should support at least:

          — PDF files;
          — Excel files, where appropriate;
          — Printed forms;
          — Several documents in one message;
          — Text accompanying the document;
          — A document generated from a print form;
          — A link to the document, if the file is too large.

          A message may look as follows:

          If several files are sent, it is better to create one ZIP archive or send the files separately with clear names.

          Recommended file name:

          ## 5. Sending receivables

          Receivables should be sent as a separate generated report or as an attachment to the customer document.

          There are two possible options.

          ### Option 1. Send a brief text message

          Example:

          This option is convenient for a quick notification.

          ### Option 2. Send a detailed debt statement

          The bot sends a PDF or Excel file containing:

          — Customer;
          — Agreement;
          — Document basis;
          — Document number and date;
          — Due date;
          — Document amount;
          — Paid amount;
          — Remaining debt;
          — Days overdue;
          — Currency.

          The preferred implementation is to use the same data source as the standard UNF report on customer settlements or receivables. A new independent calculation should not be created if the configuration already has a standard report with correct settlement logic.

          The sending form can contain the following flags:

          When sending automatically after a sale, the recommended message sequence is:

          1. Send the document.
          2. Send a short debt summary.
          3. Send a detailed statement, if selected by the user.

          For example:

          ## 6. Delivery queue

          Messages should not be sent directly from the document form. This can cause user interface delays and makes it difficult to retry failed messages.

          Create an information register or a dedicated accumulation register for the outgoing queue. For example:

          Possible fields:

          — Message ID;
          — Customer;
          — TelegramChatID;
          — Source object;
          — Source document;
          — Message type;
          — Text;
          — File address;
          — File name;
          — Status;
          — Attempt count;
          — Last attempt date;
          — Next attempt date;
          — Telegram message ID;
          — Error text;
          — Created by;
          — Creation date.

          Statuses:

          A scheduled job should process the queue, for example every minute.

          The scheduled job must:

          1. Select messages with status Pending;
          2. Check that the Telegram account is active;
          3. Send the message or file;
          4. Save the Telegram response;
          5. Set status Sent;
          6. If an error occurs, increase the attempt count;
          7. Retry temporary errors;
          8. Mark the message as Error after the maximum number of attempts.

          Temporary errors include:

          — Telegram server unavailable;
          — Network timeout;
          — HTTP 429;
          — Temporary 5xx response.

          Permanent errors include:

          — Chat not found;
          — Bot blocked by the customer;
          — Invalid chat ID;
          — File not found;
          — Unauthorized bot token.

          The same document must not be sent twice accidentally. A uniqueness key should be created from:

          ## 7. Receiving Telegram messages

          For receiving orders and requests from customers, it is better to use a webhook.

          Example:

          Telegram sends incoming messages to this address. The web server then transfers the data to 1C.

          If the 1C infobase is not publicly available, use one of these approaches:

          — A small external gateway on a public server;
          — Telegram polling through a scheduled job;
          — A corporate integration service;
          — 1C server publication via HTTPS.

          For a simple installation, polling through getUpdates can be used. For a production environment with multiple customers, webhook mode is preferable.

          The received message should be stored in an incoming message register before processing. This prevents data loss and allows repeated processing.

          Possible register:

          Fields:

          — Telegram update ID;
          — Telegram chat ID;
          — Telegram user ID;
          — Message text;
          — Message date;
          — Attached file identifier;
          — Processing status;
          — Processing error;
          — Linked customer.

          Telegram update_id should be checked for uniqueness. The same update must not be processed twice.

          ## 8. Customer menu

          After authorization, the bot can show the following menu:

          Inline buttons are preferable to requiring customers to remember commands.

          Example commands:

          ## 9. Price list functionality

          The customer should be able to request a price list from Telegram.

          Possible scenarios:

          ### Simple price list

          The customer presses:

          1C forms a price list according to predefined rules and sends it as:

          — PDF;
          — XLSX;
          — CSV;
          — A link to an online price list.

          The price list should be generated for the specific customer if customer-specific prices are used.

          It may include:

          — Product;
          — SKU;
          — Unit;
          — Customer price;
          — VAT;
          — Available balance;
          — Minimum order quantity;
          — Delivery information;
          — Product characteristics.

          ### Price list parameters

          The bot may ask:

          The preferred approach is to create predefined price list profiles in 1C rather than allowing unrestricted parameters from Telegram.

          Example configuration object:

          It can contain:

          — Price type;
          — Organization;
          — Warehouse;
          — Currency;
          — Output format;
          — Availability filter;
          — Customer-specific pricing rule;
          — Validity period;
          — File generation method.

          For a large catalog, it is better to generate the price list in the background and send it when ready. Otherwise, the Telegram request can wait too long.

          ## 10. Order placement through Telegram

          The order form should work as a dialog.

          Example dialog:

          After confirmation, 1C creates a customer order, normally based on the UNF object used for sales orders. The exact object name must be checked in the specific UNF 3 release because it may depend on localization and enabled functional options.

          The created order should contain:

          — Customer;
          — Agreement or contract;
          — Organization;
          — Warehouse;
          — Delivery address;
          — Currency;
          — Price type;
          — Products;
          — Quantities;
          — Prices;
          — Discounts;
          — Customer comment;
          — Telegram chat ID;
          — External order identifier.

          The Telegram message should include:

          The order should not necessarily be automatically posted or confirmed. A safer first version is:

          1. Create the order;
          2. Save it;
          3. Set status Awaiting confirmation;
          4. Notify the responsible manager;
          5. Send the customer an acceptance message.

          Automatic confirmation can be added later if the business rules are clear.

          ## 11. Product selection

          There are three practical approaches.

          ### Search by name or article

          The customer enters:

          1C searches the product catalog and returns the first several matches.

          ### Search by product code

          The customer enters:

          This is more reliable for B2B customers.

          ### Buttons and categories

          The bot displays:

          The customer then selects a product from the category.

          For a large catalog, the bot should not load the entire catalog into every message. Use paging:

          ## 12. Business rules for orders

          The following rules must be defined in the settings:

          — Whether the customer can order only available goods;
          — Whether negative stock is allowed;
          — Minimum order amount;
          — Minimum quantity;
          — Customer-specific prices;
          — Automatic discounts;
          — Delivery method;
          — Warehouse selection;
          — Payment terms;
          — Whether an order requires manager approval;
          — Whether the customer may cancel an order;
          — Whether an order can be changed after creation.

          The bot should not allow the customer to change the price manually. The price must be obtained from 1C at the moment the item is added or the order is confirmed.

          The price and stock should be checked again immediately before creating the order, because the information shown earlier may already be outdated.

          ## 13. Telegram messages for document events

          The integration can also notify the customer when the document status changes.

          Possible events:

          — Order accepted;
          — Order confirmed;
          — Goods shipped;
          — Invoice issued;
          — Payment received;
          — Receivables overdue;
          — Customer document generated.

          Example:

          These notifications should also be placed into the outgoing queue. The document processing procedure should only create a queue entry and should not make a direct external HTTP call.

          ## 14. Required extension objects

          A typical extension may contain the following objects.

          ### Catalogs

          A separate bot catalog is optional if only one bot is used.

          ### Information registers

          TelegramOrderSessions is required to store the current state of a customer dialog:

          — Customer;
          — Chat ID;
          — Current operation;
          — Current step;
          — Selected products;
          — Temporary order data;
          — Session expiration date.

          For example, the current operation can be:

          ### Common modules

          — TelegramServer;
          — TelegramClient;
          — TelegramAPI;
          — TelegramMessageProcessor;
          — TelegramOrderProcessor;
          — TelegramPriceListProcessor;
          — TelegramDocumentSender;
          — TelegramQueueManager.

          ### Scheduled jobs

          — Receive Telegram messages;
          — Process incoming messages;
          — Send outgoing Telegram messages;
          — Generate price lists;
          — Retry failed messages;
          — Clear expired order sessions.

          ## 15. Telegram API error handling

          The integration should analyze both HTTP status and the Telegram response body.

          Typical errors:

          Invalid bot token.

          Incorrect parameters, invalid chat ID or incorrect file.

          The customer blocked the bot.

          Incorrect Telegram API endpoint.

          Telegram rate limit. The system should wait for the number of seconds specified in retry_after.

          The error text should be recorded in the outgoing message register. The user should see a readable status, for example:

          ## 16. Security requirements

          The following points are important:

          — Use HTTPS only;
          — Do not expose the bot token in client code;
          — Do not trust customer IDs received from Telegram without checking the linked account;
          — Do not allow a customer to view another customer’s documents;
          — Check ownership of every document before sending it;
          — Check customer access before displaying receivables;
          — Do not place sensitive financial information in a public group chat;
          — Store incoming and outgoing message logs;
          — Limit the size of generated files;
          — Use expiration time for authorization codes;
          — Disable the Telegram account when the customer requests disconnection;
          — Log all created orders with the Telegram user and chat ID.

          A customer must only be able to receive:

          ## 17. Suggested implementation stages

          ### Stage 1. Telegram authorization

          — Create bot;
          — Add settings;
          — Implement customer authorization;
          — Save chat_id;
          — Add test message sending.

          ### Stage 2. Sending documents

          — Add “Send via Telegram” command;
          — Implement PDF generation;
          — Add outgoing queue;
          — Add delivery status;
          — Add retries and error handling.

          ### Stage 3. Receivables

          — Reuse the existing UNF settlement report;
          — Generate short text summary;
          — Add detailed PDF or Excel statement;
          — Add commands for manual and automatic sending.

          ### Stage 4. Price list

          — Add price list profiles;
          — Implement customer-specific prices;
          — Generate PDF or XLSX;
          — Add request through the Telegram menu.

          ### Stage 5. Orders

          — Implement dialog state machine;
          — Search products;
          — Add products to a temporary order;
          — Recheck prices and availability;
          — Create a customer order;
          — Notify the manager and customer.

          ### Stage 6. Automatic notifications

          — Order status notifications;
          — Shipment notifications;
          — Payment notifications;
          — Overdue receivables notifications.

          The safest implementation for UNF 3 is an extension with a background queue and a separate Telegram message processor. Directly calling Telegram from document forms or from document posting procedures is undesirable because it creates dependency on the Internet connection and may slow down or interrupt normal work in 1C.

      Просмотр 1 ветки ответов
      • Для ответа в этой теме необходимо авторизоваться.
      База знаний 1С