Skip to content
Back to search

1c-ai-development-kit

Comprehensive AI agents, skills and rules toolkit for 1C:Enterprise development in Cursor IDE

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/arman-kudaibergenov--1c-ai-development-kit/badge.svg)](/listings/arman-kudaibergenov--1c-ai-development-kit)

HTML

<a href="/listings/arman-kudaibergenov--1c-ai-development-kit"><img src="/api/listings/arman-kudaibergenov--1c-ai-development-kit/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 140 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # 1C AI Development Kit
  2. [![License: AGPL--3.0](https://img.shields.io/badge/License-AGPL_3.0-blue.svg)](https://www.gnu.org/licenses/agpl-3.0)
  3. [![Claude Code](https://img.shields.io/badge/Claude_Code-supported-blue.svg)](https://claude.ai/code)
  4. [![Cursor IDE](https://img.shields.io/badge/Cursor_IDE-supported-purple.svg)](https://cursor.sh/)
  5. > Комплект инструментов для AI-ассистированной разработки на 1С:Предприятие 8.3.
  6. > Поддерживает **Claude Code** и **Cursor IDE**.
  7. ---
  8. ## Что это?
  9. **1C AI Development Kit** — готовая экосистема для разработки на 1С с помощью AI. Включает агентов, навыки (skills), правила, шаблоны конфигов и документацию по форматам 1С.
  10. Проект развился из нескольких решений сообщества (см. [Благодарности](#благодарности)) и объединяет их в единый рабочий комплект с поддержкой Claude Code.
  11. ---
  12. ## Что внутри
  13. ### Claude Code Skills
  14. 52 skills для автоматизации полного цикла разработки 1С. Вызываются как `/skill-name` в диалоге с Claude:
  15. | Группа | Skills |
  16. |--------|--------|
  17. | Объекты метаданных | `meta-compile`, `meta-edit`, `meta-remove` |
  18. | Формы | `form-compile`, `form-edit`, `form-add`, `form-remove`, `form-patterns`, `help-add` |
  19. | Обработки (EPF) | `epf-expert` (init, build, dump, bsp-init, bsp-add-command) |
  20. | Отчёты (ERF) | `erf-expert` (init, build, dump) |
  21. | СКД | `skd-compile`, `skd-edit` |
  22. | Макеты (MXL) | `mxl-expert` (compile, decompile, template-add, template-remove) |
  23. | Роли | `role-expert` (compile + audit) |
  24. | Подсистемы | `subsystem-expert` (compile, edit, interface-edit) |
  25. | Конфигурация | `cf-init`, `cf-edit` |
  26. | Расширения (CFE) | `cfe-init`, `cfe-borrow`, `cfe-patch-method`, `cfe-diff` |
  27. | Инспекция | `inspect` (cf, meta, form, skd, mxl, role, subsystem info) |
  28. | Валидация | `validate` (cf, cfe, meta, form, skd, mxl, role, subsystem) |
  29. | База данных | `db-create`, `db-list`, `db-run`, `db-update`, `db-dump-cf`, `db-load-cf`, `db-dump-xml`, `db-load-xml`, `db-load-git` |
  30. | Веб-клиент | `1c-web-session`, `web-publish`, `web-unpublish`, `web-info`, `web-stop`, `web-test` |
  31. | Workflow | `brainstorm`, `write-plan`, `subagent-dev`, `1c-help-mcp`, `1c-query-opt`, `1c-project-init`, `1c-test-runner`, `bsp-patterns`, `playwright-test`, `img-grid` |
  32. | OpenSpec | `openspec-proposal`, `openspec-apply`, `openspec-archive` |
  33. ### Cursor IDE
  34. - **12 специализированных агентов** — ревью кода, генерация форм, оптимизация запросов, проектирование архитектуры и др.
  35. - **9 правил** — стандарты BSL, SDD workflow, выбор модели, использование MCP
  36. - **13 skill-групп** — навыки для Cursor
  37. ### Документация — 29 спецификаций
  38. XML-форматы объектов 1С, JSON DSL для компиляции без знания XML, паттерны форм, гайды по работе с objects.
  39. ### Шаблоны
  40. - `templates/mcp.json` — готовый конфиг MCP-серверов для нового проекта
  41. ---
  42. ## Быстрый старт
  43. Смотри [QUICK_START.md](QUICK_START.md) — там пошаговые инструкции для Claude Code и Cursor IDE.
  44. ---
  45. ## MCP-серверы
  46. Для полной функциональности рекомендуются MCP-серверы от [vibecoding1c.ru](https://vibecoding1c.ru/mcp_server):
  47. | Сервер | Назначение |
  48. |--------|-----------|
  49. | `1c-help` | Документация платформы 1С |
  50. | `1c-ssl` | Паттерны БСП (Standard Subsystems Library) |
  51. | `1c-templates` | Шаблоны кода 1С |
  52. | `1c-syntax-checker` | Проверка синтаксиса BSL |
  53. | `1c-code-checker` | Проверка логики через 1С:Напарник |
  54. | `1c-forms` | Схемы управляемых форм |
  55. | `rlm-toolkit` | Персистентная память между сессиями (от [@Dmitrii_Labintsev](https://habr.com/ru/articles/986702/)) |
  56. | `edt-mcp` | Интеграция с 1C:EDT (от [@DitriXNew](https://github.com/DitriXNew/EDT-MCP)) |
  57. Настройка MCP: [docs/guides/project-mcp-setup.md](docs/guides/project-mcp-setup.md)
  58. ---
  59. ## Требования
  60. - 1С:Предприятие 8.3.24+
  61. - PowerShell 5.1+
  62. - Git
  63. - Claude Code или Cursor IDE
  64. ---
  65. ## Благодарности
  66. Проект построен на работе сообщества. Полные благодарности: [ACKNOWLEDGMENTS.md](ACKNOWLEDGMENTS.md)
  67. | Проект | Автор | Вклад |
  68. |--------|-------|-------|
  69. | [cc-1c-skills](https://github.com/Nikolay-Shirokov/cc-1c-skills) | [@Nikolay-Shirokov](https://github.com/Nikolay-Shirokov) | Основа архитектуры Claude Code skills — 44+ skills, XML DSL, спецификации |
  70. | [cursor_rules_1c](https://github.com/comol/cursor_rules_1c) | [@comol](https://github.com/comol) | Skills для Cursor, JSON DSL, агенты, правила |
  71. | [1c-batch](https://github.com/vladimir-kharin/1c-batch) | [@vladimir-kharin](https://github.com/vladimir-kharin) | Bat-скрипты для пакетных операций с платформой 1С |
  72. | [mcp-bsl-lsp-bridge](https://github.com/SteelMorgan/mcp-bsl-lsp-bridge) | [@SteelMorgan](https://github.com/SteelMorgan) | MCP-сервер для BSL Language Server |
  73. | [1c-ai-sandbox](https://github.com/SteelMorgan/1c-ai-sandbox-client-server) | [@SteelMorgan](https://github.com/SteelMorgan) | Концепция безопасной sandbox-среды для AI-агентов |
  74. | [EDT-MCP](https://github.com/DitriXNew/EDT-MCP) | [@DitriXNew](https://github.com/DitriXNew) | MCP-сервер для интеграции с 1C:EDT |
  75. | [vibecoding1c.ru](https://vibecoding1c.ru) | [@comol_foa](https://t.me/comol_foa) | MCP-серверы, курсы, сообщество AI-разработки на 1С |
  76. ---
  77. ## Контакты
  78. - 💬 Telegram: [@Jefest9988](https://t.me/Jefest9988)
  79. - 📧 Email: arman.kudaibergenov.mail@gmail.com
  80. - 🐙 GitHub: [github.com/Arman-Kudaibergenov/1c-ai-development-kit](https://github.com/Arman-Kudaibergenov/1c-ai-development-kit)
  81. ---
  82. **Сделано с ❤️ для сообщества 1С-разработчиков**
  83. ---
  84. ## Changelog
  85. ### v1.1.0 (2026-03-05)
  86. **Консолидация skills: 14 granular skills объединены в 5 expert skills**
  87. - `epf-expert` — объединяет: `epf-add-form`, `epf-bsp-add-command`, `epf-bsp-init`, `epf-erf-build`, `epf-erf-dump`, `epf-erf-init`
  88. - `mxl-expert` — объединяет: `mxl-compile`, `mxl-decompile`, `template-add`, `template-remove`
  89. - `role-expert` — объединяет: `role-compile` + аудит прав
  90. - `subsystem-expert` — объединяет: `subsystem-compile`, `subsystem-edit`, `interface-edit`
  91. - `inspect` — заменяет 7 `*-info` skills (cf-info, meta-info, form-info, skd-info, mxl-info, role-info, subsystem-info)
  92. - `validate` — заменяет 11 `*-validate` skills
  93. Итого: 80 → 52 skills. Меньше overlap, полное domain coverage per skill.
  94. ### v1.0.0
  95. Первый публичный релиз. 80 skills для полного цикла разработки на 1С.
.claude/skills/cfe-borrow/scripts/cfe-borrow.ps1 · Bundled script · 611 lines
  1. # cfe-borrow v1.0 — Borrow objects from configuration into extension (CFE)
  2. # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
  3. param(
  4. [Parameter(Mandatory)][string]$ExtensionPath,
  5. [Parameter(Mandatory)][string]$ConfigPath,
  6. [Parameter(Mandatory)][string]$Object
  7. )
  8. $ErrorActionPreference = "Stop"
  9. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  10. function Info([string]$msg) { Write-Host "[INFO] $msg" }
  11. function Warn([string]$msg) { Write-Host "[WARN] $msg" }
  12. # --- 1. Resolve paths ---
  13. if (-not [System.IO.Path]::IsPathRooted($ExtensionPath)) {
  14. $ExtensionPath = Join-Path (Get-Location).Path $ExtensionPath
  15. }
  16. if (Test-Path $ExtensionPath -PathType Container) {
  17. $candidate = Join-Path $ExtensionPath "Configuration.xml"
  18. if (Test-Path $candidate) { $ExtensionPath = $candidate }
  19. else { Write-Error "No Configuration.xml in extension directory: $ExtensionPath"; exit 1 }
  20. }
  21. if (-not (Test-Path $ExtensionPath)) { Write-Error "Extension file not found: $ExtensionPath"; exit 1 }
  22. $extResolvedPath = (Resolve-Path $ExtensionPath).Path
  23. $extDir = Split-Path $extResolvedPath -Parent
  24. if (-not [System.IO.Path]::IsPathRooted($ConfigPath)) {
  25. $ConfigPath = Join-Path (Get-Location).Path $ConfigPath
  26. }
  27. if (Test-Path $ConfigPath -PathType Container) {
  28. $candidate = Join-Path $ConfigPath "Configuration.xml"
  29. if (Test-Path $candidate) { $ConfigPath = $candidate }
  30. else { Write-Error "No Configuration.xml in config directory: $ConfigPath"; exit 1 }
  31. }
  32. if (-not (Test-Path $ConfigPath)) { Write-Error "Config file not found: $ConfigPath"; exit 1 }
  33. $cfgResolvedPath = (Resolve-Path $ConfigPath).Path
  34. $cfgDir = Split-Path $cfgResolvedPath -Parent
  35. # --- 2. Load extension Configuration.xml ---
  36. $script:xmlDoc = New-Object System.Xml.XmlDocument
  37. $script:xmlDoc.PreserveWhitespace = $true
  38. $script:xmlDoc.Load($extResolvedPath)
  39. $script:mdNs = "http://v8.1c.ru/8.3/MDClasses"
  40. $script:xrNs = "http://v8.1c.ru/8.3/xcf/readable"
  41. $script:xsiNs = "http://www.w3.org/2001/XMLSchema-instance"
  42. $script:v8Ns = "http://v8.1c.ru/8.1/data/core"
  43. $root = $script:xmlDoc.DocumentElement
  44. $script:cfgEl = $null
  45. foreach ($child in $root.ChildNodes) {
  46. if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "Configuration") {
  47. $script:cfgEl = $child; break
  48. }
  49. }
  50. if (-not $script:cfgEl) { Write-Error "No <Configuration> element found in extension"; exit 1 }
  51. $script:propsEl = $null
  52. $script:childObjsEl = $null
  53. foreach ($child in $script:cfgEl.ChildNodes) {
  54. if ($child.NodeType -ne 'Element') { continue }
  55. if ($child.LocalName -eq "Properties") { $script:propsEl = $child }
  56. if ($child.LocalName -eq "ChildObjects") { $script:childObjsEl = $child }
  57. }
  58. if (-not $script:propsEl) { Write-Error "No <Properties> element found in extension"; exit 1 }
  59. if (-not $script:childObjsEl) { Write-Error "No <ChildObjects> element found in extension"; exit 1 }
  60. # --- 3. Extract NamePrefix ---
  61. $script:namePrefix = ""
  62. foreach ($child in $script:propsEl.ChildNodes) {
  63. if ($child.NodeType -eq 'Element' -and $child.LocalName -eq "NamePrefix") {
  64. $script:namePrefix = $child.InnerText.Trim(); break
  65. }
  66. }
  67. Info "Extension NamePrefix: $($script:namePrefix)"
  68. # --- 4. Type mappings ---
  69. $childTypeDirMap = @{
  70. "Catalog"="Catalogs"; "Document"="Documents"; "Enum"="Enums"
  71. "CommonModule"="CommonModules"; "CommonPicture"="CommonPictures"
  72. "CommonCommand"="CommonCommands"; "CommonTemplate"="CommonTemplates"
  73. "ExchangePlan"="ExchangePlans"; "Report"="Reports"; "DataProcessor"="DataProcessors"
  74. "InformationRegister"="InformationRegisters"; "AccumulationRegister"="AccumulationRegisters"
  75. "ChartOfCharacteristicTypes"="ChartsOfCharacteristicTypes"
  76. "ChartOfAccounts"="ChartsOfAccounts"; "AccountingRegister"="AccountingRegisters"
  77. "ChartOfCalculationTypes"="ChartsOfCalculationTypes"; "CalculationRegister"="CalculationRegisters"
  78. "BusinessProcess"="BusinessProcesses"; "Task"="Tasks"
  79. "Subsystem"="Subsystems"; "Role"="Roles"; "Constant"="Constants"
  80. "FunctionalOption"="FunctionalOptions"; "DefinedType"="DefinedTypes"
  81. "FunctionalOptionsParameter"="FunctionalOptionsParameters"
  82. "CommonForm"="CommonForms"; "DocumentJournal"="DocumentJournals"
  83. "SessionParameter"="SessionParameters"; "StyleItem"="StyleItems"
  84. "EventSubscription"="EventSubscriptions"; "ScheduledJob"="ScheduledJobs"
  85. "SettingsStorage"="SettingsStorages"; "FilterCriterion"="FilterCriteria"
  86. "CommandGroup"="CommandGroups"; "DocumentNumerator"="DocumentNumerators"
  87. "Sequence"="Sequences"; "IntegrationService"="IntegrationServices"
  88. "XDTOPackage"="XDTOPackages"; "WebService"="WebServices"
  89. "HTTPService"="HTTPServices"; "WSReference"="WSReferences"
  90. "CommonAttribute"="CommonAttributes"; "Style"="Styles"
  91. }
  92. # --- 4b. Russian synonym → English type ---
  93. $synonymMap = @{
  94. "Справочник"="Catalog"; "Документ"="Document"; "Перечисление"="Enum"
  95. "ОбщийМодуль"="CommonModule"; "ОбщаяКартинка"="CommonPicture"
  96. "ОбщаяКоманда"="CommonCommand"; "ОбщийМакет"="CommonTemplate"
  97. "ПланОбмена"="ExchangePlan"; "Отчет"="Report"; "Отчёт"="Report"
  98. "Обработка"="DataProcessor"; "РегистрСведений"="InformationRegister"
  99. "РегистрНакопления"="AccumulationRegister"
  100. "ПланВидовХарактеристик"="ChartOfCharacteristicTypes"
  101. "ПланСчетов"="ChartOfAccounts"; "РегистрБухгалтерии"="AccountingRegister"
  102. "ПланВидовРасчета"="ChartOfCalculationTypes"; "РегистрРасчета"="CalculationRegister"
  103. "БизнесПроцесс"="BusinessProcess"; "Задача"="Task"
  104. "Подсистема"="Subsystem"; "Роль"="Role"; "Константа"="Constant"
  105. "ФункциональнаяОпция"="FunctionalOption"; "ОпределяемыйТип"="DefinedType"
  106. "ОбщаяФорма"="CommonForm"; "ЖурналДокументов"="DocumentJournal"
  107. "ПараметрСеанса"="SessionParameter"; "ГруппаКоманд"="CommandGroup"
  108. "ПодпискаНаСобытие"="EventSubscription"; "РегламентноеЗадание"="ScheduledJob"
  109. "ОбщийРеквизит"="CommonAttribute"; "ПакетXDTO"="XDTOPackage"
  110. "HTTPСервис"="HTTPService"; "СервисИнтеграции"="IntegrationService"
  111. }
  112. # --- 5. Canonical type order (44 types) ---
  113. $script:typeOrder = @(
  114. "Language","Subsystem","StyleItem","Style",
  115. "CommonPicture","SessionParameter","Role","CommonTemplate",
  116. "FilterCriterion","CommonModule","CommonAttribute","ExchangePlan",
  117. "XDTOPackage","WebService","HTTPService","WSReference",
  118. "EventSubscription","ScheduledJob","SettingsStorage","FunctionalOption",
  119. "FunctionalOptionsParameter","DefinedType","CommonCommand","CommandGroup",
  120. "Constant","CommonForm","Catalog","Document",
  121. "DocumentNumerator","Sequence","DocumentJournal","Enum",
  122. "Report","DataProcessor","InformationRegister","AccumulationRegister",
  123. "ChartOfCharacteristicTypes","ChartOfAccounts","AccountingRegister",
  124. "ChartOfCalculationTypes","CalculationRegister",
  125. "BusinessProcess","Task","IntegrationService"
  126. )
  127. # --- 6. GeneratedType patterns per type ---
  128. $script:generatedTypes = @{
  129. "Catalog" = @(
  130. @{ prefix = "CatalogObject"; category = "Object" }
  131. @{ prefix = "CatalogRef"; category = "Ref" }
  132. @{ prefix = "CatalogSelection"; category = "Selection" }
  133. @{ prefix = "CatalogList"; category = "List" }
  134. @{ prefix = "CatalogManager"; category = "Manager" }
  135. )
  136. "Document" = @(
  137. @{ prefix = "DocumentObject"; category = "Object" }
  138. @{ prefix = "DocumentRef"; category = "Ref" }
  139. @{ prefix = "DocumentSelection"; category = "Selection" }
  140. @{ prefix = "DocumentList"; category = "List" }
  141. @{ prefix = "DocumentManager"; category = "Manager" }
  142. )
  143. "Enum" = @(
  144. @{ prefix = "EnumRef"; category = "Ref" }
  145. @{ prefix = "EnumManager"; category = "Manager" }
  146. @{ prefix = "EnumList"; category = "List" }
  147. )
  148. "Constant" = @(
  149. @{ prefix = "ConstantManager"; category = "Manager" }
  150. @{ prefix = "ConstantValueManager"; category = "ValueManager" }
  151. @{ prefix = "ConstantValueKey"; category = "ValueKey" }
  152. )
  153. "InformationRegister" = @(
  154. @{ prefix = "InformationRegisterRecord"; category = "Record" }
  155. @{ prefix = "InformationRegisterManager"; category = "Manager" }
  156. @{ prefix = "InformationRegisterSelection"; category = "Selection" }
  157. @{ prefix = "InformationRegisterList"; category = "List" }
  158. @{ prefix = "InformationRegisterRecordSet"; category = "RecordSet" }
  159. @{ prefix = "InformationRegisterRecordKey"; category = "RecordKey" }
  160. @{ prefix = "InformationRegisterRecordManager"; category = "RecordManager" }
  161. )
  162. "AccumulationRegister" = @(
  163. @{ prefix = "AccumulationRegisterRecord"; category = "Record" }
  164. @{ prefix = "AccumulationRegisterManager"; category = "Manager" }
  165. @{ prefix = "AccumulationRegisterSelection"; category = "Selection" }
  166. @{ prefix = "AccumulationRegisterList"; category = "List" }
  167. @{ prefix = "AccumulationRegisterRecordSet"; category = "RecordSet" }
  168. @{ prefix = "AccumulationRegisterRecordKey"; category = "RecordKey" }
  169. )
  170. "AccountingRegister" = @(
  171. @{ prefix = "AccountingRegisterRecord"; category = "Record" }
  172. @{ prefix = "AccountingRegisterManager"; category = "Manager" }
  173. @{ prefix = "AccountingRegisterSelection"; category = "Selection" }
  174. @{ prefix = "AccountingRegisterList"; category = "List" }
  175. @{ prefix = "AccountingRegisterRecordSet"; category = "RecordSet" }
  176. @{ prefix = "AccountingRegisterRecordKey"; category = "RecordKey" }
  177. )
  178. "CalculationRegister" = @(
  179. @{ prefix = "CalculationRegisterRecord"; category = "Record" }
  180. @{ prefix = "CalculationRegisterManager"; category = "Manager" }
  181. @{ prefix = "CalculationRegisterSelection"; category = "Selection" }
  182. @{ prefix = "CalculationRegisterList"; category = "List" }
  183. @{ prefix = "CalculationRegisterRecordSet"; category = "RecordSet" }
  184. @{ prefix = "CalculationRegisterRecordKey"; category = "RecordKey" }
  185. )
  186. "ChartOfAccounts" = @(
  187. @{ prefix = "ChartOfAccountsObject"; category = "Object" }
  188. @{ prefix = "ChartOfAccountsRef"; category = "Ref" }
  189. @{ prefix = "ChartOfAccountsSelection"; category = "Selection" }
  190. @{ prefix = "ChartOfAccountsList"; category = "List" }
  191. @{ prefix = "ChartOfAccountsManager"; category = "Manager" }
  192. )
  193. "ChartOfCharacteristicTypes" = @(
  194. @{ prefix = "ChartOfCharacteristicTypesObject"; category = "Object" }
  195. @{ prefix = "ChartOfCharacteristicTypesRef"; category = "Ref" }
  196. @{ prefix = "ChartOfCharacteristicTypesSelection"; category = "Selection" }
  197. @{ prefix = "ChartOfCharacteristicTypesList"; category = "List" }
  198. @{ prefix = "ChartOfCharacteristicTypesManager"; category = "Manager" }
  199. )
  200. "ChartOfCalculationTypes" = @(
  201. @{ prefix = "ChartOfCalculationTypesObject"; category = "Object" }
  202. @{ prefix = "ChartOfCalculationTypesRef"; category = "Ref" }
  203. @{ prefix = "ChartOfCalculationTypesSelection"; category = "Selection" }
  204. @{ prefix = "ChartOfCalculationTypesList"; category = "List" }
  205. @{ prefix = "ChartOfCalculationTypesManager"; category = "Manager" }
  206. @{ prefix = "DisplacingCalculationTypes"; category = "DisplacingCalculationTypes" }
  207. @{ prefix = "BaseCalculationTypes"; category = "BaseCalculationTypes" }
  208. @{ prefix = "LeadingCalculationTypes"; category = "LeadingCalculationTypes" }
  209. )
  210. "BusinessProcess" = @(
  211. @{ prefix = "BusinessProcessObject"; category = "Object" }
  212. @{ prefix = "BusinessProcessRef"; category = "Ref" }
  213. @{ prefix = "BusinessProcessSelection"; category = "Selection" }
  214. @{ prefix = "BusinessProcessList"; category = "List" }
  215. @{ prefix = "BusinessProcessManager"; category = "Manager" }
  216. )
  217. "Task" = @(
  218. @{ prefix = "TaskObject"; category = "Object" }
  219. @{ prefix = "TaskRef"; category = "Ref" }
  220. @{ prefix = "TaskSelection"; category = "Selection" }
  221. @{ prefix = "TaskList"; category = "List" }
  222. @{ prefix = "TaskManager"; category = "Manager" }
  223. )
  224. "ExchangePlan" = @(
  225. @{ prefix = "ExchangePlanObject"; category = "Object" }
  226. @{ prefix = "ExchangePlanRef"; category = "Ref" }
  227. @{ prefix = "ExchangePlanSelection"; category = "Selection" }
  228. @{ prefix = "ExchangePlanList"; category = "List" }
  229. @{ prefix = "ExchangePlanManager"; category = "Manager" }
  230. )
  231. "DocumentJournal" = @(
  232. @{ prefix = "DocumentJournalSelection"; category = "Selection" }
  233. @{ prefix = "DocumentJournalList"; category = "List" }
  234. @{ prefix = "DocumentJournalManager"; category = "Manager" }
  235. )
  236. "Report" = @(
  237. @{ prefix = "ReportObject"; category = "Object" }
  238. )
  239. "DataProcessor" = @(
  240. @{ prefix = "DataProcessorObject"; category = "Object" }
  241. )
  242. }
  243. # Types that need ChildObjects element
  244. $typesWithChildObjects = @(
  245. "Catalog","Document","ExchangePlan","ChartOfAccounts",
  246. "ChartOfCharacteristicTypes","ChartOfCalculationTypes",
  247. "BusinessProcess","Task","Enum",
  248. "InformationRegister","AccumulationRegister","AccountingRegister","CalculationRegister"
  249. )
  250. # CommonModule properties to copy from source
  251. $commonModuleProps = @("Global","ClientManagedApplication","Server","ExternalConnection","ClientOrdinaryApplication","ServerCall")
  252. # --- 7. XML manipulation helpers (from cf-edit) ---
  253. function Get-ChildIndent($container) {
  254. foreach ($child in $container.ChildNodes) {
  255. if ($child.NodeType -eq 'Whitespace' -or $child.NodeType -eq 'SignificantWhitespace') {
  256. if ($child.Value -match '^\r?\n(\t+)$') { return $Matches[1] }
  257. if ($child.Value -match '^\r?\n(\t+)') { return $Matches[1] }
  258. }
  259. }
  260. $depth = 0; $current = $container
  261. while ($current -and $current -ne $script:xmlDoc.DocumentElement) { $depth++; $current = $current.ParentNode }
  262. return "`t" * ($depth + 1)
  263. }
  264. function Insert-BeforeElement($container, $newNode, $refNode, $childIndent) {
  265. $ws = $script:xmlDoc.CreateWhitespace("`r`n$childIndent")
  266. if ($refNode) {
  267. $container.InsertBefore($ws, $refNode) | Out-Null
  268. $container.InsertBefore($newNode, $ws) | Out-Null
  269. } else {
  270. $trailing = $container.LastChild
  271. if ($trailing -and ($trailing.NodeType -eq 'Whitespace' -or $trailing.NodeType -eq 'SignificantWhitespace')) {
  272. $container.InsertBefore($ws, $trailing) | Out-Null
  273. $container.InsertBefore($newNode, $trailing) | Out-Null
  274. } else {
  275. $container.AppendChild($ws) | Out-Null
  276. $container.AppendChild($newNode) | Out-Null
  277. $parentIndent = if ($childIndent.Length -gt 1) { $childIndent.Substring(0, $childIndent.Length - 1) } else { "" }
  278. $closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
  279. $container.AppendChild($closeWs) | Out-Null
  280. }
  281. }
  282. }
  283. function Expand-SelfClosingElement($container, $parentIndent) {
  284. if (-not $container.HasChildNodes -or $container.IsEmpty) {
  285. $closeWs = $script:xmlDoc.CreateWhitespace("`r`n$parentIndent")
  286. $container.AppendChild($closeWs) | Out-Null
  287. }
  288. }
  289. # --- 8. Namespaces declaration for object XML ---
  290. $script:xmlnsDecl = 'xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
  291. # --- 9. Parse -Object into items ---
  292. $items = @()
  293. foreach ($part in $Object.Split(";;")) {
  294. $trimmed = $part.Trim()
  295. if ($trimmed) { $items += $trimmed }
  296. }
  297. if ($items.Count -eq 0) {
  298. Write-Error "No objects specified in -Object"
  299. exit 1
  300. }
  301. # --- 10. Helper: read source object XML ---
  302. function Read-SourceObject {
  303. param([string]$typeName, [string]$objName)
  304. $dirName = $childTypeDirMap[$typeName]
  305. if (-not $dirName) {
  306. Write-Error "Unknown type '$typeName'"
  307. exit 1
  308. }
  309. $srcFile = Join-Path (Join-Path $cfgDir $dirName) "${objName}.xml"
  310. if (-not (Test-Path $srcFile)) {
  311. Write-Error "Source object not found: $srcFile"
  312. exit 1
  313. }
  314. $srcDoc = New-Object System.Xml.XmlDocument
  315. $srcDoc.PreserveWhitespace = $false
  316. $srcDoc.Load($srcFile)
  317. $srcNs = New-Object System.Xml.XmlNamespaceManager($srcDoc.NameTable)
  318. $srcNs.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
  319. $srcNs.AddNamespace("xr", "http://v8.1c.ru/8.3/xcf/readable")
  320. # Find the type element (e.g. <Catalog uuid="...">)
  321. $srcRoot = $srcDoc.DocumentElement
  322. $srcEl = $null
  323. foreach ($c in $srcRoot.ChildNodes) {
  324. if ($c.NodeType -eq 'Element') { $srcEl = $c; break }
  325. }
  326. if (-not $srcEl) {
  327. Write-Error "No metadata element found in ${dirName}/${objName}.xml"
  328. exit 1
  329. }
  330. # Extract uuid
  331. $srcUuid = $srcEl.GetAttribute("uuid")
  332. if (-not $srcUuid) {
  333. Write-Error "No uuid attribute on source element in ${dirName}/${objName}.xml"
  334. exit 1
  335. }
  336. # Extract properties for CommonModule
  337. $srcProps = @{}
  338. $propsNode = $srcEl.SelectSingleNode("md:Properties", $srcNs)
  339. if ($propsNode) {
  340. foreach ($propName in $commonModuleProps) {
  341. $propNode = $propsNode.SelectSingleNode("md:${propName}", $srcNs)
  342. if ($propNode) {
  343. $srcProps[$propName] = $propNode.InnerText.Trim()
  344. }
  345. }
  346. }
  347. return @{
  348. Uuid = $srcUuid
  349. Properties = $srcProps
  350. Element = $srcEl
  351. NsManager = $srcNs
  352. }
  353. }
  354. # --- 11. Helper: generate InternalInfo XML ---
  355. function Build-InternalInfoXml {
  356. param([string]$typeName, [string]$objName, [string]$indent)
  357. $types = $script:generatedTypes[$typeName]
  358. if (-not $types -or $types.Count -eq 0) {
  359. return "${indent}<InternalInfo/>"
  360. }
  361. $sb = New-Object System.Text.StringBuilder
  362. $sb.AppendLine("${indent}<InternalInfo>") | Out-Null
  363. # ExchangePlan: ThisNode UUID before GeneratedTypes
  364. if ($typeName -eq "ExchangePlan") {
  365. $thisNodeUuid = [guid]::NewGuid().ToString()
  366. $sb.AppendLine("${indent}`t<xr:ThisNode>${thisNodeUuid}</xr:ThisNode>") | Out-Null
  367. }
  368. foreach ($gt in $types) {
  369. $fullName = "$($gt.prefix).${objName}"
  370. $typeId = [guid]::NewGuid().ToString()
  371. $valueId = [guid]::NewGuid().ToString()
  372. $sb.AppendLine("${indent}`t<xr:GeneratedType name=`"${fullName}`" category=`"$($gt.category)`">") | Out-Null
  373. $sb.AppendLine("${indent}`t`t<xr:TypeId>${typeId}</xr:TypeId>") | Out-Null
  374. $sb.AppendLine("${indent}`t`t<xr:ValueId>${valueId}</xr:ValueId>") | Out-Null
  375. $sb.AppendLine("${indent}`t</xr:GeneratedType>") | Out-Null
  376. }
  377. $sb.Append("${indent}</InternalInfo>") | Out-Null
  378. return $sb.ToString()
  379. }
  380. # --- 12. Helper: build borrowed object XML ---
  381. function Build-BorrowedObjectXml {
  382. param(
  383. [string]$typeName,
  384. [string]$objName,
  385. [string]$sourceUuid,
  386. [hashtable]$sourceProps
  387. )
  388. $newUuid = [guid]::NewGuid().ToString()
  389. $internalInfoXml = Build-InternalInfoXml $typeName $objName "`t`t"
  390. $sb = New-Object System.Text.StringBuilder
  391. $sb.AppendLine("<?xml version=`"1.0`" encoding=`"UTF-8`"?>") | Out-Null
  392. $sb.AppendLine("<MetaDataObject $($script:xmlnsDecl) version=`"2.17`">") | Out-Null
  393. $sb.AppendLine("`t<${typeName} uuid=`"${newUuid}`">") | Out-Null
  394. # InternalInfo
  395. $sb.AppendLine($internalInfoXml) | Out-Null
  396. # Properties
  397. $sb.AppendLine("`t`t<Properties>") | Out-Null
  398. $sb.AppendLine("`t`t`t<ObjectBelonging>Adopted</ObjectBelonging>") | Out-Null
  399. $sb.AppendLine("`t`t`t<Name>${objName}</Name>") | Out-Null
  400. $sb.AppendLine("`t`t`t<Comment/>") | Out-Null
  401. $sb.AppendLine("`t`t`t<ExtendedConfigurationObject>${sourceUuid}</ExtendedConfigurationObject>") | Out-Null
  402. # CommonModule: extra properties from source
  403. if ($typeName -eq "CommonModule") {
  404. foreach ($propName in $commonModuleProps) {
  405. $propVal = "false"
  406. if ($sourceProps.ContainsKey($propName)) {
  407. $propVal = $sourceProps[$propName]
  408. }
  409. $sb.AppendLine("`t`t`t<${propName}>${propVal}</${propName}>") | Out-Null
  410. }
  411. }
  412. $sb.AppendLine("`t`t</Properties>") | Out-Null
  413. # ChildObjects (for types that need it)
  414. if ($typesWithChildObjects -contains $typeName) {
  415. $sb.AppendLine("`t`t<ChildObjects/>") | Out-Null
  416. }
  417. $sb.AppendLine("`t</${typeName}>") | Out-Null
  418. $sb.Append("</MetaDataObject>") | Out-Null
  419. return $sb.ToString()
  420. }
  421. # --- 13. Helper: add object to extension ChildObjects ---
  422. function Add-ToChildObjects {
  423. param([string]$typeName, [string]$objName)
  424. $cfgIndent = Get-ChildIndent $script:cfgEl
  425. # Expand self-closing ChildObjects if needed
  426. if (-not $script:childObjsEl.HasChildNodes -or $script:childObjsEl.IsEmpty) {
  427. Expand-SelfClosingElement $script:childObjsEl $cfgIndent
  428. }
  429. $childIndent = Get-ChildIndent $script:childObjsEl
  430. $typeIdx = $script:typeOrder.IndexOf($typeName)
  431. if ($typeIdx -lt 0) {
  432. Write-Error "Unknown type '$typeName' for ChildObjects ordering"
  433. exit 1
  434. }
  435. # Dedup check
  436. foreach ($child in $script:childObjsEl.ChildNodes) {
  437. if ($child.NodeType -eq 'Element' -and $child.LocalName -eq $typeName -and $child.InnerText -eq $objName) {
  438. Warn "Already in ChildObjects: ${typeName}.${objName}"
  439. return
  440. }
  441. }
  442. # Find insertion point: after last element of same type, or before first element of later type
  443. $insertBefore = $null
  444. $lastSameType = $null
  445. foreach ($child in $script:childObjsEl.ChildNodes) {
  446. if ($child.NodeType -ne 'Element') { continue }
  447. $childTypeIdx = $script:typeOrder.IndexOf($child.LocalName)
  448. if ($childTypeIdx -lt 0) { continue }
  449. if ($child.LocalName -eq $typeName) {
  450. # Same type -- check alphabetical order
  451. if ($child.InnerText -gt $objName -and -not $insertBefore) {
  452. $insertBefore = $child
  453. }
  454. $lastSameType = $child
  455. } elseif ($childTypeIdx -gt $typeIdx -and -not $insertBefore) {
  456. # First element of a later type -- insert before it
  457. $insertBefore = $child
  458. }
  459. }
  460. # Create element
  461. $newEl = $script:xmlDoc.CreateElement($typeName, $script:mdNs)
  462. $newEl.InnerText = $objName
  463. if ($insertBefore) {
  464. Insert-BeforeElement $script:childObjsEl $newEl $insertBefore $childIndent
  465. } else {
  466. Insert-BeforeElement $script:childObjsEl $newEl $null $childIndent
  467. }
  468. Info "Added to ChildObjects: ${typeName}.${objName}"
  469. }
  470. # --- 14. Process each item ---
  471. $borrowedFiles = @()
  472. $borrowedCount = 0
  473. foreach ($item in $items) {
  474. $dotIdx = $item.IndexOf(".")
  475. if ($dotIdx -lt 1) {
  476. Write-Error "Invalid format '${item}', expected 'Type.Name'"
  477. exit 1
  478. }
  479. $typeName = $item.Substring(0, $dotIdx)
  480. $objName = $item.Substring($dotIdx + 1)
  481. # Resolve Russian synonym to English type name
  482. if ($synonymMap.ContainsKey($typeName)) { $typeName = $synonymMap[$typeName] }
  483. if (-not $childTypeDirMap.ContainsKey($typeName)) {
  484. Write-Error "Unknown type '${typeName}'"
  485. exit 1
  486. }
  487. $dirName = $childTypeDirMap[$typeName]
  488. Info "Borrowing ${typeName}.${objName}..."
  489. # Read source object
  490. $src = Read-SourceObject $typeName $objName
  491. Info " Source UUID: $($src.Uuid)"
  492. # Build borrowed object XML
  493. $borrowedXml = Build-BorrowedObjectXml $typeName $objName $src.Uuid $src.Properties
  494. # Create directory in extension if needed
  495. $targetDir = Join-Path $extDir $dirName
  496. if (-not (Test-Path $targetDir)) {
  497. New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
  498. }
  499. # Write borrowed object XML with UTF-8 BOM
  500. $targetFile = Join-Path $targetDir "${objName}.xml"
  501. $enc = New-Object System.Text.UTF8Encoding($true)
  502. [System.IO.File]::WriteAllText($targetFile, $borrowedXml, $enc)
  503. Info " Created: $targetFile"
  504. # Add to ChildObjects
  505. Add-ToChildObjects $typeName $objName
  506. $borrowedFiles += $targetFile
  507. $borrowedCount++
  508. }
  509. # --- 15. Save modified Configuration.xml ---
  510. $settings = New-Object System.Xml.XmlWriterSettings
  511. $settings.Encoding = New-Object System.Text.UTF8Encoding($true)
  512. $settings.Indent = $false
  513. $settings.NewLineHandling = [System.Xml.NewLineHandling]::None
  514. $memStream = New-Object System.IO.MemoryStream
  515. $writer = [System.Xml.XmlWriter]::Create($memStream, $settings)
  516. $script:xmlDoc.Save($writer)
  517. $writer.Flush(); $writer.Close()
  518. $bytes = $memStream.ToArray()
  519. $memStream.Close()
  520. $text = [System.Text.Encoding]::UTF8.GetString($bytes)
  521. if ($text.Length -gt 0 -and $text[0] -eq [char]0xFEFF) { $text = $text.Substring(1) }
  522. $text = $text.Replace('encoding="utf-8"', 'encoding="UTF-8"')
  523. $utf8Bom = New-Object System.Text.UTF8Encoding($true)
  524. [System.IO.File]::WriteAllText($extResolvedPath, $text, $utf8Bom)
  525. Info "Saved: $extResolvedPath"
  526. # --- 16. Summary ---
  527. Write-Host ""
  528. Write-Host "=== cfe-borrow summary ==="
  529. Write-Host " Extension: $extDir"
  530. Write-Host " Config: $cfgDir"
  531. Write-Host " Borrowed: $borrowedCount object(s)"
  532. foreach ($f in $borrowedFiles) {
  533. Write-Host " - $f"
  534. }
  535. exit 0
.claude/skills/cfe-patch-method/scripts/cfe-patch-method.ps1 · Bundled script · 186 lines
  1. # cfe-patch-method v1.0 — Generate method interceptor for 1C extension (CFE)
  2. # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
  3. param(
  4. [Parameter(Mandatory)]
  5. [string]$ExtensionPath,
  6. [Parameter(Mandatory)]
  7. [string]$ModulePath,
  8. [Parameter(Mandatory)]
  9. [string]$MethodName,
  10. [Parameter(Mandatory)]
  11. [ValidateSet("Before","After","ModificationAndControl")]
  12. [string]$InterceptorType,
  13. [string]$Context = "НаСервере",
  14. [switch]$IsFunction
  15. )
  16. $ErrorActionPreference = "Stop"
  17. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  18. # --- Resolve extension path ---
  19. if (-not [System.IO.Path]::IsPathRooted($ExtensionPath)) {
  20. $ExtensionPath = Join-Path (Get-Location).Path $ExtensionPath
  21. }
  22. if (Test-Path $ExtensionPath -PathType Leaf) {
  23. $ExtensionPath = Split-Path $ExtensionPath -Parent
  24. }
  25. $cfgFile = Join-Path $ExtensionPath "Configuration.xml"
  26. if (-not (Test-Path $cfgFile)) {
  27. Write-Error "Configuration.xml not found in: $ExtensionPath"
  28. exit 1
  29. }
  30. # --- Read NamePrefix from Configuration.xml ---
  31. $cfgDoc = New-Object System.Xml.XmlDocument
  32. $cfgDoc.PreserveWhitespace = $false
  33. $cfgDoc.Load($cfgFile)
  34. $cfgNs = New-Object System.Xml.XmlNamespaceManager($cfgDoc.NameTable)
  35. $cfgNs.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
  36. $propsNode = $cfgDoc.SelectSingleNode("//md:Configuration/md:Properties", $cfgNs)
  37. $prefixNode = if ($propsNode) { $propsNode.SelectSingleNode("md:NamePrefix", $cfgNs) } else { $null }
  38. $namePrefix = if ($prefixNode -and $prefixNode.InnerText) { $prefixNode.InnerText } else { "Расш_" }
  39. # --- Map ModulePath to file path ---
  40. # ModulePath formats:
  41. # Catalog.X.ObjectModule -> Catalogs/X/Ext/ObjectModule.bsl
  42. # Catalog.X.ManagerModule -> Catalogs/X/Ext/ManagerModule.bsl
  43. # Catalog.X.Form.Y -> Catalogs/X/Forms/Y/Ext/Form/Module.bsl
  44. # CommonModule.X -> CommonModules/X/Ext/Module.bsl
  45. # Document.X.ObjectModule -> Documents/X/Ext/ObjectModule.bsl
  46. # Document.X.ManagerModule -> Documents/X/Ext/ManagerModule.bsl
  47. # Document.X.Form.Y -> Documents/X/Forms/Y/Ext/Form/Module.bsl
  48. $typeDirMap = @{
  49. "Catalog"="Catalogs"; "Document"="Documents"; "Enum"="Enums"
  50. "CommonModule"="CommonModules"; "Report"="Reports"; "DataProcessor"="DataProcessors"
  51. "ExchangePlan"="ExchangePlans"; "ChartOfAccounts"="ChartsOfAccounts"
  52. "ChartOfCharacteristicTypes"="ChartsOfCharacteristicTypes"
  53. "ChartOfCalculationTypes"="ChartsOfCalculationTypes"
  54. "BusinessProcess"="BusinessProcesses"; "Task"="Tasks"
  55. "InformationRegister"="InformationRegisters"; "AccumulationRegister"="AccumulationRegisters"
  56. "AccountingRegister"="AccountingRegisters"; "CalculationRegister"="CalculationRegisters"
  57. }
  58. $parts = $ModulePath.Split(".")
  59. if ($parts.Count -lt 2) {
  60. Write-Error "Invalid ModulePath format: $ModulePath. Expected: Type.Name.Module or CommonModule.Name"
  61. exit 1
  62. }
  63. $objType = $parts[0]
  64. $objName = $parts[1]
  65. if (-not $typeDirMap.ContainsKey($objType)) {
  66. Write-Error "Unknown object type: $objType"
  67. exit 1
  68. }
  69. $dirName = $typeDirMap[$objType]
  70. $bslFile = $null
  71. if ($objType -eq "CommonModule") {
  72. # CommonModule.X -> CommonModules/X/Ext/Module.bsl
  73. $bslFile = Join-Path (Join-Path (Join-Path (Join-Path $ExtensionPath $dirName) $objName) "Ext") "Module.bsl"
  74. } elseif ($parts.Count -ge 4 -and $parts[2] -eq "Form") {
  75. # Type.X.Form.Y -> Types/X/Forms/Y/Ext/Form/Module.bsl
  76. $formName = $parts[3]
  77. $bslFile = Join-Path (Join-Path (Join-Path (Join-Path (Join-Path (Join-Path (Join-Path $ExtensionPath $dirName) $objName) "Forms") $formName) "Ext") "Form") "Module.bsl"
  78. } elseif ($parts.Count -ge 3) {
  79. # Type.X.ObjectModule -> Types/X/Ext/ObjectModule.bsl
  80. $moduleName = $parts[2]
  81. $moduleFileName = switch ($moduleName) {
  82. "ObjectModule" { "ObjectModule.bsl" }
  83. "ManagerModule" { "ManagerModule.bsl" }
  84. "RecordSetModule" { "RecordSetModule.bsl" }
  85. "CommandModule" { "CommandModule.bsl" }
  86. default { "$moduleName.bsl" }
  87. }
  88. $bslFile = Join-Path (Join-Path (Join-Path $ExtensionPath $dirName) $objName) (Join-Path "Ext" $moduleFileName)
  89. } else {
  90. Write-Error "Invalid ModulePath format: $ModulePath. Expected: Type.Name.Module, Type.Name.Form.FormName, or CommonModule.Name"
  91. exit 1
  92. }
  93. # --- Map InterceptorType to decorator ---
  94. $decorator = switch ($InterceptorType) {
  95. "Before" { "&Перед" }
  96. "After" { "&После" }
  97. "ModificationAndControl" { "&ИзменениеИКонтроль" }
  98. }
  99. # --- Map Context to annotation ---
  100. $contextAnnotation = switch ($Context) {
  101. "НаСервере" { "&НаСервере" }
  102. "НаКлиенте" { "&НаКлиенте" }
  103. "НаСервереБезКонтекста" { "&НаСервереБезКонтекста" }
  104. default { "&$Context" }
  105. }
  106. # --- Procedure name ---
  107. $procName = "${namePrefix}${MethodName}"
  108. # --- Generate BSL code ---
  109. $keyword = if ($IsFunction) { "Функция" } else { "Процедура" }
  110. $endKeyword = if ($IsFunction) { "КонецФункции" } else { "КонецПроцедуры" }
  111. $bodyLines = @()
  112. switch ($InterceptorType) {
  113. "Before" {
  114. $bodyLines += "`t// TODO: код перед вызовом оригинального метода"
  115. }
  116. "After" {
  117. $bodyLines += "`t// TODO: код после вызова оригинального метода"
  118. }
  119. "ModificationAndControl" {
  120. $bodyLines += "`t// Скопируйте тело оригинального метода и внесите изменения,"
  121. $bodyLines += "`t// используя маркеры #Удаление / #КонецУдаления и #Вставка / #КонецВставки"
  122. }
  123. }
  124. if ($IsFunction) {
  125. $bodyLines += "`t"
  126. $bodyLines += "`tВозврат Неопределено; // TODO: заменить на реальное возвращаемое значение"
  127. }
  128. $bslCode = @()
  129. $bslCode += "$contextAnnotation"
  130. $bslCode += "${decorator}(`"$MethodName`")"
  131. $bslCode += "$keyword ${procName}()"
  132. $bslCode += $bodyLines
  133. $bslCode += "$endKeyword"
  134. $bslText = ($bslCode -join "`r`n") + "`r`n"
  135. # --- Check if file exists and append ---
  136. $bslDir = Split-Path $bslFile -Parent
  137. if (-not (Test-Path $bslDir)) {
  138. New-Item -ItemType Directory -Path $bslDir -Force | Out-Null
  139. }
  140. $enc = New-Object System.Text.UTF8Encoding($true)
  141. if (Test-Path $bslFile) {
  142. # Append to existing file
  143. $existing = [System.IO.File]::ReadAllText($bslFile, $enc)
  144. $separator = "`r`n"
  145. if ($existing -and -not $existing.EndsWith("`n")) {
  146. $separator = "`r`n`r`n"
  147. }
  148. $newContent = $existing + $separator + $bslText
  149. [System.IO.File]::WriteAllText($bslFile, $newContent, $enc)
  150. Write-Host "[OK] Добавлен перехватчик в существующий файл"
  151. } else {
  152. [System.IO.File]::WriteAllText($bslFile, $bslText, $enc)
  153. Write-Host "[OK] Создан файл модуля"
  154. }
  155. Write-Host " Файл: $bslFile"
  156. Write-Host " Декоратор: $decorator(`"$MethodName`")"
  157. Write-Host " Процедура: ${procName}()"
  158. Write-Host " Контекст: $contextAnnotation"
.claude/skills/meta-compile/scripts/meta-compile.ps1 · Bundled script · 2,827 lines
  1. # meta-compile v1.0 — Compile 1C metadata object from JSON
  2. # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
  3. param(
  4. [Parameter(Mandatory)]
  5. [string]$JsonPath,
  6. [Parameter(Mandatory)]
  7. [string]$OutputDir
  8. )
  9. $ErrorActionPreference = "Stop"
  10. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  11. # --- 1. Load and validate JSON ---
  12. if (-not (Test-Path $JsonPath)) {
  13. Write-Error "File not found: $JsonPath"
  14. exit 1
  15. }
  16. $json = Get-Content -Raw -Encoding UTF8 $JsonPath
  17. $def = $json | ConvertFrom-Json
  18. # Normalize field synonyms: accept "objectType" as alias for "type"
  19. if (-not $def.type -and $def.objectType) {
  20. $def | Add-Member -NotePropertyName "type" -NotePropertyValue $def.objectType
  21. }
  22. # Object type synonyms (Russian → English)
  23. $script:objectTypeSynonyms = @{
  24. "Справочник" = "Catalog"
  25. "Каталог" = "Catalog"
  26. "Документ" = "Document"
  27. "Перечисление" = "Enum"
  28. "Константа" = "Constant"
  29. "РегистрСведений" = "InformationRegister"
  30. "РегистрНакопления" = "AccumulationRegister"
  31. "РегистрБухгалтерии" = "AccountingRegister"
  32. "РегистрРасчёта" = "CalculationRegister"
  33. "РегистрРасчета" = "CalculationRegister"
  34. "ПланСчетов" = "ChartOfAccounts"
  35. "ПланВидовХарактеристик" = "ChartOfCharacteristicTypes"
  36. "ПланВидовРасчёта" = "ChartOfCalculationTypes"
  37. "ПланВидовРасчета" = "ChartOfCalculationTypes"
  38. "БизнесПроцесс" = "BusinessProcess"
  39. "Задача" = "Task"
  40. "ПланОбмена" = "ExchangePlan"
  41. "ЖурналДокументов" = "DocumentJournal"
  42. "Отчёт" = "Report"
  43. "Отчет" = "Report"
  44. "Обработка" = "DataProcessor"
  45. "ОбщийМодуль" = "CommonModule"
  46. "РегламентноеЗадание" = "ScheduledJob"
  47. "ПодпискаНаСобытие" = "EventSubscription"
  48. "HTTPСервис" = "HTTPService"
  49. "ВебСервис" = "WebService"
  50. "ОпределяемыйТип" = "DefinedType"
  51. }
  52. if (-not $def.type) {
  53. Write-Error "JSON must have 'type' field"
  54. exit 1
  55. }
  56. # Resolve type synonym
  57. $objType = "$($def.type)"
  58. if ($script:objectTypeSynonyms.ContainsKey($objType)) {
  59. $objType = $script:objectTypeSynonyms[$objType]
  60. }
  61. $validTypes = @("Catalog","Document","Enum","Constant","InformationRegister","AccumulationRegister",
  62. "AccountingRegister","CalculationRegister","ChartOfAccounts","ChartOfCharacteristicTypes",
  63. "ChartOfCalculationTypes","BusinessProcess","Task","ExchangePlan","DocumentJournal",
  64. "Report","DataProcessor","CommonModule","ScheduledJob","EventSubscription",
  65. "HTTPService","WebService","DefinedType")
  66. if ($objType -notin $validTypes) {
  67. Write-Error "Unsupported type: $objType. Valid: $($validTypes -join ', ')"
  68. exit 1
  69. }
  70. if (-not $def.name) {
  71. Write-Error "JSON must have 'name' field"
  72. exit 1
  73. }
  74. $objName = "$($def.name)"
  75. # --- 2. XML helpers ---
  76. $script:xml = New-Object System.Text.StringBuilder 32768
  77. function X {
  78. param([string]$text)
  79. $script:xml.AppendLine($text) | Out-Null
  80. }
  81. function Esc-Xml {
  82. param([string]$s)
  83. return $s.Replace('&','&amp;').Replace('<','&lt;').Replace('>','&gt;').Replace('"','&quot;')
  84. }
  85. function Emit-MLText {
  86. param([string]$indent, [string]$tag, [string]$text)
  87. if (-not $text) {
  88. X "$indent<$tag/>"
  89. return
  90. }
  91. X "$indent<$tag>"
  92. X "$indent`t<v8:item>"
  93. X "$indent`t`t<v8:lang>ru</v8:lang>"
  94. X "$indent`t`t<v8:content>$(Esc-Xml $text)</v8:content>"
  95. X "$indent`t</v8:item>"
  96. X "$indent</$tag>"
  97. }
  98. function New-Guid-String {
  99. return [System.Guid]::NewGuid().ToString()
  100. }
  101. # --- 3. CamelCase splitter ---
  102. function Split-CamelCase {
  103. param([string]$name)
  104. if (-not $name) { return $name }
  105. # Insert space before uppercase that follows lowercase (Cyrillic + Latin)
  106. $result = [regex]::Replace($name, '([а-яё])([А-ЯЁ])', '$1 $2')
  107. $result = [regex]::Replace($result, '([a-z])([A-Z])', '$1 $2')
  108. # Lowercase all but first character of the result
  109. if ($result.Length -gt 1) {
  110. $result = $result.Substring(0,1) + $result.Substring(1).ToLower()
  111. }
  112. return $result
  113. }
  114. # Auto-synonym
  115. $synonym = if ($def.synonym) { "$($def.synonym)" } else { Split-CamelCase $objName }
  116. $comment = if ($def.comment) { "$($def.comment)" } else { "" }
  117. # --- 4. Type system ---
  118. $script:typeSynonyms = New-Object System.Collections.Hashtable
  119. $script:typeSynonyms["число"] = "Number"
  120. $script:typeSynonyms["строка"] = "String"
  121. $script:typeSynonyms["булево"] = "Boolean"
  122. $script:typeSynonyms["дата"] = "Date"
  123. $script:typeSynonyms["датавремя"]= "DateTime"
  124. $script:typeSynonyms["number"] = "Number"
  125. $script:typeSynonyms["string"] = "String"
  126. $script:typeSynonyms["boolean"] = "Boolean"
  127. $script:typeSynonyms["date"] = "Date"
  128. $script:typeSynonyms["datetime"] = "DateTime"
  129. $script:typeSynonyms["bool"] = "Boolean"
  130. # Reference synonyms (Russian, lowercase)
  131. $script:typeSynonyms["справочникссылка"] = "CatalogRef"
  132. $script:typeSynonyms["документссылка"] = "DocumentRef"
  133. $script:typeSynonyms["перечислениессылка"] = "EnumRef"
  134. $script:typeSynonyms["плансчетовссылка"] = "ChartOfAccountsRef"
  135. $script:typeSynonyms["планвидовхарактеристикссылка"] = "ChartOfCharacteristicTypesRef"
  136. $script:typeSynonyms["планвидоврасчётассылка"] = "ChartOfCalculationTypesRef"
  137. $script:typeSynonyms["планвидоврасчетассылка"] = "ChartOfCalculationTypesRef"
  138. $script:typeSynonyms["планобменассылка"] = "ExchangePlanRef"
  139. $script:typeSynonyms["бизнеспроцессссылка"] = "BusinessProcessRef"
  140. $script:typeSynonyms["задачассылка"] = "TaskRef"
  141. $script:typeSynonyms["определяемыйтип"] = "DefinedType"
  142. $script:typeSynonyms["definedtype"] = "DefinedType"
  143. function Resolve-TypeStr {
  144. param([string]$typeStr)
  145. if (-not $typeStr) { return $typeStr }
  146. # Check for parameterized types: Number(15,2), Строка(100), etc.
  147. if ($typeStr -match '^([^(]+)\((.+)\)$') {
  148. $baseName = $Matches[1].Trim()
  149. $params = $Matches[2]
  150. $resolved = $script:typeSynonyms[$baseName.ToLower()]
  151. if ($resolved) { return "$resolved($params)" }
  152. return $typeStr
  153. }
  154. # Check for reference types: СправочникСсылка.Организации → CatalogRef.Организации
  155. if ($typeStr.Contains('.')) {
  156. $dotIdx = $typeStr.IndexOf('.')
  157. $prefix = $typeStr.Substring(0, $dotIdx)
  158. $suffix = $typeStr.Substring($dotIdx) # includes the dot
  159. $resolved = $script:typeSynonyms[$prefix.ToLower()]
  160. if ($resolved) { return "$resolved$suffix" }
  161. return $typeStr
  162. }
  163. # Simple name lookup
  164. $resolved = $script:typeSynonyms[$typeStr.ToLower()]
  165. if ($resolved) { return $resolved }
  166. return $typeStr
  167. }
  168. function Emit-TypeContent {
  169. param([string]$indent, [string]$typeStr)
  170. if (-not $typeStr) { return }
  171. $typeStr = Resolve-TypeStr $typeStr
  172. # Boolean
  173. if ($typeStr -eq "Boolean") {
  174. X "$indent<v8:Type>xs:boolean</v8:Type>"
  175. return
  176. }
  177. # String or String(N)
  178. if ($typeStr -match '^String(\((\d+)\))?$') {
  179. $len = if ($Matches[2]) { $Matches[2] } else { "0" }
  180. X "$indent<v8:Type>xs:string</v8:Type>"
  181. X "$indent<v8:StringQualifiers>"
  182. X "$indent`t<v8:Length>$len</v8:Length>"
  183. X "$indent`t<v8:AllowedLength>Variable</v8:AllowedLength>"
  184. X "$indent</v8:StringQualifiers>"
  185. return
  186. }
  187. # Number(D,F) or Number(D,F,nonneg)
  188. if ($typeStr -match '^Number\((\d+),(\d+)(,nonneg)?\)$') {
  189. $digits = $Matches[1]
  190. $fraction = $Matches[2]
  191. $sign = if ($Matches[3]) { "Nonnegative" } else { "Any" }
  192. X "$indent<v8:Type>xs:decimal</v8:Type>"
  193. X "$indent<v8:NumberQualifiers>"
  194. X "$indent`t<v8:Digits>$digits</v8:Digits>"
  195. X "$indent`t<v8:FractionDigits>$fraction</v8:FractionDigits>"
  196. X "$indent`t<v8:AllowedSign>$sign</v8:AllowedSign>"
  197. X "$indent</v8:NumberQualifiers>"
  198. return
  199. }
  200. # Date / DateTime
  201. if ($typeStr -eq "Date") {
  202. X "$indent<v8:Type>xs:dateTime</v8:Type>"
  203. X "$indent<v8:DateQualifiers>"
  204. X "$indent`t<v8:DateFractions>Date</v8:DateFractions>"
  205. X "$indent</v8:DateQualifiers>"
  206. return
  207. }
  208. if ($typeStr -eq "DateTime") {
  209. X "$indent<v8:Type>xs:dateTime</v8:Type>"
  210. X "$indent<v8:DateQualifiers>"
  211. X "$indent`t<v8:DateFractions>DateTime</v8:DateFractions>"
  212. X "$indent</v8:DateQualifiers>"
  213. return
  214. }
  215. # DefinedType
  216. if ($typeStr -match '^DefinedType\.(.+)$') {
  217. $dtName = $Matches[1]
  218. X "$indent<v8:TypeSet>cfg:DefinedType.$dtName</v8:TypeSet>"
  219. return
  220. }
  221. # Reference types: CatalogRef.XXX, DocumentRef.XXX, etc.
  222. if ($typeStr -match '^(CatalogRef|DocumentRef|EnumRef|ChartOfAccountsRef|ChartOfCharacteristicTypesRef|ChartOfCalculationTypesRef|ExchangePlanRef|BusinessProcessRef|TaskRef)\.(.+)$') {
  223. X "$indent<v8:Type>cfg:$typeStr</v8:Type>"
  224. return
  225. }
  226. # Fallback — emit as-is
  227. X "$indent<v8:Type>$typeStr</v8:Type>"
  228. }
  229. function Emit-ValueType {
  230. param([string]$indent, [string]$typeStr)
  231. X "$indent<Type>"
  232. Emit-TypeContent "$indent`t" $typeStr
  233. X "$indent</Type>"
  234. }
  235. function Emit-FillValue {
  236. param([string]$indent, [string]$typeStr)
  237. if (-not $typeStr) {
  238. X "$indent<FillValue xsi:nil=`"true`"/>"
  239. return
  240. }
  241. $typeStr = Resolve-TypeStr $typeStr
  242. if ($typeStr -eq "Boolean") {
  243. X "$indent<FillValue xsi:type=`"xs:boolean`">false</FillValue>"
  244. return
  245. }
  246. if ($typeStr -match '^String') {
  247. X "$indent<FillValue xsi:type=`"xs:string`"/>"
  248. return
  249. }
  250. if ($typeStr -match '^Number') {
  251. X "$indent<FillValue xsi:type=`"xs:decimal`">0</FillValue>"
  252. return
  253. }
  254. if ($typeStr -match '^(Date|DateTime)$') {
  255. X "$indent<FillValue xsi:nil=`"true`"/>"
  256. return
  257. }
  258. # References and others
  259. X "$indent<FillValue xsi:nil=`"true`"/>"
  260. }
  261. # --- 5. Attribute shorthand parser ---
  262. function Parse-AttributeShorthand {
  263. param($val)
  264. if ($val -is [string]) {
  265. $str = "$val"
  266. $parsed = @{
  267. name = ""
  268. type = ""
  269. synonym = ""
  270. comment = ""
  271. flags = @()
  272. }
  273. # Split by | for flags
  274. $parts = $str -split '\|', 2
  275. $mainPart = $parts[0].Trim()
  276. if ($parts.Count -gt 1) {
  277. $flagStr = $parts[1].Trim()
  278. $parsed.flags = @($flagStr -split ',' | ForEach-Object { $_.Trim().ToLower() } | Where-Object { $_ })
  279. }
  280. # Split by : for name and type
  281. $colonParts = $mainPart -split ':', 2
  282. $parsed.name = $colonParts[0].Trim()
  283. if ($colonParts.Count -gt 1) {
  284. $parsed.type = $colonParts[1].Trim()
  285. }
  286. $parsed.synonym = Split-CamelCase $parsed.name
  287. return $parsed
  288. }
  289. # Object form
  290. $name = "$($val.name)"
  291. return @{
  292. name = $name
  293. type = if ($val.type) { "$($val.type)" } else { "" }
  294. synonym = if ($val.synonym) { "$($val.synonym)" } else { Split-CamelCase $name }
  295. comment = if ($val.comment) { "$($val.comment)" } else { "" }
  296. flags = @(if ($val.flags) { $val.flags } else { @() })
  297. fillChecking = if ($val.fillChecking) { "$($val.fillChecking)" } else { "" }
  298. indexing = if ($val.indexing) { "$($val.indexing)" } else { "" }
  299. }
  300. }
  301. function Parse-EnumValueShorthand {
  302. param($val)
  303. if ($val -is [string]) {
  304. $name = "$val"
  305. return @{
  306. name = $name
  307. synonym = Split-CamelCase $name
  308. comment = ""
  309. }
  310. }
  311. $name = "$($val.name)"
  312. return @{
  313. name = $name
  314. synonym = if ($val.synonym) { "$($val.synonym)" } else { Split-CamelCase $name }
  315. comment = if ($val.comment) { "$($val.comment)" } else { "" }
  316. }
  317. }
  318. # --- 6. GeneratedType categories ---
  319. $script:generatedTypes = @{
  320. "Catalog" = @(
  321. @{ prefix = "CatalogObject"; category = "Object" }
  322. @{ prefix = "CatalogRef"; category = "Ref" }
  323. @{ prefix = "CatalogSelection"; category = "Selection" }
  324. @{ prefix = "CatalogList"; category = "List" }
  325. @{ prefix = "CatalogManager"; category = "Manager" }
  326. )
  327. "Document" = @(
  328. @{ prefix = "DocumentObject"; category = "Object" }
  329. @{ prefix = "DocumentRef"; category = "Ref" }
  330. @{ prefix = "DocumentSelection"; category = "Selection" }
  331. @{ prefix = "DocumentList"; category = "List" }
  332. @{ prefix = "DocumentManager"; category = "Manager" }
  333. )
  334. "Enum" = @(
  335. @{ prefix = "EnumRef"; category = "Ref" }
  336. @{ prefix = "EnumManager"; category = "Manager" }
  337. @{ prefix = "EnumList"; category = "List" }
  338. )
  339. "Constant" = @(
  340. @{ prefix = "ConstantManager"; category = "Manager" }
  341. @{ prefix = "ConstantValueManager"; category = "ValueManager" }
  342. @{ prefix = "ConstantValueKey"; category = "ValueKey" }
  343. )
  344. "InformationRegister" = @(
  345. @{ prefix = "InformationRegisterRecord"; category = "Record" }
  346. @{ prefix = "InformationRegisterManager"; category = "Manager" }
  347. @{ prefix = "InformationRegisterSelection"; category = "Selection" }
  348. @{ prefix = "InformationRegisterList"; category = "List" }
  349. @{ prefix = "InformationRegisterRecordSet"; category = "RecordSet" }
  350. @{ prefix = "InformationRegisterRecordKey"; category = "RecordKey" }
  351. @{ prefix = "InformationRegisterRecordManager"; category = "RecordManager" }
  352. )
  353. "AccumulationRegister" = @(
  354. @{ prefix = "AccumulationRegisterRecord"; category = "Record" }
  355. @{ prefix = "AccumulationRegisterManager"; category = "Manager" }
  356. @{ prefix = "AccumulationRegisterSelection"; category = "Selection" }
  357. @{ prefix = "AccumulationRegisterList"; category = "List" }
  358. @{ prefix = "AccumulationRegisterRecordSet"; category = "RecordSet" }
  359. @{ prefix = "AccumulationRegisterRecordKey"; category = "RecordKey" }
  360. )
  361. "AccountingRegister" = @(
  362. @{ prefix = "AccountingRegisterRecord"; category = "Record" }
  363. @{ prefix = "AccountingRegisterManager"; category = "Manager" }
  364. @{ prefix = "AccountingRegisterSelection"; category = "Selection" }
  365. @{ prefix = "AccountingRegisterList"; category = "List" }
  366. @{ prefix = "AccountingRegisterRecordSet"; category = "RecordSet" }
  367. @{ prefix = "AccountingRegisterRecordKey"; category = "RecordKey" }
  368. )
  369. "CalculationRegister" = @(
  370. @{ prefix = "CalculationRegisterRecord"; category = "Record" }
  371. @{ prefix = "CalculationRegisterManager"; category = "Manager" }
  372. @{ prefix = "CalculationRegisterSelection"; category = "Selection" }
  373. @{ prefix = "CalculationRegisterList"; category = "List" }
  374. @{ prefix = "CalculationRegisterRecordSet"; category = "RecordSet" }
  375. @{ prefix = "CalculationRegisterRecordKey"; category = "RecordKey" }
  376. )
  377. "ChartOfAccounts" = @(
  378. @{ prefix = "ChartOfAccountsObject"; category = "Object" }
  379. @{ prefix = "ChartOfAccountsRef"; category = "Ref" }
  380. @{ prefix = "ChartOfAccountsSelection"; category = "Selection" }
  381. @{ prefix = "ChartOfAccountsList"; category = "List" }
  382. @{ prefix = "ChartOfAccountsManager"; category = "Manager" }
  383. )
  384. "ChartOfCharacteristicTypes" = @(
  385. @{ prefix = "ChartOfCharacteristicTypesObject"; category = "Object" }
  386. @{ prefix = "ChartOfCharacteristicTypesRef"; category = "Ref" }
  387. @{ prefix = "ChartOfCharacteristicTypesSelection"; category = "Selection" }
  388. @{ prefix = "ChartOfCharacteristicTypesList"; category = "List" }
  389. @{ prefix = "ChartOfCharacteristicTypesManager"; category = "Manager" }
  390. )
  391. "ChartOfCalculationTypes" = @(
  392. @{ prefix = "ChartOfCalculationTypesObject"; category = "Object" }
  393. @{ prefix = "ChartOfCalculationTypesRef"; category = "Ref" }
  394. @{ prefix = "ChartOfCalculationTypesSelection"; category = "Selection" }
  395. @{ prefix = "ChartOfCalculationTypesList"; category = "List" }
  396. @{ prefix = "ChartOfCalculationTypesManager"; category = "Manager" }
  397. @{ prefix = "DisplacingCalculationTypes"; category = "DisplacingCalculationTypes" }
  398. @{ prefix = "BaseCalculationTypes"; category = "BaseCalculationTypes" }
  399. @{ prefix = "LeadingCalculationTypes"; category = "LeadingCalculationTypes" }
  400. )
  401. "BusinessProcess" = @(
  402. @{ prefix = "BusinessProcessObject"; category = "Object" }
  403. @{ prefix = "BusinessProcessRef"; category = "Ref" }
  404. @{ prefix = "BusinessProcessSelection"; category = "Selection" }
  405. @{ prefix = "BusinessProcessList"; category = "List" }
  406. @{ prefix = "BusinessProcessManager"; category = "Manager" }
  407. )
  408. "Task" = @(
  409. @{ prefix = "TaskObject"; category = "Object" }
  410. @{ prefix = "TaskRef"; category = "Ref" }
  411. @{ prefix = "TaskSelection"; category = "Selection" }
  412. @{ prefix = "TaskList"; category = "List" }
  413. @{ prefix = "TaskManager"; category = "Manager" }
  414. )
  415. "ExchangePlan" = @(
  416. @{ prefix = "ExchangePlanObject"; category = "Object" }
  417. @{ prefix = "ExchangePlanRef"; category = "Ref" }
  418. @{ prefix = "ExchangePlanSelection"; category = "Selection" }
  419. @{ prefix = "ExchangePlanList"; category = "List" }
  420. @{ prefix = "ExchangePlanManager"; category = "Manager" }
  421. )
  422. "DocumentJournal" = @(
  423. @{ prefix = "DocumentJournalSelection"; category = "Selection" }
  424. @{ prefix = "DocumentJournalList"; category = "List" }
  425. @{ prefix = "DocumentJournalManager"; category = "Manager" }
  426. )
  427. "Report" = @(
  428. @{ prefix = "ReportObject"; category = "Object" }
  429. )
  430. "DataProcessor" = @(
  431. @{ prefix = "DataProcessorObject"; category = "Object" }
  432. )
  433. }
  434. function Emit-InternalInfo {
  435. param([string]$indent, [string]$objectType, [string]$objectName)
  436. $types = $script:generatedTypes[$objectType]
  437. if (-not $types) { return }
  438. X "$indent<InternalInfo>"
  439. # ExchangePlan: ThisNode UUID before GeneratedTypes
  440. if ($objectType -eq "ExchangePlan") {
  441. X "$indent`t<xr:ThisNode>$(New-Guid-String)</xr:ThisNode>"
  442. }
  443. foreach ($gt in $types) {
  444. $fullName = "$($gt.prefix).$objectName"
  445. X "$indent`t<xr:GeneratedType name=`"$fullName`" category=`"$($gt.category)`">"
  446. X "$indent`t`t<xr:TypeId>$(New-Guid-String)</xr:TypeId>"
  447. X "$indent`t`t<xr:ValueId>$(New-Guid-String)</xr:ValueId>"
  448. X "$indent`t</xr:GeneratedType>"
  449. }
  450. X "$indent</InternalInfo>"
  451. }
  452. # --- 7. StandardAttributes ---
  453. $script:standardAttributesByType = @{
  454. "Catalog" = @("PredefinedDataName","Predefined","Ref","DeletionMark","IsFolder","Owner","Parent","Description","Code")
  455. "Document" = @("Posted","Ref","DeletionMark","Date","Number")
  456. "Enum" = @("Order","Ref")
  457. "InformationRegister" = @("Active","LineNumber","Recorder","Period")
  458. "AccumulationRegister" = @("Active","LineNumber","Recorder","Period")
  459. "AccountingRegister" = @("Active","Period","Recorder","LineNumber","Account")
  460. "CalculationRegister" = @("Active","Recorder","LineNumber","RegistrationPeriod","CalculationType","ReversingEntry")
  461. "ChartOfAccounts" = @("PredefinedDataName","Predefined","Ref","DeletionMark","Description","Code","Parent","Order","Type","OffBalance")
  462. "ChartOfCharacteristicTypes" = @("PredefinedDataName","Predefined","Ref","DeletionMark","Description","Code","Parent","ValueType")
  463. "ChartOfCalculationTypes" = @("PredefinedDataName","Predefined","Ref","DeletionMark","Description","Code","ActionPeriodIsBasic")
  464. "BusinessProcess" = @("Ref","DeletionMark","Date","Number","Started","Completed","HeadTask")
  465. "Task" = @("Ref","DeletionMark","Date","Number","Executed","Description","RoutePoint","BusinessProcess")
  466. "ExchangePlan" = @("Ref","DeletionMark","Code","Description","ThisNode","SentNo","ReceivedNo")
  467. "DocumentJournal" = @("Type","Ref","Date","Posted","DeletionMark","Number")
  468. }
  469. function Emit-StandardAttribute {
  470. param([string]$indent, [string]$attrName)
  471. X "$indent<xr:StandardAttribute name=`"$attrName`">"
  472. X "$indent`t<xr:LinkByType/>"
  473. X "$indent`t<xr:FillChecking>DontCheck</xr:FillChecking>"
  474. X "$indent`t<xr:MultiLine>false</xr:MultiLine>"
  475. X "$indent`t<xr:FillFromFillingValue>false</xr:FillFromFillingValue>"
  476. X "$indent`t<xr:CreateOnInput>Auto</xr:CreateOnInput>"
  477. X "$indent`t<xr:MaxValue xsi:nil=`"true`"/>"
  478. X "$indent`t<xr:ToolTip/>"
  479. X "$indent`t<xr:ExtendedEdit>false</xr:ExtendedEdit>"
  480. X "$indent`t<xr:Format/>"
  481. X "$indent`t<xr:ChoiceForm/>"
  482. X "$indent`t<xr:QuickChoice>Auto</xr:QuickChoice>"
  483. X "$indent`t<xr:ChoiceHistoryOnInput>Auto</xr:ChoiceHistoryOnInput>"
  484. X "$indent`t<xr:EditFormat/>"
  485. X "$indent`t<xr:PasswordMode>false</xr:PasswordMode>"
  486. X "$indent`t<xr:DataHistory>Use</xr:DataHistory>"
  487. X "$indent`t<xr:MarkNegatives>false</xr:MarkNegatives>"
  488. X "$indent`t<xr:MinValue xsi:nil=`"true`"/>"
  489. X "$indent`t<xr:Synonym/>"
  490. X "$indent`t<xr:Comment/>"
  491. X "$indent`t<xr:FullTextSearch>Use</xr:FullTextSearch>"
  492. X "$indent`t<xr:ChoiceParameterLinks/>"
  493. X "$indent`t<xr:FillValue xsi:nil=`"true`"/>"
  494. X "$indent`t<xr:Mask/>"
  495. X "$indent`t<xr:ChoiceParameters/>"
  496. X "$indent</xr:StandardAttribute>"
  497. }
  498. function Emit-StandardAttributes {
  499. param([string]$indent, [string]$objectType)
  500. $attrs = $script:standardAttributesByType[$objectType]
  501. if (-not $attrs) { return }
  502. X "$indent<StandardAttributes>"
  503. foreach ($a in $attrs) {
  504. Emit-StandardAttribute "$indent`t" $a
  505. }
  506. X "$indent</StandardAttributes>"
  507. }
  508. # TabularSection standard attributes (just LineNumber)
  509. function Emit-TabularStandardAttributes {
  510. param([string]$indent)
  511. X "$indent<StandardAttributes>"
  512. Emit-StandardAttribute "$indent`t" "LineNumber"
  513. X "$indent</StandardAttributes>"
  514. }
  515. # --- 8. Attribute emitter ---
  516. function Emit-Attribute {
  517. param([string]$indent, $parsed, [string]$context)
  518. # $context: "catalog", "document", "object", "processor", "tabular", "processor-tabular", "register"
  519. $uuid = New-Guid-String
  520. X "$indent<Attribute uuid=`"$uuid`">"
  521. X "$indent`t<Properties>"
  522. X "$indent`t`t<Name>$(Esc-Xml $parsed.name)</Name>"
  523. Emit-MLText "$indent`t`t" "Synonym" $parsed.synonym
  524. X "$indent`t`t<Comment/>"
  525. # Type
  526. $typeStr = $parsed.type
  527. if ($typeStr) {
  528. Emit-ValueType "$indent`t`t" $typeStr
  529. } else {
  530. # Default: unqualified string
  531. X "$indent`t`t<Type>"
  532. X "$indent`t`t`t<v8:Type>xs:string</v8:Type>"
  533. X "$indent`t`t</Type>"
  534. }
  535. X "$indent`t`t<PasswordMode>false</PasswordMode>"
  536. X "$indent`t`t<Format/>"
  537. X "$indent`t`t<EditFormat/>"
  538. X "$indent`t`t<ToolTip/>"
  539. X "$indent`t`t<MarkNegatives>false</MarkNegatives>"
  540. X "$indent`t`t<Mask/>"
  541. X "$indent`t`t<MultiLine>false</MultiLine>"
  542. X "$indent`t`t<ExtendedEdit>false</ExtendedEdit>"
  543. X "$indent`t`t<MinValue xsi:nil=`"true`"/>"
  544. X "$indent`t`t<MaxValue xsi:nil=`"true`"/>"
  545. # FillFromFillingValue — not for tabular/processor (non-stored objects don't have these)
  546. if ($context -notin @("tabular", "processor")) {
  547. X "$indent`t`t<FillFromFillingValue>false</FillFromFillingValue>"
  548. }
  549. # FillValue — not for tabular/processor
  550. if ($context -notin @("tabular", "processor")) {
  551. Emit-FillValue "$indent`t`t" $typeStr
  552. }
  553. # FillChecking
  554. $fillChecking = "DontCheck"
  555. if ($parsed.flags -contains "req") { $fillChecking = "ShowError" }
  556. if ($parsed.fillChecking) { $fillChecking = $parsed.fillChecking }
  557. X "$indent`t`t<FillChecking>$fillChecking</FillChecking>"
  558. X "$indent`t`t<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>"
  559. X "$indent`t`t<ChoiceParameterLinks/>"
  560. X "$indent`t`t<ChoiceParameters/>"
  561. X "$indent`t`t<QuickChoice>Auto</QuickChoice>"
  562. X "$indent`t`t<CreateOnInput>Auto</CreateOnInput>"
  563. X "$indent`t`t<ChoiceForm/>"
  564. X "$indent`t`t<LinkByType/>"
  565. X "$indent`t`t<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  566. # Use — only for catalog top-level attributes
  567. if ($context -eq "catalog") {
  568. X "$indent`t`t<Use>ForItem</Use>"
  569. }
  570. # Indexing/FullTextSearch/DataHistory — not for non-stored objects (processor, processor-tabular)
  571. if ($context -notin @("processor", "processor-tabular")) {
  572. $indexing = "DontIndex"
  573. if ($parsed.flags -contains "index") { $indexing = "Index" }
  574. if ($parsed.flags -contains "indexadditional") { $indexing = "IndexWithAdditionalOrder" }
  575. if ($parsed.indexing) { $indexing = $parsed.indexing }
  576. X "$indent`t`t<Indexing>$indexing</Indexing>"
  577. X "$indent`t`t<FullTextSearch>Use</FullTextSearch>"
  578. X "$indent`t`t<DataHistory>Use</DataHistory>"
  579. }
  580. X "$indent`t</Properties>"
  581. X "$indent</Attribute>"
  582. }
  583. # --- 9. TabularSection emitter ---
  584. function Emit-TabularSection {
  585. param([string]$indent, [string]$tsName, $columns, [string]$objectType, [string]$objectName)
  586. $uuid = New-Guid-String
  587. X "$indent<TabularSection uuid=`"$uuid`">"
  588. # InternalInfo for TabularSection
  589. $typePrefix = "${objectType}TabularSection"
  590. $rowPrefix = "${objectType}TabularSectionRow"
  591. X "$indent`t<InternalInfo>"
  592. X "$indent`t`t<xr:GeneratedType name=`"$typePrefix.$objectName.$tsName`" category=`"TabularSection`">"
  593. X "$indent`t`t`t<xr:TypeId>$(New-Guid-String)</xr:TypeId>"
  594. X "$indent`t`t`t<xr:ValueId>$(New-Guid-String)</xr:ValueId>"
  595. X "$indent`t`t</xr:GeneratedType>"
  596. X "$indent`t`t<xr:GeneratedType name=`"$rowPrefix.$objectName.$tsName`" category=`"TabularSectionRow`">"
  597. X "$indent`t`t`t<xr:TypeId>$(New-Guid-String)</xr:TypeId>"
  598. X "$indent`t`t`t<xr:ValueId>$(New-Guid-String)</xr:ValueId>"
  599. X "$indent`t`t</xr:GeneratedType>"
  600. X "$indent`t</InternalInfo>"
  601. $tsSynonym = Split-CamelCase $tsName
  602. X "$indent`t<Properties>"
  603. X "$indent`t`t<Name>$(Esc-Xml $tsName)</Name>"
  604. Emit-MLText "$indent`t`t" "Synonym" $tsSynonym
  605. X "$indent`t`t<Comment/>"
  606. X "$indent`t`t<ToolTip/>"
  607. X "$indent`t`t<FillChecking>DontCheck</FillChecking>"
  608. Emit-TabularStandardAttributes "$indent`t`t"
  609. # Use=ForItem only for Catalog tabular sections (Document does not have Use)
  610. if ($objectType -eq "Catalog") {
  611. X "$indent`t`t<Use>ForItem</Use>"
  612. }
  613. X "$indent`t</Properties>"
  614. $tsContext = if ($objectType -in @("DataProcessor","Report")) { "processor-tabular" } else { "tabular" }
  615. X "$indent`t<ChildObjects>"
  616. foreach ($col in $columns) {
  617. $parsed = Parse-AttributeShorthand $col
  618. Emit-Attribute "$indent`t`t" $parsed $tsContext
  619. }
  620. X "$indent`t</ChildObjects>"
  621. X "$indent</TabularSection>"
  622. }
  623. # --- 10. EnumValue emitter ---
  624. function Emit-EnumValue {
  625. param([string]$indent, $parsed)
  626. $uuid = New-Guid-String
  627. X "$indent<EnumValue uuid=`"$uuid`">"
  628. X "$indent`t<Properties>"
  629. X "$indent`t`t<Name>$(Esc-Xml $parsed.name)</Name>"
  630. Emit-MLText "$indent`t`t" "Synonym" $parsed.synonym
  631. X "$indent`t`t<Comment/>"
  632. X "$indent`t</Properties>"
  633. X "$indent</EnumValue>"
  634. }
  635. # --- 11. Dimension emitter ---
  636. function Emit-Dimension {
  637. param([string]$indent, $parsed, [string]$registerType)
  638. # $registerType: "InformationRegister" or "AccumulationRegister"
  639. $uuid = New-Guid-String
  640. X "$indent<Dimension uuid=`"$uuid`">"
  641. X "$indent`t<Properties>"
  642. X "$indent`t`t<Name>$(Esc-Xml $parsed.name)</Name>"
  643. Emit-MLText "$indent`t`t" "Synonym" $parsed.synonym
  644. X "$indent`t`t<Comment/>"
  645. $typeStr = $parsed.type
  646. if ($typeStr) {
  647. Emit-ValueType "$indent`t`t" $typeStr
  648. } else {
  649. X "$indent`t`t<Type>"
  650. X "$indent`t`t`t<v8:Type>xs:string</v8:Type>"
  651. X "$indent`t`t</Type>"
  652. }
  653. X "$indent`t`t<PasswordMode>false</PasswordMode>"
  654. X "$indent`t`t<Format/>"
  655. X "$indent`t`t<EditFormat/>"
  656. X "$indent`t`t<ToolTip/>"
  657. X "$indent`t`t<MarkNegatives>false</MarkNegatives>"
  658. X "$indent`t`t<Mask/>"
  659. X "$indent`t`t<MultiLine>false</MultiLine>"
  660. X "$indent`t`t<ExtendedEdit>false</ExtendedEdit>"
  661. X "$indent`t`t<MinValue xsi:nil=`"true`"/>"
  662. X "$indent`t`t<MaxValue xsi:nil=`"true`"/>"
  663. # InformationRegister dimensions have FillFromFillingValue
  664. if ($registerType -eq "InformationRegister") {
  665. $fillFrom = if ($parsed.flags -contains "master") { "true" } else { "false" }
  666. X "$indent`t`t<FillFromFillingValue>$fillFrom</FillFromFillingValue>"
  667. X "$indent`t`t<FillValue xsi:nil=`"true`"/>"
  668. }
  669. $fillChecking = "DontCheck"
  670. if ($parsed.flags -contains "req") { $fillChecking = "ShowError" }
  671. X "$indent`t`t<FillChecking>$fillChecking</FillChecking>"
  672. X "$indent`t`t<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>"
  673. X "$indent`t`t<ChoiceParameterLinks/>"
  674. X "$indent`t`t<ChoiceParameters/>"
  675. X "$indent`t`t<QuickChoice>Auto</QuickChoice>"
  676. X "$indent`t`t<CreateOnInput>Auto</CreateOnInput>"
  677. X "$indent`t`t<ChoiceForm/>"
  678. X "$indent`t`t<LinkByType/>"
  679. X "$indent`t`t<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  680. # InformationRegister dimensions: Master, MainFilter, DenyIncompleteValues
  681. if ($registerType -eq "InformationRegister") {
  682. $master = if ($parsed.flags -contains "master") { "true" } else { "false" }
  683. $mainFilter = if ($parsed.flags -contains "mainfilter") { "true" } else { "false" }
  684. $denyIncomplete = if ($parsed.flags -contains "denyincomplete") { "true" } else { "false" }
  685. X "$indent`t`t<Master>$master</Master>"
  686. X "$indent`t`t<MainFilter>$mainFilter</MainFilter>"
  687. X "$indent`t`t<DenyIncompleteValues>$denyIncomplete</DenyIncompleteValues>"
  688. }
  689. # AccumulationRegister dimensions: DenyIncompleteValues
  690. if ($registerType -eq "AccumulationRegister") {
  691. $denyIncomplete = if ($parsed.flags -contains "denyincomplete") { "true" } else { "false" }
  692. X "$indent`t`t<DenyIncompleteValues>$denyIncomplete</DenyIncompleteValues>"
  693. }
  694. $indexing = "DontIndex"
  695. if ($parsed.flags -contains "index") { $indexing = "Index" }
  696. X "$indent`t`t<Indexing>$indexing</Indexing>"
  697. X "$indent`t`t<FullTextSearch>Use</FullTextSearch>"
  698. # AccumulationRegister dimensions: UseInTotals
  699. if ($registerType -eq "AccumulationRegister") {
  700. $useInTotals = if ($parsed.flags -contains "nouseintotals") { "false" } else { "true" }
  701. X "$indent`t`t<UseInTotals>$useInTotals</UseInTotals>"
  702. }
  703. # InformationRegister dimensions: DataHistory
  704. if ($registerType -eq "InformationRegister") {
  705. X "$indent`t`t<DataHistory>Use</DataHistory>"
  706. }
  707. X "$indent`t</Properties>"
  708. X "$indent</Dimension>"
  709. }
  710. # --- 12. Resource emitter ---
  711. function Emit-Resource {
  712. param([string]$indent, $parsed, [string]$registerType)
  713. $uuid = New-Guid-String
  714. X "$indent<Resource uuid=`"$uuid`">"
  715. X "$indent`t<Properties>"
  716. X "$indent`t`t<Name>$(Esc-Xml $parsed.name)</Name>"
  717. Emit-MLText "$indent`t`t" "Synonym" $parsed.synonym
  718. X "$indent`t`t<Comment/>"
  719. $typeStr = $parsed.type
  720. if ($typeStr) {
  721. Emit-ValueType "$indent`t`t" $typeStr
  722. } else {
  723. X "$indent`t`t<Type>"
  724. X "$indent`t`t`t<v8:Type>xs:decimal</v8:Type>"
  725. X "$indent`t`t`t<v8:NumberQualifiers>"
  726. X "$indent`t`t`t`t<v8:Digits>15</v8:Digits>"
  727. X "$indent`t`t`t`t<v8:FractionDigits>2</v8:FractionDigits>"
  728. X "$indent`t`t`t`t<v8:AllowedSign>Any</v8:AllowedSign>"
  729. X "$indent`t`t`t</v8:NumberQualifiers>"
  730. X "$indent`t`t</Type>"
  731. }
  732. X "$indent`t`t<PasswordMode>false</PasswordMode>"
  733. X "$indent`t`t<Format/>"
  734. X "$indent`t`t<EditFormat/>"
  735. X "$indent`t`t<ToolTip/>"
  736. X "$indent`t`t<MarkNegatives>false</MarkNegatives>"
  737. X "$indent`t`t<Mask/>"
  738. X "$indent`t`t<MultiLine>false</MultiLine>"
  739. X "$indent`t`t<ExtendedEdit>false</ExtendedEdit>"
  740. X "$indent`t`t<MinValue xsi:nil=`"true`"/>"
  741. X "$indent`t`t<MaxValue xsi:nil=`"true`"/>"
  742. # InformationRegister resources have FillFromFillingValue, FillValue
  743. if ($registerType -eq "InformationRegister") {
  744. X "$indent`t`t<FillFromFillingValue>false</FillFromFillingValue>"
  745. X "$indent`t`t<FillValue xsi:nil=`"true`"/>"
  746. }
  747. $fillChecking = "DontCheck"
  748. if ($parsed.flags -contains "req") { $fillChecking = "ShowError" }
  749. X "$indent`t`t<FillChecking>$fillChecking</FillChecking>"
  750. X "$indent`t`t<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>"
  751. X "$indent`t`t<ChoiceParameterLinks/>"
  752. X "$indent`t`t<ChoiceParameters/>"
  753. X "$indent`t`t<QuickChoice>Auto</QuickChoice>"
  754. X "$indent`t`t<CreateOnInput>Auto</CreateOnInput>"
  755. X "$indent`t`t<ChoiceForm/>"
  756. X "$indent`t`t<LinkByType/>"
  757. X "$indent`t`t<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  758. # InformationRegister resources: Indexing, FullTextSearch, DataHistory
  759. if ($registerType -eq "InformationRegister") {
  760. X "$indent`t`t<Indexing>DontIndex</Indexing>"
  761. X "$indent`t`t<FullTextSearch>Use</FullTextSearch>"
  762. X "$indent`t`t<DataHistory>Use</DataHistory>"
  763. }
  764. # AccumulationRegister resources: FullTextSearch (no Indexing, no DataHistory)
  765. if ($registerType -eq "AccumulationRegister") {
  766. X "$indent`t`t<FullTextSearch>Use</FullTextSearch>"
  767. }
  768. X "$indent`t</Properties>"
  769. X "$indent</Resource>"
  770. }
  771. # --- 13. Property emitters per type ---
  772. function Emit-CatalogProperties {
  773. param([string]$indent)
  774. $i = $indent
  775. X "$i<Name>$(Esc-Xml $objName)</Name>"
  776. Emit-MLText $i "Synonym" $synonym
  777. X "$i<Comment/>"
  778. $hierarchical = if ($def.hierarchical -eq $true) { "true" } else { "false" }
  779. $hierarchyType = if ($def.hierarchyType) { "$($def.hierarchyType)" } else { "HierarchyFoldersAndItems" }
  780. X "$i<Hierarchical>$hierarchical</Hierarchical>"
  781. X "$i<HierarchyType>$hierarchyType</HierarchyType>"
  782. X "$i<LimitLevelCount>false</LimitLevelCount>"
  783. X "$i<LevelCount>2</LevelCount>"
  784. X "$i<FoldersOnTop>true</FoldersOnTop>"
  785. X "$i<UseStandardCommands>true</UseStandardCommands>"
  786. X "$i<Owners/>"
  787. X "$i<SubordinationUse>ToItems</SubordinationUse>"
  788. $codeLength = if ($null -ne $def.codeLength) { "$($def.codeLength)" } else { "9" }
  789. $descriptionLength = if ($null -ne $def.descriptionLength) { "$($def.descriptionLength)" } else { "25" }
  790. $codeType = if ($def.codeType) { "$($def.codeType)" } else { "String" }
  791. $codeAllowedLength = if ($def.codeAllowedLength) { "$($def.codeAllowedLength)" } else { "Variable" }
  792. $autonumbering = if ($def.autonumbering -eq $false) { "false" } else { "true" }
  793. $checkUnique = if ($def.checkUnique -eq $true) { "true" } else { "false" }
  794. X "$i<CodeLength>$codeLength</CodeLength>"
  795. X "$i<DescriptionLength>$descriptionLength</DescriptionLength>"
  796. X "$i<CodeType>$codeType</CodeType>"
  797. X "$i<CodeAllowedLength>$codeAllowedLength</CodeAllowedLength>"
  798. X "$i<CodeSeries>WholeCatalog</CodeSeries>"
  799. X "$i<CheckUnique>$checkUnique</CheckUnique>"
  800. X "$i<Autonumbering>$autonumbering</Autonumbering>"
  801. $defaultPresentation = if ($def.defaultPresentation) { "$($def.defaultPresentation)" } else { "AsDescription" }
  802. X "$i<DefaultPresentation>$defaultPresentation</DefaultPresentation>"
  803. Emit-StandardAttributes $i "Catalog"
  804. X "$i<Characteristics/>"
  805. X "$i<PredefinedDataUpdate>Auto</PredefinedDataUpdate>"
  806. X "$i<EditType>InDialog</EditType>"
  807. X "$i<QuickChoice>true</QuickChoice>"
  808. X "$i<ChoiceMode>BothWays</ChoiceMode>"
  809. X "$i<InputByString>"
  810. X "$i`t<xr:Field>Catalog.$objName.StandardAttribute.Description</xr:Field>"
  811. X "$i`t<xr:Field>Catalog.$objName.StandardAttribute.Code</xr:Field>"
  812. X "$i</InputByString>"
  813. X "$i<SearchStringModeOnInputByString>Begin</SearchStringModeOnInputByString>"
  814. X "$i<FullTextSearchOnInputByString>DontUse</FullTextSearchOnInputByString>"
  815. X "$i<ChoiceDataGetModeOnInputByString>Directly</ChoiceDataGetModeOnInputByString>"
  816. X "$i<DefaultObjectForm/>"
  817. X "$i<DefaultFolderForm/>"
  818. X "$i<DefaultListForm/>"
  819. X "$i<DefaultChoiceForm/>"
  820. X "$i<DefaultFolderChoiceForm/>"
  821. X "$i<AuxiliaryObjectForm/>"
  822. X "$i<AuxiliaryFolderForm/>"
  823. X "$i<AuxiliaryListForm/>"
  824. X "$i<AuxiliaryChoiceForm/>"
  825. X "$i<AuxiliaryFolderChoiceForm/>"
  826. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  827. X "$i<BasedOn/>"
  828. X "$i<DataLockFields/>"
  829. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  830. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  831. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  832. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  833. X "$i<ObjectPresentation/>"
  834. X "$i<ExtendedObjectPresentation/>"
  835. X "$i<ListPresentation/>"
  836. X "$i<ExtendedListPresentation/>"
  837. X "$i<Explanation/>"
  838. X "$i<CreateOnInput>DontUse</CreateOnInput>"
  839. X "$i<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  840. X "$i<DataHistory>DontUse</DataHistory>"
  841. X "$i<UpdateDataHistoryImmediatelyAfterWrite>false</UpdateDataHistoryImmediatelyAfterWrite>"
  842. X "$i<ExecuteAfterWriteDataHistoryVersionProcessing>false</ExecuteAfterWriteDataHistoryVersionProcessing>"
  843. }
  844. function Emit-DocumentProperties {
  845. param([string]$indent)
  846. $i = $indent
  847. X "$i<Name>$(Esc-Xml $objName)</Name>"
  848. Emit-MLText $i "Synonym" $synonym
  849. X "$i<Comment/>"
  850. X "$i<UseStandardCommands>true</UseStandardCommands>"
  851. X "$i<Numerator/>"
  852. $numberType = if ($def.numberType) { "$($def.numberType)" } else { "String" }
  853. $numberLength = if ($null -ne $def.numberLength) { "$($def.numberLength)" } else { "11" }
  854. $numberAllowedLength = if ($def.numberAllowedLength) { "$($def.numberAllowedLength)" } else { "Variable" }
  855. $numberPeriodicity = if ($def.numberPeriodicity) { "$($def.numberPeriodicity)" } else { "Year" }
  856. $checkUnique = if ($def.checkUnique -eq $false) { "false" } else { "true" }
  857. $autonumbering = if ($def.autonumbering -eq $false) { "false" } else { "true" }
  858. X "$i<NumberType>$numberType</NumberType>"
  859. X "$i<NumberLength>$numberLength</NumberLength>"
  860. X "$i<NumberAllowedLength>$numberAllowedLength</NumberAllowedLength>"
  861. X "$i<NumberPeriodicity>$numberPeriodicity</NumberPeriodicity>"
  862. X "$i<CheckUnique>$checkUnique</CheckUnique>"
  863. X "$i<Autonumbering>$autonumbering</Autonumbering>"
  864. Emit-StandardAttributes $i "Document"
  865. X "$i<Characteristics/>"
  866. X "$i<BasedOn/>"
  867. X "$i<InputByString>"
  868. X "$i`t<xr:Field>Document.$objName.StandardAttribute.Number</xr:Field>"
  869. X "$i</InputByString>"
  870. X "$i<CreateOnInput>DontUse</CreateOnInput>"
  871. X "$i<SearchStringModeOnInputByString>Begin</SearchStringModeOnInputByString>"
  872. X "$i<FullTextSearchOnInputByString>DontUse</FullTextSearchOnInputByString>"
  873. X "$i<ChoiceDataGetModeOnInputByString>Directly</ChoiceDataGetModeOnInputByString>"
  874. X "$i<DefaultObjectForm/>"
  875. X "$i<DefaultListForm/>"
  876. X "$i<DefaultChoiceForm/>"
  877. X "$i<AuxiliaryObjectForm/>"
  878. X "$i<AuxiliaryListForm/>"
  879. X "$i<AuxiliaryChoiceForm/>"
  880. $posting = if ($def.posting) { "$($def.posting)" } else { "Allow" }
  881. $realTimePosting = if ($def.realTimePosting) { "$($def.realTimePosting)" } else { "Deny" }
  882. $registerRecordsDeletion = if ($def.registerRecordsDeletion) { "$($def.registerRecordsDeletion)" } else { "AutoDelete" }
  883. $registerRecordsWritingOnPost = if ($def.registerRecordsWritingOnPost) { "$($def.registerRecordsWritingOnPost)" } else { "WriteModified" }
  884. $sequenceFilling = if ($def.sequenceFilling) { "$($def.sequenceFilling)" } else { "AutoFill" }
  885. $postInPrivilegedMode = if ($def.postInPrivilegedMode -eq $false) { "false" } else { "true" }
  886. $unpostInPrivilegedMode = if ($def.unpostInPrivilegedMode -eq $false) { "false" } else { "true" }
  887. X "$i<Posting>$posting</Posting>"
  888. X "$i<RealTimePosting>$realTimePosting</RealTimePosting>"
  889. X "$i<RegisterRecordsDeletion>$registerRecordsDeletion</RegisterRecordsDeletion>"
  890. X "$i<RegisterRecordsWritingOnPost>$registerRecordsWritingOnPost</RegisterRecordsWritingOnPost>"
  891. X "$i<SequenceFilling>$sequenceFilling</SequenceFilling>"
  892. # RegisterRecords
  893. $regRecords = @()
  894. if ($def.registerRecords) {
  895. foreach ($rr in $def.registerRecords) {
  896. $rrStr = "$rr"
  897. # Resolve Russian synonyms in register records
  898. if ($rrStr.Contains('.')) {
  899. $dotIdx = $rrStr.IndexOf('.')
  900. $rrPrefix = $rrStr.Substring(0, $dotIdx)
  901. $rrSuffix = $rrStr.Substring($dotIdx + 1)
  902. if ($script:objectTypeSynonyms.ContainsKey($rrPrefix)) {
  903. $rrPrefix = $script:objectTypeSynonyms[$rrPrefix]
  904. }
  905. $regRecords += "$rrPrefix.$rrSuffix"
  906. } else {
  907. $regRecords += $rrStr
  908. }
  909. }
  910. }
  911. if ($regRecords.Count -gt 0) {
  912. X "$i<RegisterRecords>"
  913. foreach ($rr in $regRecords) {
  914. X "$i`t<xr:Record>$rr</xr:Record>"
  915. }
  916. X "$i</RegisterRecords>"
  917. } else {
  918. X "$i<RegisterRecords/>"
  919. }
  920. X "$i<PostInPrivilegedMode>$postInPrivilegedMode</PostInPrivilegedMode>"
  921. X "$i<UnpostInPrivilegedMode>$unpostInPrivilegedMode</UnpostInPrivilegedMode>"
  922. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  923. X "$i<DataLockFields/>"
  924. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  925. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  926. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  927. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  928. X "$i<ObjectPresentation/>"
  929. X "$i<ExtendedObjectPresentation/>"
  930. X "$i<ListPresentation/>"
  931. X "$i<ExtendedListPresentation/>"
  932. X "$i<Explanation/>"
  933. X "$i<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  934. X "$i<DataHistory>DontUse</DataHistory>"
  935. X "$i<UpdateDataHistoryImmediatelyAfterWrite>false</UpdateDataHistoryImmediatelyAfterWrite>"
  936. X "$i<ExecuteAfterWriteDataHistoryVersionProcessing>false</ExecuteAfterWriteDataHistoryVersionProcessing>"
  937. }
  938. function Emit-EnumProperties {
  939. param([string]$indent)
  940. $i = $indent
  941. X "$i<Name>$(Esc-Xml $objName)</Name>"
  942. Emit-MLText $i "Synonym" $synonym
  943. X "$i<Comment/>"
  944. X "$i<UseStandardCommands>false</UseStandardCommands>"
  945. Emit-StandardAttributes $i "Enum"
  946. X "$i<Characteristics/>"
  947. X "$i<QuickChoice>true</QuickChoice>"
  948. X "$i<ChoiceMode>BothWays</ChoiceMode>"
  949. X "$i<DefaultListForm/>"
  950. X "$i<DefaultChoiceForm/>"
  951. X "$i<AuxiliaryListForm/>"
  952. X "$i<AuxiliaryChoiceForm/>"
  953. X "$i<ListPresentation/>"
  954. X "$i<ExtendedListPresentation/>"
  955. X "$i<Explanation/>"
  956. X "$i<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  957. }
  958. function Emit-ConstantProperties {
  959. param([string]$indent)
  960. $i = $indent
  961. X "$i<Name>$(Esc-Xml $objName)</Name>"
  962. Emit-MLText $i "Synonym" $synonym
  963. X "$i<Comment/>"
  964. # Type
  965. $valueType = if ($def.valueType) { "$($def.valueType)" } else { "String" }
  966. Emit-ValueType $i $valueType
  967. X "$i<UseStandardCommands>true</UseStandardCommands>"
  968. X "$i<DefaultForm/>"
  969. X "$i<ExtendedPresentation/>"
  970. X "$i<Explanation/>"
  971. X "$i<PasswordMode>false</PasswordMode>"
  972. X "$i<Format/>"
  973. X "$i<EditFormat/>"
  974. X "$i<ToolTip/>"
  975. X "$i<MarkNegatives>false</MarkNegatives>"
  976. X "$i<Mask/>"
  977. X "$i<MultiLine>false</MultiLine>"
  978. X "$i<ExtendedEdit>false</ExtendedEdit>"
  979. X "$i<MinValue xsi:nil=`"true`"/>"
  980. X "$i<MaxValue xsi:nil=`"true`"/>"
  981. X "$i<FillChecking>DontCheck</FillChecking>"
  982. X "$i<ChoiceFoldersAndItems>Items</ChoiceFoldersAndItems>"
  983. X "$i<ChoiceParameterLinks/>"
  984. X "$i<ChoiceParameters/>"
  985. X "$i<QuickChoice>Auto</QuickChoice>"
  986. X "$i<ChoiceForm/>"
  987. X "$i<LinkByType/>"
  988. X "$i<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  989. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  990. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  991. X "$i<DataHistory>DontUse</DataHistory>"
  992. X "$i<UpdateDataHistoryImmediatelyAfterWrite>false</UpdateDataHistoryImmediatelyAfterWrite>"
  993. X "$i<ExecuteAfterWriteDataHistoryVersionProcessing>false</ExecuteAfterWriteDataHistoryVersionProcessing>"
  994. }
  995. function Emit-InformationRegisterProperties {
  996. param([string]$indent)
  997. $i = $indent
  998. X "$i<Name>$(Esc-Xml $objName)</Name>"
  999. Emit-MLText $i "Synonym" $synonym
  1000. X "$i<Comment/>"
  1001. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1002. X "$i<EditType>InDialog</EditType>"
  1003. X "$i<DefaultRecordForm/>"
  1004. X "$i<DefaultListForm/>"
  1005. X "$i<AuxiliaryRecordForm/>"
  1006. X "$i<AuxiliaryListForm/>"
  1007. Emit-StandardAttributes $i "InformationRegister"
  1008. $periodicity = if ($def.periodicity) { "$($def.periodicity)" } else { "Nonperiodical" }
  1009. $writeMode = if ($def.writeMode) { "$($def.writeMode)" } else { "Independent" }
  1010. # MainFilterOnPeriod: auto based on periodicity unless explicitly set
  1011. $mainFilterOnPeriod = "false"
  1012. if ($null -ne $def.mainFilterOnPeriod) {
  1013. $mainFilterOnPeriod = if ($def.mainFilterOnPeriod -eq $true) { "true" } else { "false" }
  1014. } elseif ($periodicity -ne "Nonperiodical") {
  1015. $mainFilterOnPeriod = "true"
  1016. }
  1017. X "$i<InformationRegisterPeriodicity>$periodicity</InformationRegisterPeriodicity>"
  1018. X "$i<WriteMode>$writeMode</WriteMode>"
  1019. X "$i<MainFilterOnPeriod>$mainFilterOnPeriod</MainFilterOnPeriod>"
  1020. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1021. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  1022. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  1023. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  1024. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  1025. X "$i<EnableTotalsSliceFirst>false</EnableTotalsSliceFirst>"
  1026. X "$i<EnableTotalsSliceLast>false</EnableTotalsSliceLast>"
  1027. X "$i<RecordPresentation/>"
  1028. X "$i<ExtendedRecordPresentation/>"
  1029. X "$i<ListPresentation/>"
  1030. X "$i<ExtendedListPresentation/>"
  1031. X "$i<Explanation/>"
  1032. X "$i<DataHistory>DontUse</DataHistory>"
  1033. X "$i<UpdateDataHistoryImmediatelyAfterWrite>false</UpdateDataHistoryImmediatelyAfterWrite>"
  1034. X "$i<ExecuteAfterWriteDataHistoryVersionProcessing>false</ExecuteAfterWriteDataHistoryVersionProcessing>"
  1035. }
  1036. function Emit-AccumulationRegisterProperties {
  1037. param([string]$indent)
  1038. $i = $indent
  1039. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1040. Emit-MLText $i "Synonym" $synonym
  1041. X "$i<Comment/>"
  1042. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1043. X "$i<DefaultListForm/>"
  1044. X "$i<AuxiliaryListForm/>"
  1045. $registerType = if ($def.registerType) { "$($def.registerType)" } else { "Balance" }
  1046. X "$i<RegisterType>$registerType</RegisterType>"
  1047. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1048. Emit-StandardAttributes $i "AccumulationRegister"
  1049. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  1050. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  1051. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  1052. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  1053. $enableTotalsSplitting = if ($def.enableTotalsSplitting -eq $false) { "false" } else { "true" }
  1054. X "$i<EnableTotalsSplitting>$enableTotalsSplitting</EnableTotalsSplitting>"
  1055. X "$i<ListPresentation/>"
  1056. X "$i<ExtendedListPresentation/>"
  1057. X "$i<Explanation/>"
  1058. }
  1059. # --- 13a. Wave 1: DefinedType, CommonModule, ScheduledJob, EventSubscription ---
  1060. function Emit-DefinedTypeProperties {
  1061. param([string]$indent)
  1062. $i = $indent
  1063. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1064. Emit-MLText $i "Synonym" $synonym
  1065. X "$i<Comment/>"
  1066. # Type — composite type with multiple v8:Type entries
  1067. $valueTypes = @()
  1068. if ($def.valueTypes) {
  1069. $valueTypes = @($def.valueTypes)
  1070. }
  1071. if ($valueTypes.Count -gt 0) {
  1072. X "$i<Type>"
  1073. foreach ($vt in $valueTypes) {
  1074. $resolved = Resolve-TypeStr "$vt"
  1075. if ($resolved -match '^(CatalogRef|DocumentRef|EnumRef|ChartOfAccountsRef|ChartOfCharacteristicTypesRef|ChartOfCalculationTypesRef|ExchangePlanRef|BusinessProcessRef|TaskRef)\.') {
  1076. X "$i`t<v8:Type>cfg:$resolved</v8:Type>"
  1077. } elseif ($resolved -eq "Boolean") {
  1078. X "$i`t<v8:Type>xs:boolean</v8:Type>"
  1079. } elseif ($resolved -match '^String') {
  1080. X "$i`t<v8:Type>xs:string</v8:Type>"
  1081. X "$i`t<v8:StringQualifiers>"
  1082. X "$i`t`t<v8:Length>0</v8:Length>"
  1083. X "$i`t`t<v8:AllowedLength>Variable</v8:AllowedLength>"
  1084. X "$i`t</v8:StringQualifiers>"
  1085. } else {
  1086. X "$i`t<v8:Type>cfg:$resolved</v8:Type>"
  1087. }
  1088. }
  1089. X "$i</Type>"
  1090. } else {
  1091. X "$i<Type/>"
  1092. }
  1093. }
  1094. function Emit-CommonModuleProperties {
  1095. param([string]$indent)
  1096. $i = $indent
  1097. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1098. Emit-MLText $i "Synonym" $synonym
  1099. X "$i<Comment/>"
  1100. # Context shortcuts
  1101. $context = if ($def.context) { "$($def.context)" } else { "" }
  1102. $global = if ($def.global -eq $true) { "true" } else { "false" }
  1103. $server = "false"; $serverCall = "false"; $clientManaged = "false"
  1104. $clientOrdinary = "false"; $externalConnection = "false"; $privileged = "false"
  1105. switch ($context) {
  1106. "server" { $server = "true"; $serverCall = "true" }
  1107. "serverCall" { $server = "true"; $serverCall = "true" }
  1108. "client" { $clientManaged = "true" }
  1109. "serverClient" { $server = "true"; $clientManaged = "true" }
  1110. default {
  1111. if ($def.server -eq $true) { $server = "true" }
  1112. if ($def.serverCall -eq $true) { $serverCall = "true" }
  1113. if ($def.clientManagedApplication -eq $true) { $clientManaged = "true" }
  1114. if ($def.clientOrdinaryApplication -eq $true) { $clientOrdinary = "true" }
  1115. if ($def.externalConnection -eq $true) { $externalConnection = "true" }
  1116. if ($def.privileged -eq $true) { $privileged = "true" }
  1117. }
  1118. }
  1119. X "$i<Global>$global</Global>"
  1120. X "$i<ClientManagedApplication>$clientManaged</ClientManagedApplication>"
  1121. X "$i<Server>$server</Server>"
  1122. X "$i<ExternalConnection>$externalConnection</ExternalConnection>"
  1123. X "$i<ClientOrdinaryApplication>$clientOrdinary</ClientOrdinaryApplication>"
  1124. X "$i<ServerCall>$serverCall</ServerCall>"
  1125. X "$i<Privileged>$privileged</Privileged>"
  1126. $returnValuesReuse = if ($def.returnValuesReuse) { "$($def.returnValuesReuse)" } else { "DontUse" }
  1127. X "$i<ReturnValuesReuse>$returnValuesReuse</ReturnValuesReuse>"
  1128. }
  1129. function Emit-ScheduledJobProperties {
  1130. param([string]$indent)
  1131. $i = $indent
  1132. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1133. Emit-MLText $i "Synonym" $synonym
  1134. X "$i<Comment/>"
  1135. $methodName = if ($def.methodName) { "$($def.methodName)" } else { "" }
  1136. X "$i<MethodName>$(Esc-Xml $methodName)</MethodName>"
  1137. $description = if ($def.description) { "$($def.description)" } else { $synonym }
  1138. X "$i<Description>$(Esc-Xml $description)</Description>"
  1139. $key = if ($def.key) { "$($def.key)" } else { "" }
  1140. X "$i<Key>$(Esc-Xml $key)</Key>"
  1141. $use = if ($def.use -eq $true) { "true" } else { "false" }
  1142. X "$i<Use>$use</Use>"
  1143. $predefined = if ($def.predefined -eq $true) { "true" } else { "false" }
  1144. X "$i<Predefined>$predefined</Predefined>"
  1145. $restartCount = if ($null -ne $def.restartCountOnFailure) { "$($def.restartCountOnFailure)" } else { "3" }
  1146. $restartInterval = if ($null -ne $def.restartIntervalOnFailure) { "$($def.restartIntervalOnFailure)" } else { "10" }
  1147. X "$i<RestartCountOnFailure>$restartCount</RestartCountOnFailure>"
  1148. X "$i<RestartIntervalOnFailure>$restartInterval</RestartIntervalOnFailure>"
  1149. }
  1150. function Emit-EventSubscriptionProperties {
  1151. param([string]$indent)
  1152. $i = $indent
  1153. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1154. Emit-MLText $i "Synonym" $synonym
  1155. X "$i<Comment/>"
  1156. # Source — array of v8:Type
  1157. $sources = @()
  1158. if ($def.source) { $sources = @($def.source) }
  1159. if ($sources.Count -gt 0) {
  1160. X "$i<Source>"
  1161. foreach ($src in $sources) {
  1162. $resolved = Resolve-TypeStr "$src"
  1163. X "$i`t<v8:Type>cfg:$resolved</v8:Type>"
  1164. }
  1165. X "$i</Source>"
  1166. } else {
  1167. X "$i<Source/>"
  1168. }
  1169. $event = if ($def.event) { "$($def.event)" } else { "BeforeWrite" }
  1170. X "$i<Event>$event</Event>"
  1171. $handler = if ($def.handler) { "$($def.handler)" } else { "" }
  1172. X "$i<Handler>$(Esc-Xml $handler)</Handler>"
  1173. }
  1174. # --- 13b. Wave 2: Report, DataProcessor ---
  1175. function Emit-ReportProperties {
  1176. param([string]$indent)
  1177. $i = $indent
  1178. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1179. Emit-MLText $i "Synonym" $synonym
  1180. X "$i<Comment/>"
  1181. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1182. $defaultForm = if ($def.defaultForm) { "$($def.defaultForm)" } else { "" }
  1183. if ($defaultForm) { X "$i<DefaultForm>$defaultForm</DefaultForm>" } else { X "$i<DefaultForm/>" }
  1184. $auxForm = if ($def.auxiliaryForm) { "$($def.auxiliaryForm)" } else { "" }
  1185. if ($auxForm) { X "$i<AuxiliaryForm>$auxForm</AuxiliaryForm>" } else { X "$i<AuxiliaryForm/>" }
  1186. $mainDCS = if ($def.mainDataCompositionSchema) { "$($def.mainDataCompositionSchema)" } else { "" }
  1187. if ($mainDCS) { X "$i<MainDataCompositionSchema>$mainDCS</MainDataCompositionSchema>" } else { X "$i<MainDataCompositionSchema/>" }
  1188. $defSettings = if ($def.defaultSettingsForm) { "$($def.defaultSettingsForm)" } else { "" }
  1189. if ($defSettings) { X "$i<DefaultSettingsForm>$defSettings</DefaultSettingsForm>" } else { X "$i<DefaultSettingsForm/>" }
  1190. $auxSettings = if ($def.auxiliarySettingsForm) { "$($def.auxiliarySettingsForm)" } else { "" }
  1191. if ($auxSettings) { X "$i<AuxiliarySettingsForm>$auxSettings</AuxiliarySettingsForm>" } else { X "$i<AuxiliarySettingsForm/>" }
  1192. $defVariant = if ($def.defaultVariantForm) { "$($def.defaultVariantForm)" } else { "" }
  1193. if ($defVariant) { X "$i<DefaultVariantForm>$defVariant</DefaultVariantForm>" } else { X "$i<DefaultVariantForm/>" }
  1194. X "$i<VariantsStorage/>"
  1195. X "$i<SettingsStorage/>"
  1196. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1197. X "$i<ExtendedPresentation/>"
  1198. X "$i<Explanation/>"
  1199. }
  1200. function Emit-DataProcessorProperties {
  1201. param([string]$indent)
  1202. $i = $indent
  1203. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1204. Emit-MLText $i "Synonym" $synonym
  1205. X "$i<Comment/>"
  1206. X "$i<UseStandardCommands>false</UseStandardCommands>"
  1207. $defaultForm = if ($def.defaultForm) { "$($def.defaultForm)" } else { "" }
  1208. if ($defaultForm) { X "$i<DefaultForm>$defaultForm</DefaultForm>" } else { X "$i<DefaultForm/>" }
  1209. $auxForm = if ($def.auxiliaryForm) { "$($def.auxiliaryForm)" } else { "" }
  1210. if ($auxForm) { X "$i<AuxiliaryForm>$auxForm</AuxiliaryForm>" } else { X "$i<AuxiliaryForm/>" }
  1211. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1212. X "$i<ExtendedPresentation/>"
  1213. X "$i<Explanation/>"
  1214. }
  1215. # --- 13c. Wave 3: ExchangePlan, ChartOfCharacteristicTypes, DocumentJournal ---
  1216. function Emit-ExchangePlanProperties {
  1217. param([string]$indent)
  1218. $i = $indent
  1219. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1220. Emit-MLText $i "Synonym" $synonym
  1221. X "$i<Comment/>"
  1222. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1223. $codeLength = if ($null -ne $def.codeLength) { "$($def.codeLength)" } else { "9" }
  1224. $descriptionLength = if ($null -ne $def.descriptionLength) { "$($def.descriptionLength)" } else { "100" }
  1225. $codeType = if ($def.codeType) { "$($def.codeType)" } else { "String" }
  1226. $codeAllowedLength = if ($def.codeAllowedLength) { "$($def.codeAllowedLength)" } else { "Variable" }
  1227. $autonumbering = if ($def.autonumbering -eq $false) { "false" } else { "true" }
  1228. $checkUnique = if ($def.checkUnique -eq $true) { "true" } else { "false" }
  1229. X "$i<CodeLength>$codeLength</CodeLength>"
  1230. X "$i<CodeType>$codeType</CodeType>"
  1231. X "$i<CodeAllowedLength>$codeAllowedLength</CodeAllowedLength>"
  1232. X "$i<DescriptionLength>$descriptionLength</DescriptionLength>"
  1233. X "$i<DefaultPresentation>AsDescription</DefaultPresentation>"
  1234. X "$i<EditType>InDialog</EditType>"
  1235. X "$i<CheckUnique>$checkUnique</CheckUnique>"
  1236. X "$i<Autonumbering>$autonumbering</Autonumbering>"
  1237. Emit-StandardAttributes $i "ExchangePlan"
  1238. $distributed = if ($def.distributedInfoBase -eq $true) { "true" } else { "false" }
  1239. $includeExt = if ($def.includeConfigurationExtensions -eq $true) { "true" } else { "false" }
  1240. X "$i<DistributedInfoBase>$distributed</DistributedInfoBase>"
  1241. X "$i<IncludeConfigurationExtensions>$includeExt</IncludeConfigurationExtensions>"
  1242. X "$i<BasedOn/>"
  1243. X "$i<QuickChoice>true</QuickChoice>"
  1244. X "$i<ChoiceMode>BothWays</ChoiceMode>"
  1245. X "$i<InputByString>"
  1246. X "$i`t<xr:Field>ExchangePlan.$objName.StandardAttribute.Description</xr:Field>"
  1247. X "$i`t<xr:Field>ExchangePlan.$objName.StandardAttribute.Code</xr:Field>"
  1248. X "$i</InputByString>"
  1249. X "$i<SearchStringModeOnInputByString>Begin</SearchStringModeOnInputByString>"
  1250. X "$i<FullTextSearchOnInputByString>DontUse</FullTextSearchOnInputByString>"
  1251. X "$i<ChoiceDataGetModeOnInputByString>Directly</ChoiceDataGetModeOnInputByString>"
  1252. X "$i<DefaultObjectForm/>"
  1253. X "$i<DefaultListForm/>"
  1254. X "$i<DefaultChoiceForm/>"
  1255. X "$i<AuxiliaryObjectForm/>"
  1256. X "$i<AuxiliaryListForm/>"
  1257. X "$i<AuxiliaryChoiceForm/>"
  1258. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1259. X "$i<DataLockFields/>"
  1260. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  1261. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  1262. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  1263. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  1264. X "$i<ObjectPresentation/>"
  1265. X "$i<ExtendedObjectPresentation/>"
  1266. X "$i<ListPresentation/>"
  1267. X "$i<ExtendedListPresentation/>"
  1268. X "$i<Explanation/>"
  1269. X "$i<CreateOnInput>DontUse</CreateOnInput>"
  1270. X "$i<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  1271. X "$i<DataHistory>DontUse</DataHistory>"
  1272. X "$i<UpdateDataHistoryImmediatelyAfterWrite>false</UpdateDataHistoryImmediatelyAfterWrite>"
  1273. X "$i<ExecuteAfterWriteDataHistoryVersionProcessing>false</ExecuteAfterWriteDataHistoryVersionProcessing>"
  1274. }
  1275. function Emit-ChartOfCharacteristicTypesProperties {
  1276. param([string]$indent)
  1277. $i = $indent
  1278. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1279. Emit-MLText $i "Synonym" $synonym
  1280. X "$i<Comment/>"
  1281. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1282. $codeLength = if ($null -ne $def.codeLength) { "$($def.codeLength)" } else { "9" }
  1283. $descriptionLength = if ($null -ne $def.descriptionLength) { "$($def.descriptionLength)" } else { "25" }
  1284. $codeType = if ($def.codeType) { "$($def.codeType)" } else { "String" }
  1285. $codeAllowedLength = if ($def.codeAllowedLength) { "$($def.codeAllowedLength)" } else { "Variable" }
  1286. $autonumbering = if ($def.autonumbering -eq $false) { "false" } else { "true" }
  1287. $checkUnique = if ($def.checkUnique -eq $true) { "true" } else { "false" }
  1288. X "$i<CodeLength>$codeLength</CodeLength>"
  1289. X "$i<CodeType>$codeType</CodeType>"
  1290. X "$i<CodeAllowedLength>$codeAllowedLength</CodeAllowedLength>"
  1291. X "$i<DescriptionLength>$descriptionLength</DescriptionLength>"
  1292. X "$i<CheckUnique>$checkUnique</CheckUnique>"
  1293. X "$i<Autonumbering>$autonumbering</Autonumbering>"
  1294. X "$i<DefaultPresentation>AsDescription</DefaultPresentation>"
  1295. # CharacteristicExtValues
  1296. $charExtValues = if ($def.characteristicExtValues) { "$($def.characteristicExtValues)" } else { "" }
  1297. if ($charExtValues) { X "$i<CharacteristicExtValues>$charExtValues</CharacteristicExtValues>" }
  1298. else { X "$i<CharacteristicExtValues/>" }
  1299. # Type — composite type of allowed characteristic value types
  1300. $valueTypes = @()
  1301. if ($def.valueTypes) { $valueTypes = @($def.valueTypes) }
  1302. if ($valueTypes.Count -gt 0) {
  1303. X "$i<Type>"
  1304. foreach ($vt in $valueTypes) {
  1305. Emit-TypeContent "$i`t" "$vt"
  1306. }
  1307. X "$i</Type>"
  1308. } else {
  1309. X "$i<Type>"
  1310. X "$i`t<v8:Type>xs:boolean</v8:Type>"
  1311. X "$i`t<v8:Type>xs:string</v8:Type>"
  1312. X "$i`t<v8:StringQualifiers>"
  1313. X "$i`t`t<v8:Length>0</v8:Length>"
  1314. X "$i`t`t<v8:AllowedLength>Variable</v8:AllowedLength>"
  1315. X "$i`t</v8:StringQualifiers>"
  1316. X "$i`t<v8:Type>xs:decimal</v8:Type>"
  1317. X "$i`t<v8:NumberQualifiers>"
  1318. X "$i`t`t<v8:Digits>15</v8:Digits>"
  1319. X "$i`t`t<v8:FractionDigits>2</v8:FractionDigits>"
  1320. X "$i`t`t<v8:AllowedSign>Any</v8:AllowedSign>"
  1321. X "$i`t</v8:NumberQualifiers>"
  1322. X "$i`t<v8:Type>xs:dateTime</v8:Type>"
  1323. X "$i`t<v8:DateQualifiers>"
  1324. X "$i`t`t<v8:DateFractions>DateTime</v8:DateFractions>"
  1325. X "$i`t</v8:DateQualifiers>"
  1326. X "$i</Type>"
  1327. }
  1328. $hierarchical = if ($def.hierarchical -eq $true) { "true" } else { "false" }
  1329. X "$i<Hierarchical>$hierarchical</Hierarchical>"
  1330. X "$i<FoldersOnTop>true</FoldersOnTop>"
  1331. Emit-StandardAttributes $i "ChartOfCharacteristicTypes"
  1332. X "$i<Characteristics/>"
  1333. X "$i<PredefinedDataUpdate>Auto</PredefinedDataUpdate>"
  1334. X "$i<EditType>InDialog</EditType>"
  1335. X "$i<QuickChoice>true</QuickChoice>"
  1336. X "$i<ChoiceMode>BothWays</ChoiceMode>"
  1337. X "$i<InputByString>"
  1338. X "$i`t<xr:Field>ChartOfCharacteristicTypes.$objName.StandardAttribute.Description</xr:Field>"
  1339. X "$i`t<xr:Field>ChartOfCharacteristicTypes.$objName.StandardAttribute.Code</xr:Field>"
  1340. X "$i</InputByString>"
  1341. X "$i<SearchStringModeOnInputByString>Begin</SearchStringModeOnInputByString>"
  1342. X "$i<FullTextSearchOnInputByString>DontUse</FullTextSearchOnInputByString>"
  1343. X "$i<ChoiceDataGetModeOnInputByString>Directly</ChoiceDataGetModeOnInputByString>"
  1344. X "$i<DefaultObjectForm/>"
  1345. X "$i<DefaultFolderForm/>"
  1346. X "$i<DefaultListForm/>"
  1347. X "$i<DefaultChoiceForm/>"
  1348. X "$i<DefaultFolderChoiceForm/>"
  1349. X "$i<AuxiliaryObjectForm/>"
  1350. X "$i<AuxiliaryFolderForm/>"
  1351. X "$i<AuxiliaryListForm/>"
  1352. X "$i<AuxiliaryChoiceForm/>"
  1353. X "$i<AuxiliaryFolderChoiceForm/>"
  1354. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1355. X "$i<BasedOn/>"
  1356. X "$i<DataLockFields/>"
  1357. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  1358. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  1359. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  1360. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  1361. X "$i<ObjectPresentation/>"
  1362. X "$i<ExtendedObjectPresentation/>"
  1363. X "$i<ListPresentation/>"
  1364. X "$i<ExtendedListPresentation/>"
  1365. X "$i<Explanation/>"
  1366. X "$i<CreateOnInput>DontUse</CreateOnInput>"
  1367. X "$i<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  1368. X "$i<DataHistory>DontUse</DataHistory>"
  1369. X "$i<UpdateDataHistoryImmediatelyAfterWrite>false</UpdateDataHistoryImmediatelyAfterWrite>"
  1370. X "$i<ExecuteAfterWriteDataHistoryVersionProcessing>false</ExecuteAfterWriteDataHistoryVersionProcessing>"
  1371. }
  1372. function Emit-DocumentJournalProperties {
  1373. param([string]$indent)
  1374. $i = $indent
  1375. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1376. Emit-MLText $i "Synonym" $synonym
  1377. X "$i<Comment/>"
  1378. $defaultForm = if ($def.defaultForm) { "$($def.defaultForm)" } else { "" }
  1379. if ($defaultForm) { X "$i<DefaultForm>$defaultForm</DefaultForm>" } else { X "$i<DefaultForm/>" }
  1380. $auxForm = if ($def.auxiliaryForm) { "$($def.auxiliaryForm)" } else { "" }
  1381. if ($auxForm) { X "$i<AuxiliaryForm>$auxForm</AuxiliaryForm>" } else { X "$i<AuxiliaryForm/>" }
  1382. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1383. # RegisteredDocuments
  1384. $regDocs = @()
  1385. if ($def.registeredDocuments) { $regDocs = @($def.registeredDocuments) }
  1386. if ($regDocs.Count -gt 0) {
  1387. X "$i<RegisteredDocuments>"
  1388. foreach ($rd in $regDocs) {
  1389. $rdStr = "$rd"
  1390. # Resolve Russian synonyms: Документ.Xxx → Document.Xxx
  1391. if ($rdStr.Contains('.')) {
  1392. $dotIdx = $rdStr.IndexOf('.')
  1393. $rdPrefix = $rdStr.Substring(0, $dotIdx)
  1394. $rdSuffix = $rdStr.Substring($dotIdx + 1)
  1395. if ($script:objectTypeSynonyms.ContainsKey($rdPrefix)) {
  1396. $rdPrefix = $script:objectTypeSynonyms[$rdPrefix]
  1397. }
  1398. $rdStr = "$rdPrefix.$rdSuffix"
  1399. }
  1400. X "$i`t<xr:Item xsi:type=`"xr:MDObjectRef`">$rdStr</xr:Item>"
  1401. }
  1402. X "$i</RegisteredDocuments>"
  1403. } else {
  1404. X "$i<RegisteredDocuments/>"
  1405. }
  1406. Emit-StandardAttributes $i "DocumentJournal"
  1407. X "$i<ListPresentation/>"
  1408. X "$i<ExtendedListPresentation/>"
  1409. X "$i<Explanation/>"
  1410. }
  1411. # --- 13d. Wave 4: ChartOfAccounts, AccountingRegister, ChartOfCalculationTypes, CalculationRegister ---
  1412. function Emit-ChartOfAccountsProperties {
  1413. param([string]$indent)
  1414. $i = $indent
  1415. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1416. Emit-MLText $i "Synonym" $synonym
  1417. X "$i<Comment/>"
  1418. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1419. # ExtDimensionTypes
  1420. $extDimTypes = if ($def.extDimensionTypes) { "$($def.extDimensionTypes)" } else { "" }
  1421. if ($extDimTypes) { X "$i<ExtDimensionTypes>$extDimTypes</ExtDimensionTypes>" }
  1422. else { X "$i<ExtDimensionTypes/>" }
  1423. $maxExtDim = if ($null -ne $def.maxExtDimensionCount) { "$($def.maxExtDimensionCount)" } else { "3" }
  1424. X "$i<MaxExtDimensionCount>$maxExtDim</MaxExtDimensionCount>"
  1425. $codeMask = if ($def.codeMask) { "$($def.codeMask)" } else { "" }
  1426. if ($codeMask) { X "$i<CodeMask>$codeMask</CodeMask>" } else { X "$i<CodeMask/>" }
  1427. $codeLength = if ($null -ne $def.codeLength) { "$($def.codeLength)" } else { "8" }
  1428. $descriptionLength = if ($null -ne $def.descriptionLength) { "$($def.descriptionLength)" } else { "120" }
  1429. $codeSeries = if ($def.codeSeries) { "$($def.codeSeries)" } else { "WholeChartOfAccounts" }
  1430. $autoOrder = if ($def.autoOrderByCode -eq $false) { "false" } else { "true" }
  1431. $orderLength = if ($null -ne $def.orderLength) { "$($def.orderLength)" } else { "5" }
  1432. X "$i<CodeLength>$codeLength</CodeLength>"
  1433. X "$i<DescriptionLength>$descriptionLength</DescriptionLength>"
  1434. X "$i<CodeSeries>$codeSeries</CodeSeries>"
  1435. X "$i<CheckUnique>false</CheckUnique>"
  1436. X "$i<Autonumbering>true</Autonumbering>"
  1437. X "$i<DefaultPresentation>AsDescription</DefaultPresentation>"
  1438. X "$i<AutoOrderByCode>$autoOrder</AutoOrderByCode>"
  1439. X "$i<OrderLength>$orderLength</OrderLength>"
  1440. $hierarchical = if ($def.hierarchical -eq $true) { "true" } else { "false" }
  1441. X "$i<Hierarchical>$hierarchical</Hierarchical>"
  1442. X "$i<EditType>InDialog</EditType>"
  1443. Emit-StandardAttributes $i "ChartOfAccounts"
  1444. # StandardTabularSections — ExtDimensionTypes
  1445. X "$i<StandardTabularSections>"
  1446. X "$i`t<xr:StandardTabularSection name=`"ExtDimensionTypes`">"
  1447. X "$i`t`t<xr:StandardAttributes>"
  1448. foreach ($stAttr in @("TurnoversOnly","Predefined","ExtDimensionType","LineNumber")) {
  1449. Emit-StandardAttribute "$i`t`t`t" $stAttr
  1450. }
  1451. X "$i`t`t</xr:StandardAttributes>"
  1452. X "$i`t</xr:StandardTabularSection>"
  1453. X "$i</StandardTabularSections>"
  1454. X "$i<Characteristics/>"
  1455. X "$i<PredefinedDataUpdate>Auto</PredefinedDataUpdate>"
  1456. X "$i<QuickChoice>true</QuickChoice>"
  1457. X "$i<ChoiceMode>BothWays</ChoiceMode>"
  1458. X "$i<InputByString>"
  1459. X "$i`t<xr:Field>ChartOfAccounts.$objName.StandardAttribute.Description</xr:Field>"
  1460. X "$i`t<xr:Field>ChartOfAccounts.$objName.StandardAttribute.Code</xr:Field>"
  1461. X "$i</InputByString>"
  1462. X "$i<SearchStringModeOnInputByString>Begin</SearchStringModeOnInputByString>"
  1463. X "$i<FullTextSearchOnInputByString>DontUse</FullTextSearchOnInputByString>"
  1464. X "$i<ChoiceDataGetModeOnInputByString>Directly</ChoiceDataGetModeOnInputByString>"
  1465. X "$i<DefaultObjectForm/>"
  1466. X "$i<DefaultListForm/>"
  1467. X "$i<DefaultChoiceForm/>"
  1468. X "$i<AuxiliaryObjectForm/>"
  1469. X "$i<AuxiliaryListForm/>"
  1470. X "$i<AuxiliaryChoiceForm/>"
  1471. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1472. X "$i<BasedOn/>"
  1473. X "$i<DataLockFields/>"
  1474. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  1475. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  1476. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  1477. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  1478. X "$i<ObjectPresentation/>"
  1479. X "$i<ExtendedObjectPresentation/>"
  1480. X "$i<ListPresentation/>"
  1481. X "$i<ExtendedListPresentation/>"
  1482. X "$i<Explanation/>"
  1483. X "$i<CreateOnInput>DontUse</CreateOnInput>"
  1484. X "$i<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  1485. X "$i<DataHistory>DontUse</DataHistory>"
  1486. X "$i<UpdateDataHistoryImmediatelyAfterWrite>false</UpdateDataHistoryImmediatelyAfterWrite>"
  1487. X "$i<ExecuteAfterWriteDataHistoryVersionProcessing>false</ExecuteAfterWriteDataHistoryVersionProcessing>"
  1488. }
  1489. function Emit-AccountingRegisterProperties {
  1490. param([string]$indent)
  1491. $i = $indent
  1492. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1493. Emit-MLText $i "Synonym" $synonym
  1494. X "$i<Comment/>"
  1495. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1496. X "$i<DefaultListForm/>"
  1497. X "$i<AuxiliaryListForm/>"
  1498. $chartOfAccounts = if ($def.chartOfAccounts) { "$($def.chartOfAccounts)" } else { "" }
  1499. if ($chartOfAccounts) { X "$i<ChartOfAccounts>$chartOfAccounts</ChartOfAccounts>" }
  1500. else { X "$i<ChartOfAccounts/>" }
  1501. $correspondence = if ($def.correspondence -eq $true) { "true" } else { "false" }
  1502. X "$i<Correspondence>$correspondence</Correspondence>"
  1503. $periodAdjLen = if ($null -ne $def.periodAdjustmentLength) { "$($def.periodAdjustmentLength)" } else { "0" }
  1504. X "$i<PeriodAdjustmentLength>$periodAdjLen</PeriodAdjustmentLength>"
  1505. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1506. Emit-StandardAttributes $i "AccountingRegister"
  1507. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  1508. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  1509. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  1510. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  1511. X "$i<ListPresentation/>"
  1512. X "$i<ExtendedListPresentation/>"
  1513. X "$i<Explanation/>"
  1514. }
  1515. function Emit-ChartOfCalculationTypesProperties {
  1516. param([string]$indent)
  1517. $i = $indent
  1518. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1519. Emit-MLText $i "Synonym" $synonym
  1520. X "$i<Comment/>"
  1521. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1522. $codeLength = if ($null -ne $def.codeLength) { "$($def.codeLength)" } else { "9" }
  1523. $descriptionLength = if ($null -ne $def.descriptionLength) { "$($def.descriptionLength)" } else { "25" }
  1524. $codeType = if ($def.codeType) { "$($def.codeType)" } else { "String" }
  1525. $codeAllowedLength = if ($def.codeAllowedLength) { "$($def.codeAllowedLength)" } else { "Variable" }
  1526. $autonumbering = if ($def.autonumbering -eq $false) { "false" } else { "true" }
  1527. $checkUnique = if ($def.checkUnique -eq $true) { "true" } else { "false" }
  1528. X "$i<CodeLength>$codeLength</CodeLength>"
  1529. X "$i<CodeType>$codeType</CodeType>"
  1530. X "$i<CodeAllowedLength>$codeAllowedLength</CodeAllowedLength>"
  1531. X "$i<DescriptionLength>$descriptionLength</DescriptionLength>"
  1532. X "$i<DefaultPresentation>AsDescription</DefaultPresentation>"
  1533. X "$i<CheckUnique>$checkUnique</CheckUnique>"
  1534. X "$i<Autonumbering>$autonumbering</Autonumbering>"
  1535. $dependence = if ($def.dependenceOnCalculationTypes) { "$($def.dependenceOnCalculationTypes)" } else { "NotUsed" }
  1536. X "$i<DependenceOnCalculationTypes>$dependence</DependenceOnCalculationTypes>"
  1537. # BaseCalculationTypes
  1538. $baseTypes = @()
  1539. if ($def.baseCalculationTypes) { $baseTypes = @($def.baseCalculationTypes) }
  1540. if ($baseTypes.Count -gt 0) {
  1541. X "$i<BaseCalculationTypes>"
  1542. foreach ($bt in $baseTypes) {
  1543. X "$i`t<xr:Item xsi:type=`"xr:MDObjectRef`">$bt</xr:Item>"
  1544. }
  1545. X "$i</BaseCalculationTypes>"
  1546. } else {
  1547. X "$i<BaseCalculationTypes/>"
  1548. }
  1549. $actionPeriodUse = if ($def.actionPeriodUse -eq $true) { "true" } else { "false" }
  1550. X "$i<ActionPeriodUse>$actionPeriodUse</ActionPeriodUse>"
  1551. Emit-StandardAttributes $i "ChartOfCalculationTypes"
  1552. X "$i<Characteristics/>"
  1553. X "$i<PredefinedDataUpdate>Auto</PredefinedDataUpdate>"
  1554. X "$i<EditType>InDialog</EditType>"
  1555. X "$i<QuickChoice>true</QuickChoice>"
  1556. X "$i<ChoiceMode>BothWays</ChoiceMode>"
  1557. X "$i<InputByString>"
  1558. X "$i`t<xr:Field>ChartOfCalculationTypes.$objName.StandardAttribute.Description</xr:Field>"
  1559. X "$i`t<xr:Field>ChartOfCalculationTypes.$objName.StandardAttribute.Code</xr:Field>"
  1560. X "$i</InputByString>"
  1561. X "$i<SearchStringModeOnInputByString>Begin</SearchStringModeOnInputByString>"
  1562. X "$i<FullTextSearchOnInputByString>DontUse</FullTextSearchOnInputByString>"
  1563. X "$i<ChoiceDataGetModeOnInputByString>Directly</ChoiceDataGetModeOnInputByString>"
  1564. X "$i<DefaultObjectForm/>"
  1565. X "$i<DefaultListForm/>"
  1566. X "$i<DefaultChoiceForm/>"
  1567. X "$i<AuxiliaryObjectForm/>"
  1568. X "$i<AuxiliaryListForm/>"
  1569. X "$i<AuxiliaryChoiceForm/>"
  1570. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1571. X "$i<BasedOn/>"
  1572. X "$i<DataLockFields/>"
  1573. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  1574. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  1575. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  1576. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  1577. X "$i<ObjectPresentation/>"
  1578. X "$i<ExtendedObjectPresentation/>"
  1579. X "$i<ListPresentation/>"
  1580. X "$i<ExtendedListPresentation/>"
  1581. X "$i<Explanation/>"
  1582. X "$i<CreateOnInput>DontUse</CreateOnInput>"
  1583. X "$i<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  1584. }
  1585. function Emit-CalculationRegisterProperties {
  1586. param([string]$indent)
  1587. $i = $indent
  1588. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1589. Emit-MLText $i "Synonym" $synonym
  1590. X "$i<Comment/>"
  1591. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1592. X "$i<DefaultListForm/>"
  1593. X "$i<AuxiliaryListForm/>"
  1594. $chartOfCalcTypes = if ($def.chartOfCalculationTypes) { "$($def.chartOfCalculationTypes)" } else { "" }
  1595. if ($chartOfCalcTypes) { X "$i<ChartOfCalculationTypes>$chartOfCalcTypes</ChartOfCalculationTypes>" }
  1596. else { X "$i<ChartOfCalculationTypes/>" }
  1597. $periodicity = if ($def.periodicity) { "$($def.periodicity)" } else { "Month" }
  1598. X "$i<Periodicity>$periodicity</Periodicity>"
  1599. $actionPeriod = if ($def.actionPeriod -eq $true) { "true" } else { "false" }
  1600. X "$i<ActionPeriod>$actionPeriod</ActionPeriod>"
  1601. $basePeriod = if ($def.basePeriod -eq $true) { "true" } else { "false" }
  1602. X "$i<BasePeriod>$basePeriod</BasePeriod>"
  1603. $schedule = if ($def.schedule) { "$($def.schedule)" } else { "" }
  1604. if ($schedule) { X "$i<Schedule>$schedule</Schedule>" } else { X "$i<Schedule/>" }
  1605. $scheduleValue = if ($def.scheduleValue) { "$($def.scheduleValue)" } else { "" }
  1606. if ($scheduleValue) { X "$i<ScheduleValue>$scheduleValue</ScheduleValue>" } else { X "$i<ScheduleValue/>" }
  1607. $scheduleDate = if ($def.scheduleDate) { "$($def.scheduleDate)" } else { "" }
  1608. if ($scheduleDate) { X "$i<ScheduleDate>$scheduleDate</ScheduleDate>" } else { X "$i<ScheduleDate/>" }
  1609. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1610. Emit-StandardAttributes $i "CalculationRegister"
  1611. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  1612. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  1613. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  1614. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  1615. X "$i<ListPresentation/>"
  1616. X "$i<ExtendedListPresentation/>"
  1617. X "$i<Explanation/>"
  1618. }
  1619. # --- 13e. Wave 5: BusinessProcess, Task ---
  1620. function Emit-BusinessProcessProperties {
  1621. param([string]$indent)
  1622. $i = $indent
  1623. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1624. Emit-MLText $i "Synonym" $synonym
  1625. X "$i<Comment/>"
  1626. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1627. $editType = if ($def.editType) { "$($def.editType)" } else { "InDialog" }
  1628. X "$i<EditType>$editType</EditType>"
  1629. $numberType = if ($def.numberType) { "$($def.numberType)" } else { "String" }
  1630. $numberLength = if ($null -ne $def.numberLength) { "$($def.numberLength)" } else { "11" }
  1631. $numberAllowedLength = if ($def.numberAllowedLength) { "$($def.numberAllowedLength)" } else { "Variable" }
  1632. $checkUnique = if ($def.checkUnique -eq $false) { "false" } else { "true" }
  1633. $autonumbering = if ($def.autonumbering -eq $false) { "false" } else { "true" }
  1634. X "$i<NumberType>$numberType</NumberType>"
  1635. X "$i<NumberLength>$numberLength</NumberLength>"
  1636. X "$i<NumberAllowedLength>$numberAllowedLength</NumberAllowedLength>"
  1637. X "$i<CheckUnique>$checkUnique</CheckUnique>"
  1638. X "$i<Autonumbering>$autonumbering</Autonumbering>"
  1639. Emit-StandardAttributes $i "BusinessProcess"
  1640. X "$i<Characteristics/>"
  1641. X "$i<BasedOn/>"
  1642. X "$i<InputByString>"
  1643. X "$i`t<xr:Field>BusinessProcess.$objName.StandardAttribute.Number</xr:Field>"
  1644. X "$i</InputByString>"
  1645. X "$i<CreateOnInput>DontUse</CreateOnInput>"
  1646. X "$i<SearchStringModeOnInputByString>Begin</SearchStringModeOnInputByString>"
  1647. X "$i<FullTextSearchOnInputByString>DontUse</FullTextSearchOnInputByString>"
  1648. X "$i<ChoiceDataGetModeOnInputByString>Directly</ChoiceDataGetModeOnInputByString>"
  1649. X "$i<DefaultObjectForm/>"
  1650. X "$i<DefaultListForm/>"
  1651. X "$i<DefaultChoiceForm/>"
  1652. X "$i<AuxiliaryObjectForm/>"
  1653. X "$i<AuxiliaryListForm/>"
  1654. X "$i<AuxiliaryChoiceForm/>"
  1655. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1656. X "$i<DataLockFields/>"
  1657. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  1658. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  1659. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  1660. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  1661. X "$i<ObjectPresentation/>"
  1662. X "$i<ExtendedObjectPresentation/>"
  1663. X "$i<ListPresentation/>"
  1664. X "$i<ExtendedListPresentation/>"
  1665. X "$i<Explanation/>"
  1666. X "$i<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  1667. X "$i<DataHistory>DontUse</DataHistory>"
  1668. X "$i<UpdateDataHistoryImmediatelyAfterWrite>false</UpdateDataHistoryImmediatelyAfterWrite>"
  1669. X "$i<ExecuteAfterWriteDataHistoryVersionProcessing>false</ExecuteAfterWriteDataHistoryVersionProcessing>"
  1670. }
  1671. function Emit-TaskProperties {
  1672. param([string]$indent)
  1673. $i = $indent
  1674. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1675. Emit-MLText $i "Synonym" $synonym
  1676. X "$i<Comment/>"
  1677. X "$i<UseStandardCommands>true</UseStandardCommands>"
  1678. $numberType = if ($def.numberType) { "$($def.numberType)" } else { "String" }
  1679. $numberLength = if ($null -ne $def.numberLength) { "$($def.numberLength)" } else { "14" }
  1680. $numberAllowedLength = if ($def.numberAllowedLength) { "$($def.numberAllowedLength)" } else { "Variable" }
  1681. $checkUnique = if ($def.checkUnique -eq $false) { "false" } else { "true" }
  1682. $autonumbering = if ($def.autonumbering -eq $false) { "false" } else { "true" }
  1683. $taskNumberAutoPrefix = if ($def.taskNumberAutoPrefix) { "$($def.taskNumberAutoPrefix)" } else { "BusinessProcessNumber" }
  1684. $descriptionLength = if ($null -ne $def.descriptionLength) { "$($def.descriptionLength)" } else { "150" }
  1685. X "$i<NumberType>$numberType</NumberType>"
  1686. X "$i<NumberLength>$numberLength</NumberLength>"
  1687. X "$i<NumberAllowedLength>$numberAllowedLength</NumberAllowedLength>"
  1688. X "$i<CheckUnique>$checkUnique</CheckUnique>"
  1689. X "$i<Autonumbering>$autonumbering</Autonumbering>"
  1690. X "$i<TaskNumberAutoPrefix>$taskNumberAutoPrefix</TaskNumberAutoPrefix>"
  1691. X "$i<DescriptionLength>$descriptionLength</DescriptionLength>"
  1692. # Addressing
  1693. $addressing = if ($def.addressing) { "$($def.addressing)" } else { "" }
  1694. if ($addressing) { X "$i<Addressing>$addressing</Addressing>" } else { X "$i<Addressing/>" }
  1695. $mainAddressing = if ($def.mainAddressingAttribute) { "$($def.mainAddressingAttribute)" } else { "" }
  1696. if ($mainAddressing) { X "$i<MainAddressingAttribute>$mainAddressing</MainAddressingAttribute>" } else { X "$i<MainAddressingAttribute/>" }
  1697. $currentPerformer = if ($def.currentPerformer) { "$($def.currentPerformer)" } else { "" }
  1698. if ($currentPerformer) { X "$i<CurrentPerformer>$currentPerformer</CurrentPerformer>" } else { X "$i<CurrentPerformer/>" }
  1699. Emit-StandardAttributes $i "Task"
  1700. X "$i<Characteristics/>"
  1701. X "$i<BasedOn/>"
  1702. X "$i<InputByString>"
  1703. X "$i`t<xr:Field>Task.$objName.StandardAttribute.Number</xr:Field>"
  1704. X "$i</InputByString>"
  1705. X "$i<CreateOnInput>DontUse</CreateOnInput>"
  1706. X "$i<SearchStringModeOnInputByString>Begin</SearchStringModeOnInputByString>"
  1707. X "$i<FullTextSearchOnInputByString>DontUse</FullTextSearchOnInputByString>"
  1708. X "$i<ChoiceDataGetModeOnInputByString>Directly</ChoiceDataGetModeOnInputByString>"
  1709. X "$i<DefaultObjectForm/>"
  1710. X "$i<DefaultListForm/>"
  1711. X "$i<DefaultChoiceForm/>"
  1712. X "$i<AuxiliaryObjectForm/>"
  1713. X "$i<AuxiliaryListForm/>"
  1714. X "$i<AuxiliaryChoiceForm/>"
  1715. X "$i<IncludeHelpInContents>false</IncludeHelpInContents>"
  1716. X "$i<DataLockFields/>"
  1717. $dataLockControlMode = if ($def.dataLockControlMode) { "$($def.dataLockControlMode)" } else { "Automatic" }
  1718. X "$i<DataLockControlMode>$dataLockControlMode</DataLockControlMode>"
  1719. $fullTextSearch = if ($def.fullTextSearch) { "$($def.fullTextSearch)" } else { "Use" }
  1720. X "$i<FullTextSearch>$fullTextSearch</FullTextSearch>"
  1721. X "$i<ObjectPresentation/>"
  1722. X "$i<ExtendedObjectPresentation/>"
  1723. X "$i<ListPresentation/>"
  1724. X "$i<ExtendedListPresentation/>"
  1725. X "$i<Explanation/>"
  1726. X "$i<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  1727. X "$i<DataHistory>DontUse</DataHistory>"
  1728. X "$i<UpdateDataHistoryImmediatelyAfterWrite>false</UpdateDataHistoryImmediatelyAfterWrite>"
  1729. X "$i<ExecuteAfterWriteDataHistoryVersionProcessing>false</ExecuteAfterWriteDataHistoryVersionProcessing>"
  1730. }
  1731. # --- 13f. Wave 6: HTTPService, WebService ---
  1732. function Emit-HTTPServiceProperties {
  1733. param([string]$indent)
  1734. $i = $indent
  1735. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1736. Emit-MLText $i "Synonym" $synonym
  1737. X "$i<Comment/>"
  1738. $rootURL = if ($def.rootURL) { "$($def.rootURL)" } else { $objName.ToLower() }
  1739. X "$i<RootURL>$(Esc-Xml $rootURL)</RootURL>"
  1740. $reuseSessions = if ($def.reuseSessions) { "$($def.reuseSessions)" } else { "DontUse" }
  1741. X "$i<ReuseSessions>$reuseSessions</ReuseSessions>"
  1742. $sessionMaxAge = if ($null -ne $def.sessionMaxAge) { "$($def.sessionMaxAge)" } else { "20" }
  1743. X "$i<SessionMaxAge>$sessionMaxAge</SessionMaxAge>"
  1744. }
  1745. function Emit-WebServiceProperties {
  1746. param([string]$indent)
  1747. $i = $indent
  1748. X "$i<Name>$(Esc-Xml $objName)</Name>"
  1749. Emit-MLText $i "Synonym" $synonym
  1750. X "$i<Comment/>"
  1751. $namespace = if ($def.namespace) { "$($def.namespace)" } else { "" }
  1752. X "$i<Namespace>$(Esc-Xml $namespace)</Namespace>"
  1753. $xdtoPackages = if ($def.xdtoPackages) { "$($def.xdtoPackages)" } else { "" }
  1754. if ($xdtoPackages) { X "$i<XDTOPackages>$xdtoPackages</XDTOPackages>" } else { X "$i<XDTOPackages/>" }
  1755. $reuseSessions = if ($def.reuseSessions) { "$($def.reuseSessions)" } else { "DontUse" }
  1756. X "$i<ReuseSessions>$reuseSessions</ReuseSessions>"
  1757. $sessionMaxAge = if ($null -ne $def.sessionMaxAge) { "$($def.sessionMaxAge)" } else { "20" }
  1758. X "$i<SessionMaxAge>$sessionMaxAge</SessionMaxAge>"
  1759. }
  1760. # --- 13g. ChildObjects emitters for new types ---
  1761. function Emit-Column {
  1762. param([string]$indent, $colDef)
  1763. $uuid = New-Guid-String
  1764. $name = ""
  1765. $synonym = ""
  1766. $indexing = "DontIndex"
  1767. $references = @()
  1768. if ($colDef -is [string]) {
  1769. $name = "$colDef"
  1770. $synonym = Split-CamelCase $name
  1771. } else {
  1772. $name = "$($colDef.name)"
  1773. $synonym = if ($colDef.synonym) { "$($colDef.synonym)" } else { Split-CamelCase $name }
  1774. if ($colDef.indexing) { $indexing = "$($colDef.indexing)" }
  1775. if ($colDef.references) { $references = @($colDef.references) }
  1776. }
  1777. X "$indent<Column uuid=`"$uuid`">"
  1778. X "$indent`t<Properties>"
  1779. X "$indent`t`t<Name>$(Esc-Xml $name)</Name>"
  1780. Emit-MLText "$indent`t`t" "Synonym" $synonym
  1781. X "$indent`t`t<Comment/>"
  1782. X "$indent`t`t<Indexing>$indexing</Indexing>"
  1783. if ($references.Count -gt 0) {
  1784. X "$indent`t`t<References>"
  1785. foreach ($ref in $references) {
  1786. X "$indent`t`t`t<xr:Item xsi:type=`"xr:MDObjectRef`">$ref</xr:Item>"
  1787. }
  1788. X "$indent`t`t</References>"
  1789. } else {
  1790. X "$indent`t`t<References/>"
  1791. }
  1792. X "$indent`t</Properties>"
  1793. X "$indent</Column>"
  1794. }
  1795. function Emit-AccountingFlag {
  1796. param([string]$indent, [string]$flagName)
  1797. $uuid = New-Guid-String
  1798. $flagSynonym = Split-CamelCase $flagName
  1799. X "$indent<AccountingFlag uuid=`"$uuid`">"
  1800. X "$indent`t<Properties>"
  1801. X "$indent`t`t<Name>$(Esc-Xml $flagName)</Name>"
  1802. Emit-MLText "$indent`t`t" "Synonym" $flagSynonym
  1803. X "$indent`t`t<Comment/>"
  1804. X "$indent`t`t<Type>"
  1805. X "$indent`t`t`t<v8:Type>xs:boolean</v8:Type>"
  1806. X "$indent`t`t</Type>"
  1807. X "$indent`t`t<PasswordMode>false</PasswordMode>"
  1808. X "$indent`t`t<Format/>"
  1809. X "$indent`t`t<EditFormat/>"
  1810. X "$indent`t`t<ToolTip/>"
  1811. X "$indent`t`t<MarkNegatives>false</MarkNegatives>"
  1812. X "$indent`t`t<Mask/>"
  1813. X "$indent`t`t<MultiLine>false</MultiLine>"
  1814. X "$indent`t`t<ExtendedEdit>false</ExtendedEdit>"
  1815. X "$indent`t`t<MinValue xsi:nil=`"true`"/>"
  1816. X "$indent`t`t<MaxValue xsi:nil=`"true`"/>"
  1817. X "$indent`t`t<FillChecking>DontCheck</FillChecking>"
  1818. X "$indent`t`t<ChoiceParameterLinks/>"
  1819. X "$indent`t`t<ChoiceParameters/>"
  1820. X "$indent`t`t<QuickChoice>Auto</QuickChoice>"
  1821. X "$indent`t`t<ChoiceForm/>"
  1822. X "$indent`t`t<LinkByType/>"
  1823. X "$indent`t`t<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  1824. X "$indent`t</Properties>"
  1825. X "$indent</AccountingFlag>"
  1826. }
  1827. function Emit-ExtDimensionAccountingFlag {
  1828. param([string]$indent, [string]$flagName)
  1829. $uuid = New-Guid-String
  1830. $flagSynonym = Split-CamelCase $flagName
  1831. X "$indent<ExtDimensionAccountingFlag uuid=`"$uuid`">"
  1832. X "$indent`t<Properties>"
  1833. X "$indent`t`t<Name>$(Esc-Xml $flagName)</Name>"
  1834. Emit-MLText "$indent`t`t" "Synonym" $flagSynonym
  1835. X "$indent`t`t<Comment/>"
  1836. X "$indent`t`t<Type>"
  1837. X "$indent`t`t`t<v8:Type>xs:boolean</v8:Type>"
  1838. X "$indent`t`t</Type>"
  1839. X "$indent`t`t<PasswordMode>false</PasswordMode>"
  1840. X "$indent`t`t<Format/>"
  1841. X "$indent`t`t<EditFormat/>"
  1842. X "$indent`t`t<ToolTip/>"
  1843. X "$indent`t`t<MarkNegatives>false</MarkNegatives>"
  1844. X "$indent`t`t<Mask/>"
  1845. X "$indent`t`t<MultiLine>false</MultiLine>"
  1846. X "$indent`t`t<ExtendedEdit>false</ExtendedEdit>"
  1847. X "$indent`t`t<MinValue xsi:nil=`"true`"/>"
  1848. X "$indent`t`t<MaxValue xsi:nil=`"true`"/>"
  1849. X "$indent`t`t<FillChecking>DontCheck</FillChecking>"
  1850. X "$indent`t`t<ChoiceParameterLinks/>"
  1851. X "$indent`t`t<ChoiceParameters/>"
  1852. X "$indent`t`t<QuickChoice>Auto</QuickChoice>"
  1853. X "$indent`t`t<ChoiceForm/>"
  1854. X "$indent`t`t<LinkByType/>"
  1855. X "$indent`t`t<ChoiceHistoryOnInput>Auto</ChoiceHistoryOnInput>"
  1856. X "$indent`t</Properties>"
  1857. X "$indent</ExtDimensionAccountingFlag>"
  1858. }
  1859. function Emit-URLTemplate {
  1860. param([string]$indent, [string]$tmplName, $tmplDef)
  1861. $uuid = New-Guid-String
  1862. $tmplSynonym = Split-CamelCase $tmplName
  1863. $template = ""
  1864. $methods = @{}
  1865. if ($tmplDef -is [string]) {
  1866. $template = "$tmplDef"
  1867. } else {
  1868. $template = if ($tmplDef.template) { "$($tmplDef.template)" } else { "/$($tmplName.ToLower())" }
  1869. if ($tmplDef.methods) {
  1870. $tmplDef.methods.PSObject.Properties | ForEach-Object {
  1871. $methods[$_.Name] = "$($_.Value)"
  1872. }
  1873. }
  1874. }
  1875. X "$indent<URLTemplate uuid=`"$uuid`">"
  1876. X "$indent`t<Properties>"
  1877. X "$indent`t`t<Name>$(Esc-Xml $tmplName)</Name>"
  1878. Emit-MLText "$indent`t`t" "Synonym" $tmplSynonym
  1879. X "$indent`t`t<Template>$(Esc-Xml $template)</Template>"
  1880. X "$indent`t</Properties>"
  1881. if ($methods.Count -gt 0) {
  1882. X "$indent`t<ChildObjects>"
  1883. foreach ($methodName in $methods.Keys) {
  1884. $methodUuid = New-Guid-String
  1885. $httpMethod = $methods[$methodName]
  1886. $methodSynonym = Split-CamelCase $methodName
  1887. $handler = "${tmplName}${methodName}"
  1888. X "$indent`t`t<Method uuid=`"$methodUuid`">"
  1889. X "$indent`t`t`t<Properties>"
  1890. X "$indent`t`t`t`t<Name>$(Esc-Xml $methodName)</Name>"
  1891. Emit-MLText "$indent`t`t`t`t" "Synonym" $methodSynonym
  1892. X "$indent`t`t`t`t<HTTPMethod>$httpMethod</HTTPMethod>"
  1893. X "$indent`t`t`t`t<Handler>$(Esc-Xml $handler)</Handler>"
  1894. X "$indent`t`t`t</Properties>"
  1895. X "$indent`t`t</Method>"
  1896. }
  1897. X "$indent`t</ChildObjects>"
  1898. } else {
  1899. X "$indent`t<ChildObjects/>"
  1900. }
  1901. X "$indent</URLTemplate>"
  1902. }
  1903. function Emit-Operation {
  1904. param([string]$indent, [string]$opName, $opDef)
  1905. $uuid = New-Guid-String
  1906. $opSynonym = Split-CamelCase $opName
  1907. $returnType = "xs:string"
  1908. $nillable = "false"
  1909. $transactioned = "false"
  1910. $handler = $opName
  1911. $params = @{}
  1912. if ($opDef -is [string]) {
  1913. $returnType = "$opDef"
  1914. } else {
  1915. if ($opDef.returnType) { $returnType = "$($opDef.returnType)" }
  1916. if ($opDef.nillable -eq $true) { $nillable = "true" }
  1917. if ($opDef.transactioned -eq $true) { $transactioned = "true" }
  1918. if ($opDef.handler) { $handler = "$($opDef.handler)" }
  1919. if ($opDef.parameters) {
  1920. $opDef.parameters.PSObject.Properties | ForEach-Object {
  1921. $params[$_.Name] = $_.Value
  1922. }
  1923. }
  1924. }
  1925. X "$indent<Operation uuid=`"$uuid`">"
  1926. X "$indent`t<Properties>"
  1927. X "$indent`t`t<Name>$(Esc-Xml $opName)</Name>"
  1928. Emit-MLText "$indent`t`t" "Synonym" $opSynonym
  1929. X "$indent`t`t<Comment/>"
  1930. X "$indent`t`t<XDTOReturningValueType>$returnType</XDTOReturningValueType>"
  1931. X "$indent`t`t<Nillable>$nillable</Nillable>"
  1932. X "$indent`t`t<Transactioned>$transactioned</Transactioned>"
  1933. X "$indent`t`t<ProcedureName>$(Esc-Xml $handler)</ProcedureName>"
  1934. X "$indent`t</Properties>"
  1935. if ($params.Count -gt 0) {
  1936. X "$indent`t<ChildObjects>"
  1937. foreach ($paramName in $params.Keys) {
  1938. $paramUuid = New-Guid-String
  1939. $paramDef = $params[$paramName]
  1940. $paramSynonym = Split-CamelCase $paramName
  1941. $paramType = "xs:string"
  1942. $paramNillable = "true"
  1943. $paramDir = "In"
  1944. if ($paramDef -is [string]) {
  1945. $paramType = "$paramDef"
  1946. } else {
  1947. if ($paramDef.type) { $paramType = "$($paramDef.type)" }
  1948. if ($paramDef.nillable -eq $false) { $paramNillable = "false" }
  1949. if ($paramDef.direction) { $paramDir = "$($paramDef.direction)" }
  1950. }
  1951. X "$indent`t`t<Parameter uuid=`"$paramUuid`">"
  1952. X "$indent`t`t`t<Properties>"
  1953. X "$indent`t`t`t`t<Name>$(Esc-Xml $paramName)</Name>"
  1954. Emit-MLText "$indent`t`t`t`t" "Synonym" $paramSynonym
  1955. X "$indent`t`t`t`t<XDTOValueType>$paramType</XDTOValueType>"
  1956. X "$indent`t`t`t`t<Nillable>$paramNillable</Nillable>"
  1957. X "$indent`t`t`t`t<TransferDirection>$paramDir</TransferDirection>"
  1958. X "$indent`t`t`t</Properties>"
  1959. X "$indent`t`t</Parameter>"
  1960. }
  1961. X "$indent`t</ChildObjects>"
  1962. } else {
  1963. X "$indent`t<ChildObjects/>"
  1964. }
  1965. X "$indent</Operation>"
  1966. }
  1967. function Emit-AddressingAttribute {
  1968. param([string]$indent, $addrDef)
  1969. $uuid = New-Guid-String
  1970. $name = ""
  1971. $attrSynonym = ""
  1972. $typeStr = ""
  1973. $addressingDimension = ""
  1974. $indexing = "Index"
  1975. if ($addrDef -is [string]) {
  1976. $name = "$addrDef"
  1977. $attrSynonym = Split-CamelCase $name
  1978. } else {
  1979. $name = "$($addrDef.name)"
  1980. $attrSynonym = if ($addrDef.synonym) { "$($addrDef.synonym)" } else { Split-CamelCase $name }
  1981. if ($addrDef.type) { $typeStr = "$($addrDef.type)" }
  1982. if ($addrDef.addressingDimension) { $addressingDimension = "$($addrDef.addressingDimension)" }
  1983. if ($addrDef.indexing) { $indexing = "$($addrDef.indexing)" }
  1984. }
  1985. X "$indent<AddressingAttribute uuid=`"$uuid`">"
  1986. X "$indent`t<Properties>"
  1987. X "$indent`t`t<Name>$(Esc-Xml $name)</Name>"
  1988. Emit-MLText "$indent`t`t" "Synonym" $attrSynonym
  1989. X "$indent`t`t<Comment/>"
  1990. if ($typeStr) {
  1991. Emit-ValueType "$indent`t`t" $typeStr
  1992. } else {
  1993. X "$indent`t`t<Type>"
  1994. X "$indent`t`t`t<v8:Type>xs:string</v8:Type>"
  1995. X "$indent`t`t</Type>"
  1996. }
  1997. if ($addressingDimension) {
  1998. X "$indent`t`t<AddressingDimension>$addressingDimension</AddressingDimension>"
  1999. } else {
  2000. X "$indent`t`t<AddressingDimension/>"
  2001. }
  2002. X "$indent`t`t<Indexing>$indexing</Indexing>"
  2003. X "$indent`t`t<FullTextSearch>Use</FullTextSearch>"
  2004. X "$indent`t`t<DataHistory>Use</DataHistory>"
  2005. X "$indent`t</Properties>"
  2006. X "$indent</AddressingAttribute>"
  2007. }
  2008. # --- 14. Namespaces ---
  2009. $script:xmlnsDecl = 'xmlns="http://v8.1c.ru/8.3/MDClasses" xmlns:app="http://v8.1c.ru/8.2/managed-application/core" xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config" xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi" xmlns:ent="http://v8.1c.ru/8.1/data/enterprise" xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform" xmlns:style="http://v8.1c.ru/8.1/data/ui/style" xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system" xmlns:v8="http://v8.1c.ru/8.1/data/core" xmlns:v8ui="http://v8.1c.ru/8.1/data/ui" xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web" xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows" xmlns:xen="http://v8.1c.ru/8.3/xcf/enums" xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef" xmlns:xr="http://v8.1c.ru/8.3/xcf/readable" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
  2010. # --- 15. Main assembler ---
  2011. $uuid = New-Guid-String
  2012. # XML declaration
  2013. X '<?xml version="1.0" encoding="UTF-8"?>'
  2014. X "<MetaDataObject $($script:xmlnsDecl) version=`"2.17`">"
  2015. X "`t<$objType uuid=`"$uuid`">"
  2016. # InternalInfo
  2017. Emit-InternalInfo "`t`t" $objType $objName
  2018. # Properties
  2019. X "`t`t<Properties>"
  2020. switch ($objType) {
  2021. "Catalog" { Emit-CatalogProperties "`t`t`t" }
  2022. "Document" { Emit-DocumentProperties "`t`t`t" }
  2023. "Enum" { Emit-EnumProperties "`t`t`t" }
  2024. "Constant" { Emit-ConstantProperties "`t`t`t" }
  2025. "InformationRegister" { Emit-InformationRegisterProperties "`t`t`t" }
  2026. "AccumulationRegister" { Emit-AccumulationRegisterProperties "`t`t`t" }
  2027. "DefinedType" { Emit-DefinedTypeProperties "`t`t`t" }
  2028. "CommonModule" { Emit-CommonModuleProperties "`t`t`t" }
  2029. "ScheduledJob" { Emit-ScheduledJobProperties "`t`t`t" }
  2030. "EventSubscription" { Emit-EventSubscriptionProperties "`t`t`t" }
  2031. "Report" { Emit-ReportProperties "`t`t`t" }
  2032. "DataProcessor" { Emit-DataProcessorProperties "`t`t`t" }
  2033. "ExchangePlan" { Emit-ExchangePlanProperties "`t`t`t" }
  2034. "ChartOfCharacteristicTypes" { Emit-ChartOfCharacteristicTypesProperties "`t`t`t" }
  2035. "DocumentJournal" { Emit-DocumentJournalProperties "`t`t`t" }
  2036. "ChartOfAccounts" { Emit-ChartOfAccountsProperties "`t`t`t" }
  2037. "AccountingRegister" { Emit-AccountingRegisterProperties "`t`t`t" }
  2038. "ChartOfCalculationTypes" { Emit-ChartOfCalculationTypesProperties "`t`t`t" }
  2039. "CalculationRegister" { Emit-CalculationRegisterProperties "`t`t`t" }
  2040. "BusinessProcess" { Emit-BusinessProcessProperties "`t`t`t" }
  2041. "Task" { Emit-TaskProperties "`t`t`t" }
  2042. "HTTPService" { Emit-HTTPServiceProperties "`t`t`t" }
  2043. "WebService" { Emit-WebServiceProperties "`t`t`t" }
  2044. }
  2045. X "`t`t</Properties>"
  2046. # ChildObjects
  2047. $hasChildren = $false
  2048. # --- Types with Attributes + TabularSections ---
  2049. $typesWithAttrTS = @("Catalog","Document","Report","DataProcessor","ExchangePlan",
  2050. "ChartOfCharacteristicTypes","ChartOfAccounts","ChartOfCalculationTypes",
  2051. "BusinessProcess","Task")
  2052. if ($objType -in $typesWithAttrTS) {
  2053. $attrs = @()
  2054. if ($def.attributes) {
  2055. foreach ($a in $def.attributes) {
  2056. $attrs += Parse-AttributeShorthand $a
  2057. }
  2058. }
  2059. $tsSections = [ordered]@{}
  2060. if ($def.tabularSections) {
  2061. # Normalize array format: [{name:"X", attributes:[...]}, ...] → {"X": [...]}
  2062. if ($def.tabularSections -is [array] -or $def.tabularSections.GetType().Name -eq "Object[]") {
  2063. foreach ($ts in $def.tabularSections) {
  2064. $tsName = $ts.name
  2065. $tsCols = if ($ts.attributes) { @($ts.attributes) } else { @() }
  2066. $tsSections[$tsName] = $tsCols
  2067. }
  2068. } else {
  2069. $def.tabularSections.PSObject.Properties | ForEach-Object {
  2070. $tsSections[$_.Name] = @($_.Value)
  2071. }
  2072. }
  2073. }
  2074. # ChartOfAccounts: AccountingFlags + ExtDimensionAccountingFlags
  2075. $acctFlags = @()
  2076. $extDimFlags = @()
  2077. if ($objType -eq "ChartOfAccounts") {
  2078. if ($def.accountingFlags) { $acctFlags = @($def.accountingFlags) }
  2079. if ($def.extDimensionAccountingFlags) { $extDimFlags = @($def.extDimensionAccountingFlags) }
  2080. }
  2081. # Task: AddressingAttributes
  2082. $addrAttrs = @()
  2083. if ($objType -eq "Task" -and $def.addressingAttributes) {
  2084. $addrAttrs = @($def.addressingAttributes)
  2085. }
  2086. $childCount = $attrs.Count + $tsSections.Count + $acctFlags.Count + $extDimFlags.Count + $addrAttrs.Count
  2087. if ($childCount -gt 0) {
  2088. $hasChildren = $true
  2089. X "`t`t<ChildObjects>"
  2090. $context = switch ($objType) {
  2091. "Catalog" { "catalog" }
  2092. "Document" { "document" }
  2093. { $_ -in @("DataProcessor","Report") } { "processor" }
  2094. default { "object" }
  2095. }
  2096. foreach ($a in $attrs) {
  2097. Emit-Attribute "`t`t`t" $a $context
  2098. }
  2099. foreach ($tsName in $tsSections.Keys) {
  2100. $columns = $tsSections[$tsName]
  2101. Emit-TabularSection "`t`t`t" $tsName $columns $objType $objName
  2102. }
  2103. foreach ($af in $acctFlags) {
  2104. Emit-AccountingFlag "`t`t`t" "$af"
  2105. }
  2106. foreach ($edf in $extDimFlags) {
  2107. Emit-ExtDimensionAccountingFlag "`t`t`t" "$edf"
  2108. }
  2109. foreach ($aa in $addrAttrs) {
  2110. Emit-AddressingAttribute "`t`t`t" $aa
  2111. }
  2112. X "`t`t</ChildObjects>"
  2113. } else {
  2114. X "`t`t<ChildObjects/>"
  2115. }
  2116. }
  2117. # --- Enum: enum values ---
  2118. if ($objType -eq "Enum") {
  2119. $values = @()
  2120. if ($def.values) {
  2121. foreach ($v in $def.values) {
  2122. $values += Parse-EnumValueShorthand $v
  2123. }
  2124. }
  2125. if ($values.Count -gt 0) {
  2126. $hasChildren = $true
  2127. X "`t`t<ChildObjects>"
  2128. foreach ($v in $values) {
  2129. Emit-EnumValue "`t`t`t" $v
  2130. }
  2131. X "`t`t</ChildObjects>"
  2132. } else {
  2133. X "`t`t<ChildObjects/>"
  2134. }
  2135. }
  2136. # --- Constant, DefinedType, ScheduledJob, EventSubscription: no ChildObjects ---
  2137. # --- Registers: dimensions + resources + attributes ---
  2138. if ($objType -in @("InformationRegister","AccumulationRegister","AccountingRegister","CalculationRegister")) {
  2139. $dims = @()
  2140. $resources = @()
  2141. $regAttrs = @()
  2142. if ($def.dimensions) {
  2143. foreach ($d in $def.dimensions) {
  2144. $dims += Parse-AttributeShorthand $d
  2145. }
  2146. }
  2147. if ($def.resources) {
  2148. foreach ($r in $def.resources) {
  2149. $resources += Parse-AttributeShorthand $r
  2150. }
  2151. }
  2152. if ($def.attributes) {
  2153. foreach ($a in $def.attributes) {
  2154. $regAttrs += Parse-AttributeShorthand $a
  2155. }
  2156. }
  2157. if ($dims.Count -gt 0 -or $resources.Count -gt 0 -or $regAttrs.Count -gt 0) {
  2158. $hasChildren = $true
  2159. X "`t`t<ChildObjects>"
  2160. foreach ($r in $resources) {
  2161. Emit-Resource "`t`t`t" $r $objType
  2162. }
  2163. foreach ($d in $dims) {
  2164. Emit-Dimension "`t`t`t" $d $objType
  2165. }
  2166. foreach ($a in $regAttrs) {
  2167. Emit-Attribute "`t`t`t" $a "register"
  2168. }
  2169. X "`t`t</ChildObjects>"
  2170. } else {
  2171. X "`t`t<ChildObjects/>"
  2172. }
  2173. }
  2174. # --- DocumentJournal: columns ---
  2175. if ($objType -eq "DocumentJournal") {
  2176. $columns = @()
  2177. if ($def.columns) { $columns = @($def.columns) }
  2178. if ($columns.Count -gt 0) {
  2179. $hasChildren = $true
  2180. X "`t`t<ChildObjects>"
  2181. foreach ($col in $columns) {
  2182. Emit-Column "`t`t`t" $col
  2183. }
  2184. X "`t`t</ChildObjects>"
  2185. } else {
  2186. X "`t`t<ChildObjects/>"
  2187. }
  2188. }
  2189. # --- HTTPService: URLTemplates ---
  2190. if ($objType -eq "HTTPService") {
  2191. $urlTemplates = @{}
  2192. if ($def.urlTemplates) {
  2193. $def.urlTemplates.PSObject.Properties | ForEach-Object {
  2194. $urlTemplates[$_.Name] = $_.Value
  2195. }
  2196. }
  2197. if ($urlTemplates.Count -gt 0) {
  2198. $hasChildren = $true
  2199. X "`t`t<ChildObjects>"
  2200. foreach ($tmplName in $urlTemplates.Keys) {
  2201. Emit-URLTemplate "`t`t`t" $tmplName $urlTemplates[$tmplName]
  2202. }
  2203. X "`t`t</ChildObjects>"
  2204. } else {
  2205. X "`t`t<ChildObjects/>"
  2206. }
  2207. }
  2208. # --- WebService: Operations ---
  2209. if ($objType -eq "WebService") {
  2210. $operations = @{}
  2211. if ($def.operations) {
  2212. $def.operations.PSObject.Properties | ForEach-Object {
  2213. $operations[$_.Name] = $_.Value
  2214. }
  2215. }
  2216. if ($operations.Count -gt 0) {
  2217. $hasChildren = $true
  2218. X "`t`t<ChildObjects>"
  2219. foreach ($opName in $operations.Keys) {
  2220. Emit-Operation "`t`t`t" $opName $operations[$opName]
  2221. }
  2222. X "`t`t</ChildObjects>"
  2223. } else {
  2224. X "`t`t<ChildObjects/>"
  2225. }
  2226. }
  2227. # --- CommonModule: no ChildObjects ---
  2228. X "`t</$objType>"
  2229. X "</MetaDataObject>"
  2230. $metadataXml = $script:xml.ToString()
  2231. # --- 16. Write files ---
  2232. # Type → plural directory mapping
  2233. $script:typePluralMap = @{
  2234. "Catalog" = "Catalogs"
  2235. "Document" = "Documents"
  2236. "Enum" = "Enums"
  2237. "Constant" = "Constants"
  2238. "InformationRegister" = "InformationRegisters"
  2239. "AccumulationRegister" = "AccumulationRegisters"
  2240. "AccountingRegister" = "AccountingRegisters"
  2241. "CalculationRegister" = "CalculationRegisters"
  2242. "ChartOfAccounts" = "ChartsOfAccounts"
  2243. "ChartOfCharacteristicTypes"= "ChartsOfCharacteristicTypes"
  2244. "ChartOfCalculationTypes" = "ChartsOfCalculationTypes"
  2245. "BusinessProcess" = "BusinessProcesses"
  2246. "Task" = "Tasks"
  2247. "ExchangePlan" = "ExchangePlans"
  2248. "DocumentJournal" = "DocumentJournals"
  2249. "Report" = "Reports"
  2250. "DataProcessor" = "DataProcessors"
  2251. "CommonModule" = "CommonModules"
  2252. "ScheduledJob" = "ScheduledJobs"
  2253. "EventSubscription" = "EventSubscriptions"
  2254. "HTTPService" = "HTTPServices"
  2255. "WebService" = "WebServices"
  2256. "DefinedType" = "DefinedTypes"
  2257. }
  2258. $typePlural = $script:typePluralMap[$objType]
  2259. $typeDir = Join-Path $OutputDir $typePlural
  2260. # Main XML file: {OutputDir}/{TypePlural}/{Name}.xml
  2261. $mainXmlPath = Join-Path $typeDir "$objName.xml"
  2262. # Types that don't have subdirectory structure (no Ext/, no modules)
  2263. $typesNoSubDir = @("DefinedType","ScheduledJob","EventSubscription")
  2264. # Object subdirectory: {OutputDir}/{TypePlural}/{Name}/Ext/
  2265. $objSubDir = Join-Path $typeDir $objName
  2266. $extDir = Join-Path $objSubDir "Ext"
  2267. if (-not (Test-Path $typeDir)) {
  2268. New-Item -ItemType Directory -Path $typeDir -Force | Out-Null
  2269. }
  2270. if ($objType -notin $typesNoSubDir) {
  2271. if (-not (Test-Path $extDir)) {
  2272. New-Item -ItemType Directory -Path $extDir -Force | Out-Null
  2273. }
  2274. }
  2275. $enc = New-Object System.Text.UTF8Encoding($true)
  2276. [System.IO.File]::WriteAllText($mainXmlPath, $metadataXml, $enc)
  2277. # Module files
  2278. $modulesCreated = @()
  2279. # Types with ObjectModule.bsl
  2280. $typesWithObjectModule = @("Catalog","Document","Report","DataProcessor","ExchangePlan",
  2281. "ChartOfAccounts","ChartOfCharacteristicTypes","ChartOfCalculationTypes",
  2282. "BusinessProcess","Task")
  2283. # Types with RecordSetModule.bsl
  2284. $typesWithRecordSetModule = @("InformationRegister","AccumulationRegister","AccountingRegister","CalculationRegister")
  2285. # Types with Module.bsl (general)
  2286. $typesWithModule = @("CommonModule","HTTPService","WebService")
  2287. if ($objType -in $typesWithObjectModule) {
  2288. $modulePath = Join-Path $extDir "ObjectModule.bsl"
  2289. if (-not (Test-Path $modulePath)) {
  2290. [System.IO.File]::WriteAllText($modulePath, "", $enc)
  2291. $modulesCreated += $modulePath
  2292. }
  2293. }
  2294. if ($objType -in $typesWithRecordSetModule) {
  2295. $modulePath = Join-Path $extDir "RecordSetModule.bsl"
  2296. if (-not (Test-Path $modulePath)) {
  2297. [System.IO.File]::WriteAllText($modulePath, "", $enc)
  2298. $modulesCreated += $modulePath
  2299. }
  2300. }
  2301. if ($objType -in $typesWithModule) {
  2302. $modulePath = Join-Path $extDir "Module.bsl"
  2303. if (-not (Test-Path $modulePath)) {
  2304. [System.IO.File]::WriteAllText($modulePath, "", $enc)
  2305. $modulesCreated += $modulePath
  2306. }
  2307. }
  2308. # Special files
  2309. if ($objType -eq "ExchangePlan") {
  2310. $contentPath = Join-Path $extDir "Content.xml"
  2311. if (-not (Test-Path $contentPath)) {
  2312. $contentXml = "<?xml version=`"1.0`" encoding=`"UTF-8`"?>`r`n<ExchangePlanContent xmlns=`"http://v8.1c.ru/8.3/MDClasses`" xmlns:xs=`"http://www.w3.org/2001/XMLSchema`" xmlns:xsi=`"http://www.w3.org/2001/XMLSchema-instance`"/>`r`n"
  2313. [System.IO.File]::WriteAllText($contentPath, $contentXml, $enc)
  2314. $modulesCreated += $contentPath
  2315. }
  2316. }
  2317. if ($objType -eq "BusinessProcess") {
  2318. $flowchartPath = Join-Path $extDir "Flowchart.xml"
  2319. if (-not (Test-Path $flowchartPath)) {
  2320. $flowchartXml = "<?xml version=`"1.0`" encoding=`"UTF-8`"?>`r`n<Flowchart xmlns=`"http://v8.1c.ru/8.3/MDClasses`"/>`r`n"
  2321. [System.IO.File]::WriteAllText($flowchartPath, $flowchartXml, $enc)
  2322. $modulesCreated += $flowchartPath
  2323. }
  2324. }
  2325. # --- 17. Register in Configuration.xml ---
  2326. $configXmlPath = Join-Path $OutputDir "Configuration.xml"
  2327. $regResult = $null
  2328. # XML tag name for Configuration.xml ChildObjects
  2329. $childTag = $objType
  2330. if (Test-Path $configXmlPath) {
  2331. $configDoc = New-Object System.Xml.XmlDocument
  2332. $configDoc.PreserveWhitespace = $true
  2333. $configDoc.Load($configXmlPath)
  2334. $nsMgr = New-Object System.Xml.XmlNamespaceManager($configDoc.NameTable)
  2335. $nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
  2336. $childObjects = $configDoc.SelectSingleNode("//md:Configuration/md:ChildObjects", $nsMgr)
  2337. if ($childObjects) {
  2338. $existing = $childObjects.SelectNodes("md:$childTag", $nsMgr)
  2339. $alreadyExists = $false
  2340. foreach ($e in $existing) {
  2341. if ($e.InnerText -eq $objName) {
  2342. $alreadyExists = $true
  2343. break
  2344. }
  2345. }
  2346. if ($alreadyExists) {
  2347. $regResult = "already"
  2348. } else {
  2349. $newElem = $configDoc.CreateElement($childTag, "http://v8.1c.ru/8.3/MDClasses")
  2350. $newElem.InnerText = $objName
  2351. if ($existing.Count -gt 0) {
  2352. # Insert after last existing element of same type
  2353. $lastElem = $existing[$existing.Count - 1]
  2354. $newWs = $configDoc.CreateWhitespace("`n`t`t`t")
  2355. $childObjects.InsertAfter($newWs, $lastElem) | Out-Null
  2356. $childObjects.InsertAfter($newElem, $newWs) | Out-Null
  2357. } else {
  2358. # No existing elements of this type — insert before closing whitespace
  2359. $lastChild = $childObjects.LastChild
  2360. if ($lastChild.NodeType -eq [System.Xml.XmlNodeType]::Whitespace) {
  2361. $newWs = $configDoc.CreateWhitespace("`n`t`t`t")
  2362. $childObjects.InsertBefore($newWs, $lastChild) | Out-Null
  2363. $childObjects.InsertBefore($newElem, $lastChild) | Out-Null
  2364. } else {
  2365. $childObjects.AppendChild($configDoc.CreateWhitespace("`n`t`t`t")) | Out-Null
  2366. $childObjects.AppendChild($newElem) | Out-Null
  2367. $childObjects.AppendChild($configDoc.CreateWhitespace("`n`t`t")) | Out-Null
  2368. }
  2369. }
  2370. # Save
  2371. $cfgSettings = New-Object System.Xml.XmlWriterSettings
  2372. $cfgSettings.Encoding = New-Object System.Text.UTF8Encoding($true)
  2373. $cfgSettings.Indent = $false
  2374. $stream = New-Object System.IO.FileStream($configXmlPath, [System.IO.FileMode]::Create)
  2375. $writer = [System.Xml.XmlWriter]::Create($stream, $cfgSettings)
  2376. $configDoc.Save($writer)
  2377. $writer.Close()
  2378. $stream.Close()
  2379. $regResult = "added"
  2380. }
  2381. } else {
  2382. $regResult = "no-childobj"
  2383. }
  2384. } else {
  2385. $regResult = "no-config"
  2386. }
  2387. # --- 18. Summary ---
  2388. $attrCount = 0
  2389. $tsCount = 0
  2390. $dimCount = 0
  2391. $resCount = 0
  2392. $valCount = 0
  2393. $colCount = 0
  2394. if ($def.attributes) { $attrCount = @($def.attributes).Count }
  2395. if ($def.tabularSections) {
  2396. if ($def.tabularSections -is [array] -or $def.tabularSections.GetType().Name -eq "Object[]") {
  2397. $tsCount = @($def.tabularSections).Count
  2398. } else {
  2399. $tsCount = @($def.tabularSections.PSObject.Properties).Count
  2400. }
  2401. }
  2402. if ($def.dimensions) { $dimCount = @($def.dimensions).Count }
  2403. if ($def.resources) { $resCount = @($def.resources).Count }
  2404. if ($def.values) { $valCount = @($def.values).Count }
  2405. if ($def.columns) { $colCount = @($def.columns).Count }
  2406. Write-Host "[OK] $objType '$objName' compiled"
  2407. Write-Host " UUID: $uuid"
  2408. Write-Host " File: $mainXmlPath"
  2409. $details = @()
  2410. if ($attrCount -gt 0) { $details += "Attributes: $attrCount" }
  2411. if ($tsCount -gt 0) { $details += "TabularSections: $tsCount" }
  2412. if ($dimCount -gt 0) { $details += "Dimensions: $dimCount" }
  2413. if ($resCount -gt 0) { $details += "Resources: $resCount" }
  2414. if ($valCount -gt 0) { $details += "Values: $valCount" }
  2415. if ($colCount -gt 0) { $details += "Columns: $colCount" }
  2416. if ($details.Count -gt 0) {
  2417. Write-Host " $($details -join ', ')"
  2418. }
  2419. foreach ($mc in $modulesCreated) {
  2420. Write-Host " Module: $mc"
  2421. }
  2422. switch ($regResult) {
  2423. "added" { Write-Host " Configuration.xml: <$childTag>$objName</$childTag> added to ChildObjects" }
  2424. "already" { Write-Host " Configuration.xml: <$childTag>$objName</$childTag> already registered" }
  2425. "no-childobj" { Write-Warning "Configuration.xml found but <ChildObjects> not found" }
  2426. "no-config" { Write-Host " Configuration.xml: not found at $configXmlPath (register manually)" }
  2427. }
.claude/skills/role-expert/scripts/role-compile.ps1 · Bundled script · 715 lines
  1. # role-compile v1.0 — Compile 1C role from JSON
  2. # Source: https://github.com/Nikolay-Shirokov/cc-1c-skills
  3. param(
  4. [Parameter(Mandatory)]
  5. [string]$JsonPath,
  6. [Parameter(Mandatory)]
  7. [string]$OutputDir
  8. )
  9. $ErrorActionPreference = "Stop"
  10. [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
  11. # --- 1. Load and validate JSON ---
  12. if (-not (Test-Path $JsonPath)) {
  13. Write-Error "File not found: $JsonPath"
  14. exit 1
  15. }
  16. $json = Get-Content -Raw -Encoding UTF8 $JsonPath
  17. $def = $json | ConvertFrom-Json
  18. if (-not $def.name) {
  19. Write-Error "JSON must have 'name' field (role programmatic name)"
  20. exit 1
  21. }
  22. $roleName = "$($def.name)"
  23. $synonym = if ($def.synonym) { "$($def.synonym)" } else { $roleName }
  24. $comment = if ($def.comment) { "$($def.comment)" } else { "" }
  25. # --- 2. XML helpers ---
  26. $script:xmlBuf = $null
  27. function X {
  28. param([string]$text)
  29. $script:xmlBuf.AppendLine($text) | Out-Null
  30. }
  31. function Esc-Xml {
  32. param([string]$s)
  33. return $s.Replace('&','&amp;').Replace('<','&lt;').Replace('>','&gt;').Replace('"','&quot;')
  34. }
  35. # --- 3. Russian synonyms → canonical English names ---
  36. $script:typeAliases = @{
  37. "Справочник" = "Catalog"
  38. "Документ" = "Document"
  39. "РегистрСведений" = "InformationRegister"
  40. "РегистрНакопления" = "AccumulationRegister"
  41. "РегистрБухгалтерии" = "AccountingRegister"
  42. "РегистрРасчета" = "CalculationRegister"
  43. "Константа" = "Constant"
  44. "ПланСчетов" = "ChartOfAccounts"
  45. "ПланВидовХарактеристик" = "ChartOfCharacteristicTypes"
  46. "ПланВидовРасчета" = "ChartOfCalculationTypes"
  47. "ПланОбмена" = "ExchangePlan"
  48. "БизнесПроцесс" = "BusinessProcess"
  49. "Задача" = "Task"
  50. "Обработка" = "DataProcessor"
  51. "Отчет" = "Report"
  52. "ОбщаяФорма" = "CommonForm"
  53. "ОбщаяКоманда" = "CommonCommand"
  54. "Подсистема" = "Subsystem"
  55. "КритерийОтбора" = "FilterCriterion"
  56. "ЖурналДокументов" = "DocumentJournal"
  57. "Последовательность" = "Sequence"
  58. "ВебСервис" = "WebService"
  59. "HTTPСервис" = "HTTPService"
  60. "СервисИнтеграции" = "IntegrationService"
  61. "ПараметрСеанса" = "SessionParameter"
  62. "ОбщийРеквизит" = "CommonAttribute"
  63. "Конфигурация" = "Configuration"
  64. "Перечисление" = "Enum"
  65. # Nested
  66. "Реквизит" = "Attribute"
  67. "СтандартныйРеквизит" = "StandardAttribute"
  68. "ТабличнаяЧасть" = "TabularSection"
  69. "Измерение" = "Dimension"
  70. "Ресурс" = "Resource"
  71. "Команда" = "Command"
  72. "РеквизитАдресации" = "AddressingAttribute"
  73. }
  74. $script:rightAliases = @{
  75. "Чтение" = "Read"
  76. "Добавление" = "Insert"
  77. "Изменение" = "Update"
  78. "Удаление" = "Delete"
  79. "Просмотр" = "View"
  80. "Редактирование" = "Edit"
  81. "ВводПоСтроке" = "InputByString"
  82. "Проведение" = "Posting"
  83. "ОтменаПроведения" = "UndoPosting"
  84. "ИнтерактивноеДобавление" = "InteractiveInsert"
  85. "ИнтерактивнаяПометкаУдаления" = "InteractiveSetDeletionMark"
  86. "ИнтерактивноеСнятиеПометкиУдаления" = "InteractiveClearDeletionMark"
  87. "ИнтерактивноеУдаление" = "InteractiveDelete"
  88. "ИнтерактивноеУдалениеПомеченных" = "InteractiveDeleteMarked"
  89. "ИнтерактивноеПроведение" = "InteractivePosting"
  90. "ИнтерактивноеПроведениеНеоперативное" = "InteractivePostingRegular"
  91. "ИнтерактивнаяОтменаПроведения" = "InteractiveUndoPosting"
  92. "ИнтерактивноеИзменениеПроведенных" = "InteractiveChangeOfPosted"
  93. "Использование" = "Use"
  94. "Получение" = "Get"
  95. "Установка" = "Set"
  96. "Старт" = "Start"
  97. "ИнтерактивныйСтарт" = "InteractiveStart"
  98. "ИнтерактивнаяАктивация" = "InteractiveActivate"
  99. "Выполнение" = "Execute"
  100. "ИнтерактивноеВыполнение" = "InteractiveExecute"
  101. "УправлениеИтогами" = "TotalsControl"
  102. "Администрирование" = "Administration"
  103. "АдминистрированиеДанных" = "DataAdministration"
  104. "ТонкийКлиент" = "ThinClient"
  105. "ВебКлиент" = "WebClient"
  106. "ТолстыйКлиент" = "ThickClient"
  107. "ВнешнееСоединение" = "ExternalConnection"
  108. "Вывод" = "Output"
  109. "СохранениеДанныхПользователя" = "SaveUserData"
  110. "МобильныйКлиент" = "MobileClient"
  111. }
  112. # Translate Russian object name to English (e.g. "Справочник.Контрагенты" → "Catalog.Контрагенты")
  113. function Translate-ObjectName {
  114. param([string]$name)
  115. $parts = $name.Split(".")
  116. $result = @()
  117. foreach ($p in $parts) {
  118. if ($script:typeAliases.ContainsKey($p)) {
  119. $result += $script:typeAliases[$p]
  120. } else {
  121. $result += $p
  122. }
  123. }
  124. return $result -join "."
  125. }
  126. # Translate Russian right name to English (e.g. "Чтение" → "Read")
  127. function Translate-RightName {
  128. param([string]$name)
  129. if ($script:rightAliases.ContainsKey($name)) {
  130. return $script:rightAliases[$name]
  131. }
  132. return $name
  133. }
  134. # --- 4. Known rights per object type (source: docs/1c-role-spec.md) ---
  135. $script:knownRights = @{
  136. "Configuration" = @(
  137. "Administration","DataAdministration","UpdateDataBaseConfiguration",
  138. "ConfigurationExtensionsAdministration","ActiveUsers","EventLog","ExclusiveMode",
  139. "ThinClient","ThickClient","WebClient","MobileClient","ExternalConnection",
  140. "Automation","Output","SaveUserData","TechnicalSpecialistMode",
  141. "InteractiveOpenExtDataProcessors","InteractiveOpenExtReports",
  142. "AnalyticsSystemClient","CollaborationSystemInfoBaseRegistration",
  143. "MainWindowModeNormal","MainWindowModeWorkplace",
  144. "MainWindowModeEmbeddedWorkplace","MainWindowModeFullscreenWorkplace","MainWindowModeKiosk"
  145. )
  146. "Catalog" = @(
  147. "Read","Insert","Update","Delete","View","Edit","InputByString",
  148. "InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
  149. "InteractiveDelete","InteractiveDeleteMarked",
  150. "InteractiveDeletePredefinedData","InteractiveSetDeletionMarkPredefinedData",
  151. "InteractiveClearDeletionMarkPredefinedData","InteractiveDeleteMarkedPredefinedData",
  152. "ReadDataHistory","ViewDataHistory","UpdateDataHistory",
  153. "UpdateDataHistoryOfMissingData","ReadDataHistoryOfMissingData",
  154. "UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
  155. "EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
  156. )
  157. "Document" = @(
  158. "Read","Insert","Update","Delete","View","Edit","InputByString",
  159. "Posting","UndoPosting",
  160. "InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
  161. "InteractiveDelete","InteractiveDeleteMarked",
  162. "InteractivePosting","InteractivePostingRegular","InteractiveUndoPosting",
  163. "InteractiveChangeOfPosted",
  164. "ReadDataHistory","ViewDataHistory","UpdateDataHistory",
  165. "UpdateDataHistoryOfMissingData","ReadDataHistoryOfMissingData",
  166. "UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
  167. "EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
  168. )
  169. "InformationRegister" = @(
  170. "Read","Update","View","Edit","TotalsControl",
  171. "ReadDataHistory","ViewDataHistory","UpdateDataHistory",
  172. "UpdateDataHistoryOfMissingData","ReadDataHistoryOfMissingData",
  173. "UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
  174. "EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
  175. )
  176. "AccumulationRegister" = @("Read","Update","View","Edit","TotalsControl")
  177. "AccountingRegister" = @("Read","Update","View","Edit","TotalsControl")
  178. "CalculationRegister" = @("Read","View")
  179. "Constant" = @(
  180. "Read","Update","View","Edit",
  181. "ReadDataHistory","ViewDataHistory","UpdateDataHistory",
  182. "UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
  183. "EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
  184. )
  185. "ChartOfAccounts" = @(
  186. "Read","Insert","Update","Delete","View","Edit","InputByString",
  187. "InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
  188. "InteractiveDelete",
  189. "InteractiveDeletePredefinedData","InteractiveSetDeletionMarkPredefinedData",
  190. "InteractiveClearDeletionMarkPredefinedData","InteractiveDeleteMarkedPredefinedData",
  191. "ReadDataHistory","ReadDataHistoryOfMissingData",
  192. "UpdateDataHistory","UpdateDataHistoryOfMissingData",
  193. "UpdateDataHistorySettings","UpdateDataHistoryVersionComment"
  194. )
  195. "ChartOfCharacteristicTypes" = @(
  196. "Read","Insert","Update","Delete","View","Edit","InputByString",
  197. "InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
  198. "InteractiveDelete","InteractiveDeleteMarked",
  199. "InteractiveDeletePredefinedData","InteractiveSetDeletionMarkPredefinedData",
  200. "InteractiveClearDeletionMarkPredefinedData","InteractiveDeleteMarkedPredefinedData",
  201. "ReadDataHistory","ViewDataHistory","UpdateDataHistory",
  202. "ReadDataHistoryOfMissingData","UpdateDataHistoryOfMissingData",
  203. "UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
  204. "EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
  205. )
  206. "ChartOfCalculationTypes" = @(
  207. "Read","Insert","Update","Delete","View","Edit","InputByString",
  208. "InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
  209. "InteractiveDelete",
  210. "InteractiveDeletePredefinedData","InteractiveSetDeletionMarkPredefinedData",
  211. "InteractiveClearDeletionMarkPredefinedData","InteractiveDeleteMarkedPredefinedData"
  212. )
  213. "ExchangePlan" = @(
  214. "Read","Insert","Update","Delete","View","Edit","InputByString",
  215. "InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
  216. "InteractiveDelete","InteractiveDeleteMarked",
  217. "ReadDataHistory","ViewDataHistory","UpdateDataHistory",
  218. "ReadDataHistoryOfMissingData","UpdateDataHistoryOfMissingData",
  219. "UpdateDataHistorySettings","UpdateDataHistoryVersionComment",
  220. "EditDataHistoryVersionComment","SwitchToDataHistoryVersion"
  221. )
  222. "BusinessProcess" = @(
  223. "Read","Insert","Update","Delete","View","Edit","InputByString",
  224. "Start","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
  225. "InteractiveDelete","InteractiveActivate","InteractiveStart"
  226. )
  227. "Task" = @(
  228. "Read","Insert","Update","Delete","View","Edit","InputByString",
  229. "Execute","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark",
  230. "InteractiveDelete","InteractiveActivate","InteractiveExecute"
  231. )
  232. "DataProcessor" = @("Use","View")
  233. "Report" = @("Use","View")
  234. "CommonForm" = @("View")
  235. "CommonCommand" = @("View")
  236. "Subsystem" = @("View")
  237. "FilterCriterion" = @("View")
  238. "DocumentJournal" = @("Read","View")
  239. "Sequence" = @("Read","Update")
  240. "WebService" = @("Use")
  241. "HTTPService" = @("Use")
  242. "IntegrationService" = @("Use")
  243. "SessionParameter" = @("Get","Set")
  244. "CommonAttribute" = @("View","Edit")
  245. }
  246. # Nested objects: Attribute, StandardAttribute, TabularSection, Dimension, Resource, AddressingAttribute
  247. $script:nestedRights = @("View","Edit")
  248. $script:commandRights = @("View")
  249. # --- 4. Presets (@view, @edit) ---
  250. $script:presets = @{
  251. "view" = @{
  252. "Catalog" = @("Read","View","InputByString")
  253. "ExchangePlan" = @("Read","View","InputByString")
  254. "Document" = @("Read","View","InputByString")
  255. "ChartOfAccounts" = @("Read","View","InputByString")
  256. "ChartOfCharacteristicTypes" = @("Read","View","InputByString")
  257. "ChartOfCalculationTypes" = @("Read","View","InputByString")
  258. "BusinessProcess" = @("Read","View","InputByString")
  259. "Task" = @("Read","View","InputByString")
  260. "InformationRegister" = @("Read","View")
  261. "AccumulationRegister" = @("Read","View")
  262. "AccountingRegister" = @("Read","View")
  263. "CalculationRegister" = @("Read","View")
  264. "Constant" = @("Read","View")
  265. "DocumentJournal" = @("Read","View")
  266. "Sequence" = @("Read")
  267. "CommonForm" = @("View")
  268. "CommonCommand" = @("View")
  269. "Subsystem" = @("View")
  270. "FilterCriterion" = @("View")
  271. "SessionParameter" = @("Get")
  272. "CommonAttribute" = @("View")
  273. "DataProcessor" = @("Use","View")
  274. "Report" = @("Use","View")
  275. "Configuration" = @("ThinClient","WebClient","Output","SaveUserData","MainWindowModeNormal")
  276. }
  277. "edit" = @{
  278. "Catalog" = @("Read","Insert","Update","Delete","View","Edit","InputByString","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark")
  279. "ExchangePlan" = @("Read","Insert","Update","Delete","View","Edit","InputByString","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark")
  280. "Document" = @("Read","Insert","Update","Delete","View","Edit","InputByString","Posting","UndoPosting","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark","InteractivePosting","InteractivePostingRegular","InteractiveUndoPosting","InteractiveChangeOfPosted")
  281. "ChartOfAccounts" = @("Read","Insert","Update","Delete","View","Edit","InputByString","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark")
  282. "ChartOfCharacteristicTypes" = @("Read","Insert","Update","Delete","View","Edit","InputByString","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark")
  283. "ChartOfCalculationTypes" = @("Read","Insert","Update","Delete","View","Edit","InputByString","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark")
  284. "BusinessProcess" = @("Read","Insert","Update","Delete","View","Edit","InputByString","Start","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark","InteractiveActivate","InteractiveStart")
  285. "Task" = @("Read","Insert","Update","Delete","View","Edit","InputByString","Execute","InteractiveInsert","InteractiveSetDeletionMark","InteractiveClearDeletionMark","InteractiveActivate","InteractiveExecute")
  286. "InformationRegister" = @("Read","Update","View","Edit")
  287. "AccumulationRegister" = @("Read","Update","View","Edit")
  288. "AccountingRegister" = @("Read","Update","View","Edit")
  289. "Constant" = @("Read","Update","View","Edit")
  290. "DocumentJournal" = @("Read","View")
  291. "Sequence" = @("Read","Update")
  292. "SessionParameter" = @("Get","Set")
  293. "CommonAttribute" = @("View","Edit")
  294. }
  295. }
  296. # --- 5. Helpers ---
  297. function Get-ObjectType {
  298. param([string]$objectName)
  299. $dotIdx = $objectName.IndexOf(".")
  300. if ($dotIdx -lt 0) { return $objectName }
  301. return $objectName.Substring(0, $dotIdx)
  302. }
  303. function Is-NestedObject {
  304. param([string]$objectName)
  305. return ($objectName.Split(".").Count -ge 3)
  306. }
  307. function Resolve-Preset {
  308. param([string]$objectType, [string]$presetName)
  309. $preset = $presetName.TrimStart('@')
  310. if (-not $script:presets.ContainsKey($preset)) {
  311. Write-Warning "Unknown preset '@$preset'. Known: @view, @edit"
  312. return @()
  313. }
  314. $typeMap = $script:presets[$preset]
  315. if (-not $typeMap.ContainsKey($objectType)) {
  316. $available = @()
  317. foreach ($k in $script:presets.Keys) {
  318. if ($script:presets[$k].ContainsKey($objectType)) {
  319. $available += "@$k"
  320. }
  321. }
  322. $availStr = if ($available.Count -gt 0) { $available -join ", " } else { "none" }
  323. Write-Warning "Preset '@$preset' not defined for type '$objectType'. Available: $availStr"
  324. return @()
  325. }
  326. return @($typeMap[$objectType])
  327. }
  328. function Validate-RightName {
  329. param([string]$objectName, [string]$rightName)
  330. $objectType = Get-ObjectType $objectName
  331. if (Is-NestedObject $objectName) {
  332. if ($objectName -match '\.Command\.') {
  333. if ($rightName -notin $script:commandRights) {
  334. Write-Warning "${objectName}: '$rightName' not valid for commands (only: View)"
  335. return $false
  336. }
  337. } else {
  338. if ($rightName -notin $script:nestedRights) {
  339. Write-Warning "${objectName}: '$rightName' not valid for nested objects (only: View, Edit)"
  340. return $false
  341. }
  342. }
  343. return $true
  344. }
  345. if (-not $script:knownRights.ContainsKey($objectType)) {
  346. Write-Warning "${objectName}: unknown object type '$objectType'"
  347. return $true
  348. }
  349. $validRights = $script:knownRights[$objectType]
  350. if ($rightName -notin $validRights) {
  351. $suggestions = @($validRights | Where-Object {
  352. $_ -like "*$rightName*" -or $rightName -like "*$_*"
  353. })
  354. $sugStr = if ($suggestions.Count -gt 0) { " Did you mean: $($suggestions -join ', ')?" } else { "" }
  355. Write-Warning "${objectName}: unknown right '$rightName'.$sugStr"
  356. return $false
  357. }
  358. return $true
  359. }
  360. # --- 6. Parse object entries ---
  361. function Parse-ObjectEntry {
  362. param($entry)
  363. # --- String shorthand ---
  364. if ($entry -is [string]) {
  365. $colonIdx = $entry.IndexOf(':')
  366. if ($colonIdx -lt 0) {
  367. Write-Warning "Invalid string '$entry' -- expected 'Object.Name: @preset' or 'Object.Name: Right1, Right2'"
  368. return $null
  369. }
  370. $objName = Translate-ObjectName ($entry.Substring(0, $colonIdx).Trim())
  371. $rightsStr = $entry.Substring($colonIdx + 1).Trim()
  372. $objectType = Get-ObjectType $objName
  373. if ($rightsStr.StartsWith('@')) {
  374. $rightNames = @(Resolve-Preset -objectType $objectType -presetName $rightsStr)
  375. } else {
  376. $rightNames = @($rightsStr -split ',\s*' | ForEach-Object { Translate-RightName $_.Trim() } | Where-Object { $_ })
  377. foreach ($r in $rightNames) {
  378. Validate-RightName -objectName $objName -rightName $r | Out-Null
  379. }
  380. }
  381. $rights = @()
  382. foreach ($r in $rightNames) {
  383. $rights += ,@{Name=$r; Value="true"; Condition=$null}
  384. }
  385. return @{ Name = $objName; Rights = $rights }
  386. }
  387. # --- Object form ---
  388. $objName = Translate-ObjectName "$($entry.name)"
  389. if (-not $objName) {
  390. Write-Warning "Object entry missing 'name' field"
  391. return $null
  392. }
  393. $objectType = Get-ObjectType $objName
  394. $rightsMap = [ordered]@{}
  395. # 1) Start with preset
  396. if ($entry.preset) {
  397. $presetRights = @(Resolve-Preset -objectType $objectType -presetName "$($entry.preset)")
  398. foreach ($r in $presetRights) {
  399. $rightsMap[$r] = @{Value="true"; Condition=$null}
  400. }
  401. }
  402. # 2) Apply explicit rights
  403. if ($entry.rights) {
  404. if ($entry.rights -is [array]) {
  405. foreach ($r in $entry.rights) {
  406. $rName = Translate-RightName "$r"
  407. Validate-RightName -objectName $objName -rightName $rName | Out-Null
  408. $rightsMap[$rName] = @{Value="true"; Condition=$null}
  409. }
  410. } else {
  411. foreach ($p in $entry.rights.PSObject.Properties) {
  412. $rName = Translate-RightName $p.Name
  413. Validate-RightName -objectName $objName -rightName $rName | Out-Null
  414. $boolVal = $p.Value
  415. if ($boolVal -eq $true -or "$boolVal" -eq "True") {
  416. $rightsMap[$rName] = @{Value="true"; Condition=$null}
  417. } else {
  418. $rightsMap[$rName] = @{Value="false"; Condition=$null}
  419. }
  420. }
  421. }
  422. }
  423. # 3) Apply RLS conditions
  424. if ($entry.rls) {
  425. foreach ($p in $entry.rls.PSObject.Properties) {
  426. $rlsRight = Translate-RightName $p.Name
  427. if ($rightsMap.Contains($rlsRight)) {
  428. $rightsMap[$rlsRight].Condition = "$($p.Value)"
  429. } else {
  430. Write-Warning "${objName}: RLS for '$rlsRight' but this right is not in the rights list"
  431. }
  432. }
  433. }
  434. # Convert to array
  435. $rights = @()
  436. foreach ($k in $rightsMap.Keys) {
  437. $rights += ,@{
  438. Name = $k
  439. Value = $rightsMap[$k].Value
  440. Condition = $rightsMap[$k].Condition
  441. }
  442. }
  443. return @{ Name = $objName; Rights = $rights }
  444. }
  445. # --- 7. Parse all object entries ---
  446. $parsedObjects = @()
  447. if ($def.objects) {
  448. foreach ($entry in $def.objects) {
  449. $parsed = Parse-ObjectEntry -entry $entry
  450. if ($parsed) {
  451. $parsedObjects += ,$parsed
  452. }
  453. }
  454. }
  455. # --- 8. Generate UUID ---
  456. $uuid = [guid]::NewGuid().ToString()
  457. # --- 9. Emit metadata XML (Roles/Name.xml) ---
  458. $script:xmlBuf = New-Object System.Text.StringBuilder 4096
  459. X '<?xml version="1.0" encoding="UTF-8"?>'
  460. X '<MetaDataObject xmlns="http://v8.1c.ru/8.3/MDClasses"'
  461. X ' xmlns:app="http://v8.1c.ru/8.2/managed-application/core"'
  462. X ' xmlns:cfg="http://v8.1c.ru/8.1/data/enterprise/current-config"'
  463. X ' xmlns:cmi="http://v8.1c.ru/8.2/managed-application/cmi"'
  464. X ' xmlns:ent="http://v8.1c.ru/8.1/data/enterprise"'
  465. X ' xmlns:lf="http://v8.1c.ru/8.2/managed-application/logform"'
  466. X ' xmlns:style="http://v8.1c.ru/8.1/data/ui/style"'
  467. X ' xmlns:sys="http://v8.1c.ru/8.1/data/ui/fonts/system"'
  468. X ' xmlns:v8="http://v8.1c.ru/8.1/data/core"'
  469. X ' xmlns:v8ui="http://v8.1c.ru/8.1/data/ui"'
  470. X ' xmlns:web="http://v8.1c.ru/8.1/data/ui/colors/web"'
  471. X ' xmlns:win="http://v8.1c.ru/8.1/data/ui/colors/windows"'
  472. X ' xmlns:xen="http://v8.1c.ru/8.3/xcf/enums"'
  473. X ' xmlns:xpr="http://v8.1c.ru/8.3/xcf/predef"'
  474. X ' xmlns:xr="http://v8.1c.ru/8.3/xcf/readable"'
  475. X ' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
  476. X ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
  477. X ' version="2.17">'
  478. X " <Role uuid=`"$uuid`">"
  479. X ' <Properties>'
  480. X " <Name>$roleName</Name>"
  481. X ' <Synonym>'
  482. X ' <v8:item>'
  483. X ' <v8:lang>ru</v8:lang>'
  484. X " <v8:content>$(Esc-Xml $synonym)</v8:content>"
  485. X ' </v8:item>'
  486. X ' </Synonym>'
  487. if ($comment) {
  488. X " <Comment>$(Esc-Xml $comment)</Comment>"
  489. } else {
  490. X ' <Comment/>'
  491. }
  492. X ' </Properties>'
  493. X ' </Role>'
  494. X '</MetaDataObject>'
  495. $metadataXml = $script:xmlBuf.ToString()
  496. # --- 10. Emit Rights XML (Roles/Name/Ext/Rights.xml) ---
  497. $script:xmlBuf = New-Object System.Text.StringBuilder 8192
  498. X '<?xml version="1.0" encoding="UTF-8"?>'
  499. X '<Rights xmlns="http://v8.1c.ru/8.2/roles"'
  500. X ' xmlns:xs="http://www.w3.org/2001/XMLSchema"'
  501. X ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
  502. X ' xsi:type="Rights" version="2.17">'
  503. # Global flags (defaults match typical 1C roles)
  504. $sfno = if ($null -ne $def.setForNewObjects) { "$($def.setForNewObjects)".ToLower() } else { "false" }
  505. $sfab = if ($null -ne $def.setForAttributesByDefault) { "$($def.setForAttributesByDefault)".ToLower() } else { "true" }
  506. $irco = if ($null -ne $def.independentRightsOfChildObjects) { "$($def.independentRightsOfChildObjects)".ToLower() } else { "false" }
  507. X " <setForNewObjects>$sfno</setForNewObjects>"
  508. X " <setForAttributesByDefault>$sfab</setForAttributesByDefault>"
  509. X " <independentRightsOfChildObjects>$irco</independentRightsOfChildObjects>"
  510. # Object blocks
  511. $totalRights = 0
  512. foreach ($obj in $parsedObjects) {
  513. X ' <object>'
  514. X " <name>$($obj.Name)</name>"
  515. foreach ($right in $obj.Rights) {
  516. X ' <right>'
  517. X " <name>$($right.Name)</name>"
  518. X " <value>$($right.Value)</value>"
  519. if ($right.Condition) {
  520. X ' <restrictionByCondition>'
  521. X " <condition>$(Esc-Xml $right.Condition)</condition>"
  522. X ' </restrictionByCondition>'
  523. }
  524. X ' </right>'
  525. $totalRights++
  526. }
  527. X ' </object>'
  528. }
  529. # RLS restriction templates
  530. $templateCount = 0
  531. if ($def.templates) {
  532. foreach ($tpl in $def.templates) {
  533. X ' <restrictionTemplate>'
  534. X " <name>$(Esc-Xml "$($tpl.name)")</name>"
  535. X " <condition>$(Esc-Xml "$($tpl.condition)")</condition>"
  536. X ' </restrictionTemplate>'
  537. $templateCount++
  538. }
  539. }
  540. X '</Rights>'
  541. $rightsXml = $script:xmlBuf.ToString()
  542. # --- 11. Write output files ---
  543. $outDir = if ([System.IO.Path]::IsPathRooted($OutputDir)) {
  544. $OutputDir
  545. } else {
  546. Join-Path (Get-Location) $OutputDir
  547. }
  548. # Metadata: OutputDir/RoleName.xml
  549. $metadataPath = Join-Path $outDir "$roleName.xml"
  550. if (-not (Test-Path $outDir)) {
  551. New-Item -ItemType Directory -Path $outDir -Force | Out-Null
  552. }
  553. # Rights: OutputDir/RoleName/Ext/Rights.xml
  554. $roleSubDir = Join-Path $outDir $roleName
  555. $extDir = Join-Path $roleSubDir "Ext"
  556. $rightsPath = Join-Path $extDir "Rights.xml"
  557. if (-not (Test-Path $extDir)) {
  558. New-Item -ItemType Directory -Path $extDir -Force | Out-Null
  559. }
  560. $enc = New-Object System.Text.UTF8Encoding($true)
  561. [System.IO.File]::WriteAllText($metadataPath, $metadataXml, $enc)
  562. [System.IO.File]::WriteAllText($rightsPath, $rightsXml, $enc)
  563. # --- 12. Register in Configuration.xml ---
  564. $configDir = Split-Path $outDir -Parent
  565. $configXmlPath = Join-Path $configDir "Configuration.xml"
  566. $regResult = $null
  567. if (Test-Path $configXmlPath) {
  568. $configDoc = New-Object System.Xml.XmlDocument
  569. $configDoc.PreserveWhitespace = $true
  570. $configDoc.Load($configXmlPath)
  571. $nsMgr = New-Object System.Xml.XmlNamespaceManager($configDoc.NameTable)
  572. $nsMgr.AddNamespace("md", "http://v8.1c.ru/8.3/MDClasses")
  573. $childObjects = $configDoc.SelectSingleNode("//md:Configuration/md:ChildObjects", $nsMgr)
  574. if ($childObjects) {
  575. $existing = $childObjects.SelectNodes("md:Role", $nsMgr)
  576. $alreadyExists = $false
  577. foreach ($r in $existing) {
  578. if ($r.InnerText -eq $roleName) {
  579. $alreadyExists = $true
  580. break
  581. }
  582. }
  583. if ($alreadyExists) {
  584. $regResult = "already"
  585. } else {
  586. $roleElem = $configDoc.CreateElement("Role", "http://v8.1c.ru/8.3/MDClasses")
  587. $roleElem.InnerText = $roleName
  588. if ($existing.Count -gt 0) {
  589. # Insert after last existing <Role>
  590. $lastRole = $existing[$existing.Count - 1]
  591. $newWs = $configDoc.CreateWhitespace("`n`t`t`t")
  592. $childObjects.InsertAfter($newWs, $lastRole) | Out-Null
  593. $childObjects.InsertAfter($roleElem, $newWs) | Out-Null
  594. } else {
  595. # No existing roles — insert before closing whitespace
  596. $lastChild = $childObjects.LastChild
  597. if ($lastChild.NodeType -eq [System.Xml.XmlNodeType]::Whitespace) {
  598. $newWs = $configDoc.CreateWhitespace("`n`t`t`t")
  599. $childObjects.InsertBefore($newWs, $lastChild) | Out-Null
  600. $childObjects.InsertBefore($roleElem, $lastChild) | Out-Null
  601. } else {
  602. $childObjects.AppendChild($configDoc.CreateWhitespace("`n`t`t`t")) | Out-Null
  603. $childObjects.AppendChild($roleElem) | Out-Null
  604. $childObjects.AppendChild($configDoc.CreateWhitespace("`n`t`t")) | Out-Null
  605. }
  606. }
  607. # Save
  608. $cfgSettings = New-Object System.Xml.XmlWriterSettings
  609. $cfgSettings.Encoding = New-Object System.Text.UTF8Encoding($true)
  610. $cfgSettings.Indent = $false
  611. $stream = New-Object System.IO.FileStream($configXmlPath, [System.IO.FileMode]::Create)
  612. $writer = [System.Xml.XmlWriter]::Create($stream, $cfgSettings)
  613. $configDoc.Save($writer)
  614. $writer.Close()
  615. $stream.Close()
  616. $regResult = "added"
  617. }
  618. } else {
  619. $regResult = "no-childobj"
  620. }
  621. } else {
  622. $regResult = "no-config"
  623. }
  624. # --- 13. Summary ---
  625. Write-Host "[OK] Role '$roleName' compiled"
  626. Write-Host " UUID: $uuid"
  627. Write-Host " Metadata: $metadataPath"
  628. Write-Host " Rights: $rightsPath"
  629. Write-Host " Objects: $($parsedObjects.Count), Rights: $totalRights, Templates: $templateCount"
  630. switch ($regResult) {
  631. "added" { Write-Host " Configuration.xml: <Role>$roleName</Role> added to ChildObjects" }
  632. "already" { Write-Host " Configuration.xml: <Role>$roleName</Role> already registered" }
  633. "no-childobj" { Write-Warning "Configuration.xml found but <ChildObjects> not found" }
  634. "no-config" { Write-Warning "Configuration.xml not found at $configXmlPath — register manually" }
  635. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.