odant-work 1.0.91 → 1.0.92

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (427) hide show
  1. package/#system/certs/russian_trusted_root_ca.pem +32 -32
  2. package/#system/mail.json.example +9 -9
  3. package/#system/package-manifest.json +332 -373
  4. package/#system/settings.json.example +3 -3
  5. package/$server/$folder/$class/$data/handlers/pages/form/objects/$handler/class.js +2158 -0
  6. package/$server/$folder/$class/$data/handlers/pages/form/objects/object/$handler/class.js +1377 -0
  7. package/$server/$folder/$class/$domain/class.js +4 -4
  8. package/$server/$folder/$class/$handler/$trigger/class.js +3 -3
  9. package/$server/$folder/$class/$handler/class.js +9 -9
  10. package/$server/$folder/$class/$handler/handlers/pages/editor/$handler/class.js +5 -5
  11. package/$server/$folder/$class/$handler/readme.md +23 -23
  12. package/$server/$folder/$class/$module/handlers/pages/form/system/{$handler/tabs/mcp/$handler/mcp.js → mcp/$handler/class.js} +251 -210
  13. package/$server/$folder/$class/$module/handlers/pages/form/system/{$handler/tabs/modules → modules}/$handler/class.js +1 -0
  14. package/$server/$folder/$class/$structure/$organization/handlers/pages/site/$handler/{site.js → class.js} +351 -364
  15. package/$server/$folder/$class/$structure/$server/handlers/pages/form/system/{$handler/tabs/license/$handler/license.js → license/$handler/class.js} +104 -103
  16. package/$server/$folder/$class/$structure/$server/handlers/pages/site/$handler/{site.js → class.js} +45 -30
  17. package/$server/$folder/$class/$structure/$user/class.js +2 -2
  18. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/agent/$handler/class.js +3 -0
  19. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/messengers/$handler/class.js +3 -0
  20. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/modules/$handler/class.js +3 -0
  21. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/{$handler/tabs/profile/$handler/profile.js → profile/$handler/class.js} +6 -2
  22. package/$server/$folder/$class/$structure/handlers/pages/data/$handler/class.js +308 -5
  23. package/$server/$folder/$class/$structure/handlers/pages/explorer/$handler/class.js +14 -3
  24. package/$server/$folder/$class/$structure/handlers/pages/form/calendar/$handler/class.js +1281 -7
  25. package/$server/$folder/$class/$structure/handlers/pages/form/calendar/$handler/readme.md +40 -40
  26. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +2216 -6
  27. package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/class.js +1304 -6
  28. package/$server/$folder/$class/$structure/handlers/pages/form/search/$handler/class.js +305 -5
  29. package/$server/$folder/$class/$structure/handlers/pages/form/system/{$handler/tabs/agent/$handler/agent.js → agent/$handler/class.js} +329 -320
  30. package/$server/$folder/$class/$structure/handlers/pages/form/system/{$handler/tabs/database/$handler/database.js → database/$handler/class.js} +510 -577
  31. package/$server/$folder/$class/$structure/handlers/pages/form/system/{$handler/tabs/messengers/$handler/messengers.js → messengers/$handler/class.js} +142 -143
  32. package/$server/$folder/$class/$structure/handlers/pages/form/system/modules/$handler/class.js +270 -0
  33. package/$server/$folder/$class/$structure/handlers/pages/form/system/staff/$handler/class.js +2114 -0
  34. package/$server/$folder/$class/$structure/handlers/pages/site/$handler/class.js +229 -4
  35. package/$server/$folder/$class/ai/config.js +19 -19
  36. package/$server/$folder/$class/ai/prompt/$method/class.js +41 -41
  37. package/$server/$folder/$class/ai/skills/approval-flow.md +14 -14
  38. package/$server/$folder/$class/ai/skills/backup-check.md +13 -13
  39. package/$server/$folder/$class/ai/skills/computer.md +27 -27
  40. package/$server/$folder/$class/ai/skills/delegate-task.md +15 -15
  41. package/$server/$folder/$class/ai/skills/external-signup.md +14 -14
  42. package/$server/$folder/$class/ai/skills/onboarding.md +15 -15
  43. package/$server/$folder/$class/ai/skills/orchestration.md +41 -41
  44. package/$server/$folder/$class/ai/system.md +1 -1
  45. package/$server/$folder/$class/class.js +0 -3
  46. package/$server/$folder/$class/handlers/pages/form/folder/$handler/class.js +3 -0
  47. package/$server/$folder/$class/handlers/pages/form/system/$handler/class.js +2 -4
  48. package/$server/$folder/$class/handlers/pages/form/system/{$handler/tabs/files → files}/$handler/class.js +2 -0
  49. package/$server/$folder/$class/handlers/pages/form/system/{$handler/tabs/requisites/$handler/requisites.js → requisites/$handler/class.js} +43 -36
  50. package/$server/$folder/$class/handlers/pages/storage/$handler/class.js +25 -6
  51. package/$server/$folder/$file/$audio/handlers/preview/$handler/class.js +3 -3
  52. package/$server/$folder/$file/$audio/handlers/preview/$handler/preview.js +88 -88
  53. package/$server/$folder/$file/$call/class.js +10 -10
  54. package/$server/$folder/$file/$call/handlers/preview/$handler/class.js +4 -4
  55. package/$server/$folder/$file/$call/triggers/on_save/$trigger/class.js +48 -48
  56. package/$server/$folder/$file/$data/class.js +16 -16
  57. package/$server/$folder/$file/$data/handlers/pages/form/editor/$handler/class.js +31 -4
  58. package/$server/$folder/$file/$devs/$js/class.js +2 -2
  59. package/$server/$folder/$file/$devs/$json/class.js +2 -2
  60. package/$server/$folder/$file/$devs/$ts/class.js +2 -2
  61. package/$server/$folder/$file/$devs/handlers/pages/form/file/$handler/class.js +30 -2
  62. package/$server/$folder/$file/$eml/class.js +17 -17
  63. package/$server/$folder/$file/$ics/class.js +44 -44
  64. package/$server/$folder/$file/$ics/handlers/pages/form/file/$handler/class.js +10 -2
  65. package/$server/$folder/$file/$ics/handlers/preview/$handler/class.js +3 -3
  66. package/$server/$folder/$file/$ics/handlers/preview/$handler/preview.js +67 -67
  67. package/$server/$folder/$file/$ics/readme.md +21 -21
  68. package/$server/$folder/$file/$image/$svg/class.js +11 -11
  69. package/$server/$folder/$file/$image/handlers/preview/$handler/class.js +3 -3
  70. package/$server/$folder/$file/$image/handlers/preview/$handler/preview.js +33 -33
  71. package/$server/$folder/$file/$ipynb/handlers/pages/form/file/$handler/class.js +82 -2
  72. package/$server/$folder/$file/$logs/class.js +39 -39
  73. package/$server/$folder/$file/$logs/handlers/methods/txt-test/$handler/class.js +4 -4
  74. package/$server/$folder/$file/$md/handlers/pages/form/file/$handler/class.js +60 -2
  75. package/$server/$folder/$file/$office/$outlook/$ics/class.js +227 -227
  76. package/$server/$folder/$file/$office/$word/$rtf/template.rtf +159 -159
  77. package/$server/$folder/$file/$office/handlers/pages/form/file/$handler/class.js +1699 -2
  78. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +827 -2
  79. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/readme.md +1 -1
  80. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +17 -0
  81. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/panel.js +7 -1
  82. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +1 -0
  83. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/voice-policy.js +6 -2
  84. package/$server/$folder/$file/$task/handlers/preview/$handler/class.js +3 -3
  85. package/$server/$folder/$file/$task/readme.md +32 -32
  86. package/$server/$folder/$file/$txt/handlers/preview/$handler/class.js +3 -3
  87. package/$server/$folder/$file/$txt/handlers/preview/$handler/preview.js +41 -41
  88. package/$server/$folder/$file/$video/handlers/preview/$handler/class.js +4 -4
  89. package/$server/$folder/$file/$video/handlers/preview/$handler/preview.js +13 -13
  90. package/$server/$folder/$file/class.js +2 -2
  91. package/$server/$folder/$file/handlers/methods/download/$handler/class.js +2 -2
  92. package/$server/$folder/$file/handlers/methods/download/$handler/download.js +4 -4
  93. package/$server/$folder/$file/handlers/pages/form/$handler/class.js +2 -2
  94. package/$server/$folder/$file/handlers/pages/form/file/$handler/class.js +32 -2
  95. package/$server/$folder/$file/handlers/pages/form/folder/$handler/class.js +3 -0
  96. package/$server/$folder/$file/readme.md +31 -31
  97. package/$server/$folder/class.js +11 -11
  98. package/$server/$folder/handlers/pages/form/$handler/class.js +2469 -5
  99. package/$server/$folder/handlers/pages/form/folder/$handler/class.js +22 -0
  100. package/$server/$folder/lib/chat-item/chat-item.js +2 -2
  101. package/$server/$folder/lib/email/settings.js +82 -82
  102. package/$server/$folder/lib/file-viewer/file-viewer.js +8 -8
  103. package/$server/$folder/lib/icon/user/user.js +6 -6
  104. package/$server/$folder/lib/item-data-grid/item-data-grid.js +48 -48
  105. package/$server/$folder/lib/item-form/item-form.js +84 -84
  106. package/$server/$folder/lib/menu/menu.js +3 -2
  107. package/$server/$folder/lib/menu/readme.md +29 -29
  108. package/$server/$folder/lib/node/readme.md +29 -29
  109. package/$server/$folder/lib/pack/pack.js +4 -4
  110. package/$server/$folder/lib/site-loc/readme.md +16 -16
  111. package/.github/workflows/ci.yml +39 -39
  112. package/AGENTS.md +1 -1
  113. package/{models/$ai/$folder/$class/$ai/handlers/pages/form/system/$handler/tabs/ai/$handler/ai.js → MODELS/$ai/$folder/$class/$ai/handlers/pages/form/system/ai/$handler/class.js} +383 -430
  114. package/{models/$ai/$folder/$class/$provider/handlers/pages/form/system/$handler/tabs/ai/$handler/ai.js → MODELS/$ai/$folder/$class/$provider/handlers/pages/form/system/ai/$handler/class.js} +155 -166
  115. package/{models → MODELS}/$ai/$folder/$class/$provider/readme.md +16 -16
  116. package/{models/$ai/handlers/pages/form/system/$handler/tabs/ai/$handler/ai.js → MODELS/$ai/handlers/pages/form/system/ai/$handler/class.js} +34 -33
  117. package/{models → MODELS}/GigaChat/$provider/readme.md +24 -24
  118. package/{models/Local/$provider/handlers/pages/form/system/$handler/tabs/ai/$handler/ai.js → MODELS/Local/$provider/handlers/pages/form/system/ai/$handler/class.js} +569 -626
  119. package/MODULES/$domain/handlers/pages/form/system/{$handler/tabs/mcp → mcp}/$handler/class.js +1 -0
  120. package/MODULES/Geo//320/232/320/260/321/200/321/202/320/260/$catalog/handlers/pages/form/map/$handler/class.js +648 -20
  121. package/MODULES/KLADR/$module/handlers/pages/form/kladr/$handler/class.js +140 -6
  122. package/MODULES/Process//320/227/320/260/320/264/320/260/321/207/320/270 /320/270 /321/215/321/202/320/260/320/277/321/213/$catalog/handlers/pages/form/gantt/$handler/class.js" +305 -5
  123. package/MODULES/Process//320/227/320/260/320/264/320/260/321/207/320/270 /320/270 /321/215/321/202/320/260/320/277/321/213/$catalog/handlers/pages/form/scheduler/$handler/class.js" +241 -5
  124. package/MODULES/Process//320/241/321/205/320/265/320/274/321/213 /320/277/321/200/320/276/321/206/320/265/321/201/321/201/320/276/320/262/$catalog/handlers/pages/form/bpmn/$handler/class.js" +515 -15
  125. package/MODULES/Register/CATALOGS/$catalog/$folder/$class/$data/$catalog/$virtual/handlers/pages/form/objects/$handler/class.js +3 -0
  126. package/MODULES/Register/CATALOGS/$catalog/$folder/$class/$data/$catalog/$virtual/handlers/pages/form/virtual/$handler/class.js +422 -5
  127. package/MODULES/Register/OPERATIONS//320/240/320/265/320/260/320/273/320/270/320/267/320/260/321/206/320/270/321/217//320/237/320/276/320/272/321/203/320/277/320/260/321/202/320/265/320/273/321/216/$operation/print//320/241/321/207/321/221/321/202 /320/275/320/260 /320/276/320/277/320/273/320/260/321/202/321/203.html" +40 -40
  128. package/MODULES/Register/OPERATIONS//320/240/320/265/320/260/320/273/320/270/320/267/320/260/321/206/320/270/321/217//320/237/320/276/320/272/321/203/320/277/320/260/321/202/320/265/320/273/321/216/$operation/print//320/242/320/276/320/262/320/260/321/200/320/275/320/260/321/217 /320/275/320/260/320/272/320/273/320/260/320/264/320/275/320/260/321/217.html" +56 -56
  129. package/MODULES/Register/REGISTER/$register/$folder/$class/$data/$register/$account/handlers/pages/form/analysis/$handler/class.js +13 -7
  130. package/MODULES/Register/REGISTER/$register/$folder/$class/$data/$register/$account/handlers/pages/form/postings/$handler/class.js +1791 -7
  131. package/MODULES/Register/REGISTER/$register/$folder/$class/$data/$register/$account/handlers/pages/form/turnovers/$handler/class.js +13 -7
  132. package/MODULES/Register/REGISTER/$register/handlers/pages/form/journal/$handler/class.js +776 -5
  133. package/MODULES/Register/REGISTER/$register/handlers/pages/form/sheet/$handler/class.js +807 -5
  134. package/MODULES/Register/REGISTER/68/01/$account/class.js +1 -1
  135. package/MODULES/Register/REGISTER/68/02/$account/class.js +1 -1
  136. package/MODULES/Register/REGISTER//320/232/320/260/320/264/321/200/320/276/320/262/321/213/320/271 /321/200/320/265/320/267/320/265/321/200/320/262/$account/class.js" +1 -1
  137. package/MODULES/Register/REGISTER//320/232/320/260/320/264/321/200/321/213//320/222 /320/276/321/202/320/277/321/203/321/201/320/272/320/265/$account/class.js" +1 -1
  138. package/MODULES/Register/REGISTER//320/232/320/260/320/264/321/200/321/213//320/240/320/260/320/261/320/276/321/202/320/260/321/216/321/202/$account/class.js +1 -1
  139. package/MODULES/Register/REGISTER//320/242/320/265/321/205/320/275/320/270/321/207/320/265/321/201/320/272/320/270/320/271/$account/class.js +1 -1
  140. package/MODULES/Register/STRUCTS/$struct/class.js +4 -4
  141. package/NODES/$node/$folder/$class/$node/class.js +35 -35
  142. package/NODES/$node/class.js +5 -5
  143. package/NODES/$node/handlers/pages/form/network/$handler/class.js +121 -4
  144. package/oda/benchmarks/dbmon/lib/ENV.js +213 -213
  145. package/oda/benchmarks/dbmon/lib/ga.js +11 -11
  146. package/oda/benchmarks/dbmon/lib/memory-stats.js +105 -105
  147. package/oda/benchmarks/dbmon/lib/monitor.js +69 -69
  148. package/oda/benchmarks/sierpinski/sierpinski.js +149 -149
  149. package/oda/components/editors/code-editor/code-editor.js +387 -387
  150. package/oda/components/editors/code-editor/src/ace.js +16 -16
  151. package/oda/components/editors/code-editor/src/beautify-css.js +1625 -1625
  152. package/oda/components/editors/code-editor/src/beautify-html.js +3122 -3122
  153. package/oda/components/editors/code-editor/src/beautify.js +4005 -4005
  154. package/oda/components/editors/code-editor/src/ext-beautify.js +7 -7
  155. package/oda/components/editors/code-editor/src/ext-code_lens.js +7 -7
  156. package/oda/components/editors/code-editor/src/ext-elastic_tabstops_lite.js +7 -7
  157. package/oda/components/editors/code-editor/src/ext-emmet.js +7 -7
  158. package/oda/components/editors/code-editor/src/ext-error_marker.js +7 -7
  159. package/oda/components/editors/code-editor/src/ext-hardwrap.js +7 -7
  160. package/oda/components/editors/code-editor/src/ext-keybinding_menu.js +7 -7
  161. package/oda/components/editors/code-editor/src/ext-language_tools.js +7 -7
  162. package/oda/components/editors/code-editor/src/ext-linking.js +7 -7
  163. package/oda/components/editors/code-editor/src/ext-modelist.js +7 -7
  164. package/oda/components/editors/code-editor/src/ext-options.js +7 -7
  165. package/oda/components/editors/code-editor/src/ext-prompt.js +7 -7
  166. package/oda/components/editors/code-editor/src/ext-rtl.js +7 -7
  167. package/oda/components/editors/code-editor/src/ext-searchbox.js +7 -7
  168. package/oda/components/editors/code-editor/src/ext-settings_menu.js +7 -7
  169. package/oda/components/editors/code-editor/src/ext-spellcheck.js +7 -7
  170. package/oda/components/editors/code-editor/src/ext-split.js +7 -7
  171. package/oda/components/editors/code-editor/src/ext-static_highlight.js +7 -7
  172. package/oda/components/editors/code-editor/src/ext-statusbar.js +7 -7
  173. package/oda/components/editors/code-editor/src/ext-textarea.js +7 -7
  174. package/oda/components/editors/code-editor/src/ext-themelist.js +7 -7
  175. package/oda/components/editors/code-editor/src/ext-whitespace.js +7 -7
  176. package/oda/components/editors/code-editor/src/keybinding-emacs.js +7 -7
  177. package/oda/components/editors/code-editor/src/keybinding-sublime.js +7 -7
  178. package/oda/components/editors/code-editor/src/keybinding-vim.js +7 -7
  179. package/oda/components/editors/code-editor/src/keybinding-vscode.js +7 -7
  180. package/oda/components/editors/code-editor/src/mode-css.js +7 -7
  181. package/oda/components/editors/code-editor/src/mode-html.js +7 -7
  182. package/oda/components/editors/code-editor/src/mode-javascript.js +7 -7
  183. package/oda/components/editors/code-editor/src/mode-json.js +7 -7
  184. package/oda/components/editors/code-editor/src/mode-markdown.js +7 -7
  185. package/oda/components/editors/code-editor/src/mode-svg.js +7 -7
  186. package/oda/components/editors/code-editor/src/mode-text.js +7 -7
  187. package/oda/components/editors/code-editor/src/mode-xml.js +7 -7
  188. package/oda/components/editors/code-editor/src/mode-xquery.js +7 -7
  189. package/oda/components/editors/code-editor/src/snippets/css.js +7 -7
  190. package/oda/components/editors/code-editor/src/snippets/html.js +7 -7
  191. package/oda/components/editors/code-editor/src/snippets/javascript.js +7 -7
  192. package/oda/components/editors/code-editor/src/snippets/json.js +7 -7
  193. package/oda/components/editors/code-editor/src/snippets/markdown.js +7 -7
  194. package/oda/components/editors/code-editor/src/snippets/svg.js +7 -7
  195. package/oda/components/editors/code-editor/src/snippets/text.js +7 -7
  196. package/oda/components/editors/code-editor/src/snippets/xml.js +7 -7
  197. package/oda/components/editors/code-editor/src/snippets/xquery.js +7 -7
  198. package/oda/components/editors/code-editor/src/theme-solarized_dark.js +7 -7
  199. package/oda/components/editors/code-editor/src/theme-solarized_light.js +7 -7
  200. package/oda/components/editors/markdown/markdown-editor/lib/font-awesome.min.css +3 -3
  201. package/oda/components/editors/markdown/markdown-editor/lib/readme.md +332 -332
  202. package/oda/components/editors/markdown/markdown-editor/markdown-editor.js +78 -78
  203. package/oda/components/editors/markdown/markdown-viewer/test.md +239 -239
  204. package/oda/components/editors/markdown/markdown.js +76 -76
  205. package/oda/components/inputs/block/readme.md +39 -39
  206. package/oda/components/inputs/checkbox/checkbox.js +92 -92
  207. package/oda/components/inputs/color/color.js +83 -83
  208. package/oda/components/inputs/date/date.js +40 -40
  209. package/oda/components/inputs/input/input.js +219 -219
  210. package/oda/components/inputs/link/link.js +1 -1
  211. package/oda/components/inputs/link/readme.md +42 -42
  212. package/oda/components/inputs/markdown-input/markdown-input.js +77 -77
  213. package/oda/components/inputs/numeric/numeric.js +141 -141
  214. package/oda/components/inputs/table-input/readme.md +39 -39
  215. package/oda/components/inputs/text/text.js +88 -88
  216. package/oda/components/inputs/toggle/toggle.js +101 -101
  217. package/oda/components/layouts/hexagon-layout/hexagon-layout.js +218 -218
  218. package/oda/components/menus/menu/index_old.html +140 -140
  219. package/oda/components/structure/controls-map.js +56 -56
  220. package/oda/components/structure/controls.js +29 -29
  221. package/oda/components/structure/readme.md +31 -31
  222. package/oda/components/structure/structure.js +64 -64
  223. package/oda/components/table/index.html +210 -210
  224. package/oda/components/table/lib/coerce.js +68 -68
  225. package/oda/components/table/lib/column.js +568 -568
  226. package/oda/components/table/readme.md +120 -120
  227. package/oda/components/table/router.js +86 -86
  228. package/oda/components/table/settings.js +89 -89
  229. package/oda/index.html +159 -159
  230. package/oda/tools/icons/icons-set/icons-set.js +60 -60
  231. package/oda/tools/icons/lib/svg/_makeSVG.html +41 -41
  232. package/oda/tools/icons/lib/svg/aws.svg +2679 -2679
  233. package/oda/tools/icons/lib/svg/info.json +46 -46
  234. package/oda/tools/jupyter/demo.ipynb +160 -160
  235. package/oda/tools/jupyter/lib/print_elements.js +73 -73
  236. package/oda/tools/jupyter/test-2.ipynb +305 -305
  237. package/oda/tools/jupyter/test.ipynb +603 -603
  238. package/oda/tools/styles/adoptedStyleSheets.js +333 -333
  239. package/oda/tools/tester/device-preview/devices.json +9 -9
  240. package/package.json +1 -1
  241. package/rules/rules.md +445 -445
  242. package/scripts/SYNC-README.md +107 -107
  243. package/scripts/agent-eval.mjs +223 -223
  244. package/scripts/dump-svn-chat.mjs +9 -9
  245. package/scripts/extract-chat-day.mjs +21 -21
  246. package/scripts/rag-bench.mjs +166 -166
  247. package/scripts/restore-chat.mjs +166 -166
  248. package/scripts/sync-svn-git.bat +129 -129
  249. package/scripts/test-merge.mjs +75 -75
  250. package/scripts/work-desktop-bridge.mjs +101 -101
  251. package/sources/client/class.js +3 -0
  252. package/sources/client/field.js +168 -168
  253. package/sources/client/handler.js +68 -32
  254. package/sources/client/index.js +32 -32
  255. package/sources/client/readme.md +16 -16
  256. package/sources/client.js +12 -0
  257. package/sources/core.js +91 -91
  258. package/sources/data/choices.js +125 -125
  259. package/sources/host/babel-merge.js +398 -353
  260. package/sources/host/config.js +48 -48
  261. package/sources/host/index-db.js +94 -94
  262. package/sources/host/net-guard.js +228 -228
  263. package/sources/host/package-install.js +63 -63
  264. package/sources/host/push.js +86 -86
  265. package/sources/host/readme.md +41 -41
  266. package/sources/host/secret-box.js +93 -93
  267. package/sources/host/server-id.js +26 -26
  268. package/sources/host/stun.js +33 -33
  269. package/sources/host/tls-ca.js +60 -60
  270. package/sources/host/vapid.js +14 -14
  271. package/sources/index.html +1 -1
  272. package/sources/modules/a2a/server.js +608 -608
  273. package/sources/modules/agent/connections.js +442 -442
  274. package/sources/modules/agent/diff.js +69 -69
  275. package/sources/modules/agent/eval.js +222 -222
  276. package/sources/modules/agent/hooks.js +131 -131
  277. package/sources/modules/agent/index.js +6 -3
  278. package/sources/modules/agent/log.js +43 -43
  279. package/sources/modules/agent/loop.js +65 -0
  280. package/sources/modules/agent/mcp-pool.js +253 -253
  281. package/sources/modules/agent/recovery.js +89 -89
  282. package/sources/modules/agent/scope.js +387 -0
  283. package/sources/modules/agent/session.js +350 -15
  284. package/sources/modules/agent/taint.js +100 -100
  285. package/sources/modules/agent/tools/branch.js +311 -311
  286. package/sources/modules/agent/tools/browser.js +254 -254
  287. package/sources/modules/agent/tools/computer.js +120 -120
  288. package/sources/modules/agent/tools/connect.js +316 -316
  289. package/sources/modules/agent/tools/dev/lsp.js +334 -334
  290. package/sources/modules/agent/tools/dev/patch.js +564 -564
  291. package/sources/modules/agent/tools/memory.js +153 -153
  292. package/sources/modules/agent/tools/meta.js +60 -0
  293. package/sources/modules/agent/tools/os-files.js +358 -358
  294. package/sources/modules/agent/tools/plugins.js +80 -80
  295. package/sources/modules/agent/tools/sandbox.js +268 -268
  296. package/sources/modules/agent/types.d.ts +183 -183
  297. package/sources/modules/agent/undo.js +254 -254
  298. package/sources/modules/agent/util.js +179 -179
  299. package/sources/modules/contacts/contacts.js +200 -200
  300. package/sources/modules/contacts/index.html +546 -546
  301. package/sources/modules/lan/discovery.js +192 -192
  302. package/sources/modules/lan/store.js +62 -62
  303. package/sources/modules/mcp/readme.md +70 -70
  304. package/sources/modules/mcp/server.js +525 -525
  305. package/sources/modules/mcp/tokens.js +140 -140
  306. package/sources/modules/nodes/identity.js +123 -123
  307. package/sources/modules/nodes/outbound.js +105 -105
  308. package/sources/modules/nodes/signing.js +71 -71
  309. package/sources/modules/rag/embed-worker.js +36 -36
  310. package/sources/modules/rag/readme.md +70 -70
  311. package/sources/modules/readme.md +21 -21
  312. package/sources/modules/sandbox/config.js +74 -74
  313. package/sources/modules/sandbox/driver.js +100 -100
  314. package/sources/modules/sandbox/images/work-computer/Dockerfile +34 -34
  315. package/sources/modules/sandbox/images/work-computer/entrypoint.sh +24 -24
  316. package/sources/modules/sandbox/manager.js +1089 -1089
  317. package/sources/modules/sandbox/readme.md +63 -63
  318. package/sources/modules/sandbox/vnc-proxy.js +296 -296
  319. package/sources/server/access/audit.js +138 -138
  320. package/sources/server/access/refs.js +106 -106
  321. package/sources/server/assert-class-id.js +23 -23
  322. package/sources/server/chat-threads.js +16 -5
  323. package/sources/server/class.js +4 -1
  324. package/sources/server/external-source.js +90 -90
  325. package/sources/server/file.js +1 -1
  326. package/sources/server/folder.js +75 -33
  327. package/sources/server/handler.js +25 -12
  328. package/sources/server/index.js +12 -12
  329. package/sources/server/memory-mark.js +34 -34
  330. package/sources/server/readme.md +110 -110
  331. package/sources/server/safe-node-name.js +67 -67
  332. package/sources/server/server.js +6 -6
  333. package/sources/server/upload-mark.js +24 -24
  334. package/sources/server/zip-guard.js +81 -81
  335. package/whitepaper.md +568 -568
  336. package/$server/$folder/$class/$module/handlers/pages/form/system/$handler/tabs/mcp/$handler/class.js +0 -9
  337. package/$server/$folder/$class/$module/handlers/pages/form/system/$handler/tabs/modules/$handler/modules.js +0 -1
  338. package/$server/$folder/$class/$structure/$server/handlers/pages/form/system/$handler/tabs/license/$handler/class.js +0 -6
  339. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/$handler/tabs/agent/$handler/class.js +0 -3
  340. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/$handler/tabs/messengers/$handler/class.js +0 -3
  341. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/$handler/tabs/modules/$handler/class.js +0 -3
  342. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/$handler/tabs/profile/$handler/class.js +0 -5
  343. package/$server/$folder/$class/$structure/handlers/pages/data/$handler/data.js +0 -313
  344. package/$server/$folder/$class/$structure/handlers/pages/explorer/$handler/explorer.js +0 -16
  345. package/$server/$folder/$class/$structure/handlers/pages/form/calendar/$handler/calendar.js +0 -1226
  346. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +0 -2095
  347. package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/email.js +0 -1188
  348. package/$server/$folder/$class/$structure/handlers/pages/form/search/$handler/search.js +0 -289
  349. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/agent/$handler/class.js +0 -6
  350. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/database/$handler/class.js +0 -9
  351. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/messengers/$handler/class.js +0 -6
  352. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/modules/$handler/class.js +0 -5
  353. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/modules/$handler/modules.js +0 -281
  354. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/staff/$handler/class.js +0 -5
  355. package/$server/$folder/$class/$structure/handlers/pages/form/system/$handler/tabs/staff/$handler/staff.js +0 -2126
  356. package/$server/$folder/$class/$structure/handlers/pages/site/$handler/site.js +0 -240
  357. package/$server/$folder/$class/handlers/pages/form/object/$handler/class.js +0 -32
  358. package/$server/$folder/$class/handlers/pages/form/object/$handler/object.js +0 -1371
  359. package/$server/$folder/$class/handlers/pages/form/objects/$handler/class.js +0 -32
  360. package/$server/$folder/$class/handlers/pages/form/objects/$handler/objects.js +0 -2130
  361. package/$server/$folder/$class/handlers/pages/form/system/$handler/system.js +0 -309
  362. package/$server/$folder/$class/handlers/pages/form/system/$handler/tabs/files/$handler/files.js +0 -17
  363. package/$server/$folder/$class/handlers/pages/form/system/$handler/tabs/requisites/$handler/class.js +0 -16
  364. package/$server/$folder/$class/handlers/pages/storage/$handler/storage.js +0 -21
  365. package/$server/$folder/$file/$data/handlers/pages/form/editor/$handler/editor.js +0 -27
  366. package/$server/$folder/$file/$devs/handlers/pages/form/file/$handler/file.js +0 -31
  367. package/$server/$folder/$file/$ics/handlers/pages/form/file/$handler/file.js +0 -10
  368. package/$server/$folder/$file/$ipynb/handlers/pages/form/file/$handler/file.js +0 -72
  369. package/$server/$folder/$file/$md/handlers/pages/form/file/$handler/file.js +0 -63
  370. package/$server/$folder/$file/$office/handlers/pages/form/file/$handler/file.js +0 -1845
  371. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +0 -760
  372. package/$server/$folder/$file/handlers/pages/form/file/$handler/file.js +0 -29
  373. package/$server/$folder/handlers/pages/form/$handler/form.js +0 -2122
  374. package/MODULES/$domain/handlers/pages/form/system/$handler/tabs/mcp/$handler/mcp.js +0 -1
  375. package/MODULES/Geo//320/232/320/260/321/200/321/202/320/260/$catalog/handlers/pages/form/map/$handler/map.js +0 -623
  376. package/MODULES/KLADR/$module/handlers/pages/form/kladr/$handler/kladr.js +0 -134
  377. package/MODULES/Process//320/227/320/260/320/264/320/260/321/207/320/270 /320/270 /321/215/321/202/320/260/320/277/321/213/$catalog/handlers/pages/form/gantt/$handler/gantt.js" +0 -293
  378. package/MODULES/Process//320/227/320/260/320/264/320/260/321/207/320/270 /320/270 /321/215/321/202/320/260/320/277/321/213/$catalog/handlers/pages/form/scheduler/$handler/scheduler.js" +0 -234
  379. package/MODULES/Process//320/241/321/205/320/265/320/274/321/213 /320/277/321/200/320/276/321/206/320/265/321/201/321/201/320/276/320/262/$catalog/handlers/pages/form/bpmn/$handler/bpmn.js" +0 -406
  380. package/MODULES/Register/CATALOGS/$catalog/$folder/$class/$data/$catalog/$virtual/handlers/pages/form/virtual/$handler/virtual.js +0 -399
  381. package/MODULES/Register/REGISTER/$register/$folder/$class/$data/$register/$account/handlers/pages/form/analysis/$handler/analysis.js +0 -9
  382. package/MODULES/Register/REGISTER/$register/$folder/$class/$data/$register/$account/handlers/pages/form/postings/$handler/postings.js +0 -1700
  383. package/MODULES/Register/REGISTER/$register/$folder/$class/$data/$register/$account/handlers/pages/form/turnovers/$handler/turnovers.js +0 -9
  384. package/MODULES/Register/REGISTER/$register/handlers/pages/form/journal/$handler/journal.js +0 -723
  385. package/MODULES/Register/REGISTER/$register/handlers/pages/form/sheet/$handler/sheet.js +0 -808
  386. package/NODES/$node/handlers/pages/form/network/$handler/network.js +0 -110
  387. package/models/$ai/$folder/$class/$ai/handlers/pages/form/system/$handler/tabs/ai/$handler/class.js +0 -6
  388. package/models/$ai/$folder/$class/$provider/handlers/pages/form/system/$handler/tabs/ai/$handler/class.js +0 -6
  389. package/models/$ai/handlers/pages/form/system/$handler/tabs/ai/$handler/class.js +0 -6
  390. package/models/Local/$provider/handlers/pages/form/system/$handler/tabs/ai/$handler/class.js +0 -6
  391. /package/$server/$folder/$class/$structure/$organization/handlers/pages/form/system/{$handler/tabs/requisites → requisites}/$handler/class.js +0 -0
  392. /package/$server/$folder/$class/$structure/$server/handlers/pages/form/system/{$handler/tabs/database → database}/$handler/class.js +0 -0
  393. /package/{models → MODELS}/$ai/$folder/$class/$ai/class.js +0 -0
  394. /package/{models → MODELS}/$ai/$folder/$class/$ai/methods/chat/$method/class.js +0 -0
  395. /package/{models → MODELS}/$ai/$folder/$class/$provider/class.js +0 -0
  396. /package/{models → MODELS}/$ai/class.js +0 -0
  397. /package/{models → MODELS}/$ai/readme.md +0 -0
  398. /package/{models → MODELS}/GigaChat/$provider/$folder/$class/$ai/class.js +0 -0
  399. /package/{models → MODELS}/GigaChat/$provider/class.js +0 -0
  400. /package/{models → MODELS}/GigaChat/GigaChat 2 Lite/$ai/class.js +0 -0
  401. /package/{models → MODELS}/GigaChat/GigaChat 2 Max/$ai/class.js +0 -0
  402. /package/{models → MODELS}/GigaChat/GigaChat 2 Pro/$ai/class.js +0 -0
  403. /package/{models → MODELS}/GigaChat/GigaChat Embeddings/$ai/class.js +0 -0
  404. /package/{models → MODELS}/Local/$provider/$folder/$class/$ai/class.js +0 -0
  405. /package/{models → MODELS}/Local/$provider/class.js +0 -0
  406. /package/{models → MODELS}/Local/$provider/handlers/methods/transfer/$handler/class.js +0 -0
  407. /package/{models → MODELS}/MTS-AI/$provider/$folder/$class/$ai/class.js +0 -0
  408. /package/{models → MODELS}/MTS-AI/$provider/class.js +0 -0
  409. /package/{models → MODELS}/MTS-AI/Cotype Lite/$ai/class.js +0 -0
  410. /package/{models → MODELS}/MTS-AI/Cotype Pro 2/$ai/class.js +0 -0
  411. /package/{models → MODELS}/MTS-AI/Cotype Vision/$ai/class.js +0 -0
  412. /package/{models → MODELS}/T-Bank/$provider/$folder/$class/$ai/class.js +0 -0
  413. /package/{models → MODELS}/T-Bank/$provider/class.js +0 -0
  414. /package/{models → MODELS}/T-Bank/T-Lite 2.0/$ai/class.js +0 -0
  415. /package/{models → MODELS}/T-Bank/T-Pro 2.0/$ai/class.js +0 -0
  416. /package/{models → MODELS}/T-Bank/T-VoiceKit ASR/$ai/class.js +0 -0
  417. /package/{models → MODELS}/T-Bank/T-VoiceKit TTS/$ai/class.js +0 -0
  418. /package/{models → MODELS}/Yandex/$provider/$folder/$class/$ai/class.js +0 -0
  419. /package/{models → MODELS}/Yandex/$provider/class.js +0 -0
  420. /package/{models → MODELS}/Yandex/Alice AI (YandexGPT 5 Pro)/$ai/class.js +0 -0
  421. /package/{models → MODELS}/Yandex/Yandex Embeddings/$ai/class.js +0 -0
  422. /package/{models → MODELS}/Yandex/Yandex SpeechKit ASR/$ai/class.js +0 -0
  423. /package/{models → MODELS}/Yandex/Yandex SpeechKit TTS/$ai/class.js +0 -0
  424. /package/{models → MODELS}/Yandex/YandexART/$ai/class.js +0 -0
  425. /package/{models → MODELS}/Yandex/YandexGPT 5 Lite/$ai/class.js +0 -0
  426. /package/{models → MODELS}/Yandex/YandexGPT Reasoning/$ai/class.js +0 -0
  427. /package/{users → USERS}/$users/class.js +0 -0
