Repository navigation
Expand file tree
/
Copy pathunf.php
More file actions
819 lines (697 loc) · 29.5 KB
/
Copy pathunf.php
File metadata and controls
819 lines (697 loc) · 29.5 KB
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
<?php
declare(strict_types=1);
require_once __DIR__ . '/config.php';
const UNF_ZERO_GUID = '00000000-0000-0000-0000-000000000000';
const UNF_DAY_ZERO_TIME = '0001-01-01T00:00:00';
// Предохранитель на число строк в «Операциях»: 10 строк — это 1680 часов,
// вчетверо больше самого длинного месяца. Дальше данные точно битые.
const UNF_TIME_MAX_OPERATION_ROWS = 10;
function unfOdataRequest(string $method, string $path, ?array $payload = null, array $params = []): array
{
if (UNF_ODATA_USER === '' || UNF_ODATA_PASSWORD === '') {
throw new RuntimeException('Не настроены UNF_ODATA_USER и UNF_ODATA_PASSWORD.');
}
$url = unfOdataUrl($path, $params);
$headers = [
'Accept: application/json',
'Authorization: Basic ' . base64_encode(UNF_ODATA_USER . ':' . UNF_ODATA_PASSWORD),
];
$body = null;
if ($payload !== null) {
$body = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($body)) {
throw new RuntimeException('Не удалось подготовить JSON для УНФ.');
}
$headers[] = 'Content-Type: application/json; charset=utf-8';
}
if (function_exists('curl_init')) {
$curl = curl_init();
$options = [
CURLOPT_CUSTOMREQUEST => $method,
CURLOPT_HEADER => false,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_URL => $url,
CURLOPT_CONNECTTIMEOUT => 20,
CURLOPT_TIMEOUT => 180,
];
if ($body !== null) {
$options[CURLOPT_POSTFIELDS] = $body;
}
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$error = curl_error($curl);
$statusCode = (int)curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if ($response === false) {
throw new RuntimeException('Ошибка запроса к УНФ: ' . $error);
}
} else {
$contextHeaders = implode("\r\n", $headers) . "\r\n";
$context = stream_context_create([
'http' => [
'method' => $method,
'header' => $contextHeaders,
'content' => $body ?? '',
'ignore_errors' => true,
'timeout' => 180,
],
'ssl' => [
'verify_peer' => false,
'verify_peer_name' => false,
],
]);
$response = file_get_contents($url, false, $context);
$statusCode = 0;
foreach (($http_response_header ?? []) as $headerLine) {
if (preg_match('/^HTTP\/\S+\s+(\d+)/', $headerLine, $matches)) {
$statusCode = (int)$matches[1];
break;
}
}
if ($response === false) {
throw new RuntimeException('Ошибка запроса к УНФ.');
}
}
$decoded = [];
if ($response !== '') {
$decoded = json_decode($response, true);
if (!is_array($decoded)) {
throw new RuntimeException('УНФ вернула некорректный JSON.');
}
}
if ($statusCode >= 400) {
throw new RuntimeException('Ошибка УНФ OData: ' . unfOdataErrorMessage($decoded, $statusCode));
}
return $decoded;
}
function unfOdataUrl(string $path, array $params = []): string
{
$segments = array_filter(explode('/', ltrim($path, '/')), static function (string $segment): bool {
return $segment !== '';
});
$encodedPath = implode('/', array_map('rawurlencode', $segments));
$query = $params !== [] ? '?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986) : '';
return rtrim(UNF_ODATA_BASE_URL, '/') . '/' . $encodedPath . $query;
}
function unfOdataErrorMessage(array $decoded, int $statusCode): string
{
$paths = [
['error', 'message', 'value'],
['error', 'message'],
['odata.error', 'message', 'value'],
['odata.error', 'message'],
];
foreach ($paths as $path) {
$value = $decoded;
foreach ($path as $key) {
if (!is_array($value) || !array_key_exists($key, $value)) {
continue 2;
}
$value = $value[$key];
}
if (is_scalar($value) && (string)$value !== '') {
return (string)$value;
}
}
return 'HTTP ' . $statusCode;
}
function unfOdataValues(array $response): array
{
if (isset($response['value']) && is_array($response['value'])) {
return $response['value'];
}
if (isset($response['d']['results']) && is_array($response['d']['results'])) {
return $response['d']['results'];
}
return [];
}
function unfOdataEntity(array $response): array
{
if (isset($response['d']) && is_array($response['d']) && !isset($response['d']['results'])) {
return $response['d'];
}
return $response;
}
function unfFetchEmployees(): array
{
static $employees = null;
if (is_array($employees)) {
return $employees;
}
$employees = [];
$top = 500;
$skip = 0;
do {
$response = unfOdataRequest('GET', 'Catalog_Сотрудники', null, [
'$format' => 'json',
'$select' => 'Ref_Key,Description,DeletionMark',
'$orderby' => 'Description',
'$top' => (string)$top,
'$skip' => (string)$skip,
]);
$items = unfOdataValues($response);
foreach ($items as $item) {
if (!is_array($item) || (bool)($item['DeletionMark'] ?? false)) {
continue;
}
$key = (string)($item['Ref_Key'] ?? '');
$description = trim((string)($item['Description'] ?? ''));
if ($key === '' || $description === '') {
continue;
}
$employees[] = [
'Ref_Key' => $key,
'Description' => $description,
'normalized' => unfNormalizeName($description),
'tokens' => unfNameTokens($description),
];
}
$skip += $top;
} while (count($items) === $top);
if ($employees === []) {
throw new RuntimeException('В УНФ не найдены сотрудники через Catalog_Сотрудники.');
}
return $employees;
}
function unfFindEmployeeForReportRow(array $row, array $employees): array
{
$bitrixUserId = (string)(int)($row['id'] ?? 0);
$name = trim((string)($row['name'] ?? ''));
$normalized = unfNormalizeName($name);
$configuredKey = unfConfiguredEmployeeKey($bitrixUserId, $name, $normalized);
if ($configuredKey !== '') {
return [
'Ref_Key' => $configuredKey,
'Description' => $name !== '' ? $name : 'Bitrix user ' . $bitrixUserId,
];
}
foreach ($employees as $employee) {
if ($employee['normalized'] === $normalized) {
return $employee;
}
}
$tokens = unfNameTokens($name);
$matches = [];
foreach ($employees as $employee) {
if (unfTokensAreSubset($tokens, $employee['tokens'])) {
$matches[] = $employee;
}
}
if (count($matches) === 1) {
return $matches[0];
}
if (count($matches) > 1) {
$names = array_map(static function (array $employee): string {
return (string)$employee['Description'];
}, array_slice($matches, 0, 5));
throw new RuntimeException('Найдено несколько сотрудников УНФ для "' . $name . '": ' . implode(', ', $names));
}
throw new RuntimeException('Не найден сотрудник УНФ для "' . $name . '". Добавьте соответствие в UNF_EMPLOYEE_KEY_MAP.');
}
function unfConfiguredEmployeeKey(string $bitrixUserId, string $name, string $normalizedName): string
{
$map = UNF_EMPLOYEE_KEY_MAP;
$keys = [$bitrixUserId, $name, $normalizedName];
foreach ($keys as $key) {
if ($key !== '' && isset($map[$key]) && is_scalar($map[$key])) {
return (string)$map[$key];
}
}
return '';
}
function unfNormalizeName(string $name): string
{
$name = str_replace(['Ё', 'ё'], ['Е', 'е'], $name);
if (function_exists('mb_strtolower')) {
$name = mb_strtolower($name, 'UTF-8');
} else {
$name = strtolower($name);
}
$cleaned = preg_replace('/[^\p{L}\p{N}\s]+/u', ' ', $name);
if (is_string($cleaned)) {
$name = $cleaned;
}
$collapsed = preg_replace('/\s+/u', ' ', trim($name));
return is_string($collapsed) ? $collapsed : trim($name);
}
function unfNameTokens(string $name): array
{
$normalized = unfNormalizeName($name);
if ($normalized === '') {
return [];
}
$tokens = preg_split('/\s+/u', $normalized);
if (!is_array($tokens)) {
return [];
}
$tokens = array_values(array_unique(array_filter($tokens, static function (string $token): bool {
return $token !== '';
})));
sort($tokens);
return $tokens;
}
function unfTokensAreSubset(array $required, array $available): bool
{
if ($required === []) {
return false;
}
foreach ($required as $token) {
if (!in_array($token, $available, true)) {
return false;
}
}
return true;
}
function createUnfTimeDocumentsForReport(array $report): array
{
$period = (string)($report['period'] ?? '');
[$documentDate, $dateFrom, $dateTo] = unfTimeDocumentDates($period);
$rows = array_values(array_filter((array)($report['rows'] ?? []), static function ($row): bool {
return is_array($row);
}));
$created = [];
$skipped = [];
$errors = [];
foreach ($rows as $row) {
$name = (string)($row['name'] ?? '');
$hours = round((float)($row['hours'] ?? 0), 2);
$bitrixUserId = (int)($row['id'] ?? 0);
if ($hours <= 0) {
$skipped[] = [
'bitrix_user_id' => $bitrixUserId,
'name' => $name,
'hours' => $hours,
'reason' => 'Нулевые часы',
];
}
}
$rowsToCreate = array_values(array_filter($rows, static function (array $row): bool {
return round((float)($row['hours'] ?? 0), 2) > 0;
}));
if ($rowsToCreate !== []) {
$employees = unfFetchEmployees();
foreach ($rowsToCreate as $row) {
$name = (string)($row['name'] ?? '');
$hours = round((float)($row['hours'] ?? 0), 2);
$bitrixUserId = (int)($row['id'] ?? 0);
try {
$employee = unfFindEmployeeForReportRow($row, $employees);
$existing = unfFindExistingTimeDocument((string)$employee['Ref_Key'], $dateFrom, $dateTo);
if ($existing !== null) {
$skipped[] = [
'bitrix_user_id' => $bitrixUserId,
'name' => $name,
'hours' => $hours,
'reason' => 'Документ за эту неделю уже есть',
'existing_number' => (string)($existing['Number'] ?? ''),
'existing_ref_key' => (string)($existing['Ref_Key'] ?? ''),
];
continue;
}
$payload = unfBuildTimeDocumentPayload($row, (string)$employee['Ref_Key'], $period, $documentDate, $dateFrom, $dateTo);
$document = unfOdataEntity(unfOdataRequest('POST', 'Document_УчетВремени', $payload, ['$format' => 'json']));
if (UNF_TIME_POST_DOCUMENTS && isset($document['Ref_Key'])) {
unfOdataRequest('POST', "Document_УчетВремени(guid'" . $document['Ref_Key'] . "')/Post()");
}
$created[] = [
'bitrix_user_id' => $bitrixUserId,
'name' => $name,
'hours' => $hours,
'number' => (string)($document['Number'] ?? ''),
'ref_key' => (string)($document['Ref_Key'] ?? ''),
'posted' => UNF_TIME_POST_DOCUMENTS,
];
} catch (Throwable $e) {
$errors[] = [
'bitrix_user_id' => $bitrixUserId,
'name' => $name,
'hours' => $hours,
'error' => $e->getMessage(),
];
}
}
}
return [
'ok' => $errors === [],
'period' => $period,
'month_title' => (string)($report['month_title'] ?? $period),
'source' => [
'rows' => count($rows),
'total_hours' => round((float)($report['total_hours'] ?? 0), 2),
],
'unf_period' => [
'date' => unfOdataDate($documentDate),
'date_from' => unfOdataDate($dateFrom),
'date_to' => unfOdataDate($dateTo),
],
'created' => $created,
'skipped' => $skipped,
'errors' => $errors,
];
}
function unfTimeDocumentDates(string $period): array
{
if (!preg_match('/^\d{4}-\d{2}$/', $period)) {
throw new InvalidArgumentException('Укажите месяц в формате YYYY-MM.');
}
$monthStart = DateTimeImmutable::createFromFormat('!Y-m-d', $period . '-01');
if (!$monthStart) {
throw new InvalidArgumentException('Некорректный месяц отчёта.');
}
$monthEnd = $monthStart->modify('last day of this month');
$documentDate = $monthEnd->setTime(12, 0, 0);
$dateFrom = ((int)$monthStart->format('N') === 1 ? $monthStart : $monthStart->modify('next monday'))->setTime(0, 0, 0);
$dateTo = $dateFrom->modify('+6 days')->setTime(0, 0, 0);
if ($dateTo > $monthEnd->setTime(23, 59, 59)) {
throw new RuntimeException('В выбранном месяце не найдена полная неделя для документа УНФ.');
}
return [$documentDate, $dateFrom, $dateTo];
}
function unfBuildTimeDocumentPayload(
array $row,
string $employeeKey,
string $period,
DateTimeImmutable $documentDate,
DateTimeImmutable $dateFrom,
DateTimeImmutable $dateTo
): array {
$hours = round((float)($row['hours'] ?? 0), 2);
$operationRows = unfDistributeHours($hours);
$rate = round((float)UNF_TIME_RATE, 2);
// Время "С"/"По" по дням: 24 ч -> 00:00-23:59, 22 ч -> 00:00-22:00 и т.д.
$dayPrefixes = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
// Одна строка табличной части вмещает максимум 168 часов (7 дней по 24),
// поэтому остаток уходит в следующую строку и снова считается с понедельника.
$operations = [];
foreach ($operationRows as $index => $dayDurations) {
$rowHours = round(array_sum($dayDurations), 2);
$dayTimes = [];
foreach ($dayPrefixes as $dayIndex => $prefix) {
$duration = (float)($dayDurations[$dayIndex] ?? 0);
$dayTimes[$prefix . 'ВремяНачала'] = UNF_DAY_ZERO_TIME;
$dayTimes[$prefix . 'ВремяОкончания'] = $duration > 0 ? unfTimeOfDay($duration) : UNF_DAY_ZERO_TIME;
}
$operations[] = [
'LineNumber' => (string)($index + 1),
'Заказчик' => '',
'Заказчик_Type' => 'StandardODATA.Undefined',
'ВидРабот_Key' => UNF_TIME_WORK_TYPE_KEY,
'Номенклатура_Key' => UNF_TIME_NOMENCLATURE_KEY,
'Характеристика_Key' => UNF_ZERO_GUID,
'Расценка' => $rate,
'ВидЦен_Key' => UNF_TIME_PRICE_TYPE_KEY,
'Всего' => $rowHours,
'ПнДлительность' => $dayDurations[0],
'ВтДлительность' => $dayDurations[1],
'СрДлительность' => $dayDurations[2],
'ЧтДлительность' => $dayDurations[3],
'ПтДлительность' => $dayDurations[4],
'СбДлительность' => $dayDurations[5],
'ВсДлительность' => $dayDurations[6],
'Сумма' => round($rate * $rowHours, 2),
'Комментарий' => '',
] + $dayTimes;
}
return [
'Date' => unfOdataDate($documentDate),
'DeletionMark' => false,
'Posted' => false,
'Организация_Key' => UNF_TIME_ORGANIZATION_KEY,
'СтруктурнаяЕдиница_Key' => UNF_TIME_STRUCTURAL_UNIT_KEY,
'Сотрудник_Key' => $employeeKey,
'Комментарий' => unfTimeDocumentComment($row, $period),
'ДатаС' => unfOdataDate($dateFrom),
'ДатаПо' => unfOdataDate($dateTo),
'Автор_Key' => UNF_TIME_AUTHOR_KEY,
'ХозяйственнаяОперация_Key' => UNF_TIME_BUSINESS_OPERATION_KEY,
'ДокументОснование_Key' => UNF_ZERO_GUID,
'Операции' => $operations,
];
}
function unfFormatHours(float $hours): string
{
$formatted = number_format($hours, 2, '.', '');
return rtrim(rtrim($formatted, '0'), '.');
}
function unfTimeOfDay(float $hours): string
{
// 24 часа в УНФ записываются как 00:00-23:59 (само значение часов хранится в Длительности).
if ($hours >= 24) {
return '0001-01-01T23:59:00';
}
$totalMinutes = (int)round($hours * 60);
return sprintf('0001-01-01T%02d:%02d:00', intdiv($totalMinutes, 60), $totalMinutes % 60);
}
function unfTimeDocumentComment(array $row, string $period): string
{
$name = trim((string)($row['name'] ?? ''));
$bitrixUserId = (int)($row['id'] ?? 0);
$hours = round((float)($row['hours'] ?? 0), 2);
return trim('#Загружено_task2; загружено ' . unfFormatHours($hours) . ' ч за ' . $period . '; Bitrix user ' . $bitrixUserId . '; ' . $name);
}
/**
* Раскладывает часы по дням недели строками табличной части.
*
* В одну строку «Операций» помещается максимум 168 часов — 7 дней по 24.
* Если часов больше, остаток уходит в следующую строку и снова считается с
* понедельника: ровно так документ заполняется руками (эталон — КДНФ-000085,
* где 168.5 ч легли как 168 в первой строке и 0.5 во второй).
*
* @return array<int, array<int, float>> Список строк, в каждой 7 длительностей.
*/
function unfDistributeHours(float $hours): array
{
if ($hours < 0) {
throw new InvalidArgumentException('Количество часов не может быть отрицательным.');
}
$remaining = round($hours, 2);
$rows = [];
do {
$days = [];
for ($day = 0; $day < 7; $day++) {
$duration = min(24.0, max(0.0, $remaining));
$duration = round($duration, 2);
$days[] = $duration;
$remaining = round($remaining - $duration, 2);
}
$rows[] = $days;
} while ($remaining > 0 && count($rows) < UNF_TIME_MAX_OPERATION_ROWS);
if ($remaining > 0) {
// В месяце физически не больше 744 часов, так что сюда попадают только
// испорченные данные — молча резать часы в документе для счёта нельзя.
throw new RuntimeException(sprintf(
'Не удалось разложить %s ч: это больше %d часов, максимума для %d строк документа. Проверьте списания времени в Битриксе.',
unfFormatHours($hours),
UNF_TIME_MAX_OPERATION_ROWS * 168,
UNF_TIME_MAX_OPERATION_ROWS
));
}
return $rows;
}
function unfFindExistingTimeDocument(string $employeeKey, DateTimeImmutable $dateFrom, DateTimeImmutable $dateTo): ?array
{
// Помеченный на удаление документ не считается существующим: иначе после
// удаления неудачного документа кнопка молча пропускала бы сотрудника.
$filter = "Сотрудник_Key eq guid'" . $employeeKey . "'"
. " and ДатаС eq datetime'" . unfOdataDate($dateFrom) . "'"
. " and ДатаПо eq datetime'" . unfOdataDate($dateTo) . "'"
. " and DeletionMark eq false";
$response = unfOdataRequest('GET', 'Document_УчетВремени', null, [
'$format' => 'json',
'$select' => 'Ref_Key,Number,Date,Posted,Сотрудник_Key,ДатаС,ДатаПо,Комментарий',
'$filter' => $filter,
'$top' => '1',
]);
$items = unfOdataValues($response);
if ($items === []) {
return null;
}
return is_array($items[0]) ? $items[0] : null;
}
function unfOdataDate(DateTimeImmutable $date): string
{
return $date->format('Y-m-d\TH:i:s');
}
/* =====================================================================
* Задания на работу (Document_ЗаданиеНаРаботу)
* ===================================================================== */
function unfWorkOrderDates(string $period): array
{
if (!preg_match('/^\d{4}-\d{2}$/', $period)) {
throw new InvalidArgumentException('Укажите месяц в формате YYYY-MM.');
}
$monthStart = DateTimeImmutable::createFromFormat('!Y-m-d', $period . '-01');
if (!$monthStart) {
throw new InvalidArgumentException('Некорректный месяц отчёта.');
}
// Задание создаётся 1-м числом СЛЕДУЮЩЕГО месяца и действует весь этот месяц.
$nextMonthStart = $monthStart->modify('first day of next month');
$documentDate = $nextMonthStart->setTime(12, 0, 0);
$dateFrom = $nextMonthStart->setTime(0, 0, 0);
$dateTo = $nextMonthStart->modify('last day of this month')->setTime(23, 59, 59);
return [$documentDate, $dateFrom, $dateTo];
}
function unfFindExistingWorkOrder(string $employeeKey, DateTimeImmutable $dateFrom): ?array
{
$filter = "Сотрудник_Key eq guid'" . $employeeKey . "'"
. " and ДатаНачала eq datetime'" . unfOdataDate($dateFrom) . "'"
. " and DeletionMark eq false";
$response = unfOdataRequest('GET', 'Document_ЗаданиеНаРаботу', null, [
'$format' => 'json',
'$select' => 'Ref_Key,Number,Date,Posted,Сотрудник_Key,ДатаНачала,ДатаОкончания',
'$filter' => $filter,
'$top' => '1',
]);
$items = unfOdataValues($response);
if ($items === []) {
return null;
}
return is_array($items[0]) ? $items[0] : null;
}
function unfBuildWorkOrderPayload(
array $row,
string $employeeKey,
string $period,
float $planHours,
DateTimeImmutable $documentDate,
DateTimeImmutable $dateFrom,
DateTimeImmutable $dateTo
): array {
$rate = round((float)UNF_WORK_ORDER_RATE, 2);
$sum = round($rate * $planHours, 2);
return [
'Date' => unfOdataDate($documentDate),
'DeletionMark' => false,
'Posted' => false,
'ВидОперации' => 'Внешнее',
'ВидРабот_Key' => UNF_TIME_WORK_TYPE_KEY,
'ВидЦен_Key' => UNF_TIME_PRICE_TYPE_KEY,
'ДатаНачала' => unfOdataDate($dateFrom),
'ДатаОкончания' => unfOdataDate($dateTo),
'КалендарьСотрудника_Key' => UNF_WORK_ORDER_CALENDAR_KEY,
'Комментарий' => unfWorkOrderComment($row, $period, $planHours),
'Организация_Key' => UNF_TIME_ORGANIZATION_KEY,
'ПодписьМОЛ_Key' => UNF_ZERO_GUID,
'ПоложениеВидаРабот' => 'ВШапке',
'Событие_Key' => UNF_ZERO_GUID,
'Состояние_Key' => UNF_WORK_ORDER_STATE_KEY,
'Сотрудник_Key' => $employeeKey,
'СтруктурнаяЕдиница_Key' => UNF_TIME_STRUCTURAL_UNIT_KEY,
'СуммаДокумента' => $sum,
'ХозяйственнаяОперация_Key' => UNF_WORK_ORDER_BUSINESS_OPERATION_KEY,
'Автор_Key' => UNF_TIME_AUTHOR_KEY,
'Работы' => [
[
'LineNumber' => '1',
'ВидРабот_Key' => UNF_TIME_WORK_TYPE_KEY,
'Заказчик' => '',
'Заказчик_Type' => 'StandardODATA.Undefined',
'Номенклатура_Key' => UNF_TIME_NOMENCLATURE_KEY,
'Характеристика_Key' => UNF_ZERO_GUID,
'Трудоемкость' => $planHours,
'Цена' => $rate,
'Сумма' => $sum,
'Комментарий' => '',
'ДатаНачала' => unfOdataDate($dateFrom),
'ДатаОкончания' => unfOdataDate($dateTo),
],
],
];
}
function unfWorkOrderComment(array $row, string $period, float $planHours): string
{
$name = trim((string)($row['name'] ?? ''));
$bitrixUserId = (int)($row['id'] ?? 0);
$factHours = round((float)($row['hours'] ?? 0), 2);
return trim('#Загружено_task2; план ' . unfFormatHours($planHours) . ' ч (факт ' . unfFormatHours($factHours)
. ' ч за ' . $period . ' +10%); Bitrix user ' . $bitrixUserId . '; ' . $name);
}
function createUnfWorkOrdersForReport(array $report): array
{
$period = (string)($report['period'] ?? '');
[$documentDate, $dateFrom, $dateTo] = unfWorkOrderDates($period);
$rows = array_values(array_filter((array)($report['rows'] ?? []), static function ($row): bool {
return is_array($row);
}));
$created = [];
$skipped = [];
$errors = [];
foreach ($rows as $row) {
$name = (string)($row['name'] ?? '');
$hours = round((float)($row['hours'] ?? 0), 2);
$bitrixUserId = (int)($row['id'] ?? 0);
if ($hours <= 0) {
$skipped[] = [
'bitrix_user_id' => $bitrixUserId,
'name' => $name,
'hours' => $hours,
'reason' => 'Нулевые часы',
];
}
}
$rowsToCreate = array_values(array_filter($rows, static function (array $row): bool {
return round((float)($row['hours'] ?? 0), 2) > 0;
}));
if ($rowsToCreate !== []) {
$employees = unfFetchEmployees();
foreach ($rowsToCreate as $row) {
$name = (string)($row['name'] ?? '');
$hours = round((float)($row['hours'] ?? 0), 2);
$bitrixUserId = (int)($row['id'] ?? 0);
$planHours = round($hours * (float)UNF_WORK_ORDER_UPLIFT, 2);
try {
$employee = unfFindEmployeeForReportRow($row, $employees);
$existing = unfFindExistingWorkOrder((string)$employee['Ref_Key'], $dateFrom);
if ($existing !== null) {
$skipped[] = [
'bitrix_user_id' => $bitrixUserId,
'name' => $name,
'hours' => $planHours,
'reason' => 'Задание на этот месяц уже есть',
'existing_number' => (string)($existing['Number'] ?? ''),
'existing_ref_key' => (string)($existing['Ref_Key'] ?? ''),
];
continue;
}
$payload = unfBuildWorkOrderPayload($row, (string)$employee['Ref_Key'], $period, $planHours, $documentDate, $dateFrom, $dateTo);
$document = unfOdataEntity(unfOdataRequest('POST', 'Document_ЗаданиеНаРаботу', $payload, ['$format' => 'json']));
if (UNF_TIME_POST_DOCUMENTS && isset($document['Ref_Key'])) {
unfOdataRequest('POST', "Document_ЗаданиеНаРаботу(guid'" . $document['Ref_Key'] . "')/Post()");
}
$created[] = [
'bitrix_user_id' => $bitrixUserId,
'name' => $name,
'hours' => $planHours,
'number' => (string)($document['Number'] ?? ''),
'ref_key' => (string)($document['Ref_Key'] ?? ''),
'posted' => UNF_TIME_POST_DOCUMENTS,
];
} catch (Throwable $e) {
$errors[] = [
'bitrix_user_id' => $bitrixUserId,
'name' => $name,
'hours' => $planHours,
'error' => $e->getMessage(),
];
}
}
}
return [
'ok' => $errors === [],
'period' => $period,
'month_title' => (string)($report['month_title'] ?? $period),
'source' => [
'rows' => count($rows),
'total_hours' => round((float)($report['total_hours'] ?? 0), 2),
],
'unf_period' => [
'date' => unfOdataDate($documentDate),
'date_from' => unfOdataDate($dateFrom),
'date_to' => unfOdataDate($dateTo),
],
'created' => $created,
'skipped' => $skipped,
'errors' => $errors,
];
}