+page.svelte 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  1. <script>
  2. import { browser } from '$app/environment';
  3. import { goto } from '$app/navigation';
  4. import { onDestroy, onMount, tick } from 'svelte';
  5. import { get } from 'svelte/store';
  6. import Header from '$lib/layout/Header.svelte';
  7. import Tabs from '$lib/components/Tabs.svelte';
  8. import RegisterCpr from '$lib/components/commodities/cpr/RegisterCpr.svelte';
  9. import ContractCpr from '$lib/components/commodities/cpr/ContractCpr.svelte';
  10. import EmissionCpr from '$lib/components/commodities/cpr/EmissionCpr.svelte';
  11. import CprDetailModal from '$lib/components/commodities/cpr/CprDetailModal.svelte';
  12. import { authToken } from '$lib/utils/stores';
  13. const apiUrl = import.meta.env.VITE_API_URL;
  14. const fieldKeys = [
  15. 'cpr_contract_code',
  16. 'cpr_contract_number',
  17. 'cpr_number',
  18. 'cpr_self_number',
  19. 'cpr_ipoc_code',
  20. 'cpr_calculation_type_code',
  21. 'cpr_initial_exchange_value',
  22. 'cpr_fixing_type_code',
  23. 'cpr_data_source_type_code',
  24. 'cpr_adjustment_frequency_type_code',
  25. 'cpr_adjustment_pro_rata_type_code',
  26. 'cpr_adjustment_type_code',
  27. 'cpr_maturity_date',
  28. 'cpr_reference_date',
  29. 'cpr_payment_start_date',
  30. 'cpr_amortization_start_date',
  31. 'cpr_interest_payment_date',
  32. 'cpr_issue_value',
  33. 'cpr_unit_value',
  34. 'cpr_unit_price_value',
  35. 'cpr_interest_unit_price_value',
  36. 'cpr_residual_value',
  37. 'cpr_amortization_percentage',
  38. 'cpr_event_quantity',
  39. 'cpr_payment_method_code',
  40. 'cpr_index_code',
  41. 'cpr_index_short_name',
  42. 'cpr_vcp_indicator_type_code',
  43. 'cpr_indexador_percentage_value',
  44. 'cpr_interest_rate_spread_percentage',
  45. 'cpr_interest_rate_criteria_type_code',
  46. 'cpr_interest_payment_value',
  47. 'cpr_interest_payment_frequency_code',
  48. 'cpr_interest_months_quantity',
  49. 'cpr_interestPaymentFlow_time_unit_type_code',
  50. 'cpr_interestPaymentFlow_deadline_type_code',
  51. 'cpr_amortization_type_code',
  52. 'cpr_amortization_months_quantity',
  53. 'cpr_amortizationPaymentFlow_time_unit_type_code',
  54. 'cpr_amortizationPaymentFlow_deadline_type_code',
  55. 'cpr_additional_text',
  56. 'cpr_internal_control_number',
  57. 'cpr_isin_code',
  58. // 'cpr_type_code',
  59. // 'cpr_otc_register_account_code',
  60. // 'cpr_otc_payment_agent_account_code',
  61. // 'cpr_otc_custodian_account_code',
  62. 'cpr_otc_favored_account_code',
  63. 'cpr_settlement_modality_type_code',
  64. 'cpr_otc_settlement_bank_account_code',
  65. 'cpr_ballast_type_code',
  66. 'cpr_lot_number',
  67. 'cpr_ballast_quantity',
  68. 'cpr_currency_code',
  69. 'cpr_transaction_identification',
  70. 'cpr_guarantee_limit_type_code',
  71. 'cpr_mother_code',
  72. 'cpr_deposit_quantity',
  73. 'cpr_deposit_unit_price_value',
  74. 'cpr_deposit_person_type_acronym',
  75. 'cpr_deposit_document_number',
  76. 'cpr_event_type_code',
  77. 'cpr_event_original_date',
  78. 'cpr_operation_modality_type_code',
  79. 'cpr_bacen_reference_code',
  80. 'cpr_children_codes',
  81. // 'cpr_scr_type_code',
  82. // 'cpr_finality_code',
  83. 'cpr_scr_customer_detail',
  84. 'cpr_scr_person_type_acronym',
  85. 'cpr_scr_document_number',
  86. 'cpr_issuer_name',
  87. 'cpr_place_name',
  88. 'cpr_document_deadline_days_number',
  89. 'cpr_deliveryPlace_state_acronym',
  90. 'cpr_deliveryPlace_city_name',
  91. 'cpr_deliveryPlace_ibge_code',
  92. 'cpr_issuer_legal_nature_code',
  93. 'cpr_issuers_person_type_acronym',
  94. 'cpr_issuers_document_number',
  95. 'cpr_issuers_state_acronym',
  96. 'cpr_issuers_city_name',
  97. 'cpr_issuers_ibge_code',
  98. 'cpr_collateral_type_code',
  99. 'cpr_collateral_type_name',
  100. 'cpr_constitution_process_indicator',
  101. 'cpr_otc_bondsman_account_code',
  102. 'cpr_collaterals_document_number',
  103. 'cpr_product_name',
  104. 'cpr_product_class_name',
  105. 'cpr_product_harvest',
  106. 'cpr_product_quantity',
  107. 'cpr_measure_unit_name',
  108. 'cpr_packaging_way_name',
  109. 'cpr_product_status_code',
  110. 'cpr_production_type_code',
  111. 'cpr_product_description',
  112. 'cpr_production_place_name',
  113. 'cpr_property_registration_number',
  114. 'cpr_notary_name',
  115. 'cpr_total_production_area_in_hectares_number',
  116. 'cpr_total_area_in_hectares_number',
  117. 'cpr_car_code',
  118. 'cpr_latitude_code',
  119. 'cpr_longitude_code',
  120. 'cpr_zip_code',
  121. 'cpr_green_cpr_indicator',
  122. 'cpr_green_cpr_certificate_name',
  123. 'cpr_green_cpr_certificate_cnpj_number',
  124. 'cpr_green_cpr_declaration_indicator',
  125. 'cpr_green_cpr_georeferencing_description'
  126. ];
  127. const allFieldKeys = Array.from(new Set(fieldKeys));
  128. const requiredFields = new Set([
  129. 'cpr_maturity_date',
  130. 'cpr_issue_value',
  131. 'cpr_collateral_type_code',
  132. 'cpr_collateral_type_name',
  133. 'cpr_constitution_process_indicator',
  134. 'cpr_product_name',
  135. 'cpr_product_class_name',
  136. 'cpr_product_harvest',
  137. 'cpr_product_description',
  138. 'cpr_product_quantity',
  139. 'cpr_measure_unit_name',
  140. 'cpr_packaging_way_name',
  141. 'cpr_product_status_code',
  142. 'cpr_production_type_code',
  143. 'cpr_place_name',
  144. 'cpr_deliveryPlace_state_acronym',
  145. 'cpr_deliveryPlace_city_name',
  146. 'cpr_issuer_legal_nature_code',
  147. 'cpr_issuers_person_type_acronym',
  148. 'cpr_issuers_document_number',
  149. 'cpr_issuers_state_acronym',
  150. 'cpr_issuers_city_name',
  151. 'cpr_contract_code',
  152. 'cpr_production_place_name',
  153. 'cpr_zip_code'
  154. ]);
  155. const repeatingGroupDefinitions = [
  156. {
  157. key: 'issuers',
  158. title: 'Dados dos emissores',
  159. description: 'Adicione quantos emissores forem necessários.',
  160. itemLabel: 'Emissor',
  161. addLabel: 'Adicionar emissor',
  162. columns: 2,
  163. fields: [
  164. { key: 'cpr_issuer_name', label: 'Nome / (Razão Social do Emissor)' },
  165. { key: 'cpr_issuers_document_number', label: 'Documento (CPF/CNPJ)' },
  166. {
  167. key: 'cpr_issuers_person_type_acronym',
  168. label: 'Tipo de pessoa',
  169. type: 'select',
  170. options: [
  171. { label: 'Selecione...', value: '' },
  172. { label: 'Pessoa Jurídica (PJ)', value: 'PJ' },
  173. { label: 'Pessoa Física (PF)', value: 'PF' }
  174. ]
  175. },
  176. {
  177. key: 'cpr_issuer_legal_nature_code',
  178. label: 'Natureza jurídica',
  179. type: 'select',
  180. options: [
  181. { label: 'Selecione...', value: '' },
  182. { label: 'Produtor Rural', value: '02' }
  183. ]
  184. },
  185. { key: 'cpr_issuers_state_acronym', label: 'Estado' },
  186. { key: 'cpr_issuers_city_name', label: 'Cidade' }
  187. ]
  188. },
  189. {
  190. key: 'collaterals',
  191. title: 'Garantias e colaterais',
  192. description: 'Informe todos os colaterais vinculados a esta CPR.',
  193. itemLabel: 'Colateral',
  194. addLabel: 'Adicionar colateral',
  195. columns: 2,
  196. fields: [
  197. {
  198. key: 'cpr_collateral_type_code',
  199. label: 'Código do colateral',
  200. type: 'select',
  201. options: [
  202. { label: 'Selecione...', value: '' },
  203. { label: 'Penhor', value: '6' },
  204. { label: 'Alienação', value: '7' }
  205. ]
  206. },
  207. { key: 'cpr_collateral_type_name', label: 'Descrição do colateral' },
  208. { key: 'cpr_constitution_process_indicator', label: 'Processo constituído', type: 'select', options: [
  209. { label: 'Selecione...', value: '' },
  210. { label: 'Sim', value: 'S' },
  211. { label: 'Não', value: 'N' }
  212. ] },
  213. { key: 'cpr_otc_bondsman_account_code', label: 'Conta OTC do fiador' }
  214. ]
  215. },
  216. {
  217. key: 'productionPlaces',
  218. title: 'Locais de produção',
  219. description: 'Cadastre cada propriedade vinculada ao lastro.',
  220. itemLabel: 'Propriedade',
  221. addLabel: 'Adicionar propriedade',
  222. columns: 3,
  223. fields: [
  224. { key: 'cpr_production_place_name', label: 'Nome da propriedade' },
  225. { key: 'cpr_property_registration_number', label: 'Registro da propriedade' },
  226. { key: 'cpr_notary_name', label: 'Cartório' },
  227. { key: 'cpr_total_production_area_in_hectares_number', label: 'Área de produção (ha)' },
  228. { key: 'cpr_total_area_in_hectares_number', label: 'Área total (ha)' },
  229. { key: 'cpr_car_code', label: 'Código CAR' },
  230. { key: 'cpr_latitude_code', label: 'Latitude' },
  231. { key: 'cpr_longitude_code', label: 'Longitude' },
  232. { key: 'cpr_zip_code', label: 'CEP' }
  233. ]
  234. }
  235. ];
  236. const repeatingFieldToGroup = repeatingGroupDefinitions.reduce((acc, config) => {
  237. config.fields.forEach((field) => {
  238. acc[field.key] = config.key;
  239. });
  240. return acc;
  241. }, {});
  242. function createEmptyRepeatingEntry(config) {
  243. return config.fields.reduce((entry, field) => {
  244. entry[field.key] = '';
  245. return entry;
  246. }, {});
  247. }
  248. const createInitialRepeatingGroups = () => {
  249. const groups = {};
  250. repeatingGroupDefinitions.forEach((config) => {
  251. groups[config.key] = [createEmptyRepeatingEntry(config)];
  252. });
  253. return groups;
  254. };
  255. const createInitialForm = () =>
  256. allFieldKeys.reduce((acc, key) => {
  257. acc[key] = '';
  258. return acc;
  259. }, {});
  260. let cprForm = createInitialForm();
  261. let repeatingGroups = createInitialRepeatingGroups();
  262. let submitError = '';
  263. let submitSuccess = '';
  264. let isSubmitting = false;
  265. const PAYMENT_STORAGE_KEY = 'tooeasy_cpr_payment';
  266. const PAYMENT_TIMEOUT_MS = 30 * 60 * 1000;
  267. const PAYMENT_POLL_INTERVAL_MS = 10_000;
  268. let paymentModalVisible = false;
  269. let paymentCode = '';
  270. let paymentId = null;
  271. let paymentError = '';
  272. let paymentStatusMessage = '';
  273. let paymentCopyFeedback = '';
  274. let paymentCountdownMs = PAYMENT_TIMEOUT_MS;
  275. let paymentStartedAt = null;
  276. let paymentLoadingVisible = false;
  277. let paymentQrContainer;
  278. let paymentQrInstance = null;
  279. let paymentPollIntervalId = null;
  280. let paymentCountdownIntervalId = null;
  281. let paymentCopyTimeoutId = null;
  282. let isCheckingPayment = false;
  283. let paymentSuccessOverlayVisible = false;
  284. let paymentSuccessMessage = '';
  285. let emissionDiscountCode = '';
  286. const breadcrumb = [{ label: 'Início' }, { label: 'CPR', active: true }];
  287. let activeTab = 4;
  288. const tabs = ['Contrato', 'Registro', 'Emissão'];
  289. const B3_OFFLINE_START_HOUR = 20;
  290. const B3_OFFLINE_END_HOUR = 8;
  291. const B3_OFFLINE_POLL_INTERVAL_MS = 60_000;
  292. const historyEndpoint = `${apiUrl}/cpr/history`;
  293. const paymentConfirmEndpoint = `${apiUrl}/b3/payment/confirm`;
  294. const historyColumns = [
  295. { key: 'cpr_id', label: 'CPR ID' },
  296. { key: 'cpr_product_class_name', label: 'Produto' },
  297. { key: 'cpr_issue_date', label: 'Data de emissão' },
  298. { key: 'cpr_issuer_name', label: 'Emitente' },
  299. { key: 'cpr_issue_financial_value', label: 'Valor' }
  300. ];
  301. let historyRows = [];
  302. let historyLoading = false;
  303. let historyError = '';
  304. let detailLoading = false;
  305. let detailError = '';
  306. let selectedDetail = null;
  307. let selectedDetailId = null;
  308. let showDetailModal = false;
  309. let historyInitialized = false;
  310. let isB3OfflineWindow = false;
  311. let b3OfflineIntervalId = null;
  312. function handleFieldChange(key, value) {
  313. submitError = '';
  314. submitSuccess = '';
  315. cprForm = { ...cprForm, [key]: value ?? '' };
  316. }
  317. function cloneRepeatingEntries(groupKey) {
  318. const entries = repeatingGroups[groupKey] ?? [];
  319. return entries.map((entry) => ({ ...entry }));
  320. }
  321. function handleRepeatingFieldChange(groupKey, index, fieldKey, value) {
  322. submitError = '';
  323. submitSuccess = '';
  324. const nextEntries = cloneRepeatingEntries(groupKey);
  325. if (!nextEntries[index]) return;
  326. nextEntries[index] = {
  327. ...nextEntries[index],
  328. [fieldKey]: value ?? ''
  329. };
  330. repeatingGroups = {
  331. ...repeatingGroups,
  332. [groupKey]: nextEntries
  333. };
  334. }
  335. function handleAddRepeatingEntry(groupKey) {
  336. const config = repeatingGroupDefinitions.find((c) => c.key === groupKey);
  337. if (!config) return;
  338. const nextEntries = cloneRepeatingEntries(groupKey);
  339. nextEntries.push(createEmptyRepeatingEntry(config));
  340. repeatingGroups = {
  341. ...repeatingGroups,
  342. [groupKey]: nextEntries
  343. };
  344. }
  345. function handleRemoveRepeatingEntry(groupKey, index) {
  346. const nextEntries = cloneRepeatingEntries(groupKey);
  347. if (nextEntries.length <= 1) return;
  348. repeatingGroups = {
  349. ...repeatingGroups,
  350. [groupKey]: nextEntries.filter((_, i) => i !== index)
  351. };
  352. }
  353. function handleAddTop() {
  354. cprForm = createInitialForm();
  355. repeatingGroups = createInitialRepeatingGroups();
  356. submitError = '';
  357. submitSuccess = '';
  358. activeTab = 0;
  359. }
  360. function handleCancel() {
  361. activeTab = 4;
  362. submitError = '';
  363. emissionDiscountCode = '';
  364. }
  365. function ensureAuthContext() {
  366. const token = get(authToken);
  367. if (!token) {
  368. throw new Error('Sessão expirada. Faça login novamente.');
  369. }
  370. return { token };
  371. }
  372. async function parseJsonResponse(res) {
  373. const raw = await res.text();
  374. if (!raw) return null;
  375. const trimmed = raw.trim();
  376. if (trimmed.startsWith('<')) {
  377. console.error('Resposta HTML inesperada do endpoint de histórico/detalhe de CPR:', trimmed.slice(0, 300));
  378. const statusMsg =
  379. res.status === 404
  380. ? 'Endpoint /cpr/history não encontrado (404). Verifique a URL da API.'
  381. : `Resposta inesperada do servidor (status ${res.status}).`;
  382. throw new Error(statusMsg);
  383. }
  384. try {
  385. return JSON.parse(trimmed);
  386. } catch (err) {
  387. console.error('Resposta inválida do histórico de CPRs:', err, trimmed);
  388. throw new Error('Resposta inválida do servidor.');
  389. }
  390. }
  391. function normalizeHistoryList(payload) {
  392. if (Array.isArray(payload)) return payload;
  393. if (Array.isArray(payload?.data)) return payload.data;
  394. return [];
  395. }
  396. function sanitizeDetail(detail) {
  397. if (!detail || typeof detail !== 'object') return null;
  398. const cleaned = {};
  399. Object.entries(detail).forEach(([key, value]) => {
  400. if (value === null || value === undefined) return;
  401. if (typeof value === 'string' && value.trim().toUpperCase() === 'NA') return;
  402. cleaned[key] = value;
  403. });
  404. return Object.keys(cleaned).length ? cleaned : null;
  405. }
  406. function formatDetailValue(value) {
  407. if (value == null) return '—';
  408. if (typeof value === 'number') {
  409. return value.toLocaleString('pt-BR', { minimumFractionDigits: 0, maximumFractionDigits: 4 });
  410. }
  411. return String(value);
  412. }
  413. function humanizeKey(key = '') {
  414. if (!key) return '';
  415. return key
  416. .replace(/^cpr_/i, '')
  417. .replace(/_/g, ' ')
  418. .replace(/\b\w/g, (match) => match.toUpperCase());
  419. }
  420. function formatCurrency(value) {
  421. if (value == null || value === '') return '—';
  422. const numeric = Number(value);
  423. if (Number.isNaN(numeric)) return value;
  424. return numeric.toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
  425. }
  426. function formatCountdown(ms) {
  427. if (ms == null || Number.isNaN(ms)) return '--:--';
  428. const totalSeconds = Math.max(0, Math.floor(ms / 1000));
  429. const minutes = String(Math.floor(totalSeconds / 60)).padStart(2, '0');
  430. const seconds = String(totalSeconds % 60).padStart(2, '0');
  431. return `${minutes}:${seconds}`;
  432. }
  433. function persistPaymentState() {
  434. if (!browser || !paymentId || !paymentCode) return;
  435. try {
  436. const payload = {
  437. paymentId,
  438. paymentCode,
  439. startedAt: paymentStartedAt ?? Date.now()
  440. };
  441. localStorage.setItem(PAYMENT_STORAGE_KEY, JSON.stringify(payload));
  442. } catch (err) {
  443. console.warn('[CPR] Não foi possível salvar o estado do pagamento', err);
  444. }
  445. }
  446. function removePaymentStateFromStorage() {
  447. if (!browser) return;
  448. try {
  449. localStorage.removeItem(PAYMENT_STORAGE_KEY);
  450. } catch {}
  451. }
  452. function stopPaymentPolling() {
  453. if (paymentPollIntervalId) {
  454. clearInterval(paymentPollIntervalId);
  455. paymentPollIntervalId = null;
  456. }
  457. }
  458. function stopPaymentCountdown() {
  459. if (paymentCountdownIntervalId) {
  460. clearInterval(paymentCountdownIntervalId);
  461. paymentCountdownIntervalId = null;
  462. }
  463. }
  464. function stopPaymentCopyTimeout() {
  465. if (paymentCopyTimeoutId) {
  466. clearTimeout(paymentCopyTimeoutId);
  467. paymentCopyTimeoutId = null;
  468. }
  469. }
  470. function startPaymentCountdown(startTimestamp = Date.now()) {
  471. if (!browser) return;
  472. paymentStartedAt = startTimestamp;
  473. updatePaymentCountdown();
  474. stopPaymentCountdown();
  475. paymentCountdownIntervalId = window.setInterval(updatePaymentCountdown, 1000);
  476. }
  477. function updatePaymentCountdown() {
  478. if (!paymentStartedAt) {
  479. paymentCountdownMs = PAYMENT_TIMEOUT_MS;
  480. return;
  481. }
  482. const elapsed = Date.now() - paymentStartedAt;
  483. const remaining = PAYMENT_TIMEOUT_MS - elapsed;
  484. paymentCountdownMs = remaining > 0 ? remaining : 0;
  485. if (remaining <= 0) {
  486. handlePaymentExpired();
  487. }
  488. }
  489. function handlePaymentExpired() {
  490. if (!paymentId) return;
  491. stopPaymentPolling();
  492. stopPaymentCountdown();
  493. removePaymentStateFromStorage();
  494. paymentStatusMessage = '';
  495. paymentError = 'O tempo limite para pagamento expirou. Gere uma nova CPR para emitir outro QR Code.';
  496. paymentId = null;
  497. paymentCode = '';
  498. }
  499. function startPaymentPolling(immediate = true) {
  500. if (!browser || !paymentId) return;
  501. stopPaymentPolling();
  502. if (immediate) {
  503. void pollPaymentStatus();
  504. }
  505. paymentPollIntervalId = window.setInterval(() => {
  506. void pollPaymentStatus();
  507. }, PAYMENT_POLL_INTERVAL_MS);
  508. }
  509. async function pollPaymentStatus() {
  510. if (!paymentId || isCheckingPayment) return;
  511. isCheckingPayment = true;
  512. paymentError = '';
  513. try {
  514. const result = await requestPaymentConfirmation();
  515. if (result.state === 'success') {
  516. handlePaymentConfirmationSuccess(result.data);
  517. } else if (result.state === 'pending') {
  518. paymentStatusMessage = result.message ?? 'Pagamento pendente. Continuaremos monitorando.';
  519. } else if (result.state === 'error') {
  520. paymentStatusMessage = '';
  521. paymentError = result.message ?? 'Falha ao confirmar pagamento.';
  522. stopPaymentPolling();
  523. }
  524. } catch (err) {
  525. console.error('[CPR] Erro ao confirmar pagamento', err);
  526. paymentError = err?.message ?? 'Não foi possível verificar o pagamento.';
  527. } finally {
  528. isCheckingPayment = false;
  529. }
  530. }
  531. async function requestPaymentConfirmation() {
  532. if (!paymentId) {
  533. return { state: 'error', message: 'Pagamento inválido. Gere um novo QR Code.' };
  534. }
  535. const { token } = ensureAuthContext();
  536. const res = await fetch(paymentConfirmEndpoint, {
  537. method: 'POST',
  538. headers: {
  539. 'content-type': 'application/json',
  540. Authorization: `Bearer ${token}`
  541. },
  542. body: JSON.stringify({ payment_id: paymentId })
  543. });
  544. const raw = await res.text();
  545. let body = null;
  546. if (raw) {
  547. try {
  548. body = JSON.parse(raw);
  549. } catch (err) {
  550. console.error('[CPR] Resposta inválida ao confirmar pagamento:', err, raw);
  551. }
  552. }
  553. const isSuccessResponse = Boolean(body?.success || body?.status === 'ok');
  554. if (res.ok && isSuccessResponse) {
  555. console.log('[CPR] Confirmação de pagamento bem-sucedida:', body);
  556. return { state: 'success', data: body };
  557. }
  558. const code = body?.code ?? body?.error;
  559. const backendMessage = body?.message ?? body?.msg ?? body?.data?.message ?? raw ?? '';
  560. const backendMessageText = typeof backendMessage === 'string' ? backendMessage.trim() : '';
  561. const isKnownPending =
  562. code === 'E_PAYMENT_PENDING' ||
  563. body?.data?.status === 0 ||
  564. res.status === 409 ||
  565. backendMessageText.toLowerCase?.().includes('pagamento ainda não confirmado');
  566. if (isKnownPending) {
  567. return {
  568. state: 'pending',
  569. message: backendMessageText || 'Pagamento pendente. Assim que confirmado, você será avisado.'
  570. };
  571. }
  572. const normalizedBackendMessage = typeof backendMessage === 'string' ? backendMessage.trim() : '';
  573. const normalizedRaw = typeof raw === 'string' ? raw.trim() : '';
  574. const message = normalizedBackendMessage || normalizedRaw || 'Não foi possível confirmar o pagamento.';
  575. return { state: 'error', message };
  576. }
  577. function handlePaymentConfirmationSuccess(payload) {
  578. const message = payload?.data?.message ?? payload?.message ?? 'Pagamento confirmado com sucesso.';
  579. submitSuccess = message;
  580. paymentSuccessMessage = message;
  581. paymentError = '';
  582. paymentStatusMessage = '';
  583. paymentSuccessOverlayVisible = true;
  584. stopPaymentPolling();
  585. stopPaymentCountdown();
  586. stopPaymentCopyTimeout();
  587. removePaymentStateFromStorage();
  588. paymentId = null;
  589. paymentCode = '';
  590. paymentStartedAt = null;
  591. paymentCountdownMs = PAYMENT_TIMEOUT_MS;
  592. paymentCopyFeedback = '';
  593. }
  594. function resetPaymentTracking({ hideModal = true } = {}) {
  595. stopPaymentPolling();
  596. stopPaymentCountdown();
  597. stopPaymentCopyTimeout();
  598. removePaymentStateFromStorage();
  599. paymentId = null;
  600. paymentCode = '';
  601. paymentStartedAt = null;
  602. paymentCountdownMs = PAYMENT_TIMEOUT_MS;
  603. paymentCopyFeedback = '';
  604. paymentSuccessOverlayVisible = false;
  605. paymentSuccessMessage = '';
  606. if (hideModal) {
  607. paymentModalVisible = false;
  608. }
  609. }
  610. function handlePaymentSuccessAcknowledge() {
  611. paymentSuccessOverlayVisible = false;
  612. paymentModalVisible = false;
  613. activeTab = 4;
  614. void fetchHistory();
  615. }
  616. function handleCancelPaymentFlow() {
  617. resetPaymentTracking({ hideModal: true });
  618. paymentStatusMessage = '';
  619. paymentError = '';
  620. }
  621. function handleRetryPaymentCheck() {
  622. if (!paymentId) return;
  623. paymentError = '';
  624. paymentStatusMessage = 'Verificando status do pagamento...';
  625. startPaymentPolling(true);
  626. }
  627. async function renderPaymentQrCode(link) {
  628. if (!browser || !link) return;
  629. try {
  630. if (!paymentQrInstance) {
  631. const module = await import('qr-code-styling');
  632. const QRCodeStyles = module.default ?? module;
  633. paymentQrInstance = new QRCodeStyles({
  634. width: 240,
  635. height: 240,
  636. type: 'svg',
  637. data: link,
  638. dotsOptions: {
  639. color: '#0f172a',
  640. type: 'rounded'
  641. },
  642. backgroundOptions: {
  643. color: '#ffffff'
  644. }
  645. });
  646. } else {
  647. paymentQrInstance.update({ data: link });
  648. }
  649. await tick();
  650. if (paymentQrContainer) {
  651. paymentQrContainer.innerHTML = '';
  652. paymentQrInstance.append(paymentQrContainer);
  653. }
  654. } catch (error) {
  655. console.error('[CPR] Falha ao renderizar QR Code de pagamento', error);
  656. paymentError = 'Não foi possível gerar o QR Code. Use o código Pix copiado para pagar.';
  657. }
  658. }
  659. async function openPaymentModalWithPayment(data, startedAt = Date.now(), immediatePoll = true) {
  660. if (!data?.payment_id || !data?.payment_code) return;
  661. paymentModalVisible = true;
  662. paymentId = Number(data.payment_id);
  663. paymentCode = data.payment_code;
  664. paymentError = '';
  665. paymentStatusMessage = 'Aguardando pagamento via Pix.';
  666. paymentCopyFeedback = '';
  667. paymentStartedAt = startedAt;
  668. const remaining = PAYMENT_TIMEOUT_MS - (Date.now() - startedAt);
  669. paymentCountdownMs = remaining > 0 ? remaining : PAYMENT_TIMEOUT_MS;
  670. persistPaymentState();
  671. await tick();
  672. await renderPaymentQrCode(paymentCode);
  673. startPaymentCountdown(startedAt);
  674. startPaymentPolling(immediatePoll);
  675. }
  676. async function restorePersistedPayment() {
  677. if (!browser) return;
  678. try {
  679. const raw = localStorage.getItem(PAYMENT_STORAGE_KEY);
  680. if (!raw) return;
  681. const stored = JSON.parse(raw);
  682. if (!stored?.paymentId || !stored?.paymentCode) {
  683. removePaymentStateFromStorage();
  684. return;
  685. }
  686. const startedAt = stored.startedAt ?? Date.now();
  687. const remaining = PAYMENT_TIMEOUT_MS - (Date.now() - startedAt);
  688. if (remaining <= 0) {
  689. removePaymentStateFromStorage();
  690. return;
  691. }
  692. await openPaymentModalWithPayment(
  693. { payment_id: stored.paymentId, payment_code: stored.paymentCode },
  694. startedAt,
  695. false
  696. );
  697. paymentStatusMessage = 'Retomamos a verificação do pagamento pendente.';
  698. startPaymentPolling(true);
  699. } catch (err) {
  700. console.error('[CPR] Não foi possível restaurar o pagamento pendente', err);
  701. removePaymentStateFromStorage();
  702. }
  703. }
  704. async function handleCopyPaymentCode() {
  705. if (!browser || !paymentCode) return;
  706. try {
  707. await navigator.clipboard.writeText(paymentCode);
  708. paymentCopyFeedback = 'Código Pix copiado!';
  709. } catch {
  710. paymentCopyFeedback = 'Não foi possível copiar automaticamente. Copie manualmente.';
  711. } finally {
  712. stopPaymentCopyTimeout();
  713. if (browser) {
  714. paymentCopyTimeoutId = window.setTimeout(() => {
  715. paymentCopyFeedback = '';
  716. paymentCopyTimeoutId = null;
  717. }, 2000);
  718. }
  719. }
  720. }
  721. async function fetchHistory() {
  722. historyLoading = true;
  723. historyError = '';
  724. detailError = '';
  725. detailLoading = false;
  726. try {
  727. const { token } = ensureAuthContext();
  728. const res = await fetch(historyEndpoint, {
  729. method: 'POST',
  730. headers: {
  731. 'content-type': 'application/json',
  732. Authorization: `Bearer ${token}`
  733. },
  734. body: JSON.stringify({})
  735. });
  736. const body = await parseJsonResponse(res);
  737. if (!res.ok) {
  738. throw new Error(body?.message ?? 'Falha ao carregar histórico.');
  739. }
  740. historyRows = normalizeHistoryList(body);
  741. selectedDetail = null;
  742. selectedDetailId = null;
  743. historyInitialized = true;
  744. } catch (err) {
  745. historyRows = [];
  746. historyError = err?.message ?? 'Falha ao carregar histórico.';
  747. } finally {
  748. historyLoading = false;
  749. }
  750. }
  751. async function fetchDetail(cprId) {
  752. if (!cprId) return;
  753. detailLoading = true;
  754. detailError = '';
  755. try {
  756. const { token } = ensureAuthContext();
  757. const res = await fetch(historyEndpoint, {
  758. method: 'POST',
  759. headers: {
  760. 'content-type': 'application/json',
  761. Authorization: `Bearer ${token}`
  762. },
  763. body: JSON.stringify({ cpr_id: cprId })
  764. });
  765. const body = await parseJsonResponse(res);
  766. if (!res.ok) {
  767. throw new Error(body?.message ?? 'Falha ao carregar detalhes da CPR.');
  768. }
  769. const detail = Array.isArray(body) ? body[0] : body?.data ?? body;
  770. selectedDetail = sanitizeDetail(detail) ?? detail ?? {};
  771. } catch (err) {
  772. detailError = err?.message ?? 'Falha ao carregar detalhes da CPR.';
  773. selectedDetail = null;
  774. } finally {
  775. detailLoading = false;
  776. }
  777. }
  778. function handleViewDetails(cprId) {
  779. if (!cprId) return;
  780. selectedDetailId = cprId;
  781. selectedDetail = null;
  782. detailError = '';
  783. showDetailModal = true;
  784. void fetchDetail(cprId);
  785. }
  786. function handleCloseDetail() {
  787. selectedDetail = null;
  788. selectedDetailId = null;
  789. detailError = '';
  790. showDetailModal = false;
  791. detailLoading = false;
  792. }
  793. function handleRetryDetail() {
  794. if (selectedDetailId) {
  795. detailError = '';
  796. detailLoading = true;
  797. void fetchDetail(selectedDetailId);
  798. }
  799. }
  800. onMount(() => {
  801. void fetchHistory();
  802. void restorePersistedPayment();
  803. updateB3OfflineState();
  804. if (browser) {
  805. b3OfflineIntervalId = window.setInterval(updateB3OfflineState, B3_OFFLINE_POLL_INTERVAL_MS);
  806. }
  807. });
  808. onDestroy(() => {
  809. stopPaymentPolling();
  810. stopPaymentCountdown();
  811. stopPaymentCopyTimeout();
  812. if (b3OfflineIntervalId) {
  813. clearInterval(b3OfflineIntervalId);
  814. b3OfflineIntervalId = null;
  815. }
  816. });
  817. function getMissingRequiredFields() {
  818. const missing = [];
  819. requiredFields.forEach((key) => {
  820. const groupKey = repeatingFieldToGroup[key];
  821. if (groupKey) {
  822. const config = repeatingGroupDefinitions.find((c) => c.key === groupKey);
  823. const entries = repeatingGroups[groupKey] ?? [];
  824. if (!entries.length) {
  825. missing.push(`${key} (${config?.itemLabel ?? groupKey})`);
  826. return;
  827. }
  828. entries.forEach((entry, index) => {
  829. const raw = entry?.[key];
  830. if (!raw || String(raw).trim() === '') {
  831. missing.push(`${key} (${config?.itemLabel ?? groupKey} ${index + 1})`);
  832. }
  833. });
  834. } else {
  835. const raw = cprForm[key];
  836. if (!raw || String(raw).trim() === '') {
  837. missing.push(key);
  838. }
  839. }
  840. });
  841. return missing;
  842. }
  843. function buildPayload() {
  844. const payload = {};
  845. for (const key of allFieldKeys) {
  846. const groupKey = repeatingFieldToGroup[key];
  847. if (groupKey) {
  848. const entries = repeatingGroups[groupKey] ?? [];
  849. const values = entries
  850. .map((entry) => entry?.[key])
  851. .map((value) => (typeof value === 'string' ? value.trim() : value))
  852. .filter((value) => value && value !== '');
  853. payload[key] = values.length
  854. ? values.join('; ')
  855. : requiredFields.has(key)
  856. ? ''
  857. : 'NA';
  858. continue;
  859. }
  860. const raw = cprForm[key];
  861. const trimmed = typeof raw === 'string' ? raw.trim() : raw;
  862. if (trimmed === '' || trimmed === undefined || trimmed === null) {
  863. payload[key] = requiredFields.has(key) ? '' : 'NA';
  864. } else {
  865. payload[key] = raw;
  866. }
  867. }
  868. return payload;
  869. }
  870. async function handleFinalize(event) {
  871. event?.preventDefault();
  872. submitError = '';
  873. submitSuccess = '';
  874. const missing = getMissingRequiredFields();
  875. if (missing.length) {
  876. submitError = `Preencha os campos obrigatórios: ${missing.join(', ')}`;
  877. return;
  878. }
  879. const token = $authToken;
  880. if (!token) {
  881. submitError = 'Sessão expirada. Faça login novamente.';
  882. return;
  883. }
  884. const payload = buildPayload();
  885. payload.discount = typeof emissionDiscountCode === 'string' ? emissionDiscountCode.trim() : '';
  886. isSubmitting = true;
  887. paymentLoadingVisible = true;
  888. try {
  889. const res = await fetch(`${apiUrl}/b3/cpr/register`, {
  890. method: 'POST',
  891. headers: {
  892. 'content-type': 'application/json',
  893. Authorization: `Bearer ${token}`
  894. },
  895. body: JSON.stringify(payload)
  896. });
  897. const raw = await res.text();
  898. let response = null;
  899. if (raw) {
  900. try {
  901. response = JSON.parse(raw);
  902. } catch (err) {
  903. console.error('Resposta inválida ao registrar CPR:', err, raw);
  904. throw new Error('Resposta inválida do servidor ao registrar CPR.');
  905. }
  906. }
  907. const serverStatus = response?.status?.toLowerCase?.() ?? '';
  908. if (!res.ok || (response?.status && serverStatus !== 'ok')) {
  909. console.error('[CPR] Falha ao registrar CPR', {
  910. status: res.status,
  911. statusText: res.statusText,
  912. raw,
  913. response
  914. });
  915. throw new Error((response?.msg ?? raw) || 'Falha ao registrar CPR.');
  916. }
  917. submitSuccess = response?.msg ?? 'CPR registrada com sucesso.';
  918. const paymentData = response?.data;
  919. cprForm = createInitialForm();
  920. repeatingGroups = createInitialRepeatingGroups();
  921. emissionDiscountCode = '';
  922. if (paymentData?.payment_id && paymentData?.payment_code) {
  923. await openPaymentModalWithPayment(paymentData);
  924. }
  925. } catch (err) {
  926. console.error('[CPR] Erro inesperado ao registrar CPR', err);
  927. submitError = err?.message ?? 'Falha ao registrar CPR.';
  928. } finally {
  929. isSubmitting = false;
  930. paymentLoadingVisible = false;
  931. }
  932. }
  933. function isWithinB3OfflineWindow(date = new Date()) {
  934. let hour = date.getHours();
  935. try {
  936. const parts = new Intl.DateTimeFormat('pt-BR', {
  937. timeZone: 'America/Sao_Paulo',
  938. hour: '2-digit',
  939. hourCycle: 'h23'
  940. }).formatToParts(date);
  941. const hourPart = parts.find((part) => part.type === 'hour')?.value;
  942. const parsed = Number(hourPart);
  943. if (Number.isFinite(parsed)) {
  944. hour = parsed;
  945. }
  946. } catch (err) {
  947. hour = date.getHours();
  948. }
  949. return hour >= B3_OFFLINE_START_HOUR || hour < B3_OFFLINE_END_HOUR;
  950. }
  951. function updateB3OfflineState() {
  952. if (!browser) {
  953. isB3OfflineWindow = false;
  954. return;
  955. }
  956. isB3OfflineWindow = isWithinB3OfflineWindow(new Date());
  957. }
  958. function handleB3OfflineRedirect() {
  959. goto('/dashboard');
  960. }
  961. </script>
  962. {#if isB3OfflineWindow}
  963. <div class="fixed inset-0 z-50 flex items-center justify-center px-4 bg-black/70 backdrop-blur-sm">
  964. <div class="w-full max-w-xl rounded-2xl bg-white shadow-2xl border border-red-200 dark:bg-gray-900 dark:border-red-800/40 overflow-hidden">
  965. <div class="px-6 py-5 space-y-4 text-center">
  966. <p class="text-sm uppercase tracking-[0.3em] text-red-500 font-semibold">Manutenção programada</p>
  967. <h2 class="text-2xl font-bold text-gray-900 dark:text-gray-100">B3 indisponível entre 20h e 8h (horário de Brasília)</h2>
  968. <p class="text-base text-gray-600 dark:text-gray-300">
  969. A emissão de novas CPRs fica temporariamente suspensa enquanto a B3 está offline. Retorne ao dashboard e tente novamente após as 08:00 (horário de Brasília).
  970. </p>
  971. <button
  972. type="button"
  973. class="mt-2 inline-flex items-center justify-center rounded-lg bg-gray-900 text-white font-semibold px-6 py-3 hover:bg-gray-800 focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-gray-900 dark:bg-white dark:text-gray-900"
  974. on:click={handleB3OfflineRedirect}
  975. >
  976. Voltar para o dashboard
  977. </button>
  978. </div>
  979. </div>
  980. </div>
  981. {/if}
  982. <div>
  983. <Header title="CPR - Cédula de Produto Rural" subtitle="Gestão de contratos, emissão e registro de CPRs" breadcrumb={breadcrumb} />
  984. <div class="p-4">
  985. <div class="max-w-6xl mx-auto mt-4">
  986. {#if submitError}
  987. <div class="mb-4 rounded border border-red-300 bg-red-50 text-red-700 px-3 py-2 text-sm">{submitError}</div>
  988. {/if}
  989. {#if submitSuccess}
  990. <div class="mb-4 rounded border border-green-300 bg-green-50 text-green-700 px-3 py-2 text-sm">{submitSuccess}</div>
  991. {/if}
  992. {#if activeTab === 4}
  993. <section class="space-y-4">
  994. <div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
  995. <div>
  996. <h2 class="text-lg font-semibold text-gray-900 dark:text-gray-50">Histórico de CPRs</h2>
  997. <p class="text-sm text-gray-500 dark:text-gray-400">
  998. Consulte as últimas CPRs emitidas e visualize os detalhes completos.
  999. </p>
  1000. </div>
  1001. <div class="flex gap-2">
  1002. <button
  1003. type="button"
  1004. class="inline-flex items-center gap-2 rounded-md border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-60"
  1005. on:click={handleAddTop}
  1006. >
  1007. Nova CPR
  1008. </button>
  1009. <button
  1010. type="button"
  1011. class="inline-flex items-center gap-2 rounded-md border border-gray-300 dark:border-gray-600 px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-100 hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-60"
  1012. on:click={() => fetchHistory()}
  1013. disabled={historyLoading}
  1014. >
  1015. {historyLoading ? 'Atualizando...' : 'Atualizar'}
  1016. </button>
  1017. </div>
  1018. </div>
  1019. {#if historyError}
  1020. <div class="rounded border border-red-200 bg-red-50 dark:border-red-900/40 dark:bg-red-900/20 px-3 py-2 text-sm text-red-700 dark:text-red-300">
  1021. {historyError}
  1022. </div>
  1023. {/if}
  1024. <div class="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
  1025. <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700 text-sm">
  1026. <thead class="bg-gray-50 dark:bg-gray-900/40 text-gray-600 dark:text-gray-300 uppercase text-xs">
  1027. <tr>
  1028. {#each historyColumns as column}
  1029. <th class="px-4 py-3 text-left font-semibold">{column.label}</th>
  1030. {/each}
  1031. <th class="px-4 py-3 text-left font-semibold">Monitoramento</th>
  1032. <th class="px-4 py-3 text-left font-semibold">Ação</th>
  1033. </tr>
  1034. </thead>
  1035. <tbody class="divide-y divide-gray-200 dark:divide-gray-700 text-gray-800 dark:text-gray-100">
  1036. {#if historyLoading && !historyInitialized}
  1037. <tr>
  1038. <td class="px-4 py-6 text-center" colspan={historyColumns.length + 2}>
  1039. Carregando histórico...
  1040. </td>
  1041. </tr>
  1042. {:else if !historyRows.length}
  1043. <tr>
  1044. <td class="px-4 py-6 text-center text-gray-500 dark:text-gray-400" colspan={historyColumns.length + 2}>
  1045. Nenhuma CPR encontrada.
  1046. </td>
  1047. </tr>
  1048. {:else}
  1049. {#each historyRows as row}
  1050. <tr class="hover:bg-gray-50 dark:hover:bg-gray-700/60">
  1051. <td class="px-4 py-3 font-medium">{row.cpr_id ?? '—'}</td>
  1052. <td class="px-4 py-3">{row.cpr_product_class_name ?? '—'}</td>
  1053. <td class="px-4 py-3">{row.cpr_issue_date ?? '—'}</td>
  1054. <td class="px-4 py-3">{row.cpr_issuer_name ?? '—'}</td>
  1055. <td class="px-4 py-3">{formatCurrency(row.cpr_issue_financial_value)}</td>
  1056. <td class="px-4 py-3">
  1057. {#if row.cpr_id}
  1058. <a
  1059. class="inline-flex items-center justify-center rounded-full p-1.5 text-gray-700 hover:text-gray-900 dark:text-gray-200 dark:hover:text-white"
  1060. href={`/cpr/monitoring?cpr_id=${encodeURIComponent(String(row.cpr_id))}`}
  1061. aria-label="Abrir monitoramento"
  1062. >
  1063. <svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
  1064. <path
  1065. d="M4 7h3l2-2h6l2 2h3a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2z"
  1066. stroke-linecap="round"
  1067. stroke-linejoin="round"
  1068. />
  1069. <path
  1070. d="M12 18a4 4 0 1 0 0-8 4 4 0 0 0 0 8z"
  1071. stroke-linecap="round"
  1072. stroke-linejoin="round"
  1073. />
  1074. </svg>
  1075. </a>
  1076. {:else}
  1077. {/if}
  1078. </td>
  1079. <td class="px-4 py-3">
  1080. <button
  1081. type="button"
  1082. class="inline-flex items-center justify-center rounded-full p-1.5 text-blue-600 hover:text-blue-500 disabled:opacity-60"
  1083. on:click={() => handleViewDetails(row.cpr_id)}
  1084. disabled={!row.cpr_id || detailLoading && selectedDetailId === row.cpr_id}
  1085. aria-label={detailLoading && selectedDetailId === row.cpr_id ? 'Carregando detalhes' : 'Mais informações'}
  1086. >
  1087. <svg
  1088. class="h-4 w-4"
  1089. viewBox="0 0 20 20"
  1090. fill="none"
  1091. stroke="currentColor"
  1092. stroke-width="1.8"
  1093. >
  1094. <path d="M7 5l5 5-5 5" stroke-linecap="round" stroke-linejoin="round" />
  1095. </svg>
  1096. </button>
  1097. </td>
  1098. </tr>
  1099. {/each}
  1100. {/if}
  1101. </tbody>
  1102. </table>
  1103. </div>
  1104. </section>
  1105. <CprDetailModal
  1106. visible={showDetailModal}
  1107. title="Detalhes da CPR"
  1108. detailId={selectedDetailId}
  1109. loading={detailLoading}
  1110. error={detailError}
  1111. detail={selectedDetail}
  1112. formatKey={humanizeKey}
  1113. formatValue={formatDetailValue}
  1114. on:close={handleCloseDetail}
  1115. on:retry={handleRetryDetail}
  1116. />
  1117. {:else if activeTab === 0}
  1118. <Tabs {tabs} bind:active={activeTab} showCloseIcon={true} on:close={handleCancel} />
  1119. <div class="mt-4">
  1120. <ContractCpr formData={cprForm} onFieldChange={handleFieldChange} {requiredFields} />
  1121. </div>
  1122. <!-- Navigation Controls -->
  1123. <div class="flex justify-between mt-6">
  1124. <button
  1125. type="button"
  1126. class="px-4 py-2 bg-gray-300 text-gray-700 rounded-lg cursor-not-allowed"
  1127. disabled
  1128. >
  1129. Anterior
  1130. </button>
  1131. <button
  1132. type="button"
  1133. class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
  1134. on:click={() => activeTab = 1}
  1135. >
  1136. Próximo
  1137. </button>
  1138. </div>
  1139. {:else if activeTab === 1}
  1140. <Tabs {tabs} bind:active={activeTab} showCloseIcon={true} on:close={handleCancel} />
  1141. <div class="mt-4">
  1142. <RegisterCpr formData={cprForm} onFieldChange={handleFieldChange} {requiredFields} />
  1143. </div>
  1144. <!-- Navigation Controls -->
  1145. <div class="flex justify-between mt-6">
  1146. <button
  1147. type="button"
  1148. class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600"
  1149. on:click={() => activeTab = 0}
  1150. >
  1151. Anterior
  1152. </button>
  1153. <button
  1154. type="button"
  1155. class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
  1156. on:click={() => activeTab = 2}
  1157. >
  1158. Próximo
  1159. </button>
  1160. </div>
  1161. {:else if activeTab === 2}
  1162. <Tabs {tabs} bind:active={activeTab} showCloseIcon={true} on:close={handleCancel} />
  1163. <div class="mt-4">
  1164. <EmissionCpr
  1165. formData={cprForm}
  1166. onFieldChange={handleFieldChange}
  1167. {requiredFields}
  1168. repeatingConfigs={repeatingGroupDefinitions}
  1169. {repeatingGroups}
  1170. onRepeatingFieldChange={handleRepeatingFieldChange}
  1171. onAddRepeatingEntry={handleAddRepeatingEntry}
  1172. onRemoveRepeatingEntry={handleRemoveRepeatingEntry}
  1173. />
  1174. </div>
  1175. <div class="mt-4 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg shadow-sm">
  1176. <div class="p-4 space-y-1">
  1177. <label class="block text-sm font-medium text-gray-700 dark:text-gray-300" for="cpr-emission-discount-code">
  1178. Código de desconto de emissão
  1179. </label>
  1180. <input
  1181. id="cpr-emission-discount-code"
  1182. type="text"
  1183. class="w-full rounded border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700/70 text-gray-900 dark:text-gray-100 px-3 py-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
  1184. bind:value={emissionDiscountCode}
  1185. disabled={isSubmitting}
  1186. placeholder="Opcional"
  1187. autocomplete="off"
  1188. />
  1189. </div>
  1190. </div>
  1191. <!-- Navigation Controls -->
  1192. <div class="flex justify-between mt-6">
  1193. <button
  1194. type="button"
  1195. class="px-4 py-2 bg-gray-500 text-white rounded-lg hover:bg-gray-600"
  1196. on:click={() => activeTab = 1}
  1197. >
  1198. Anterior
  1199. </button>
  1200. <button
  1201. type="button"
  1202. class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold"
  1203. on:click|preventDefault={handleFinalize}
  1204. disabled={isSubmitting}
  1205. >
  1206. {isSubmitting ? 'Enviando...' : 'Finalizar CPR'}
  1207. </button>
  1208. </div>
  1209. {/if}
  1210. </div>
  1211. </div>
  1212. {#if paymentModalVisible}
  1213. <div class="fixed inset-0 z-40 flex items-center justify-center bg-black/60 px-4">
  1214. <div class="w-full max-w-xl rounded-2xl bg-white dark:bg-gray-900 p-6 shadow-2xl relative">
  1215. <button
  1216. class="absolute top-4 right-4 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
  1217. aria-label="Fechar"
  1218. on:click={handleCancelPaymentFlow}
  1219. >
  1220. </button>
  1221. <div class="space-y-4">
  1222. <div>
  1223. <p class="text-sm uppercase tracking-wider text-blue-500 font-semibold">Pagamento pendente</p>
  1224. <h3 class="text-2xl font-bold text-gray-900 dark:text-white">Finalize a CPR via Pix</h3>
  1225. <p class="text-sm text-gray-600 dark:text-gray-300">
  1226. Utilize o QR Code ou copie o código Pix para concluir o pagamento. O QR Code expira em
  1227. <span class="font-semibold">{formatCountdown(paymentCountdownMs)}</span>.
  1228. </p>
  1229. </div>
  1230. <div class="flex flex-col gap-6 md:flex-row">
  1231. <div class="flex-1 rounded-xl border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/80 p-4 flex flex-col items-center gap-4">
  1232. <div class="text-center">
  1233. <p class="text-xs uppercase tracking-wider text-gray-500">QR Code Pix</p>
  1234. <p class="text-sm text-gray-600 dark:text-gray-300">Escaneie com o app do banco</p>
  1235. </div>
  1236. <div
  1237. class="w-56 h-56 flex items-center justify-center bg-white rounded-xl shadow-inner"
  1238. bind:this={paymentQrContainer}
  1239. aria-label="QR Code do pagamento"
  1240. ></div>
  1241. <button
  1242. type="button"
  1243. class="w-full rounded-lg bg-blue-600 hover:bg-blue-700 text-white py-2 text-sm font-semibold transition disabled:opacity-60"
  1244. on:click={handleCopyPaymentCode}
  1245. disabled={!paymentCode}
  1246. >
  1247. {paymentCopyFeedback ? paymentCopyFeedback : 'Copiar código Pix'}
  1248. </button>
  1249. </div>
  1250. <div class="flex-1 space-y-4">
  1251. <div class="rounded-lg border border-amber-200 bg-amber-50 text-amber-900 px-3 py-2 text-sm">
  1252. <p class="font-semibold text-amber-900">Tempo restante</p>
  1253. <p class="text-3xl font-mono tracking-widest">{formatCountdown(paymentCountdownMs)}</p>
  1254. </div>
  1255. <div class="space-y-2">
  1256. <label class="text-sm font-medium text-gray-700 dark:text-gray-300" for="payment-code-copy">Código Pix copia e cola</label>
  1257. <textarea
  1258. id="payment-code-copy"
  1259. class="w-full text-sm rounded-lg border border-gray-300 dark:border-gray-700 bg-gray-50 dark:bg-gray-900 text-gray-800 dark:text-gray-100 p-2 resize-none"
  1260. rows="4"
  1261. readonly
  1262. value={paymentCode}
  1263. ></textarea>
  1264. </div>
  1265. {#if paymentStatusMessage}
  1266. <div class="rounded-lg border border-blue-200 bg-blue-50 text-blue-900 px-3 py-2 text-sm">
  1267. {paymentStatusMessage}
  1268. </div>
  1269. {/if}
  1270. {#if paymentError}
  1271. <div class="rounded-lg border border-red-200 bg-red-50 text-red-900 px-3 py-2 text-sm">
  1272. {paymentError}
  1273. </div>
  1274. {/if}
  1275. <div class="flex flex-wrap gap-2">
  1276. <button
  1277. type="button"
  1278. class="flex-1 min-w-[140px] inline-flex items-center justify-center rounded-lg border border-gray-300 dark:border-gray-700 px-3 py-2 text-sm font-semibold text-gray-700 dark:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-800 disabled:opacity-60"
  1279. on:click={handleRetryPaymentCheck}
  1280. disabled={isCheckingPayment}
  1281. >
  1282. {isCheckingPayment ? 'Verificando...' : 'Reverificar agora'}
  1283. </button>
  1284. <button
  1285. type="button"
  1286. class="flex-1 min-w-[140px] inline-flex items-center justify-center rounded-lg border border-red-300 px-3 py-2 text-sm font-semibold text-red-600 hover:bg-red-50"
  1287. on:click={handleCancelPaymentFlow}
  1288. >
  1289. Cancelar pagamento
  1290. </button>
  1291. </div>
  1292. </div>
  1293. </div>
  1294. </div>
  1295. </div>
  1296. </div>
  1297. {/if}
  1298. {#if paymentLoadingVisible}
  1299. <div class="fixed inset-0 z-50 flex items-center justify-center bg-gray-900/60 backdrop-blur-sm">
  1300. <div class="flex flex-col items-center gap-4 text-white">
  1301. <div class="w-12 h-12 border-4 border-white/30 border-t-white rounded-full animate-spin"></div>
  1302. <p class="text-base font-semibold">Gerando QR Code do Pix...</p>
  1303. </div>
  1304. </div>
  1305. {/if}
  1306. {#if paymentSuccessOverlayVisible}
  1307. <div class="fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm px-4">
  1308. <div class="w-full max-w-md rounded-2xl bg-white dark:bg-gray-900 p-6 text-center space-y-4 shadow-2xl">
  1309. <div class="text-green-600 dark:text-green-400 flex justify-center">
  1310. <svg class="w-16 h-16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  1311. <path d="M20 6L9 17l-5-5" />
  1312. </svg>
  1313. </div>
  1314. <h3 class="text-2xl font-semibold text-gray-900 dark:text-gray-50">Pagamento confirmado!</h3>
  1315. <p class="text-gray-600 dark:text-gray-300">{paymentSuccessMessage || 'A CPR foi emitida com sucesso. Você será redirecionado para o histórico.'}</p>
  1316. <button
  1317. type="button"
  1318. class="w-full rounded-lg bg-green-600 hover:bg-green-700 text-white font-semibold py-2"
  1319. on:click={handlePaymentSuccessAcknowledge}
  1320. >
  1321. Ir para histórico de CPRs
  1322. </button>
  1323. </div>
  1324. </div>
  1325. {/if}
  1326. </div>