o
    i9c                     @   s(  d dl mZ d dlmZmZ d dlmZmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZ d d	lZd d	lZd d
lmZ d dlmZ d dlmZ d dlmZmZmZmZmZ d dlm Z  d dl!m"Z" d dlm#Z# G dd de#j$Z%G dd de#j$Z&G dd dej'Z(G dd dej)Z*d	S )    )render)viewsetsstatus)actionapi_view)Response)swagger_auto_schema)openapi)HttpResponse)datetimeN)Workbook)transaction)OportunidadDeVenta)OportunidadDeVentaSerializerDeleteOportunidadSerializerCreateOportunidadSerializerEditOportunidadSerializerIncidenciaSerializer)oportunidad_de_venta_model)timezone)serializersc                   @   s$   e Zd ZejddZejddZdS )ChangeWorkflowSerializerT)requiredN)__name__
__module____qualname__r   IntegerFieldidcolumn_workflow_id r   r   7/var/www/html/crm_dreinet/oportunidad_de_venta/views.pyr      s    r   c                   @   sJ   e Zd ZejdddZejdddZejdddZejddgddd	Z	d
S )ExportSerializerFu   Fecha única (YYYY-MM-DD))r   	help_textzFecha desde (YYYY-MM-DD)zFecha hasta (YYYY-MM-DD)csvexcelz Tipo de archivo: 'csv' o 'excel')choicesdefaultr"   N)
r   r   r   r   	DateFieldfechadesdehastaChoiceFieldtipor   r   r   r    r!      s
    r!   c                   @   sp  e Zd Zeddeddideddgdd	d
d Zedeej	dej
ejej
ejddej
ejddej
ejdddddej	dej
ejej
ejdej
ejddddddeddgdd	ejdd Zededej	dej
ejej
ejdej
ejdej
ejejejdd ej
ejdd!ddideddgd"d	ejd#d$ Zed%eej	d&ej
ejej
ejdej
ejdd'ddej	d(ej
ejej
ejdej
ejddddej	d)ej
ejd*ej
ejdiddd+deddgd,d	d-d. Zed/ejd0ejd1ejdd2gdeddid3eddgd4d	d5d6 Zed7eej	d8ej
ejej
ejdej
ejdej
ejdd9ddej	d(ej
ejej
ejdej
ejddddej	d)ej
ejd*ej
ejdiddd+deddgd:d	d;d< Zed=ej
ejej
ejejd>d?d@ej
ejejdAdBd@ej
ejejdCdDd@ej
ejdEdFgdGdEdFdHdIdBdDdFdJdKej	dLej
ejddej	dMej
ejej
ejdej
ejdddddNdeddgdOd	dPdQ ZedRdej	dSej
ejej
ejejejdd ej
ejejejdd ej
ejddTddideddgdUd	dVdW ZdXS )YOportunidadDeVentaViewSetz.Lista todas las oportunidades de venta activas   Tmany)operation_description	responsesFgetlist_sales_opportunity)detailmethodsurl_pathc                 C   s0   t jjdddddd}t|dd}t|jS )NTdeleted_at__isnullempresausuario_responsableestado_oportunidadcolumn_workflowr/   )r   objectsfilterselect_relatedr   r   data)selfrequestoportunidades
serializerr   r   r    r4      s   
z0OportunidadDeVentaViewSet.list_sales_opportunityu   Crea una nueva oportunidad de venta. El campo estado_oportunidad_id debe ser un ID existente en la tabla de estados de oportunidad. Consulte el endpoint /api/estado_oportunidad_venta/listar/ para obtener los valores válidos.z Oportunidad creada correctamenteu   Mensaje de éxito)typedescriptionzID de la oportunidad creadazDatos de la oportunidad creadamensajer   datos)rF   
properties)rG   schemaz!Error en los datos proporcionados)rF   errordetalles)     )r1   request_bodyr2   postcreatec           	      C   s   t |jd}| std|jdtjdS |jdg }|j	t
 t
 d}|raddlm} |D ]/}z|jj||d	 |d
d|d d W q1 ty` } ztd|  W Y d }~q1d }~ww t|j}|jrp|jj|d< nd |d< td|j|dtjdS )NrA      Datos inválidosrM   r   	productos)fecha_creacionfecha_ultima_actualizacionr   OportunidadProductoproducto_idcantidad   precio_unitariooportunidadr]   r^   r`   zError creating product item: workflow_idz)Oportunidad de venta creada correctamenterH   )r   rA   is_validr   errorsr   HTTP_400_BAD_REQUESTvalidated_datapopsaver   nowproducto.modelsr\   r>   rT   r3   	Exceptionprintr   r=   r   HTTP_201_CREATED)	rB   rC   rE   productos_datarb   r\   itemerA   r   r   r    create_opportunity.   sH   



