File size: 37,500 Bytes
8e17064
 
 
 
 
 
2ab515e
8e17064
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab515e
8e17064
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab515e
8e17064
 
2ab515e
8e17064
 
 
 
2ab515e
8e17064
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2ab515e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
import { c as create_ssr_component, o as onDestroy, v as validate_component, d as add_attribute, k as add_classes, e as escape, h as each } from './ssr-6MZFlfLu.js';
import { S as Splitpanes, P as Pane, a as SearchResults } from './SearchResults-bzu8BmOk.js';
import 'docx';
import 'file-saver';
import { g as getToastStore, M as ModalPromptEditor } from './ModalPromptEditor-isPsJANV.js';
import './ProgressBar.svelte_svelte_type_style_lang-H22V2Yrx.js';
import { D as DEFAULT_SEARCH_INPUT_PARAMS } from './constants-PEBBwOxo.js';
import { L as LlmSelector } from './LlmSelector-fG0hpxMx.js';
import { S as SearchTypeSelector } from './SearchTypeSelector-iwYUZlnB.js';
import { g as getModalStore } from './stores-0qksNY90.js';
import './index2-f61NAEsz.js';

const LoadingSpinner = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { size = 20 } = $$props;
  if ($$props.size === void 0 && $$bindings.size && size !== void 0)
    $$bindings.size(size);
  return `<svg version="1.1" id="L4" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 100 100" enable-background="new 0 0 0 0" xml:space="preserve"><circle fill="#1976d2" stroke="none" cx="6" cy="50" r="6"><animate attributeName="opacity" dur="1s" values="0;1;0" repeatCount="indefinite" begin="0.1"></animate></circle><circle fill="#1976d2" stroke="none" cx="26" cy="50" r="6"><animate attributeName="opacity" dur="1s" values="0;1;0" repeatCount="indefinite" begin="0.2"></animate></circle><circle fill="#1976d2" stroke="none" cx="46" cy="50" r="6"><animate attributeName="opacity" dur="1s" values="0;1;0" repeatCount="indefinite" begin="0.3"></animate></circle></svg>`;
});
const css$6 = {
  code: ".llm-health-status.svelte-1wcf73j{color:slategray;font-size:12px;display:inline-flex;align-items:center}.dot.svelte-1wcf73j{width:20px;height:20px}",
  map: null
};
const LlmHealthStatus = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { disableIntervalChecks = false } = $$props;
  let { llmName = "" } = $$props;
  let color = "#af4f4c";
  let shadowColor = "#af4f4c";
  let text = "Сервис LLM недоступен";
  let abortController = new AbortController();
  let healthInterval;
  onDestroy(() => {
    clearInterval(healthInterval);
    abortController.abort("user canceled");
    abortController = new AbortController();
  });
  if ($$props.disableIntervalChecks === void 0 && $$bindings.disableIntervalChecks && disableIntervalChecks !== void 0)
    $$bindings.disableIntervalChecks(disableIntervalChecks);
  if ($$props.llmName === void 0 && $$bindings.llmName && llmName !== void 0)
    $$bindings.llmName(llmName);
  $$result.css.add(css$6);
  return `<div class="llm-health-status w-40 inline-block svelte-1wcf73j"><svg class="dot svelte-1wcf73j" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><circle cx="10" cy="10" r="5"${add_attribute("fill", color, 0)} style="${"filter: drop-shadow(0 0 1px " + escape(shadowColor, true) + ")"}"></circle></svg> ${escape(text)} </div>`;
});
const css$5 = {
  code: ".llm-health-status.svelte-1wcf73j{color:slategray;font-size:12px;display:inline-flex;align-items:center}.dot.svelte-1wcf73j{width:20px;height:20px}",
  map: null
};
const SearchApiHealthStatus = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { disableIntervalChecks = false } = $$props;
  let color = "#af4f4c";
  let shadowColor = "#af4f4c";
  let text = "Поиск недоступен";
  let abortController = new AbortController();
  let healthInterval;
  onDestroy(() => {
    clearInterval(healthInterval);
    abortController.abort("user canceled");
    abortController = new AbortController();
  });
  if ($$props.disableIntervalChecks === void 0 && $$bindings.disableIntervalChecks && disableIntervalChecks !== void 0)
    $$bindings.disableIntervalChecks(disableIntervalChecks);
  $$result.css.add(css$5);
  return `<div class="llm-health-status w-40 inline-block svelte-1wcf73j"><svg class="dot svelte-1wcf73j" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><circle cx="10" cy="10" r="5"${add_attribute("fill", color, 0)} style="${"filter: drop-shadow(0 0 1px " + escape(shadowColor, true) + ")"}"></circle></svg> ${escape(text)} </div>`;
});
const css$4 = {
  code: ".annotation.svelte-1uvb5ib{overflow:hidden;display:block;-webkit-box-orient:vertical;text-overflow:ellipsis;white-space:normal}",
  map: null
};
const ConsultationItem = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { showFullText = Array(10).fill(false) } = $$props;
  let { index } = $$props;
  let { title } = $$props;
  let { text } = $$props;
  if ($$props.showFullText === void 0 && $$bindings.showFullText && showFullText !== void 0)
    $$bindings.showFullText(showFullText);
  if ($$props.index === void 0 && $$bindings.index && index !== void 0)
    $$bindings.index(index);
  if ($$props.title === void 0 && $$bindings.title && title !== void 0)
    $$bindings.title(title);
  if ($$props.text === void 0 && $$bindings.text && text !== void 0)
    $$bindings.text(text);
  $$result.css.add(css$4);
  return `<div class="mb-5"><div class="font-bold"><button class="btn-link ml-3 text-left">${escape(title)}</button></div> ${showFullText[index] ? `<div class="annotation svelte-1uvb5ib">${each(text.split("\n"), (line) => {
    return `<p class="mt-3 mb-3">${escape(line)}</p>`;
  })}</div>` : ``} </div>`;
});
const RelevantConsultations = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let showFullText = Array(10).fill(false);
  let { consultations = [] } = $$props;
  let previousConsultations = [];
  if ($$props.consultations === void 0 && $$bindings.consultations && consultations !== void 0)
    $$bindings.consultations(consultations);
  {
    {
      if (consultations !== previousConsultations) {
        showFullText = Array(consultations.length).fill(false);
        previousConsultations = consultations;
      }
    }
  }
  return `<div class="flex-1 overflow-y-auto p-4"><h2 class="w-full p-5 space-y-2 mb-3 text-lg" style="border-bottom:2px solid #ccc;border-top:2px solid #ccc" data-svelte-h="svelte-bhrtd7">Консультации</h2> ${each(consultations, ({ title, text }, index) => {
    return `${validate_component(ConsultationItem, "ConsultationItem").$$render($$result, { title, text, index, showFullText }, {}, {})}`;
  })}</div>`;
});
const css$3 = {
  code: "textarea.svelte-3qvypm{border:1px solid #ccc;border-radius:4px;width:100%;font-size:14px;margin-bottom:10px;box-sizing:border-box;padding:1rem}",
  map: null
};
const UserClarification = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { llmClarification = "" } = $$props;
  if ($$props.llmClarification === void 0 && $$bindings.llmClarification && llmClarification !== void 0)
    $$bindings.llmClarification(llmClarification);
  $$result.css.add(css$3);
  return `<div class="w-full flex p-2 space-x-2"><textarea rows="3" placeholder="Уточнение для LLM" class="svelte-3qvypm">${escape(llmClarification || "")}</textarea> </div>`;
});
const API_BASE_URL = "/api/log";
class LogService {
  /**
   * Сохраняет лог в базу данных через API.
   * @param log - Лог-документ для сохранения.
   * @returns {Promise<void>}
   */
  static async log(log) {
    try {
      const response = await fetch(`${API_BASE_URL}/write`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify(log)
      });
      if (!response.ok) {
        throw new Error("Failed to record log entry");
      }
      const data = await response.json();
      return data.id;
    } catch (error) {
      console.error("Error while sending log to server:", error);
    }
  }
  /**
   * Экспортирует логи в формате JSON.
   * @param dateFrom - Дата начала фильтрации (необязательно).
   * @param dateTo - Дата окончания фильтрации (необязательно).
   * @returns {Promise<void>}
   */
  static async exportToJson(dateFrom, dateTo) {
    try {
      const queryParams = new URLSearchParams();
      if (dateFrom)
        queryParams.append("dateFrom", dateFrom.toISOString());
      if (dateTo)
        queryParams.append("dateTo", dateTo.toISOString());
      const response = await fetch(`${API_BASE_URL}/export/json?${queryParams.toString()}`);
      if (!response.ok) {
        throw new Error("Failed to export logs to JSON");
      }
      const result = await response.json();
      console.log(result.message);
    } catch (error) {
      console.error("Error while exporting logs to JSON:", error);
    }
  }
  /**
   * Экспортирует логи в формате Excel.
   * @param dateFrom - Дата начала фильтрации (необязательно).
   * @param dateTo - Дата окончания фильтрации (необязательно).
   * @param fields - Поля для экспорта
   * @returns {Promise<Blob|null>}
   */
  static async exportToExcel(dateFrom, dateTo, fields) {
    try {
      const queryParams = new URLSearchParams();
      if (dateFrom)
        queryParams.append("dateFrom", dateFrom.toISOString());
      if (dateTo)
        queryParams.append("dateTo", dateTo.toISOString());
      if (fields && fields.length > 0) {
        queryParams.append("fields", fields.join(","));
      }
      const response = await fetch(`${API_BASE_URL}/export/excel?${queryParams.toString()}`);
      if (!response.ok) {
        throw new Error("Failed to export logs to Excel");
      }
      const blob = await response.blob();
      return blob;
    } catch (error) {
      console.error("Error while exporting logs to Excel:", error);
    }
    return null;
  }
  /**
   * Обновляет поле userScore в записи на сервере.
   * @param id - ID записи, которую нужно обновить.
   * @param score - Новое значение для userScore.
   * @returns Результат обновления.
   */
  static async logUserScore(id, score, comment) {
    const response = await fetch("/api/log/write/userScore", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ id, score, comment })
    });
    if (!response.ok) {
      throw new Error("Failed to update user score");
    }
    const data = await response.json();
    if (data.message !== "User score updated successfully") {
      throw new Error("User score update failed");
    }
  }
}
const css$2 = {
  code: ".star-rating.svelte-zykxm3{display:inline-block;margin-bottom:10px}.star.svelte-zykxm3{font-size:30px;color:grey;background:none;border:none;cursor:pointer}.star.selected.svelte-zykxm3{color:gold}button[disabled].svelte-zykxm3{opacity:0.5;cursor:not-allowed}textarea[disabled].svelte-zykxm3{background-color:#f5f5f5}",
  map: null
};
const Rating = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  getToastStore();
  let selectedRating = 0;
  let { onSubmit = function(args) {
  } } = $$props;
  let hoveredRating = 0;
  let buttonText = "Отправить";
  if ($$props.onSubmit === void 0 && $$bindings.onSubmit && onSubmit !== void 0)
    $$bindings.onSubmit(onSubmit);
  $$result.css.add(css$2);
  return `<div><span data-svelte-h="svelte-9pssby">Оцените ответ:</span> <div class="star-rating svelte-zykxm3" role="none">${each(Array(5), (_, i) => {
    return `<button class="${"star " + escape(
      hoveredRating >= i + 1 || selectedRating >= i + 1 ? "selected" : "",
      true
    ) + " svelte-zykxm3"}">★
			</button>`;
  })}</div> <textarea rows="3" placeholder="Комментарий" ${"disabled"} class="textarea bg-white p-1 svelte-zykxm3">${escape("")}</textarea> <button class="btn variant-form-material svelte-zykxm3" ${"disabled"}>${escape(buttonText)}</button> </div>`;
});
const SearchSettings = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  getModalStore();
  let { llmParams } = $$props;
  if ($$props.llmParams === void 0 && $$bindings.llmParams && llmParams !== void 0)
    $$bindings.llmParams(llmParams);
  return ` <button class="btn variant-outline-tertiary" data-svelte-h="svelte-1np4oyj">Настроить поиск</button> `;
});
const css$1 = {
  code: ".annotation.svelte-1uvb5ib{overflow:hidden;display:block;-webkit-box-orient:vertical;text-overflow:ellipsis;white-space:normal}",
  map: null
};
const ExplanationItem = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { showFullText = Array(10).fill(false) } = $$props;
  let { index } = $$props;
  let { title } = $$props;
  let { text } = $$props;
  if ($$props.showFullText === void 0 && $$bindings.showFullText && showFullText !== void 0)
    $$bindings.showFullText(showFullText);
  if ($$props.index === void 0 && $$bindings.index && index !== void 0)
    $$bindings.index(index);
  if ($$props.title === void 0 && $$bindings.title && title !== void 0)
    $$bindings.title(title);
  if ($$props.text === void 0 && $$bindings.text && text !== void 0)
    $$bindings.text(text);
  $$result.css.add(css$1);
  return `<div class="mb-5"><div class="font-bold"><button class="btn-link ml-3 text-left">${escape(title)}</button></div> ${showFullText[index] ? `<div class="annotation svelte-1uvb5ib">${each(text.split("\n"), (line) => {
    return `<p class="mt-3 mb-3">${escape(line)}</p>`;
  })}</div>` : ``} </div>`;
});
const Explanations = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let showFullText = Array(10).fill(false);
  let { explanations = [] } = $$props;
  let previousExplanations = [];
  if ($$props.explanations === void 0 && $$bindings.explanations && explanations !== void 0)
    $$bindings.explanations(explanations);
  {
    {
      if (explanations !== previousExplanations) {
        showFullText = Array(explanations.length).fill(false);
        previousExplanations = explanations;
      }
    }
  }
  return `<div class="flex-1 overflow-y-auto p-4"><h2 class="w-full p-5 space-y-2 mb-3 text-lg" style="border-bottom:2px solid #ccc;border-top:2px solid #ccc" data-svelte-h="svelte-81a5qt">Разъяснения</h2> ${each(explanations, ({ title, text }, index) => {
    return `${validate_component(ExplanationItem, "ExplanationItem").$$render($$result, { title, text, index, showFullText }, {}, {})}`;
  })}</div>`;
});
function getDeclension(count, one, few, many) {
  const mod10 = count % 10;
  const mod100 = count % 100;
  if (mod100 >= 11 && mod100 <= 19)
    return many;
  if (mod10 === 1)
    return one;
  if (mod10 >= 2 && mod10 <= 4)
    return few;
  return many;
}
const DocumentTypeSelector = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let selectedCount;
  let { disabled = false } = $$props;
  let { selected = {
    НКРФ: false,
    ГКРФ: false,
    ТКРФ: false,
    "Федеральный закон": false,
    "Письмо Минфина": false,
    "Письмо ФНС": false,
    "Приказ ФНС": false,
    "Постановление Правительства": false,
    "Судебный документ": false,
    ВНД: false,
    "Бухгалтерский документ": false
  } } = $$props;
  getModalStore();
  let documentTypeLabels = {
    НКРФ: "НК РФ",
    ГКРФ: "ГК РФ",
    ТКРФ: "ТК РФ",
    "Федеральный закон": "Федеральный Закон",
    "Письмо Минфина": "Письмо Минфина",
    "Письмо ФНС": "Письмо ФНС",
    "Приказ ФНС": "Приказ ФНС",
    "Постановление Правительства": "Постановление Правительства",
    "Судебный документ": "Судебный документ",
    ВНД: "ВНД",
    "Бухгалтерский документ": "ФСБУ"
  };
  let buttonTitle = "Выбрать типы источников для поиска";
  if ($$props.disabled === void 0 && $$bindings.disabled && disabled !== void 0)
    $$bindings.disabled(disabled);
  if ($$props.selected === void 0 && $$bindings.selected && selected !== void 0)
    $$bindings.selected(selected);
  selectedCount = Object.values(selected).filter((v) => v === true).length;
  buttonTitle = selectedCount > 0 ? `${getDeclension(selectedCount, "Выбран", "Выбрано", "Выбрано")} ${selectedCount} ${getDeclension(selectedCount, "тип", "типа", "типов")} источников` : "Выбрать типы источников для поиска";
  return `<button class="${[
    "chip variant-soft-primary flex items-center min-w-64",
    selectedCount ? "variant-soft-error" : ""
  ].join(" ").trim()}">${escape(buttonTitle)} <i class="fa-solid fa-angle-down ml-1"></i></button> <div class="card p-4 w-150 shadow-xl z-10" data-popup="popupFeatured"><div>${each(Object.entries(documentTypeLabels), ([key, value]) => {
    return `<label class="flex items-center space-x-2"><input class="checkbox accent-white" type="checkbox" ${disabled ? "disabled" : ""}${add_attribute("checked", selected[key], 1)}> <p>${escape(value)}</p> </label>`;
  })}</div></div>`;
});
const InvestigatorSettings = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  getModalStore();
  let { settings } = $$props;
  if ($$props.settings === void 0 && $$bindings.settings && settings !== void 0)
    $$bindings.settings(settings);
  let $$settled;
  let $$rendered;
  let previous_head = $$result.head;
  do {
    $$settled = true;
    $$result.head = previous_head;
    $$rendered = ` <button class="btn variant-outline-tertiary" data-svelte-h="svelte-og5a6t">Почемучки</button>  <div class="${[
      "p-4 shadow-xl space-y-4 w-3/4",
      "hidden"
    ].join(" ").trim()}"><form class="space-y-4"><div class="grid grid-cols-3 gap-4"><div> <div class="form-control"><label class="label">Количество потоков для этапа ответов на вопросы
						<input type="number" class="input input-bordered w-full variant-filled" max="30" min="1"${add_attribute("value", settings.maxThreads, 0)}></label></div></div></div> <div><div data-svelte-h="svelte-zzrwnb">Генерация вопросов</div> ${validate_component(ModalPromptEditor, "ModalPromptEditor").$$render(
      $$result,
      {
        label: "system промпт",
        prompt: settings.prompts.createQuestions[0]
      },
      {
        prompt: ($$value) => {
          settings.prompts.createQuestions[0] = $$value;
          $$settled = false;
        }
      },
      {}
    )} ${validate_component(ModalPromptEditor, "ModalPromptEditor").$$render(
      $$result,
      {
        label: "user промпт",
        prompt: settings.prompts.createQuestions[1]
      },
      {
        prompt: ($$value) => {
          settings.prompts.createQuestions[1] = $$value;
          $$settled = false;
        }
      },
      {}
    )} ${validate_component(LlmSelector, "LlmSelector").$$render(
      $$result,
      {
        skipLoadList: true,
        selectedLLM: settings.llmParams.createQuestions
      },
      {
        selectedLLM: ($$value) => {
          settings.llmParams.createQuestions = $$value;
          $$settled = false;
        }
      },
      {}
    )}</div> <div><div data-svelte-h="svelte-k26452">Ответы на вопросы</div> ${validate_component(ModalPromptEditor, "ModalPromptEditor").$$render(
      $$result,
      {
        label: "system промпт",
        prompt: settings.prompts.answerQuestion[0]
      },
      {
        prompt: ($$value) => {
          settings.prompts.answerQuestion[0] = $$value;
          $$settled = false;
        }
      },
      {}
    )} ${validate_component(ModalPromptEditor, "ModalPromptEditor").$$render(
      $$result,
      {
        label: "user промпт",
        prompt: settings.prompts.answerQuestion[1]
      },
      {
        prompt: ($$value) => {
          settings.prompts.answerQuestion[1] = $$value;
          $$settled = false;
        }
      },
      {}
    )} ${validate_component(LlmSelector, "LlmSelector").$$render(
      $$result,
      {
        skipLoadList: true,
        selectedLLM: settings.llmParams.answerQuestion
      },
      {
        selectedLLM: ($$value) => {
          settings.llmParams.answerQuestion = $$value;
          $$settled = false;
        }
      },
      {}
    )}</div> <div><div data-svelte-h="svelte-bu8rgi">Финальный ответ</div> ${validate_component(ModalPromptEditor, "ModalPromptEditor").$$render(
      $$result,
      {
        label: "system промпт",
        prompt: settings.prompts.generateFinalAnswer[0]
      },
      {
        prompt: ($$value) => {
          settings.prompts.generateFinalAnswer[0] = $$value;
          $$settled = false;
        }
      },
      {}
    )} ${validate_component(ModalPromptEditor, "ModalPromptEditor").$$render(
      $$result,
      {
        label: "user промпт",
        prompt: settings.prompts.generateFinalAnswer[1]
      },
      {
        prompt: ($$value) => {
          settings.prompts.generateFinalAnswer[1] = $$value;
          $$settled = false;
        }
      },
      {}
    )} ${validate_component(LlmSelector, "LlmSelector").$$render(
      $$result,
      {
        skipLoadList: true,
        selectedLLM: settings.llmParams.generateFinalAnswer
      },
      {
        selectedLLM: ($$value) => {
          settings.llmParams.generateFinalAnswer = $$value;
          $$settled = false;
        }
      },
      {}
    )}</div></form> </div>`;
  } while (!$$settled);
  return $$rendered;
});
const css = {
  code: '.loading-container.svelte-fiifsz.svelte-fiifsz{display:flex;justify-content:center;align-items:center;align-self:center;width:3rem;height:90%;margin-left:5px}.loading-status.svelte-fiifsz.svelte-fiifsz{display:flex;justify-content:center;align-items:center;align-self:center}.grow-wrap.svelte-fiifsz.svelte-fiifsz{display:grid}.grow-wrap.svelte-fiifsz.svelte-fiifsz::after{content:attr(data-replicated-value) " ";white-space:pre-wrap;visibility:hidden;max-width:100%;max-height:250px;display:block;overflow-x:hidden}.grow-wrap.svelte-fiifsz>textarea.svelte-fiifsz{resize:none}.grow-wrap.svelte-fiifsz>textarea.svelte-fiifsz,.grow-wrap.svelte-fiifsz.svelte-fiifsz::after{border:1px solid #ccc;width:100%;padding:1rem;font-size:14px;box-sizing:border-box;grid-area:1/1/2/2}.grow-wrap.svelte-fiifsz>textarea .svelte-fiifsz:focus,.grow-wrap.svelte-fiifsz::after .svelte-fiifsz:focus{outline:none;border-color:#1976d2}.grow-wrap.svelte-fiifsz>textarea .svelte-fiifsz:placeholder,.grow-wrap.svelte-fiifsz::after .svelte-fiifsz:placeholder{color:#aaa}.auto-expand-textarea.svelte-fiifsz.svelte-fiifsz{box-sizing:border-box;width:100%;font-size:16px;border:1px solid #ccc;resize:vertical;overflow-y:auto;min-height:1rem}.search-column.svelte-fiifsz.svelte-fiifsz{flex:1;display:flex;flex-direction:column;border-right:1px solid #ccc}.search-bar.svelte-fiifsz textarea.svelte-fiifsz{width:100%;max-width:100%;padding:1rem;box-sizing:border-box}.textarea-column.svelte-fiifsz.svelte-fiifsz{flex:1;display:flex;flex-direction:column;padding-left:10px}.textarea.svelte-fiifsz.svelte-fiifsz{width:100%;height:100%;margin:10px;margin-left:0px;border:none;outline:none;resize:none;background:transparent}@media(max-width: 767px){.search-column.svelte-fiifsz.svelte-fiifsz,.textarea-column.svelte-fiifsz.svelte-fiifsz{border-right:none}}.search-second-bar.svelte-fiifsz.svelte-fiifsz{display:flex;flex-wrap:wrap}@media(max-width: 600px){.search-second-bar.svelte-fiifsz.svelte-fiifsz{flex-direction:column}}textarea.svelte-fiifsz.svelte-fiifsz{border:1px solid #ccc;width:100%;font-size:14px;box-sizing:border-box;padding:1rem}a.svelte-fiifsz.svelte-fiifsz{cursor:pointer}.reference-btn.svelte-fiifsz.svelte-fiifsz{text-decoration:none;color:black}.reference-btn.svelte-fiifsz.svelte-fiifsz:hover{text-decoration:none;color:black}',
  map: null
};
const Page = create_ssr_component(($$result, $$props, $$bindings, slots) => {
  let { data } = $$props;
  const { ENV_DOCUMENT_DB_URL, ENV_ENABLE_DOCUMENT_DB, ENV_ENABLE_DB_SUPPORT, ENV_ENABLE_DEV_FEATURES, ENV_DISABLE_HEALTH_CHECKS, ENV_FAQ_DOCUMENT_ID } = data;
  let Model = data.Model;
  let searchResultComponent;
  let userLlmClarification = "";
  let searchCategories = {
    НКРФ: false,
    ГКРФ: false,
    ТКРФ: false,
    "Федеральный закон": false,
    "Письмо Минфина": false,
    "Письмо ФНС": false,
    "Приказ ФНС": false,
    "Постановление Правительства": false,
    "Судебный документ": false,
    ВНД: false,
    "Бухгалтерский документ": false
  };
  onDestroy(() => {
    cancelRequest();
  });
  let usedSearchResults = [];
  let relevantConsultations = [];
  let isSearchLoading = false;
  let isLlmLoading = false;
  let isSearchInitiated = false;
  let baseLlmResponse = "";
  let currentUserRequest = "";
  let savedUserRequest = "";
  let loadingStatusText = "";
  let showFullText = [];
  Array(relevantConsultations.length).fill(false);
  let useSearchResult;
  let enableSearchResultSelection = false;
  let searchInTransactionLedger = false;
  let enableQueryExpansionSearch = false;
  let searchLlmParams = DEFAULT_SEARCH_INPUT_PARAMS.llm_params;
  let useShortestPrompt = false;
  let shortestPromptGenerationFinished = false;
  let enableRealtimeLlmReponse = false;
  let showRatingBlock = false;
  let showClarifyLlmResponseButton = false;
  let isClarificationPaneVisible = false;
  let showOnlyUsedByLlmSearchResults = false;
  let lastLogId = null;
  let submitButtonLabel = "Отправить";
  let abortController = new AbortController();
  const cancelRequest = () => {
    abortController.abort("user canceled");
    abortController = new AbortController();
    isLlmLoading = false;
    loadingStatusText = "";
    lastLogId = null;
    isSearchInitiated = false;
    isSearchLoading = false;
    usedSearchResults = [];
    showOnlyUsedByLlmSearchResults = false;
  };
  async function handleRatingSubmit(data2) {
    console.log(`Оценка: ${data2.rating} звезд, Комментарий: ${data2.comment}`);
    if (lastLogId !== null) {
      await LogService.logUserScore(lastLogId, data2.rating, data2.comment);
    }
  }
  let selectedLlm;
  if ($$props.data === void 0 && $$bindings.data && data !== void 0)
    $$bindings.data(data);
  $$result.css.add(css);
  let $$settled;
  let $$rendered;
  let previous_head = $$result.head;
  do {
    $$settled = true;
    $$result.head = previous_head;
    {
      {
        {
          searchInTransactionLedger = false;
        }
        if (userLlmClarification && (Model.search?.searchResults || []).length > 0 && baseLlmResponse && savedUserRequest == currentUserRequest && !isLlmLoading) {
          showClarifyLlmResponseButton = true;
        } else {
          showClarifyLlmResponseButton = false;
        }
      }
    }
    submitButtonLabel = isSearchInitiated || isLlmLoading || isSearchLoading ? "Стоп" : "Отправить";
    $$rendered = `<div class="${[
      "absolute top-0 left-0 w-full bg-black text-white shadow-lg z-50 h-15",
      !ENV_ENABLE_DEV_FEATURES ? "hidden" : ""
    ].join(" ").trim()}"><div class="mx-auto flex items-center justify-between"><div class="status-components justify-between align-middle flex m-2"><div class="flex-wrap justify-between">${validate_component(LlmHealthStatus, "LlmHealthStatus").$$render(
      $$result,
      {
        disableIntervalChecks: Boolean(ENV_DISABLE_HEALTH_CHECKS)
      },
      {},
      {}
    )} ${validate_component(SearchApiHealthStatus, "SearchApiHealthStatus").$$render(
      $$result,
      {
        disableIntervalChecks: Boolean(ENV_DISABLE_HEALTH_CHECKS)
      },
      {},
      {}
    )} ${validate_component(LlmSelector, "LlmSelector").$$render(
      $$result,
      { selectedLLM: selectedLlm },
      {
        selectedLLM: ($$value) => {
          selectedLlm = $$value;
          $$settled = false;
        }
      },
      {}
    )} ${searchLlmParams ? `${validate_component(SearchSettings, "SearchSettings").$$render(
      $$result,
      { llmParams: searchLlmParams },
      {
        llmParams: ($$value) => {
          searchLlmParams = $$value;
          $$settled = false;
        }
      },
      {}
    )}` : ``} <label class="inline-block cursor-pointer"><input type="checkbox"${add_attribute("checked", Model.useInvestigator, 1)}> Использовать почемучки</label> ${Model.investigatorSettings !== null ? `<div class="${["inline-block", !Model.useInvestigator ? "hidden" : ""].join(" ").trim()}">${validate_component(InvestigatorSettings, "InvestigatorSettings").$$render(
      $$result,
      { settings: Model.investigatorSettings },
      {
        settings: ($$value) => {
          Model.investigatorSettings = $$value;
          $$settled = false;
        }
      },
      {}
    )}</div>` : ``}</div></div></div></div> <section${add_classes((ENV_ENABLE_DEV_FEATURES ? "mt-16" : "").trim())}><div class="search-bar flex flex-wrap px-2 pt-2 svelte-fiifsz"><div class="grow-wrap w-full svelte-fiifsz"> <textarea class="auto-expand-textarea rounded-sm svelte-fiifsz" rows="1" placeholder="Введите ваш запрос (Ctrl+Enter для отправки)">${escape("")}</textarea></div> <div class="search-second-bar w-full flex justify-end svelte-fiifsz"><div class="flex justify-end flex-wrap gap-2 m-2 mr-0 ml-0"><a${add_attribute("href", `${ENV_DOCUMENT_DB_URL}file/view/id/${ENV_FAQ_DOCUMENT_ID}`, 0)} target="_blank" rel="noopener noreferrer" class="btn variant-outline-tertiary reference-btn svelte-fiifsz"><i class="fa-regular fa-circle-question"></i> Справка</a> <button class="${[
      "chip " + escape(
        "variant-soft-primary",
        true
      ),
      "hidden"
    ].join(" ").trim()}">${escape("Уточнить")}</button>  ${`${validate_component(SearchTypeSelector, "SearchTypeSelector").$$render(
      $$result,
      {
        use_olympic: Model.useInvestigator,
        use_qe: enableQueryExpansionSearch
      },
      {
        use_olympic: ($$value) => {
          Model.useInvestigator = $$value;
          $$settled = false;
        },
        use_qe: ($$value) => {
          enableQueryExpansionSearch = $$value;
          $$settled = false;
        }
      },
      {}
    )}`} <button class="${"chip " + escape(
      "variant-soft-primary",
      true
    )}">${``} <span data-svelte-h="svelte-1cu0b9t">Искать карту проводок по вопросу</span></button> ${validate_component(DocumentTypeSelector, "DocumentTypeSelector").$$render(
      $$result,
      {
        disabled: searchInTransactionLedger,
        selected: searchCategories
      },
      {
        disabled: ($$value) => {
          searchInTransactionLedger = $$value;
          $$settled = false;
        },
        selected: ($$value) => {
          searchCategories = $$value;
          $$settled = false;
        }
      },
      {}
    )}  <button title="Ctrl+Enter" ${!loadingStatusText ? "disabled" : ""} class="btn variant-filled-primary w-40">${escape(submitButtonLabel)}</button></div></div> <div class="flex space-x-2 items-center justify-center w-full">${isSearchLoading || isLlmLoading ? `<div class="loading-status svelte-fiifsz">${escape(loadingStatusText)}</div> <div class="loading-container svelte-fiifsz">${validate_component(LoadingSpinner, "LoadingSpinner").$$render($$result, {}, {}, {})}</div>` : ``}</div> <div class="${["w-full", "hidden"].join(" ").trim()}">${validate_component(UserClarification, "UserClarification").$$render(
      $$result,
      { llmClarification: userLlmClarification },
      {
        llmClarification: ($$value) => {
          userLlmClarification = $$value;
          $$settled = false;
        }
      },
      {}
    )}</div> ${``} <div class="w-full my-2">${``}</div> ${``} <div${add_classes((!/*isSearchInitiated ||*/
    (((Model.search?.searchResults || []).length > 0 || relevantConsultations && relevantConsultations.length > 0) && !searchInTransactionLedger) ? "hidden" : "").trim())}>${validate_component(Splitpanes, "Splitpanes").$$render($$result, { theme: "modern-theme" }, {}, {
      default: () => {
        return `${validate_component(Pane, "Pane").$$render(
          $$result,
          {
            minSize: 20,
            class: "search-column",
            size: 49
          },
          {},
          {
            default: () => {
              return `<div class="search-column svelte-fiifsz">${Model.search?.searchResults ? `${validate_component(SearchResults, "SearchResults").$$render(
                $$result,
                {
                  enableDocumentDb: ENV_ENABLE_DOCUMENT_DB,
                  documentDbUrl: ENV_DOCUMENT_DB_URL,
                  this: searchResultComponent,
                  searchResults: Model.search.searchResults,
                  usedSearchResults,
                  showFullText,
                  useSearchResult,
                  enableSearchResultSelection,
                  searchInTransactionLedger,
                  showOnlyLlmUsed: showOnlyUsedByLlmSearchResults
                },
                {
                  this: ($$value) => {
                    searchResultComponent = $$value;
                    $$settled = false;
                  },
                  searchResults: ($$value) => {
                    Model.search.searchResults = $$value;
                    $$settled = false;
                  },
                  usedSearchResults: ($$value) => {
                    usedSearchResults = $$value;
                    $$settled = false;
                  },
                  showFullText: ($$value) => {
                    showFullText = $$value;
                    $$settled = false;
                  },
                  useSearchResult: ($$value) => {
                    useSearchResult = $$value;
                    $$settled = false;
                  },
                  enableSearchResultSelection: ($$value) => {
                    enableSearchResultSelection = $$value;
                    $$settled = false;
                  },
                  searchInTransactionLedger: ($$value) => {
                    searchInTransactionLedger = $$value;
                    $$settled = false;
                  },
                  showOnlyLlmUsed: ($$value) => {
                    showOnlyUsedByLlmSearchResults = $$value;
                    $$settled = false;
                  }
                },
                {}
              )}` : ``} ${Model.search?.explanations ? `${validate_component(Explanations, "Explanations").$$render(
                $$result,
                { explanations: Model.search.explanations },
                {
                  explanations: ($$value) => {
                    Model.search.explanations = $$value;
                    $$settled = false;
                  }
                },
                {}
              )}` : ``} ${relevantConsultations && relevantConsultations.length > 0 ? `${validate_component(RelevantConsultations, "RelevantConsultations").$$render(
                $$result,
                { consultations: relevantConsultations },
                {
                  consultations: ($$value) => {
                    relevantConsultations = $$value;
                    $$settled = false;
                  }
                },
                {}
              )}` : ``}</div>`;
            }
          }
        )} ${validate_component(Pane, "Pane").$$render($$result, { size: 49 }, {}, {
          default: () => {
            return `<div class="textarea-column svelte-fiifsz"><div class="textarea svelte-fiifsz"><button class="${[
              "btn variant-filled",
              !(enableSearchResultSelection && (Model.search?.searchResults || []).length > 0 && !showClarifyLlmResponseButton) ? "hidden" : ""
            ].join(" ").trim()}" data-svelte-h="svelte-1fu5ju8">Получить ответ</button> <button class="${[
              "btn variant-filled",
              !showClarifyLlmResponseButton || !isClarificationPaneVisible ? "hidden" : ""
            ].join(" ").trim()}" data-svelte-h="svelte-1jv1usb">Уточнить ответ</button> <div class="textarea svelte-fiifsz">${!isLlmLoading || enableRealtimeLlmReponse || Model.llmFinalAnswer && useShortestPrompt && shortestPromptGenerationFinished ? `<!-- HTML_TAG_START -->${Model.llmFinalAnswer.replaceAll("\n", "<br>")}<!-- HTML_TAG_END -->` : ``}</div> <button class="${[
              "btn variant-filled mb-4 mt-4",
              !Model.llmFinalAnswer ? "hidden" : ""
            ].join(" ").trim()}" data-svelte-h="svelte-1n8n71z">Скачать ответ в Word</button> ${Model.llmFinalAnswer && showRatingBlock && ENV_ENABLE_DB_SUPPORT ? `${validate_component(Rating, "Rating").$$render($$result, { onSubmit: handleRatingSubmit }, {}, {})}` : ``}</div></div>`;
          }
        })}`;
      }
    })}</div></div> </section>`;
  } while (!$$settled);
  return $$rendered;
});

export { Page as default };
//# sourceMappingURL=_page.svelte-utVVFjse.js.map