odant-work 1.0.90 → 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 (326) hide show
  1. package/#system/package-manifest.json +275 -246
  2. package/$server/$folder/$class/$data/$catalog/$folder/$class/$data/$catalog/$virtual/class.js +4 -0
  3. package/$server/$folder/$class/$data/$catalog/$folder/$class/$data/$catalog/class.js +4 -0
  4. package/$server/$folder/$class/$data/$catalog/$virtual/$folder/$class/$data/$catalog/$virtual/class.js +4 -0
  5. package/$server/$folder/$class/$data/$catalog/$virtual/class.js +8 -0
  6. package/{MODULES/Register/CATALOGS/$catalog/$folder/$class → $server/$folder/$class/$data}/$catalog/class.js +1 -0
  7. package/$server/$folder/$class/$data/$operation/$folder/$class/$data/$operation/class.js +4 -0
  8. package/{MODULES/Register/OPERATIONS/$operation/$folder/$class → $server/$folder/$class/$data}/$operation/class.js +1 -0
  9. package/$server/$folder/$class/$data/$register/$account/$folder/$class/$data/$register/$account/class.js +4 -0
  10. package/$server/$folder/$class/$data/$register/$account/class.js +8 -0
  11. package/$server/$folder/$class/$data/$register/$folder/$class/$data/$register/$account/class.js +4 -0
  12. package/$server/$folder/$class/$data/$register/$folder/$class/$data/$register/class.js +4 -0
  13. package/$server/$folder/$class/$data/$register/class.js +8 -0
  14. package/$server/$folder/$class/$data/$struct/$folder/$class/$data/$struct/class.js +4 -0
  15. package/$server/$folder/$class/$data/$struct/class.js +5 -0
  16. package/$server/$folder/$class/$data/class.js +5 -0
  17. package/$server/$folder/$class/$data/handlers/pages/form/objects/$handler/class.js +2158 -0
  18. package/$server/$folder/$class/$data/handlers/pages/form/objects/object/$handler/class.js +1377 -0
  19. package/$server/$folder/$class/$domain/$folder/$class/$domain/class.js +4 -0
  20. package/$server/$folder/$class/$domain/handlers/methods/restore/$handler/class.js +5 -5
  21. package/$server/$folder/$class/$domain/readme.md +1 -1
  22. package/$server/$folder/$class/$handler/$method/class.js +4 -0
  23. package/$server/$folder/$class/$handler/$timer/class.js +4 -0
  24. package/$server/$folder/$class/$module/$folder/$class/$data/$catalog/class.js +4 -0
  25. package/$server/$folder/$class/$module/$folder/$class/$data/$operation/class.js +4 -0
  26. package/$server/$folder/$class/$module/$folder/$class/$data/$register/class.js +4 -0
  27. package/$server/$folder/$class/$module/$folder/$class/$data/$struct/class.js +4 -0
  28. package/$server/$folder/$class/$module/$folder/$class/$domain/class.js +4 -0
  29. package/$server/$folder/$class/$module/$folder/$class/$module/class.js +4 -0
  30. package/$server/$folder/$class/$module/class.js +418 -6
  31. package/$server/$folder/$class/{handlers/pages/form/system/$handler/tabs/mcp.js → $module/handlers/pages/form/system/mcp/$handler/class.js} +261 -220
  32. package/$server/$folder/$class/$module/handlers/pages/form/system/modules/$handler/class.js +7 -0
  33. package/$server/$folder/$class/$structure/$folder/$class/$structure/class.js +4 -0
  34. package/$server/$folder/$class/$structure/$organization/$folder/$class/$data/$catalog/class.js +4 -0
  35. package/$server/$folder/$class/$structure/$organization/$folder/$class/$data/$operation/class.js +4 -0
  36. package/$server/$folder/$class/$structure/$organization/$folder/$class/$data/$register/class.js +4 -0
  37. package/$server/$folder/$class/$structure/$organization/$folder/$class/$data/$struct/class.js +4 -0
  38. package/$server/$folder/$class/$structure/$organization/$folder/$class/$domain/class.js +4 -0
  39. package/$server/$folder/$class/$structure/$organization/$folder/$class/$module/class.js +4 -0
  40. package/{ORGANIZATIONS/$domain/$folder/$class/$base → $server/$folder/$class/$structure/$organization/$folder/$class/$structure/$organization}/class.js +4 -5
  41. package/$server/$folder/$class/$structure/$organization/$folder/$class/$structure/class.js +4 -0
  42. package/{ORGANIZATIONS/$domain/$folder/$class/$base/$folder/$class/$structure/$base → $server/$folder/$class/$structure/$organization}/class.js +19 -17
  43. package/$server/$folder/$class/$structure/$organization/handlers/pages/form/system/requisites/$handler/class.js +3 -0
  44. package/$server/$folder/$class/$structure/{$base/handlers/pages/site/$handler/site.js → $organization/handlers/pages/site/$handler/class.js} +352 -365
  45. package/$server/$folder/$class/$structure/$project/$folder/$class/$data/$catalog/class.js +4 -0
  46. package/$server/$folder/$class/$structure/$project/$folder/$class/$data/$operation/class.js +4 -0
  47. package/$server/$folder/$class/$structure/$project/$folder/$class/$data/$register/class.js +4 -0
  48. package/$server/$folder/$class/$structure/$project/$folder/$class/$data/$struct/class.js +4 -0
  49. package/$server/$folder/$class/$structure/$project/$folder/$class/$domain/class.js +4 -0
  50. package/$server/$folder/$class/$structure/$project/$folder/$class/$module/class.js +4 -0
  51. package/$server/$folder/$class/$structure/$project/class.js +1 -0
  52. package/$server/$folder/$class/$structure/$project/readme.md +1 -1
  53. package/$server/$folder/$class/$structure/$server/$folder/$class/$domain/class.js +4 -0
  54. package/$server/$folder/$class/$structure/$server/handlers/pages/form/system/database/$handler/class.js +3 -0
  55. package/$server/$folder/$class/{handlers/pages/form/system/$handler/tabs/license.js → $structure/$server/handlers/pages/form/system/license/$handler/class.js} +104 -103
  56. package/$server/$folder/$class/$structure/$server/handlers/pages/site/$handler/{site.js → class.js} +45 -30
  57. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/agent/$handler/class.js +3 -0
  58. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/messengers/$handler/class.js +3 -0
  59. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/modules/$handler/class.js +3 -0
  60. package/$server/$folder/$class/$structure/$user/handlers/pages/form/system/profile/$handler/class.js +18 -0
  61. package/$server/$folder/$class/$structure/ai/system.md +1 -1
  62. package/$server/$folder/$class/$structure/class.js +1 -1
  63. package/$server/$folder/$class/$structure/handlers/methods/archive/$handler/class.js +3 -3
  64. package/$server/$folder/$class/$structure/handlers/pages/data/$handler/class.js +309 -8
  65. package/$server/$folder/$class/$structure/handlers/pages/explorer/$handler/class.js +15 -4
  66. package/$server/$folder/$class/$structure/handlers/pages/form/calendar/$handler/class.js +1281 -7
  67. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/class.js +2216 -6
  68. package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/class.js +1304 -6
  69. package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/methods/refresh/$method/class.js +1 -1
  70. package/$server/$folder/$class/$structure/handlers/pages/form/search/$handler/class.js +305 -9
  71. package/$server/$folder/$class/{handlers/pages/form/system/$handler/tabs/agent.js → $structure/handlers/pages/form/system/agent/$handler/class.js} +329 -320
  72. package/$server/$folder/$class/{handlers/pages/form/system/$handler/tabs/database.js → $structure/handlers/pages/form/system/database/$handler/class.js} +510 -577
  73. package/$server/$folder/$class/{handlers/pages/form/system/$handler/tabs/messengers.js → $structure/handlers/pages/form/system/messengers/$handler/class.js} +143 -144
  74. package/$server/$folder/$class/$structure/handlers/pages/form/system/modules/$handler/class.js +270 -0
  75. package/$server/$folder/$class/$structure/handlers/pages/form/system/staff/$handler/class.js +2114 -0
  76. package/$server/$folder/$class/$structure/handlers/pages/site/$handler/class.js +229 -4
  77. package/$server/$folder/$class/$structure/handlers/pages/site/$handler/readme.md +1 -1
  78. package/$server/$folder/$class/$structure/readme.md +3 -3
  79. package/$server/$folder/$class/$users/$folder/$class/$structure/$user/class.js +4 -0
  80. package/$server/$folder/$class/$users/class.js +4 -0
  81. package/$server/$folder/$class/ai/agents/integrator-1c.md +1 -1
  82. package/$server/$folder/$class/ai/agents/it-admin.md +1 -1
  83. package/$server/$folder/$class/ai/agents/org-architect.md +4 -4
  84. package/$server/$folder/$class/ai/agents/readme.md +1 -1
  85. package/$server/$folder/$class/ai/agents/schema-validator.md +2 -2
  86. package/$server/$folder/$class/ai/skills/lan-inventory.md +2 -2
  87. package/$server/$folder/$class/ai/skills/org-structure.md +1 -1
  88. package/$server/$folder/$class/ai/skills/printer-setup.md +1 -1
  89. package/$server/$folder/$class/ai/skills/telegram-notify.md +2 -2
  90. package/$server/$folder/$class/ai/skills/work-scenarios.md +3 -3
  91. package/$server/$folder/$class/ai/system.md +14 -8
  92. package/$server/$folder/$class/class.js +2 -6
  93. package/$server/$folder/$class/handlers/pages/form/folder/$handler/class.js +3 -0
  94. package/$server/$folder/$class/handlers/pages/form/system/$handler/class.js +2 -4
  95. package/$server/$folder/$class/handlers/pages/form/system/files/$handler/class.js +7 -0
  96. package/$server/$folder/$class/handlers/pages/form/system/requisites/$handler/class.js +100 -0
  97. package/$server/$folder/$class/handlers/pages/storage/$handler/class.js +25 -6
  98. package/$server/$folder/$file/$data/handlers/pages/form/editor/$handler/class.js +32 -5
  99. package/$server/$folder/$file/$devs/handlers/pages/form/file/$handler/class.js +31 -3
  100. package/$server/$folder/$file/$ics/handlers/pages/form/file/$handler/class.js +11 -3
  101. package/$server/$folder/$file/$ipynb/handlers/pages/form/file/$handler/class.js +83 -3
  102. package/$server/$folder/$file/$md/handlers/pages/form/file/$handler/class.js +61 -3
  103. package/$server/$folder/$file/$office/handlers/pages/form/file/$handler/class.js +1699 -2
  104. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/class.js +827 -2
  105. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/readme.md +1 -1
  106. package/$server/$folder/$file/handlers/pages/form/file/$handler/class.js +33 -3
  107. package/$server/$folder/$file/handlers/pages/form/folder/$handler/class.js +3 -0
  108. package/$server/$folder/handlers/methods/create/$handler/class.js +5 -5
  109. package/$server/$folder/handlers/pages/form/$handler/class.js +2467 -3
  110. package/$server/$folder/handlers/pages/form/folder/$handler/class.js +22 -0
  111. package/$server/$folder/handlers/readme.md +1 -1
  112. package/$server/$folder/lib/chat-item/chat-item.js +5 -10
  113. package/$server/$folder/lib/consultant/consultant.js +7 -10
  114. package/$server/$folder/lib/explorer/explorer.js +1 -1
  115. package/$server/$folder/lib/icon/icon.js +1 -1
  116. package/$server/$folder/lib/menu/menu.js +3 -2
  117. package/$server/$folder/lib/messenger-settings/messenger-settings.js +4 -4
  118. package/$server/$folder/lib/node/node.js +3 -3
  119. package/$server/$folder/lib/prompt-bar/prompt-bar.js +2 -2
  120. package/$server/$folder/lib/role/role.js +1 -2
  121. package/$server/$folder/lib/security/admin/admin.js +3 -3
  122. package/$server/$folder/lib/security/security.js +4 -4
  123. package/$server/$folder/lib/security/users/users.js +2 -5
  124. package/$server/$folder/lib/site-loc/site-loc.js +3 -3
  125. package/$server/$folder/lib/tree/tree.js +14 -22
  126. package/$server/class.js +1 -0
  127. package/AGENTS.md +21 -13
  128. package/{$server/$folder/$class/handlers/pages/form/system/$handler/tabs/ai-model.js → MODELS/$ai/$folder/$class/$ai/handlers/pages/form/system/ai/$handler/class.js} +385 -425
  129. package/{$server/$folder/$class/handlers/pages/form/system/$handler/tabs/ai-provider.js → MODELS/$ai/$folder/$class/$provider/handlers/pages/form/system/ai/$handler/class.js} +157 -161
  130. package/{$server/$folder/$class/handlers/pages/form/system/$handler/tabs/ai-root.js → MODELS/$ai/handlers/pages/form/system/ai/$handler/class.js} +34 -33
  131. package/{$server/$folder/$class/handlers/pages/form/system/$handler/tabs/ai-local.js → MODELS/Local/$provider/handlers/pages/form/system/ai/$handler/class.js} +572 -622
  132. package/MODULES/$domain/class.js +85 -4
  133. package/MODULES/$domain/handlers/pages/form/system/mcp/$handler/class.js +7 -0
  134. package/MODULES/$domain/readme.md +7 -6
  135. package/{SERVICES/1C/$service → MODULES/1C/$module}/class.js +7 -1
  136. package/MODULES/2GIS/$module/class.js +32 -0
  137. package/MODULES/2GIS/$module/readme.md +57 -0
  138. package/{SERVICES/Bitrix24/$service → MODULES/Bitrix24/$module}/class.js +7 -2
  139. package/{SERVICES/CBR/$service → MODULES/CBR/$module}/class.js +5 -0
  140. package/{SERVICES/DaData/$service → MODULES/DaData/$module}/class.js +9 -3
  141. package/MODULES/Geo//320/232/320/260/321/200/321/202/320/260/$catalog/handlers/pages/form/map/$handler/class.js +648 -21
  142. package/MODULES/KLADR/$module/handlers/pages/form/kladr/$handler/class.js +140 -6
  143. package/{SERVICES/Marketplaces/$service → MODULES/Marketplaces/$domain}/class.js +1 -1
  144. package/{SERVICES/Marketplaces/Ozon/$service → MODULES/Marketplaces/Ozon/$module}/class.js +1 -1
  145. package/{SERVICES/Marketplaces/Wildberries/$service → MODULES/Marketplaces/Wildberries/$module}/class.js +1 -1
  146. package/{SERVICES/Marketplaces/YandexMarket/$service → MODULES/Marketplaces/YandexMarket/$module}/class.js +1 -1
  147. package/MODULES/Process/$module/readme.md +1 -1
  148. 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 -6
  149. 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 -6
  150. 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 -16
  151. package/MODULES/Register/CATALOGS/$catalog/$folder/$class/{$virtual → $data/$catalog/$virtual}/class.js +3 -0
  152. package/MODULES/Register/CATALOGS/$catalog/$folder/$class/$data/$catalog/$virtual/handlers/pages/form/objects/$handler/class.js +3 -0
  153. package/MODULES/Register/CATALOGS/$catalog/$folder/$class/{$virtual/handlers/pages/form/virtual/$handler/virtual.js → $data/$catalog/$virtual/handlers/pages/form/virtual/$handler/class.js} +413 -390
  154. package/MODULES/Register/CATALOGS/$catalog/$folder/$class/$data/$catalog/class.js +14 -0
  155. package/MODULES/Register/CATALOGS/$catalog/class.js +7 -14
  156. package/MODULES/Register/CATALOGS//320/241/320/276/321/202/321/200/321/203/320/264/320/275/320/270/320/272/320/270/$virtual/$folder/$class/$data/$catalog/$virtual/class.js +9 -0
  157. package/MODULES/Register/CATALOGS//320/241/320/276/321/202/321/200/321/203/320/264/320/275/320/270/320/272/320/270/$virtual/class.js +0 -7
  158. package/MODULES/Register/CATALOGS//320/241/321/203/320/261/321/212/320/265/320/272/321/202/321/213/$catalog/$folder/$class/$data/$catalog/class.js +11 -0
  159. package/MODULES/Register/CATALOGS//320/241/321/203/320/261/321/212/320/265/320/272/321/202/321/213/$catalog/class.js +0 -9
  160. package/MODULES/Register/OPERATIONS/$operation/$folder/$class/$data/$operation/class.js +16 -0
  161. package/MODULES/Register/OPERATIONS/$operation/class.js +0 -9
  162. package/MODULES/Register/OPERATIONS//320/232/320/260/320/264/321/200/321/213/$operation/$folder/$class/$data/$operation/class.js +8 -0
  163. package/MODULES/Register/OPERATIONS//320/232/320/260/320/264/321/200/321/213/$operation/class.js +4 -10
  164. package/MODULES/Register/OPERATIONS//320/232/320/260/321/201/321/201/320/260/$operation/$folder/$class/$data/$operation/class.js +8 -0
  165. package/MODULES/Register/OPERATIONS//320/232/320/260/321/201/321/201/320/260/$operation/class.js +0 -6
  166. package/MODULES/Register/OPERATIONS//320/232/320/276/320/274/320/274/321/203/320/275/320/270/320/272/320/260/321/206/320/270/320/270/$operation/$folder/$class/$data/$operation/class.js +8 -0
  167. package/MODULES/Register/OPERATIONS//320/232/320/276/320/274/320/274/321/203/320/275/320/270/320/272/320/260/321/206/320/270/320/270/$operation/class.js +4 -10
  168. package/MODULES/Register/OPERATIONS//320/237/320/273/320/260/321/202/320/265/320/266/320/270 /321/201 /321/200/320/260/321/201/321/207/321/221/321/202/320/275/320/276/320/263/320/276 /321/201/321/207/321/221/321/202/320/260/$operation/$folder/$class/$data/$operation/class.js" +10 -0
  169. package/MODULES/Register/OPERATIONS//320/237/320/273/320/260/321/202/320/265/320/266/320/270 /321/201 /321/200/320/260/321/201/321/207/321/221/321/202/320/275/320/276/320/263/320/276 /321/201/321/207/321/221/321/202/320/260/$operation/class.js" +4 -12
  170. package/MODULES/Register/OPERATIONS//320/237/320/276/321/201/321/202/321/203/320/277/320/273/320/265/320/275/320/270/321/217 /320/275/320/260 /321/200/320/260/321/201/321/207/321/221/321/202/320/275/321/213/320/271 /321/201/321/207/321/221/321/202/$operation/$folder/$class/$data/$operation/class.js" +10 -0
  171. package/MODULES/Register/OPERATIONS//320/237/320/276/321/201/321/202/321/203/320/277/320/273/320/265/320/275/320/270/321/217 /320/275/320/260 /321/200/320/260/321/201/321/207/321/221/321/202/320/275/321/213/320/271 /321/201/321/207/321/221/321/202/$operation/class.js" +4 -12
  172. package/MODULES/Register/OPERATIONS//320/240/320/265/320/260/320/273/320/270/320/267/320/260/321/206/320/270/321/217/$operation/$folder/$class/$data/$operation/class.js +24 -0
  173. package/MODULES/Register/OPERATIONS//320/240/320/265/320/260/320/273/320/270/320/267/320/260/321/206/320/270/321/217/$operation/class.js +0 -22
  174. package/MODULES/Register/REGISTER/$register/$folder/$class/{$account/handlers/pages/form/analysis/$handler/analysis.js → $data/$register/$account/handlers/pages/form/analysis/$handler/class.js} +9 -4
  175. package/MODULES/Register/REGISTER/$register/$folder/$class/{$account/handlers/pages/form/postings/$handler/postings.js → $data/$register/$account/handlers/pages/form/postings/$handler/class.js} +845 -753
  176. package/MODULES/Register/REGISTER/$register/$folder/$class/{$account/handlers/pages/form/turnovers/$handler/turnovers.js → $data/$register/$account/handlers/pages/form/turnovers/$handler/class.js} +9 -4
  177. package/MODULES/Register/REGISTER/$register/{$folder/$class/$register/handlers/pages/form/journal/$handler/journal.js → handlers/pages/form/journal/$handler/class.js} +382 -329
  178. package/MODULES/Register/REGISTER/$register/handlers/pages/form/sheet/$handler/class.js +807 -0
  179. package/MODULES/Register/REGISTER/10/$account/$folder/$class/$data/$register/$account/class.js +21 -0
  180. package/MODULES/Register/REGISTER/10/$account/class.js +0 -19
  181. package/MODULES/Register/REGISTER//320/232/320/260/320/264/321/200/321/213/$account/$folder/$class/$data/$register/$account/class.js +14 -0
  182. package/MODULES/Register/REGISTER//320/232/320/260/320/264/321/200/321/213/$account/class.js +4 -16
  183. package/{SERVICES/SearXNG/$service → MODULES/SearXNG/$module}/class.js +5 -0
  184. package/{SERVICES/Yandex/$service → MODULES/Yandex/$module}/class.js +7 -0
  185. package/{SERVICES/YandexDisk/$service → MODULES/YandexDisk/$module}/class.js +8 -2
  186. package/NODES/$node/handlers/pages/form/network/$handler/class.js +122 -5
  187. package/ORGANIZATIONS/$domain/$folder/$class/$structure/$organization/class.js +5 -0
  188. package/ORGANIZATIONS/$domain/class.js +5 -5
  189. package/oda/components/inputs/link/link.js +1 -1
  190. package/package.json +1 -1
  191. package/readme.md +6 -7
  192. package/scripts/check-architecture.mjs +541 -0
  193. package/scripts/cleanup-storage.mjs +1 -1
  194. package/scripts/demo-seed.mjs +3 -3
  195. package/scripts/import-bis.mjs +33 -15
  196. package/scripts/import-delovaya.mjs +26 -14
  197. package/sources/client/class.js +19 -10
  198. package/sources/client/folder.js +10 -22
  199. package/sources/client/handler.js +75 -33
  200. package/sources/data/api.js +9 -10
  201. package/sources/data/classes.js +85 -9
  202. package/sources/data/db.js +10 -6
  203. package/sources/data/print.js +15 -41
  204. package/sources/data/readme.md +5 -5
  205. package/sources/data/schema.js +206 -118
  206. package/sources/data/sql-inspector.js +7 -7
  207. package/sources/host/auth-methods.js +2 -5
  208. package/sources/host/auto-updater.js +1 -2
  209. package/sources/host/babel-merge.js +174 -129
  210. package/sources/host/prewarm.js +1 -1
  211. package/sources/host/watch.js +1 -1
  212. package/sources/index.html +1 -1
  213. package/sources/modules/agent/extensions.js +48 -38
  214. package/sources/modules/agent/index.js +1 -1
  215. package/sources/modules/agent/node-rules.js +69 -41
  216. package/sources/modules/agent/permissions.js +1 -1
  217. package/sources/modules/agent/plugins.js +11 -11
  218. package/sources/modules/agent/resources.js +96 -52
  219. package/sources/modules/agent/tools/net.js +1 -1
  220. package/sources/modules/agent/tools/services.js +7 -7
  221. package/sources/modules/agent/tools/work/access.js +10 -8
  222. package/sources/modules/agent/tools/work/classes.js +26 -47
  223. package/sources/modules/agent/tools/work/common.js +8 -10
  224. package/sources/modules/agent/tools/work/data.js +4 -4
  225. package/sources/modules/agent/triggers.js +1 -1
  226. package/sources/modules/agent/twin-bus.js +4 -4
  227. package/sources/modules/agent/voice.js +1 -1
  228. package/sources/modules/call/call.js +4 -4
  229. package/sources/modules/kladr/index.js +3 -3
  230. package/sources/modules/lan/register.js +7 -7
  231. package/sources/modules/mcp-marketplaces/ozon.js +1 -1
  232. package/sources/modules/mcp-marketplaces/wildberries.js +1 -1
  233. package/sources/modules/mcp-marketplaces/yandex-market.js +1 -1
  234. package/sources/modules/nodes/mount.js +2 -4
  235. package/sources/modules/notify/index.js +18 -18
  236. package/sources/modules/rag/extract.js +9 -2
  237. package/sources/modules/rag/indexer.js +1 -1
  238. package/sources/modules/rag/scope.js +7 -33
  239. package/sources/modules/trainer/dataset.js +2 -2
  240. package/sources/modules/trainer/local-engine.js +1 -1
  241. package/sources/page.html +2 -2
  242. package/sources/readme.md +1 -1
  243. package/sources/server/access/gateway.js +19 -19
  244. package/sources/server/access/invites.js +4 -5
  245. package/sources/server/access/links.js +10 -8
  246. package/sources/server/access/policy.js +65 -39
  247. package/sources/server/access/workplaces.js +20 -14
  248. package/sources/server/chat-threads.js +4 -4
  249. package/sources/server/class/archive.js +15 -15
  250. package/sources/server/class/base-template.js +13 -9
  251. package/sources/server/class/distro.js +3 -4
  252. package/sources/server/class/feed.js +3 -3
  253. package/sources/server/class/mail-calendar.js +9 -8
  254. package/sources/server/class/scaffold.js +110 -60
  255. package/sources/server/class/search.js +2 -2
  256. package/sources/server/class/security.js +76 -94
  257. package/sources/server/class.js +181 -64
  258. package/sources/server/file.js +2 -2
  259. package/sources/server/folder.js +376 -191
  260. package/sources/server/handler.js +52 -13
  261. package/sources/server/logs.js +7 -7
  262. package/sources/server/node.js +12 -43
  263. package/sources/server/server.js +16 -17
  264. package/$server/$folder/$class/$device/class.js +0 -3
  265. package/$server/$folder/$class/$handler/$task/class.js +0 -3
  266. package/$server/$folder/$class/$service/$class/$service/class.js +0 -4
  267. package/$server/$folder/$class/$structure/$base/class.js +0 -10
  268. package/$server/$folder/$class/$structure/$base/roots_1/roots.test +0 -0
  269. package/$server/$folder/$class/$structure/handlers/pages/data/$handler/data.js +0 -313
  270. package/$server/$folder/$class/$structure/handlers/pages/explorer/$handler/explorer.js +0 -16
  271. package/$server/$folder/$class/$structure/handlers/pages/form/calendar/$handler/calendar.js +0 -1226
  272. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +0 -2217
  273. package/$server/$folder/$class/$structure/handlers/pages/form/email/$handler/email.js +0 -1188
  274. package/$server/$folder/$class/$structure/handlers/pages/form/search/$handler/search.js +0 -289
  275. package/$server/$folder/$class/$structure/handlers/pages/site/$handler/site.js +0 -240
  276. package/$server/$folder/$class/handlers/pages/form/object/$handler/class.js +0 -33
  277. package/$server/$folder/$class/handlers/pages/form/object/$handler/object.js +0 -1371
  278. package/$server/$folder/$class/handlers/pages/form/objects/$handler/class.js +0 -33
  279. package/$server/$folder/$class/handlers/pages/form/objects/$handler/objects.js +0 -2130
  280. package/$server/$folder/$class/handlers/pages/form/system/$handler/system.js +0 -384
  281. package/$server/$folder/$class/handlers/pages/form/system/$handler/tabs/modules.js +0 -244
  282. package/$server/$folder/$class/handlers/pages/form/system/$handler/tabs/staff.js +0 -2126
  283. package/$server/$folder/$class/handlers/pages/storage/$handler/storage.js +0 -21
  284. package/$server/$folder/$file/$data/handlers/pages/form/editor/$handler/editor.js +0 -27
  285. package/$server/$folder/$file/$devs/handlers/pages/form/file/$handler/file.js +0 -31
  286. package/$server/$folder/$file/$ics/handlers/pages/form/file/$handler/file.js +0 -10
  287. package/$server/$folder/$file/$ipynb/handlers/pages/form/file/$handler/file.js +0 -72
  288. package/$server/$folder/$file/$md/handlers/pages/form/file/$handler/file.js +0 -63
  289. package/$server/$folder/$file/$office/handlers/pages/form/file/$handler/file.js +0 -1845
  290. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +0 -785
  291. package/$server/$folder/$file/handlers/pages/form/file/$handler/file.js +0 -29
  292. package/$server/$folder/handlers/pages/form/$handler/form.js +0 -2122
  293. package/MODULES/Geo//320/232/320/260/321/200/321/202/320/260/$catalog/handlers/pages/form/map/$handler/map.js +0 -623
  294. package/MODULES/KLADR/$module/handlers/pages/form/kladr/$handler/kladr.js +0 -134
  295. 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
  296. 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
  297. 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
  298. package/MODULES/Register/CATALOGS/$catalog/$folder/$class/$virtual/handlers/pages/form/virtual/$handler/class.js +0 -6
  299. package/MODULES/Register/REGISTER/$register/$folder/$class/$account/handlers/pages/form/analysis/$handler/class.js +0 -9
  300. package/MODULES/Register/REGISTER/$register/$folder/$class/$account/handlers/pages/form/postings/$handler/class.js +0 -9
  301. package/MODULES/Register/REGISTER/$register/$folder/$class/$account/handlers/pages/form/turnovers/$handler/class.js +0 -9
  302. package/MODULES/Register/REGISTER/$register/$folder/$class/$register/handlers/pages/form/journal/$handler/class.js +0 -6
  303. package/MODULES/Register/REGISTER/$register/$folder/$class/$register/handlers/pages/form/sheet/$handler/class.js +0 -6
  304. package/MODULES/Register/REGISTER/$register/$folder/$class/$register/handlers/pages/form/sheet/$handler/sheet.js +0 -808
  305. package/NODES/$node/handlers/pages/form/network/$handler/network.js +0 -110
  306. package/SERVICES/$service/$folder/$storage/$service/class.js +0 -8
  307. package/SERVICES/$service/class.js +0 -442
  308. package/SERVICES/readme.md +0 -36
  309. /package/$server/$folder/$class/$structure/{$base → $organization}/icon.png +0 -0
  310. /package/{SERVICES/DuckDuckGo/$service → MODULES/DuckDuckGo/$module}/class.js +0 -0
  311. /package/MODULES/KLADR/$module/$folder/$class/{$catalog → $data/$catalog}/class.js +0 -0
  312. /package/MODULES/Process/$module/$folder/$class/{$catalog → $data/$catalog}/class.js +0 -0
  313. /package/MODULES/Register/$module/$folder/$class/{$catalog → $data/$catalog}/class.js +0 -0
  314. /package/MODULES/Register/$module/$folder/$class/{$operation → $data/$operation}/class.js +0 -0
  315. /package/MODULES/Register/$module/$folder/$class/{$register → $data/$register}/class.js +0 -0
  316. /package/MODULES/Register/$module/$folder/$class/{$struct → $data/$struct}/class.js +0 -0
  317. /package/MODULES/Register/CATALOGS/$catalog/$folder/$class/{$virtual/$folder/$class → $data/$catalog/$virtual/$folder/$class/$data/$catalog}/$virtual/class.js +0 -0
  318. /package/MODULES/Register/OPERATIONS//320/237/320/273/320/260/321/202/320/265/320/266/320/270 /321/201 /321/200/320/260/321/201/321/207/321/221/321/202/320/275/320/276/320/263/320/276 /321/201/321/207/321/221/321/202/320/260/$operation/{print → $folder/$class/$data/$operation/print}//320/237/320/273/320/260/321/202/321/221/320/266/320/275/320/276/320/265 /320/277/320/276/321/200/321/203/321/207/320/265/320/275/320/270/320/265.html" +0 -0
  319. /package/MODULES/Register/REGISTER/$register/$folder/$class/{$account → $data/$register/$account}/class.js +0 -0
  320. /package/MODULES/Register/REGISTER/$register/$folder/$class/{$account → $data/$register/$account}/readme.md +0 -0
  321. /package/MODULES/Register/REGISTER/$register/$folder/$class/{$register → $data/$register}/class.js +0 -0
  322. /package/MODULES/Register/STRUCTS/$struct/$folder/$class/{$struct → $data/$struct}/class.js +0 -0
  323. /package/{SERVICES/RuCalendar/$service → MODULES/RuCalendar/$module}/class.js +0 -0
  324. /package/{SERVICES/Telegram/$service → MODULES/Telegram/$module}/class.js +0 -0
  325. /package/{SERVICES/Weather/$service → MODULES/Weather/$module}/class.js +0 -0
  326. /package/PROJECTS/$domain/$folder/$class/{$project → $structure/$project}/class.js +0 -0
