/* 
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Other/SQLTemplate.sql to edit this template
 */
/**
 * Author:  pc one
 * Created: 26 may 2023
 */

CREATE TABLE compra_lote_cancelada(
    id CHAR(36) NOT NULL,
    id_lote CHAR(36) NOT NULL,
    id_persona CHAR(36) NOT NULL,
    comentario TEXT,
    created_by CHAR(36),
    created_on DATETIME,
    last_update_by CHAR(36),
    last_update_on DATETIME,
    PRIMARY KEY(id)
);

CREATE TABLE `mensajes_predefinidos` (
`id` char(36) NOT NULL,
`title` text,
`message_type` enum('OTRO','PAGO_RETARDO','PAGO_CINCO_DIAS','PAGO_HOY','PAGO_GENERAL') NOT NULL DEFAULT 'OTRO',
`message` text,
`active` tinyint DEFAULT '1',
`created_on` date NOT NULL,
`created_by` char(36) NOT NULL,
`last_updated_on` date,
`last_updated_by` char(36),
PRIMARY KEY (`id`)
);
CREATE TABLE `mensajes_enviados` (
`id` char(36) NOT NULL,
`id_mensaje_predefinido` char(36) NOT NULL,
`id_abono_lote` char(36) NOT NULL,
`mensaje_enviado` text,
`active` tinyint DEFAULT '1',
`created_on` date NOT NULL,
`created_by` char(36) NOT NULL,
`last_updated_on` date,
`last_updated_by` char(36),
PRIMARY KEY (`id`),
KEY `closing_day_details_id_mensaje_predefinido_fk` (`id_mensaje_predefinido`),
KEY `closing_day_details_id_abono_lote_fk` (`id_abono_lote`),
CONSTRAINT `closing_day_details_id_mensaje_predefinido_fk` FOREIGN KEY (`id_mensaje_predefinido`) REFERENCES `mensajes_predefinidos` (`id`) ON UPDATE CASCADE,
CONSTRAINT `closing_day_details_id_abono_lote_fk` FOREIGN KEY (`id_abono_lote`) REFERENCES `abono_lote` (`id`) ON UPDATE CASCADE
);

CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`@`localhost`
SQL SECURITY DEFINER
VIEW `pre_cobranza_view` AS
SELECT
`ab`.`id` AS `id_abono_lote`,
`p`.`id` AS `id_person`,
`lo`.`folio` AS `folio`,
`lo`.`total_a_pagar` AS `total_a_pagar`,
`lo`.`periodo_pago` AS `periodo_pago`,
`lo`.`plazo_meses` AS `plazo_meses`,
`ab`.`pago_estatus` AS `pago_estatus`,
`ab`.`fecha_a_pagar` AS `fecha_a_pagar`,
(CASE
WHEN ((TO_DAYS(`ab`.`fecha_a_pagar`) - TO_DAYS(CURDATE())) < 0) THEN -(1)
WHEN ((TO_DAYS(`ab`.`fecha_a_pagar`) - TO_DAYS(CURDATE())) = 0) THEN 0
WHEN ((TO_DAYS(`ab`.`fecha_a_pagar`) - TO_DAYS(CURDATE())) BETWEEN 1 AND 5) THEN 5
ELSE (TO_DAYS(`ab`.`fecha_a_pagar`) - TO_DAYS(CURDATE()))
END) AS `diferencia_dias`,
`ab`.`pago` AS `pago`,
CONCAT(`p`.`first_name`,
' ',
`p`.`second_name`,
' ',
`p`.`last_name`,
' ',
`p`.`middle_name`) AS `complete_name`,
`cn`.`contact_number` AS `contact_number`
FROM
(((`abono_lote` `ab`
JOIN `lote` `lo` ON ((`ab`.`id_lote` = `lo`.`id`)))
JOIN `contact_number` `cn` ON ((`ab`.`id_cliente` = `cn`.`person_id`)))
JOIN `person` `p` ON ((`cn`.`person_id` = `p`.`id`)))
WHERE
((`ab`.`estatus_activo` = 'ENABLED')
AND (`cn`.`number_type` = 'MOBILE'))
ORDER BY `ab`.`fecha_a_pagar`;
