CprModel.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. <?php
  2. namespace Models;
  3. class CprModel
  4. {
  5. private \PDO $pdo;
  6. private static ?array $columnsMeta = null;
  7. public function __construct()
  8. {
  9. if (isset($GLOBALS['pdo']) && $GLOBALS['pdo'] instanceof \PDO) {
  10. $this->pdo = $GLOBALS['pdo'];
  11. return;
  12. }
  13. throw new \RuntimeException('Global PDO connection not initialized');
  14. }
  15. /**
  16. * @return array<string, array{nullable: bool, data_type: string}>
  17. */
  18. private function getColumnsMeta(): array
  19. {
  20. if (self::$columnsMeta !== null) {
  21. return self::$columnsMeta;
  22. }
  23. $stmt = $this->pdo->prepare(
  24. 'SELECT column_name, is_nullable, data_type
  25. FROM information_schema.columns
  26. WHERE table_schema = current_schema()
  27. AND table_name = :table
  28. ORDER BY ordinal_position'
  29. );
  30. $stmt->execute(['table' => 'cpr']);
  31. $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);
  32. if (!$rows) {
  33. throw new \RuntimeException('Unable to load CPR table metadata');
  34. }
  35. $meta = [];
  36. foreach ($rows as $row) {
  37. $meta[$row['column_name']] = [
  38. 'nullable' => strtoupper((string)$row['is_nullable']) === 'YES',
  39. 'data_type' => (string)$row['data_type'],
  40. ];
  41. }
  42. self::$columnsMeta = $meta;
  43. return self::$columnsMeta;
  44. }
  45. /**
  46. * @return array<string, array{nullable: bool, data_type: string}>
  47. */
  48. public function getUserColumns(): array
  49. {
  50. $meta = $this->getColumnsMeta();
  51. unset($meta['cpr_id']);
  52. return array_diff_key($meta, ['status_id' => true, 'payment_id' => true, 'user_id' => true, 'company_id' => true]);
  53. }
  54. public function create(array $data, int $statusId, int $paymentId, int $userId, int $companyId): array
  55. {
  56. $data = $this->flattenB3Arrays($data);
  57. $meta = $this->getColumnsMeta();
  58. $columns = [];
  59. $placeholders = [];
  60. $params = [];
  61. foreach ($meta as $column => $info) {
  62. if ($column === 'cpr_id') {
  63. continue;
  64. }
  65. if ($column === 'status_id') {
  66. $columns[] = '"status_id"';
  67. $placeholders[] = ':status_id';
  68. $params['status_id'] = $statusId;
  69. continue;
  70. }
  71. if ($column === 'payment_id') {
  72. $columns[] = '"payment_id"';
  73. $placeholders[] = ':payment_id';
  74. $params['payment_id'] = $paymentId;
  75. continue;
  76. }
  77. if ($column === 'user_id') {
  78. $columns[] = '"user_id"';
  79. $placeholders[] = ':user_id';
  80. $params['user_id'] = $userId;
  81. continue;
  82. }
  83. if ($column === 'company_id') {
  84. $columns[] = '"company_id"';
  85. $placeholders[] = ':company_id';
  86. $params['company_id'] = $companyId;
  87. continue;
  88. }
  89. if (!array_key_exists($column, $data)) {
  90. if ($info['nullable']) {
  91. $columns[] = '"' . $column . '"';
  92. $placeholders[] = ':' . $column;
  93. $params[$column] = null;
  94. continue;
  95. }
  96. throw new \InvalidArgumentException("Missing field: {$column}");
  97. }
  98. $value = $data[$column];
  99. if ($column === 'cpr_children_codes') {
  100. $value = $this->normalizeChildrenCodes($value);
  101. }
  102. if (in_array($column, $this->getSemicolonListColumns(), true)) {
  103. $value = $this->normalizeSemicolonList($value, $column);
  104. }
  105. $columns[] = '"' . $column . '"';
  106. $placeholders[] = ':' . $column;
  107. $params[$column] = $value;
  108. }
  109. $sql = 'INSERT INTO "cpr" (' . implode(', ', $columns) . ')
  110. VALUES (' . implode(', ', $placeholders) . ')
  111. RETURNING cpr_id';
  112. $stmt = $this->pdo->prepare($sql);
  113. $stmt->execute($params);
  114. $cprId = (int)$stmt->fetchColumn();
  115. $record = $this->fetchById($cprId);
  116. if (!$record) {
  117. throw new \RuntimeException('Failed to load created CPR record');
  118. }
  119. if (isset($record['cpr_children_codes'])) {
  120. $record['cpr_children_codes'] = $this->decodeChildrenCodes((string)$record['cpr_children_codes']);
  121. }
  122. $record['cpr_id'] = (int)$record['cpr_id'];
  123. if (isset($record['status_id'])) {
  124. $record['status_id'] = (int)$record['status_id'];
  125. }
  126. if (isset($record['payment_id'])) {
  127. $record['payment_id'] = (int)$record['payment_id'];
  128. }
  129. if (isset($record['user_id'])) {
  130. $record['user_id'] = (int)$record['user_id'];
  131. }
  132. if (isset($record['company_id'])) {
  133. $record['company_id'] = (int)$record['company_id'];
  134. }
  135. return $record;
  136. }
  137. private function normalizeChildrenCodes($value): string
  138. {
  139. if (is_array($value)) {
  140. $value = array_map('strval', array_values($value));
  141. if (!$value) {
  142. throw new \InvalidArgumentException('cpr_children_codes must not be empty');
  143. }
  144. $encoded = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  145. if ($encoded === false) {
  146. throw new \InvalidArgumentException('Invalid cpr_children_codes payload');
  147. }
  148. return $encoded;
  149. }
  150. if (is_string($value) && trim($value) !== '') {
  151. return $value;
  152. }
  153. throw new \InvalidArgumentException('cpr_children_codes must be a non-empty string or array of strings');
  154. }
  155. private function normalizeSemicolonList($value, string $field): string
  156. {
  157. if (is_array($value)) {
  158. $items = array_map(static fn($v) => trim((string)$v), array_values($value));
  159. $items = array_values(array_filter($items, static fn($v) => $v !== ''));
  160. if (!$items) {
  161. throw new \InvalidArgumentException("{$field} must not be empty");
  162. }
  163. return implode('; ', $items);
  164. }
  165. if (is_string($value)) {
  166. $trimmed = trim($value);
  167. if ($trimmed === '') {
  168. throw new \InvalidArgumentException("{$field} must not be empty");
  169. }
  170. $parts = preg_split('/\s*;\s*/', $trimmed) ?: [];
  171. $parts = array_map(static fn($v) => trim((string)$v), $parts);
  172. $parts = array_values(array_filter($parts, static fn($v) => $v !== ''));
  173. return implode('; ', $parts);
  174. }
  175. throw new \InvalidArgumentException("{$field} must be a non-empty string or array of strings");
  176. }
  177. private function getSemicolonListColumns(): array
  178. {
  179. return [
  180. 'cpr_collateral_type_code',
  181. 'cpr_collateral_type_name',
  182. 'cpr_constitution_process_indicator',
  183. 'cpr_otc_bondsman_account_code',
  184. 'cpr_issuer_name',
  185. 'cpr_issuers_document_number',
  186. 'cpr_issuers_person_type_acronym',
  187. 'cpr_issuer_legal_nature_code',
  188. 'cpr_issuers_state_acronym',
  189. 'cpr_issuers_city_name',
  190. 'cpr_production_place_name',
  191. 'cpr_property_registration_number',
  192. 'cpr_notary_name',
  193. 'cpr_total_production_area_in_hectares_number',
  194. 'cpr_total_area_in_hectares_number',
  195. 'cpr_car_code',
  196. 'cpr_latitude_code',
  197. 'cpr_longitude_code',
  198. 'cpr_zip_code',
  199. ];
  200. }
  201. private function flattenB3Arrays(array $data): array
  202. {
  203. if (!array_key_exists('collaterals', $data) && !array_key_exists('issuers', $data) && !array_key_exists('productionPlaces', $data)) {
  204. return $data;
  205. }
  206. if (array_key_exists('collaterals', $data) && !array_key_exists('cpr_collateral_type_code', $data)) {
  207. $collaterals = $data['collaterals'];
  208. if (is_array($collaterals) && $collaterals && $this->isAssoc($collaterals)) {
  209. $collaterals = [$collaterals];
  210. }
  211. if (is_array($collaterals)) {
  212. $data['cpr_collateral_type_code'] = array_map(static fn($c) => $c['collateralTypeCode'] ?? null, $collaterals);
  213. $data['cpr_collateral_type_name'] = array_map(static fn($c) => $c['collateralTypeName'] ?? null, $collaterals);
  214. $data['cpr_constitution_process_indicator'] = array_map(static fn($c) => $c['constitutionProcessIndicator'] ?? null, $collaterals);
  215. $data['cpr_otc_bondsman_account_code'] = array_map(static fn($c) => $c['otcBondsmanAccountCode'] ?? null, $collaterals);
  216. }
  217. }
  218. if (array_key_exists('issuers', $data) && !array_key_exists('cpr_issuer_name', $data)) {
  219. $issuers = $data['issuers'];
  220. if (is_array($issuers) && $issuers && $this->isAssoc($issuers)) {
  221. $issuers = [$issuers];
  222. }
  223. if (is_array($issuers)) {
  224. $data['cpr_issuer_name'] = array_map(static fn($i) => $i['cprIssuerName'] ?? null, $issuers);
  225. $data['cpr_issuers_document_number'] = array_map(static fn($i) => $i['documentNumber'] ?? null, $issuers);
  226. $data['cpr_issuers_person_type_acronym'] = array_map(static fn($i) => $i['personTypeAcronym'] ?? null, $issuers);
  227. $data['cpr_issuer_legal_nature_code'] = array_map(static fn($i) => $i['issuerLegalNatureCode'] ?? null, $issuers);
  228. $data['cpr_issuers_state_acronym'] = array_map(static fn($i) => $i['stateAcronym'] ?? null, $issuers);
  229. $data['cpr_issuers_city_name'] = array_map(static fn($i) => $i['cityName'] ?? null, $issuers);
  230. }
  231. }
  232. if (array_key_exists('productionPlaces', $data) && !array_key_exists('cpr_production_place_name', $data)) {
  233. $productionPlaces = $data['productionPlaces'];
  234. if (is_array($productionPlaces) && $productionPlaces && $this->isAssoc($productionPlaces)) {
  235. $productionPlaces = [$productionPlaces];
  236. }
  237. if (is_array($productionPlaces)) {
  238. $data['cpr_production_place_name'] = array_map(static fn($p) => $p['productionPlaceName'] ?? null, $productionPlaces);
  239. $data['cpr_property_registration_number'] = array_map(static fn($p) => $p['propertyRegistrationNumber'] ?? null, $productionPlaces);
  240. $data['cpr_notary_name'] = array_map(static fn($p) => $p['notaryName'] ?? null, $productionPlaces);
  241. $data['cpr_total_production_area_in_hectares_number'] = array_map(static fn($p) => $p['totalProductionAreaInHectaresNumber'] ?? null, $productionPlaces);
  242. $data['cpr_total_area_in_hectares_number'] = array_map(static fn($p) => $p['totalAreaInHectaresNumber'] ?? null, $productionPlaces);
  243. $data['cpr_car_code'] = array_map(static fn($p) => $p['carCode'] ?? null, $productionPlaces);
  244. $data['cpr_latitude_code'] = array_map(static fn($p) => $p['latitudeCode'] ?? null, $productionPlaces);
  245. $data['cpr_longitude_code'] = array_map(static fn($p) => $p['longitudeCode'] ?? null, $productionPlaces);
  246. $data['cpr_zip_code'] = array_map(static fn($p) => $p['zipCode'] ?? null, $productionPlaces);
  247. }
  248. }
  249. return $data;
  250. }
  251. private function isAssoc(array $arr): bool
  252. {
  253. return array_keys($arr) !== range(0, count($arr) - 1);
  254. }
  255. /**
  256. * @return array<int, string>|string
  257. */
  258. private function decodeChildrenCodes(string $stored)
  259. {
  260. $decoded = json_decode($stored, true);
  261. if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  262. return $decoded;
  263. }
  264. return $stored;
  265. }
  266. private function fetchById(int $id): ?array
  267. {
  268. $stmt = $this->pdo->prepare('SELECT * FROM "cpr" WHERE cpr_id = :id');
  269. $stmt->execute(['id' => $id]);
  270. $record = $stmt->fetch(\PDO::FETCH_ASSOC);
  271. return $record ?: null;
  272. }
  273. }