DeviceProductCatalog.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace plugin\saiadmin\app\service;
  3. use plugin\saiadmin\exception\ApiException;
  4. use support\think\Db;
  5. /** 设备筛选和分成使用同一份数据库字典;每次请求读取,字典修改立即生效。 */
  6. class DeviceProductCatalog
  7. {
  8. public function categories(): array
  9. {
  10. $products = $this->dictionary('device_product');
  11. $mappings = $this->dictionary('device_type_product');
  12. $typesByProduct = [];
  13. $mappedTypes = [];
  14. foreach ($mappings as $mapping) {
  15. if (!ctype_digit((string) $mapping['value']) || (int) $mapping['value'] < 1) {
  16. throw new ApiException('设备类型产品映射的键值必须为有效设备类型编号');
  17. }
  18. $type = (int) $mapping['value'];
  19. if (isset($mappedTypes[$type])) {
  20. throw new ApiException('设备类型产品映射存在重复编号,请检查数据字典');
  21. }
  22. $mappedTypes[$type] = true;
  23. $typesByProduct[$mapping['label']][] = $type;
  24. }
  25. $categories = [];
  26. $productCodes = [];
  27. foreach ($products as $product) {
  28. $code = (string) $product['value'];
  29. if ($code === '' || isset($productCodes[$code])) {
  30. throw new ApiException('设备产品编码为空或重复,请检查数据字典');
  31. }
  32. $productCodes[$code] = true;
  33. if (!empty($typesByProduct[$code])) {
  34. $categories[] = ['value' => $code, 'label' => $product['label'], 'goods_types' => $typesByProduct[$code]];
  35. }
  36. }
  37. return $categories;
  38. }
  39. private function dictionary(string $code): array
  40. {
  41. return Db::table('sa_system_dict_data')->alias('d')
  42. ->join('sa_system_dict_type t', 't.id=d.type_id')
  43. ->where('t.code', $code)->where('t.status', 1)->whereNull('t.delete_time')
  44. ->where('d.status', 1)->whereNull('d.delete_time')
  45. ->field('d.label,d.value')->order('d.sort', 'desc')->order('d.id', 'asc')->select()->toArray();
  46. }
  47. }