z,OportunidadDeVentaViewSet.create_opportunityu   Edita una oportunidad de venta existente mediante método POST. Permite actualizar cualquier campo excepto la fecha de creación. Solo es necesario incluir el ID y los campos que se desean modificar.z%Oportunidad actualizada correctamente)rF   itemsrI   r   campos_actualizadosrJ   updatec              	   C   s  t |jd}| std|jdtjdS z|jd}|jdd }t	j
j|dd}g }|j D ]+\}}|d	krH|j|krG||_|d
 q2t||d }	|	|kr]t||| || q2t |_|j|dg d |d urddlm}
 |
j
j|d  |D ]}d|v r|
j
j||d |dd|ddd q|d t|j}|jr|jjnd |d	< td|||dtjdW S  t	jy   tdditjd Y S w )NrU   rV   rM   rW   r   rX   Tr   r9   rc   r   rZ   )update_fieldsr   r[   )rb   r]   r^   r_   r`   ra   z.Oportunidad de venta actualizada correctamentert   rN   4La oportunidad de venta no existe o ya fue eliminada) r   rA   rd   r   re   r   rf   rg   rh   r   r>   r3   rs   r   appendgetattrsetattrr   rj   rZ   ri   rk   r\   r?   deleterT   r   r=   r   HTTP_200_OKDoesNotExistHTTP_404_NOT_FOUND)rB   rC   rE   id_oportunidadro   rb   ru   campovalor	old_valuer\   rp   rA   r   r   r    update_opportunityw   sj   









z,OportunidadDeVentaViewSet.update_opportunityu7   Elimina lógicamente una oportunidad de venta por su IDz#Oportunidad eliminada correctamenterI   r   rV   zOportunidad no encontradarN   )r.   rQ   i  r}   c                 C   s   t |jd}| std|jdtjdS z!|jd }tj	j
|dd}t |_|  td|d	tjdW S  tjyI   td
ditjd Y S w )NrU   rV   rM   rW   r   Trw   z,Oportunidad de venta eliminada correctamenter   rN   ry   )r   rA   rd   r   re   r   rf   rg   r   r>   r3   r   rj   
deleted_atri   r~   r   r   )rB   rC   rE   r   rb   r   r   r    delete_opportunity   s   %

z,OportunidadDeVentaViewSet.delete_opportunityzULista todas las oportunidades de venta filtradas por workflow_id (column_workflow_id)rc   z$ID del workflow (column_workflow_id))rG   rF   r   )r1   manual_parametersr2   by_workflowc                 C   sZ   |j d}|stdditjdS tjj|ddddd	d
}t	|dd}t|j
tjdS )Nrc   rN   zworkflow_id es requeridorW   T)r   r9   r:   r;   r<   r=   r/   )query_paramsr3   r   r   rf   r   r>   r?   r@   r   rA   r~   )rB   rC   rc   rD   rE   r   r   r    list_by_workflow   s    z*OportunidadDeVentaViewSet.list_by_workflowzNCambia el workflow (column_workflow_id) de una oportunidad de venta por su ID."Workflow actualizado correctamenterI   r   r   change_workflowc                 C   s   t |jd}| std|jdtjdS z#tjj	|j
d dd}|j
d |_|  td	|j|jd
tjdW S  tjyK   tdditjd Y S w )NrU   rV   rM   rW   r   Trw   r   r   r   rN   u*   La oportunidad no existe o está eliminada)r   rA   rd   r   re   r   rf   r   r>   r3   rg   r   ri   r   r~   r   r   )rB   rC   rE   rb   r   r   r    r     s"   &z)OportunidadDeVentaViewSet.change_workflowur   Exporta oportunidades de venta filtradas por fecha. Envía los parámetros como JSON en el cuerpo de la petición.u.   Fecha única (YYYY-MM-DD). Ejemplo: 2025-10-20z
2025-10-20)rF   formatrG   examplez-Fecha desde (YYYY-MM-DD). Ejemplo: 2025-10-01z
2025-10-01z-Fecha hasta (YYYY-MM-DD). Ejemplo: 2025-10-31z
2025-10-31r#   r$   u   Tipo de archivo de exportación)rF   enumrG   r&   r   )r(   r)   r*   r,   )r)   r*   r,   )rF   rK   r   z-Archivo exportado correctamente (CSV o Excel)u7   Error en los parámetros o tipo de archivo no soportado)r.   rQ   exportc                 C   s0  t |jd}| std|jdtjdS |j}|d}|d}|d}|dd		 }t
jjd
d}|r?|j|d}n|rL|rL|j||gd}n|rU|j|d}n|r]|j|d}|dddd}t|d
d}	|	j}
|
D ]}|dd  qp|d	krt }tj||
r|
d  ng d}|  |
D ]}|| qd|p|r|rt|d t| nd d}t| dd}d| d|d < |S |d!krt }|j}|
r|t|
d   |
D ]}|t|  qd|p|r|rt|d t| nd d"}td#d}d| d|d < || |S d S )$NrU   rV   rM   rW   r(   r)   r*   r,   r#   Tr8   )fecha_creacion__date)fecha_creacion__date__range)fecha_creacion__date__gte)fecha_creacion__date__lter:   r;   r<   r=   r/   r   r   )
fieldnamesoportunidades__todasz.csvztext/csv)content_typezattachment; filename=""zContent-Dispositionr$   z.xlsxzAapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet) r!   rA   rd   r   re   r   rf   rg   r3   lowerr   r>   r?   r@   r   rh   ioStringIOr#   
DictWriterkeyswriteheaderwriterowstrr
   getvaluer   activerz   listvaluesri   )rB   rC   rE   rg   r(   r)   r*   r,   querysetserializer_datarA   rowoutputwriterfilenameresponsewbwsr   r   r    r   U  sh   8



,
,
z OportunidadDeVentaViewSet.exportu_   Obtiene notificaciones de oportunidades vencidas o por vencer (7 días) para el usuario actual.zListado de notificacionesexpiredexpiring_sooncountnotificationsc              
   C   s  d }|j r|j jrt|j d|j }|stdditjdS t  }|tj	dd }d}t|ddr5d	}nt
|d
rA|jdkrAd	}tjjd	ddjdddd}|sZ|j|jd}ddlm} |||d|||gdB }g }g }	|D ]#}
|
j|
j|
j|
jr|
jjndd}|
j|k r|| qu|	| quz9ddlm} ddlm} |s|	r|jj|d|jtdt| dt|	 ddd |D d d |	D d!d" W n ty } zt d#|  W Y d }~nd }~ww t||	t|t|	 d$S )%N_userrN   zUsuario no autenticadorW      )daysFis_superuserTrol_usuario_idr_   )r9   estado_oportunidad__es_final   )estado_oportunidad_idr:   r;   )usuario_responsable_idr   )Q)fecha_estimada_cierre__lt)fecha_estimada_cierre__rangezSin Empresa)r   nombrefecha_estimada_cierreempresa_nombre)AuditLog)ContentTypeNOTIFICATIONzNotifications checked: z
 expired, z expiring soonc                 S      g | ]}|d  qS r   r   .0xr   r   r    
<listcomp>       z?OportunidadDeVentaViewSet.get_notifications.<locals>.<listcomp>c                 S   r   r   r   r   r   r   r    r   !  r   )expired_idsexpiring_soon_ids)userr   r   rG   
data_afterzError auditing notifications: r   )!r   is_authenticatedr{   r   r   HTTP_401_UNAUTHORIZEDr   rj   date	timedeltahasattrr   r   r>   r?   excluder@   r   django.db.modelsr   r   r   r:   rz   audit.modelsr   "django.contrib.contenttypes.modelsr   rT   get_for_modellenrl   rm   )rB   rC   r   today
limit_dateis_adminr   r   r   r   oprA   r   r   rq   r   r   r    get_notifications  s~   


z+OportunidadDeVentaViewSet.get_notificationsN) r   r   r   r   r   r   r4   r   r	   r   SchemaTYPE_OBJECTTYPE_STRINGTYPE_INTEGERr   atomicrr   r   
TYPE_ARRAYItemsr   r   r   	ParameterIN_QUERYr   r   r   FORMAT_DATE	TYPE_FILEr   r   r   r   r   r    r-      s   
	,?

#


$$6Br-   c                       sH   e Zd ZdZddlmZ ej dZ	e
Z fddZdd Z  ZS )	IncidenciaViewSetzV
    ViewSet para manejar incidencias (usadas como comentarios) de oportunidades.
    r   )
Incidenciaz-fecha_creacionc                    s,   t   }| jjd}|r|j|d}|S )z4
        Permite filtrar por oportunidad_id
        oportunidad_id)r   )superget_querysetrC   r   r3   r?   )rB   qsr   	__class__r   r    r   7  s
   
zIncidenciaViewSet.get_querysetc                 C   s:   d }| j jr| j jjrt| j jd| j j}|j|d d S )Nr   )usuario)rC   r   r   r{   ri   )rB   rE   r   r   r   r    perform_createA  s   z IncidenciaViewSet.perform_create)r   r   r   __doc__Models.incidencia_modelr   r>   allorder_byr   r   serializer_classr   r   __classcell__r   r   r   r    r   /  s    
r   )+django.shortcutsr   rest_frameworkr   r   rest_framework.decoratorsr   r   rest_framework.responser   drf_yasg.utilsr   drf_yasgr	   django.httpr
   r   r#   r   openpyxlr   	django.dbr   !Models.oportunidad_de_venta_modelr    oportunidad_de_venta.serializersr   r   r   r   r   Modelsr   django.utilsr   r   
Serializerr   r!   ViewSetr-   ModelViewSetr   r   r   r   r    <module>   s2        