
    "je$                     h    d dl mZmZmZ d dlmZmZmZmZm	Z	m
Z
 d dlmZ dedefdZ G d d      Zy	)
    )ListDictAny)ProductCostInputTaxProfileInputMarketplaceInputPricingResultCostBreakdownCalculationTrace)PricingValidatorvaluereturnc                     t        | d      S )u4   Arredonda valores monetários para 2 casas decimais.   )round)r   s    R/var/www/hypershopcomercio.com.br/hyper-ai/app/services/pricing/core_calculator.pyround_moneyr      s    ?    c                       e Zd ZdZd Zddedededeeef   fdZ	d	e
d
ededefdZ	 	 	 	 dd	e
d
edededededededefdZd	e
d
ededefdZy)PricingCoreCalculatoru   
    Motor matemático puro para cálculo de custos e precificação.
    Não possui dependência de banco de dados ou APIs externas.
    c                     g | _         y N)traces)selfs    r   __init__zPricingCoreCalculator.__init__   s	    .0r   Nstepformularesultdetailsc           	      \    | j                   j                  t        ||||xs i              y )N)r   r   r   r   )r   appendr   )r   r   r   r   r   s        r   
_add_tracez PricingCoreCalculator._add_trace   s,    +Mr	
 	r   product_costtax_profilemarketplacer   c                 H	   g | _         t        j                  |||      }d}|j                  r_|j                  dkD  rPt        |j                  |j                  dz  z        }| j                  dd||j                  |j                  d       d}|j                  rt        |j                  |z         }t        |d|j                  dz  z   z        }t        ||j                  dz  z        }	t        |j                  |j                  dz  z        }
t        t        d|	|
z
              }| j                  dd	|       | j                  d
d|d|j                  i       | j                  dd|	d|j                  i       | j                  dd|
d|j                  i       | j                  dd|       |j                  rt        |j                        nd}|dkD  r| j                  dd|       t        |j                  |z   |z   |z   |j                   z         }| j                  dd|       t#        t        |j                        |||t        |j                         |      }|j                  r|j$                  n|j&                  }t        |j(                  |dz  z        }| j                  dd|j                  rdnd |||j                  d       t        |j(                  |j*                  dz  z        }| j                  dd |d!|j*                  i       t        ||j,                  z   |j.                  z         }| j                  d"d#||j,                  |j.                  d$       t        ||z   |z   |j0                  z         }| j                  d%d&|d'|j0                  i       t        |j(                  |z
        }| j                  d(d)|       d}|j(                  dkD  r.t        ||j(                  z  dz        }| j                  d*d+|       d}|dkD  r$t        ||z  dz        }| j                  d,d-|       t3        |j(                  |||||t        |j.                        || j                   |.
      }|j4                  j7                  t        j8                  |             |S )/N        r   g      Y@u   Cálculo de IPIu    Valor NF * (Alíquota IPI / 100))valor_nfipi_rate   u   Cálculo de ST (Base + IPI)zValor NF + IPIu    Cálculo de ST (Base ST com MVA)z(Valor NF + IPI) * (1 + MVA)mva_rateu   Cálculo de ST (ICMS Destino)zBase ST * ICMS Destinoicms_destinou   Cálculo de ST (ICMS Próprio)zValor NF * ICMS Origemicms_origemu   Cálculo de ST (Valor a Pagar)u   ICMS Destino - ICMS PróprioDIFALzValor manual preenchidozCusto Final do Produtoz&Custo Real + IPI + ST + DIFAL + Outros)	real_cost	ipi_valuest_valuedifal_valueother_costsfinal_product_costzImposto sobre Venda (DAS)u   Preço de Venda * zDAS (sem ICMS)z