@@ -1,2130 +0,0 @@
1
- /**
2
- * form/objects — список объектов класса и редактор на учётном ядре (методы `db_*`, sources/data/api.js).
3
- * Схема — `db_schema` (поля с учётом наследования), список — `db_query` (класс с потомками,
4
- * названия ссылок приходят в `names`), редактор — модальное окно `item-object-editor`;
5
- * закрытие с несохранёнными изменениями спрашивает «Сохранить перед закрытием?».
6
- *
7
- * Операции: полоса периодов сверху (дата операции), колонки «Дата» и «Статус», в окне — дата,
8
- * проводки (действующие или предпросмотр черновика) и действия по статусу:
9
- * черновик — сохранить, удалить, провести (несохранённое сначала сохраняется);
10
- * проведённая — сохранить (= исправление: сторно и новые проводки), отменить; отменённая — только просмотр.
11
- * Справочники — весь список без полосы периодов.
12
- *
13
- * Период хранится здесь, а не в пакете: пакет stateless, состояние — per-point ($save).
14
- * `packetsKey` хранит КЛЮЧ выбора, а не границы: у пункта «Сейчас» ключ 'now'
15
- * относителен, поэтому нетронутый дефолт остаётся «сегодня», а не вчерашним днём.
16
- */
17
-
18
- // Дата по местному времени: ядро понимает 'YYYY-MM-DD' как местный день.
19
- function _day(d) {
20
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
21
- }
22
- const _today = () => _day(new Date());
23
-
24
- /** Тип поля ядра → тип редактора (editor-form). */
25
- const TYPES = {
26
- string: 'String', text: 'Text', number: 'Number', money: 'Number', integer: 'Number', boolean: 'Boolean',
27
- date: 'Date', datetime: 'DateTime', link: 'Link', struct: 'Struct', table: 'Table', enum: 'Select', file: 'File',
28
- };
29
- const STATUS = { draft: 'черновик', registered: 'проведена', cancelled: 'отменена', deleted: 'удалена' };
30
- const DATE_FIELD = Object.freeze({ id: 'time', label: 'Дата', type: 'Date', required: true });
31
- const NUM_FIELD_IDS = new Set(['num', 'doc_number', 'order_number', 'number', 'doc_num']);
32
-
33
- /** Поле схемы ядра → поле редактора: тип, справочник ссылки, варианты, вложенные поля структуры и колонки табличной части. */
34
- function formField(f) {
35
- const rawType = String(f.type || '').toLowerCase();
36
- const out = { id: f.id, label: f.label || f.id, type: TYPES[rawType] || TYPES[f.type] || 'String' };
37
- if (rawType === 'money')
38
- out.formatMoney = true;
39
- if (f.required)
40
- out.required = true;
41
- if (rawType === 'link')
42
- out.catalog = f.targetPath || f.target;
43
- if (rawType === 'enum')
44
- out.options = (f.values || f.options || []).map(v => (v && typeof v === 'object'
45
- ? { value: String(v.id ?? v.value), label: String(v.label ?? v.id ?? v.value) }
46
- : { value: String(v), label: String(v) }));
47
- if (rawType === 'struct')
48
- out.children = (f.fields || []).map(formField);
49
- if (rawType === 'table')
50
- out.columns = (f.fields || []).map(formField);
51
- return out;
52
- }
53
-
54
- /** Ключ места записи для выбора и сохранения: «подразделение|место». */
55
- function contextKeyOf(c) {
56
- return c ? `${c.unit}|${c.place ?? ''}` : '';
57
- }
58
-
59
- const money = v => (Number(v) ? Number(v).toLocaleString('ru-RU', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '');
60
- const saldo = (d, c) => {
61
- const net = (Number(d) || 0) - (Number(c) || 0);
62
- return net > 0 ? money(net) + ' Дт' : net < 0 ? money(-net) + ' Кт' : '0';
63
- };
64
-
65
- /** Строка табличной части не пуста: есть хотя бы одно заполненное поле. */
66
- function isNonEmptyRow(row) {
67
- if (!row || typeof row !== 'object')
68
- return false;
69
- return Object.values(row).some(v => v !== undefined && v !== null && String(v).trim() !== '');
70
- }
71
-
72
- const OP_STATUSES = [
73
- { id: '', label: 'Все статусы' },
74
- { id: 'draft', label: 'Черновики' },
75
- { id: 'registered', label: 'Проведённые' },
76
- { id: 'cancelled', label: 'Отменённые' },
77
- ];
78
- const CAT_STATUSES = [
79
- { id: '', label: 'Действующие' },
80
- { id: 'deleted', label: 'Удалённые' },
81
- ];
82
-
83
- export default {
84
- imports: 'oda//button, oda//packets, oda//table, ~/lib//editor-form, ~/lib//menu, ~/lib//popover, ~/lib//class-picker',
85
- template: /*html*/`
86
- <style>
87
- :host {
88
- @apply --vertical;
89
- @apply --flex;
90
- @apply --content;
91
- gap: 0;
92
- padding: 0;
93
- overflow: hidden;
94
- font-size: 13px;
95
- }
96
- .body {
97
- @apply --horizontal;
98
- flex: 1;
99
- gap: 0;
100
- overflow: hidden;
101
- }
102
- .list {
103
- @apply --vertical;
104
- flex: 1;
105
- overflow: hidden;
106
- }
107
- oda-table {
108
- flex: 1;
109
- }
110
- .bar {
111
- @apply --horizontal;
112
- @apply --header;
113
- flex-shrink: 0;
114
- gap: 8px;
115
- align-items: center;
116
- flex-wrap: wrap;
117
- padding: 3px 8px;
118
- min-height: 28px;
119
- border-bottom: 1px solid var(--border-color);
120
- font-size: 12px;
121
- }
122
- .bar input.search,
123
- .bar select {
124
- @apply --content;
125
- min-width: 0;
126
- padding: 2px 6px;
127
- font-size: 12px;
128
- border: 1px solid var(--border-color);
129
- border-radius: 3px;
130
- }
131
- .bar input.search {
132
- width: 170px;
133
- }
134
- .pager {
135
- @apply --horizontal;
136
- gap: 4px;
137
- align-items: center;
138
- margin-left: auto;
139
- font-size: 12px;
140
- }
141
- .error {
142
- padding: 6px 10px;
143
- color: var(--error-color);
144
- background: var(--error-soft);
145
- border-bottom: 1px solid var(--error-color);
146
- white-space: break-spaces;
147
- }
148
- .grid-footer {
149
- @apply --horizontal;
150
- @apply --light;
151
- color: var(--content-color);
152
- flex-shrink: 0;
153
- align-items: center;
154
- justify-content: space-between;
155
- min-height: 24px;
156
- padding: 2px 10px;
157
- border-top: 1px solid var(--border-color);
158
- font-size: 11.5px;
159
- font-weight: 600;
160
- user-select: none;
161
- }
162
- </style>
163
- <oda-packets no-flex mode="day" ~if="packetsStart && isOperation"
164
- :start="packetsStart" :end="packetsEnd" :days="packetsDays"
165
- ::value="packetsKey" @selection-changed="onPackets($event)"></oda-packets>
166
- <div class="body">
167
- <div class="list">
168
- <div class="bar" ~if="!inWorkForm">
169
- <oda-button ~if="canCreate && !inWorkForm" icon="icons:plus" @tap="create">Создать</oda-button>
170
- <oda-button icon="icons:refresh" @tap="reload">Обновить</oda-button>
171
- <input class="search" type="search" :value="searchQuery" placeholder="Поиск…" @change="onSearch($this.value)">
172
- <select title="Статус" @change="filterStatus($this.value)">
173
- <option ~for="statusOptions" :value="$for.item.id" :selected="$for.item.id === statusFilter">{{$for.item.label}}</option>
174
- </select>
175
- <select ~for="filterableFields" :title="$for.item.label" @change="setFieldFilter($for.item.id, $this.value)">
176
- <option value="" :selected="!fieldFilters[$for.item.id]">{{$for.item.label}}: все</option>
177
- <option ~for="$for.item.filterOptions" :value="$for.$for.item.value" :selected="$for.$for.item.value === fieldFilters[$for.item.id]">{{$for.$for.item.label}}</option>
178
- </select>
179
- <select ~if="units.length > 1" title="Подразделение" @change="filterUnit($this.value)">
180
- <option value="" :selected="!unitFilter">Все подразделения</option>
181
- <option ~for="units" :value="$for.item.cid" :selected="$for.item.cid === unitFilter">{{$for.item.label}}</option>
182
- </select>
183
- </div>
184
- <div class="error" ~if="error && !editorOpen">{{error}}</div>
185
- <oda-table id="objectsTable" allow-focus allow-selection even-odd col-lines row-lines readonly ::focused-row="focusedRow" ::selected-rows="selectedRows"
186
- :metadata="tableMetadata" :data-set="tableRows"
187
- :$save-key="$item?.short || $item?.path" @click="onTableClick($event)" @dblclick="onTableDblClick($event)" @cell-link-click="onCellLinkClick($event)" @row-contextmenu="onRowContextMenu($event)"></oda-table>
188
- <div class="grid-footer">
189
- <span>{{total || rows.length}}</span>
190
- <span ~if="selectedRows?.length > 1">Выбрано: {{selectedRows.length}}</span>
191
- <div class="pager" ~if="total > pageSize || page > 1">
192
- <span>{{pageText}}</span>
193
- <oda-button ~if="page > 1" icon="icons:chevron-left" icon-size="16" title="Предыдущая страница" @tap="setPage(page - 1)"></oda-button>
194
- <oda-button ~if="page * pageSize < total" icon="icons:chevron-right" icon-size="16" title="Следующая страница" @tap="setPage(page + 1)"></oda-button>
195
- </div>
196
- </div>
197
- </div>
198
- </div>
199
- `,
200
- rows: [],
201
- columns: [],
202
- schema: null,
203
- /** листья поддерева для создания объектов в группе (db_schema.leaves): [{ cid, path, label, count }] */
204
- leaves: [],
205
- /** описание классов поддерева (db_schema.classes): cid → { cid, path, parent, label, icon, leaf, count, group } */
206
- classes: {},
207
- /** выбранный лист при создании/редактировании в группе и его схема */
208
- leafCid: '',
209
- leafSchema: null,
210
- editing: null,
211
- /** проводки редактируемой операции: действующие или предпросмотр черновика */
212
- entries: [],
213
- /** названия счетов и аналитик для предпросмотра проводок (db_preview.names) */
214
- entryNames: { objects: {}, classes: {} },
215
- /** текущие сальдо объекта справочника по счетам (db_trajectory.closing) */
216
- objectBalances: [],
217
- /** движения объекта справочника по журналу (db_trajectory.items) */
218
- trajectory: [],
219
- trajectoryNames: { objects: {}, classes: {}, paths: {} },
220
- /** печатные формы открытой операции (db_print_list): [{ name, label }] */
221
- printForms: [],
222
- focusedRow: null,
223
- selectedRows: [],
224
- focusedItem: null,
225
- /** окно редактора открыто: второй клик по таблице не открывает ещё одно */
226
- editorOpen: false,
227
- /** идёт сохранение/удаление/проведение: повторные действия и закрытие ждут */
228
- busy: false,
229
- /** снимок значений на момент открытия/успешного действия — база для isDirty */
230
- _snapshot: '',
231
- /** поиск, фильтр статуса, фильтры по полям и постраничность списка */
232
- searchQuery: '',
233
- statusFilter: '',
234
- fieldFilters: {},
235
- total: 0,
236
- page: 1,
237
- pageSize: 200,
238
- _findFormHost() {
239
- if (this.$form && ('focusedItem' in this.$form || typeof this.$form.syncFromView === 'function' || typeof this.$form.openInForm === 'function' || typeof this.$form.updateActiveTabLabel === 'function' || typeof this.$form.setFormPeriod === 'function'))
240
- return this.$form;
241
- for (let p = this.parentElement || this.domHost; p; p = p.parentElement || p.domHost) {
242
- if (p.localName === 'work-form' || typeof p.syncFromView === 'function' || typeof p.openInForm === 'function' || typeof p.setFormPeriod === 'function' || 'focusedItem' in p)
243
- return p;
244
- }
245
- return null;
246
- },
247
- get inWorkForm() {
248
- return Boolean(this._findFormHost());
249
- },
250
- _notifyForm() {
251
- const host = this._findFormHost();
252
- if (!host)
253
- return;
254
- if (host.view_control && host.view_control !== this)
255
- return;
256
- if (typeof host.syncFromView === 'function')
257
- host.syncFromView(this);
258
- else
259
- host.focusedItem = this.focusedItem;
260
- },
261
- /** Вынести поле поиска в правую зону тулбара work-form (.toolbar-zone.right). */
262
- mountToolbarSlots(formHost = this._findFormHost()) {
263
- if (!formHost || typeof document === 'undefined')
264
- return;
265
- const container = formHost.$?.('.toolbar-zone.right') || formHost;
266
- let searchWrap = container.querySelector?.('[data-objects-search-wrap]');
267
- let searchInput = container.querySelector?.('input[data-objects-search]');
268
- if (!searchWrap) {
269
- searchWrap = document.createElement('div');
270
- searchWrap.setAttribute('slot', 'tool-right');
271
- searchWrap.setAttribute('data-toolbar-widget', '1');
272
- searchWrap.setAttribute('data-objects-search-wrap', '1');
273
- searchWrap.style.cssText = 'display: inline-flex; align-items: center; gap: 2px; border: 1px solid var(--border-color); border-radius: 3px; background: var(--content-background); padding: 0 2px 0 6px; min-height: 24px; box-sizing: border-box;';
274
-
275
- searchInput = document.createElement('input');
276
- searchInput.setAttribute('data-objects-search', '1');
277
- searchInput.type = 'search';
278
- searchInput.placeholder = 'Поиск по объектам…';
279
- searchInput.title = 'Серверный поиск по всему содержимому объектов (Enter или кнопка поиска)';
280
- searchInput.style.cssText = 'width: 195px; min-height: 22px; padding: 1px 4px; font-size: 12.5px; border: none; background: transparent; color: var(--content-color); outline: none;';
281
-
282
- const searchBtn = document.createElement('button');
283
- searchBtn.type = 'button';
284
- searchBtn.title = 'Найти на сервере во всём содержимом объектов';
285
- searchBtn.textContent = '🔍';
286
- searchBtn.style.cssText = 'border: none; background: transparent; color: var(--accent-color); cursor: pointer; font-size: 12px; padding: 1px 5px; border-radius: 2px; line-height: 1;';
287
-
288
- let searchTimer = null;
289
- const runNow = (force = false) => {
290
- if (searchTimer) {
291
- clearTimeout(searchTimer);
292
- searchTimer = null;
293
- }
294
- const owner = searchWrap._ownerView || this;
295
- const val = String(searchInput.value ?? '').trim();
296
- if (force || val !== String(owner.searchQuery ?? '').trim())
297
- owner.onSearch(val);
298
- };
299
- searchInput.addEventListener('input', () => {
300
- if (searchTimer)
301
- clearTimeout(searchTimer);
302
- searchTimer = setTimeout(() => runNow(false), 260);
303
- });
304
- searchInput.addEventListener('keydown', (ev) => {
305
- if (ev.key === 'Enter') {
306
- ev.preventDefault();
307
- runNow(true);
308
- }
309
- else if (ev.key === 'Escape' && searchInput.value) {
310
- ev.preventDefault();
311
- searchInput.value = '';
312
- runNow(true);
313
- }
314
- });
315
- searchInput.addEventListener('change', () => runNow(false));
316
- searchInput.addEventListener('search', () => runNow(true));
317
- searchBtn.addEventListener('click', () => runNow(true));
318
-
319
- searchWrap.appendChild(searchInput);
320
- searchWrap.appendChild(searchBtn);
321
- container.appendChild(searchWrap);
322
- }
323
- searchWrap._ownerView = this;
324
- if (searchInput) {
325
- searchInput._ownerView = this;
326
- searchInput.value = this.searchQuery || '';
327
- }
328
- formHost._checkToolbarSlots?.();
329
- },
330
- getItemButtons() {
331
- return [
332
- {
333
- id: 'create',
334
- label: 'Новый',
335
- icon: 'icons:add',
336
- isButton: true,
337
- order: 1,
338
- disabled: !this.canCreate,
339
- execute: () => this.create(),
340
- },
341
- ];
342
- },
343
- get itemButtons() {
344
- return this.getItemButtons();
345
- },
346
- getActiveSelection() {
347
- const tblSel = this.$?.('#objectsTable')?.selectedRows;
348
- const rawSel = Array.isArray(tblSel) && tblSel.length ? tblSel : this.selectedRows;
349
- const sel = Array.isArray(rawSel) ? rawSel.filter(r => r?.id) : [];
350
- if (sel.length > 0)
351
- return sel;
352
- return this.focusedRow?.id ? [this.focusedRow] : [];
353
- },
354
- get activeSelection() {
355
- return this.getActiveSelection();
356
- },
357
- canDeleteRow(row = this.focusedRow) {
358
- if (!row?.id || !this.canCreate)
359
- return false;
360
- if (this.isOperation)
361
- return row.status === 'draft';
362
- return row.status !== 'deleted';
363
- },
364
- canDeleteSelection(rows = this.getActiveSelection()) {
365
- const list = Array.isArray(rows) ? rows : (rows?.id ? [rows] : []);
366
- return list.length > 0 && list.every(r => this.canDeleteRow(r));
367
- },
368
- getFocusedButtons() {
369
- const sel = this.getActiveSelection();
370
- const isMulti = sel.length > 1;
371
- const row = sel[0] || this.focusedRow;
372
- return [
373
- {
374
- id: 'copy',
375
- label: 'Копия',
376
- icon: 'icons:content-copy',
377
- isButton: true,
378
- order: 2,
379
- disabled: isMulti || !row?.id || !this.canCreate,
380
- execute: () => this.copyRow(row),
381
- },
382
- {
383
- id: 'open',
384
- label: 'Открыть',
385
- icon: 'icons:launch',
386
- isButton: true,
387
- order: 3,
388
- disabled: isMulti || !row?.id,
389
- execute: () => this.openEditor(row),
390
- },
391
- {
392
- id: 'delete',
393
- label: 'Удалить',
394
- icon: 'icons:delete',
395
- isButton: true,
396
- allowList: true,
397
- order: 4,
398
- disabled: !this.canDeleteSelection(sel),
399
- execute: () => this.deleteRow(sel),
400
- },
401
- ];
402
- },
403
- get focusedButtons() {
404
- return this.getFocusedButtons();
405
- },
406
- getFocusedServices() {
407
- return [];
408
- },
409
- get focusedServices() {
410
- return this.getFocusedServices();
411
- },
412
- async onCellLinkClick(e) {
413
- const d = e?.detail?.value || e?.detail || {};
414
- const row = d.row;
415
- const col = d.column;
416
- const field = col?.field || col;
417
- if (!row || !field)
418
- return;
419
- if (field.isGroupCol) {
420
- const path = row._groupPath || (row.cid && this.classes?.[row.cid]?.path) || row.cid || '';
421
- if (!path)
422
- return;
423
- try {
424
- const target = await WORK.get_item(path);
425
- if (!target)
426
- return;
427
- const formHost = this._findFormHost();
428
- if (formHost && typeof formHost.openInForm === 'function')
429
- await formHost.openInForm(target, { view: 'objects' });
430
- else if (window.execute)
431
- window.execute(target, { view: 'objects' });
432
- }
433
- catch (err) {
434
- this.setError(err);
435
- }
436
- return;
437
- }
438
- const linkInfo = d.link || row._links?.[field.id];
439
- const objId = linkInfo?.id;
440
- let targetPath = linkInfo?.target || field.linkTarget || field.catalog || '';
441
- if (!objId || !targetPath)
442
- return;
443
- if (!targetPath.startsWith('/')) {
444
- const curPath = this.$item?.short || this.$item?.path || '';
445
- const m = curPath.match(/^(\/(?:ORGANIZATIONS|PROJECTS)\/[^/]+\/MODULES\/[^/]+)/);
446
- if (m)
447
- targetPath = `${m[1]}/${targetPath.replace(/^\/+/, '')}`;
448
- }
449
- try {
450
- const target = await WORK.get_item(targetPath);
451
- if (!target)
452
- return;
453
- const nav = { view: 'object', id: String(objId), label: String(row[field.id] || objId) };
454
- const formHost = this._findFormHost();
455
- if (formHost && typeof formHost.openInForm === 'function')
456
- await formHost.openInForm(target, nav);
457
- else if (window.execute)
458
- window.execute(target, nav);
459
- }
460
- catch (err) {
461
- this.setError(err);
462
- }
463
- },
464
- onTableClick() {
465
- const tbl = this.$?.('#objectsTable');
466
- if (tbl) {
467
- if (tbl.focusedRow !== undefined)
468
- this.focusedRow = tbl.focusedRow;
469
- if (Array.isArray(tbl.selectedRows))
470
- this.selectedRows = tbl.selectedRows;
471
- }
472
- this._syncFocusedItem();
473
- },
474
- onTableDblClick() {
475
- if (this.focusedRow?.id && !this.editorOpen)
476
- this.openEditor(this.focusedRow);
477
- },
478
- async onRowContextMenu(e) {
479
- const d = e?.detail?.value || e?.detail || {};
480
- const row = d.row || this.focusedRow;
481
- const origEvent = d.originalEvent || e;
482
- const tbl = this.$?.('#objectsTable');
483
- if (tbl) {
484
- if (tbl.focusedRow !== undefined)
485
- this.focusedRow = tbl.focusedRow;
486
- if (Array.isArray(tbl.selectedRows))
487
- this.selectedRows = tbl.selectedRows;
488
- }
489
- else if (row) {
490
- this.focusedRow = row;
491
- }
492
- this._syncFocusedItem();
493
- if (!row?.id || typeof WORK?.showMenu !== 'function')
494
- return;
495
- const sel = this.getActiveSelection();
496
- const isMulti = sel.length > 1;
497
- const objTitle = row.name || row.id;
498
- const tools = [
499
- {
500
- id: 'create',
501
- label: 'Создать объект',
502
- shortcut: 'CTRL+INSERT',
503
- icon: 'icons:add',
504
- disabled: !this.canCreate,
505
- execute: () => this.create(),
506
- },
507
- {
508
- id: 'copy',
509
- label: 'Создать объект (копия)',
510
- shortcut: 'CTRL+SHIFT+C',
511
- icon: 'icons:content-copy',
512
- disabled: isMulti || !row?.id || !this.canCreate,
513
- execute: () => this.copyRow(row),
514
- },
515
- {
516
- id: 'open',
517
- label: `Открыть объект '${objTitle}'`,
518
- icon: 'icons:launch',
519
- disabled: isMulti || !row?.id,
520
- execute: () => this.openEditor(row),
521
- },
522
- {
523
- id: 'delete',
524
- label: isMulti ? `Удалить объекты (${sel.length})` : 'Удалить объект',
525
- shortcut: 'DELETE',
526
- icon: 'icons:delete',
527
- disabled: !this.canDeleteSelection(sel),
528
- execute: () => this.deleteRow(sel),
529
- },
530
- ];
531
- try {
532
- await WORK.showMenu({
533
- TITLE: { label: isMulti ? `объекты (${sel.length})` : `объект: ${objTitle}` },
534
- mode: 'tools',
535
- customTools: tools,
536
- }, origEvent);
537
- }
538
- catch (err) {
539
- if (!(WORK.CancelError && err instanceof WORK.CancelError))
540
- console.warn(err);
541
- }
542
- },
543
- _syncFocusedItem() {
544
- const sel = this.getActiveSelection();
545
- if (sel.length > 1)
546
- this.focusedItem = sel;
547
- else if (sel.length === 1)
548
- this.focusedItem = sel[0];
549
- else
550
- this.focusedItem = null;
551
- this._notifyForm();
552
- },
553
- $observers: {
554
- /** внутри work-form одиночный клик фокусирует строку ($focusedItem), множественный — массив ($focusedItem), автономно — открывает редактор */
555
- select(focusedRow) {
556
- this._syncFocusedItem();
557
- if (!this.inWorkForm && focusedRow?.id && !this.editorOpen)
558
- this.openEditor(focusedRow);
559
- },
560
- onSelectedRowsChanged(selectedRows) {
561
- this._syncFocusedItem();
562
- }
563
- },
564
- /** id объекта → название (ссылки в строках списка) */
565
- names: {},
566
- error: '',
567
- /** Ошибки полей из ответа сервера (DataError.errors): { [field]: message } */
568
- fieldErrors: {},
569
- setError(e) {
570
- this.error = String(e?.message || e || '');
571
- const map = {};
572
- if (Array.isArray(e?.errors)) {
573
- for (const item of e.errors) {
574
- if (item?.field && item?.message)
575
- map[item.field] = map[item.field] ? `${map[item.field]}; ${item.message}` : item.message;
576
- }
577
- }
578
- else if (this.error.includes('\n')) {
579
- for (const line of this.error.split('\n')) {
580
- const m = /^\s*[—-]\s*([a-zA-Z0-9_.\[\]]+)\s*:\s*(.+)$/.exec(line);
581
- if (m)
582
- map[m[1]] = map[m[1]] ? `${map[m[1]]}; ${m[2].trim()}` : m[2].trim();
583
- }
584
- }
585
- this.fieldErrors = map;
586
- },
587
- clearError() {
588
- this.error = '';
589
- this.fieldErrors = {};
590
- },
591
- /** Ключ выбранного пакета: 'now' | '*' | маска единицы | 'period:start:end'. */
592
- packetsKey: { $def: 'now', $type: String, $save: true },
593
- /** Режим гранулярности пакета: 'day' | 'week' | 'month' | 'quarter' | 'year'. */
594
- packetsMode: { $def: 'day', $type: String, $save: true },
595
- packetsStart: '',
596
- packetsEnd: '',
597
- packetsDays: [],
598
- /** Период, который показал пакет, — единственный источник границ для выборки операций. */
599
- period: null,
600
- /** Подразделения, данные которых видны (db_scope): больше одного — фильтр списка. */
601
- units: [],
602
- /** Выбранное подразделение фильтра (cid), пусто — все. */
603
- unitFilter: '',
604
- /** Подразделения и места, от которых пользователь создаёт объекты (db_scope). */
605
- contexts: [],
606
- /** Последнее выбранное место записи: «подразделение|место». */
607
- contextKey: { $def: '', $type: String, $save: true },
608
- /** Место записи нового объекта: выбранное или первое из доступных. */
609
- get context() {
610
- const list = this.contexts || [];
611
- return list.find(c => contextKeyOf(c) === this.contextKey) ?? list[0] ?? null;
612
- },
613
- /** Выбор места записи нужен, если их несколько (иначе сервер возьмёт единственное). */
614
- get showContext() {
615
- return (this.contexts || []).length > 1;
616
- },
617
- contextKeyOf,
618
- /** Сменить фильтр подразделения списка и перечитать. */
619
- filterUnit(cid) {
620
- this.unitFilter = cid || '';
621
- this.page = 1;
622
- return this.reload();
623
- },
624
- onSearch(q) {
625
- this.searchQuery = String(q ?? '').trim();
626
- this.page = 1;
627
- return this.reload();
628
- },
629
- filterStatus(status) {
630
- this.statusFilter = status || '';
631
- this.page = 1;
632
- return this.reload();
633
- },
634
- setFieldFilter(fieldId, value) {
635
- const next = { ...(this.fieldFilters || {}) };
636
- if (value === '' || value === undefined || value === null)
637
- delete next[fieldId];
638
- else
639
- next[fieldId] = String(value);
640
- this.fieldFilters = next;
641
- this.page = 1;
642
- return this.reload();
643
- },
644
- setPage(p) {
645
- const n = Math.max(1, Number(p) || 1);
646
- if (n === this.page)
647
- return;
648
- this.page = n;
649
- return this.reload();
650
- },
651
- get statusOptions() {
652
- return this.schema?.family === 'operation' ? OP_STATUSES : CAT_STATUSES;
653
- },
654
- /** Поля списка и флагов для быстрого отбора в шапке. */
655
- get filterableFields() {
656
- return (this.columns || []).filter(c => c.type === 'Select' || c.type === 'Boolean').map(c => ({
657
- id: c.id,
658
- label: c.label || c.id,
659
- filterOptions: c.type === 'Boolean'
660
- ? [{ value: '1', label: 'Да' }, { value: '0', label: 'Нет' }]
661
- : (c.options || []),
662
- }));
663
- },
664
- get pageText() {
665
- const from = (this.page - 1) * this.pageSize + 1;
666
- const to = Math.min(this.page * this.pageSize, this.total || this.rows.length);
667
- return `${from}–${to} из ${this.total}`;
668
- },
669
- contextTitle(c) {
670
- return c?.place ? `${c.unit_label} / ${c.place_label}` : c?.unit_label || '';
671
- },
672
- /** Действующая схема редактора: у выбранного в группе листа — его схема, иначе схема класса. */
673
- get activeSchema() {
674
- return this.leafSchema || this.schema;
675
- },
676
- get isOperation() {
677
- return this.schema?.family === 'operation';
678
- },
679
- get hasPostings() {
680
- const s = this.activeSchema;
681
- return this.isOperation && Array.isArray(s?.POSTINGS) && s.POSTINGS.length > 0;
682
- },
683
- /** Объекты создаются в листе справочника или операции (либо в группе, где есть листья). */
684
- get canCreate() {
685
- const s = this.schema;
686
- return !!s && (!!s.leaf || (this.leaves?.length > 0)) && (s.family === 'catalog' || s.family === 'operation') && s.type !== '$virtual';
687
- },
688
- /** Выбор листа в окне нового объекта нужен в группе с несколькими листьями. */
689
- get showLeafSelect() {
690
- return !!this.schema && !this.schema.leaf && (this.leaves?.length || 0) > 1;
691
- },
692
- /** Колонка «Операция» / «Вид» показывается у группы классов с поддеревом. */
693
- get showClassCol() {
694
- return !!this.schema && !this.schema.leaf && Object.keys(this.classes || {}).length > 1;
695
- },
696
- get status() {
697
- return this.editing?.status || '';
698
- },
699
- /** Сохранять можно справочник, новый объект, черновик и проведённую операцию (исправление). */
700
- get canSave() {
701
- return !!this.editing && this.status !== 'cancelled' && this.status !== 'deleted';
702
- },
703
- get canRemove() {
704
- return !!this.editing?.id && (!this.isOperation || this.status === 'draft') && this.status !== 'deleted';
705
- },
706
- get canRestore() {
707
- return !!this.editing?.id && !this.isOperation && this.status === 'deleted';
708
- },
709
- get canRegister() {
710
- return this.isOperation && !!this.editing && (!this.editing.id || this.status === 'draft');
711
- },
712
- get canCancel() {
713
- return this.isOperation && this.status === 'registered';
714
- },
715
- /** Заголовок окна: класс + имя объекта; у нового имени ещё нет. */
716
- get editorTitle() {
717
- const title = this.activeSchema?.title || this.schema?.title || '';
718
- const field = this.fieldList().find(f => ['name', 'label', 'title'].includes(f.id));
719
- const name = field ? String(this.editing?.[field.id] ?? '').trim() : '';
720
- const object = name || (this.editing?.id ? '' : 'новый объект');
721
- if (!title)
722
- return object || 'Объект';
723
- if (!object || title === object)
724
- return title;
725
- return title + ' · ' + object;
726
- },
727
- /** Относительный путь места хранения объекта внутри промежуточного класса (для колонки «Группа»). */
728
- groupLabelOf(cid) {
729
- if (!cid)
730
- return '';
731
- const entry = this.classes?.[cid];
732
- if (!entry)
733
- return String(cid);
734
- if (typeof entry.group === 'string' && entry.group)
735
- return entry.group;
736
- const rootCid = this.schema?.cid || '';
737
- const rootPath = this.schema?.path || this.$item?.path || this.$item?.short || '';
738
- if (entry.parent) {
739
- const parts = [];
740
- let cur = entry;
741
- const seen = new Set();
742
- while (cur && cur.cid !== rootCid && cur.path !== rootPath && !seen.has(cur.cid)) {
743
- seen.add(cur.cid);
744
- parts.unshift(cur.label || cur.cid.split('/').pop());
745
- cur = cur.parent ? this.classes?.[cur.parent] : null;
746
- }
747
- if (parts.length)
748
- return parts.join('/');
749
- }
750
- let basePath = rootPath;
751
- if (!basePath) {
752
- const rootEntry = Object.values(this.classes || {}).find(c => !c.leaf);
753
- basePath = rootEntry?.path || '';
754
- }
755
- if (basePath && entry.path && entry.path.startsWith(basePath + '/')) {
756
- const rel = entry.path.slice(basePath.length + 1).split('/').filter(Boolean);
757
- const byPath = new Map(Object.values(this.classes || {}).filter(c => c?.path).map(c => [c.path, c.label]));
758
- let acc = basePath;
759
- const labels = rel.map(seg => {
760
- acc += '/' + seg;
761
- return byPath.get(acc) || seg;
762
- });
763
- if (labels.length)
764
- return labels.join('/');
765
- }
766
- return entry.label || String(cid);
767
- },
768
- /** Колонки таблицы: первым всегда «Наименование» (прилипает слева), у операций — дата и статус, у промежуточного класса — колонка «Группа» справа (прилипает справа). */
769
- get tableMetadata() {
770
- const rawCols = (this.columns || []).map(c => {
771
- if (c.type === 'Link')
772
- return { ...c, type: 'String', isLinkCol: true, linkTarget: c.catalog || '' };
773
- if (c.type === 'Table' || c.type === 'Struct')
774
- return { ...c, type: 'String' };
775
- return c;
776
- });
777
- const existingName = rawCols.find(c => c.id === 'name');
778
- const nameCol = {
779
- ...(existingName || { id: 'name', type: 'String' }),
780
- id: 'name',
781
- label: (!existingName?.label || existingName.label === 'name') ? 'Наименование' : existingName.label,
782
- stickyLeft: true,
783
- minWidth: 200,
784
- };
785
- const restCols = rawCols.filter(c => c.id !== 'name');
786
- const orderedCols = this.isOperation && restCols.length > 1
787
- ? [...rawCols.filter(c => c.id !== 'name' && c.id !== 'comment'), ...rawCols.filter(c => c.id === 'comment')]
788
- : restCols;
789
- const clsCol = this.showClassCol ? [{ id: 'cls', label: 'Группа', type: 'String', isGroupCol: true, stickyRight: true, minWidth: 170 }] : [];
790
- return this.isOperation
791
- ? [nameCol, { id: 'time', label: 'Дата', type: 'String', isDateCol: true, system: false, minWidth: 96 }, ...orderedCols, { id: 'state', label: 'Статус', type: 'String', minWidth: 96 }, ...clsCol]
792
- : [nameCol, ...orderedCols, ...clsCol];
793
- },
794
- /** Строки таблицы: названия вместо id ссылок, число строк табличной части, выжимка структуры, статус текстом; id сохраняется. */
795
- get tableRows() {
796
- const cols = this.columns || [];
797
- return (this.rows || []).map(r => {
798
- const out = { ...r };
799
- if (this.showClassCol) {
800
- const grp = this.groupLabelOf(r.cid);
801
- out.cls = grp;
802
- out.group = grp;
803
- const grpPath = (r.cid && this.classes?.[r.cid]?.path) || r.cid || '';
804
- if (grpPath)
805
- Object.defineProperty(out, '_groupPath', { value: grpPath, enumerable: false, configurable: true });
806
- }
807
- let links = null;
808
- for (const c of cols) {
809
- const v = r[c.id];
810
- if (c.type === 'Link' && v) {
811
- out[c.id] = this.names?.[v] || v;
812
- (links ??= {})[c.id] = { id: v, target: c.catalog || '' };
813
- }
814
- else if (Array.isArray(v))
815
- out[c.id] = v.length ? `${v.length} стр.` : '';
816
- else if (c.type === 'Struct' && v && typeof v === 'object')
817
- out[c.id] = Object.values(v).filter(x => x !== undefined && x !== null && typeof x !== 'object' && String(x).trim() !== '').join(' ');
818
- }
819
- if (links)
820
- Object.defineProperty(out, '_links', { value: links, enumerable: false, configurable: true });
821
- if (this.isOperation)
822
- out.state = STATUS[r.status] || r.status || '';
823
- return out;
824
- });
825
- },
826
- /** Поля редактора: у операции первым — дата. */
827
- fieldList() {
828
- return (this.activeSchema?.FIELDS || this.schema?.FIELDS || []).filter(f => f?.id);
829
- },
830
- /** Значение для снимка: пустые null/undefined/'' эквивалентны. */
831
- _value(v) {
832
- if (v === undefined || v === null || v === '')
833
- return '';
834
- if (Array.isArray(v))
835
- return v.map(x => this._value(x));
836
- if (typeof v === 'object') {
837
- const out = {};
838
- for (const k of Object.keys(v).sort())
839
- out[k] = this._value(v[k]);
840
- return out;
841
- }
842
- return v;
843
- },
844
- /** Отпечаток только полей редактора: служебные id/status/version в dirty не входят. */
845
- fingerprint(data) {
846
- const out = {};
847
- for (const f of this.fieldList())
848
- out[f.id] = this._value(data?.[f.id]);
849
- return JSON.stringify(out);
850
- },
851
- /** Запомнить текущее состояние как чистое (открытие, сохранение, проведение). */
852
- snapshot() {
853
- this._snapshot = this.fingerprint(this.editing);
854
- },
855
- /** Есть ли несохранённые изменения относительно снимка. */
856
- isDirty() {
857
- return !!this.editing && this.fingerprint(this.editing) !== this._snapshot;
858
- },
859
- /** Собрать описание схемы для формы и колонок из ответа db_schema.schema. */
860
- _buildSchema(s) {
861
- const fields = (Array.isArray(s?.fields) ? s.fields : []).filter(f => f?.id && f.id !== 'time').map(formField);
862
- let editorFields = fields;
863
- if (s?.family === 'operation') {
864
- const numId = s?.numerator?.field || fields.find(f => NUM_FIELD_IDS.has(f.id))?.id || '';
865
- const numField = numId ? fields.find(f => f.id === numId) : null;
866
- const scalars = fields.filter(f => f !== numField && f.id !== 'comment' && f.type !== 'Table');
867
- const comments = fields.filter(f => f !== numField && f.id === 'comment');
868
- const tables = fields.filter(f => f !== numField && f.type === 'Table');
869
- editorFields = [
870
- DATE_FIELD,
871
- ...(numField ? [numField] : []),
872
- ...scalars,
873
- ...comments,
874
- ...tables,
875
- ];
876
- }
877
- return {
878
- cid: s?.cid || '',
879
- path: s?.path || '',
880
- title: s?.label || '',
881
- family: s?.family || '',
882
- type: s?.type || '',
883
- leaf: !!s?.leaf,
884
- autoRegister: !!s?.autoRegister,
885
- numerator: s?.numerator || null,
886
- POSTINGS: Array.isArray(s?.postings) ? s.postings : [],
887
- LAYOUT: s?.layout || null,
888
- FIELDS: editorFields,
889
- columns: fields,
890
- };
891
- },
892
- /** Схема класса с учётом наследования: поля для колонок и редактора, правила проводок, семейство, поддерево. */
893
- async loadSchema() {
894
- const res = await this.$item?.fetch('db_schema');
895
- const built = this._buildSchema(res?.schema);
896
- this.columns = built.columns;
897
- this.leaves = Array.isArray(res?.leaves) ? res.leaves : [];
898
- this.classes = res?.classes && typeof res.classes === 'object' ? res.classes : {};
899
- this._hasServerDays = Array.isArray(res?.days);
900
- this.packetsDays = this._hasServerDays ? res.days : [];
901
- this.schema = {
902
- cid: built.cid,
903
- path: built.path,
904
- title: built.title,
905
- family: built.family,
906
- type: built.type,
907
- leaf: built.leaf,
908
- autoRegister: built.autoRegister,
909
- numerator: built.numerator,
910
- POSTINGS: built.POSTINGS,
911
- LAYOUT: built.LAYOUT,
912
- FIELDS: built.FIELDS,
913
- };
914
- },
915
- /** Элемент целевого класса-листа (при работе из группы); на самом листе или без WORK.get_item — $item. */
916
- async targetItem(cid = this.leafCid) {
917
- if (!cid || this.schema?.leaf || typeof WORK?.get_item !== 'function')
918
- return this.$item;
919
- const path = this.classes?.[cid]?.path || this.leaves?.find(l => l.cid === cid)?.path;
920
- if (!path)
921
- return this.$item;
922
- try {
923
- return (await WORK.get_item(path)) || this.$item;
924
- }
925
- catch {
926
- return this.$item;
927
- }
928
- },
929
- /** Загрузить схему выбранного листа в группе классов. */
930
- async loadLeafSchema(cid) {
931
- this.leafCid = cid || '';
932
- this.leafSchema = null;
933
- if (!cid || this.schema?.leaf)
934
- return;
935
- try {
936
- const target = await this.targetItem(cid);
937
- if (!target || target === this.$item)
938
- return;
939
- const res = await target.fetch('db_schema');
940
- if (res?.schema) {
941
- const b = this._buildSchema(res.schema);
942
- this.leafSchema = {
943
- title: b.title,
944
- family: b.family,
945
- type: b.type,
946
- leaf: b.leaf,
947
- autoRegister: b.autoRegister,
948
- numerator: b.numerator,
949
- POSTINGS: b.POSTINGS,
950
- FIELDS: b.FIELDS,
951
- };
952
- }
953
- }
954
- catch {
955
- this.leafSchema = null;
956
- }
957
- },
958
- _autoGeneratedNum: '',
959
- _autoNumPeriodKey: '',
960
- _numeratorFieldId() {
961
- const s = this.activeSchema;
962
- if (s?.numerator?.enabled === false)
963
- return '';
964
- if (s?.numerator?.field)
965
- return s.numerator.field;
966
- const found = this.fieldList().find(f => NUM_FIELD_IDS.has(f.id));
967
- return found ? found.id : '';
968
- },
969
- _periodKeyForNumerator(timeStr) {
970
- const raw = String(timeStr || _today());
971
- const reset = this.activeSchema?.numerator?.reset || 'year';
972
- if (reset === 'never')
973
- return 'all';
974
- if (reset === 'day')
975
- return raw.slice(0, 10);
976
- if (reset === 'month')
977
- return raw.slice(0, 7);
978
- if (reset === 'quarter') {
979
- const y = raw.slice(0, 4);
980
- const m = parseInt(raw.slice(5, 7), 10) || 1;
981
- return `${y}-Q${Math.floor((m - 1) / 3) + 1}`;
982
- }
983
- return raw.slice(0, 4);
984
- },
985
- async _assignAutoNumber(force = false) {
986
- if (!this.isOperation || !this.editing || this.editing.id)
987
- return;
988
- const numField = this._numeratorFieldId();
989
- if (!numField)
990
- return;
991
- const curVal = String(this.editing[numField] ?? '').trim();
992
- if (!force && curVal && curVal !== this._autoGeneratedNum)
993
- return;
994
- try {
995
- const target = await this.targetItem();
996
- if (!target || typeof target.fetch !== 'function')
997
- return;
998
- const res = await target.fetch('db_next_number', { time: this.editing.time || _today() });
999
- if (res?.number && this.editing && !this.editing.id) {
1000
- const latestVal = String(this.editing[numField] ?? '').trim();
1001
- if (force || !latestVal || latestVal === this._autoGeneratedNum) {
1002
- this.editing[numField] = String(res.number);
1003
- this._autoGeneratedNum = String(res.number);
1004
- this._autoNumPeriodKey = this._periodKeyForNumerator(this.editing.time);
1005
- if (this.isObjectView) {
1006
- this._dirtyTick = (this._dirtyTick || 0) + 1;
1007
- this._findFormHost()?.updateActiveTabLabel?.(this.documentTitle);
1008
- this._notifyForm();
1009
- }
1010
- }
1011
- }
1012
- }
1013
- catch { /* ignore if server doesn't return db_next_number in mock */ }
1014
- },
1015
- /** Сменить лист при создании объекта в группе классов. */
1016
- async selectLeaf(cid) {
1017
- await this.loadLeafSchema(cid);
1018
- await this._assignAutoNumber(true);
1019
- this.snapshot();
1020
- if (this.isOperation)
1021
- this.schedulePreview();
1022
- },
1023
- _applyNavFields(nav) {
1024
- if (!nav || typeof nav !== 'object')
1025
- return;
1026
- if (nav.packetsKey)
1027
- this.packetsKey = String(nav.packetsKey);
1028
- },
1029
- async syncFormPeriod(fp) {
1030
- if (!this.isOperation || !fp || typeof fp !== 'object' || !fp.packetsKey)
1031
- return;
1032
- if (this.packetsKey === fp.packetsKey)
1033
- return;
1034
- this.packetsKey = String(fp.packetsKey);
1035
- if (fp.packetsKey === '*') {
1036
- this.period = this.packetsStart && this.packetsEnd ? { start: this.packetsStart, end: this.packetsEnd } : null;
1037
- await this.reload();
1038
- }
1039
- else if (fp.from && fp.to) {
1040
- this.period = { start: String(fp.from), end: String(fp.to) };
1041
- await this.reload();
1042
- }
1043
- },
1044
- async attached() {
1045
- if (this._attachedDone && !this._initialNav && !this._pendingNavId) {
1046
- this.mountToolbarSlots();
1047
- return;
1048
- }
1049
- const initNav = this._initialNav;
1050
- this._initialNav = null;
1051
- if (initNav?.id)
1052
- this._pendingNavId = String(initNav.id);
1053
- const formPeriodKey = initNav?.packetsKey || this._findFormHost()?.formPeriod?.packetsKey || '';
1054
- if (formPeriodKey) {
1055
- this.packetsKey = String(formPeriodKey);
1056
- }
1057
- else {
1058
- const savedLocalKey = typeof this.loadFromLocalStorage === 'function' ? this.loadFromLocalStorage('packetsKey') : undefined;
1059
- if (typeof savedLocalKey === 'string' && savedLocalKey)
1060
- this.packetsKey = savedLocalKey;
1061
- }
1062
- this.mountToolbarSlots();
1063
- try {
1064
- await Promise.all([this.loadSchema(), this.loadScope()]);
1065
- }
1066
- catch (e) {
1067
- this.error = String(e?.message || e);
1068
- return;
1069
- }
1070
- // у операций строки грузит пакет (событие выбора периода), справочник — весь список сразу
1071
- if (this.isOperation)
1072
- await this.loadRange();
1073
- else
1074
- await this.reload();
1075
- if (this._pendingNavId) {
1076
- const id = this._pendingNavId;
1077
- this._pendingNavId = '';
1078
- await this.openEditor({ id });
1079
- }
1080
- this._attachedDone = true;
1081
- },
1082
- /** Переход из отчёта (журнал, карточка счёта, состав, траектория) сразу к объекту по id. */
1083
- async applyNav(nav = {}) {
1084
- if (!nav?.id)
1085
- return;
1086
- if (!this.schema) {
1087
- this._pendingNavId = String(nav.id);
1088
- return;
1089
- }
1090
- await this.openEditor({ id: String(nav.id) });
1091
- },
1092
- /** Видимые подразделения и места записи; без ответа — форма работает без выбора (сервер решит сам). */
1093
- async loadScope() {
1094
- try {
1095
- const s = await this.$item?.fetch('db_scope');
1096
- this.units = Array.isArray(s?.units) && !s.all ? s.units : [];
1097
- this.contexts = Array.isArray(s?.contexts) ? s.contexts : [];
1098
- }
1099
- catch {
1100
- this.units = [];
1101
- this.contexts = [];
1102
- }
1103
- },
1104
- /** Границы полосы: по реально существующим дням операций (db_schema.days) либо от первой до последней операции. */
1105
- async loadRange() {
1106
- if (!this.$item)
1107
- return;
1108
- if (Array.isArray(this.packetsDays) && this.packetsDays.length > 0) {
1109
- const firstDay = this.packetsDays[0];
1110
- const lastDay = this.packetsDays[this.packetsDays.length - 1];
1111
- const today = _today();
1112
- if (this.packetsKey === 'now' && !this.packetsDays.includes(today))
1113
- this.packetsKey = '*';
1114
- this.packetsStart = firstDay;
1115
- this.packetsEnd = lastDay;
1116
- return;
1117
- }
1118
- if (this._hasServerDays) {
1119
- const today = _today();
1120
- this.packetsStart = today;
1121
- this.packetsEnd = today;
1122
- return;
1123
- }
1124
- const edge = order => this.$item.fetch('db_query', { order, limit: 1 })
1125
- .then(r => r?.items?.[0]?.time).catch(() => undefined);
1126
- const [first, last] = await Promise.all([edge('time'), edge('-time')]);
1127
- const today = _today();
1128
- const lastDay = last ? _day(new Date(last)) : today;
1129
- this.packetsEnd = lastDay > today ? lastDay : today;
1130
- this.packetsStart = first ? _day(new Date(first)) : this.packetsEnd;
1131
- },
1132
- /**
1133
- * Смена периода в пакете — единственный повод грузить строки операций заново.
1134
- * Пакет шлёт selection-changed дважды: авто-событие пропа `selection`
1135
- * (detail — массив выбранных единиц) и явное при смене выбора (detail — объект).
1136
- * Учитываем только явное, иначе первая выборка ушла бы без границ.
1137
- */
1138
- async onPackets(e) {
1139
- const d = e?.detail?.value ?? e?.detail ?? {};
1140
- if (Array.isArray(d)) return;
1141
- this.period = d.period || null;
1142
- const nextKey = d.value || (d.selected?.name === '*' ? '*' : (d.selected?.mask || this.packetsKey));
1143
- if (nextKey)
1144
- this.packetsKey = nextKey;
1145
- if (this.isOperation) {
1146
- this._findFormHost()?.setFormPeriod?.({
1147
- packetsKey: this.packetsKey || '*',
1148
- from: this.period?.start || '',
1149
- to: this.period?.end || '',
1150
- });
1151
- }
1152
- await this.reload();
1153
- },
1154
- /** Объект ядра → строка формы: поля тела, id, статус, версия; у операции — день даты; у группы — cid. */
1155
- rowOf(o) {
1156
- const b = o?.body || {};
1157
- const row = { ...b, id: o.id, status: o.status, version: o.version };
1158
- if (o?.cid)
1159
- row.cid = o.cid;
1160
- if (this.isOperation) {
1161
- row.time = o.time ? _day(new Date(o.time)) : '';
1162
- if (row.sum === undefined) {
1163
- const fallbackSum = b.total ?? b.credited ?? b.saldo_26;
1164
- if (fallbackSum !== undefined)
1165
- row.sum = fallbackSum;
1166
- }
1167
- if (!row.comment)
1168
- row.comment = b.descript || b.base || b.reason || b.theme || b.subject || b.content || '';
1169
- }
1170
- if (!row.name) {
1171
- const clsTitle = (o?.cid && this.classes?.[o.cid]?.label) || this.schema?.title || '';
1172
- const numPart = b.num ? ` № ${b.num}` : '';
1173
- const datePart = row.time ? ` от ${row.time}` : '';
1174
- row.name = (clsTitle || b.num) ? `${clsTitle}${numPart}${datePart}`.trim() : (o?.id || '');
1175
- }
1176
- return row;
1177
- },
1178
- _reloadSeq: 0,
1179
- async reload() {
1180
- const seq = ++this._reloadSeq;
1181
- this.rows = [];
1182
- this.names = {};
1183
- this.error = '';
1184
- if (!this.$item)
1185
- return;
1186
- try {
1187
- const params = { limit: this.pageSize || 200, order: '-time' };
1188
- if (this.page > 1)
1189
- params.offset = (this.page - 1) * (this.pageSize || 200);
1190
- if (this.isOperation && this.period) {
1191
- params.from = this.period.start;
1192
- params.to = this.period.end;
1193
- }
1194
- if (this.unitFilter)
1195
- params.unit = this.unitFilter;
1196
- if (this.searchQuery)
1197
- params.search = this.searchQuery;
1198
- if (this.statusFilter)
1199
- params.status = this.statusFilter;
1200
- const where = {};
1201
- for (const [k, v] of Object.entries(this.fieldFilters || {})) {
1202
- if (v !== '' && v !== undefined && v !== null) {
1203
- const col = (this.columns || []).find(c => c.id === k);
1204
- where[k] = col?.type === 'Boolean' ? (v === '1' || v === 'true' ? 1 : 0) : v;
1205
- }
1206
- }
1207
- if (Object.keys(where).length)
1208
- params.where = JSON.stringify(where);
1209
- const res = await this.$item.fetch('db_query', params);
1210
- if (seq !== this._reloadSeq)
1211
- return;
1212
- this.names = res?.names || {};
1213
- this.rows = (Array.isArray(res?.items) ? res.items : []).map(o => this.rowOf(o));
1214
- this.total = Number(res?.total) || this.rows.length;
1215
- // строки пересозданы: выделение возвращаем на открытый объект по id
1216
- this.selectedRows = [];
1217
- this.$?.('#objectsTable')?.clearSelection?.();
1218
- this.focusedRow = this.tableRows.find(r => r.id === (this.editing?.id || this.focusedRow?.id)) ?? null;
1219
- this.focusedItem = this.focusedRow?.id ? this.focusedRow : null;
1220
- this._notifyForm();
1221
- }
1222
- catch (e) {
1223
- if (seq !== this._reloadSeq)
1224
- return;
1225
- this.error = String(e?.message || e);
1226
- this._notifyForm();
1227
- }
1228
- },
1229
- async select(row) {
1230
- if (!row?.id)
1231
- return;
1232
- this.error = '';
1233
- try {
1234
- const found = await this.$item.fetch('db_read', { id: row.id });
1235
- if (found?.names && typeof found.names === 'object')
1236
- this.names = { ...(this.names || {}), ...found.names };
1237
- await this.loadLeafSchema(found?.cid || row.cid || '');
1238
- this.editing = this.rowOf(found || { id: row.id });
1239
- await this.loadEntries();
1240
- await this.loadPrints();
1241
- await this.loadTrajectory();
1242
- }
1243
- catch (e) {
1244
- this.error = String(e?.message || e);
1245
- }
1246
- },
1247
- /** Состояние (остатки по счетам) и траектория движений объекта справочника (db_trajectory). */
1248
- async loadTrajectory() {
1249
- this.objectBalances = [];
1250
- this.trajectory = [];
1251
- this.trajectoryNames = { objects: {}, classes: {}, paths: {} };
1252
- if (this.isOperation || !this.editing?.id || !this.$item)
1253
- return;
1254
- try {
1255
- const res = await this.$item.fetch('db_trajectory', { id: this.editing.id, limit: 50 });
1256
- if (!res)
1257
- return;
1258
- const names = { objects: {}, classes: {}, paths: {}, ...(res.names || {}) };
1259
- this.trajectoryNames = names;
1260
- const accText = cid => {
1261
- const code = String(cid || '').split('/').pop().replace(/^acc\./, '');
1262
- const label = names.classes?.[cid];
1263
- return label && label !== code && !label.startsWith(code + ' ') ? `${code} ${label}` : (label || code);
1264
- };
1265
- this.objectBalances = (Array.isArray(res.closing) ? res.closing : []).map(b => ({
1266
- account: b.account,
1267
- slot: b.slot || '',
1268
- label: accText(b.account),
1269
- balance: saldo(b.debit, b.credit),
1270
- qty: b.qty ? String(b.qty) : '',
1271
- }));
1272
- this.trajectory = (Array.isArray(res.items) ? res.items : []).map(i => {
1273
- const title = names.objects?.[i.op_id];
1274
- const op = (title && title !== i.op_id ? title : '') || names.classes?.[i.op_cid] || i.op_id || '';
1275
- return {
1276
- date: i.time ? new Date(i.time).toLocaleDateString() : '',
1277
- op,
1278
- op_id: i.op_id || '',
1279
- op_cid: i.op_cid || '',
1280
- account: accText(i.account),
1281
- account_cid: i.account || '',
1282
- debit: money(i.debit),
1283
- credit: money(i.credit),
1284
- qty: i.qty ? String(i.qty) : '',
1285
- balance: saldo(i.balance > 0 ? i.balance : 0, i.balance < 0 ? -i.balance : 0),
1286
- storno: !!i.storno,
1287
- };
1288
- });
1289
- }
1290
- catch {
1291
- this.objectBalances = [];
1292
- this.trajectory = [];
1293
- }
1294
- },
1295
- /** Печатные формы сохранённой операции; без ответа — кнопок печати нет. */
1296
- async loadPrints() {
1297
- this.printForms = [];
1298
- if (!this.isOperation || !this.editing?.id)
1299
- return;
1300
- try {
1301
- const target = await this.targetItem();
1302
- const list = await target.fetch('db_print_list', { id: this.editing.id });
1303
- this.printForms = Array.isArray(list) ? list : [];
1304
- }
1305
- catch {
1306
- this.printForms = [];
1307
- }
1308
- },
1309
- /** Открыть печатную форму в новом окне: окно создаётся сразу по клику, иначе браузер заблокирует его. */
1310
- async printForm(name) {
1311
- const win = window.open('', '_blank');
1312
- if (!win)
1313
- return this.error = 'Браузер заблокировал окно печати';
1314
- try {
1315
- const target = await this.targetItem();
1316
- const res = await target.fetch('db_print', { id: this.editing.id, name });
1317
- win.document.open();
1318
- win.document.write(res?.html || '');
1319
- win.document.close();
1320
- win.focus();
1321
- }
1322
- catch (e) {
1323
- win.close();
1324
- this.error = String(e?.message || e);
1325
- }
1326
- },
1327
- /** Проводки операции: проведённой — действующие, черновика — предпросмотр (ошибки правил — текстом). */
1328
- async loadEntries() {
1329
- this.entries = [];
1330
- this.entryNames = { objects: {}, classes: {} };
1331
- const op = this.editing;
1332
- if (!this.hasPostings || !op?.id || op.status === 'cancelled')
1333
- return;
1334
- try {
1335
- const target = await this.targetItem();
1336
- if (op.status === 'registered')
1337
- this.entries = await target.fetch('db_entries', { id: op.id }) || [];
1338
- else {
1339
- const p = await target.fetch('db_preview', { id: op.id });
1340
- this.entryNames = p?.names || { objects: {}, classes: {} };
1341
- this.entries = [...(p?.entries || []), ...(p?.errors || []).map(e => ({ error: (e.field ? e.field + ': ' : '') + e.message }))];
1342
- }
1343
- }
1344
- catch (e) {
1345
- this.entries = [{ error: String(e?.message || e) }];
1346
- }
1347
- },
1348
- /** Предпросмотр проводок по несохранённому телу операции при вводе в форме. */
1349
- async previewDraft() {
1350
- const op = this.editing;
1351
- if (!this.isOperation || !this.hasPostings || !op || op.status === 'registered')
1352
- return;
1353
- try {
1354
- const target = await this.targetItem();
1355
- const params = op.time ? { time: op.time } : {};
1356
- const p = await target.fetch('db_preview', params, this.postData());
1357
- this.entryNames = p?.names || { objects: {}, classes: {} };
1358
- this.entries = [...(p?.entries || []), ...(p?.errors || []).map(e => ({ error: (e.field ? e.field + ': ' : '') + e.message }))];
1359
- if (this.isObjectView) {
1360
- this._dirtyTick = (this._dirtyTick || 0) + 1;
1361
- this._findFormHost()?.updateActiveTabLabel?.(this.documentTitle);
1362
- }
1363
- }
1364
- catch (e) {
1365
- this.entries = [{ error: String(e?.message || e) }];
1366
- }
1367
- },
1368
- schedulePreview() {
1369
- if (!this.isOperation || !this.hasPostings)
1370
- return;
1371
- clearTimeout(this._previewTimer);
1372
- this._previewTimer = setTimeout(() => {
1373
- if (this.editing && (!this.editing.id || this.status === 'draft' || this.status === 'cancelled'))
1374
- this.previewDraft();
1375
- }, 250);
1376
- },
1377
- /** Строка проводки в окне: «Дт 62 — Кт 90: 500», с названиями счетов и аналитик (если есть) и количеством. */
1378
- entryText(e) {
1379
- if (e?.error)
1380
- return e.error;
1381
- const side = (cid, an) => {
1382
- const code = String(cid || '').split('/').pop().replace(/^acc\./, '');
1383
- const label = this.entryNames?.classes?.[cid];
1384
- const base = label && label !== code && !label.startsWith(code + ' ') ? `${code} ${label}` : (label || code);
1385
- const objs = Object.values(an || {}).map(id => this.entryNames?.objects?.[id] || this.names?.[id] || id).filter(Boolean).join(', ');
1386
- return objs ? `${base} (${objs})` : base;
1387
- };
1388
- const qty = e.qty ? ` (${e.doc_qty ?? e.qty}${e.doc_unit ? ' ' + e.doc_unit : ''})` : '';
1389
- return `Дт ${side(e.debit, e.debit_analytics)} — Кт ${side(e.credit, e.credit_analytics)}: ${Number(e.amount || 0).toLocaleString('ru-RU', { minimumFractionDigits: 2 })}${qty}`;
1390
- },
1391
- /** Загрузить объект и открыть вьюху редактора (внутри work-form — на вкладке form/object, автономно — модально). */
1392
- async openEditor(row) {
1393
- if (!row?.id || this.editorOpen)
1394
- return;
1395
- const formHost = this._findFormHost();
1396
- if (formHost && typeof formHost.openInForm === 'function') {
1397
- const target = await this.targetItem(row.cid || '');
1398
- await formHost.openInForm(target || this.$item, {
1399
- view: 'object',
1400
- id: row.id,
1401
- leafCid: row.cid || '',
1402
- label: row.name || row.title || row.id,
1403
- });
1404
- return;
1405
- }
1406
- this.editorOpen = true;
1407
- this.editing = null;
1408
- try {
1409
- await this.select(row);
1410
- if (this.editing)
1411
- await this.showEditor();
1412
- }
1413
- finally {
1414
- this.focusedRow = null;
1415
- this.editorOpen = false;
1416
- }
1417
- },
1418
- /**
1419
- * Построить дерево подклассов промежуточного класса для диалога выбора конечной точки хранения.
1420
- * В промежуточных классах объекты храниться не могут — они отображаются как серые узлы группировки,
1421
- * а выбрать можно только конечный класс-лист (`leaf: true`).
1422
- */
1423
- buildClassTree() {
1424
- const fn = globalThis.__workClassPicker?.buildClassTree || globalThis.WORK?.buildClassTree;
1425
- if (typeof fn === 'function') {
1426
- return fn({
1427
- classes: this.classes,
1428
- leaves: this.leaves,
1429
- rows: this.rows,
1430
- rootCid: this.schema?.cid || '',
1431
- rootPath: this.schema?.path || this.$item?.path || this.$item?.short || '',
1432
- defaultIcon: this.isOperation ? 'carbon:task-complete' : 'carbon:catalog',
1433
- defaultType: this.schema?.type || '$catalog',
1434
- });
1435
- }
1436
- return [];
1437
- },
1438
- /** Открыть модальное окно выбора конечного класса хранения перед созданием объекта из промежуточного класса. */
1439
- async pickTargetLeafClass() {
1440
- const tree = this.buildClassTree();
1441
- if (!tree.length)
1442
- return '';
1443
- const classTitle = this.schema?.title || this.$item?.DATA?.label || this.$item?.label || this.$item?.id || '';
1444
- const dialogTitle = `Выберите класс для создания объекта '${classTitle}'`;
1445
- const pickFn = globalThis.__workClassPicker?.pickClassFromTree || globalThis.WORK?.pickClassFromTree;
1446
- if (typeof pickFn === 'function')
1447
- return pickFn(tree, { title: dialogTitle });
1448
- const picker = ODA.createComponent('item-class-picker', {
1449
- treeNodes: tree,
1450
- selectedCid: '',
1451
- });
1452
- try {
1453
- await WORK.showModal(picker, {
1454
- TITLE: { label: dialogTitle },
1455
- allowClose: true,
1456
- width: Math.min(580, (window.innerWidth || 640) - 32),
1457
- });
1458
- return picker.confirmedCid || '';
1459
- }
1460
- catch {
1461
- return '';
1462
- }
1463
- },
1464
- /** Новый объект — если вызван на промежуточном классе, сначала предлагаем выбрать конечный класс-лист хранения. */
1465
- async create() {
1466
- if (this.editorOpen)
1467
- return;
1468
- if (!this.schema)
1469
- await this.loadSchema().catch(() => {});
1470
- let chosenCid = '';
1471
- if (!this.schema?.leaf) {
1472
- if (!this.leaves?.length)
1473
- return;
1474
- if (typeof WORK?.showModal === 'function' && typeof document !== 'undefined') {
1475
- chosenCid = await this.pickTargetLeafClass();
1476
- if (!chosenCid)
1477
- return;
1478
- }
1479
- else {
1480
- chosenCid = this.leafCid || this.leaves[0].cid;
1481
- }
1482
- }
1483
- const formHost = this._findFormHost();
1484
- if (formHost && typeof formHost.openInForm === 'function') {
1485
- const target = chosenCid ? await this.targetItem(chosenCid) : this.$item;
1486
- const leafLabel = chosenCid ? (this.classes?.[chosenCid]?.label || this.leaves?.find(l => l.cid === chosenCid)?.label || '') : '';
1487
- const title = leafLabel || this.schema?.title || 'Объект';
1488
- const fmtNew = globalThis.__workClassPicker?.formatNewObjectLabel || globalThis.WORK?.formatNewObjectLabel;
1489
- const tabLabel = typeof fmtNew === 'function' ? fmtNew(title) : `${title} · новый объект`;
1490
- if (target && chosenCid && typeof formHost.ensureClassTab === 'function') {
1491
- await formHost.ensureClassTab(target);
1492
- }
1493
- await formHost.openInForm(target || this.$item, {
1494
- view: 'object',
1495
- create: true,
1496
- leafCid: chosenCid || '',
1497
- label: tabLabel,
1498
- });
1499
- return;
1500
- }
1501
- if (chosenCid) {
1502
- this.editorOpen = true;
1503
- await this.loadLeafSchema(chosenCid);
1504
- }
1505
- else {
1506
- this.editorOpen = true;
1507
- this.leafCid = '';
1508
- this.leafSchema = null;
1509
- }
1510
- this.editing = this.isOperation ? { time: _today() } : {};
1511
- await this._assignAutoNumber(true);
1512
- this.entries = [];
1513
- this.entryNames = { objects: {}, classes: {} };
1514
- this.objectBalances = [];
1515
- this.trajectory = [];
1516
- this.printForms = [];
1517
- this.clearError();
1518
- try {
1519
- await this.showEditor();
1520
- }
1521
- finally {
1522
- this.focusedRow = null;
1523
- this.editorOpen = false;
1524
- }
1525
- },
1526
- /** Клонирование выбранного объекта: открывает окно создания нового объекта с заполненными полями оригинала. */
1527
- async copyRow(row = this.focusedRow) {
1528
- if (!row?.id || this.editorOpen || !this.canCreate)
1529
- return;
1530
- const formHost = this._findFormHost();
1531
- if (formHost && typeof formHost.openInForm === 'function') {
1532
- const target = await this.targetItem(row.cid || '');
1533
- await formHost.openInForm(target || this.$item, {
1534
- view: 'object',
1535
- copyFrom: row.id,
1536
- leafCid: row.cid || '',
1537
- label: `${row.name || 'Объект'} (копия)`,
1538
- });
1539
- return;
1540
- }
1541
- this.editorOpen = true;
1542
- this.clearError();
1543
- try {
1544
- const found = await this.$item.fetch('db_read', { id: row.id });
1545
- if (found?.names && typeof found.names === 'object')
1546
- this.names = { ...(this.names || {}), ...found.names };
1547
- await this.loadLeafSchema(found?.cid || row.cid || '');
1548
- const baseBody = { ...(found?.body || {}) };
1549
- delete baseBody.id;
1550
- delete baseBody.version;
1551
- delete baseBody.status;
1552
- const nf = this._numeratorFieldId();
1553
- if (nf)
1554
- delete baseBody[nf];
1555
- this.editing = this.isOperation ? { ...baseBody, time: _today() } : baseBody;
1556
- await this._assignAutoNumber(true);
1557
- this.entries = [];
1558
- this.entryNames = { objects: {}, classes: {} };
1559
- this.objectBalances = [];
1560
- this.trajectory = [];
1561
- this.printForms = [];
1562
- await this.showEditor();
1563
- }
1564
- catch (e) {
1565
- this.setError(e);
1566
- }
1567
- finally {
1568
- this.editorOpen = false;
1569
- }
1570
- },
1571
- /** Удаление выбранного объекта или списка объектов (при множественном выборе с allowList) из тулбара. */
1572
- async deleteRow(target = this.activeSelection) {
1573
- const list = (Array.isArray(target) ? target : (target?.id ? [target] : this.activeSelection))
1574
- .filter(r => this.canDeleteRow(r));
1575
- if (!list.length || this.busy)
1576
- return;
1577
- this.busy = true;
1578
- this.clearError();
1579
- try {
1580
- for (const row of list) {
1581
- const item = await this.targetItem(row.cid || '');
1582
- await item.fetch('db_delete', { id: row.id });
1583
- }
1584
- this.selectedRows = [];
1585
- this.focusedRow = null;
1586
- this.focusedItem = null;
1587
- this.$?.('#objectsTable')?.clearSelection?.();
1588
- await this.reload();
1589
- }
1590
- catch (e) {
1591
- this.setError(e);
1592
- }
1593
- finally {
1594
- this.busy = false;
1595
- }
1596
- },
1597
- /** Только поля схемы (без даты операции — она уходит параметром); пустые строки таблиц отбрасываются. */
1598
- postData() {
1599
- // editing — та же data, в которую пишет форма: снимок form.result может отставать
1600
- const fields = this.fieldList().filter(f => f.id !== DATE_FIELD.id || !this.isOperation);
1601
- const byId = new Map(fields.map(f => [f.id, f]));
1602
- const out = {};
1603
- for (const [k, v] of Object.entries(this.editing || {})) {
1604
- const f = byId.get(k);
1605
- if (!f)
1606
- continue;
1607
- if (f.type === 'Table' && Array.isArray(v))
1608
- out[k] = v.filter(isNonEmptyRow);
1609
- else if (f.type === 'File' && v && typeof v === 'object')
1610
- out[k] = v.path || v.name || String(v);
1611
- else
1612
- out[k] = v;
1613
- }
1614
- return out;
1615
- },
1616
- /** Загрузить выбранные в контролах File файлы на сервер перед сохранением объекта. */
1617
- async uploadFiles(target) {
1618
- if (!this.editing || typeof this.editing !== 'object')
1619
- return;
1620
- for (const f of this.fieldList()) {
1621
- if (f.type !== 'File')
1622
- continue;
1623
- const val = this.editing[f.id];
1624
- if (!val || typeof val === 'string')
1625
- continue;
1626
- const fileObj = Array.isArray(val) ? val[0] : val;
1627
- if (!fileObj)
1628
- continue;
1629
- if (typeof target?.save_file === 'function' && typeof File !== 'undefined' && fileObj instanceof File) {
1630
- const saved = await target.save_file(fileObj);
1631
- this.editing[f.id] = saved?.path || saved?.id || fileObj.name;
1632
- }
1633
- else {
1634
- this.editing[f.id] = fileObj.path || fileObj.name || String(fileObj);
1635
- }
1636
- }
1637
- },
1638
- /** Параметры записи: id и версия (защита от чужой правки), дата операции; у нового — место записи. */
1639
- writeParams(extra = {}) {
1640
- const p = { ...extra };
1641
- if (this.editing?.id) {
1642
- p.id = this.editing.id;
1643
- if (this.editing.version)
1644
- p.version = this.editing.version;
1645
- }
1646
- else if (this.showContext && this.context) {
1647
- p.unit = this.context.unit;
1648
- if (this.context.place)
1649
- p.place = this.context.place;
1650
- }
1651
- if (this.isOperation && this.editing?.time)
1652
- p.time = this.editing.time;
1653
- return p;
1654
- },
1655
- /** Ответ записи: id, статус и версия — для следующего действия в том же окне. */
1656
- accept(res) {
1657
- if (res?.id && this.editing)
1658
- Object.assign(this.editing, { id: res.id, status: res.status, version: res.version });
1659
- },
1660
- hasPendingUploads() {
1661
- if (!this.editing || typeof this.editing !== 'object' || typeof File === 'undefined')
1662
- return false;
1663
- for (const f of this.fieldList()) {
1664
- if (f.type !== 'File')
1665
- continue;
1666
- const val = this.editing[f.id];
1667
- const fileObj = Array.isArray(val) ? val[0] : val;
1668
- if (fileObj instanceof File)
1669
- return true;
1670
- }
1671
- return false;
1672
- },
1673
- async save() {
1674
- if (this.busy || !this.canSave)
1675
- return false;
1676
- this.busy = true;
1677
- this.clearError();
1678
- try {
1679
- if (this.hasPendingUploads()) {
1680
- const t = await this.targetItem();
1681
- await this.uploadFiles(t);
1682
- }
1683
- const data = this.postData();
1684
- // снимок отправленного, а не текущего: ввод во время запроса остаётся dirty
1685
- const saved = this.fingerprint({ ...data, time: this.editing.time });
1686
- const target = await this.targetItem();
1687
- let res;
1688
- if (!this.editing.id)
1689
- res = await target.fetch('db_create', this.writeParams(), data);
1690
- else if (this.status === 'registered')
1691
- res = await target.fetch('db_correct', this.writeParams({ replace: true }), data);
1692
- else
1693
- res = await target.fetch('db_update', this.writeParams({ replace: true }), data);
1694
- this.accept(res);
1695
- this._snapshot = saved;
1696
- // внутри окна список обновит его закрытие; внешняя кнопка — сразу
1697
- if (!this.editorOpen && !this.isObjectView)
1698
- await this.reload();
1699
- return true;
1700
- }
1701
- catch (e) {
1702
- this.setError(e);
1703
- return false;
1704
- }
1705
- finally {
1706
- this.busy = false;
1707
- }
1708
- },
1709
- /** Подтверждение действия; отмена диалога — false. */
1710
- async confirm(text, title, ok) {
1711
- try {
1712
- await WORK.showConfirm(text, {
1713
- TITLE: { label: title },
1714
- OK: ok,
1715
- CANCEL: { label: 'Отмена', icon: 'icons:close', colorMode: 'info' },
1716
- });
1717
- return true;
1718
- }
1719
- catch {
1720
- return false;
1721
- }
1722
- },
1723
- /** Удалить редактируемый объект (имя не remove — не затенять Element.remove). */
1724
- async removeObject() {
1725
- if (this.busy || !this.canRemove)
1726
- return false;
1727
- // подтверждение — часть операции: пока оно открыто, окно не закрыть
1728
- this.busy = true;
1729
- try {
1730
- if (!await this.confirm('Удалить объект?', 'Удаление', { label: 'Удалить', icon: 'icons:delete', colorMode: 'error' }))
1731
- return false;
1732
- this.error = '';
1733
- const target = await this.targetItem();
1734
- await target.fetch('db_delete', this.writeParams());
1735
- this.snapshot();
1736
- if (!this.editorOpen && !this.isObjectView)
1737
- await this.reload();
1738
- return true;
1739
- }
1740
- catch (e) {
1741
- this.error = String(e?.message || e);
1742
- return false;
1743
- }
1744
- finally {
1745
- this.busy = false;
1746
- }
1747
- },
1748
- /** Восстановить удалённый объект справочника (db_restore). */
1749
- async restoreObject() {
1750
- if (this.busy || !this.canRestore)
1751
- return false;
1752
- this.busy = true;
1753
- this.error = '';
1754
- try {
1755
- const target = await this.targetItem();
1756
- const res = await target.fetch('db_restore', { id: this.editing.id });
1757
- this.accept(res || { id: this.editing.id, status: 'active', version: this.editing.version });
1758
- this.snapshot();
1759
- if (!this.editorOpen && !this.isObjectView)
1760
- await this.reload();
1761
- else if (this.isObjectView)
1762
- await this._findFormHost()?.reloadSiblingLists?.();
1763
- return true;
1764
- }
1765
- catch (e) {
1766
- this.error = String(e?.message || e);
1767
- return false;
1768
- }
1769
- finally {
1770
- this.busy = false;
1771
- }
1772
- },
1773
- /** Провести: несохранённое (и новый объект) сначала сохраняется. */
1774
- async post() {
1775
- if (this.busy || !this.canRegister)
1776
- return false;
1777
- if ((!this.editing.id || this.isDirty()) && !await this.save())
1778
- return false;
1779
- this.busy = true;
1780
- this.clearError();
1781
- try {
1782
- const target = await this.targetItem();
1783
- const res = await target.fetch('db_register', this.writeParams());
1784
- this.accept(res);
1785
- await this.select({ id: this.editing.id });
1786
- this.focusedItem = this.editing || this.focusedItem;
1787
- this.snapshot();
1788
- if (!this.isObjectView)
1789
- await this.reload();
1790
- else
1791
- await this._findFormHost()?.reloadSiblingLists?.();
1792
- return true;
1793
- }
1794
- catch (e) {
1795
- this.setError(e);
1796
- return false;
1797
- }
1798
- finally {
1799
- this.busy = false;
1800
- }
1801
- },
1802
- /** Отменить проведённую операцию: сторно всех проводок. */
1803
- async cancelOperation() {
1804
- if (this.busy || !this.canCancel)
1805
- return false;
1806
- this.busy = true;
1807
- this.error = '';
1808
- try {
1809
- if (!await this.confirm('Отменить операцию? Её проводки будут сторнированы.', 'Отмена операции',
1810
- { label: 'Отменить операцию', icon: 'icons:block', colorMode: 'error' }))
1811
- return false;
1812
- const target = await this.targetItem();
1813
- const res = await target.fetch('db_cancel', this.writeParams());
1814
- this.accept(res);
1815
- await this.select({ id: this.editing.id });
1816
- this.focusedItem = this.editing || this.focusedItem;
1817
- this.snapshot();
1818
- if (!this.isObjectView)
1819
- await this.reload();
1820
- else
1821
- await this._findFormHost()?.reloadSiblingLists?.();
1822
- return true;
1823
- }
1824
- catch (e) {
1825
- this.error = String(e?.message || e);
1826
- return false;
1827
- }
1828
- finally {
1829
- this.busy = false;
1830
- }
1831
- },
1832
- /** Открыть карточку счёта по строке остатка объекта справочника. */
1833
- async openBalanceAccount(b) {
1834
- const path = this.trajectoryNames?.paths?.[b?.account] || b?.account;
1835
- if (!path)
1836
- return;
1837
- const nav = { view: 'postings' };
1838
- if (b.slot && this.editing?.id)
1839
- nav.filters = { [b.slot]: this.editing.id };
1840
- try {
1841
- const t = await WORK.get_item(path);
1842
- if (t && window.execute)
1843
- window.execute(t, nav);
1844
- }
1845
- catch (e) {
1846
- this.error = String(e?.message || e);
1847
- }
1848
- },
1849
- /** Открыть операцию из траектории объекта справочника. */
1850
- async openTrajectoryOp(item) {
1851
- const path = this.trajectoryNames?.paths?.[item?.op_cid] || item?.op_cid;
1852
- if (!path)
1853
- return;
1854
- try {
1855
- const t = await WORK.get_item(path);
1856
- if (t && window.execute)
1857
- window.execute(t, item?.op_id ? { view: 'objects', id: item.op_id } : undefined);
1858
- }
1859
- catch (e) {
1860
- this.error = String(e?.message || e);
1861
- }
1862
- },
1863
- /** Окно редактора и единый guard закрытия: dirty/busy не пропускают close дальше. */
1864
- async showEditor() {
1865
- // «Создать» доступна до ответа схемы: иначе окно откроется с пустой формой и без имени класса
1866
- if (!this.schema)
1867
- await this.loadSchema().catch(() => {});
1868
- this.snapshot();
1869
- let unguard = () => {};
1870
- try {
1871
- const el = ODA.createComponent('item-object-editor', { owner: this });
1872
- unguard = this.guardClose(el);
1873
- await WORK.showModal(el, {
1874
- TITLE: { label: this.editorTitle },
1875
- allowClose: true,
1876
- width: Math.min(720, window.innerWidth || 720),
1877
- });
1878
- }
1879
- catch (e) {
1880
- if (!(WORK.CancelError && e instanceof WORK.CancelError))
1881
- this.error = String(e?.message || e);
1882
- }
1883
- finally {
1884
- clearTimeout(this._previewTimer);
1885
- unguard();
1886
- this.editing = null;
1887
- this.entries = [];
1888
- this.objectBalances = [];
1889
- this.trajectory = [];
1890
- this.leafCid = '';
1891
- this.leafSchema = null;
1892
- await this.reload();
1893
- }
1894
- },
1895
- /**
1896
- * Capture-слушатель close: событие всплывает и composed, поэтому документ видит его
1897
- * раньше платформенного слушателя на popover. Dirty/busy останавливаем и решаем судьбу окна.
1898
- */
1899
- guardClose(el) {
1900
- let pop = null;
1901
- let bypass = false;
1902
- let checking = false;
1903
- const onClose = (e) => {
1904
- const target = e.target;
1905
- if (!target?.contains?.(el))
1906
- return;
1907
- pop = target;
1908
- if (bypass)
1909
- return;
1910
- if (this.busy) {
1911
- e.stopImmediatePropagation();
1912
- return;
1913
- }
1914
- if (!this.isDirty())
1915
- return;
1916
- e.stopImmediatePropagation();
1917
- if (checking)
1918
- return;
1919
- checking = true;
1920
- // крестик закрывает по pointerdown: промпт открываем после текущего события
1921
- setTimeout(async () => {
1922
- try {
1923
- if (!await this.confirmClose())
1924
- return;
1925
- if (!pop?.isConnected)
1926
- return;
1927
- bypass = true;
1928
- pop.close('');
1929
- }
1930
- catch { /* не закрываем: окно остаётся открытым */ }
1931
- finally {
1932
- checking = false;
1933
- }
1934
- }, 0);
1935
- };
1936
- document.addEventListener('close', onClose, true);
1937
- return () => document.removeEventListener('close', onClose, true);
1938
- },
1939
- /** Да — сохранить и закрыть; Нет — не сохранять и закрыть; Отмена/X/Esc/Enter — остаться. */
1940
- async confirmClose() {
1941
- const text = ODA.createElement('p', {
1942
- textContent: 'Сохранить перед закрытием?',
1943
- style: 'margin: var(--space-l);',
1944
- });
1945
- let result;
1946
- try {
1947
- result = await WORK.showDialog(text, {
1948
- TITLE: { label: 'Закрытие' },
1949
- allowClose: true,
1950
- OK: null,
1951
- BUTTONS: [
1952
- { label: 'Да', icon: 'icons:check', colorMode: 'success' },
1953
- { label: 'Нет', icon: 'icons:close', colorMode: 'error' },
1954
- ],
1955
- CANCEL: { label: 'Отмена', icon: 'icons:close', colorMode: 'info' },
1956
- });
1957
- }
1958
- catch {
1959
- return false;
1960
- }
1961
- if (result === 1)
1962
- return await this.save();
1963
- return result === 2;
1964
- },
1965
- };
1966
-
1967
- /**
1968
- * item-object-editor — содержимое модального окна: форма, проводки, состояние/траектория, ошибка и действия.
1969
- * Бизнес-методы остаются на handler'е; компонент только связывает их с разметкой.
1970
- */
1971
- ODA({
1972
- is: 'item-object-editor',
1973
- imports: '/oda/components/button/button.js, /oda/components/layouts/editor-form/editor-form.js',
1974
- template: /*html*/`
1975
- <style>
1976
- :host {
1977
- @apply --vertical;
1978
- width: min(680px, calc(100vw - 24px));
1979
- max-width: 100%;
1980
- min-height: 0;
1981
- box-sizing: border-box;
1982
- overflow: hidden;
1983
- }
1984
- oda-editor-form {
1985
- flex: 1 1 auto;
1986
- min-height: 0;
1987
- overflow-y: auto;
1988
- }
1989
- .error {
1990
- color: var(--error-color);
1991
- white-space: break-spaces;
1992
- padding: 0 var(--space-m);
1993
- }
1994
- .entries {
1995
- @apply --vertical;
1996
- gap: 2px;
1997
- padding: 0 var(--space-m);
1998
- font-size: smaller;
1999
- opacity: .8;
2000
- }
2001
- .trajectory {
2002
- @apply --vertical;
2003
- gap: 4px;
2004
- padding: var(--space-s) var(--space-m);
2005
- max-height: 180px;
2006
- overflow-y: auto;
2007
- font-size: smaller;
2008
- border-top: 1px solid var(--border-color, #ddd);
2009
- }
2010
- .trajectory-title {
2011
- font-weight: bold;
2012
- opacity: .85;
2013
- }
2014
- .traj-row {
2015
- @apply --horizontal;
2016
- flex-wrap: wrap;
2017
- gap: 4px 8px;
2018
- align-items: center;
2019
- }
2020
- .traj-link {
2021
- cursor: pointer;
2022
- text-decoration: underline;
2023
- }
2024
- .traj-num {
2025
- margin-left: auto;
2026
- text-align: right;
2027
- white-space: nowrap;
2028
- }
2029
- .bar {
2030
- @apply --horizontal;
2031
- flex-wrap: wrap;
2032
- justify-content: flex-end;
2033
- gap: var(--space-s);
2034
- padding: var(--space-m);
2035
- border-top: 1px solid var(--subtle-border, var(--border-color, #ddd));
2036
- flex-shrink: 0;
2037
- }
2038
- .context {
2039
- @apply --horizontal;
2040
- flex-wrap: wrap;
2041
- align-items: center;
2042
- gap: var(--space-s);
2043
- padding: var(--space-m) var(--space-m) 0;
2044
- }
2045
- </style>
2046
- <label class="context" ~if="owner.showContext && !owner.editing?.id">От места
2047
- <select @change="owner.contextKey = $this.value">
2048
- <option ~for="owner.contexts" :value="owner.contextKeyOf($for.item)"
2049
- :selected="owner.contextKeyOf($for.item) === owner.contextKeyOf(owner.context)">{{owner.contextTitle($for.item)}}</option>
2050
- </select>
2051
- </label>
2052
- <oda-editor-form :metadata="owner.activeSchema" :data="owner.editing" :field-errors="owner.fieldErrors" @input="onFormInput" @change="onFormInput" @cell-changed="onFormInput"></oda-editor-form>
2053
- <div class="entries" ~if="owner.entries?.length">
2054
- <div class="entry" ~for="owner.entries">{{owner.entryText($for.item)}}</div>
2055
- </div>
2056
- <div class="trajectory" ~if="owner.objectBalances?.length || owner.trajectory?.length">
2057
- <div class="trajectory-title" ~if="owner.objectBalances?.length">Остатки по счетам</div>
2058
- <div class="traj-row" ~for="owner.objectBalances">
2059
- <span class="traj-link" @tap="openBalance($for.item)">{{$for.item.label}}</span>
2060
- <span class="traj-num">{{$for.item.balance}}{{$for.item.qty ? ' (' + $for.item.qty + ')' : ''}}</span>
2061
- </div>
2062
- <div class="trajectory-title" ~if="owner.trajectory?.length">Движения ({{owner.trajectory.length}})</div>
2063
- <div class="traj-row" ~for="owner.trajectory">
2064
- <span>{{$for.item.date}}</span>
2065
- <span class="traj-link" @tap="openTrajOp($for.item)">{{$for.item.op}}</span>
2066
- <span>{{$for.item.account}}</span>
2067
- <span class="traj-num">{{$for.item.debit ? '+' + $for.item.debit : ($for.item.credit ? '−' + $for.item.credit : $for.item.qty)}} → {{$for.item.balance}}</span>
2068
- </div>
2069
- </div>
2070
- <div class="error" ~if="owner.error">{{owner.error}}</div>
2071
- <div class="bar" no-flex>
2072
- <oda-button ~if="owner.canSave" icon="editor:save" :disabled="owner.busy" @tap="save">Сохранить</oda-button>
2073
- <oda-button ~if="owner.canRemove" icon="icons:delete" :disabled="owner.busy"
2074
- @tap="removeObject">Удалить</oda-button>
2075
- <oda-button ~if="owner.canRestore" icon="icons:restore" :disabled="owner.busy"
2076
- @tap="restoreObject">Восстановить</oda-button>
2077
- <oda-button ~if="owner.canRegister" :disabled="owner.busy" @tap="post">Провести</oda-button>
2078
- <oda-button ~if="owner.canCancel" :disabled="owner.busy" @tap="cancelOperation">Отменить</oda-button>
2079
- <oda-button ~for="owner.printForms" icon="icons:print" :title="$for.item.label" @tap="printForm($for.item.name)">{{$for.item.label}}</oda-button>
2080
- <oda-button icon="icons:close" :disabled="owner.busy" @tap="close">Закрыть</oda-button>
2081
- </div>
2082
- `,
2083
- owner: null,
2084
- attached() {
2085
- // после первого рендера формы: контролы могли нормализовать значения
2086
- this.async(() => {
2087
- if (this.isConnected)
2088
- this.owner?.snapshot?.();
2089
- });
2090
- },
2091
- onFormInput() {
2092
- if (this.owner && this.owner.fieldErrors && Object.keys(this.owner.fieldErrors).length)
2093
- this.owner.fieldErrors = {};
2094
- this.owner?.schedulePreview?.();
2095
- },
2096
- async save() {
2097
- if (await this.owner.save())
2098
- this.close();
2099
- },
2100
- async removeObject() {
2101
- if (await this.owner.removeObject())
2102
- this.close();
2103
- },
2104
- async restoreObject() {
2105
- if (await this.owner.restoreObject())
2106
- this.close();
2107
- },
2108
- async post() {
2109
- await this.owner.post();
2110
- },
2111
- async cancelOperation() {
2112
- await this.owner.cancelOperation();
2113
- },
2114
- async printForm(name) {
2115
- await this.owner.printForm(name);
2116
- },
2117
- async openBalance(b) {
2118
- const owner = this.owner;
2119
- this.close();
2120
- await owner?.openBalanceAccount?.(b);
2121
- },
2122
- async openTrajOp(item) {
2123
- const owner = this.owner;
2124
- this.close();
2125
- await owner?.openTrajectoryOp?.(item);
2126
- },
2127
- close() {
2128
- this.parentElement?.close?.();
2129
- },
2130
- });