@@ -1,2217 +0,0 @@
1
- import {
2
- taskKeyOf,
3
- taskDayOf,
4
- isCreatedTask,
5
- pathOfLog,
6
- isChatModel,
7
- getUserPreferredModel,
8
- setUserPreferredModel,
9
- } from './chat-task.js';
10
-
11
- const sleep = ms => new Promise(r => setTimeout(r, ms));
12
- const SORT_TIMES = new WeakMap();
13
- /** localStorage.workChatDebug = 1 — журнал времён создания задачи в консоли. */
14
- function chatDebug(...a) {
15
- try {
16
- if (globalThis.localStorage?.workChatDebug)
17
- console.log('[chat]', Math.round(performance.now()) + 'мс', ...a);
18
- }
19
- catch { /* нет localStorage */ }
20
- }
21
-
22
- /** Первый лист $ai с chat. Неязыковые модели (image/audio/embedding/asr/tts) отсекаются. */
23
- async function firstChatLeaf(node) {
24
- if (!node)
25
- return null;
26
- if (!node.items?.length) {
27
- if (!isChatModel(node))
28
- return null;
29
- try {
30
- const item = node.path ? await WORK.get_item(node.path) : null;
31
- if (item && !isChatModel(item))
32
- return null;
33
- }
34
- catch { /* лист без доп. данных — проверен по node */ }
35
- return node;
36
- }
37
- for (const child of node.items) {
38
- const found = await firstChatLeaf(child);
39
- if (found)
40
- return found;
41
- }
42
- return null;
43
- }
44
-
45
- export default{
46
- icon: 'icons:question-answer',
47
- imports: '/oda//toggle.js, ~/lib//tree.js, ~/lib//chat-item',
48
- template: /* html */`
49
- <style>
50
- :host{
51
- @apply --vertical;
52
- overflow: hidden;
53
- position: relative;
54
- }
55
- </style>
56
- <form-chat flex :$item></form-chat>
57
- `
58
- }
59
- ODA({is: 'form-chat',
60
- imports: '/oda//toggle.js, ~/lib//tree.js',
61
- template: /* html */`
62
- <style>
63
- :host {
64
- @apply --vertical;
65
- overflow: hidden;
66
- position: relative;
67
- }
68
- </style>
69
- <oda-chat id="chat" :$item ::model></oda-chat>
70
- `,
71
- async attached(){
72
- if (typeof BroadcastChannel !== 'undefined' && !this._modelBc) {
73
- try {
74
- this._modelBc = new BroadcastChannel('work-user-ai-model');
75
- this._modelBc.onmessage = (ev) => {
76
- const m = ev?.data?.model;
77
- if (m && m !== this.model)
78
- this.model = m;
79
- };
80
- }
81
- catch { /* ignore */ }
82
- }
83
- await this._hydrateModel();
84
- if (this._initialNav) {
85
- const nav = this._initialNav;
86
- this._initialNav = null;
87
- this.async(() => this.applyNav(nav), 0);
88
- }
89
- },
90
- _applyNavFields(nav) {
91
- if (nav?.openTaskPath) {
92
- this._pendingOpenTaskPath = String(nav.openTaskPath);
93
- }
94
- },
95
- async applyNav(nav) {
96
- if (!nav || typeof nav !== 'object')
97
- return;
98
- const taskPath = nav.openTaskPath || this._pendingOpenTaskPath;
99
- if (!taskPath)
100
- return;
101
- this._pendingOpenTaskPath = '';
102
- let chatEl = this.chat;
103
- for (let i = 0; i < 20 && !chatEl; i++) {
104
- await sleep(50);
105
- chatEl = this.chat;
106
- }
107
- if (chatEl) {
108
- if (chatEl.feedMode !== 'dialog')
109
- chatEl.feedMode = 'dialog';
110
- await chatEl.openMovedTask?.(taskPath);
111
- }
112
- },
113
- detached(){
114
- try {
115
- this._modelBc?.close?.();
116
- this._modelBc = null;
117
- }
118
- catch { /* ignore */ }
119
- },
120
- last:{
121
- $def: 0,
122
- $save: true
123
- },
124
- model: {
125
- $def: '',
126
- set(n) {
127
- if (n)
128
- setUserPreferredModel(n);
129
- }
130
- },
131
- get $saveKey(){
132
- return this.$item?.short;
133
- },
134
- async _hydrateModel(){
135
- const userModel = getUserPreferredModel();
136
- if (userModel && this.model !== userModel)
137
- this.model = userModel;
138
- if (!this.model) {
139
- try {
140
- const children = await WORK.children;
141
- const aiRoot = children?.find(el => el.type === '$ai');
142
- if (!aiRoot) return;
143
- const tree = await aiRoot.info({ deep: -1 });
144
- const leaf = await firstChatLeaf(tree);
145
- const path = leaf?.path;
146
- if (path) {
147
- this.model = path;
148
- setUserPreferredModel(path);
149
- }
150
- } catch {}
151
- }
152
- },
153
- get formChat(){
154
- return this;
155
- },
156
- get chat(){
157
- return this.$('oda-chat');
158
- },
159
- get isPrivate(){
160
- return this.$item?.type === '$user'
161
- },
162
- focusInput(){
163
- this.async(()=>{
164
- this.chat?.focusInput?.();
165
- })
166
- },
167
- receivers: [],
168
- deptUsers: [],
169
- operationClasses: [],
170
- async _loadDepartmentContext($item = this.$item) {
171
- if (!$item || this.isPrivate) {
172
- this.deptUsers = [];
173
- this.operationClasses = [];
174
- return;
175
- }
176
- try {
177
- const d = await $item.fetch('places').catch(() => null);
178
- const placeLabels = new Map();
179
- const uidSet = new Set();
180
- const opMap = new Map();
181
-
182
- const collectTreeOps = (nodes, parentOpPath = '') => {
183
- for (const n of nodes || []) {
184
- if (!n) continue;
185
- const isOp = n.type === '$operation';
186
- const hasKids = Array.isArray(n.children) && n.children.length > 0;
187
- const isOpsRoot = isOp && /(?:^|\/)OPERATIONS$/i.test(n.path || '');
188
- if (isOp && n.path && !isOpsRoot) {
189
- const leaf = !hasKids;
190
- if (!leaf || n.access !== 'read') {
191
- const prev = opMap.get(n.path);
192
- const count = Number(n.objectCount ?? n.count) || prev?.count || 0;
193
- opMap.set(n.path, {
194
- id: n.path,
195
- cid: n.path,
196
- path: n.path,
197
- parent: parentOpPath || prev?.parent || '',
198
- label: n.label || n.id || n.path.split('/').pop(),
199
- type: '$operation',
200
- icon: n.icon || prev?.icon || 'carbon:task-complete',
201
- leaf: prev ? (prev.leaf && leaf) : leaf,
202
- count,
203
- hint: n.path,
204
- });
205
- }
206
- }
207
- if (hasKids) {
208
- const nextParent = (isOp && n.path && !isOpsRoot) ? n.path : parentOpPath;
209
- collectTreeOps(n.children, nextParent);
210
- }
211
- }
212
- };
213
-
214
- const walkPlaces = (places) => {
215
- for (const p of places || []) {
216
- if (!p) continue;
217
- const pLabel = p.label || p.id || '';
218
- for (const u of p.users || []) {
219
- if (u && u !== 'GUEST' && u !== 'GUESTS' && u !== 'USERS') {
220
- uidSet.add(u);
221
- if (pLabel && !placeLabels.has(u))
222
- placeLabels.set(u, pLabel);
223
- }
224
- }
225
- if (Array.isArray(p.tree))
226
- collectTreeOps(p.tree);
227
- if (Array.isArray(p.roles))
228
- walkPlaces(p.roles);
229
- }
230
- };
231
-
232
- if (d) {
233
- if (Array.isArray(d.commonTree))
234
- collectTreeOps(d.commonTree);
235
- walkPlaces(d.places);
236
- }
237
-
238
- const roleIds = $item.DATA?.roleIds || {};
239
- for (const [roleKey, list] of Object.entries(roleIds)) {
240
- for (const u of list || []) {
241
- if (u && u !== 'GUEST' && u !== 'GUESTS' && u !== 'USERS') {
242
- uidSet.add(u);
243
- if (!placeLabels.has(u))
244
- placeLabels.set(u, roleKey === 'BOSS' ? 'Руководитель (BOSS)' : 'Сотрудник');
245
- }
246
- }
247
- }
248
-
249
- // Если в подразделении ещё не распределены места — подгружаем список пользователей из /USERS
250
- if (!uidSet.size && WORK.DEV_MODE) {
251
- const uRoot = await WORK.get_item('/USERS').catch(() => null);
252
- const all = (await uRoot?.items) || [];
253
- for (const u of all) {
254
- if (u?.id && u.id[0] !== '$')
255
- uidSet.add(u.id);
256
- }
257
- }
258
-
259
- // Если по дереву ссылок не нашлось листовых $operation, добираем из db_workspace
260
- if (![...opMap.values()].some(x => x.leaf)) {
261
- const ws = await $item.fetch('db_workspace').catch(() => null);
262
- for (const [cid, cls] of Object.entries(ws?.classes || {})) {
263
- const p = cls?.path || cid;
264
- if (cls?.type === '$operation' && p && !/(?:^|\/)OPERATIONS$/i.test(p)) {
265
- const parentPath = /(?:^|\/)OPERATIONS$/i.test(cls.parent || '') ? '' : (cls.parent || '');
266
- opMap.set(p, {
267
- id: p,
268
- cid: p,
269
- path: p,
270
- parent: parentPath,
271
- label: cls.label || p.split('/').pop(),
272
- type: '$operation',
273
- icon: cls.icon || 'carbon:task-complete',
274
- leaf: !!cls.leaf,
275
- count: Number(cls.count ?? cls.objectCount) || 0,
276
- hint: p,
277
- });
278
- }
279
- }
280
- }
281
-
282
- const users = uidSet.size && typeof WORK.usersByIds === 'function'
283
- ? ((await WORK.usersByIds([...uidSet])) || []).filter(Boolean)
284
- : [];
285
- for (const u of users) {
286
- if (u?.id && placeLabels.has(u.id))
287
- u._placeLabel = placeLabels.get(u.id);
288
- }
289
- this.deptUsers = users;
290
- this.operationClasses = [...opMap.values()];
291
- }
292
- catch (err) {
293
- console.warn('[chat] _loadDepartmentContext:', err);
294
- }
295
- },
296
- // $item: null
297
- $item: {
298
- $def: null,
299
- set($item) {
300
- if($item && this.isPrivate && this.$item.id !== WORK.uid) this.receivers = [$item];
301
- else this.receivers = [];
302
- if ($item) {
303
- this._hydrateModel();
304
- this._loadDepartmentContext($item);
305
- }
306
- }
307
- }
308
- })
309
- ODA({is: 'oda-chat',
310
- imports: 'oda//button, oda//icon, ~/lib//pack, ~/lib//tree, ~/lib//user, ~/lib//prompt-bar',
311
- template:/* html */`
312
- <style>
313
- :host{
314
- @apply --flex;
315
- @apply --vertical;
316
- overflow: hidden;
317
- position: relative;
318
- background: {{background}};
319
- }
320
- .back{
321
- position: absolute;
322
- top: 0px;
323
- left: 0px;
324
- width: 100%;
325
- height: 100%;
326
- background-repeat: round;
327
- background: url({{url}});
328
- pointer-events: none;
329
- opacity: .1;
330
- }
331
- .mover{
332
- gap: 4px;
333
- position: absolute;
334
- align-self: anchor-center;
335
- right: 8px;
336
- opacity: .5;
337
- }
338
- .mover>oda-button{
339
- border-radius: 50%;
340
- }
341
- .feed-top-bar {
342
- position: relative;
343
- z-index: 8;
344
- display: flex;
345
- align-items: center;
346
- justify-content: flex-end;
347
- gap: 6px;
348
- flex-wrap: wrap;
349
- padding: 6px 12px 4px;
350
- flex-shrink: 0;
351
- }
352
- .feed-mode-bar {
353
- display: inline-flex;
354
- align-items: center;
355
- gap: 2px;
356
- padding: 2px;
357
- border-radius: 999px;
358
- background: var(--content-background, #ffffff);
359
- border: 1px solid var(--border-color, #cbd5e1);
360
- box-shadow: 0 2px 8px rgba(0, 0, 0, 0.12);
361
- opacity: 0.94;
362
- }
363
- .feed-mode-bar:hover {
364
- opacity: 1;
365
- }
366
- .feed-mode-btn {
367
- border: none;
368
- background: transparent;
369
- color: var(--content-color, inherit);
370
- font: inherit;
371
- font-size: 11px;
372
- font-weight: 600;
373
- padding: 4px 10px;
374
- border-radius: 999px;
375
- cursor: pointer;
376
- white-space: nowrap;
377
- transition: background 0.15s ease, color 0.15s ease;
378
- }
379
- .feed-mode-btn:hover:not(.active) {
380
- background: var(--subtle-background, rgba(0, 0, 0, 0.05));
381
- }
382
- .feed-mode-btn.active {
383
- background: var(--accent-color, #2563eb);
384
- color: var(--accent-back, #ffffff);
385
- }
386
- .audit-overlay {
387
- position: absolute;
388
- inset: 44px 12px 68px 12px;
389
- z-index: 11;
390
- background: var(--content-background, #fff);
391
- border: 1px solid var(--border-color, #cbd5e1);
392
- border-radius: 10px;
393
- box-shadow: 0 6px 24px rgba(0,0,0,0.14);
394
- display: flex;
395
- overflow: hidden;
396
- }
397
- .audit-sidebar {
398
- width: 260px;
399
- flex-shrink: 0;
400
- border-right: 1px solid var(--subtle-border, #e2e8f0);
401
- overflow-y: auto;
402
- padding: 8px;
403
- display: flex;
404
- flex-direction: column;
405
- gap: 4px;
406
- background: var(--subtle-background, #f8fafc);
407
- box-sizing: border-box;
408
- }
409
- .audit-messages {
410
- flex: 1 1 auto;
411
- min-width: 0;
412
- min-height: 0;
413
- display: flex;
414
- flex-direction: column;
415
- overflow-y: auto;
416
- padding: 12px 16px;
417
- gap: 8px;
418
- }
419
- .participants-popover {
420
- position: absolute;
421
- top: 44px;
422
- right: 12px;
423
- z-index: 12;
424
- width: min(280px, calc(100vw - 24px));
425
- max-height: min(360px, 60dvh);
426
- overflow-y: auto;
427
- background: var(--content-background, #fff);
428
- border: 1px solid var(--border-color, #cbd5e1);
429
- border-radius: 10px;
430
- box-shadow: 0 6px 20px rgba(0,0,0,0.16);
431
- padding: 10px 12px;
432
- display: flex;
433
- flex-direction: column;
434
- gap: 8px;
435
- font-size: 12.5px;
436
- box-sizing: border-box;
437
- }
438
- .chat-composer {
439
- z-index: 10;
440
- max-height: 50%;
441
- overflow: visible;
442
- padding-bottom: var(--safe-bottom, 0px);
443
- }
444
- @media (max-width: 768px) {
445
- .feed-top-bar {
446
- padding: 4px 8px;
447
- }
448
- .feed-mode-bar {
449
- max-width: 100%;
450
- overflow-x: auto;
451
- }
452
- .audit-overlay {
453
- inset: 42px 6px 64px 6px;
454
- flex-direction: column;
455
- }
456
- .audit-sidebar {
457
- width: 100%;
458
- max-height: 36%;
459
- border-right: none;
460
- border-bottom: 1px solid var(--subtle-border, #e2e8f0);
461
- }
462
- .participants-popover {
463
- left: 8px;
464
- right: 8px;
465
- width: auto;
466
- }
467
- }
468
- </style>
469
-
470
- <style>
471
- ::-webkit-scrollbar {
472
- width: 4px;
473
- height: 4px;
474
- }
475
- ::-webkit-scrollbar-thumb {
476
- background-color: transparent;
477
- }
478
- ::-webkit-scrollbar-thumb:hover {
479
- background-color: transparent;
480
- }
481
- ::-webkit-scrollbar-track {
482
- background-color: transparent;
483
- }
484
- </style>
485
- <div class="back"></div>
486
- <div class="feed-top-bar" ~if="showFeedModeToggle || ($item && $item.type !== '$user')">
487
- <div class="feed-mode-bar" ~if="showFeedModeToggle">
488
- <button type="button" class="feed-mode-btn" ~class="{ active: feedMode === 'dialog' }" @tap="setFeedMode('dialog')" title="Мой диалог и задачи с Агентом этого узла">Диалог</button>
489
- <button type="button" class="feed-mode-btn" ~class="{ active: feedMode === 'local' }" @tap="setFeedMode('local')" title="Местный лог открытой точки (доступно только BOSS)">Местный лог</button>
490
- <button type="button" class="feed-mode-btn" ~class="{ active: feedMode === 'audit' }" @tap="setFeedMode('audit')" title="Взаимодействия пользователей и клиентов с Агентом (доступно только BOSS)">Взаимодействия</button>
491
- </div>
492
- <div class="feed-mode-bar" ~if="$item && $item.type !== '$user'">
493
- <button type="button" class="feed-mode-btn" ~class="{ active: showParticipants }" @tap="toggleParticipants()" title="Участники и рабочие места подразделения">Участники ({{participantsCount}})</button>
494
- </div>
495
- </div>
496
- <div ~if="feedMode === 'audit' && showFeedModeToggle" class="audit-overlay">
497
- <div class="audit-sidebar">
498
- <div style="font-size:12px;font-weight:700;padding:4px 6px;color:var(--muted-color);">Диалоги с Агентом ({{auditThreads.length}})</div>
499
- <div ~if="!auditThreads.length" style="font-size:12.5px;color:var(--muted-color);padding:8px 6px;">Взаимодействий пока нет</div>
500
- <div ~for="auditThreads" @tap="openAuditThread($for.item)" ~class="{ active: auditSelectedId === $for.item.id }" style="padding:7px 9px;border-radius:7px;cursor:pointer;border:1px solid var(--subtle-border,transparent);background:var(--content-background,#fff);font-size:12.5px;">
501
- <div style="font-weight:600;display:flex;justify-content:space-between;gap:6px;">
502
- <span>{{$for.item.peerLabel}}</span>
503
- <span style="font-size:11px;opacity:0.7;">{{$for.item.messageCount}}</span>
504
- </div>
505
- <div ~if="$for.item.lastMessage" style="font-size:11.5px;color:var(--muted-color);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-top:2px;">{{$for.item.lastMessage.content || ($for.item.lastMessage.taskPath ? 'Задача' : 'Вложение')}}</div>
506
- </div>
507
- </div>
508
- <div class="audit-messages">
509
- <div ~if="!auditSelectedId" style="color:var(--muted-color);font-size:13px;margin:auto;">Выберите пользователя для просмотра истории взаимодействия с Агентом</div>
510
- <div ~for="auditMessages" style="padding:8px 11px;border-radius:8px;border:1px solid var(--subtle-border,#e2e8f0);background:var(--subtle-background,#f8fafc);font-size:13px;">
511
- <div style="font-size:11px;color:var(--muted-color);display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap;margin-bottom:3px;">
512
- <b>{{$for.item.sender === '$twin' ? 'Агент узла' : $for.item.sender}}</b>
513
- <span>{{new Date($for.item.created).toLocaleString()}}</span>
514
- </div>
515
- <div style="white-space:pre-wrap;word-break:break-word;">{{$for.item.content || ($for.item.taskPath ? 'Задача: ' + $for.item.taskPath : '')}}</div>
516
- <div ~if="$for.item.kind === 'approval'" style="display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin-top:6px;">
517
- <span ~if="$for.item.meta?.status === 'approved'" style="font-size:11.5px;font-weight:700;color:#059669;">✓ Утверждено</span>
518
- <span ~if="$for.item.meta?.status === 'rejected'" style="font-size:11.5px;font-weight:700;color:#dc2626;">✕ Отклонено</span>
519
- <oda-button ~if="$for.item.meta?.status === 'pending'" icon="icons:check" info-invert @tap="resolveApprovalMsg($for.item, 'approve')">Утвердить</oda-button>
520
- <oda-button ~if="$for.item.meta?.status === 'pending'" icon="icons:close" @tap="resolveApprovalMsg($for.item, 'reject')">Отклонить</oda-button>
521
- </div>
522
- </div>
523
- </div>
524
- </div>
525
- <div ~if="showParticipants && $item && $item.type !== '$user'" class="participants-popover">
526
- <div style="display:flex;align-items:center;justify-content:space-between;font-weight:700;">
527
- <span>Участники ({{participantsCount}})</span>
528
- <oda-button icon="icons:close" :icon-size="14" @tap="showParticipants = false"></oda-button>
529
- </div>
530
- <div ~if="!participantsList.length" style="color:var(--muted-color);">Назначенных участников нет</div>
531
- <div ~for="participantsList" @tap="openParticipant($for.item)" style="display:flex;align-items:center;gap:8px;padding:5px 7px;border-radius:7px;cursor:pointer;border:1px solid var(--subtle-border,transparent);">
532
- <item-icon :$item="$for.item" icon-size="22" default="icons:person"></item-icon>
533
- <div style="flex:1;min-width:0;">
534
- <div style="font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">{{$for.item.label || $for.item.id}}</div>
535
- <div ~if="$for.item._placeLabel" style="font-size:11px;color:var(--muted-color);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">{{$for.item._placeLabel}}</div>
536
- </div>
537
- </div>
538
- </div>
539
- <chat-ribbon id="ribbon" :$item @chat-item-expanded="onCardExpanded($event)"></chat-ribbon>
540
- <div class="mover" vertical hidden>
541
- <oda-button :hidden="$('#ribbon').scrollTop < 0" content shadow icon="icons:chevron-right:270" @tap="$('#ribbon').scrollTop = -($('#ribbon').scrollHeight)"></oda-button>
542
- <oda-button :hidden="$('#ribbon').scrollTop > 0" content shadow icon="icons:chevron-right:90" @tap="$('#ribbon').scrollTop = 0"></oda-button>
543
- </div>
544
- <div vertical shadow content :hidden="hasExpandedCard" class="chat-composer">
545
- <div ~if="replyTarget" horizontal accent-invert style="padding: 4px;">
546
- <div horizontal flex style="overflow: auto; align-self: center;"></div>
547
- <oda-button icon="icons:close" @tap="clear" style="padding: 0"></oda-button>
548
- </div>
549
- <div ~if="replyTarget" light vertical style="overflow-y: auto;" disabled>
550
- <chat-item reply :$file="replyTarget"></chat-item>
551
- </div>
552
- <microchat-voice ~if="voiceOn"></microchat-voice>
553
- <work-prompt-bar style="margin: 8px;" @tap="focusedItem = null"
554
- ::value ::files :ai="isAIMode" :placeholder :pending="awaitTask"
555
- ::model ::tts-mode ::receivers :dept-users="deptUsers" :operation-classes="operationClasses" :show-tts="true"
556
- @receivers-changed="onReceiversChanged($event)" @create-operation="onCreateOperation($event)"
557
- @send="onBarSend" @stop="onBarStop" @clear="clear" @prompt-key="_onPromptKey"></work-prompt-bar>
558
- </div>
559
- `,
560
- get background(){
561
- return `linear-gradient(145deg, var(--info-background), var(--info-color))`
562
- },
563
- get url(){
564
- if(this.$pdp.$handler)
565
- return this.$pdp.$handler.short + '/~/background.jpg';
566
- },
567
- files: [],
568
- hasExpandedCard: false,
569
- onCardExpanded(e) {
570
- const detail = e?.detail || {};
571
- this._expandedCards ??= new Set();
572
- if (detail.card) {
573
- if (detail.expanded)
574
- this._expandedCards.add(detail.card);
575
- else
576
- this._expandedCards.delete(detail.card);
577
- for (const c of [...this._expandedCards]) {
578
- if (!c.isConnected || !c.expanded)
579
- this._expandedCards.delete(c);
580
- }
581
- this.hasExpandedCard = this._expandedCards.size > 0;
582
- }
583
- else {
584
- this.hasExpandedCard = Boolean(detail.expanded);
585
- }
586
- },
587
- get placeholder(){
588
- if(this.$pdp.receivers.length)
589
- return 'Сообщение для ' + this.$pdp.receivers.map(user => user.label).join(', ') + ' ...';
590
- return 'Новая задача для ИИ ...'
591
- },
592
- get isAIMode(){
593
- const isForeign = this.$pdp?.isPrivate && this.$pdp?.$item?.id !== WORK.uid;
594
- const hasReceivers = !!(this.$pdp?.receivers?.length);
595
- return !isForeign && !hasReceivers;
596
- },
597
- get receivers(){
598
- return this.$pdp.receivers;
599
- },
600
- set receivers(v) {
601
- if (this.$pdp)
602
- this.$pdp.receivers = Array.isArray(v) ? v : [];
603
- },
604
- get deptUsers() {
605
- return this.$pdp?.deptUsers || [];
606
- },
607
- get operationClasses() {
608
- return this.$pdp?.operationClasses || [];
609
- },
610
- onReceiversChanged(e) {
611
- const list = e?.detail?.value ?? e?.detail ?? [];
612
- if (this.$pdp)
613
- this.$pdp.receivers = Array.isArray(list) ? list : [];
614
- },
615
- async onCreateOperation(e) {
616
- const d = e?.detail?.value ?? e?.detail ?? {};
617
- const path = d.path || d;
618
- if (!path || typeof path !== 'string') return;
619
- const clsItem = await WORK.get_item(path).catch(() => null);
620
- if (!clsItem) return;
621
- const unit = this.$pdp?.$item?.short || this.$pdp?.$item?.path || '';
622
- const title = clsItem.DATA?.label || clsItem.label || clsItem.id || path.split('/').pop() || 'Операция';
623
- const fmtNew = globalThis.__workClassPicker?.formatNewObjectLabel || globalThis.WORK?.formatNewObjectLabel;
624
- const newLabel = typeof fmtNew === 'function' ? fmtNew(title) : `Новое ${title.toLowerCase()}`;
625
- const nav = {
626
- view: 'object',
627
- create: true,
628
- unit,
629
- label: newLabel,
630
- };
631
- if (window.top && window.top !== window && typeof window.top.execute === 'function') {
632
- await window.top.execute(clsItem, nav);
633
- return;
634
- }
635
- let formHost = null;
636
- for (let p = this; p; p = p.parentElement || p.domHost || p.getRootNode?.()?.host) {
637
- if (typeof p.openInForm === 'function') {
638
- formHost = p;
639
- break;
640
- }
641
- }
642
- if (!formHost) {
643
- const pf = document.querySelector?.('pages-form');
644
- formHost = pf?.$?.('work-form') || pf || document.querySelector?.('work-form');
645
- }
646
- if (formHost && typeof formHost.openInForm === 'function') {
647
- await formHost.openInForm(clsItem, nav);
648
- }
649
- else if (typeof window.top?.execute === 'function') {
650
- window.top.execute(clsItem, nav);
651
- }
652
- },
653
- model: {
654
- $def: '',
655
- set(n) {
656
- if (!n) return;
657
- setUserPreferredModel(n);
658
- },
659
- },
660
- get $saveKey(){
661
- return this.$item?.short;
662
- },
663
- get modelItem(){
664
- return this.model ? WORK.get_item(this.model) : null;
665
- },
666
- clear(e){
667
- this.value = '';
668
- this.files = [];
669
- this.$pdp.replyTarget = null;
670
- this.$pdp.files = [];
671
- this.$('#ribbon').lastIdxHistory = -1;
672
- this.focusInput();
673
- },
674
- $public:{
675
- showDatePanel: {
676
- $def: false,
677
- $save: true
678
- }
679
- },
680
- onBarSend(e){
681
- if (this.skillSelectMode) {
682
- this.value = '@' + this.$('skill-tree').focusedItem.name;
683
- this.$('skill-tree').executed = true;
684
- return;
685
- }
686
- this.send();
687
- },
688
- onBarStop() {
689
- // Пока send в полёте — стоп не снимает ожидание карточки: это может быть
690
- // второй клик по send, а не осознанный отказ от ожидания.
691
- if (this._sending)
692
- return;
693
- this.awaitTask = false;
694
- this._awaitingLogExpand = false;
695
- },
696
- async _onPromptKey(e){
697
- e = e?.detail instanceof Event ? e.detail : e;
698
- if (e.keyCode === 38 || e.code === 'ArrowUp') {
699
- this.value = await this.$('chat-ribbon').getFromHistory(this.value, -1);
700
- this.$('work-prompt-bar')?.selectInput();
701
- }
702
- else if (e.keyCode === 40 || e.code === 'ArrowDown') {
703
- this.value = await this.$('chat-ribbon').getFromHistory(this.value, 1);
704
- this.$('work-prompt-bar')?.selectInput();
705
- }
706
- },
707
- value: {
708
- $def: ''
709
- },
710
- replyTarget: {
711
- $der: null,
712
- set(n){
713
- this.focusInput();
714
- }
715
- },
716
- attached(){
717
- this.async(()=>{
718
- this.focusInput();
719
- }, 100);
720
- this.$pdp?._hydrateModel?.();
721
- this._geo();
722
- this._bindChatSocket();
723
- this._bindTaskMoved();
724
- },
725
- detached() {
726
- if (this._onWsChatMsg && globalThis.WORK?.chatEvents) {
727
- globalThis.WORK.chatEvents.removeEventListener('chat:message', this._onWsChatMsg);
728
- globalThis.WORK.chatEvents.removeEventListener('chat:action', this._onWsChatMsg);
729
- globalThis.WORK.chatEvents.removeEventListener('task.moved', this._onWsTaskMoved);
730
- this._onWsChatMsg = null;
731
- this._onWsTaskMoved = null;
732
- }
733
- if (this._onLocalTaskMoved) {
734
- this.removeEventListener('work-task-moved', this._onLocalTaskMoved);
735
- this._onLocalTaskMoved = null;
736
- }
737
- },
738
- _bindTaskMoved() {
739
- if (!this._onLocalTaskMoved) {
740
- this._onLocalTaskMoved = (ev) => this._handleTaskMoved(ev?.detail, { navigate: true });
741
- this.addEventListener('work-task-moved', this._onLocalTaskMoved);
742
- }
743
- if (!this._onWsTaskMoved) {
744
- globalThis.WORK.chatEvents ??= new EventTarget();
745
- this._onWsTaskMoved = (ev) => this._handleTaskMoved(ev?.detail, { navigate: false });
746
- globalThis.WORK.chatEvents.addEventListener('task.moved', this._onWsTaskMoved);
747
- }
748
- },
749
- async _handleTaskMoved(moved, { navigate = false } = {}) {
750
- if (!moved?.newPath)
751
- return;
752
- const oldPath = String(moved.oldPath || '');
753
- const key = oldPath + '->' + moved.newPath;
754
- const oldKey = taskKeyOf(oldPath);
755
- const ribbon = this.$('#ribbon');
756
- const curPath = String(this.$item?.path || '/').replace(/\/+$/, '') || '/';
757
- const isSourceChat = Boolean(oldPath && (oldPath === curPath || oldPath.startsWith((curPath === '/' ? '' : curPath) + '/')));
758
- if (isSourceChat || navigate) {
759
- if (moved.mode === 'move' && oldKey && ribbon) {
760
- for (const d of ribbon.$$('chat-day') || []) {
761
- d._adopted?.delete?.(oldKey);
762
- if (Array.isArray(d.logItems))
763
- d.logItems = d.logItems.filter(it => !d._isMatchingTaskItem?.(it, oldKey));
764
- }
765
- }
766
- await ribbon?.refreshFeed?.();
767
- }
768
- if (!navigate || this._navigatedMoveKey === key)
769
- return;
770
- this._navigatedMoveKey = key;
771
- const targetNodePath = String(moved.targetNodePath || '/').trim() || '/';
772
- let targetItem = null;
773
- try {
774
- targetItem = targetNodePath === '/' ? globalThis.WORK : await globalThis.WORK.get_item(targetNodePath);
775
- if (Array.isArray(targetItem))
776
- targetItem = targetItem[targetItem.length - 1] || null;
777
- }
778
- catch {
779
- targetItem = null;
780
- }
781
- if (!targetItem)
782
- return;
783
- const nav = { view: 'chat', openTaskPath: moved.newPath };
784
- if (window.top && window.top !== window && typeof window.top.execute === 'function') {
785
- await window.top.execute(targetItem, nav);
786
- return;
787
- }
788
- let formHost = null;
789
- for (let p = this; p; p = p.parentElement || p.domHost || p.getRootNode?.()?.host) {
790
- if (typeof p.openInForm === 'function') {
791
- formHost = p;
792
- break;
793
- }
794
- }
795
- if (!formHost) {
796
- const pf = document.querySelector?.('pages-form');
797
- formHost = pf?.$?.('work-form') || pf || document.querySelector?.('work-form');
798
- }
799
- if (formHost && typeof formHost.openInForm === 'function')
800
- await formHost.openInForm(targetItem, nav);
801
- else if (typeof window.execute === 'function')
802
- await window.execute(targetItem, nav);
803
- },
804
- async openMovedTask(path) {
805
- if (!path)
806
- return;
807
- const ribbon = this.$('#ribbon');
808
- if (!ribbon)
809
- return;
810
- await ribbon.refreshDates?.(true);
811
- await this._openCreated(path);
812
- },
813
- _bindChatSocket() {
814
- if (this._onWsChatMsg)
815
- return;
816
- globalThis.WORK.chatEvents ??= new EventTarget();
817
- this._onWsChatMsg = (ev) => {
818
- const d = ev?.detail;
819
- const cur = this.$item;
820
- if (!d || !cur)
821
- return;
822
- const curPath = String(cur.path || '/').replace(/\/+$/, '') || '/';
823
- const hitTwin = d.kind === 'twin' && d.nodePath === curPath;
824
- const hitDm = d.kind === 'dm' && cur.type === '$user' && (d.message?.sender === cur.id || d.message?.sender === WORK.uid);
825
- const hitThread = d.threadId && this.$('#ribbon')?._threadId === d.threadId;
826
- if (hitTwin || hitDm || hitThread) {
827
- this.$('#ribbon')?.refreshFeed?.();
828
- if (d.threadId && ev.type === 'chat:message') {
829
- cur.fetch?.('chat_mark_read', { threadId: d.threadId })
830
- ?.then?.(res => WORK.applyChatReadLocal?.(res || { threadId: d.threadId, kind: d.kind, nodePath: curPath, peerId: cur.type === '$user' ? cur.id : '' }))
831
- ?.catch?.(() => {});
832
- }
833
- }
834
- };
835
- globalThis.WORK.chatEvents.addEventListener('chat:message', this._onWsChatMsg);
836
- globalThis.WORK.chatEvents.addEventListener('chat:action', this._onWsChatMsg);
837
- },
838
- focusInput(){
839
- this.$('work-prompt-bar')?.focusInput();
840
- },
841
- focusedItem: null,
842
- feedMode: 'dialog',
843
- showParticipants: false,
844
- _canLocalFeed: false,
845
- get participantsList() {
846
- return Array.isArray(this.$pdp?.deptUsers) ? this.$pdp.deptUsers : [];
847
- },
848
- get participantsCount() {
849
- return this.participantsList.length;
850
- },
851
- toggleParticipants() {
852
- this.showParticipants = !this.showParticipants;
853
- },
854
- openParticipant(u) {
855
- if (!u?.id || typeof window?.execute !== 'function')
856
- return;
857
- this.showParticipants = false;
858
- window.execute(u);
859
- },
860
- get showFeedModeToggle() {
861
- return Boolean(this.$item && this.$item.type !== '$user' && this._canLocalFeed);
862
- },
863
- async _refreshCanLocalFeed(item = this.$item) {
864
- if (!item || item.type === '$user') {
865
- this._canLocalFeed = false;
866
- return;
867
- }
868
- if (globalThis.WORK?.DEV_MODE) {
869
- this._canLocalFeed = true;
870
- return;
871
- }
872
- const key = (item.path || '') + '|' + (item.id || '');
873
- try {
874
- const cached = item.myRoles;
875
- const roles = await Promise.resolve(cached !== undefined ? cached : item.fetch?.('roles')).catch(() => []);
876
- const curKey = (this.$item?.path || '') + '|' + (this.$item?.id || '');
877
- if (curKey !== key)
878
- return;
879
- this._canLocalFeed = Array.isArray(roles) && roles.includes('BOSS');
880
- }
881
- catch {
882
- const curKey = (this.$item?.path || '') + '|' + (this.$item?.id || '');
883
- if (curKey === key)
884
- this._canLocalFeed = false;
885
- }
886
- },
887
- auditThreads: [],
888
- auditSelectedId: '',
889
- auditMessages: [],
890
- setFeedMode(mode) {
891
- const next = (mode === 'local' || mode === 'audit') && this.showFeedModeToggle ? mode : 'dialog';
892
- if (this.feedMode === next)
893
- return;
894
- this.feedMode = next;
895
- if (next === 'audit') {
896
- this.loadAuditThreads();
897
- return;
898
- }
899
- this.$('#ribbon')?.refreshFeed?.();
900
- },
901
- async loadAuditThreads() {
902
- if (!this.$item?.fetch)
903
- return;
904
- try {
905
- const list = await this.$item.fetch('chat_threads_list', { mode: 'audit' });
906
- const raw = Array.isArray(list) ? list : [];
907
- const uids = [...new Set(raw.flatMap(t => (t.participants || []).map(p => p.uid)).filter(Boolean))];
908
- const users = uids.length && typeof WORK.usersByIds === 'function' ? await WORK.usersByIds(uids).catch(() => []) : [];
909
- const nameMap = Object.fromEntries((users || []).filter(Boolean).map(u => [u.id, u.label || u.DATA?.label || u.id]));
910
- this.auditThreads = raw.map(t => {
911
- const peer = (t.participants || []).find(p => p.uid !== '$twin') || t.participants?.[0];
912
- const roleHint = peer?.role === 'client' ? ' (Клиент)' : '';
913
- return {
914
- ...t,
915
- peerLabel: (nameMap[peer?.uid] || peer?.uid || t.title || t.id) + roleHint,
916
- };
917
- });
918
- if (this.auditThreads.length && !this.auditSelectedId)
919
- await this.openAuditThread(this.auditThreads[0]);
920
- }
921
- catch {
922
- this.auditThreads = [];
923
- }
924
- },
925
- async openAuditThread(thread) {
926
- if (!thread?.id || !this.$item?.fetch)
927
- return;
928
- this.auditSelectedId = thread.id;
929
- try {
930
- const res = await this.$item.fetch('chat_messages_list', { threadId: thread.id, limit: 100 });
931
- this.auditMessages = Array.isArray(res?.messages) ? res.messages : [];
932
- }
933
- catch {
934
- this.auditMessages = [];
935
- }
936
- },
937
- async resolveApprovalMsg(msg, action) {
938
- if (!msg?.id || !this.auditSelectedId || !this.$item?.fetch)
939
- return;
940
- try {
941
- await this.$item.fetch('chat_action', { threadId: this.auditSelectedId, messageId: msg.id, action });
942
- await this.openAuditThread({ id: this.auditSelectedId });
943
- }
944
- catch { /* ignore */ }
945
- },
946
- async _ownCabinet() {
947
- const uid = globalThis.WORK?.uid;
948
- if (!uid || typeof globalThis.WORK?.get_item !== 'function')
949
- return null;
950
- return globalThis.WORK.get_item('/USERS//' + uid).catch(() => null);
951
- },
952
- _isAccessError(err) {
953
- return /доступ запрещ|forbidden|\b403\b/i.test(String(err?.message || err || ''));
954
- },
955
- async _runWithCabinetFallback(fn) {
956
- const primary = this.$pdp?.$item || this.$item;
957
- return { target: primary, result: await fn(primary) };
958
- },
959
- $item: {
960
- $def: null,
961
- set(n) {
962
- const changed = Boolean(this._prevItem && this._prevItem !== n);
963
- this._prevItem = n;
964
- this.feedMode = 'dialog';
965
- this._canLocalFeed = false;
966
- this._refreshCanLocalFeed(n);
967
- if (changed)
968
- this.$('#ribbon')?.refreshFeed?.();
969
- }
970
- },
971
- taskItem: null,
972
- data: null,
973
- streams: {},
974
- status: 'idle',
975
- __microchatShell: true,
976
- voiceOn: {
977
- $def: false,
978
- set(v) {
979
- this.async(() => {
980
- const bar = this.$('work-prompt-bar');
981
- if (!v || !this._voice) {
982
- bar?.setDialogLevel?.(0);
983
- return;
984
- }
985
- this._voice.addEventListener('level', e => { if (this._voice?.state !== 'speaking') bar?.setDialogLevel?.(e.detail); });
986
- this._voice.addEventListener('speechlevel', e => { if (this._voice?.state === 'speaking') bar?.setDialogLevel?.(e.detail); });
987
- });
988
- },
989
- },
990
- get canVoice() {
991
- return !!(navigator.mediaDevices?.getUserMedia || window.SpeechRecognition || window.webkitSpeechRecognition);
992
- },
993
- toast(msg) {
994
- ODA.showMessage?.(String(msg || ''));
995
- },
996
- async toggleVoice(on) {
997
- const want = typeof on === 'boolean' ? on : !this.voiceOn;
998
- if (!want) {
999
- this._voice?.disable();
1000
- this.voiceOn = false;
1001
- return;
1002
- }
1003
- await Promise.all([
1004
- import('/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/voice-ui.js'),
1005
- import('/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/voice.js').then(m => { this._VoiceController = m.VoiceController; }),
1006
- ]);
1007
- if (!this._VoiceController)
1008
- return;
1009
- this._voice ??= new this._VoiceController(this);
1010
- this.voiceOn = await this._voice.enable();
1011
- },
1012
- async sendVoiceText(text, { voice = true, interrupt = true, spokenText } = {}) {
1013
- text = String(text ?? '').trim();
1014
- if (!text)
1015
- return;
1016
- if (this.taskItem) {
1017
- let tz = '';
1018
- try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; } catch { /* ignore */ }
1019
- const geo = await Promise.race([
1020
- Promise.resolve(this._geo?.()).catch(() => null),
1021
- new Promise(r => setTimeout(() => r(this._geoFix || null), 150)),
1022
- ]);
1023
- const location = (geo && geo.lat != null && geo.lon != null)
1024
- ? { lat: geo.lat, lon: geo.lon, ...(tz ? { tz } : {}) }
1025
- : (tz ? { tz } : null);
1026
- const payload = JSON.stringify({
1027
- prompt: text,
1028
- attachments: [],
1029
- ...(location ? { location, ...(tz ? { tz } : {}) } : {}),
1030
- ...(voice ? { voice: true } : {}),
1031
- ...(interrupt ? { interrupt: true } : {}),
1032
- ...(spokenText !== undefined ? { spokenText } : {}),
1033
- });
1034
- await this.taskItem.fetch('prompt', {}, payload);
1035
- return;
1036
- }
1037
- await this._createTask({ text, files: [], draft: { value: '', files: [], reply: null }, voice: true });
1038
- },
1039
- awaitTask: false,
1040
- ttsMode: {
1041
- $def: 'off',
1042
- $save: true,
1043
- },
1044
- async send(){
1045
- // Один send за раз: повторные Enter/клики игнорируются, иначе каждый клик создаст свою задачу-дубликат.
1046
- if (this._sending)
1047
- return;
1048
- const files = this.$('work-prompt-bar')?.files ?? this.files;
1049
- if (!(this.value || files.length)) return;
1050
- chatDebug('send: клик');
1051
- this.$('#ribbon').scrollDown = true;
1052
-
1053
- const text = String(this.value ?? '').trim();
1054
- const list = [...files];
1055
- // Черновик на случай сбоя: поле очищается до сохранения — при ошибке вернуть текст и вложения.
1056
- const draft = { value: this.value, files: list, reply: this.$pdp.replyTarget };
1057
- this._sending = true;
1058
-
1059
- try {
1060
- if (this.isAIMode) {
1061
- // экран «создаю задачу» — сразу, до любых запросов: человек видит, что процесс пошёл
1062
- this.clear();
1063
- await this._createTask({ text, files: list, draft });
1064
- } else {
1065
- const params = { encoding: 'utf-8' };
1066
- if (WORK.uid)
1067
- params.sender = WORK.uid;
1068
- if (this.$pdp.isPrivate && this.$pdp.$item.id !== WORK.uid)
1069
- params.receivers = [this.$pdp.$item.id];
1070
- else if (this.$pdp.receivers.length)
1071
- params.receivers = this.$pdp.receivers.map(u => u.id);
1072
- const uploadedPaths = [];
1073
- const isForeignDm = Boolean(this.$pdp.isPrivate && this.$pdp.$item?.id && this.$pdp.$item.id !== WORK.uid);
1074
- const runWrite = typeof this._runWithCabinetFallback === 'function'
1075
- ? fn => this._runWithCabinetFallback(fn)
1076
- : async fn => ({ target: this.$pdp.$item, result: await fn(this.$pdp.$item) });
1077
- await runWrite(async target => {
1078
- uploadedPaths.length = 0;
1079
- const uploadTarget = isForeignDm ? ((await this._ownCabinet()) || target) : target;
1080
- if (list.length) {
1081
- const formData = new FormData();
1082
- for (const file of list)
1083
- formData.append('file', file, file.name);
1084
- const fileParams = (text || isForeignDm) ? { ...params, ignore_save_logs: true } : params;
1085
- const savedLogs = await uploadTarget.save_files(formData, fileParams);
1086
- const arr = Array.isArray(savedLogs) ? savedLogs : (savedLogs ? [savedLogs] : []);
1087
- for (const l of arr) {
1088
- const p = await pathOfLog(l);
1089
- if (p)
1090
- uploadedPaths.push(p.startsWith('/') ? p : '/' + p);
1091
- }
1092
- }
1093
- if (text && !isForeignDm) {
1094
- const msgParams = { ...params, message: text };
1095
- if (uploadedPaths.length)
1096
- msgParams.includes = JSON.stringify(uploadedPaths);
1097
- await target.fetch('save_message', msgParams);
1098
- }
1099
- const chatTarget = this.$pdp.$item || target;
1100
- if (chatTarget?.fetch && (text || uploadedPaths.length)) {
1101
- const chatPayload = {
1102
- kind: this.$pdp.isPrivate ? 'dm' : 'twin',
1103
- ...(this.$pdp.isPrivate ? { peerId: this.$pdp.$item?.id || WORK.uid } : {}),
1104
- message: text,
1105
- attachments: uploadedPaths.map(p => ({ path: p, name: p.split('/').pop() || 'file' })),
1106
- };
1107
- await chatTarget.fetch('chat_send', {}, JSON.stringify(chatPayload))?.catch?.(() => {});
1108
- }
1109
- });
1110
- this.clear();
1111
- this.$('#ribbon')?.refreshFeed?.();
1112
- }
1113
- } catch (err) {
1114
- console.warn('[chat] send', err);
1115
- // Сбой — черновик не теряем: текст и вложения обратно в поле.
1116
- this.value = draft.value;
1117
- this.files = draft.files;
1118
- this.$pdp.replyTarget = draft.reply;
1119
- ODA.showMessage?.('Не удалось отправить: ' + (err?.message || err));
1120
- this.focusInput();
1121
- }
1122
- finally {
1123
- this._sending = false;
1124
- }
1125
- this.$('#ribbon').scrollDown = true;
1126
- },
1127
- _collectKnownLogKeys() {
1128
- const ribbon = this.$('#ribbon');
1129
- const known = new Set();
1130
- for (const d of ribbon?.$$?.('chat-day') || []) {
1131
- for (const it of d.logItems || []) {
1132
- if (it?.id)
1133
- known.add(String(it.id));
1134
- const tk = taskKeyOf(it?.logRow?.path || it?.path || it?.id);
1135
- if (tk)
1136
- known.add(tk);
1137
- }
1138
- }
1139
- return known;
1140
- },
1141
- /**
1142
- * Создание задачи: экран «создаю» → вложения → сохранение → явный запуск агента → карточка открыта по пути из ответа.
1143
- * resume — задача уже создана (повтор запуска после сбоя), второй не создаётся.
1144
- */
1145
- async _createTask({ text, files, draft, voice = false }) {
1146
- this.awaitTask = true;
1147
- this._awaitingLogExpand = false;
1148
- this._awaitTaskPath = '';
1149
- this._awaitTaskKey = '';
1150
- this._awaitKnown = this._collectKnownLogKeys?.() || new Set();
1151
- clearTimeout(this._awaitTimer);
1152
- const item = this.$pdp.$item;
1153
- try {
1154
- const rawName = String(text || '').trim() || (files || []).map(f => f?.name).filter(Boolean).join(', ');
1155
- const name = String(rawName).replace(/[<>:"/\\|?*\n\r]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 90) || 'task';
1156
- const useVoice = voice || !!this.voiceOn;
1157
- let tz = '';
1158
- try { tz = Intl.DateTimeFormat().resolvedOptions().timeZone || ''; } catch { /* ignore */ }
1159
- this._geo?.();
1160
- const root = globalThis.top || globalThis;
1161
- let geo = this._geoFix || root.__workGeoFix || null;
1162
- if (!geo) {
1163
- try {
1164
- const raw = globalThis.localStorage?.getItem?.('WORK.geo-fix');
1165
- if (raw)
1166
- geo = JSON.parse(raw);
1167
- } catch { /* ignore */ }
1168
- }
1169
- const location = (geo && geo.lat != null && geo.lon != null)
1170
- ? { lat: geo.lat, lon: geo.lon, ...(tz ? { tz } : {}) }
1171
- : (tz ? { tz } : null);
1172
- const body = {
1173
- name,
1174
- ...(text ? {} : { prompt: '' }),
1175
- created: Date.now(),
1176
- items: [],
1177
- ...(location ? { location, ...(tz ? { tz } : {}) } : {}),
1178
- ...(useVoice ? { voice: true } : {}),
1179
- };
1180
- if (this.model)
1181
- body.model = this.model;
1182
- const params = {
1183
- encoding: 'utf-8',
1184
- ...(text ? {} : { prompt: '' }),
1185
- ...(location ? { location: JSON.stringify(location), ...(tz ? { tz } : {}) } : {}),
1186
- ...(useVoice ? { voice: true } : {}),
1187
- };
1188
- if (globalThis.WORK?.uid)
1189
- params.sender = globalThis.WORK.uid;
1190
- const canLookupTask = typeof globalThis.WORK?.get_item === 'function';
1191
- const runWrite = typeof this._runWithCabinetFallback === 'function'
1192
- ? fn => this._runWithCabinetFallback(fn)
1193
- : async fn => ({ target: item, result: await fn(item) });
1194
- const { target: writeTarget, result: log } = await runWrite(async targetItem => {
1195
- const saveParams = { ...params };
1196
- if (files.length && !canLookupTask) {
1197
- const preAttachments = [];
1198
- await Promise.all(files.map(async file => {
1199
- const fLog = await targetItem.save_file(file, { encoding: 'utf-8', ignore_save_logs: true });
1200
- const fPath = await pathOfLog(fLog);
1201
- if (fPath)
1202
- preAttachments.push({ path: fPath.startsWith('/') ? fPath : '/' + fPath, name: file.name });
1203
- }));
1204
- if (preAttachments.length) {
1205
- saveParams.includes = JSON.stringify(preAttachments.map(a => a.path));
1206
- saveParams.attachments = JSON.stringify(preAttachments);
1207
- }
1208
- }
1209
- // Сначала создаём саму задачу, чтобы прикреплённые и создаваемые файлы размещались в папке этого таска
1210
- if (files.length && canLookupTask)
1211
- saveParams.skip_file_handler = true;
1212
- return targetItem.save_file(new File([JSON.stringify(body, null, 2)], name + '.task', { type: 'application/json' }), saveParams);
1213
- });
1214
- const path = await pathOfLog(log);
1215
- if (path && files.length && canLookupTask) {
1216
- const createdTask = await globalThis.WORK.get_item(path).catch(() => null);
1217
- const targetHolder = createdTask || writeTarget || item;
1218
- const attachments = [];
1219
- await Promise.all(files.map(async file => {
1220
- const fLog = await targetHolder.save_file(file, { encoding: 'utf-8', ignore_save_logs: true, mainContext: path });
1221
- const fPath = await pathOfLog(fLog);
1222
- if (fPath)
1223
- attachments.push({ path: fPath.startsWith('/') ? fPath : '/' + fPath, name: file.name });
1224
- }));
1225
- if (attachments.length && createdTask) {
1226
- const includePaths = attachments.map(a => a.path);
1227
- await (writeTarget || item).fetch?.('append_log_includes', { entryPath: path, includePaths })?.catch?.(() => {});
1228
- await createdTask.fetch?.('prompt', {}, JSON.stringify({ prompt: text, attachments }))?.catch?.(() => {});
1229
- }
1230
- }
1231
- if (path) {
1232
- const threadItem = this.$pdp?.$item || item;
1233
- threadItem?.fetch?.('chat_send', {}, JSON.stringify({
1234
- kind: threadItem.type === '$user' ? 'dm' : 'twin',
1235
- ...(threadItem.type === '$user' ? { peerId: threadItem.id } : {}),
1236
- message: text,
1237
- taskPath: path,
1238
- }))?.catch?.(() => {});
1239
- this._awaitTaskPath = String(path);
1240
- this._awaitTaskKey = taskKeyOf(path);
1241
- await this._openCreated(path);
1242
- if (useVoice && canLookupTask) {
1243
- const createdTask = await globalThis.WORK.get_item(path).catch(() => null);
1244
- if (createdTask)
1245
- this._bindChatVoiceTask(createdTask);
1246
- }
1247
- }
1248
- else {
1249
- this.awaitTask = true;
1250
- this._awaitNewTask('');
1251
- }
1252
- }
1253
- catch (err) {
1254
- console.warn('[chat] создание задачи', err);
1255
- this.awaitTask = false;
1256
- this._awaitingLogExpand = false;
1257
- ODA.showMessage?.('Не удалось отправить: ' + (err?.message || err));
1258
- this.value = draft.value;
1259
- this.files = draft.files;
1260
- this.$pdp.replyTarget = draft.reply;
1261
- this.focusInput();
1262
- }
1263
- },
1264
- /**
1265
- * Карточка созданной задачи — раскрыта сразу по пути из ответа сервера: .task-файл кладётся в ленту дня
1266
- * (chat-day.adoptTask), события ленты не ждём. Не вышло — прежний путь: ждать запись ленты (_awaitNewTask).
1267
- */
1268
- async _openCreated(path) {
1269
- const ribbon = this.$('#ribbon');
1270
- const day = taskDayOf(path) || new Date().toLocalDay();
1271
- try {
1272
- if (!ribbon.dateList.includes(day)) {
1273
- ribbon.dateList = [...ribbon.dateList, day].sort();
1274
- ribbon.render();
1275
- }
1276
- let dayEl = null;
1277
- for (let i = 0; i < 40 && !dayEl; i++) {
1278
- dayEl = [...(ribbon.$$('chat-day') || [])].find(d => d.day === day);
1279
- if (!dayEl)
1280
- await sleep(50);
1281
- }
1282
- if (!dayEl)
1283
- throw new Error('нет дня в ленте: ' + day);
1284
- const file = await WORK.get_item(path);
1285
- if (!file || Array.isArray(file))
1286
- throw new Error('нет файла задачи: ' + path);
1287
- await dayEl.adoptTask(file);
1288
- this.awaitTask = false;
1289
- this._awaitingLogExpand = false;
1290
- this._awaitTaskPath = '';
1291
- this._awaitTaskKey = '';
1292
- this._awaitKnown = null;
1293
- clearTimeout(this._awaitTimer);
1294
- }
1295
- catch (err) {
1296
- console.warn('[chat] открыть созданную задачу напрямую не вышло — ждём запись ленты:', err?.message || err);
1297
- if (!this._awaitKnown?.size)
1298
- this._awaitKnown = this._collectKnownLogKeys();
1299
- this.awaitTask = true;
1300
- this._awaitNewTask(path);
1301
- }
1302
- },
1303
- _bindChatVoiceTask(task) {
1304
- if (this.taskItem && this._chatTaskH) {
1305
- for (const [k, fn] of Object.entries(this._chatTaskH))
1306
- this.taskItem.unlisten?.(k, fn);
1307
- }
1308
- this.taskItem = task;
1309
- this.streams = {};
1310
- if (!task)
1311
- return;
1312
- const reload = async () => {
1313
- try {
1314
- const raw = await task.load();
1315
- const data = typeof raw === 'string' ? JSON.parse(raw || '{}') : (raw || {});
1316
- this.data = data;
1317
- this.status = data.status || 'idle';
1318
- this._voice?.onData(data);
1319
- }
1320
- catch { /* ignore */ }
1321
- };
1322
- this._chatTaskH = {
1323
- 'changed': () => reload(),
1324
- 'chat.done': () => reload(),
1325
- 'task.state': e => {
1326
- const s = e.detail?.value?.status;
1327
- if (s)
1328
- this.status = s;
1329
- },
1330
- 'task.delta': e => {
1331
- const d = e.detail?.value;
1332
- if (!d?.item || !d.token)
1333
- return;
1334
- const cur = this.streams[d.item] || {};
1335
- const field = d.field === 'reasoning' ? 'reasoning' : 'content';
1336
- this.streams = { ...this.streams, [d.item]: { ...cur, [field]: (cur[field] || '') + d.token } };
1337
- this.status = 'running';
1338
- this._voice?.onDelta({ item: d.item, field });
1339
- },
1340
- };
1341
- for (const [k, fn] of Object.entries(this._chatTaskH))
1342
- task.listen?.(k, fn);
1343
- reload();
1344
- },
1345
- /**
1346
- * Новая задача сохранена: день — из пути файла (…/YYYY-MM-DD/….task), а не из часов браузера.
1347
- * Нет дня в ленте — добавить (chat-day раскроет карточку, пока awaitTask). Страховка: 15 с — снять ожидание.
1348
- * _awaitTaskKey — имя файла задачи: точный ключ карточки (chat-task.js), не зависит от времени и префикса пути.
1349
- */
1350
- _awaitNewTask(path) {
1351
- const day = taskDayOf(path);
1352
- const ribbon = this.$('#ribbon');
1353
- if (day && ribbon && !ribbon.dateList.includes(day)) {
1354
- ribbon.dateList = [...ribbon.dateList, day].sort();
1355
- ribbon.render();
1356
- }
1357
- this._awaitTaskPath = String(path || '');
1358
- this._awaitTaskKey = taskKeyOf(path);
1359
- this._awaitingLogExpand = true;
1360
- // Ретрай: вызываем _expandCreatedTask на всех видимых днях (найдёт по времени).
1361
- for (const el of ribbon?.$$?.('chat-day') || [])
1362
- el?._expandCreatedTask?.();
1363
- clearTimeout(this._awaitTimer);
1364
- this._awaitTimer = setTimeout(() => {
1365
- if (!this.awaitTask)
1366
- return;
1367
- this.awaitTask = false;
1368
- this._awaitingLogExpand = false;
1369
- this._awaitTaskPath = '';
1370
- this._awaitTaskKey = '';
1371
- this._awaitKnown = null;
1372
- ODA.showMessage?.('Задача создана' + (path ? ': ' + path : '') + ' — карточка не появилась в ленте, откройте из журнала');
1373
- }, 15000);
1374
- },
1375
- /**
1376
- * Геопозиция для запроса: уже известная (30 минут) или запрашивается при открытии чата. Отправку она не держит:
1377
- * getCurrentPosition не имеет тайм-аута, пока человек не ответил на запрос разрешения, — свои 6 с; отказ помним 30 минут.
1378
- */
1379
- _geo() {
1380
- const now = Date.now();
1381
- const TTL = 30 * 60 * 1000;
1382
- if (this._geoFix && now - (this._geoFix.at || 0) < TTL)
1383
- return this._geoFix;
1384
- this._geoFix = null;
1385
- if (!navigator.geolocation || (this._geoDeniedAt && now - this._geoDeniedAt < TTL))
1386
- return null;
1387
- if (this._geoWait)
1388
- return this._geoWait;
1389
- let finished = false;
1390
- const promise = new Promise(resolve => {
1391
- const finish = (pos, denied = false) => {
1392
- if (finished)
1393
- return;
1394
- finished = true;
1395
- clearTimeout(timer);
1396
- this._geoWait = null;
1397
- if (pos) {
1398
- this._geoFix = pos;
1399
- try {
1400
- const root = globalThis.top || globalThis;
1401
- root.__workGeoFix = pos;
1402
- globalThis.__workGeoFix = pos;
1403
- globalThis.localStorage?.setItem?.('WORK.geo-fix', JSON.stringify(pos));
1404
- } catch { /* ignore */ }
1405
- }
1406
- if (denied)
1407
- this._geoDeniedAt = Date.now();
1408
- resolve(pos);
1409
- };
1410
- const timer = setTimeout(() => {
1411
- chatDebug('геопозиция: ответа нет');
1412
- finish(null);
1413
- }, 6000);
1414
- navigator.geolocation.getCurrentPosition(
1415
- p => finish({ lat: p.coords.latitude, lon: p.coords.longitude, at: Date.now() }),
1416
- err => {
1417
- chatDebug('геопозиция недоступна:', err?.message || err);
1418
- finish(null, err?.code === 1);
1419
- },
1420
- { enableHighAccuracy: false, maximumAge: 300000, timeout: 4000 }
1421
- );
1422
- });
1423
- // колбэк мог сработать синхронно (finished) — тогда запоминать ожидание нельзя: оно залипло бы навсегда
1424
- if (!finished)
1425
- this._geoWait = promise;
1426
- return promise;
1427
- },
1428
- });
1429
- ODA({is: 'chat-ribbon',
1430
- template:/* html */`
1431
- <style>
1432
- :host{
1433
- position: relative;
1434
- @apply --light;
1435
- @apply --vertical;
1436
- @apply --flex;
1437
- overflow-x: hidden;
1438
- overflow-y: auto;
1439
- scroll-behavior: smooth;
1440
- flex-direction: column-reverse;
1441
- background: transparent;
1442
- --chat-card-max: {{ribbonHeight > 0 ? Math.round(ribbonHeight * 0.9) + 'px' : '90vh'}};
1443
- }
1444
- #ribbon{
1445
- overflow: visible;
1446
- height: max-content;
1447
- @apply --vertical;
1448
- position: relative;
1449
- gap: 2px;
1450
- }
1451
- </style>
1452
- <div id="ribbon" vertical flex>
1453
- <div flex></div>
1454
- <chat-day ~for="dates" :day="$for.item"></chat-day>
1455
- </div>
1456
-
1457
- `,
1458
- $item: {
1459
- $def: null,
1460
- set(n) {
1461
- if (this._prevRibbonItem && this._prevRibbonItem !== n) {
1462
- this._prevRibbonItem = n;
1463
- this.refreshFeed();
1464
- }
1465
- else {
1466
- this._prevRibbonItem = n;
1467
- }
1468
- }
1469
- },
1470
- ribbonHeight: 0,
1471
- attached() {
1472
- this.async(() => {
1473
- this.ribbonHeight = this.clientHeight - 8;
1474
- });
1475
- },
1476
- get lastDay(){
1477
- return this.$$('chat-day').last;
1478
- },
1479
- lastIdxHistory: -1,
1480
- async getFromHistory(value, direction = -1){
1481
- let history = await this.history;
1482
- let lastInHistory = history[this.lastIdxHistory];
1483
- if(value && value != lastInHistory)
1484
- return value;
1485
- let idx = this.lastIdxHistory + direction;
1486
- if(idx < 0)
1487
- idx = history.length - 1;
1488
- else if(idx > history.length - 1)
1489
- idx = 0;
1490
- this.lastIdxHistory = idx;
1491
- return history[idx];
1492
- },
1493
- get history(){
1494
- return Promise.resolve(this.lastDay?.logs).then(async items=>{
1495
- if (!Array.isArray(items))
1496
- return [];
1497
- const result = [];
1498
- for (const file of items) {
1499
- if (typeof file?.load !== 'function')
1500
- continue;
1501
- let raw;
1502
- try {
1503
- raw = await file.load();
1504
- }
1505
- catch {
1506
- continue;
1507
- }
1508
- const body = typeof raw === 'string' ? JSON.parse(raw) : raw;
1509
- const ext = body?.ext || body?.path?.split('/').pop()?.split('.').pop();
1510
- if (ext !== 'txt' && ext !== 'prompt' && ext !== 'msg')
1511
- continue;
1512
- const text = body.content != null ? String(body.content) : '';
1513
- if (text && !result.has(text))
1514
- result.push(text);
1515
- }
1516
- return result;
1517
- })
1518
- },
1519
- $listeners:{
1520
- scroll(e){
1521
- if (this.clientHeight <= 0 || this._restoringScroll || this._wasHidden)
1522
- return;
1523
- this._savedScrollTop = this.scrollTop;
1524
- const down = this.scrollTop > -10;
1525
- if (this.scrollDown === down)
1526
- return;
1527
- this.scrollDown = down;
1528
- this.render();
1529
- },
1530
- resize(){
1531
- if (this.clientHeight <= 0) {
1532
- this._wasHidden = true;
1533
- return;
1534
- }
1535
- const nextHeight = this.clientHeight - 8;
1536
- if (nextHeight > 0 && this.ribbonHeight !== nextHeight)
1537
- this.ribbonHeight = nextHeight;
1538
- if (this._wasHidden) {
1539
- this._wasHidden = false;
1540
- this.restoreScrollPosition();
1541
- }
1542
- }
1543
- },
1544
- scrollDown: true,
1545
- _savedScrollTop: 0,
1546
- _wasHidden: false,
1547
- _restoringScroll: false,
1548
- restoreScrollPosition(targetTop = this._savedScrollTop) {
1549
- if (typeof targetTop !== 'number' || this.clientHeight <= 0)
1550
- return;
1551
- this._wasHidden = false;
1552
- this._restoringScroll = true;
1553
- const apply = () => {
1554
- if (this.clientHeight <= 0)
1555
- return;
1556
- const prevBehavior = this.style.scrollBehavior;
1557
- this.style.scrollBehavior = 'auto';
1558
- this.scrollTop = targetTop;
1559
- this.style.scrollBehavior = prevBehavior;
1560
- };
1561
- apply();
1562
- requestAnimationFrame(() => {
1563
- apply();
1564
- this._restoringScroll = false;
1565
- });
1566
- },
1567
- get ribbon(){
1568
- return this;
1569
- },
1570
- dateList: [],
1571
- _datesWatch: null,
1572
- _lastRole: '',
1573
- _listenedSource: null,
1574
- get activeRole() {
1575
- return this.$item?.role || 'USER';
1576
- },
1577
- get isLocalFeed() {
1578
- return this.$pdp?.feedMode === 'local';
1579
- },
1580
- get isDialogFeed() {
1581
- return !this.isLocalFeed && this.$pdp?.feedMode !== 'audit';
1582
- },
1583
- _threadId: '',
1584
- _threadMessages: [],
1585
- _threadMessagesByDay: null,
1586
- _localDayOf(ms) {
1587
- const dt = new Date(Number(ms) || Date.now());
1588
- if (typeof dt.toLocalDay === 'function')
1589
- return dt.toLocalDay();
1590
- const y = dt.getFullYear();
1591
- const m = String(dt.getMonth() + 1).padStart(2, '0');
1592
- const d = String(dt.getDate()).padStart(2, '0');
1593
- return `${y}-${m}-${d}`;
1594
- },
1595
- threadMessagesForDay(day) {
1596
- if (!day || !(this._threadMessagesByDay instanceof Map))
1597
- return [];
1598
- return this._threadMessagesByDay.get(day) || [];
1599
- },
1600
- async _resolveLogsSource() {
1601
- return this.$item || null;
1602
- },
1603
- _syncSourceListeners(source) {
1604
- if (this._listenedSource === source)
1605
- return;
1606
- if (this._listenedSource && this._listenedSource !== this.$item)
1607
- this._listenedSource.unlisten?.('changed', this.onChanged);
1608
- this._listenedSource = source || null;
1609
- if (source && source !== this.$item)
1610
- source.listen?.('changed', this.onChanged);
1611
- },
1612
- async refreshFeed() {
1613
- this.dateList = [];
1614
- await this.refreshDates(true);
1615
- for (const dayEl of this.$$('chat-day') || []) {
1616
- dayEl._logsInit = false;
1617
- dayEl._ensureLogsInit?.();
1618
- }
1619
- },
1620
- async refreshDates(force = false){
1621
- if (!this.$item)
1622
- return false;
1623
- const curRole = this.activeRole;
1624
- if (this._lastRole && this._lastRole !== curRole) {
1625
- this.dateList = [];
1626
- }
1627
- this._lastRole = curRole;
1628
- const source = (await this._resolveLogsSource()) || this.$item;
1629
- this._syncSourceListeners(source);
1630
- source.invalidate?.('logs_dates');
1631
- const logsPromise = source.fetch('logs', {
1632
- mode: 'dates',
1633
- nonEmpty: 1,
1634
- ...(this.isLocalFeed ? { local: 1, feedMode: 'local' } : { feedMode: 'dialog' }),
1635
- role: curRole,
1636
- uid: WORK.uid || '',
1637
- }).catch(() => []);
1638
- const threadPromise = this.isDialogFeed && typeof this.$item.fetch === 'function'
1639
- ? this.$item.fetch('chat_messages_list', {
1640
- kind: this.$item.type === '$user' ? 'dm' : 'twin',
1641
- ...(this.$item.type === '$user' ? { peerId: this.$item.id } : {}),
1642
- limit: 200,
1643
- }).catch(() => null)
1644
- : Promise.resolve(null);
1645
-
1646
- const [rawDates, threadRes] = await Promise.all([logsPromise, threadPromise]);
1647
- // dates на сервере — по убыванию; в ленте дни — от старых к новым.
1648
- const dateSet = new Set((Array.isArray(rawDates) ? rawDates : []).slice().reverse());
1649
- const byDay = new Map();
1650
- const msgs = Array.isArray(threadRes?.messages) ? threadRes.messages : [];
1651
- this._threadId = threadRes?.thread?.id || '';
1652
- this._threadMessages = msgs;
1653
- for (const msg of msgs) {
1654
- const d = this._localDayOf(msg.created);
1655
- if (!d) continue;
1656
- dateSet.add(d);
1657
- let arr = byDay.get(d);
1658
- if (!arr) {
1659
- arr = [];
1660
- byDay.set(d, arr);
1661
- }
1662
- arr.push(msg);
1663
- }
1664
- this._threadMessagesByDay = byDay;
1665
- const curPath = String(this.$item.path || '/').replace(/\/+$/, '') || '/';
1666
- const localUnread = this.$item.type === '$user'
1667
- ? (Number(WORK.chatUnread?.byPeer?.[this.$item.id]) || 0)
1668
- : (Number(WORK.chatUnread?.byNode?.[curPath]) || 0);
1669
- if ((threadRes?.thread?.unreadCount > 0 || localUnread > 0) && threadRes?.thread?.id) {
1670
- const fallbackInfo = {
1671
- threadId: threadRes.thread.id,
1672
- kind: this.$item.type === '$user' ? 'dm' : 'twin',
1673
- nodePath: curPath,
1674
- peerId: this.$item.type === '$user' ? this.$item.id : '',
1675
- };
1676
- this.$item.fetch?.('chat_mark_read', { threadId: threadRes.thread.id })
1677
- ?.then?.(res => WORK.applyChatReadLocal?.(res?.threadId ? res : fallbackInfo))
1678
- ?.catch?.(() => {});
1679
- WORK.applyChatReadLocal?.(fallbackInfo);
1680
- }
1681
- let dates = [...dateSet].sort();
1682
- // Пока создаётся новая задача (awaitTask), не сбрасываем локально добавленный _openCreated день
1683
- if (!force && this.$pdp?.awaitTask && Array.isArray(this.dateList)) {
1684
- for (const d of this.dateList) {
1685
- if (d && !dates.includes(d))
1686
- dates.push(d);
1687
- }
1688
- dates.sort();
1689
- }
1690
- const prevDates = Array.isArray(this.dateList) ? this.dateList : [];
1691
- if (prevDates.length !== dates.length || prevDates.some((d, i) => d !== dates[i])) {
1692
- this.dateList = dates;
1693
- this.render();
1694
- return true;
1695
- }
1696
- return false;
1697
- },
1698
- get onChanged() {
1699
- return () => this.refreshDates();
1700
- },
1701
- _ensureDatesWatch(){
1702
- if (this._datesWatch) return this._datesWatch;
1703
- this._datesWatch = this.refreshDates().then(()=>{
1704
- this.$item?.listen?.('changed', this.onChanged);
1705
- });
1706
- if (!this._rolePollTimer) {
1707
- this._rolePollTimer = setInterval(() => {
1708
- if (this.$item && this._lastRole && this.activeRole !== this._lastRole) {
1709
- this.$pdp?._refreshCanLocalFeed?.();
1710
- this.refreshFeed();
1711
- }
1712
- }, 400);
1713
- }
1714
- return this._datesWatch;
1715
- },
1716
- get dates(){
1717
- this._ensureDatesWatch();
1718
- return this.dateList;
1719
- },
1720
- detached() {
1721
- this.$item?.unlisten?.('changed', this.onChanged);
1722
- if (this._listenedSource && this._listenedSource !== this.$item)
1723
- this._listenedSource.unlisten?.('changed', this.onChanged);
1724
- this._listenedSource = null;
1725
- if (this._rolePollTimer) {
1726
- clearInterval(this._rolePollTimer);
1727
- this._rolePollTimer = 0;
1728
- }
1729
- this._datesWatch = null;
1730
- }
1731
- })
1732
- ODA({is: 'chat-day',
1733
- template:/* html */`
1734
- <style>
1735
- :host{
1736
- @apply --vertical;
1737
- @apply --no-flex;
1738
-
1739
- }
1740
- :host([expanded]) .day-ribbon{
1741
- transition: opacity 1s ease-in-out;
1742
- opacity: 1;
1743
- }
1744
- .label{
1745
- cursor: pointer;
1746
- font-size: x-small;
1747
- align-self: center;
1748
- align-items: center;
1749
- text-align: center;
1750
- width: 150px;
1751
- border-radius: 16px;
1752
- padding: 0px 8px;
1753
- z-index: 1;
1754
- }
1755
- .date-line{
1756
- top: 4px;
1757
- position: sticky;
1758
- align-items: center;
1759
- width: -webkit-fill-available;
1760
- }
1761
- .day-ribbon{
1762
- gap: 8px;
1763
- padding: 8px;
1764
- opacity: 0;
1765
- }
1766
- </style>
1767
- <div flex vertical class="date-line" center>
1768
- <div class="label" raised dark horizontal :accent-invert="expanded" @tap="expanded = !expanded">
1769
- <label flex style="padding: 0px 4px;">{{label}}</label>
1770
- <oda-button icon-size="16" :icon="expanderIcon"></oda-button>
1771
- </div>
1772
- </div>
1773
-
1774
- <div class="day-ribbon" flex vertical ~if="expanded">
1775
- <chat-item @tap="setFocus" ~for="logs" :$item="$for.item"></chat-item>
1776
- </div>
1777
- `,
1778
- get expanderIcon(){
1779
- return this.expanded?'icons:chevron-right:90':'icons:chevron-right';
1780
- },
1781
- get last(){
1782
- let dates = this.$pdp.dates;
1783
- if (dates?.then)
1784
- return dates.then(days => days.last === this.day);
1785
- return dates?.last === this.day;
1786
- },
1787
- day: '',
1788
- setFocus(e) {
1789
- this.$pdp.focusedItem = e.target.$item;
1790
- },
1791
- expanded:{
1792
- $def: false,
1793
- $attr: true,
1794
- get(){
1795
- return this.last;
1796
- }
1797
- },
1798
- logItems: [],
1799
- _logsFolder: null,
1800
- _logsInit: false,
1801
- _logsInitPromise: null,
1802
- _logsListenersHooked: false,
1803
- _dayFolderHooked: false,
1804
- _expandedTaskKey: '',
1805
- _logItemTime(f) {
1806
- if (!f)
1807
- return 0;
1808
- const st = SORT_TIMES.get(f);
1809
- if (Number.isFinite(st) && st > 0)
1810
- return st;
1811
- const isProxyItem = Boolean(typeof f.fetch === 'function' || f.short);
1812
- const rowTime = !isProxyItem ? Number(f.logRow?.time || f.DATA?.logRow?.time || 0) : 0;
1813
- if (rowTime > 0)
1814
- return rowTime;
1815
- const idPrefix = parseInt(String(f.id || '').split('.')[0], 10);
1816
- if (idPrefix > 0)
1817
- return idPrefix;
1818
- const pathMatch = String(f.path || '').match(/\/(\d{10,16})\.[^/]+$/);
1819
- if (pathMatch)
1820
- return parseInt(pathMatch[1], 10) || 0;
1821
- return 0;
1822
- },
1823
- _sortLogFiles(files){
1824
- return files.slice().sort((a, b) => {
1825
- const ta = this._logItemTime(a);
1826
- const tb = this._logItemTime(b);
1827
- if (ta && tb && ta !== tb)
1828
- return ta - tb;
1829
- return String(a?.id || '') < String(b?.id || '') ? -1 : 1;
1830
- });
1831
- },
1832
- _isMatchingTaskItem(it, key, fileId = '') {
1833
- if (!it)
1834
- return false;
1835
- if (fileId && it.id === fileId)
1836
- return true;
1837
- if (!key)
1838
- return false;
1839
- return taskKeyOf(it.logRow?.path || it.path || it.id) === key
1840
- || String(it.id || '').replace(/\.logs$/i, '.task') === key;
1841
- },
1842
- _syncExpandedTaskCard() {
1843
- const key = this._expandedTaskKey;
1844
- const cards = [...(this.$$('chat-item') || [])];
1845
- if (!key)
1846
- return;
1847
- for (const c of cards) {
1848
- const match = this._isMatchingTaskItem(c.$item, key);
1849
- if (match && !c.expanded)
1850
- c.expanded = true;
1851
- else if (!match && c.expanded)
1852
- c.expanded = false;
1853
- }
1854
- },
1855
- async _dedupeLogFiles(files){
1856
- const seen = new Set();
1857
- const result = [];
1858
- for (const f of files) {
1859
- let key = f?.id;
1860
- if (typeof f?.load === 'function') {
1861
- try {
1862
- const raw = await f.load();
1863
- const row = typeof raw === 'string' ? JSON.parse(raw) : raw;
1864
- // Записи файлов из контекста задачи — только внутри её карточки, не отдельными карточками.
1865
- if (row?.mainContext)
1866
- continue;
1867
- // задача, принятая в ленту напрямую (adoptTask), — карточка уже есть; запись журнала о ней не дублируем
1868
- if (row?.ext === 'task' && this._adopted?.has(taskKeyOf(row.path)))
1869
- continue;
1870
- if (row?.path)
1871
- key = row.path;
1872
- }
1873
- catch { /* skip */ }
1874
- }
1875
- if (!key || seen.has(key))
1876
- continue;
1877
- seen.add(key);
1878
- result.push(f);
1879
- }
1880
- // принятые напрямую задачи в журнале дня могут ещё не появиться — не теряем их при перечитывании ленты
1881
- for (const f of this._adopted?.values() || [])
1882
- if (!result.some(r => r?.id === f.id))
1883
- result.push(f);
1884
- return this._sortLogFiles(result);
1885
- },
1886
- /**
1887
- * Принять только что созданную задачу в ленту дня сразу по её файлу: карточка раскрывается, не дожидаясь записи
1888
- * журнала. Резолвится, когда форма задачи нарисована (до этого чат держит экран «создаю задачу»).
1889
- */
1890
- async adoptTask(file) {
1891
- if (!this._logsInit)
1892
- this._ensureLogsInit();
1893
- if (this._logsInitPromise)
1894
- await Promise.race([this._logsInitPromise, sleep(400)]).catch(() => {});
1895
- const key = taskKeyOf(file.path) || String(file.id);
1896
- if (!SORT_TIMES.has(file))
1897
- SORT_TIMES.set(file, this._logItemTime(file) || Date.now());
1898
- this._expandedTaskKey = key;
1899
- (this._adopted ??= new Map()).set(key, file);
1900
- const isSameTask = it => this._isMatchingTaskItem(it, key, file.id);
1901
- const filtered = (this.logItems || []).filter(it => !isSameTask(it));
1902
- this.logItems = this._sortLogFiles([...filtered, file]);
1903
- this.expanded = true;
1904
- this.render();
1905
- this._scrollRibbonDown();
1906
- for (let i = 0; i < 60; i++) {
1907
- const allCards = [...(this.$$('chat-item') || [])];
1908
- const card = allCards.find(el => isSameTask(el.$item));
1909
- if (card) {
1910
- for (const other of allCards) {
1911
- if (other !== card && other.expanded)
1912
- other.expanded = false;
1913
- }
1914
- card.expanded = true;
1915
- for (let j = 0; j < 30; j++) {
1916
- if (card.$('.body > *')?.data)
1917
- break;
1918
- await new Promise(r => setTimeout(r, 50));
1919
- }
1920
- return true;
1921
- }
1922
- await new Promise(r => setTimeout(r, 50));
1923
- }
1924
- throw new Error('карточка задачи не появилась в ленте');
1925
- },
1926
- _scrollRibbonDown(){
1927
- if (this.$pdp.ribbon?.scrollDown) {
1928
- this.async(() => {
1929
- if (this.$pdp.ribbon) {
1930
- this.$pdp.ribbon._savedScrollTop = 0;
1931
- this.$pdp.ribbon.scrollTop = 0;
1932
- }
1933
- }, 0);
1934
- }
1935
- },
1936
- _wrapLogRow(row) {
1937
- if (!row)
1938
- return row;
1939
- if (typeof row.load === 'function' && !row.logsFilePath && !row.DATA?.logsFilePath)
1940
- return row;
1941
- const rawRow = row.DATA?.logsFilePath ? { ...row.DATA } : row;
1942
- const uid = rawRow.sender || 'system';
1943
- const id = `${rawRow.time || 0}.${uid}.logs`;
1944
- this._wrappedById ??= new Map();
1945
- const existing = this._wrappedById.get(id);
1946
- if (existing) {
1947
- existing.logRow = rawRow;
1948
- return existing;
1949
- }
1950
- const wrapped = {
1951
- id,
1952
- name: id,
1953
- ext: 'logs',
1954
- path: rawRow.logsFilePath || `/${id}`,
1955
- logRow: rawRow,
1956
- load: async () => ({ ...(wrapped.logRow || rawRow) }),
1957
- };
1958
- this._wrappedById.set(id, wrapped);
1959
- return wrapped;
1960
- },
1961
- _wrapThreadMessage(msg) {
1962
- if (!msg || !msg.id)
1963
- return null;
1964
- const id = `chatmsg.${msg.id}.msg`;
1965
- this._wrappedById ??= new Map();
1966
- const nodeLabel = this.$pdp?.$item?.DATA?.label || this.$pdp?.$item?.label || this.$pdp?.$item?.id || '';
1967
- const enriched = { ...msg, nodeLabel };
1968
- const rawRow = {
1969
- time: msg.created || Date.now(),
1970
- sender: msg.sender,
1971
- content: msg.content || '',
1972
- kind: msg.kind || 'text',
1973
- includes: (msg.attachments || []).map(a => a.path).filter(Boolean),
1974
- chatMessage: enriched,
1975
- };
1976
- const existing = this._wrappedById.get(id);
1977
- if (existing) {
1978
- SORT_TIMES.set(existing, rawRow.time);
1979
- existing.logRow = rawRow;
1980
- return existing;
1981
- }
1982
- const wrapped = {
1983
- id,
1984
- name: id,
1985
- ext: 'msg',
1986
- path: '',
1987
- logRow: rawRow,
1988
- load: async () => ({ ...(wrapped.logRow || rawRow) }),
1989
- };
1990
- SORT_TIMES.set(wrapped, rawRow.time);
1991
- this._wrappedById.set(id, wrapped);
1992
- return wrapped;
1993
- },
1994
- async _bindLogsFolder(){
1995
- const source = await Promise.resolve(this.logsSource);
1996
- return !!source;
1997
- },
1998
- async _fetchLogFiles(){
1999
- const source = await Promise.resolve(this.logsSource);
2000
- if (!source)
2001
- return [];
2002
- const role = this.$pdp?.$item?.role || 'USER';
2003
- const uid = WORK.uid || '';
2004
- const local = this.$pdp?.isLocalFeed ? { local: 1, feedMode: 'local' } : { feedMode: 'dialog' };
2005
- let rows = [];
2006
- try {
2007
- if (typeof source.fetch === 'function')
2008
- rows = await source.fetch('logs', { mode: 'bodies', day: this.day, role, uid, ...local });
2009
- else if (typeof source.logs === 'function')
2010
- rows = await source.logs({ mode: 'bodies', day: this.day, role, uid, ...local });
2011
- }
2012
- catch {
2013
- rows = [];
2014
- }
2015
- if (!Array.isArray(rows))
2016
- rows = [];
2017
- const hasVisibleRowPayload = (r) => {
2018
- if (!r) return false;
2019
- if (r.path || r.ext || r.chatMessage?.kind === 'approval')
2020
- return true;
2021
- if (String(r.content || '').trim())
2022
- return true;
2023
- if (Array.isArray(r.includes) ? r.includes.length > 0 : Boolean(String(r.includes || '').trim()))
2024
- return true;
2025
- return false;
2026
- };
2027
- const files = rows.filter(hasVisibleRowPayload).map(r => this._wrapLogRow(r)).filter(f => f?.id?.endsWith?.('.logs') || f?.id?.endsWith?.('.task'));
2028
-
2029
- if (!this.$pdp?.isLocalFeed && typeof this.$pdp?.threadMessagesForDay === 'function') {
2030
- const taskKeys = new Set(rows.map(r => taskKeyOf(r?.path)).filter(Boolean));
2031
- for (const f of this._adopted?.values() || []) {
2032
- const tk = taskKeyOf(f?.path || f?.id);
2033
- if (tk) taskKeys.add(tk);
2034
- }
2035
- const msgs = this.$pdp.threadMessagesForDay(this.day);
2036
- for (const m of msgs) {
2037
- if (m.taskPath && taskKeys.has(taskKeyOf(m.taskPath)))
2038
- continue;
2039
- if (!String(m.content || '').trim() && !(m.attachments?.length) && m.kind !== 'approval')
2040
- continue;
2041
- if (m.sender !== '$twin' && m.kind === 'text' && rows.some(r => r?.sender === m.sender && String(r?.content || '').trim() === String(m.content || '').trim() && Math.abs((Number(r?.time) || 0) - (Number(m.created) || 0)) < 5000))
2042
- continue;
2043
- const w = this._wrapThreadMessage(m);
2044
- if (w)
2045
- files.push(w);
2046
- }
2047
- }
2048
- return this._dedupeLogFiles(this._sortLogFiles(files));
2049
- },
2050
- /**
2051
- * Раскрыть карточку только что созданной задачи. Строго та, что создана: по имени файла .task;
2052
- * пока путь неизвестен — только новая запись моего авторства, которой не было в ленте до отправки.
2053
- * «Ближайшая по времени» не подходит: раскрывалась последняя прежняя задача (см. chat-task.js).
2054
- */
2055
- async _expandCreatedTask(file) {
2056
- const chat = this.$pdp.$pdp;
2057
- if (!chat?.awaitTask || !chat?._awaitingLogExpand)
2058
- return;
2059
- const day = taskDayOf(chat._awaitTaskPath);
2060
- if (day && this.day !== day)
2061
- return;
2062
- const want = { key: chat._awaitTaskKey || '', known: chat._awaitKnown || new Set(), uid: WORK.uid };
2063
- const loadRow = async f => {
2064
- try {
2065
- const raw = await f.load();
2066
- return typeof raw === 'string' ? JSON.parse(raw) : raw;
2067
- }
2068
- catch {
2069
- return null;
2070
- }
2071
- };
2072
- let hit = null;
2073
- let hitRow = null;
2074
- for (const f of file ? [file] : this.logItems) {
2075
- if (want.known.has(String(f?.id || '')))
2076
- continue;
2077
- const row = await loadRow(f);
2078
- const rowKey = taskKeyOf(row?.path || f?.path || f?.id);
2079
- if (rowKey && want.known.has(rowKey))
2080
- continue;
2081
- if (isCreatedTask(f, row, want)) {
2082
- hit = f;
2083
- hitRow = row;
2084
- break;
2085
- }
2086
- }
2087
- if (!hit)
2088
- return;
2089
- const hitKey = taskKeyOf(hitRow?.path || hit?.path || hit?.id) || String(hit.id || '').replace(/\.logs$/i, '.task');
2090
- if (hitKey)
2091
- this._expandedTaskKey = hitKey;
2092
- // день мог быть свёрнут, карточка рисуется после render — ждём её появления
2093
- if (!this.expanded)
2094
- this.expanded = true;
2095
- this.render();
2096
- for (let i = 0; i < 30; i++) {
2097
- const allCards = [...this.$$('chat-item')];
2098
- const card = allCards.find(el => el.$item?.id === hit.id || (hitKey && this._isMatchingTaskItem(el.$item, hitKey)));
2099
- if (card) {
2100
- for (const other of allCards) {
2101
- if (other !== card && other.expanded)
2102
- other.expanded = false;
2103
- }
2104
- card.expanded = true;
2105
- chat.awaitTask = false;
2106
- chat._awaitingLogExpand = false;
2107
- chat._awaitTaskPath = '';
2108
- chat._awaitTaskKey = '';
2109
- chat._awaitKnown = null;
2110
- clearTimeout(chat._awaitTimer);
2111
- return;
2112
- }
2113
- await new Promise(r => setTimeout(r, 50));
2114
- }
2115
- },
2116
- async _onLogsChangedRun(){
2117
- if (!this._logsInit)
2118
- return;
2119
- try {
2120
- const items = await this._fetchLogFiles();
2121
- const prev = Array.isArray(this.logItems) ? this.logItems : [];
2122
- const prevLen = prev.length;
2123
- const sameList = prev.length === items.length && items.every((it, idx) => it === prev[idx] || (it?.id && it.id === prev[idx]?.id));
2124
- if (!sameList) {
2125
- this.logItems = items;
2126
- this.render();
2127
- this._syncExpandedTaskCard();
2128
- if (items.length > prevLen)
2129
- this._scrollRibbonDown();
2130
- }
2131
- await this._expandCreatedTask();
2132
- }
2133
- catch (err) {
2134
- console.warn('[chat-day] log changed', err);
2135
- }
2136
- },
2137
- _onLogsChanged(e){
2138
- this._lastChangedEvent = e;
2139
- this.debounce('chat-day-logs', () => this._onLogsChangedRun(this._lastChangedEvent), 30);
2140
- },
2141
- _ensureLogsInit() {
2142
- if (this._logsInit)
2143
- return this._logsInitPromise;
2144
- this._logsInit = true;
2145
- this._wasInit = true;
2146
- this._logsInitPromise = Promise.resolve(this.logsSource).then(async source => {
2147
- if (!source)
2148
- return;
2149
- if (!this._logsListenersHooked) {
2150
- this._logsListenersHooked = true;
2151
- const onChanged = this._onChangedFn = e => this._onLogsChanged(e);
2152
- this._listened = [source, this.$pdp.$item].filter(Boolean);
2153
- source?.listen?.('changed', onChanged);
2154
- if (this.$pdp.$item && this.$pdp.$item !== source)
2155
- this.$pdp.$item?.listen?.('changed', onChanged);
2156
- }
2157
- this.logItems = await this._fetchLogFiles();
2158
- this.render();
2159
- this._syncExpandedTaskCard();
2160
- this._scrollRibbonDown();
2161
- await this._expandCreatedTask();
2162
- }).catch(e => {
2163
- console.warn('[chat-day] logs', e.message);
2164
- this._logsInit = false;
2165
- });
2166
- return this._logsInitPromise;
2167
- },
2168
- get logs() {
2169
- this._ensureLogsInit();
2170
- return this.logItems;
2171
- },
2172
- /** День вернули в DOM после снятия подписок — подписаться заново (день, который не открывали, ленту не грузит). */
2173
- attached() {
2174
- if (this._wasInit && !this._logsInit)
2175
- this._ensureLogsInit();
2176
- },
2177
- /** Снять подписки на ленту: день убрали из DOM — события больше не нужны (иначе копятся по числу дней). */
2178
- detached() {
2179
- for (const target of this._listened || [])
2180
- target?.unlisten?.('changed', this._onChangedFn);
2181
- this._listened = null;
2182
- this._logsListenersHooked = false;
2183
- this._logsInit = false;
2184
- if (this._logsFolder && this._dayFolderHooked) {
2185
- this._logsFolder.unlisten?.('changed', this._dayHandler);
2186
- this._dayFolderHooked = false;
2187
- }
2188
- },
2189
- get logsSource(){
2190
- // По умолчанию всегда показывается личный кабинет (/USERS/<uid>);
2191
- // местный лог точки (this.$pdp.$item) — только при явном включении режима local для BOSS.
2192
- const role = this.$pdp?.$item?.role || 'USER';
2193
- const uid = WORK.uid || '';
2194
- const local = this.$pdp?.isLocalFeed ? { local: 1 } : {};
2195
- return Promise.resolve(this.$pdp.$item?.fetch?.('chatSource', { role, uid, ...local })).then(path => {
2196
- if (path && typeof path === 'string')
2197
- return WORK.get_item(path);
2198
- return this.$pdp.$item;
2199
- });
2200
- },
2201
- get label(){
2202
- let date = new Date(this.day);
2203
- return date.toLocaleDateString(undefined, {
2204
- weekday: "short",
2205
- year: "numeric",
2206
- month: "long",
2207
- day: "numeric",
2208
- });
2209
- }
2210
- })
2211
- ODA({is: 'skill-tree', imports: '~/lib//tree.js', extends: 'item-tree',
2212
- execute($item) {
2213
- this.$pdp.chat.value = '@' + $item.name;
2214
- this.focusedItem = $item;
2215
- this.executed = true;
2216
- },
2217
- })