Skip to content
Educora
Intermediate20 min9 / 14

Document posting: records, balance control and modules

Create register records in the `ОбработкаПроведения` handler, control negative balances, tell object and manager modules apart, and attach code with event subscriptions without touching the objects themselves.

Check yourself
In this lesson you will learn
  • Explain step by step what happens during posting
  • Create records in code and with the wizard, and control balances
  • Use object modules, manager modules and event subscriptions in the right place

Elvin, the storekeeper, posts a “Goods sale” document. The program must do two things: reduce the stock balance and refuse to post the document if there is not enough tea. In this lesson we write the engine of posting: the ОбработкаПроведения procedure, register records and balance control.

What happens during posting

  1. The platform opens a transaction and writes the document with Проведен = Истина.
  2. ОбработкаПроведения(Отказ, РежимПроведения) (Posting) is called in the object module — records are filled here.
  3. Record sets with Записывать = Истина are written and replace this document's old records — so re-posting never doubles the data.
  4. If the code set Отказ = Истина (Cancel), the transaction is rolled back: neither the document nor the records are saved.

On the document's Движения (Register records) tab, Проведение (Posting) must be Разрешить (Allow) and the registers must be ticked. There is also the Удаление движений property: Удалять автоматически, Удалять автоматически при отмене проведения or Не удалять автоматически — it decides what happens to old records on unposting and re-posting.

Creating register records

  1. 1
    Open the wizard

    On the Движения tab of ПриходТовара, tick the ОстаткиТоваров register and click Конструктор движений (Register records wizard).

  2. 2
    Choose the source and expressions

    Tabular section Товары, record type Приход. Click Заполнить выражения (Fill expressions) — the wizard matches register fields with attributes of the same name; type the rest by hand.

  3. 3
    Check the code

    Click ОК: ОбработкаПроведения appears in the object module. Post a document with F5 and view its records via Перейти › Остатки товаров (Go to).

1C
// Модуль объекта документа ПриходТовара
Процедура ОбработкаПроведения(Отказ, РежимПроведения)
    Движения.ОстаткиТоваров.Записывать = Истина;
    Для Каждого СтрокаТовары Из Товары Цикл
        Движение = Движения.ОстаткиТоваров.Добавить();
        Движение.ВидДвижения = ВидДвиженияНакопления.Приход;
        Движение.Период = Дата;
        Движение.Товар = СтрокаТовары.Товар;
        Движение.Склад = Склад;
        Движение.Количество = СтрокаТовары.Количество;
    КонецЦикла;
КонецПроцедуры
In the object module the document's attributes are accessed directly: Дата, Склад, Товары. The platform fills the Регистратор field itself.

Balance control

The РасходТовара document reduces the balance. The modern (“new”) method is: first write the Расход records, then check with one query that no balance has gone negative. Before writing, set БлокироватьДляИзменения = Истина (LockForUpdate) so that users working in parallel cannot “spend” the same stock at the same moment. If a negative balance is found — Отказ = Истина.

1C
// Модуль объекта документа РасходТовара
Процедура ОбработкаПроведения(Отказ, РежимПроведения)
    Движения.ОстаткиТоваров.Записывать = Истина;
    Для Каждого СтрокаТовары Из Товары Цикл
        Движение = Движения.ОстаткиТоваров.Добавить();
        Движение.ВидДвижения = ВидДвиженияНакопления.Расход;
        Движение.Период = Дата;
        Движение.Товар = СтрокаТовары.Товар;
        Движение.Склад = Склад;
        Движение.Количество = СтрокаТовары.Количество;
    КонецЦикла;

    Движения.ОстаткиТоваров.БлокироватьДляИзменения = Истина;
    Движения.ОстаткиТоваров.Записать();
    ПроверитьОстатки(Отказ);
КонецПроцедуры
1C
Процедура ПроверитьОстатки(Отказ)
    Запрос = Новый Запрос;
    Запрос.Текст =
    "ВЫБРАТЬ
    |    Остатки.Товар КАК Товар,
    |    Остатки.КоличествоОстаток КАК Остаток
    |ИЗ
    |    РегистрНакопления.ОстаткиТоваров.Остатки(&Момент, Склад = &Склад) КАК Остатки
    |ГДЕ
    |    Остатки.КоличествоОстаток < 0";
    Запрос.УстановитьПараметр("Момент", Новый Граница(МоментВремени(), ВидГраницы.Включая));
    Запрос.УстановитьПараметр("Склад", Склад);

    Выборка = Запрос.Выполнить().Выбрать();
    Пока Выборка.Следующий() Цикл
        Сообщить(СтрШаблон("Товара %1 не хватает: %2", Выборка.Товар, -Выборка.Остаток));
        Отказ = Истина;
    КонецЦикла;
КонецПроцедуры
Новый Граница(…, ВидГраницы.Включая) includes the document's own records in the balance. We will study the query language in detail in the next module.

Object module, manager module and event subscriptions

WhereWhat goes thereExample
Object moduleevents of one particular objectОбработкаПроведения, ПередЗаписью, ОбработкаПроверкиЗаполнения, ОбработкаЗаполнения
Manager moduleexport functions for the whole typeДокументы.РасходТовара.ПечатнаяФорма(Ссылка)
Event subscriptionone handler for many objectschecking the date in all documents

An event subscription (Общие › Подписки на события) is set up with three properties: Источник (Source — which objects), Событие (Event, for example ПередЗаписью) and Обработчик (Handler) — an export procedure in a server common module. It lets you extend the behaviour of a typical configuration's objects without touching their modules.

1C
// Общий модуль ПроверкиДокументов (флаг «Сервер»)
Процедура ПроверитьДатуПередЗаписью(Источник, Отказ, РежимЗаписи, РежимПроведения) Экспорт
    Если Источник.ОбменДанными.Загрузка Тогда
        Возврат;  // при загрузке из обмена проверки не выполняем
    КонецЕсли;
    Если Источник.Дата > КонецДня(ТекущаяДатаСеанса()) Тогда
        Сообщить("Нельзя записать документ будущей датой");
        Отказ = Истина;
    КонецЕсли;
КонецПроцедуры
A subscription handler for a document's ПередЗаписью (BeforeWrite) event. The ОбменДанными.Загрузка check is the standard way to skip checks during data exchange.

Key points

  • Posting runs in a transaction: ОбработкаПроведения fills the records, Отказ = Истина cancels everything.
  • Record sets with Записывать = Истина replace the document's old records.
  • New method: write the records → check for negative balances with one query on the Остатки virtual table.
  • Object module — events of one object; manager module — functions for the whole type.
  • Event subscriptions extend behaviour without touching the objects' modules.

Check yourself

10 questions. Every correct answer earns XP.

1 / 10
When a document is posted a second time, what happens to its old register records?