DAS (Full))active_ratehas_stu   Comissão Marketplaceu   Preço Venda * Taxa Marketplacefee_ratezCusto Total Marketplaceu   Comissão + Taxa Fixa + Frete)	fixed_feefreightu   Deduções TotaisuC   Custo Final + Total Marketplace + Imposto Venda + Outros Variáveisother_variable_costszLucro Finalu    Preço Venda - Deduções Totaisu   Margem de Contribuiçãou   (Lucro / Preço Venda) * 100z.Retorno sobre Custo Total (Markup Equivalente)u!   (Lucro / Deduções Totais) * 100)
suggested_selling_priceprofit_amountcontribution_margin_percentreturn_over_cost_percentsales_tax_valuemarketplace_fee_valuefreight_costcost_breakdowntracewarnings)r   r   validate_inputshas_ipir)   r   r(   r"   r6   r+   destination_icms_rateorigin_icms_ratemax	has_difalr2   r/   other_purchase_costsr
   das_without_icms_ratefull_das_rateselling_pricer7   r8   rA   r:   r	   rD   extendvalidate_result)r   r#   r$   r%   rD   r0   r1   base_with_ipist_base	dest_icmsown_icmsr2   r4   rB   active_das_rater?   	fee_valuetotal_marketplace_coststotal_deductionsprofitcontribution_margin_pctreturn_over_cost_pctr   s                          r   	calculatezPricingCoreCalculator.calculate!   s    #33L+{[ 	<#8#81#<#L$9$9\=R=RUZ=Z$[\IOO!2)22@U@UV	 '(=(=	(IJM!-18L8Lu8T3U"VWG#G{/P/PSX/X$YZI"<#8#8K<X<X[`<`#abH"3sI,@#ABHOO- 
 OO2.[112	 OO/(!B!BC	 OO0( < <=	 OO0. @K?T?Tk,":":;Z]?OOG%>L )""Y.9KG,JkJkk
 	$4	
 '!,"8"89##L$E$EF1
 @K?Q?Q+;;WbWpWp%k&?&??UZCZ&[\' [5G5G!1\ Z[+{7I7IJ		
   9 9[=Q=QTY=Y Z[	#---.		
 #.i+:O:O.OR]RjRj.j"k%+#%//K<T<TU		
 ''9<S'SVe'ehs  iI  iI  (I  JQ#[%E%EF		
 [669IIJ.	
 #&$$q(&16K<U<U3UY^2^&_#OO*.'  #a#.9I0IU/R#S OO@3$ $/$=$= (?%9+"+$[%=%=>)++
 	/??GHr   target_margin_percent	min_price	max_price	tolerancemax_iterationsc	                    |dk\  ryddl }	|	j                  |      }
|}|}d}t        |      D ]I  }||z   dz  }||
_        | j	                  |||
      }|j
                  }||k\  r|}||z
  }n||z   }||k  sI n |dkD  rt        |      S y)u   
        Usa busca binária para encontrar o menor preço de venda que gera uma margem de contribuição
        igual ou maior à target_margin_percent.
        Retorna 0.0 se não encontrar preço viável.
        d   r'   r   Nr   )copydeepcopyrangerN   r\   r=   r   )r   r#   r$   r%   r]   r^   r_   r`   ra   rd   
market_simlowhigh
best_price_midr   current_margins                     r    find_minimum_price_target_marginz6PricingCoreCalculator.find_minimum_price_target_margin   s      !C']];/

~& 	A:"C'*J$^^L+zJF#??N!66 
YIocz	  
++r   c                 *    | j                  |||d      S )u-   Encontra o preço exato onde o lucro é zero.r'   )rn   )r   r#   r$   r%   s       r   find_minimum_price_zero_profitz4PricingCoreCalculator.find_minimum_price_zero_profit   s     44\;P[]`aar   r   ){Gz?g     j@rq   2   )__name__
__module____qualname____doc__r   strfloatr   r   r"   r   r   r   r	   r\   intrn   rp    r   r   r   r      s   
1s S % $sTWx. c&c %c &	c
 
cV  # ,&, %, &	,
  %, , , , , 
,\b&b %b &	b
 
br   r   N)typingr   r   r   app.services.pricing.typesr   r   r   r	   r
   r   app.services.pricing.validatorr   rx   r   r   rz   r   r   <module>r~      s;    " "  <u  kb kbr   