File size: 2,554 Bytes
55d9355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export const EMPTY_REASON = { descricao: '', alegado: true, confirmado: false };
export const REVIEW_FIELDS = ['metodo_avaliacao', 'modelo_avaliacao', 'datas_referencia'];

export function importDefaults(value) {
  if (!value) return {};
  const suggestions = value.preview.sugestoes || {};
  const rows = value.preview.avaliacoes;
  const baseYears = rows.map((row) => {
    const year = String(value.anos[row.id] || '');
    return /^(19|20|21)\d{2}$/.test(year)
      ? Number(year) - (value.referenciaAnos === 'exercicio_iptu' ? 1 : 0) : null;
  }).filter((year) => year !== null).sort((a, b) => a - b);
  return {
    metodo_avaliacao: suggestions.metodo_avaliacao || ('Método Comparativo Dados de Mercado - ABNT NBR 14.653-2' + (value.preview.tipo === 'evolutivo' ? ' e Método de Quantificação de Custo' : '')),
    modelo_avaliacao: suggestions.modelo_avaliacao ?? [...new Set(rows.map((row) => row.modelo).filter(Boolean))].join(', '),
    datas_referencia: [...new Set(baseYears)].map((year) => `Dezembro/${year}`).join(', '),
    motivos_desvalorizantes: suggestions.motivos_desvalorizantes?.length
      ? suggestions.motivos_desvalorizantes.map((item) => ({ ...item })) : [{ ...EMPTY_REASON }],
  };
}

export function applyImportDefaults(form, next, previous, edited) {
  if (!form) return form;
  const patch = {};
  for (const field of new Set([...Object.keys(previous), ...Object.keys(next)])) {
    if (edited.has(field)) continue;
    const value = next[field] ?? (field === 'motivos_desvalorizantes' ? [{ ...EMPTY_REASON }] : '');
    if (JSON.stringify(form[field]) !== JSON.stringify(value)) patch[field] = value;
  }
  return Object.keys(patch).length ? { ...form, ...patch } : form;
}

export function decimalValue(input) {
  const value = String(input ?? '').trim().replace(/^R\$\s*/, '');
  if (value.includes(',')) {
    if (!/^(?:\d{1,3}(?:\.\d{3})+|\d+),\d{1,2}$/.test(value)) return null;
    return value.replace(/\./g, '').replace(',', '.');
  }
  return /^\d+(?:\.\d{1,2})?$/.test(value) ? value : null;
}

export function moneyInput(value) {
  const [whole, cents = '00'] = String(value).split('.');
  return `${whole.replace(/\B(?=(\d{3})+(?!\d))/g, '.')},${cents.padEnd(2, '0')}`;
}

export function adoptedValues(value) {
  const output = {};
  for (const [id, input] of Object.entries(value.valoresAdotados || {})) {
    const parsed = decimalValue(input);
    if (parsed === null) throw new Error('Informe valores de mercado válidos na seção 5. Avaliação.');
    output[id] = parsed;
  }
  return output;
}