Consutoría, Soporte y Desarrollo de software en Opera PMS Oracle, Java Oracle y AWS Amazon Cloud
|
OPERA Property Management Suite (Opera PMS) es un sistema de gestión de Hoteles para operaciones, distribución y asignación de habitaciones basado en tecnologías en la nube. La plataforma, segura, escalable y habilitada para dispositivos móviles, ofrece las capacidades integrales que los hoteles necesitan para brindar excelentes experiencias a los huéspedes, mejorar la eficiencia operativa y mejorar la productividad de los empleados. La visibilidad en tiempo real es fundamental para el éxito en la industria de la hospitalidad y OPERA (Oracle Hospitality) es líder del mercado en software hotelero para boutiques independientes, hoteles independientes, cadenas hoteleras y grupos de hoteles con múltiples propiedades. El sistema de administración de propiedades de Opera puede manejar todo, desde tareas de recepción como cancelaciones, bloqueo de habitaciones y administración de habitaciones desde Housekeeping hasta elementos esenciales del servicio al huésped, como perfiles de huéspedes e incluso funciones administrativas como la gestión de ingresos.
operapmsbi.COM Cloud habilita de forma simplificada y eficiente información para dispositivos móviles haciendo que la información sea accesible para todos, en cualquier momento, en cualquier lugar y desde cualquier dispositivo, con una arquitectura abierta, servicios de integración integrados y una API abierta para acelerar la innovación.
operapmsbi.COM satisface las necesidades de todos los hoteles y redefine la experiencia de gestión del Hotel.
Realizamos consultoría y desarrollo de aplicaciones web con tecnología Java & AWS Amazon Cloud para la consulta y análisis de información de las operaciones del Hotel en tiempo real.
Nuestras soluciones cumplen con todas las especificaciones y funcionalidades únicas requeridas para cada uno de nuestros clientes de la industria hotelera,
proporcionando consultas en tiempo real desde tu smartphone de la información de su PMS, dándole agilidad en la toma de decisiones sobre las operación del Hotel.
Para mayor información escribir al whatsapp:https://wa.link/cdgbzx
En el mercado competitivo actual, el éxito a largo plazo de su hotel depende de qué tan bien tome decisiones comerciales informadas en el momento adecuado.
Para descubrir tendencias y oportunidades, debe analizar constantemente los informes de pérdidas y ganancias, los informes de análisis empresarial, los informes de análisis de mercado y muchos más.
El reporte de History And Forecast le ofrece claridad sobre los niveles de ocupación anteriores junto con el nivel de ocupación futuro que puede presenciar en el Hotel.
Puede ver la ocupación total de cualquier fecha (Occupancy), las habitaciones de llegada (arrival rooms), las habitaciones de salida (departure rooms), el porcentaje de ocupación (occupancy percentage), los ingresos de la habitación (room Revenue), RevPAR, ADR, etc.
En el siguiente enlace se muestra el reporte History And Forecast en tiempo real con datos de Opera PMS Training:
History & Forecast Report from operapmsbi.com
Una comunicación adecuada del estado de la habitación ayuda a la adecuada administración y la distribución de las habitaciones del Hotel.
La relación, tradicionalmente conflictiva, entre los departamentos de recepción y de housekeeping es frecuente y depende totalmente de la calidad de la comunicación entre ambos departamentos, con las actualizaciones de estado de la habitación en tiempo real y la comunicación instantánea permite la reducción de los conflictos y la gestión de los costes es más eficiente.
Cuando un huésped abandona el hotel, el servicio de housekeeping puede revisar el estado de la habitación a través de un smartphone, lo que elimina la necesidad de esperar o comprobar en el PMS si pueden preparar la habitación para el siguiente huésped.
Es importante entender las brechas de información y la solución mediante sistemas de gestión hotelera en tiempo real que permiten integraciones de software útiles.
Una comunicación adecuada del estado de la habitación ayuda a la adecuada administración y la distribución de las habitaciones del Hotel.
La relación, tradicionalmente conflictiva, entre los departamentos de recepción y de housekeeping es frecuente y depende totalmente de la calidad de la comunicación entre ambos departamentos, con las actualizaciones de estado de la habitación en tiempo real y la comunicación instantánea permite la reducción de los conflictos y la gestión de los costes es más eficiente.
Cuando un huésped abandona el hotel, el servicio de housekeeping puede revisar el estado de la habitación a través de un smartphone, lo que elimina la necesidad de esperar o comprobar en el PMS si pueden preparar la habitación para el siguiente huésped.
Es importante entender las brechas de información y la solución mediante sistemas de gestión hotelera en tiempo real que permiten integraciones de software útiles.
El Costo de cada solución es de 800.00 USD. (pago único por solución).
La solución incluye un proceso automático que recupera de manera periódica los datos necesarios del PMS y HMS del Hotel, envía estos datos a una base de datos en la cloud de AWS de Amazon, base de datos cuyo uso es exclusivo para el cliente o propietario del Hotel, estos datos son consultados mediante un aplicativo web por el cliente de la solución.
La solución se puede desplegar en servidores web con Apache Tomcat/Java sobre base de datos SQL Server u Oracle en AWS Amazon, Windows Azure o sus servidores locales.
Índice de contenidos.
Emisión de comprobantes Facturas y Boletas desde Opera PMS
Proceso de Cierre de Día o Auditoría con Opera PMS
Configuración de Rate Strategy en Opera PMS
Notas de Crédito mediante Credit Bill en Opera PMS
Rate Strategy Configuración y demostración en Opera PMS
Creación de reportes con Opera PMS y Oracle Reports Developer.
Diccionario de Datos Opera PMS - Oracle
Diseño y creación de reporte de Pagos Diarios desde Opera PMS
Creación de reporte ForeCast and History en Opera PMS
Creación Reporte Trial Balance Details By Transactions en Opera PMS
Room Status y Housekeeping Status en Opera PMS, consulta web Online desde Smartphone
Cuentas Contables asignadas a Transaction Codes en Opera PMS
Cambiar Tipo de Habitación Room Type en Opera PMS
Querys SQL Oracle para gestión de ventas en Opera PMS
Lista de habitaciones bloqueadas
Lista de Habitaciones reservadas
Ingresos por empresa y mercado (Market)
Forecast de habitaciones por dia
Forecast por Marked Code Mensual
Producción por ejecutivo de ventas
Producción por ejecutivo de venta
Producción por ejecutivo de ventas detallado.
Producción por ejecutivo de ventas agrupado
Forecast agrupado por fecha de reserva
Producción por empresa y por tipo de habitación.
Producción mensual por Market y por Ejecutivo
Producción por ejecutivo, habitación y empresa.
Forecast por Market Code Mensual Detallado
Activity Search Notas por ejecutivo y Huésped
Detalle de facturas asociados a Transaction Codes por Factura
Querys SQL Oracle para Housekeeping en Opera PMS
Listado de habitaciones de la propiedad por Ocupación
Listado de los pisos de la propiedad por Estado
Listado de habitaciones de la propiedad por Estado
Listado de habitaciones de la propiedad por Discrepancia
Listado de habitaciones de la propiedad por Fecha/Hora de Llegada
Creación de Kardex físico valorado en Material Controls Micros Fidelio
Permisos y grupo de permisos en Opera PMS
Crear reportes utilizando las Vistas de Ópera Simple Report Writer
Reporte de Ventas generadas desde Micros 9700
Reporte de Listado de huéspedes en casa
Para poder emitir una Boleta debemos verificar que el cliente posea el campo “Tax Type” como BOLETA en el profile del Cliente.
ingrese al menú “Front Desk” opción “In House Guests“ para listar todos los clientes que están hospedados en el Hotel.
En la pantalla “In House Guest” seleccione al cliente al cual desea verificar el Tax Type de su profile y seleccione el boton de opcion “Profile”.
En la pantalla “Individual Profile” se muestra los datos más importantes del cliente. en esta pantalla seleccione el botón de opción “More Fields”.
En la pantalla “More Fields” asegúrese que el campo Tax Type este con la opción BOLETA y seleccione el botón de opción OK.
Al retornar a la pantalla “Individual Profile” seleccione el botón de opción “Save” para guardar los cambios realizados, luego click en el botón Ok y Close.
Con esto nos aseguramos que el cliente posee el Tax Type como BOLETA, lo que nos permitirá generar el comprobante de pago de tipo Boleta.
Ingrese al menú “Cashiering” opción “Billing” para mostrar los clientes que están hospedados a los cuales es posible generarlos un comprobante de pago por algún concepto de estadía, consumo o por servicios.
previamente se mostrará la pantalla de Login para solicitar las credenciales de acceso del cajero.
En la pantalla In “House Guest Search”, filtrar los registros “Due Outs” que son los registros de clientes pendientes de salida, clientes que se encuentran hospedados y consumen los servicios que el Hotel ofrece al cual se les debe generar un comprobante de pago, en este caso una Boleta.
Seleccione la opción “Due Outs” y haga click en el botón de opción “Search”
En la pantalla “House Guest Search” seleccione el registro del cliente al cual se le desea generar la boleta de pago para luego hacer Click en el botón “Select”, se mostrará la pantalla de “Billing”.
En la pantalla de “Billing” se muestran los datos de la cuenta del cliente. es importante indicar que en esta pantalla puede tener hasta 8 Windows, ventanas que nos permitirán clasificar las cuentas del cliente y generar comprobantes por cada Window.
Observemos que el Window (02) posee una cuenta de cuenta de 140.80 USD que aún no está pagada y que el Window (03) posee una cuenta de 32.00 USD que se encuentra pagada mediante el medio de pago VISA.
Seleccionamos el Windows (02) y hacemos click en el boton de opcion “Check Out”, se mostrará la pantalla “Payment”.
En la pantalla “Payment”, seleccione la opción “Payment Code” a “Cash Dollars”, la opción Currency a USD, en el campo Amount indique el monto 140.80 y en el campo Reference indique alguna descripción de la cuenta, luego haga click en el boton de opcion Post con esto el pago se carga al sistema y se cierra la cuenta.
En la siguiente pantalla PoPup indique No, para enviar el comprobante al programa de emisor de documentos fiscales digitales de su País (o Facturación Electrónica de la Administración Tributaria Central)
Este proceso de enviar los datos del comprobante a la administración tributaria central de su país, imprimir el comprobante con los datos del número de comprobante, código QR.
Al concluir con el proceso se muestra en el Window de la cuenta un registro por -140.80 (en negativo) indicador del cierre de la cuenta.
El cierre de día permite actualizar la fecha de negocio (Business Date) a la fecha de operación actual, además el proceso de cierre es muy importante para la generación de reportes de gestión del hotel.
Ingrese al menú de opción “End of Day” y seleccionamos el menú “Night Audit”
Se mostrará el formulario “End of Day Login” y seleccionamos el “Business Date” que deseamos cerrar.
Se mostrará la pantalla “End of Day Routine” que validará la conclusión de los procesos que permitan el cierre adecuado del día.
Realice click en el botón OK y luego en click en el botón Start.
Opera te muestra las llegadas o reservas pendientes de Check In aún no registradas, los cuales se deben registrar, esto también nos alerta sobre el estado de las llegadas pendientes.
Para continuar con el cierre del día, es importante realizar el check in de todas las llegadas de la fecha que se está cerrando a fin de continuar con el proceso.
Luego de realizar la asignación de Habitación y la Tarifa, hacer click en el boton de opcion Check In.
Si el Check In se realiza satisfactoriamente el registro debe salir del listado de pendientes de Check In. Continuar con este proceso hasta dejar la bandeja de pendientes de registro de Check In sin registros.
Durante la validación de las registros pendientes de Check Out se muestra la pantalla “Huéspedes En Casa”, a los cuales se les debe generar el Check Out correspondientes antes de continuar con el proceso de cierre.
Antes de proceder con los Check out es importante realizar la configuración de los printtask necesarios para la impresión de los CheckOut.
Loguearse con el rol del supervisor, seleccionar la opción de Configuration, en la pantalla de Configuración, seleccione la opción de menu Workstation.
Selecciona el WorkStatons correspondiente a pa pc actual de trabajo, que generalmente está resaltado de color azul.
Haga click en el boton de opcion Print Tasks para mostrar la pantalla Print Task
Dentro de esta pantalla haga click en el botón New.
Si en la pantalla no se muestra el Printer Task, se debe registrar en la pantalla Printers, seleccione el menú de opción Printers, se mostrará la pantalla, y hacer click en New
Crear el print task requerido, luego en el WorkStation agregar el PrintTask necesario.
Opera iniciará a cerrar el día y completar todas las operaciones pendientes para un cierre adecuado.
El proceso de cierre, también imprime los reportes pendientes de las operaciones del día.
Al concluir el proceso de cierre el dia, se pide la impresión del reporte final
La estrategia de tarifas nos permite controlar las restricciones de precios (descuentos y sobreprecios) que deseamos aplicar a las reservas de habitaciones de acuerdo a la ocupabilidad o disponibilidad de las habitaciones del hotel.
Por ejemplo si las habitaciones de una determinada categoría se venden con un descuentos hasta que superan el 10% de ocupabilidad, superado este porcentaje de ocupabilidad se retira el descuento y se vende el 90% restante sin ningún descuento.
Esta restricción deseamos que se aplique para los checkin desde 01/05/2019 hasta 31/05/2019, el control de las restricciones deseamos hacerlos durante el mes de marzo y el mes de abril es decir desde el 01/03/2019 hasta el 30/04/2019.
En Opera ingresamos al módulo de configuración.
Luego seleccionamos la opción Rate Strategy
En la pantalla Rate Strategy definiremos la estrategia de tarifas de acuerdo a las condiciones establecidas.
Siempre se debe definir dos registros de estrategias la estrategia de tarifas y su contraparte. es decir se define las tarifas para reservas superiores a un 10% de ocupabilidad y el registro de estrategias de tarifas para reservas inferiores al 10% de ocupabilidad.
Estrategia de tarifas para un codigo de precios específico llamado CRESP.
Para los check in o llegadas desde el 01 de mayo del 2019 al 31 de mayo del 2019
cuyas ventas o reservas se realicen desde el 01 de marzo al 30 de abril, además definimos su contraparte de la restricción
por lo tanto en la pantalla de Rate Strategy se debe tener 2 registros por restricción de tarifas.
Luego probamos la estrategia de tarifas definidas al momento de hacer las reservas.
Realizaremos notas de crédito mediante CREDIT BILL, ingrese al menú de Cashiering, opción Cashier Functions
Se mostrará el formulario de Cashier Functions
Seleccione la opción de Folio History se mostrará el formulario Flio History
** Considere que solo se puede emitir Notas de Crédito mediante CREDIT BILL a comprobantes que hayan sido emitidos con un día de antelación, de lo contrario el Opera deshabilita el boton de opcion Credit Bill, por ejemplo al dia de hoy 12 de marzo solo se permite emitir las notas de crédito mediante Credit Bill de comprobantes emitidos hasta el 11 de marzo.
** Otra consideración a tener en cuenta es que la emisión de notas de crédito debe corresponder a la categoría de serie del comprobante de pago, es decir si la categoría de serie es F010, se debe emitir notas de crédito con la serie F010. si la categoría de serie es B011 se debe emitir notas de crédito con la serie B011 en esa correlación. si esta correlación no se da se corre el riesgo que la administración tributaria central rechace la nota de crédito emitida.
** Para que esta correlación se de es muy importante que al momento de emitir notas de crédito se deba cambiar el campo Tax Type del Profile del Cliente.
Por ejemplo para la emisión de la notas de crédito para el comprobante FACTURA del cliente Liu, Fang
Ingrese al Menú Reservations opción Profiles, en la pantalla de Profile Search busque y seleccione Profile del Cliente.
Click en el botón de opción Edit para mostrar el formulario Individual Profile con los datos del cliente,
Seleccione el botón de opción More Fields para visualizar las opciones Tax Type
Para generar adecuadamente la nota de crédito de la FACTURA es importante cambiar el Tax Type del Profile del Cliente a FACTURA.
Luego de cambiar el campo Tax Type, procedemos a generar el Credit Bill de la factura desde la pantalla Folio History.
se nos pedirá las credenciales del cajero
debe indicar los valores de Marked Code y Source Code para luego hacer click en el boton de opcion Post.
Realizamos el posting de la nota de crédito por el mismo valor pero en negativo.
Considere que para la realización del CREDIT BILL, debe usar la misma market code y la misma source que utilizó para la hacer la reserva.
En esta guía se configura las estrategias de precios y se hace una demostración de la aplicación de sus restricciones.
1. PERFILES DE USUARIO
Considere los siguientes permisos para los perfiles de recepción y reservas:
Perfil Recepción
Permisos para los perfiles cuyos usuarios deben respetar las restricciones de las estrategias de precios. Esto es aplicable para los usuarios cajeros o recepcionistas.
No debe poseer los siguientes permisos:
RESERVATIONS \ OVERRIDE RATECODE
BLOCKS \ OVERRIDE BLOCK RATE RESTRICTIONS
Debe poseer los siguientes permisos:
RESERVATION \ RATE CODE CHANGE
Perfil Reservas
Permisos para los perfiles cuyos usuarios pueden autorizar la ruptura de las restricciones de las estrategias de precios. Esto es aplicable para los usuarios supervisores, cajeros senior o personal de reservas senior.
Debe poseer los siguientes permisos:
RESERVATION \ OVERRIDE RATECODE
BLOCKS \ OVERRIDE BLOCK RATE RESTRICTIONS
RESERVATION \ RATE CODE CHANGE
2. PARÁMETROS DE SISTEMA
Debe indicar los siguientes parámetros en la pantalla “Application Settings” con los valores “Y“.
Parámetro
Valor
RATES \ SET RATE CATEGORY RESTRICTIONS
Y
RATES \ SET RATE CODE RESTRICTIONS
Y
3. DEFINICIÓN DE ESTRATEGIA DE PRECIOS
Para realizar la configuración de la estrategias de precios, ingrese al menú principal “Configuración” se mostrará la pantalla “Configuration”, en esta pantalla ingrese a la opción de menú “Rate Management”, opcion “Rate Strategy”, se mostrará la pantalla “Rate Strategy”.
Realice click en el botón “New”.
Defina la estrategia de precios directa (<10% de ocupabilidad ABIERTO)
Además defina la estrategia de precios inversa (>10% de ocupabilidad CERRADO)
Las fechas del campo “Restriction Dates” corresponden a fechas de “Arrival” de la reserva en la cual se aplican las estrategias de precios.
Las fechas del campo “Control Dates” corresponden a las fechas en la que se registra la reserva.
4. NIVEL DE OCUPABILIDAD Y FORECAST PROCESSOR
Ingrese a la pantalla de nivel de ocupabilidad usando la combinación de teclas Shift + F1 y observemos que en la fecha 02 de Mayo no se tiene habitaciones reservadas.
La adecuada ejecución de la estrategia de precios considera el nivel de ocupabilidad para aplicar o no las restricciones de precios. Este nivel de ocupabilidad necesita que las habitaciones reservadas estén deducidas (Deduct) del inventario de habitaciones.
Para activar las deducciones del inventario de habitaciones es importante que el procesador del forecast esté en ejecución.
Para activarlo ingrese al menú principal “Utilities”, se mostrará la pantalla “Utilities”. En esta pantalla ingrese al menú “Processors” submenu “Forecast Processor”, se mostrará la pantalla “Forecast Processor Status”
´
En la pantalla “Forecast Processor Status” se debe mostrar el proceso en ejecución “Running”, de lo contrario haga click en el botón “Start”.
5. CONFIGURACIÓN DEL RATE CODE
Debemos verificar la configuración del “Rate Code”, ingrese al menú “Rate Management”, opción de menú “Rate Classifications”, opción ”Rate Codes”. Seleccione el “Rate Code”,involucrado en el “Rate Strategy” y haga clic en el botón “Edit”.
En el formulario “Rate Header” asegúrese que el campo “Room Types” posee el tipo de habitación ST al que estamos estableciendo la estrategia de precios, además verificar que el rango de fechas “Begin Sell Date” y “End Sell Date” sea un rango de fechas acorde a las fechas de ejecución y fechas de control de la estrategia de precios.
En el formulario “Rate Detail”, seleccione el registro correspondiente al “Room Types” ST considerado en la estrategia de precios, asegúrese que el rango de fechas “Start Date” y “End Date” esté en concordancia con las fechas de ejecución y las fechas de control definidas en la estrategias de precios.
Dejamos en blanco los registros del formulario “Negotiated”.
Dejamos en blanco los campos del formulario “More”.
6. CONFIGURACIÓN DEL RESERVATION TYPES
Debemos verificar los tipos de reservación “Reservation Types” y tener en cuenta aquellos tipos de reserva que Deducen del inventario físico de habitaciones, es decir que hacen que una reserva esté confirmada y no se pueda cancelar.
Esto es muy importante debido a que el Rate Strategy solo contabiliza las habitaciones reservadas y deducidas del inventario de habitaciones para verificar el nivel de ocupabilidad.
En la pantalla “Reservation Type” debemos tener al menos un registro como tipo de reserva “Deduct”.
7. REALIZACIÓN DE RESERVAS
Luego de la adecuada verificación de la configuración de los parámetros preliminares, ingresamos al menú de opción “Reservations”, seleccionamos el botón de opción “New Reservation”
En la pantalla “Profile Search”, hacemos la búsqueda de un determinado cliente.
En la pantalla “Reservation” la fecha del campo “Arrival” debe estar dentro del rango de ejecución de la estrategia de precios, seleccione el “Room Type” y el “Rate Code“ definido en la estrategia de precios.
**importante** debe seleccionar en el campo “Res Type” un tipo de reserva con Deduct.
Mientras las regla de restricción no llegue al límite de la estrategia de precios directa (<10% de ocupabilidad ABIERTO) las reservas se realizan de manera cotidiana.
Realizada la reserva en la pantalla de ocupabilidad (Shift +F1) en la fecha 02 de Mayo observamos que existe 01 habitación reservada y deducida del inventario (Deduct).
hacemos reservas con el perfil Cajero la cantidad de habitaciones necesarias hasta cubrir el 10% de ocupabilidad (límite de la estrategia de precios).
En la siguiente intención de reserva se mostrará la pantalla “Rate Query Details” con el precio en estado “Close”, lo que confirma que la estrategia de precios restringe la asignación del precio.
Si se desea proceder con la asignación se mostrará la pantalla de solicitud de permiso de asignación de precio. Esta autorización es proporcionada por un usuario Supervisor.
8. REPORTES ASOCIADOS AL RATE STRATEGY
Si se desea revisar el comportamiento de las estrategias de precios utilice los siguientes reportes:
Denominación de reporte
Archivo .rep
Restrictions Detail
raterest.rep
Reservation Rate Check
res_rate_check.rep
Reservations made On by Ratecode
paris_reservationsmadeonbyratecode.rep
Para crear reportes personalizados en Opera primero se debe crear la sentencia SQL que obtendrá los datos del reporte desde la base de datos Oracle del Opera, para luego diseñar el reporte en la herramienta Oracle Reports Developer y al final asignar una opción en el listado de reportes disponibles del Opera.
Es muy importante utilizar la versión adecuada del Oracle Reports Developer, por lo general esta herramienta lo instala el proveedor de Opera PMS.
Opera | Oracle Reports Developer
v 5.0 | v 10.1.2.0.2
v 5.5 | v 11.1.2.2.0
En este blog haremos un reporte que liste la relación de clientes hospedados.
Realizamos la sentencia SQL que extraiga los datos desde la base de datos Oracle del Opera.
SQL
SELECT a.room,trim(initcap(a.guest_first_name))||' '||trim(initcap(a.sname)) As Name,
trim(a.company_name)||' '||a.travel_agent_name As Company,
a.resv_status,a.arrival,a.departure
FROM reservation_general_view a
WHERE (a.resv_status='CHECKED IN' OR a.resv_status='DUE OUT')
ORDER BY a.room
Utilizaremos la vista “reservation_general_view”, esta vista posee el query necesario para extraer los datos de todas las reservas de los clientes, en sus diferentes estados:
CHECKED IN
PROSPECT
CANCELLED
NO SHOW
CHECKED OUT
RESERVED
Ejecutamos esta consulta en el entorno de desarrollo Oracle SQL Developer para validar que la consulta funciona adecuadamente
Ejecutamos el programa de diseño Oracle Reports Developer
Se mostrará el Builder
Conectamos a la base de datos el builder, para esto seleccionamos el menú “File” opción de menú “Connect...”,
Se mostrará el asistente de coneccion a la base de datos donde debe colocar el User, Password y el nombre de instancia de la base de datos Oracle. luego haga click en el boton de opcion “Connect” para conectarse a la base de datos.
Seleccione el Menú “File” opción de menú “New” / “Report…”, se mostrará el asistente “New Report”. seleccione la opción “Use the Report Wizard” y click en el boton de opcion OK
Se mostrará el asistente “Report Wizard!”, realice click en el botón de opción “Next >”
Mantenga la opción “Create both Web and Paper Layout” seleccionada por defecto y realice click en el botón “Next >”
Colocamos la denominación del reporte “Reporte huéspedes en propiedad” y hacemos click en el botón “Next >”.
Seleccionamos la opción “SQL Query” y hacemos click en la opción “Next >”.
En la pantalla Data Source definition colocamos el SQL Query que permite la extracción de datos de las reservas y hacemos click en la opción “Next >”.
Seleccionamos todos los campos del Query que se mostrarán en el reporte y hacemos click en la opción “Next >”.
En la pantalla del cálculo de campos totalizados no es necesario totalizar por un determinado campo, hacemos click en la opción “Next >”.
En esta pantalla mantenemos el ancho de las etiquetas y hacemos click en la opción “Next >”
Seleccionamos una plantilla de reporte y hacemos click en la opción “Next >”
Hacemos click en finish para luego previsualizar el diseño del reporte
Se mostrará el prediseño del reporte de la siguiente manera
Compilamos el reporte haciendo click en el menú “Compilar”, opción de menú “All..”
Click en Ok para confirmar el proceso de compilación.
Luego de compilar el reporte es importante exportar el archivo del reporte en formato .rep, formato que se podrá ser utilizado desde el Opera.
Se debe colocar los archivos del reporte .rep en la carpeta runtimes\ que se encuentra en la siguiente dirección: D:\MICROS\OPERA\production\runtimes\
Ingresamos al módulo de Configuración del Opera.
Seleccionamos las opciones de menú “Setup”, opción de Menú “Report Setup” opción “Reports”
Se mostrará la pantalla “Reports - Configuration”, hacer click en el botón “New”
En la pantalla “Reports - New” colocamos el nombre del reporte y seleccionamos un determinado “Report Group”.
Hacemos click en el botón de selecciones de lista asociado a “File Name”. en la pantalla “File List” buscamos el archivo de reporte .rep.
Nos aseguramos que el reporte custom_report_huespedes.rep se encuentre en la pantalla “Reports - Configuration”
Para mostrar el nuevo reporte seleccionamos el botón de opción “Miscelaneous”, opción “Reports”, se mostrará la pantalla “Reports”
En la pantalla “Reports” buscar el reporte “Custom Reporte Huespedes” y realiza click en el boton Ok
Se mostrará la pantalla “Report Parameters” y realice click en el botón “Preview”
Se mostrará el reporte personalizado
El tener acceso al diccionario de datos de un sistema de información es muy importante para iniciar todo proceso de desarrollo y mantenimiento del sistema de información.
Para poder acceder al diccionario de datos de Opera debe tener acceso a la base de datos Oracle desde el Oracle SQL Developer u otro entorno de desarrollo para Oracle.
Utilice la siguiente sentencia SQL para extraer el diccionario de datos de Opera:
select cc.table_name,tc.column_name,tc.nullable, tc.data_type ||
case
when tc.data_type = 'NUMBER' and tc.data_precision is not null
then '(' || tc.data_precision || ',' || tc.data_scale || ')'
when tc.data_type like '%CHAR%'
then '(' || tc.data_length || ')'
else null
end type
,cc.comments
from user_col_comments cc
join user_tab_columns tc
on (cc.column_name = tc.column_name and cc.table_name = tc.table_name)
order by cc.table_name ASC,tc.column_name ASC
Para los que no pudieran tener acceso a la base de datos Oracle del Opera dejo el Diccionario de Datos en formato Excel y la descripción de los campos en ingles y su traducción en español.
Debido a que Opera posee más de 4800 tablas en este blog se realizará la descripción de las tablas y los campos más importantes para un proceso de mantenimiento y desarrollo.
Diccionario de Datos Opera PMS – Oracle
Realizaremos un reporte que muestre el listado de pagos realizados por dia, pagos desde los diversos formas de pago; efectivo, tarjetas, etc. Este tipo de reportes nos permiten visualizar y validar los cobros que realizan los cajeros por dia de transacción.
El reporte va ha mostrar las siguientes columnas:
SELECT TO_CHAR(fi.TRX_DATE,'DD/MM/RR') TRX_FECHA, --Fecha de Transaccion
fi.TRX_CODE TRX_CODE, --Codigo de Transaccion
UPPER(trc.DESCRIPTION) TRX_DESCRIPTION, --Descripcion de Codigo de Transaccion
fi.RESV_NAME_ID NR_RESERVA, --Numero de Reserva
fi.ROOM NR_HAB, --Numero de Habitacion
NVL(n.SNAME||','||n.SFIRST,' ') HUESPED, --Nombre del Huesped
fi.fiscal_bill_no NR_DOCUMENTO, --Numero de Comprobante
DECODE(fi.bill_no,NULL,0,decode(fi.trx_no,fol.bill_payment_trx_no,fol.total_gross,0)) FACTURADO_USD, --Total Facturado en Dolares
fi.CURRENCY MONEDA, --Codigo de Moneda
RPAD(UPPER(au.APP_USER),5) USUARIO --Usuario
FROM
FINANCIAL_TRANSACTIONS fi
INNER JOIN FOLIO_TAX fol ON (fol.BILL_NO = fi.BILL_NO AND fol.NAME_ID = fi.NAME_ID)
INNER JOIN NAME n ON (n.NAME_ID = fi.NAME_ID)
INNER JOIN TRX$_CODES trc ON (trc.TRX_CODE = fi.TRX_CODE)
INNER JOIN APPLICATION$_USER au ON (au.APP_USER_ID = fi.INSERT_USER)
WHERE
---TO_CHAR(fol.BUSINESS_DATE,'DD/MM/RRRR') = '11/03/2019'
fol.BUSINESS_DATE = :P_BUSDATE
AND fi.BILL_NO IS NOT NULL
AND (fi.TRX_CODE BETWEEN 9000 AND 9999)
AND fi.DISPLAY_YN ='Y'
AND fi.RECPT_TYPE != 'CUX'
AND fi.PACKAGE_CREDIT IS NULL
AND fi.PACKAGE_DEBIT IS NULL
AND fi.PRICE_PER_UNIT <> 0
ORDER BY
TRX_FECHA, NR_DOCUMENTO, TRX_CODE, TRX_FECHA;
Para realizar este reporte se va usar las tablas relacionadas a transacciones financieras, folio de cliente y otras tablas asociadas:
FINANCIAL_TRANSACTIONS: Esta tabla almacena todas las transacciones relacionadas con el servicio de caja, transacciones para cada reserva (libro de huespedes, libro de depósitos, libro de cuentas por cobrar y libro de paquetes).
FOLIO_TAX: Esta tabla almacena un resumen de la información de ingresos por factura.
NAME: Esta tabla almacena la información de perfil de los huéspedes, compañías, agencias de viajes, fuentes y grupos.
TRX$_CODES: Esta tabla almacena todos los códigos de transacción del sistema, estas transacciones son los conceptos que se seleccionan al momento de hacer POST.
APPLICATION$_USER: Esta tabla almacena toda la información del usuario que opera el sistema.
Validamos la sentencia SQL ejecutando el query en el entorno de desarrollo “Oracle SQL Developer”
Ejecutamos el programa de diseño de reportes “Oracle Reports Builder” y creamos un nuevo reporte mediante el asistente “Report Wizard”.
En la pantalla “Report Style” indicamos el título del reporte y seleccionamos el formato “Group Left”, este formato nos permitirá crear agrupaciones en el reporte.
En la pantalla “Data Source Definition” del Report Wizard se presentará la confirmación para la creación del parámetro de reporte P_BUSDATE, este parámetro nos permitirá seleccionar desde Opera la fecha para cual deseamos se genere el reporte de pagos.
Hacemos click en el botón OK y continuamos con los valores por defectos de las demás pantallas del asistente.
En la pantalla “Agrupación de Campos” seleccionamos los campos que nos permitirán agrupar los registros del reporte y calcular los subtotales de estos grupos. En nuestro caso seleccionamos los campos TRX_CODE y TRX_DESCRIPTION lo que nos permitirá agrupar y totalizar por forma de pago.
En la pantalla “Select Fields to Display” seleccionamos todos los campos del Query que formarán parte del reporte.
En la pantalla “Calculate Totals” seleccione los campos que serán totalizados y la forma de totalización, en nuestro caso haremos una suma del monto facturado y un conteo de la cantidad de comprobantes.
Sum(FACTURADO_USD)
Count(NR_DOCUMENTO)
hacemos click en el botón “Next>” y continuamos con los valores por defectos de las demás pantallas del asistente.
Al culminar el asistente se mostrará el reporte con las agrupaciones y los campos totalizados:
La herramienta de diseño “Oracle Reports Builder” permite hacer el cambio del diseño original del reporte permitiendo un diseño mucho más estético del reporte.
Una vez compilado el reporte se debe exportar el archivo en formato .rep “custom_reporte_pagos.rep”, este formato permitirá que se pueda crear el reporte desde la pantalla de configuración “Reports - New” del Opera.
Desde la pantalla de “Configuración” seleccione la opción de menú “Setup”, Sub Menu “Report Setup” opción Reports.
En la pantalla “Reports - Configuration”, seleccione el botón de opción “New”
En la Pantalla “Reports - New” indicamos el nombre del reporte, este caso “Custom Reporte de Pagos”, en el campo “Report Group” seleccione la opción “Utilities” y dejamos las demás opciones como se muestra en la imagen.
En el campo “File Name” hacemos click en el botón de Listado, se mostrar la Pantalla “File List”, en esta pantalla seleccionamos el archivo .rep que hemos creado desde del “Oracle Reports Builder” en pasos anteriores.
Seleccionamos el reporte “custom_reporte_pagos.rep” y hacemos click en el botón “OK” para seleccionar este archivo.
En la pantalla “Reports New” seleccionamos el botón “Parameter”, se mostrará la pantalla “Parameters” para crear el parámetro “P_BUSDATE” que el reporte de pagos requiere.
En la pantalla “Parameters” coloque los siguientes datos del parametro P_BUSDATE y haga click en el botón “OK”.
Para mostrar el reporte como usuario en la pantalla “PMS” haga click en el botón de opción “Miscellaneous” opción “Reports”
En la pantalla “Reports” busque el reporte de pagos creado y haga click en el botón “OK”
Se mostrará la pantalla “Report Parameters”, en esta pantalla indique una determinada fecha y haga click en el botón “Preview”
Se mostrará el reporte de pagos diseñado en el “Oracle Reports Builder”.
Revenue Management es una técnica que consiste en vender el producto adecuado, al cliente adecuado, en el momento adecuado y al precio adecuado, se trata de predecir el comportamiento del consumidor con el objetivo de maximizar los ingresos y minimizar los costos.
El forecasting consiste en la estimación y el análisis de la demanda futura para un producto o servicio utilizando diferentes variables como datos históricos.
Una de las principales variables en las que se fundamenta el forecasting hotelero es el análisis de datos estadísticos de la propiedad en periodos anteriores, con esto podemos prever el los ingresos futuros y tomar las decisiones comerciales oportunas para corregir desviaciones con el propósito de maximizar los ingresos y minimizar los costos.
Teniendo claro la importancia de una herramienta forecast en especial online, en tiempo real y desde un smartphone que consulte datos directamente desde el Opera PMS sería una herramienta de gran utilidad para la gestión eficiente de la Propiedad.
Es importante considerar que la herramienta forecast online deba contemplar los siguientes datos cuyas descripciones se mantienen de la documentación original de Opera:
Date. Date to which the statistics apply.
Total Occupancy. Total occupied rooms (non-deduct, deduct, individual and group).
Arrival Rooms. Rooms with guests arriving this date. For arrivals, component rooms count as 1 and not the number of physical rooms making up the component room.
Comp Rooms. Complementary rooms (rooms attached to reservations having a rate code that is flagged Complimentary).
House Use. House use rooms (rooms attached to reservations having a rate code that is flagged House Use).
Deduct Individual. Individual reservations having a reservation type that is flagged Deduct from inventory.
Non-Deduct Individual. Individual reservations having a reservation type that is not flagged Deduct from inventory.
Deduct Group. Group reservations having a reservation type that is flagged Deduct from inventory.
Non-Deduct Group. Group reservations having a reservation type that is not flagged Deduct from inventory.
Occupancy %. (Total Occupied Rooms / Number of Rooms in Property) x 100).
Room Revenue. Total revenue for this date associated with Lodging transaction codes for deduct, non-deduct, individual, and group reservations.
Average Rate. Total Room Revenue / Number of Occupied rooms.
Departure Rooms. Rooms due out this date. For departures, component rooms count as 1 and not the number of physical rooms making up the component room.
Day Use Rooms. Day Use Rooms for the date.
No Show Rooms. No Show Rooms for the date.
Con este propósito se construye el siguiente Query SQL para Oracle que obtiene el forecast con los ingresos del el mes corriente (HISTORY) hacia el estimado de ingresos anual (FORECAST).
Este Query será la base para comenzar a construir la herramienta forecast online para smartphone.
SELECT rec_type rec_type,
DECODE(rec_type,'A_STAT',f_message('REP_HISTORY','History'),f_message('REP_FORECAST','Forecast')) rec_type_desc,
TO_CHAR(considered_date,'DD/MM/RRRR') considered_date,
SUM(no_rooms * count_resv_01) no_rooms,
SUM(ind_deduct_rooms * count_resv_01) ind_deduct_rooms,
SUM(ind_non_deduct_rooms * count_resv_01) ind_non_deduct_rooms,
SUM(grp_deduct_rooms * count_resv_01) grp_deduct_rooms,
SUM(grp_non_deduct_rooms * count_resv_01) grp_non_deduct_rooms,
SUM(no_persons * count_resv_01) no_persons,
SUM(arrival_rooms * count_resv_01) arrival_rooms,
SUM(departure_rooms * count_resv_01) departure_rooms,
SUM(complimentary_rooms * count_resv_01) complimentary_rooms,
SUM(house_use_rooms * count_resv_01) house_use_rooms,
SUM(day_use_rooms * count_resv_01) day_use_rooms,
SUM(no_show_rooms * count_resv_01) no_show_rooms,
SUM(revenue * count_revenue_01) revenue,
SUM(DECODE(group_yn,'N',DECODE(deduct_yn,'Y',revenue,0),0) * count_revenue_01) ind_deduct_revenue,
SUM(DECODE(group_yn,'N',DECODE(deduct_yn,'N',revenue,0),0) * count_revenue_01) ind_non_deduct_revenue,
SUM(DECODE(group_yn,'Y',DECODE(deduct_yn,'Y',revenue,0),0) * count_revenue_01) grp_deduct_revenue,
SUM(DECODE(group_yn,'Y',DECODE(deduct_yn,'N',revenue,0),0) * count_revenue_01) grp_non_deduct_revenue,
SUM(owner_rooms * count_resv_01) owner_rooms,
SUM(ff_rooms * count_resv_01) ff_rooms
FROM (
SELECT SUBSTR(rsf.rec_type,1,6) rec_type,
rsf.considered_date considered_date,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,rsf.no_rooms) no_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,DECODE(rsf.group_yn,'N',DECODE(deduct_yn,'Y',rsf.no_rooms,0),0)) ind_deduct_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,DECODE(rsf.group_yn,'N',DECODE(deduct_yn,'N',rsf.no_rooms,0),0)) ind_non_deduct_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,DECODE(rsf.group_yn,'Y',DECODE(deduct_yn,'Y',rsf.no_rooms,0),0)) grp_deduct_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,DECODE(rsf.group_yn,'Y',DECODE(deduct_yn,'N',rsf.no_rooms,0),0)) grp_non_deduct_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,rsf.no_persons) no_persons,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,rsf.arrival_rooms) arrival_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,rsf.departure_rooms) departure_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,rsf.complimentary_rooms) complimentary_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,rsf.house_use_rooms) house_use_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,rsf.day_use_rooms) day_use_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,rsf.no_show_rooms) no_show_rooms,
DECODE(nvl(rsf.owner_rental_flag,'H'),'O',0,
CASE 'RN'
WHEN 'RN' THEN rsf.net_room_revenue -- net room revenue
WHEN 'RG' THEN rsf.net_room_revenue + rsf.room_revenue_tax -- net total revenue
WHEN 'TN' THEN rsf.total_revenue -- gross room revenue
WHEN 'TG' THEN rsf.total_revenue + rsf.total_revenue_tax -- gross total revenue
ELSE rsf.net_room_revenue
END
) revenue,
(CASE WHEN SUBSTR(rsf.room_category,1,1) <> '-' THEN 1 -- this is not a PM resv, count it
WHEN SUBSTR(rsf.rec_type,1,6) = 'A_STAT' THEN 0 -- for statistics we never count PM reservations (rooms)
WHEN NVL('N','N') = 'Y' THEN 1 -- for forecast look at parameter whether to count PM rooms
ELSE 0
END ) count_resv_01,
(CASE WHEN SUBSTR(rsf.room_category,1,1) <> '-' THEN 1 -- this is not a PM resv, count the revenue
WHEN SUBSTR(rsf.rec_type,1,6) = 'A_STAT' THEN 1 -- for statistics we count all revenue, even from PM resv
WHEN NVL('N','N') = 'Y' THEN 1 -- for forecast look at parameter whether to count PM rooms
ELSE 0
END ) count_revenue_01,
rsf.owner_rooms owner_rooms,
rsf.ff_rooms ff_rooms,
rsf.deduct_yn,
rsf.group_yn
FROM rep_res_stati_forecast_hld rsf
where rsf.considered_date between TO_DATE(('01'||to_char(sysdate,'MMRRRR')),'DDMMRRRR') and TO_DATE(TO_CHAR(LAST_DAY(to_date(to_char(ADD_MONTHS(SYSDATE, 11),'YYYYMM'),'YYYYMM')),'DDMMRRRR'),'DDMMRRRR')
and rsf.deduct_yn='Y'
-- make sure that we have at least one record per day
UNION ALL
SELECT (CASE WHEN (TO_DATE(('01'||to_char(sysdate,'MMRRRR')),'DDMMRRRR') + ns.n - 1) < pms_p.business_date THEN
'A_STAT'
ELSE 'B_FORE'
END) rec_type,
(TO_DATE(('01'||to_char(sysdate,'MMRRRR')),'DDMMRRRR') + ns.n - 1) considered_date,
0 no_rooms,
0 ind_deduct_rooms,
0 ind_non_deduct_rooms,
0 grp_deduct_rooms,
0 grp_non_deduct_rooms,
0 no_persons,
0 arrival_rooms,
0 departure_rooms,
0 complimentary_rooms,
0 house_use_rooms,
0 day_use_rooms,
CASE WHEN (TO_DATE(('01'||to_char(sysdate,'MMRRRR')),'DDMMRRRR') + ns.n - 1) < pms_p.business_date THEN
0
ELSE TO_NUMBER(NULL)
END no_show_rooms, -- for the forecasting section the No Show rooms should be NULL since we cannot predict how many rooms will be no-show
0 revenue,
0 count_resv_01,
0 count_revenue_01,
0 owner_rooms,
0 ff_rooms,
'N' deduct_yn,
'N' group_yn
FROM number_scale ns
WHERE ns.n <= TO_DATE(TO_CHAR(LAST_DAY(to_date(to_char(ADD_MONTHS(SYSDATE, 11),'YYYYMM'),'YYYYMM')),'DDMMRRRR'),'DDMMRRRR') - TO_DATE(('01'||to_char(sysdate,'MMRRRR')),'DDMMRRRR') + 1
)
group by rec_type,
considered_date
ORDER BY rec_type,
TO_DATE(considered_date,'DD/MM/RRRR')
Es importante comentarles que al igual como hicimos en HouseKeeping para mostrar el estado de las habitaciones desde el smartphone se puede desarrollar reportes analiticos en base al Trial Balance para tener en línea el estado de los ingresos.
En este reporte se muestra el detalle de todas las transacciones posteadas al huesped y la clasificación de estas transacciones.
Debido a que los términos del Balance no se pueden traducir de manera directa al español sin desnaturalizar su significado mantendré en este blog las definiciones en inglés.
The Trial Balance reprt includes all transactions posted, and then a breakdown of business within each of the five Ledgers (Guest Ledger, AR Ledger, Deposit Ledger, Package Ledger, and Inter Hotel Ledger). The Trial Balance may be used to assist in ensuring your property's accounts are balanced and in good standing.
Summary of others Reports That May Be Used For Balancing
Report Title |
.REP Filename |
Additional Information |
Aging Summary by Types |
araging |
May be run for a specific date. |
Detailed Aging Report |
aragingdet |
May be run for a specific date. |
AR Ledger |
arledger |
Continually updating |
Deposit Activity Report |
deposit_activity |
May be run for a specific date but should be run by Activity Date if used for balancing. |
NA Deposit Ledger |
deposit_ledger |
Continually updating. |
Financial Payments and Revenue Postings |
findeptcodes |
May be run for a specific date but should always be run for NET revenue if used for balancing. |
Journal by Cashier and Transaction Code |
finjrnlbytrans |
May be run for a specific date but should always be run for NET revenue if used for balancing. |
Financial Transactions with Generates |
finjrnlbytrans2 |
May be run for a specific date but should always be run for NET revenue if used for balancing. |
Package Postings |
finpkgposting |
Captures data for the current business date, must be attached to Night Audit Report Group if used for balancing. |
Guest Trial Balance |
gl_trial_balance |
May be run for a specific date. |
Manager Report |
manager_report |
May be run for a specific date. |
Deposits Transferred at C/I |
nadeptransci |
Captures data for the current business date, must be run with the Night Audit if used for balancing to trial_balance. |
Package Ledger Detail |
napkgledger |
Captures data for the current business date, must be run with the Night Audit if used for balancing to trial_balance. |
Trial Balance |
trial_balance |
May be run for a specific date. |
El Trial Balance Detail posee la siguiente estructura:
Room. Room number of the reservation.
Guest Name. Name of the guest.
Arragement Desc. Name of transaction clasification.
Trx Code. Code Transaction
Trx No. Transaction secuencial number.
Description. Transaction description.
Old Balance (Opening Balance). Total balance of the guest account for the date in which the report was ran.
Credits. Total Amount that has been paid against the account by the guest.
Debits. Total Amount that has been charged to the guests account.
Transferred Credits. Any amounts that have been transferred to the guests account and that is considered a credit.
Transferred Debits. Any amounts charged to the guest account as a result of a transfer.
New Balance (Closing Balance). Closing balance for the account. This column is calculated by the following formula: Opening Balance + Debits + Transfer Debit - Credits - Transfer Credits.
La consulta SQL para Oracle:
SELECT t.room,t.guest_name,t.arrangement_desc,
t.trx_code,t.trx_no,
t.description,
t.old_balance, t.credit,t.debit,t.transfer_credit,t.transfer_debit,t.new_balance
FROM(
SELECT
fs.trx_no,
ar.arrangement_desc,
fs.resv_name_id,
fs.name_id,
fs.resort,
rv.room,
rv.guest_name,
co.trx_code,
co.description,
-- all GL postings from days prior to p_from_date
DECODE(abs(trunc(to_date(to_char(to_date(to_char(pms_p.business_date))))) - trunc(fs.trx_date)),
0,0,
-1,0,
(NVL(fs.guest_account_debit,0))- (NVL(fs.guest_account_credit,0))) old_balance,
-- all GL credits posted on p_from_date
DECODE(fs.from_resv_id,NULL,decode(pms_p.business_date - trunc(fs.trx_date),
0,nvl(fs.guest_account_credit,0),
0),
0) credit,
-- all GL debits posted on p_from_date
DECODE(fs.from_resv_id,NULL,decode(pms_p.business_date - trunc(fs.trx_date),
0,nvl(fs.guest_account_debit,0),
0),
0) debit,
-- all GL transfer credits from other reservations posted on p_from_date
DECODE(fs.from_resv_id,NULL,0,
decode(pms_p.business_date - trunc(fs.trx_date),
0,nvl(fs.guest_account_credit,0),
0)) transfer_credit,
-- all GL transfer debits from other reservations posted on p_from_date
DECODE(fs.from_resv_id,NULL,0,
decode(pms_p.business_date - trunc(fs.trx_date),
0,nvl(fs.guest_account_debit,0),
0)) transfer_debit,
-- all GL postings posted on p_from_date or before
DECODE(abs(pms_p.business_date - trunc(fs.trx_date)),
-1,0,
NVL(fs.guest_account_debit,0) - NVL(fs.guest_account_credit,0)) new_balance
FROM financial_transactions_view fs
inner join rep_reservation_all_view rv on (fs.resv_name_id = rv.resv_name_id)
inner join trx$_codes co on (co.trx_code=fs.trx_code)
inner join trx$_code_arrangement ar on (ar.arrangement_id=co.arrange_code)
where fs.resv_name_id IN
(-- all resv_name_ids that had a posting today
SELECT resv_name_id
FROM financial_transactions ftx
WHERE ftx.resort = :RESORT
AND ftx.trx_date = pms_p.business_date
AND ftx.resv_name_id IS NOT NULL
UNION ALL
-- all reservations that were (supposed to be) in-house today
SELECT resv_name_id
FROM reservation_daily_elements rde,
reservation_daily_element_name rdn
WHERE rde.resort = :RESORT
AND rde.reservation_date = pms_p.business_date
AND rdn.resort = rde.resort
AND rdn.reservation_date = rde.reservation_date
AND rdn.resv_daily_el_seq = rde.resv_daily_el_seq
UNION ALL
SELECT resv_name_id
FROM reservation_name rn
WHERE rn.resort = :RESORT
AND rn.post_co_flag = 'O'
)
AND fs.trx_date <= pms_p.business_date
AND (fs.guest_account_credit IS NOT NULL OR fs.guest_account_debit IS NOT NULL)
and fs.resv_name_id=3142559 and rv.room='0206'
)t
ORDER BY t.room,t.arrangement_desc,t.trx_code,t.trx_no
Es importante comentarles que al igual como hicimos en HouseKeeping para mostrar el estado de las habitaciones desde el smartphone se puede desarrollar reportes analiticos en base al Trial Balance para tener en línea el estado de los ingresos.
En este blog mostramos el desarrollo de un sistema web responsivo que muestra el estado de las habitaciones de una propiedad, este sistema web es muy importante para la operativa ágil de los supervisores de habitaciones, los supervisores revisan constantemente el estado de las habitaciones en línea desde sus celulares y evitan tener que acercarse a una PC desktop para consultar el reporte de opera sobre el estado de las habitaciones.
Los estados de las habitaciones a considerar son las siguientes:
SELECT ROOM_STATUS_ID,ROOM_STATUS_CODE,ROOM_STATUS_DESC FROM OPERA.ROOM_STATUS_CODES_ALL
ROOM_STATUS_ID |
ROOM_STATUS_CODE |
ROOM_STATUS_DESC |
1 |
CL |
Clean |
2 |
DI |
Dirty |
3 |
IP |
Inspected |
4 |
OS |
Out of Service |
5 |
OO |
Out of Order |
SELECT DISTINCT HK_STATUS FROM OPERA.ROOM
OCC : ocupado
VAC : vacante
SELECT DISTINCT HK_STATUS FROM OPERA.ROOM
OCC : ocupado
VAC : vacante
Utilice el siguiente Query para la visualización del estado actual de las habitaciones de un determinado Piso:
SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description,
CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status,
TO_CHAR(v.arrival,'DD/MM') arrival,
TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time
,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy
FROM OPERA.ROOM r
INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category)
LEFT JOIN (
SELECT r.room,MIN(r.resv_status) resv_status,min(r.arrival) arrival,max(r.departure) departure,max(r.departure_time) departure_time
FROM reservation_general_view r
WHERE r.trunc_departure>=pms_p.business_date and r.room is not null
AND r.resv_status IN ('CHECKED IN','CHECKED OUT')
GROUP BY r.room
) v ON (v.room=r.room)
WHERE SUITE_TYPE<>'PSUEDO'
AND to_number(r.floor)=4--PISO
ORDER BY to_number(r.floor) ASC, to_number(r.room) ASC
Las pantallas del sistema web que consulta el estado de las habitaciones que se visualizan desde un dispositivo smartphone se muestran de la siguiente manera:
Discrepancias:
Las discrepancias se pueden observar en el reporte “Room Discrepancy” de Opera:
en el módulo de PMS ingrese al menú “Miscellaneous”, submenu “Reports”, buscamos el reporte “Room Discrepancy” y hacemos click en “OK”.
Se mostrará la pantalla de “Report Parameters”, en esta pantalla seleccione el “Room Status” que desea visualizar.
En la selecciones de “Room Status”, observe los 2 diferentes estados de discrepancia:
“Skip/Sleep Discrepant”: Discrepancias basadas en estado de habitación.
“Persons Discrepant”: Discrepancias basadas en cantidad de huéspedes por habitación.
En este ejemplo seleccionamos la opción “ALL Rooms”, nos mostrará todas las discrepancias de la propiedad.
Observemos que las discrepancias Skip o Sleep se aparecen si el campo FO Estatus es diferente al campo HK Status.
Las discrepancias en los estado de las habitaciones se producen por los siguientes motivos:
Sleep.-
FO_STATUS Indica VAC (front office registra el check out de huesped)
HK_STATUS indica OCC (hk indica que alguien todavía está en la habitación)
Skip.-
FO_STATUS Indica OCC (huésped deja la habitación sin hacer check out de manera oficial)
HK_STATUS Indica VAC (HK indica que la habitación está vacante)
Para resolver las discrepancias ingresa al menú de Rooms Management, seleccione el item “Housekeeping”, se mostrará la pantalla Housekeeping con las opciones a realizar. seleccionamos la opcion “Rm. Discrepancies”
En la pantalla “Room Discrepancies”, se puede observar la discrepancia de estados entre los campos “FO Status” (Front Office Status) y “HK Status” (HouseKeeping Status), para resolver la discrepancia ambos estados deben coincidir.
Es importante conocer que los “Transaction Codes” que usamos durante el “Post” en “Billing” están asociados a determinadas cuentas contables que la administración tributaria del país de residencia nos exige.
Para mostrar la correspondencia o el mapeo entre los “Transaction Codes” y las Cuentas Contables se muestran en el reporte de “BackOffice Interface Transaction Codes Mapping”. En el Menú “Miscellaneous” ingrese a la opción “Reports”
En la pantalla “Reports” buscar el reporte “BackOffice Interface Transaction Codes Mapping” y luego click en OK se previsualiza el reporte con la correspondencia entre los “Transaction Codes” y las Cuentas Contables.
Si requiere asignar una determinada Cuenta Contable a un “Transaction Code” ingrese en Configuration al menú “External” , submenu “Back Office” opción “Configuration”
En la pantalla “Back Office Configuration” seleccionamos la opción “Transaction codes” y hacemos click en OK
Se nos mostrará la pantalla “Transaction Codes”, seleccionaremos un determinado Code y hacemos click en el botón “Edit”
Se mostrará la pantalla de asignación de Cuentas Contables, asigne la cuenta contable adecuada y realice click en Ok.
En este Post se mostrará, el procedimiento de cambiar el Room Type de una habitación en Opera PMS.
Listamos las habitaciones de la propiedad con sus respectivos estados, de este listado filtramos sólo las habitaciones con estados Vacio “VAC” e Inspeccionado “IP”, solo podemos cambiar el Room Type de habitaciones que no estén reservados y no estén ocupados.
SELECT r.room,r.room_status,r.suite_type,r.fo_status,r.hk_status,r.description,c.label,c.short_description
FROM OPERA.ROOM r
INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category)
WHERE r.fo_status='VAC' AND r.room_status='IP
En el módulo de Configuración ingrese a la opción de menú “Reservations” submenu “Room Classifications” item “Rooms”
En el formulario “Room List” ubicamos la habitación al cual deseamos cambiar el Tipo de Habitación “Room Type”
En esta pantalla podemos verificar el estado y las características de cada una de las habitaciones y seleccionar las habitaciones que deseamos cambiar de estado.
En “Utilities”, ingrese al menú “Utilies”, submenu “Property Config”, submenu “Change Rooms” item “Change Room Type for a Room Number”
Se muestra la pantalla “Change Room Type”
En esta pantalla selecciona el Room Number, al cual desea cambiar el “Room Type”, es importante considerar que las habitaciones se pueden cambiar solo si se encuentran en los siguientes estados:
FO_STATUS : VAC (Vacío)
ROOM_STATUS : IP (Inspeccionado)
indicamos el número de la habitación y seleccionamos el nuevo tipo de habitación a asignar.
Si la habitación se encuentra ocupada o reservada se mostrará el siguiente mensaje de error, con ello se evita la reasignación del tipo de habitación.
Revisamos la reserva de la habitación en el Room Plan, para mostrar la pantalla Room Plan presione la tecla Ctrl + F3, si colocamos el puntero del mouse encima del icono >> observaras un resumen.
Esperamos la liberación de la reserva de la habitación.
Para continuar con el ejemplo ubicamos una habitación no reservado y no ocupado mediante el Room Plan, en nuestro caso la habitación 1018.
Le hacemos click en el botón “Yes”. se realizará el cambio del Room Type.
SELECT a.room, a.resv_name_id, a.passerby_name, a.trx_code,a.trx_date, a.guest_account_debit
FROM financial_transactions_view a
WHERE to_char(a.trx_date,'RRRR') = 2019 and
a.guest_account_debit <> 0.00 and
a.trx_code IN (2580,2503)
SELECT distinct a.room,a.description, b.begin_date, b.end_date,
b.repair_remarks,b.reason_code,a.room_status,b.completed_date
FROM room a,room_repairs b
WHERE substr(a.room_status,1,1)='O'
and a.room=b.room
and b.end_date>=TO_CHAR(pms_p.business_date)
and b.begin_date<=TO_CHAR(pms_p.business_date)
and b.completed_date is NULL
ORDER BY room,begin_date
SELECT distinct a.share_id, a.room, a.room_category_label, a.company_name, a.sguest_name, a.guest_country_desc,
a.trunc_arrival, a.trunc_departure, a.currency_code, a.share_amount,
a.market_desc, a.confirmation_no, a.market_code,a.effective_rate_amount,a.fixed_charge
FROM reservation_general_view a
WHERE substr(a.ARRIVAL,1,11)=TO_CHAR(SYSDATE)
and (A.RESV_STATUS='RESERVED'OR A.RESV_STATUS='PROSPECT')
and a.share_amount<>0.00
SELECT distinct a.share_id, a.room, a.room_category_label, a.company_name, a.sguest_name, a.guest_country_desc,
a.trunc_arrival, a.trunc_departure, a.currency_code, a.share_amount,
a.market_desc, a.confirmation_no, a.market_code,a.effective_rate_amount,a.fixed_charge
FROM reservation_general_view_hld a
WHERE a.resv_status='CHECKED IN'
and a.share_amount>0.00
UNION ALL
SELECT distinct a.share_id, a.room, a.room_category_label, a.company_name, a.sguest_name, a.guest_country_desc,
a.trunc_arrival, a.trunc_departure, a.currency_code, a.share_amount,
a.market_desc, a.confirmation_no, a.market_code,a.effective_rate_amount,a.fixed_charge
FROM reservation_general_view_hld a
WHERE a.resv_status='CHECKED IN'
and substr(a.market_code,1,2)='80' and a.financially_responsible_yn is null
SELECT a.considered_date,sum(a.no_rooms), sum(a.arrival_rooms),sum(a.departure_rooms),sum(a.complimentary_rooms),
sum(a.net_room_revenue)
FROM rep_res_statistics_forecast a
WHERE (a.CONSIDERED_DATE BETWEEN TO_CHAR(SYSDATE -TO_CHAR(sysdate-1,'DD')) and TO_CHAR(SYSDATE+366) ) and a.ROOM_CATEGORY<>'-1'
AND ( (a.deduct_yn='N' AND a.market_code= '50A') or a.deduct_yn='Y')
GROUP BY a.CONSIDERED_DATE
SELECT
CONSIDERED_MONTH,
CONSIDERED_YEAR,
MARKET_GROUP,
MARKET_GROUP_DESC,
SUM(no_rooms) NO_ROOMS,
SUM(room_revenue) ROOM_REVENUE,
market_code
FROM(
SELECT
CONSIDERED_MONTH,
CONSIDERED_YEAR,
CONSIDERED_DATE,
MARKET_GROUP,
MARKET_GROUP_DESC,
MARKET_CODE,
SUM(no_rooms) NO_ROOMS,
SUM(room_revenue) ROOM_REVENUE
FROM(
SELECT
to_char(rsf.considered_date,'MONTH') CONSIDERED_MONTH,
to_char(rsf.considered_date,'RRRR') CONSIDERED_YEAR,
mc.parent_market_code MARKET_GROUP,
mg.description MARKET_GROUP_DESC,
rsf.market_code MARKET_CODE,
rsf.considered_date CONSIDERED_DATE,
decode(rsf.room_category,-1,0,rsf.no_rooms) NO_ROOMS,
rsf.net_room_revenue ROOM_REVENUE
FROM
rep_res_statistics_forecast rsf, markets mc, market_groups mg
WHERE
(rsf.CONSIDERED_DATE BETWEEN TO_CHAR(SYSDATE -TO_CHAR(sysdate-1,'DD')) and TO_CHAR(SYSDATE+135) )
AND (mc.parent_market_code = mg.market_group AND rsf.market_code(+) = mc.market_code )
AND rsf.deduct_yn='Y'
)
GROUP BY
CONSIDERED_MONTH,
CONSIDERED_YEAR,
CONSIDERED_DATE,
MARKET_GROUP,
MARKET_GROUP_DESC,
MARKET_CODE
ORDER BY
CONSIDERED_MONTH,
CONSIDERED_YEAR,
CONSIDERED_DATE,
MARKET_GROUP,
MARKET_GROUP_DESC,
MARKET_CODE
)
GROUP BY
CONSIDERED_MONTH, CONSIDERED_YEAR, MARKET_GROUP, MARKET_GROUP_DESC, market_code
ORDER BY
CONSIDERED_MONTH,
CONSIDERED_YEAR,
MARKET_GROUP,
MARKET_Code
SELECT a.business_date_created as Fch_Reserva, a.trunc_arrival as LLegada, a.trunc_departure as Salida,a.nights,
a.room_category_label as Hab,a.share_amount as tarifa, a.rate_code,a.guarantee_code,
a.sfirst_guest_name as nombres,a.guest_name as apellido, a.company_name, a.travel_agent_name,
b.srep_code as Ejecutivo,a.share_amount
FROM reservation_general_view a , name_view b
WHERE a.room_category_label<>'PM' and
a.resv_status<>'CANCELLED' and
a.share_amount > 0.00 and
b.name_id (+)= decode(a.company_id,null,a.travel_agent_id,a.company_id) and
a.business_date_created =TO_CHAR(pms_p.business_date)
ORDER BY a.trunc_arrival
SELECT a.room_revenue, a.share_amount,b.srep_code,a.rate_code,
a.sfirst_guest_name || ' ' || a.guest_name as nombres,
a.trunc_arrival, a.trunc_departure,a.company_name,a.origin_of_booking,a.guarantee_code
FROM reservation_general_view a , name_view b
WHERE a.guarantee_code not in ('G01', 'G02') and
a.resv_status<>'CANCELLED' and
a.share_amount > 0.00 and
b.name_id = decode(a.company_id,null,a.travel_agent_id,a.company_id) and
(a.trunc_departure >= TO_CHAR(SYSDATE))
UNION ALL
SELECT a.available_revenue,a.avg_rate, a.owner_code,a.rate_code,
'BLK ' || a.description,
a.begin_date, a.end_date,a.acc_name,a.source,a.guarantee_code
FROM sc_busblock_info a
WHERE a.status<>'C' and
a.available_rooms>0 and
a.avg_rate >0 and a.guarantee_code not in ('G01', 'G02')
SELECT 'F' HF,to_char(a.trunc_arrival,'DD') DD,to_char(a.trunc_arrival,'MM') MM,to_char(a.trunc_arrival,'YYYY') AA,
a.nights Noches, a.room_category CRoom , a.share_amount Rate,b.srep_code Owner,
a.trunc_arrival Arrival, a.trunc_departure Departure,a.company_name Compania
FROM reservation_general_view a , name_view b
WHERE a.resv_status<>'CANCELLED' and a.share_amount > 0.00 and
b.name_id = decode(a.company_id,null,a.travel_agent_id,a.company_id) and
(a.trunc_departure >= TO_CHAR(SYSDATE) )
UNION ALL
SELECT 'F',to_char(a.begin_date,'DD') DD,to_char(a.begin_date,'MM') MM,to_char(a.begin_date,'YYYY') AA,
round(a.available_revenue/a.avg_rate,0),
'BLOCK ' CRoom, a.avg_rate, a.owner_code,a.begin_date, a.end_date,a.acc_name
FROM sc_busblock_info a
WHERE a.status<>'C' and a.available_rooms>0 and a.avg_rate >0
UNION ALL
SELECT 'H',to_char(rsd.business_date,'DD') DD,to_char(rsd.business_date,'MM') MM,to_char(rsd.business_date,'YYYY') AA,
1 noches,rsd.room_category CRoom,rsd.room_revenue ROOM_REVENUE,au.app_user CIA_OWNER,rsd.trunc_begin_date,
rsd.business_date BUSINESS_DATE,n2.company
FROM reservation_stat_daily rsd , name_owner no, application$_user au, name n1, name n2
WHERE no.name_id = rsd.company_id and no.primary_yn = 'Y'
and au.person_name_id = no.user_id and rsd.market_code<>'80C'
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and n1.name_id(+) = rsd.name_id and n2.name_id(+) = rsd.company_id
and rsd.room_revenue>0
UNION ALL
SELECT 'H',to_char(rsd.business_date,'DD') DD,to_char(rsd.business_date,'MM') MM,to_char(rsd.business_date,'YYYY') AA,
1 noches,rsd.room_category CRoom,rsd.room_revenue ROOM_REVENUE,au.app_user CIA_OWNER,rsd.trunc_begin_date,
rsd.business_date BUSINESS_DATE,n2.company
FROM reservation_stat_daily rsd, name_owner no, application$_user au, name n1, name n2
WHERE rsd.company_id is null and no.name_id = rsd.agent_id
and no.primary_yn = 'Y' and au.person_name_id = no.user_id
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW' and rsd.resv_status <> 'CHECKED OUT')
and n1.name_id(+) = rsd.name_id and n2.name_id(+) = rsd.agent_id
and rsd.room_revenue<>0
ORDER BY AA,MM,DD,CRoom
SELECT
rsd.business_date BUSINESS_DATE,
rsd.room_revenue ROOM_REVENUE,
au.app_user CIA_OWNER,
rsd.rate_code RATE_CODE,
initcap(n1.sname||','||n1.sfirst) GUEST_NAME,
to_char(rsd.trunc_begin_date,'DD-MM-RR') ARRIVAL,
to_char(rsd.trunc_end_date,'DD-MM-RR') DEPARTURE,
n2.company,
rsd.source_code,
rsd.market_code,
rsd.room,
rsd.room_category
FROM
reservation_stat_daily rsd, name_owner no, application$_user au, name n1, name n2
WHERE
no.name_id = rsd.company_id
and no.primary_yn = 'Y'
and au.person_name_id = no.user_id
and rsd.market_code<>'80C'
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and n1.name_id(+) = rsd.name_id
and n2.name_id(+) = rsd.company_id
and rsd.room_revenue>0
UNION ALL
SELECT
rsd.business_date BUSINESS_DATE,
rsd.room_revenue ROOM_REVENUE,
au.app_user CIA_OWNER,
rsd.rate_code RATE_CODE,
initcap(n1.sname||','||n1.sfirst) GUEST_NAME,
to_char(rsd.trunc_begin_date,'DD-MM-RR') ARRIVAL,
to_char(rsd.trunc_end_date,'DD-MM-RR') DEPARTURE,
n2.company,
rsd.source_code,
rsd.market_code,
rsd.room,
rsd.room_category
FROM
reservation_stat_daily rsd, name_owner no, application$_user au, name n1, name n2
WHERE
no.name_id = rsd.company_id
and no.primary_yn = 'Y'
and au.person_name_id = no.user_id
and rsd.market_code<>'80C'
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and n1.name_id(+) = rsd.name_id
and n2.name_id(+) = rsd.company_id
and rsd.room_revenue<0
UNION ALL
SELECT
rsd.business_date BUSINESS_DATE,
rsd.room_revenue ROOM_REVENUE,
au.app_user CIA_OWNER,
rsd.rate_code RATE_CODE,
initcap(n1.sname||','||n1.sfirst) GUEST_NAME,
to_char(rsd.trunc_begin_date,'DD-MM-RR') ARRIVAL,
to_char(rsd.trunc_end_date,'DD-MM-RR') DEPARTURE,
n2.company,
rsd.source_code,
rsd.market_code,
rsd.room,
rsd.room_category
FROM
reservation_stat_daily rsd, name_owner no, application$_user au, name n1, name n2
WHERE
rsd.company_id is null
and no.name_id = rsd.agent_id
and no.primary_yn = 'Y'
and au.person_name_id = no.user_id
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW' and rsd.resv_status <> 'CHECKED OUT')
and n1.name_id(+) = rsd.name_id
and n2.name_id(+) = rsd.agent_id
and rsd.room_revenue<>0
UNION ALL
SELECT
rsd.business_date BUSINESS_DATE,
rsd.room_revenue ROOM_REVENUE,
'SUPERVISOR' CIA_OWNER,
rsd.rate_code RATE_CODE,
'*** NO DISPONIBLE ***' GUEST_NAME,
to_char(rsd.trunc_begin_date,'DD-MM-RR') ARRIVAL,
to_char(rsd.trunc_end_date,'DD-MM-RR') DEPARTURE,
n1.display_name company,
rsd.source_code,
rsd.market_code,
rsd.room,
rsd.room_category
FROM
reservation_stat_daily rsd,name_view n1
WHERE
n1.name_id(+) = rsd.name_id
and rsd.market_main_group='900'
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and rsd.company_id is NULL
and rsd.room_revenue>0
UNION ALL
SELECT
rsd.business_date BUSINESS_DATE,
rsd.room_revenue ROOM_REVENUE,
'SUPERVISOR' CIA_OWNER,
rsd.rate_code RATE_CODE,
'*** NO DISPONIBLE ***' GUEST_NAME,
to_char(rsd.trunc_begin_date,'DD-MM-RR') ARRIVAL,
to_char(rsd.trunc_end_date,'DD-MM-RR') DEPARTURE,
n1.display_name company,
rsd.source_code,
rsd.market_code,
rsd.room,
rsd.room_category
FROM
reservation_stat_daily rsd,name_view n1
WHERE
n1.name_id(+) = rsd.name_id
and rsd.market_main_group='900'
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and rsd.company_id is NULL
and rsd.room_revenue<0
UNION ALL
SELECT
rsd.business_date BUSINESS_DATE,
rsd.room_revenue ROOM_REVENUE,
au.app_user CIA_OWNER,
rsd.rate_code RATE_CODE,
initcap(n1.sname||','||n1.sfirst) GUEST_NAME,
to_char(rsd.trunc_begin_date,'DD-MM-RR') ARRIVAL,
to_char(rsd.trunc_end_date,'DD-MM-RR') DEPARTURE,
n2.company,
rsd.source_code,
rsd.market_code,
rsd.room,
rsd.room_category
FROM
reservation_stat_daily rsd, name_owner no, application$_user au, name n1, name n2
WHERE
to_char(rsd.business_date,'RRRR') = 2018
and to_char(rsd.business_date,'MM') = '12'
and no.name_id = rsd.company_id
and no.primary_yn = 'Y'
and rsd.nights>0
and au.person_name_id = no.user_id
and substr(rsd.market_code,1,2)='80'
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and n1.name_id(+) = rsd.name_id
and n2.name_id(+) = rsd.company_id
and rsd.room_revenue=0
UNION ALL
SELECT
rsd.business_date BUSINESS_DATE,
rsd.room_revenue ROOM_REVENUE,
alh.rms_owner_code CIA_OWNER,
rsd.rate_code RATE_CODE,
initcap(n1.sname||','||n1.sfirst) GUEST_NAME,
to_char(rsd.trunc_begin_date,'DD-MM-RR') ARRIVAL,
to_char(rsd.trunc_end_date,'DD-MM-RR') DEPARTURE,
n2.company,
rsd.source_code,
rsd.market_code,
rsd.room,
rsd.room_category
FROM
reservation_stat_daily rsd, name n1, name n2, allotment$header alh
WHERE
rsd.company_id is NULL
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and rsd.room_revenue>0
and n1.name_id = rsd.name_id
and alh.allotment_header_id = rsd.allotment_header_id
and n2.name_id = alh.company_name_id
ORDER BY arrival,departure
SELECT
rsd.business_date BUSINESS_DATE,
to_char(rsd.business_date,'MM') MONTH,
to_char(rsd.business_date,'RRRR') YEAR,
rsd.stay_rooms STAY_ROOMS,
decode(n2.sname,NULL,'SIN COMPAÑIA',n2.sname) CIA_NAME,
au.app_user CIA_OWNER,
rsd.rate_code RATE_CODE,
rsd.room_revenue ROOM_REVENUE,
n2.industry_code,
rsd.source_code
FROM
reservation_stat_daily rsd, name_owner no, application$_user au, name n1, name n2
WHERE
rsd.business_date>=TO_CHAR(pms_p.business_date-30)
and no.name_id = rsd.company_id
and rsd.room_revenue<>0
and no.primary_yn = 'Y'
and au.person_name_id = no.user_id
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and n1.name_id(+) = rsd.name_id
and n2.name_id(+) = rsd.company_id
UNION ALL
SELECT
rsd.business_date BUSINESS_DATE,
to_char(rsd.business_date,'MM') MONTH,
to_char(rsd.business_date,'RRRR') YEAR,
rsd.stay_rooms STAY_ROOMS,
decode(n2.sname,NULL,'SIN COMPAÑIA',n2.sname) CIA_NAME,
au.app_user CIA_OWNER,
rsd.rate_code RATE_CODE,
rsd.room_revenue ROOM_REVENUE,
n2.industry_code,
rsd.source_code
FROM
reservation_stat_daily rsd, name_owner no, application$_user au, name n1, name n2
WHERE
rsd.business_date>=TO_CHAR(pms_p.business_date-30)
and rsd.company_id is null
and no.name_id = rsd.agent_id
and no.primary_yn = 'Y'
and au.person_name_id = no.user_id
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW' and rsd.resv_status <> 'CHECKED OUT')
and n1.name_id(+) = rsd.name_id
and n2.name_id(+) = rsd.agent_id
and rsd.room_revenue<>0
SELECT
au.app_user ,sum(rsd.room_revenue)
FROM
reservation_stat_daily rsd, name_owner no, application$_user au
WHERE
no.name_id = rsd.company_id
and no.primary_yn = 'Y'
and au.person_name_id = no.user_id
and rsd.market_code<>'80C'
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and rsd.room_revenue<>0
group by au.app_user
UNION ALL
SELECT
au.app_user,sum(rsd.room_revenue)
FROM
reservation_stat_daily rsd, name_owner no, application$_user au
WHERE
rsd.company_id is null
and no.name_id = rsd.agent_id
and no.primary_yn = 'Y'
and au.person_name_id = no.user_id
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW' and rsd.resv_status <> 'CHECKED OUT')
and rsd.room_revenue<>0
group by au.app_user
SELECT a.considered_date,sum(a.no_rooms), sum(a.arrival_rooms),sum(a.departure_rooms),sum(a.complimentary_rooms),
sum(a.net_room_revenue)
FROM rep_res_statistics_forecast a
WHERE ( EXTRACT(YEAR FROM a.CONSIDERED_DATE) = 2019 ) and a.ROOM_CATEGORY IS NOT NULL
GROUP BY a.CONSIDERED_DATE
UNION ALL
SELECT a.considered_date,sum(a.no_rooms), sum(a.arrival_rooms),sum(a.departure_rooms),sum(a.complimentary_rooms),
sum(a.net_room_revenue)
FROM rep_res_statistics_forecast a
WHERE ( EXTRACT(YEAR FROM a.CONSIDERED_DATE) = 2019 ) and a.ROOM_CATEGORY IS NOT NULL
and (a.group_yn='N' or (a.group_yn='Y' and a.deduct_yn='Y'))
GROUP BY a.CONSIDERED_DATE
SELECT to_char(rsd.business_date,'RRRR'),to_char(rsd.business_date,'MM'),rsd.company_id,rsd.room,rsd.room_category,sum(rsd.room_revenue),sum(rsd.room_adults)
FROM
reservation_stat_daily rsd
WHERE
to_char(rsd.business_date,'RRRR') >= 2010
AND Rsd.market_code<>'80C'
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and rsd.room_revenue<>0
group by to_char(rsd.business_date,'RRRR'),to_char(rsd.business_date,'MM'),rsd.company_id,rsd.room,rsd.room_category
order by to_char(rsd.business_date,'RRRR'),to_char(rsd.business_date,'MM'),rsd.company_id,rsd.room
SELECT
rsd.business_date BUSINESS_DATE,
to_char(rsd.business_date,'MM') MONTH,
to_char(rsd.business_date,'RRRR') YEAR,
decode(n2.sname,NULL,'SIN COMPAÑIA',n2.sname) CIA_NAME,
rsd.market_main_group MARKET_GRP,
rsd.market_code,
n2.industry_code,
au.app_user OWNER,
rsd.rate_code RATE_CODE,
sum(rsd.room_revenue) ROOM_REVENUE,sum(rsd.stay_rooms) ROOMS
FROM
reservation_stat_daily rsd, name_owner no, application$_user au, name n1, name n2
WHERE
rsd.business_date=TO_CHAR(pms_p.business_date-2)
and no.name_id = rsd.company_id
and rsd.room_revenue<>0
and no.primary_yn = 'Y'
and au.person_name_id = no.user_id
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and n1.name_id(+) = rsd.name_id
and n2.name_id(+) = rsd.company_id
GROUP BY
rsd.business_date,
decode(n2.sname,NULL,'SIN COMPAÑIA',n2.sname),
rsd.market_main_group,
rsd.market_code,
n2.industry_code,
au.app_user,
rsd.rate_code
UNION ALL
SELECT
rsd.business_date BUSINESS_DATE,
to_char(rsd.business_date,'MM') MONTH,
to_char(rsd.business_date,'RRRR') YEAR,
decode(n2.sname,NULL,'SIN COMPAÑIA',n2.sname) CIA_NAME,
rsd.market_main_group MARKET_GRP,
rsd.market_code,
n2.industry_code,
au.app_user OWNER,
rsd.rate_code RATE_CODE,
sum(rsd.room_revenue) ROOM_REVENUE,sum(rsd.stay_rooms) ROOMS
FROM
reservation_stat_daily rsd, name_owner no, application$_user au, name n1, name n2
WHERE
rsd.business_date=TO_CHAR(pms_p.business_date-2)
and rsd.company_id is null
and no.name_id = rsd.agent_id
and no.primary_yn = 'Y'
and au.person_name_id = no.user_id
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW' and rsd.resv_status <> 'CHECKED OUT')
and n1.name_id(+) = rsd.name_id
and n2.name_id(+) = rsd.agent_id
and rsd.room_revenue<>0
GROUP BY
rsd.business_date,
decode(n2.sname,NULL,'SIN COMPAÑIA',n2.sname),
rsd.market_main_group,
rsd.market_code,
n2.industry_code,
au.app_user,
rsd.rate_code
SELECT
rsd.room,n1.last,
rsd.business_date BUSINESS_DATE,
to_char(rsd.business_date,'MM') MONTH,
to_char(rsd.business_date,'RRRR') YEAR,
rsd.stay_rooms STAY_ROOMS,
decode(n2.sname,NULL,'SIN COMPAÑIA',n2.sname) CIA_NAME,
au.app_user CIA_OWNER,
rsd.room_revenue ROOM_REVENUE,
rsd.source_code
FROM
reservation_stat_daily rsd, name_owner no, application$_user au, name n1, name n2
WHERE no.name_id = rsd.company_id
and rsd.room_revenue<>0
and no.primary_yn = 'Y'
and au.person_name_id = no.user_id
and (rsd.resv_status <> 'CANCELLED' and rsd.resv_status <> 'NO SHOW')
and n1.name_id(+) = rsd.name_id
and n2.name_id(+) = rsd.company_id
order by BUSINESS_DATE,room
SELECT
CONSIDERED_MONTH,
CONSIDERED_YEAR,
CONSIDERED_DATE,
MARKET_GROUP,
MARKET_GROUP_DESC,
MARKET_CODE,
NO_ROOMS,
ROOM_REVENUE
FROM(
SELECT
to_char(rsf.considered_date,'MONTH') CONSIDERED_MONTH,
to_char(rsf.considered_date,'RRRR') CONSIDERED_YEAR,
mc.parent_market_code MARKET_GROUP,
mg.description MARKET_GROUP_DESC,
rsf.market_code MARKET_CODE,
rsf.considered_date CONSIDERED_DATE,
decode(rsf.room_category,-1,0,rsf.no_rooms) NO_ROOMS,
rsf.net_room_revenue ROOM_REVENUE
FROM
rep_res_statistics_forecast rsf, markets mc, market_groups mg
WHERE
(year(rsf.CONSIDERED_DATE) =2019 )
AND (mc.parent_market_code = mg.market_group AND rsf.market_code(+) = mc.market_code )
)
SELECT a.salesrep,a.insert_date, a.act_type, a.purpose,a.acc_name, a.con_name, a.notes,a.problem_desc
FROM activity_search a
WHERE a.insert_date>= sysdate-1
ORDER BY a.insert_date
SELECT a.nights*a.share_amount as trevenue, a.nights,b.srep_code,a.rate_code,a.sfirst_guest_name || ' ' || a.guest_name as nombres, a.trunc_arrival, a.trunc_departure,
b.name,a.cancellation_reason_desc
FROM reservation_general_view a, name_view b
WHERE a.resv_status='CANCELLED'
and a.booked_room_category_label<>'PM'
and substr(a.cancellation_date,1,11)>=TO_CHAR(SYSDATE-10)
and b.name_id = decode(a.company_id,null,a.travel_agent_id,a.company_id)
ORDER BY a.trunc_arrival
SELECT a.name as Apellidos,a.first as Nombre,a.udfc10 ,a.udfd11 as sexo,a.title as Trato,
a.business_title as Cargo,a.email,a.name_id as Key_con_Cia,a.company Razon_Social,a.udfc12 as Nbr_Comercial,
a.address1 as Direccion,a.city as Distrito, a.udfc13 as Rubro, a.srep_code as Owner,a.phone_no as Telefono,
a.mobile_phone_number as Celular,a.udfc14,a.udfc15,a.udfc16,a.udfc01 as DClub
FROM name_view a
WHERE a.tracecode='CON' and a.active_yn='Y' and a.country='PE'
ORDER BY a.name
SELECT ft.resort,ft.folio_no, ft.folio_type, ft.FISCAL_BILL_NO, ft.trx_date, ft.room, DECODE(NVL('GROSS','GROSS'),'GROSS',tb_amount_gross * is_debit_01, tb_amount_net * is_debit_01) debit, DECODE(is_debit_01,1,0, DECODE(NVL('GROSS','GROSS'),'GROSS',tb_amount_gross * is_credit_01, tb_amount_net * is_credit_01)) credit, ft.currency, ft.trx_code, ft.transaction_description FROM financial_transactions_view ft WHERE ft.resort = 'HOTELS' AND ft.trx_date between TO_DATE('01/01/2020','DD/MM/RRRR') and TO_DATE('31/01/2020','DD/MM/RRRR') AND ft.trx_type <> 'PACKAGE' AND is_internal_yn = 'N' AND ft.display_yn <> 'N' AND (NVL('GROSS','GROSS') = 'NET' OR trx_code_type <> 'X' OR guest_account_debit IS NOT NULL OR guest_account_credit IS NOT NULL) order by ft.FISCAL_BILL_NO ASC, ft.trx_no ASC,ft.tran_action_id ASC |
SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status, TO_CHAR(v.arrival,'DD/MM') arrival, TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy ,NVL(v.adults,0) adults,NVL(v.children,0)children,NVL(SUBSTR(v.company_name,1,15),'-') company_name ,NVL(v.vip,' ') vip FROM OPERA.ROOM r INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) LEFT JOIN ( select r.room,MIN(r.resv_status) resv_status,min(r.arrival) arrival,max(r.departure) departure,max(r.departure_time) departure_time ,SUM(case when r.resv_status ='CHECKED IN' then r.adults else 0 end) adults, SUM(case when r.resv_status ='CHECKED IN' then r.children else 0 end) children, MAX(case when r.resv_status ='CHECKED IN' then r.company_name else '' end) company_name ,MIN(r.vip) vip from reservation_general_view_hld r where r.trunc_departure>=pms_p.business_date and r.room is not null and r.resv_status IN ('CHECKED IN','CHECKED OUT') group by r.room ) v ON (v.room=r.room) WHERE SUITE_TYPE<>'PSUEDO' AND to_number(r.floor)=2 ORDER BY to_number(r.floor) ASC, to_number(r.room) ASC |
SELECT TO_NUMBER(r.floor) id,LPAD(r.floor,2,'0') floor, SUM(CASE WHEN r.hk_status='OCC' THEN 1 ELSE 0 END) CANTIDAD_OCC, SUM(CASE WHEN r.hk_status='VAC' THEN 1 ELSE 0 END) CANTIDAD_VAC, SUM(CASE WHEN r.hk_status<>r.fo_status THEN 1 ELSE 0 END) CANTIDAD_DISC, SUM(CASE WHEN r.room_status='IP' THEN 1 ELSE 0 END) CANTIDAD_IP, SUM(CASE WHEN r.room_status='DI' THEN 1 ELSE 0 END) CANTIDAD_DI, SUM(CASE WHEN r.room_status='CL' THEN 1 ELSE 0 END) CANTIDAD_CL, SUM(CASE WHEN r.room_status='OO' THEN 1 ELSE 0 END) CANTIDAD_OO, SUM(CASE WHEN r.room_status='OS' THEN 1 ELSE 0 END) CANTIDAD_OS ,SUM(o.adults) adults,SUM(o.children) children FROM OPERA.ROOM r LEFT JOIN ( select v.room ,sum(v.adults) adults, sum(v.children) children from reservation_general_view_hld v where v.resv_status ='CHECKED IN' group by v.room ) o ON (o.room=r.room) WHERE r.SUITE_TYPE<>'PSUEDO' GROUP BY TO_NUMBER(r.floor),LPAD(r.floor,2,'0') ORDER BY ID ASC
|
SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status, TO_CHAR(v.arrival,'DD/MM') arrival, TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy ,l.repair_remarks ,x.reserved,x.arrival_next,x.arrival_next_time ,NVL(v.vip,' ') vip FROM OPERA.ROOM r INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) LEFT JOIN ( select r.room,MIN(r.resv_status) resv_status,min(r.arrival) arrival,max(r.departure) departure,max(r.departure_time) departure_time,MIN(r.vip) vip from reservation_general_view_hld r where r.trunc_departure>=pms_p.business_date and r.room is not null and r.resv_status IN ('CHECKED IN','CHECKED OUT') group by r.room ) v ON (v.room=r.room) LEFT JOIN ( SELECT r.room,(r.reason_code||' '||r.repair_remarks) repair_remarks FROM opera.room_repairs r WHERE R.END_DATE>=pms_p.business_date AND R.COMPLETED_DATE IS NULL )l ON (l.room=r.room) LEFT JOIN ( SELECT V.ROOM,1 reserved,MIN(v.arrival) arrival_next,MIN(v.arrival_time) arrival_next_time from reservation_general_view_hld v where v.resv_status ='RESERVED' and TO_CHAR(v.arrival,'DDMMRRRR')=TO_CHAR(pms_p.business_date,'DDMMRRRR') GROUP BY V.ROOM ) x ON (x.room=r.room) WHERE SUITE_TYPE<>'PSUEDO' --AND r.room_status='CL' ORDER BY r.hk_status DESC,to_number(r.floor) ASC, to_number(r.room) ASC
|
SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status, TO_CHAR(v.arrival,'DD/MM') arrival, TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy ,NVL(v.vip,' ') vip FROM OPERA.ROOM r INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) LEFT JOIN ( select r.room,MIN(r.resv_status) resv_status,min(r.arrival) arrival,max(r.departure) departure,max(r.departure_time) departure_time,MIN(r.vip) vip from reservation_general_view_hld r where r.trunc_departure>=pms_p.business_date and r.room is not null and r.resv_status IN ('CHECKED IN','CHECKED OUT') group by r.room ) v ON (v.room=r.room) WHERE SUITE_TYPE<>'PSUEDO' AND r.fo_status<>r.hk_status ORDER BY r.hk_status DESC,to_number(r.floor) ASC, to_number(r.room) ASC
|
SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status, TO_CHAR(v.arrival,'DD/MM') arrival, TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy ,v.arrival_time ,NVL(v.vip,' ') vip FROM OPERA.ROOM r INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) LEFT JOIN ( select v.room,v.resv_status,v.departure,v.departure_time,v.arrival,v.arrival_time,v.vip from reservation_general_view_hld v inner join ( SELECT V.ROOM,MIN(V.RESV_NAME_ID) RESV_NAME_ID from reservation_general_view_hld v where v.resv_status ='RESERVED' and TO_CHAR(v.arrival,'DDMMRRRR')=TO_CHAR(pms_p.business_date,'DDMMRRRR') GROUP BY V.ROOM ) m ON (v.RESV_NAME_ID=m.RESV_NAME_ID) where m.RESV_NAME_ID=v.RESV_NAME_ID ) v ON (v.room=r.room) WHERE r.SUITE_TYPE<>'PSUEDO' AND r.fo_status='VAC' AND r.room_status IN ('CL','DI','OS') AND v.arrival_time IS NOT NULL ORDER BY r.hk_status DESC,to_number(r.floor) ASC, to_number(r.room) ASC
|
create or replace PROCEDURE SP_KARDEX_FISICO_VALORADO(
vn_kst_id IN MCDATA.KOSTST.KST_ID%TYPE,
vn_art_id IN MCDATA.ARTIKEL.ART_ID%TYPE,
vs_tipo IN CHAR,
vs_fec_ini IN varchar2,
vs_fec_fin IN varchar2,
P_OUT_ID_GTT_KARDEX OUT NUMBER
)
IS
-----------------------------------------------------------------------------------------------
-- PROCEDIMIENTO DE GENERACION DE KARDEX FISICO VALORADO
-- VERSION : Micros Fidelio :: Materials Control v 8.6.5.10
-----------------------------------------------------------------------------------------------
CURSOR SC_ARTICULOS IS
--COMPRAS O DEVOLUCIONES (10)
SELECT K.KST_ID,
K.KST_ADRESSE,
K.KST_NAME,
I.ART_ID,
A.ART_NUMMER AS ART_COD,
A.ART_NAME,
unidad_code_sunat(A.VPK_NR) VPK_NR,
VP.VPK_NAME,
A.ART_INFO,
I.WES_TYP,
'01' AS TIPO_OPE,
I.WES_ID1,
I.WES_ID2,
L.lfs_datum WES_DOCDATE,
DECODE(L.LFS_STATUS,42,
(CASE TRIM(SUBSTR(TRIM(MCDATA.F_FACT_NAME(L.LFS_ID)),1,3))
WHEN 'F' THEN '01' --FACTURA
WHEN 'B' THEN '03' --BOLETA DE VENTA
WHEN 'LC' THEN '04' --LIQUIDACIÓN DE COMPRA
WHEN 'NCP' THEN '07' --NOTA DE CREDITO
WHEN 'NDP' THEN '08' --NOTA DE DEBITO
WHEN 'GRE' THEN '09' --GUÍA DE REMISIÓN Remitente
WHEN 'TK' THEN '12' --TICKET
WHEN 'RET' THEN '20' --Retencion
WHEN 'GT' THEN '31' --GUÍA DE REMISIÓN Transportista
WHEN 'OT' THEN '99' --Otros
WHEN 'I' THEN '16' --INVEMTARIO
ELSE '01'
END),
(CASE TRIM(SUBSTR(TRIM(L.LFS_NAME),1,3))
WHEN 'F' THEN '01' --FACTURA
WHEN 'B' THEN '03' --BOLETA DE VENTA
WHEN 'LC' THEN '04' --LIQUIDACIÓN DE COMPRA
WHEN 'NCP' THEN '07' --NOTA DE CREDITO
WHEN 'NDP' THEN '08' --NOTA DE DEBITO
WHEN 'GRE' THEN '09' --GUÍA DE REMISIÓN Remitente
WHEN 'TK' THEN '12' --TICKET
WHEN 'RET' THEN '20' --Retencion
WHEN 'GT' THEN '31' --GUÍA DE REMISIÓN Transportista
WHEN 'OT' THEN '99' --Otros
WHEN 'I' THEN '16' --INVEMTARIO
ELSE '01'
END))AS TIPO_DOC,
DECODE(L.LFS_STATUS,42,SUBSTR(MCDATA.F_FACT_NAME(L.LFS_ID),2,3),SUBSTR(L.LFS_NAME,2,3)) AS SERIE_DOC,
DECODE(L.LFS_STATUS,42,SUBSTR(MCDATA.F_FACT_NAME(L.LFS_ID),6,LENGTH(MCDATA.F_FACT_NAME(L.LFS_ID))),SUBSTR(L.LFS_NAME,6,LENGTH(L.LFS_NAME))) AS NRO_DOC,
ROUND(I.WES_MENGE,4) AS CANT_COMPRA,
ROUND(I.WES_ESP,4) AS COST_UNI_COMPRA,
ROUND(I.WES_MENGE * I.WES_ESP,4) AS COST_TOT_COMPRA,
0.00 AS CANT_VENTA,
0.00 AS COST_UNI_VENTA,
0.00 AS COST_TOT_VENTA,
I.WES_VKP,
L.LFS_STATUS,
(SELECT NVL(COUNT(1),0)
FROM MCDATA.LIEFERPOS T
WHERE T.LFP_MENGE < 0 AND T.LFP_STATUS <> 64
AND T.LFS_ID = L.LFS_ID) AS LFP_STATUS
FROM MCDATA.INVWES I,
MCDATA.ARTIKEL A,
MCDATA.VPCKEINH VP,
MCDATA.KOSTST K,
MCDATA.LIEFERSCHEIN L
WHERE ( I.ART_ID = A.ART_ID )
AND ( I.KST_ID = K.KST_ID )
AND ( A.VPK_NR = VP.VPK_ID )
AND ( I.WES_ID1 = L.LFS_ID )
AND ( I.WES_TYP = 10 )
AND ( I.ART_ID = vn_art_id OR vn_art_id=0 )
AND ( K.KST_ID = vn_kst_id )
AND ((L.lfs_datum >= TO_DATE(vs_fec_ini||'00:00:00', 'DD/MM/YYYY HH24:MI:SS'))
AND (L.lfs_datum <= TO_DATE(vs_fec_fin||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')))
UNION ALL
-- COMPRAS EN CONTABILIDAD
SELECT K.KST_ID,
K.KST_ADRESSE,
K.KST_NAME,
I.ART_ID,
A.ART_NUMMER AS ART_COD,
A.ART_NAME,
unidad_code_sunat(A.VPK_NR) VPK_NR,
VP.VPK_NAME,
A.ART_INFO,
I.WES_TYP,
'02'AS TIPO_OPE,
I.WES_ID1,
I.WES_ID2,
RE.RNG_DATUM WES_DOCDATE,
(CASE TRIM(SUBSTR(TRIM(RE.RNG_NAME) ,1,3))
WHEN 'F' THEN '01' --FACTURA
WHEN 'B' THEN '03' --BOLETA DE VENTA
WHEN 'LC' THEN '04' --LIQUIDACIÓN DE COMPRA
WHEN 'NCP' THEN '07' --NOTA DE CREDITO
WHEN 'NDP' THEN '08' --NOTA DE DEBITO
WHEN 'GRE' THEN '09' --GUÍA DE REMISIÓN Remitente
WHEN 'TK' THEN '12' --TICKET
WHEN 'RET' THEN '20' --Retencion
WHEN 'GT' THEN '31' --GUÍA DE REMISIÓN Transportista
WHEN 'OT' THEN '99' --Otros
WHEN 'I' THEN '16' --INVEMTARIO
ELSE '01'
END)AS TIPO_DOC,
SUBSTR(RE.RNG_NAME,INSTR(RE.RNG_NAME,' '),INSTR(RE.RNG_NAME,'-')-INSTR(RE.RNG_NAME,' ')) AS SERIE_DOC,
SUBSTR(RE.RNG_NAME,INSTR(RE.RNG_NAME,'-')+1,LENGTH(RE.RNG_NAME)) AS NRO_DOC,
ROUND(I.WES_MENGE,4) AS CANT_COMPRA,
ROUND(I.WES_ESP,4) AS COST_UNI_COMPRA,
ROUND(I.WES_MENGE * I.WES_ESP,4) AS COST_TOT_COMPRA,
0.00 AS CANT_VENTA,
0.00 AS COST_UNI_VENTA,
0.00 AS COST_TOT_VENTA,
I.WES_VKP,
RE.RNG_STATUS,
(SELECT NVL(COUNT(1),0)
FROM MCDATA.LIEFERPOS T
WHERE T.LFP_MENGE < 0 AND T.LFP_STATUS <> 64
AND T.LFS_ID = I.WES_ID1) AS LFP_STATUS
FROM MCDATA.INVWES I,
MCDATA.ARTIKEL A,
MCDATA.VPCKEINH VP,
MCDATA.KOSTST K,
MCDATA.RECHNUNG RE
WHERE ( I.ART_ID = A.ART_ID )
AND ( I.KST_ID = K.KST_ID )
AND ( A.VPK_NR = VP.VPK_ID )
AND ( I.WES_TYP = 10 )
AND ( I.ART_ID = vn_art_id OR vn_art_id=0 )
AND ( K.KST_ID = vn_kst_id )
AND ( (RE.RNG_DATUM >= TO_DATE(vs_fec_ini||'00:00:00', 'DD/MM/YYYY HH24:MI:SS'))
AND (RE.RNG_DATUM <= TO_DATE(vs_fec_fin||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')))
UNION ALL
--TRASFERENCIAS DE ALMACEN (2)
SELECT K.KST_ID,
K.KST_ADRESSE,
K.KST_NAME,
I.ART_ID,
A.ART_NUMMER AS ART_COD,
A.ART_NAME,
unidad_code_sunat(A.VPK_NR) VPK_NR,
VP.VPK_NAME,
A.ART_INFO,
I.WES_TYP,
'11' AS TIPO_OPE,
I.WES_ID1,
I.WES_ID2,
HL.LBW_DATUM WES_DOCDATE,
'00' AS TIPO_DOC,
TRIM(SUBSTR(HL.LBW_NAME,1,6)) AS SERIE_DOC,
TRIM(HL.LBW_NAME) AS NRO_DOC,
ROUND(I.WES_MENGE,4) AS CANT_COMPRA,
ROUND(I.WES_ESP,4) AS COST_UNI_COMPRA,
ROUND(I.WES_MENGE * I.WES_ESP,4) AS COST_TOT_COMPRA,
0.00 AS CANT_VENTA,
0.00 AS COST_UNI_VENTA,
0.00 AS COST_TOT_VENTA,
I.WES_VKP,
HL.LBW_STATUS AS LFS_STATUS,
0 AS LFP_STATUS
FROM MCDATA.INVWES I,
MCDATA.ARTIKEL A,
MCDATA.VPCKEINH VP,
MCDATA.KOSTST K,
MCDATA.HIS_LAGERBEW HL
WHERE ( I.ART_ID = A.ART_ID )
AND ( I.KST_ID = K.KST_ID )
AND ( A.VPK_NR = VP.VPK_ID )
AND ( I.WES_ID1 = HL.LBW_ID )
AND ( I.WES_TYP=2 )
AND ( I.ART_ID = vn_art_id OR vn_art_id=0 )
AND ( K.KST_ID = vn_kst_id )
AND ((HL.LBW_DATUM >= TO_DATE(vs_fec_ini||'00:00:00', 'DD/MM/YYYY HH24:MI:SS'))
AND (HL.LBW_DATUM <= TO_DATE(vs_fec_fin||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')))
UNION ALL
--SALIDAS (1)
SELECT K.KST_ID,
K.KST_ADRESSE,
K.KST_NAME,
I.ART_ID,
A.ART_NUMMER AS ART_COD,
A.ART_NAME,
unidad_code_sunat(A.VPK_NR) VPK_NR,
VP.VPK_NAME,
A.ART_INFO,
I.WES_TYP,
'11' AS TIPO_OPE,
I.WES_ID1,
I.WES_ID2,
HL.LBW_DATUM WES_DOCDATE,
'00' AS TIPO_DOC,
TRIM(SUBSTR(HL.LBW_NAME,1,6)) AS SERIE_DOC,
TRIM(HL.LBW_NAME) AS NRO_DOC,
0.00 AS CANT_COMPRA,
0.00 AS COST_UNI_COMPRA,
0.00 AS COST_TOT_COMPRA,
ROUND(I.WES_MENGE,4) AS CANT_VENTA,
ROUND(I.WES_ESP,4) AS COST_UNI_VENTA,
ROUND(I.WES_MENGE * I.WES_ESP,4) AS COST_TOT_VENTA,
I.WES_VKP,
HL.LBW_STATUS AS LFS_STATUS,
0 AS LFP_STATUS
FROM MCDATA.INVWES I,
MCDATA.ARTIKEL A,
MCDATA.VPCKEINH VP,
MCDATA.KOSTST K,
MCDATA.HIS_LAGERBEW HL
WHERE ( I.ART_ID = A.ART_ID )
AND ( I.KST_ID = K.KST_ID )
AND ( A.VPK_NR = VP.VPK_ID )
AND ( I.WES_ID1 = HL.LBW_ID )
AND ( I.WES_TYP =1 )
AND ( I.ART_ID = vn_art_id OR vn_art_id=0 )
AND ( K.KST_ID = vn_kst_id )
AND ((HL.LBW_DATUM >= TO_DATE(vs_fec_ini||'00:00:00', 'DD/MM/YYYY HH24:MI:SS'))
AND (HL.LBW_DATUM <= TO_DATE(vs_fec_fin||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')))
UNION ALL
-- MERMAS
SELECT K.KST_ID,
K.KST_ADRESSE,
K.KST_NAME,
I.ART_ID,
A.ART_NUMMER AS ART_COD,
A.ART_NAME,
unidad_code_sunat(A.VPK_NR) VPK_NR,
VP.VPK_NAME,
A.ART_INFO,
I.WES_TYP,
'05' AS TIPO_OPE,
I.WES_ID1,
I.WES_ID2,
HV.VBR_DATUM WES_DOCDATE,
'00' AS TIPO_DOC,
TRIM(SUBSTR(VBR_NAME,1,7)) AS SERIE_DOC,
HV.VBR_NAME AS NRO_DOC,
0.00 AS CANT_COMPRA,
0.00 AS COST_UNI_COMPRA,
0.00 AS COST_TOT_COMPRA,
ROUND(I.WES_MENGE,4) AS CANT_VENTA,
ROUND(I.WES_ESP,4) AS COST_UNI_VENTA,
ROUND(I.WES_MENGE * I.WES_ESP,4) AS COST_TOT_VENTA,
I.WES_VKP,
HV.VBR_STATUS AS LFS_STATUS,
0 AS LFP_STATUS
FROM MCDATA.INVWES I,
MCDATA.ARTIKEL A,
MCDATA.VPCKEINH VP,
MCDATA.KOSTST K,
MCDATA.HIS_VERBRAUCH HV
WHERE ( I.ART_ID = A.ART_ID )
AND ( I.KST_ID = K.KST_ID )
AND ( A.VPK_NR = VP.VPK_ID )
AND ( I.WES_TYP IN (30,31) )
AND ( I.WES_ID1 = HV.VBR_ID )
AND ( I.KST_ID = HV.KST_ID )
AND ( I.ART_ID = vn_art_id OR vn_art_id=0 )
AND ( K.KST_ID = vn_kst_id )
AND ( (HV.VBR_DATUM >= TO_DATE(vs_fec_ini||'00:00:00', 'DD/MM/YYYY HH24:MI:SS'))
AND (HV.VBR_DATUM <= TO_DATE(vs_fec_fin||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')))
UNION ALL
--VENTAS
SELECT K.KST_ID,
K.KST_ADRESSE,
K.KST_NAME,
I.ART_ID,
A.ART_NUMMER AS ART_COD,
A.ART_NAME,
unidad_code_sunat(A.VPK_NR) VPK_NR,
VP.VPK_NAME,
A.ART_INFO,
I.WES_TYP,
'10' AS TIPO_OPE,
I.WES_ID1,
I.WES_ID2,
T.TAT_DATUM WES_DOCDATE,
'00' AS TIPO_DOC,
TRIM(SUBSTR(T.TAT_NAME,1,6)) AS SERIE_DOC,
T.TAT_NAME AS NRO_DOC,
0.00 AS CANT_COMPRA,
0.00 AS COST_UNI_COMPRA,
0.00 AS COST_TOT_COMPRA,
ROUND(I.WES_MENGE,4) AS CANT_VENTA,
ROUND(I.WES_ESP,4) AS COST_UNI_VENTA,
ROUND(I.WES_MENGE * I.WES_ESP,4) AS COST_TOT_VENTA,
I.WES_VKP,
AU.ATG_STATUS AS LFS_STATUS,
0 AS LFP_STATUS
FROM MCDATA.INVWES I,
MCDATA.ARTIKEL A,
MCDATA.VPCKEINH VP,
MCDATA.KOSTST K,
MCDATA.TEILAUFTRAG T,
MCDATA.AUFTRAG AU
WHERE ( I.ART_ID = A.ART_ID )
AND ( I.KST_ID = K.KST_ID )
AND ( A.VPK_NR = VP.VPK_ID )
AND ( I.WES_TYP = 21 )
AND ( I.WES_ID1 = T.TAT_ID )
AND ( T.ATG_ID = AU.ATG_ID )
AND ( I.ART_ID = vn_art_id OR vn_art_id=0 )
AND ( K.KST_ID = vn_kst_id )
AND ( (T.TAT_DATUM >= TO_DATE(vs_fec_ini||'00:00:00', 'DD/MM/YYYY HH24:MI:SS'))
AND (T.TAT_DATUM <= TO_DATE(vs_fec_fin||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')))
UNION ALL
-- AJUSTES DE INVENTARIO
SELECT K.KST_ID,
K.KST_ADRESSE,
K.KST_NAME,
I.ART_ID,
A.ART_NUMMER AS ART_COD,
A.ART_NAME,
unidad_code_sunat(A.VPK_NR) VPK_NR,
VP.VPK_NAME,
A.ART_INFO,
I.WES_TYP,
'99' AS TIPO_OPE,
I.WES_ID1,
I.WES_ID2,
IV.INV_DATUM WES_DOCDATE,
'00' AS TIPO_DOC,
TRIM(SUBSTR(INV_NAME,1,7)) AS SERIE_DOC,
IV.INV_NAME AS NRO_DOC,
DECODE(SIGN(I.WES_MENGE),1,ROUND(I.WES_MENGE,4),0.00) AS CANT_COMPRA,
DECODE(SIGN(WES_MENGE),1,ROUND(I.WES_ESP,4),0.00) AS COST_UNI_COMPRA,
DECODE(SIGN(ROUND(I.WES_MENGE * I.WES_ESP,4)),1,ROUND(I.WES_MENGE * I.WES_ESP,4),0.00) AS COST_TOT_COMPRA,
DECODE(SIGN(I.WES_MENGE),-1,ROUND(I.WES_MENGE,4),0.00) AS CANT_VENTA,
DECODE(SIGN(WES_MENGE),-1,ROUND(I.WES_ESP,4),0.00) AS COST_UNI_VENTA,
DECODE(SIGN(ROUND(I.WES_MENGE * I.WES_ESP,4)),-1,ROUND(I.WES_MENGE * I.WES_ESP,4),0.00) AS COST_TOT_VENTA,
I.WES_VKP,
IV.INV_STATUS AS LFS_STATUS,
0 AS LFP_STATUS
FROM MCDATA.INVWES I,
MCDATA.INVENTUR IV,
MCDATA.ARTIKEL A,
MCDATA.VPCKEINH VP,
MCDATA.KOSTST K
WHERE ( I.ART_ID = A.ART_ID )
AND ( I.KST_ID = K.KST_ID )
AND ( A.VPK_NR = VP.VPK_ID )
AND ( I.WES_ID1 = IV.INV_ID )
AND ( I.WES_TYP = 50 )
AND ( IV.INV_TYP IN (1,22) )
AND ( I.ART_ID = vn_art_id OR vn_art_id=0 )
AND ( K.KST_ID = vn_kst_id )
AND ((IV.INV_DATUM >= TO_DATE(vs_fec_ini||'00:00:00', 'DD/MM/YYYY HH24:MI:SS'))
AND (IV.INV_DATUM <= TO_DATE(vs_fec_fin||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')))
UNION ALL
SELECT K.KST_ID,
K.KST_ADRESSE,
K.KST_NAME,
I.ART_ID,
A.ART_NUMMER AS ART_COD,
A.ART_NAME,
unidad_code_sunat(A.VPK_NR) VPK_NR,
VP.VPK_NAME,
A.ART_INFO,
I.WES_TYP,
'10'AS TIPO_OPE,
I.WES_ID1,
I.WES_ID2,
I.wes_datum WES_DOCDATE,
'00' AS TIPO_DOC,
'MNPR1' AS SERIE_DOC,
'MNPR'||TO_CHAR(I.wes_datum, 'YYYYMMDD') AS NRO_DOC,
ROUND(I.WES_MENGE,4) AS CANT_COMPRA,
NVL(ROUND(art_wes_esp(I.KST_ID,I.ART_ID,I.wes_datum),4),0.00) AS COST_UNI_COMPRA,
ROUND(I.WES_MENGE * art_wes_esp(I.KST_ID,I.ART_ID,I.wes_datum),4) AS COST_TOT_COMPRA,
0.00 AS CANT_VENTA,
0.00 AS COST_UNI_VENTA,
0.00 AS COST_TOT_VENTA,
I.WES_VKP,
0 RNG_STATUS,
0 AS LFP_STATUS
FROM MCDATA.INVWES I,
MCDATA.ARTIKEL A,
MCDATA.VPCKEINH VP,
MCDATA.KOSTST K
WHERE ( I.ART_ID = A.ART_ID )
AND ( I.KST_ID = K.KST_ID )
AND ( A.VPK_NR = VP.VPK_ID )
AND ( I.WES_TYP=62)
AND ( I.ART_ID = vn_art_id OR vn_art_id=0 )
AND ( K.KST_ID = vn_kst_id)
AND ((I.wes_datum >= TO_DATE(vs_fec_ini||'00:00:00', 'DD/MM/YYYY HH24:MI:SS'))
AND (I.wes_datum <= TO_DATE(vs_fec_fin||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')))
UNION ALL
SELECT K.KST_ID,
K.KST_ADRESSE,
K.KST_NAME,
I.ART_ID,
A.ART_NUMMER AS ART_COD,
A.ART_NAME,
unidad_code_sunat(A.VPK_NR) VPK_NR,
VP.VPK_NAME,
A.ART_INFO,
I.WES_TYP,
'10'AS TIPO_OPE,
I.WES_ID1,
I.WES_ID2,
I.wes_datum WES_DOCDATE,
'00' AS TIPO_DOC,
'MNPR2' AS SERIE_DOC,
'MNPR'||TO_CHAR(I.wes_datum, 'YYYYMMDD') AS NRO_DOC,
0.00 AS CANT_COMPRA,
0.00 AS COST_UNI_COMPRA,
0.00 AS COST_TOT_COMPRA,
ROUND(I.WES_MENGE,4) AS CANT_VENTA,
NVL(ROUND(art_wes_esp(I.KST_ID,I.ART_ID,I.wes_datum),4),0.00) AS COST_UNI_VENTA,
ROUND(I.WES_MENGE * art_wes_esp(I.KST_ID,I.ART_ID,I.wes_datum),4) AS COST_TOT_VENTA,
I.WES_VKP,
0 RNG_STATUS,
0 AS LFP_STATUS
FROM MCDATA.INVWES I,
MCDATA.ARTIKEL A,
MCDATA.VPCKEINH VP,
MCDATA.KOSTST K
WHERE ( I.ART_ID = A.ART_ID )
AND ( I.KST_ID = K.KST_ID )
AND ( A.VPK_NR = VP.VPK_ID )
AND ( I.WES_TYP in (63))
AND ( I.ART_ID = vn_art_id OR vn_art_id=0 )
AND ( K.KST_ID = vn_kst_id)
AND ((I.wes_datum >= TO_DATE(vs_fec_ini||'00:00:00', 'DD/MM/YYYY HH24:MI:SS'))
AND (I.wes_datum <= TO_DATE(vs_fec_fin||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')))
UNION ALL
SELECT K.KST_ID,
K.KST_ADRESSE,
K.KST_NAME,
I.ART_ID,
A.ART_NUMMER AS ART_COD,
A.ART_NAME,
unidad_code_sunat(A.VPK_NR) VPK_NR,
VP.VPK_NAME,
A.ART_INFO,
I.WES_TYP,
'10'AS TIPO_OPE,
I.WES_ID1,
I.WES_ID2,
I.wes_datum WES_DOCDATE,
'00' AS TIPO_DOC,
'MNPR3' AS SERIE_DOC,
'MNPR'||TO_CHAR(I.wes_datum, 'YYYYMMDD') AS NRO_DOC,
0.00 AS CANT_COMPRA,
0.00 AS COST_UNI_COMPRA,
0.00 AS COST_TOT_COMPRA,
ROUND(I.WES_MENGE,4) AS CANT_VENTA,
NVL(ROUND(art_wes_esp(I.KST_ID,I.ART_ID,I.wes_datum),4),0.00) AS COST_UNI_VENTA,
ROUND(I.WES_MENGE * art_wes_esp(I.KST_ID,I.ART_ID,I.wes_datum),4) AS COST_TOT_VENTA,
I.WES_VKP,
0 RNG_STATUS,
0 AS LFP_STATUS
FROM MCDATA.INVWES I,
MCDATA.ARTIKEL A,
MCDATA.VPCKEINH VP,
MCDATA.KOSTST K
WHERE ( I.ART_ID = A.ART_ID )
AND ( I.KST_ID = K.KST_ID )
AND ( A.VPK_NR = VP.VPK_ID )
AND ( I.WES_TYP in (64))
AND ( I.ART_ID = vn_art_id OR vn_art_id=0 )
AND ( K.KST_ID = vn_kst_id)
AND ((I.wes_datum >= TO_DATE(vs_fec_ini||'00:00:00', 'DD/MM/YYYY HH24:MI:SS'))
AND (I.wes_datum <= TO_DATE(vs_fec_fin||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')))
ORDER BY ART_NAME,WES_DOCDATE, NRO_DOC ASC;
ln_cant_tota NUMBER(14,4);
ln_cost_tota NUMBER(14,4);
ln_cost_uni_tota NUMBER(14,4);
ld_inv_datum MCDATA.INVENTUR.INV_DATUM%TYPE;
ls_inv_name MCDATA.INVENTUR.INV_NAME%TYPE;
ln_inv_status MCDATA.INVENTUR.INV_STATUS%TYPE;
ln_inv_ist MCDATA.INVPOSART.INP_IST%TYPE;
ln_inv_esp MCDATA.INVPOSART.INP_ESP%TYPE;
ln_total NUMBER(14,2);
ln_inv_id NUMBER;
ln_nError NUMBER;
ln_art_id NUMBER;
ls_cError LONG;
ls_mensaje VARCHAR2(250);
ls_tipo_ope VARCHAR2(2);
V_QUANTITY NUMBER;
V_ID_GTT_KARDEX NUMBER;
V_SUM_LAST_CNT_SLD_FIN NUMBER(14,2);
V_SUM_LAST_CST_TOT_SLD_FIN NUMBER(14,2);
BEGIN
ln_inv_ist := 0;
ln_inv_esp := 0;
ln_total := 0;
ln_art_id := 0;
V_QUANTITY := 0;
select gtt_kardex_seq.nextval into V_ID_GTT_KARDEX from dual;
FOR VC_ARTICULO IN SC_ARTICULOS LOOP
IF ln_art_id <> VC_ARTICULO.ART_ID THEN
ln_cant_tota := 0.00;
ln_cost_uni_tota := 0.00;
ln_cost_tota := 0.00;
ln_art_id := VC_ARTICULO.ART_ID;
-- Inventario Inicial del Artículo.
SELECT MAX(I.INV_ID) INTO ln_inv_id
FROM MCDATA.INVENTUR I,
MCDATA.INVPOSART IA
WHERE I.INV_ID = IA.INV_ID
AND I.KST_ID = vn_kst_id
AND IA.ART_ID = ln_art_id
AND I.INV_DATUM < TO_DATE(vs_fec_ini, 'DD/MM/YYYY');
IF ln_inv_id > 0 THEN
SELECT IA.INP_IST,IA.INP_ESP into ln_cant_tota,ln_cost_uni_tota
FROM MCDATA.INVENTUR I, MCDATA.INVPOSART IA
WHERE I.INV_ID = IA.INV_ID
AND I.INV_ID = ln_inv_id
AND I.KST_ID = vn_kst_id
AND IA.ART_ID = ln_art_id
AND I.INV_STATUS = 8 -- CERRADO
AND I.INV_TYP <> 22; -- DIFERENTE A AJUSTE DE INVENTARIO
ln_cant_tota:=NVL(ln_cant_tota,0);
ln_cost_tota:=ln_cant_tota*ln_cost_uni_tota;
ln_inv_ist:=ln_cant_tota;
ln_inv_esp:=ln_cost_uni_tota;
ln_total:=ln_cost_tota;
INSERT INTO MCDATA.GTT_KARDEX_VALORIZADO
(KST_ID,
KST_ADRESSE,
KST_NAME,
FEC_INI_PER,
FEC_FIN_PER,
ART_ID,
WES_TYP,
ART_COD,
ART_NAME,
ART_INFO,
VPK_NR,
VPK_NAME,
TIPO_OPE,
LFS_STATUS,
LFP_STATUS,
WES_ID1,
WES_ID2,
WES_DOCDATE,
TIPO_DOC,
SERIE_DOC,
NRO_DOC,
CNT_COM,
CST_UNI_COM,
CST_TOT_COM,
CNT_VTA,
CST_UNI_VTA,
CST_TOT_VTA,
CNT_SLD_FIN,
CST_UNI_SLD_FIN,
CST_TOT_SLD_FIN,
ID_GTT_KARDEX,
ID_GTT_KARDEX_VALORIZADO)
VALUES
(VC_ARTICULO.KST_ID,
VC_ARTICULO.KST_ADRESSE,
VC_ARTICULO.KST_NAME,
TO_DATE(vs_fec_ini, 'DD/MM/YYYY'),
TO_DATE(vs_fec_fin, 'DD/MM/YYYY'),
VC_ARTICULO.ART_ID,
0,
VC_ARTICULO.ART_COD,
VC_ARTICULO.ART_NAME,
VC_ARTICULO.ART_INFO,
TRIM(VC_ARTICULO.VPK_NR),
VC_ARTICULO.VPK_NAME,
'16',
0,
0,
null,
0,
TO_DATE(vs_fec_ini, 'DD/MM/YYYY'),
'',
'',
'INV INICIAL',
NULL,
NULL,
NULL,
NULL,
NULL,
NULL,
ln_inv_ist,
ln_inv_esp,
ln_total,
V_ID_GTT_KARDEX,
ID_GTT_KARDEX_VALORIZADO_SEQ.nextval);
COMMIT;
--Actualizamos Saldo
ln_cant_tota := ln_inv_ist;
ln_cost_tota := ln_cost_tota;
END IF;
END IF;
ln_cant_tota:= ln_cant_tota + ROUND(NVL(VC_ARTICULO.CANT_COMPRA,0),4) + ROUND(NVL(VC_ARTICULO.CANT_VENTA,0),4);
ln_cant_tota:=NVL(ln_cant_tota,0);
IF (VC_ARTICULO.CANT_COMPRA>0) THEN
ln_cost_uni_tota := ROUND(VC_ARTICULO.COST_UNI_COMPRA,4);
ELSE
IF (VC_ARTICULO.CANT_VENTA>0) THEN
ln_cost_uni_tota := ROUND(VC_ARTICULO.COST_UNI_VENTA,4);
ELSE
ln_cost_uni_tota := CASE WHEN VC_ARTICULO.COST_UNI_VENTA>0 THEN ROUND(VC_ARTICULO.COST_UNI_VENTA,4) ELSE ROUND(VC_ARTICULO.COST_UNI_COMPRA,4) END;
END IF;
END IF;
ln_cost_tota := ln_cost_uni_tota*ln_cant_tota;
--Tipo Operacion
IF VC_ARTICULO.WES_TYP = 10 THEN
IF VC_ARTICULO.LFP_STATUS = 0 THEN
ls_tipo_ope := '02'; -- COMPRA
ELSE
ls_tipo_ope := '05'; -- DEVOLUCION
END IF;
ELSE
ls_tipo_ope := VC_ARTICULO.TIPO_OPE;
END IF;
INSERT INTO MCDATA.GTT_KARDEX_VALORIZADO
(KST_ID,
KST_ADRESSE,
KST_NAME,
FEC_INI_PER,
FEC_FIN_PER,
ART_ID,
WES_TYP,
ART_COD,
ART_NAME,
ART_INFO,
VPK_NR,
VPK_NAME,
TIPO_OPE,
LFS_STATUS,
LFP_STATUS,
WES_ID1,
WES_ID2,
WES_DOCDATE,
TIPO_DOC,
SERIE_DOC,
NRO_DOC,
CNT_COM,
CST_UNI_COM,
CST_TOT_COM,
CNT_VTA,
CST_UNI_VTA,
CST_TOT_VTA,
CNT_SLD_FIN,
CST_UNI_SLD_FIN,
CST_TOT_SLD_FIN,
ID_GTT_KARDEX,
ID_GTT_KARDEX_VALORIZADO)
VALUES
(VC_ARTICULO.KST_ID,
VC_ARTICULO.KST_ADRESSE,
VC_ARTICULO.KST_NAME,
TO_DATE(vs_fec_ini, 'DD/MM/RRRR'),
TO_DATE(vs_fec_fin, 'DD/MM/RRRR'),
VC_ARTICULO.ART_ID,
VC_ARTICULO.WES_TYP,
VC_ARTICULO.ART_COD,
VC_ARTICULO.ART_NAME,
VC_ARTICULO.ART_INFO,
TRIM(VC_ARTICULO.VPK_NR),
VC_ARTICULO.VPK_NAME,
ls_tipo_ope,
VC_ARTICULO.LFS_STATUS,
VC_ARTICULO.LFP_STATUS,
VC_ARTICULO.WES_ID1,
VC_ARTICULO.WES_ID2,
VC_ARTICULO.WES_DOCDATE,
VC_ARTICULO.TIPO_DOC,
VC_ARTICULO.SERIE_DOC,
VC_ARTICULO.NRO_DOC,
VC_ARTICULO.CANT_COMPRA,
VC_ARTICULO.COST_UNI_COMPRA,
VC_ARTICULO.COST_TOT_COMPRA,
VC_ARTICULO.CANT_VENTA*(-1),
VC_ARTICULO.COST_UNI_VENTA,
VC_ARTICULO.COST_TOT_VENTA*(-1),
ln_cant_tota,
ln_cost_uni_tota,
ln_cost_tota,
V_ID_GTT_KARDEX,
ID_GTT_KARDEX_VALORIZADO_SEQ.nextval);
COMMIT;
END LOOP;
select sum(LAST_CNT_SLD_FIN),sum(LAST_CST_TOT_SLD_FIN) INTO V_SUM_LAST_CNT_SLD_FIN, V_SUM_LAST_CST_TOT_SLD_FIN from (
SELECT ART_ID,max(LAST_CNT_SLD_FIN) LAST_CNT_SLD_FIN,max(LAST_CST_TOT_SLD_FIN) LAST_CST_TOT_SLD_FIN FROM (
SELECT ART_ID,
LAST_VALUE(CNT_SLD_FIN) OVER (PARTITION BY ART_ID ORDER BY ID_GTT_KARDEX_VALORIZADO ASC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LAST_CNT_SLD_FIN,
LAST_VALUE(CST_TOT_SLD_FIN) OVER (PARTITION BY ART_ID ORDER BY ID_GTT_KARDEX_VALORIZADO ASC ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS LAST_CST_TOT_SLD_FIN
FROM MCDATA.GTT_KARDEX_VALORIZADO
WHERE id_gtt_kardex=V_ID_GTT_KARDEX
)
group by ART_ID
);
SELECT COUNT(1) INTO V_QUANTITY FROM MCDATA.GTT_KARDEX_VALORIZADO WHERE ID_GTT_KARDEX=V_ID_GTT_KARDEX;
INSERT INTO MCDATA.GTT_KARDEX(ID_GTT_KARDEX,INSERT_DATE,QUANTITY_RECORDS,STATUS_REG,P_FECHA_INICIO,P_FECHA_FIN,P_ID_ESTABLECIMIENTO,SUM_LAST_CNT_SLD_FIN,SUM_LAST_CST_TOT_SLD_FIN)
VALUES(V_ID_GTT_KARDEX,CURRENT_TIMESTAMP,V_QUANTITY,1,vs_fec_ini,vs_fec_fin,vn_kst_id,V_SUM_LAST_CNT_SLD_FIN,V_SUM_LAST_CST_TOT_SLD_FIN);
COMMIT;
SELECT V_ID_GTT_KARDEX INTO P_OUT_ID_GTT_KARDEX FROM DUAL;
EXCEPTION
WHEN OTHERS THEN
ln_nError := SQLCODE;
ls_cError := SQLERRM(ln_nError);
RAISE_APPLICATION_ERROR(-20001,
ls_mensaje || TO_CHAR(ln_nError) || ', ' ||
ls_cError);
END;
Durante la revisión de las funcionalidades que ofrece Opera se debe considerar los permisos concedidos a los usuarios, permisos que pueden ser tan determinantes que si no se asignan los permisos al perfil del usuario daría la impresión de que una determinada funcionalidad no trabaja correctamente o no trabaja según lo indicado en el opera help, por ejemplo usuarios que por su perfil se les aplica las restricciones definidas en “Rate Strategy” durante la realización del proceso de Check In y usuarios que pueden obviar estas restricciones.
Utilice la siguiente sentencia SQL para extraer todos los permisos disponibles en el Opera PMS.
SELECT permission_group,permission_display,description FROM OPERA.APP_PERMISSIONS ORDER BY permission_group,permission_display |
En el siguiente enlace podrás encontrar la lista de todos los permisos en formato Excel y la descripción del permiso en inglés y su traducción en español.
Permisos de Perfil de Usuario en Opera PMS - Oracle
La asignación de permisos a perfiles de usuario se realiza en el menú “Setup”, submenu “User Configuration”, opción “User Groups”.
En la pantalla “User Groups”, seleccione un determinado perfil para luego hacer click en el botón “Permission”
Se mostrará la pantalla de asignación de permisos “User Group and Permissions for Group” donde podrá asignar los permisos al perfil seleccionado.
La asignación de permisos al perfil seleccionado se puede realizar por cada permiso de manera individual o asignar el grupo de permisos asociado a otro perfil o grupo de usuarios.
En el siguiente video se muestra la creación de reportes desde el Opera utilizando las vistas de OSR (Opera Simple Report).
https://www.youtube.com/watch?v=fFnlAHHarys&t=16s
Para crear estos reportes no es necesario conocer de programación en Transact-SQL de Oracle, solo se debe conocer las columnas de las vistas asociadas al asistente OSR:
View |
View en Base de Datos |
Reservations |
RESERVATION_GENERAL_VIEW |
Profiles |
PROFILE_VIEW |
Financial Transactions |
FINANCIAL_TRANSACTIONS_VIEW |
Business Blocks |
EXP_SCBUSBLOCK_VIEW |
Events |
EXP_SCEVENT_VIEW |
Activities |
ACTIVITY_VIEW |
El detalle de las columnas de las vistas de Ópera Simple Report (OSR) se detalla en el siguiente enlace:
Vistas de Ópera Simple Report Writer
A continuación crearemos un reporte de información de cliente utilizando las Vistas y el asistente Opera Simple Report Writer.
Ingrese a la sección de configuración de Opera.
Dirigirse a la opción de Menú “Setup”, submenu “Report Setup” opción “Reports”
En la pantalla “Report - Configuration” realizar click en el botón “New” para crear un nuevo reporte.
Se mostrará la pantalla “Reports - New”, asignarle el nombre “checkouts” y seleccionar el Report Group “Arrival”, para luego hacer click en el botón “Customize”
En la pantalla “Opera Simple Reports” seleccionar vistas “Reservations” y “Profile”
Realice click en el botón “Columns”. En la pantalla de selección de columnas y seleccione las siguientes columnas en el orden indicado en la imagen:
Realice click en el botón “Filters”. En la pantalla de definición de filtros crear los siguientes filtros:
Arrival Date = BUSINESS DATE
Or Arrival Date > BUSINESS DATE
Or Departure Date = BUSINESS DATE
Or Departure Date > BUSINESS DATE
Para crear el reporte “checkouts” hacer click en el botón “OK”, este reporte se encontrara en el buscador de reportes.
Este Query permite obtener la información de las ventas de A&B (Alimentos y Bebidas del Hotel) realizadas desde Micros 9700, ventas que podrían estar facturadas directamente desde Micros o ventas que fueron cargadas a una determinada habitación del hotel, los cargos a habitación se visualizan y se facturan desde el PMS Opera generalmente cuando el cliente realiza el Check Out. Este Query de obtencion de informacion de ventas se puede automatizar mediante una tarea para obtener los ingresos por ventas de A&B en Línea.
La información obtenida a partir de este Query se puede utilizar para la realización de reportes de Business Intelligence que nos permitan analiticas adicionales a las presentadas en las herramientas de Oracle como el MyMicros.
SELECT t.cf_cnumser,t.cf_cnumdoc,t.cf_dfecdoc,t.cf_dfecven,t.cf_ccodcli,t.cf_cnombre,t.cf_ccodmon,t.cf_ntipcam,t.cf_nprecio,t.cf_nigv,t.others,t.cf_nimport from (
select to_char(c.checknumber) as cf_cnumser,
'CARGO HAB' as cf_cnumdoc,
to_char(c.checkopen,'DD/MM/RRRR') as cf_dfecdoc,
to_char(c.checkclose,'DD/MM/RRRR') as cf_dfecven,
'HAB '||to_char(t.OBJECTNUMBER) as cf_ccodcli,
'CHK '||to_char(c.checknumber) as cf_cnombre,
'MN' as cf_ccodmon,
2.776 as cf_ntipcam,
round(c.subtotal,2) as cf_nprecio,
round(c.tax,2) as cf_nigv,
(round(c.other,2)+round(c.autogratuity,2)) as others,
round(c.payment,2) as cf_nimport
from microsdb.checks c
INNER JOIN MICROSDB.DINING_TABLE t on (c.diningtableid=t.diningtableid)
where c.checkopen >= TO_DATE('07/08/2019'||'00:00:00', 'DD/MM/RRRR HH24:MI:SS')
AND c.checkopen <= TO_DATE('07/08/2019'||'23:59:59', 'DD/MM/RRRR HH24:MI:SS')
AND c.revctrid!=4 and c.payment>0
AND c.checkid not in (
SELECT cs.checkid
FROM microsdb.fcr_invoice_data a
inner join MICROSDB.CHECKS cs on (cs.checknumber=a.microschknum and cs.revctrid=2)
where a.microsbsnzdate >= TO_DATE('07/08/2019'||'00:00:00', 'DD/MM/YYYY HH24:MI:SS')
AND a.microsbsnzdate <= TO_DATE('07/08/2019'||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')
)
UNION ALL
SELECT to_char(substr(a.fcrinvnumber,1,4)) as cf_cnumser,
to_char(substr(a.fcrinvnumber,6,7)) as cf_cnumdoc,
to_char(a.microsbsnzdate,'DD/MM/RRRR') as cf_dfecdoc,
to_char(a.microsbsnzdate,'DD/MM/RRRR') as cf_dfecven,
to_char(a.customerid) as cf_ccodcli,
to_char(a.extrafield1) as cf_cnombre,
'MN' as cf_ccodmon,
2.776 as cf_ntipcam,
round(a.subtotal8/1.18,2) as cf_nprecio,
round(a.subtotal8-(a.subtotal8/1.18),2) as cf_nigv,
0 as others,
a.subtotal8 as cf_nimport
FROM microsdb.fcr_invoice_data a
where a.microsbsnzdate >= TO_DATE('07/08/2019'||'00:00:00', 'DD/MM/YYYY HH24:MI:SS')
AND a.microsbsnzdate <= TO_DATE('07/08/2019'||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')
AND a.microschknum NOT IN (
SELECT c.checknumber
FROM MICROSDB.CHECKS c
inner join MICROSDB.CHECK_DETAIL cd on (c.CHECKID=cd.CHECKID and cd.detailtype=1)
inner join MICROSDB.menu_item_detail mid on (mid.CHECKDETAILID=cd.CHECKDETAILID)
inner join MICROSDB.menu_item_definition mif on (mif.MENUITEMDEFID=mid.MENUITEMDEFID)
inner join MICROSDB.v_string_table st on (st.STRINGNUMBERID=mif.name1id)
where c.checkopen >= TO_DATE('07/08/2019'||'00:00:00', 'DD/MM/YYYY HH24:MI:SS')
AND c.checkopen <= TO_DATE('07/08/2019'||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')
and st.stringid in (
1,2,3--SERVICIOS A EXCLUIR
)
)
) t order by t.cf_dfecdoc ASC
Este Query permite obtener la información de todos los Check que se realizan desde el Micros 9700 independientemente de si genera un comprobante de pago o un cargo a habitación, esta información se puede utilizar para generar reportes de análisis de ingresos en tiempo real por cada Revenue Center definido en el Micros 9700
SELECT c.CHECKID,c.checknumber,cd.detailindex,cd.salescount,cd.total,st.stringtext,
to_char(t.OBJECTNUMBER) nro_habitacion,
(select listagg (sd.plaindata, ',') WITHIN GROUP (ORDER BY sd.plaindata) from MICROSDB.CHECK_DETAIL cd inner join MICROSDB.secure_detail sd on (sd.checkdetailid=cd.CHECKDETAILID) where cd.checkid=c.CHECKID group by cd.checkid) secure_detail
FROM MICROSDB.CHECK_DETAIL cd
inner JOIN MICROSDB.CHECKS C on (c.CHECKID=cd.CHECKID)
inner JOIN MICROSDB.DINING_TABLE t on (c.diningtableid=t.diningtableid)
inner join MICROSDB.menu_item_detail mid on (mid.CHECKDETAILID=cd.CHECKDETAILID)
inner join MICROSDB.menu_item_definition mif on (mif.MENUITEMDEFID=mid.MENUITEMDEFID)
inner join MICROSDB.v_string_table st on (st.STRINGNUMBERID=mif.name1id)
where c.checkpostingtime >= TO_DATE('08/08/2019'||'00:00:00', 'DD/MM/YYYY HH24:MI:SS')
AND c.checkpostingtime <= TO_DATE('08/08/2019'||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')
order by c.checknumber,cd.detailindex asc
New Fiscal Tables Added
Internationally, businesses are often required to report fiscal information
over and above that which is currently supported by RES. This is done in a
variety of ways and is specific to each country’s requirements.
With this release, MICROS has added four new tables that can be used by an
integrater to store fiscal information directly in the RES database. They are:
FCR_Invoice_Control
FCR_Customer_Data
FCR_Invoice_Data
FCR_TTL_Data
As part of the RES database schema, these tables are automatically included
in the RES installation. This simplifies support while allowing sites to save
and protect the fiscal data mandated by their local government authorities.
In the future this information will be sent to mymicros.net.
cambio del tipo de documento RUC en micros
update microsdb.FCR_Customer_Data set custinfo6=6 where customerid='20461851887' --and custinfo1='Equipos Magneticos y Vibratorios SAC'
Este reporte muestra todos los huéspedes que están registrados en el hotel en este momento. En este reporte se muestra la habitación ocupada por el huésped, el estado de la reserva, la fecha de salida y el número de teléfono principal importante para comunicarse con el cliente mediante medios digitales como el WhatsApp.
SELECT a.room, a.room_category_label, trim(initcap(a.guest_first_name)) || ' ' || trim(initcap(a.sname)) As NamePax, a.resv_status, a.arrival, a.departure, trim(a.company_name) || ' ' || a.travel_agent_name As NameCiaAgent, a.rate_code, a.vip, ( select x.phone_number from ( select m.phone_number, m.name_id, row_number() over (partition by m.name_id order by m.display_seq ASC) as row_num from opera.name_phone m ) x where x.row_num = 1 and x.name_id = a.guest_name_id ) phone_number FROM reservation_general_view a WHERE ( a.resv_status = 'CHECKED IN' or a.resv_status = 'DUE OUT' ) AND ( a.room BETWEEN '0000' and '1499' ) ORDER BY a.room |
Utilizaremos la vista “reservation_general_view”, esta vista posee el query necesario para extraer los datos de todas las reservas de los clientes, en sus diferentes estados:
Ejecutamos esta consulta en el entorno de desarrollo Oracle SQL Developer para validar que la consulta funciona adecuadamente.
Es importante indicar que el número de teléfono del huésped debe estar registrado adecuadamente en la sección “Communications” el “Profile” del huésped
Ejecutamos el programa de diseño Oracle Reports Developer
Se mostrará el Builder
Conectamos a la base de datos el builder, para esto seleccionamos el menú “File” opción de menú “Connect...”,
Se mostrará el asistente de coneccion a la base de datos donde debe colocar el User, Password y el nombre de instancia de la base de datos Oracle. luego haga click en el boton de opcion “Connect” para conectarse a la base de datos.
Seleccione el Menú “File” opción de menú “New” / “Report…”, se mostrará el asistente “New Report”. seleccione la opción “Use the Report Wizard” y click en el boton de opcion OK
Se mostrará el asistente “Report Wizard!”, realice click en el botón de opción “Next >”
Mantenga la opción “Create both Web and Paper Layout” seleccionada por defecto y realice click en el botón “Next >”
Colocamos la denominación del reporte “Reporte de listado de huéspedes en Casa” y hacemos click en el botón “Next >”.
Seleccionamos la opción “SQL Query” y hacemos click en la opción “Next >”.
En la pantalla Data Source definition colocamos el SQL Query que permite la extracción de datos de las reservas y hacemos click en la opción “Next >”.
Seleccionamos todos los campos del Query que se mostrarán en el reporte y hacemos click en la opción “Next >”.
En la pantalla del cálculo de campos totalizados no es necesario totalizar por un determinado campo, hacemos click en la opción “Next >”.
En esta pantalla mantenemos el ancho de las etiquetas y hacemos click en la opción “Next >”
Seleccionamos una plantilla de reporte y hacemos click en la opción “Next >”
Hacemos click en finish para luego previsualizar el diseño del reporte
Se mostrará el prediseño del reporte de la siguiente manera
Compilamos el reporte haciendo click en el menú “Compilar”, opción de menú “All..”
Click en Ok para confirmar el proceso de compilación.
Luego de compilar el reporte es importante exportar el archivo del reporte en formato .rep, formato que se podrá ser utilizado desde el Opera.
Se debe colocar los archivos del reporte .rep en la carpeta runtimes\ que se encuentra en la siguiente dirección: D:\MICROS\OPERA\production\runtimes\
Ingresamos al módulo de Configuración del Opera.
Seleccionamos las opciones de menú “Setup”, opción de Menú “Report Setup” opción “Reports”
Se mostrará la pantalla “Reports - Configuration”, hacer click en el botón “New”
En la pantalla “Reports - New” colocamos el nombre del reporte y seleccionamos un determinado “Report Group”.
Hacemos click en el botón de selecciones de lista asociado a “File Name”. en la pantalla “File List” buscamos el archivo de reporte .rep.
Nos aseguramos que el reporte custom_report_huespedes.rep se encuentre en la pantalla “Reports - Configuration”
Para mostrar el nuevo reporte seleccionamos el botón de opción “Miscelaneous”, opción “Reports”, se mostrará la pantalla “Reports”
En la pantalla “Reports” buscar el reporte “Custom Reporte Huespedes” y realiza click en el boton Ok
Se mostrará la pantalla “Report Parameters” y realice click en el botón “Preview”
Se mostrará el reporte personalizado
Descargar el articulo en PDF en el siguiente enlace:
oracle-opera-pms-hotel-hospitality_ESPAÑOL.pdf
oracle-opera-pms-hotel-hospitality_ENGLISH.pdf
oracle-opera-pms-hotel-hospitality.pdf
119806003-Micros-3700.pdf
123584668-Micros-RES-Reports.pdf
134046449-MIS-Support-Guide-for-Opera.pdf
142089179-Horiba-ABX-Micros-60-Technical-Manual.pdf
14416785-Food-and-Beverage-Sequence-Of-Service.pdf
17681305-1427-Opera-v5-0-1-NT-Database-Server-Install.pdf
216130000-Micros-Opera-Tds.pdf
259621330-EAME-OPERA-PMS-Utilities-Description-V4.pdf
266893889-Account-Receivable-Opera-5-0.pdf
271983447-Opera-Intro.pdf
276957979-Horiba-ABX-Micros-ES60-ESV60-Service-manual-pdf.pdf
303538176-Configuring-an-Opera-Workstation-on-Windows-8.pdf
304537328-Micross-Opera.pdf
49595815-Fidelio-Suite-7-Overview.pdf
51028269-01-Introduction-Opera-PMS-User-Guide-Version-4.pdf
55683862-FrontDesk-FIDELIO-Manual.pdf
67254636-Opsera-Configuration-on-Windows7-Client.pdf
72152409-Micros-3700-POS-Configurator-Manual.pdf
77887689-Micros-3700-User-Guide.pdf
78550062-9700-Setup-V300.pdf
92689259-Micros-Opera-Vision-XLExercises.pdf
Conceptos Basicos para Utilizar Opera.pdf
Data-Dictionary OPERA.pdf
guia+xml+boleta+version2-1.pdf
guia+xml+factura+version2-1.pdf
guia+xml+nota de credito+version2-1.pdf
hotelapp-beds-availability-source.zip
hotelapp-cost-controller-source.zip
hotelapp-e-invoice-source.zip
hotelapp-gosocket-source.zip
hotelapp-housekeeping-source.zip
hotelapp-json2xml-source.zip
hotelapp-kardex-source.zip
hotelapp-laundry-source.zip
hotelapp-reception-attach-source.zip
hotelapp-rooms-availability-source.zip
oracle-opera-pms-hotel-hospitality_ENGLISH.pdf
Manual Configuracion Impresoras y Print task.pdf
MICROS_9700_HMS_MAN_SQL.pdf
Opera-Cluster-instalacion-espanol.pdf
Opera-V4-PMS-Top-Reports-Description-1-pdf.pdf
Opera_V4_Users_Guide.pdf
oracle-opera-pms-hotel-hospitality_ENGLISH.pdf
259621330-EAME-OPERA-PMS-Utilities-Description-V4.pdf
Opera V5.5 - Workstation Setup Guide.pdf
Hotels-2025-LAD-tecnologias-emergentes.pdf
biblioteca-digital-uml-diseno-desarrollo-sistema.pdf
desarrollo-despliegue-java-spring-aws-amazon.pdf
certificado-digital-gratis-facturacion-electronica-sunat.pdf
sistema-recaudacion-tributaria-municipal-peru.pdf
manual-modulo-caja-sistema-recaudacion-tributaria-municipal-peru.pdf
manual-modulo-cobranza-coactiva-sistema-recaudacion-tributaria-municipal-peru.pdf
manual-modulo-control-cobranza-ordinaria-sistema-recaudacion-tributaria-municipal-peru.pdf
manual-modulo-fiscalizacion-tributaria-sistema-recaudacion-tributaria-municipal-peru.pdf
manual-modulo-fraccionamiento-deuda-tributaria-sistema-recaudacion-tributaria-municipal-peru.pdf
manual-modulo-registro-contribuyente-sistema-recaudacion-tributaria-municipal-peru.pdf
manual-modulo-registro-determinacion-predial-sistema-recaudacion-tributaria-municipal-peru.pdf
manual-modulo-tramite-documentario-sistema-recaudacion-tributaria-municipal-peru.pdf
create or replace OPERA.PROCEDURE TRAINING.HLD_SP_OP_SALES_DETAIL IS v_ddate_process DATE:=(SYSDATE-1); BEGIN INSERT INTO TRAINING.HLD_PASEOPDT( RESORT, BILL_GENERATION_DATE, INSERT_DATE, INSERT_DATE_HHMM , FOLIO_TYPE_CODE , FOLIO_TYPE_DESC , FISCAL_BILL_NO_SERIE , FISCAL_BILL_NO , TRX_DATE , ROOM , RESV_NAME , TC_GROUP , TC_SUBGROUP , TRX_CODE , DESCRIPTION , QUANTITY , PRICE_PER_UNIT , POSTED_AMOUNT , CURRENCY , EXCHANGE_RATE , BOF_CODE1 , REMARK ) SELECT rpad(ft1.RESORT,8) RESORT, to_char(ft1.BILL_GENERATION_DATE,'DD/MM/YYYY') BILL_GENERATION_DATE, to_char(ft1.INSERT_DATE,'DD/MM/YYYY') INSERT_DATE, rpad(to_char(ft1.INSERT_DATE,'HH24:MI:SS'),8) INSERT_DATE_HHMM, rpad(DECODE(ft1.FOLIO_TYPE,'BOLETA','03','BOLEXSRV', '03','FACTURA','01','FAEXON', '01','FACEXSRV','01','FOL', '00','FOLEX','00','NCBOL', '07','NCBOLEXSRV','07','NCFAC', '07','NCFACEXIGV','07','NCFACEXSRV', '07','NCFOL','00','NCFOLEX', '00','??'),2) FOLIO_TYPE_CODE, rpad(DECODE(ft1.FOLIO_TYPE,'BOLETA','BV','BOLEXSRV', 'BV','FACTURA','FA','FAEXON', 'FA','FACEXSRV','FA','FOL', 'FO','FOLEX','FO','NCBOL', 'NC','NCBOLEXSRV','NC','NCFAC', 'NC','NCFACEXIGV','NC','NCFACEXSRV', 'NC','NCFOL','NF','NCFOLEX', 'NF','??'),2) FOLIO_TYPE_DESC, rpad(nvl(ft1.FISCAL_BILL_NO,' '),4) FISCAL_BILL_NO_SERIE, lpad(SUBSTR(ft1.FISCAL_BILL_NO,6,7),7,'0') FISCAL_BILL_NO, to_char(ft2.TRX_DATE,'DD/MM/YYYY') TRX_DATE, rpad(ft1.ROOM,4) ROOM, rpad(ft1.RESV_NAME_ID,8) RESV_NAME, rpad(nvl(ft2.TC_GROUP,' '),2) TC_GROUP, rpad(nvl(ft2.TC_SUBGROUP,' '),3) TC_SUBGROUP, rpad(ft2.TRX_CODE,4) TRX_CODE, rpad(nvl(trc.DESCRIPTION,' '),40) DESCRIPTION, rpad(nvl(to_char(ft2.QUANTITY),' '),2) QUANTITY, rpad(to_char(ft2.PRICE_PER_UNIT,'999999D00'),10) PRICE_PER_UNIT, rpad(to_char(ft2.POSTED_AMOUNT,'999999D00'),10) POSTED_AMOUNT, decode(ft2.currency,'USD','D','PNS','S', ' ') CURRENCY, to_char(ROUND(nvl(multi_currency.get_exchange_rate(R.CURRENCY_CODE,1,'PNS','P',ft2.TRX_DATE,ft2.resort),0),2), '999990D00') EXCHANGE_RATE, rpad(nvl(BO.BOF_CODE1,' '),9,' ') BOF_CODE1, rpad(nvl(ft2.remark,' '),50,' ') REMARK FROM OPERA.FOLIO_TAX ft1, OPERA.NAME N, OPERA.RESERVATION_NAME RES_N, OPERA.FINANCIAL_TRANSACTIONS ft2, OPERA.RESORT R, OPERA.BOF$INTSETUP BO, OPERA.TRX$_CODES trc WHERE TO_CHAR(ft1.BILL_GENERATION_DATE,'DD-MM-RRRR') = to_char(v_ddate_process,'DD-MM-RRRR') AND ft1.FOLIO_TYPE = ft2.FOLIO_TYPE AND n.NAME_ID = ft1.payee_NAME_ID AND res_n.RESORT(+) = ft1.RESORT AND res_n.RESV_NAME_ID(+) = ft1.RESV_NAME_ID AND ft2.FOLIO_NO = ft1.FOLIO_NO AND ft2.BILL_NO = ft1.BILL_NO AND ft2.PACKAGE_CREDIT IS NULL AND ft2.PACKAGE_DEBIT IS NULL AND ft2.DISPLAY_YN ='Y' AND R.RESORT = ft1.RESORT AND BO.BOF_INTF_CODE(+) = 1 AND BO.RESORT(+) = ft2.RESORT AND BO.BOF_TRX_CODE(+) = ft2.TRX_CODE AND trc.TRX_CODE(+) = ft2.TRX_CODE AND ft2.PRICE_PER_UNIT <> 0 ORDER BY ft1.QUEUE_NAME, ft1.BILL_NO, ft2.TRX_DATE, ft2.TRX_CODE; COMMIT; END;
create or replace PROCEDURE TRAINING.HLD_SP_OP_SALES_HEADER IS ID_CURRENT NUMBER; NUM_ROWS NUMBER; ID_CURRENT_END NUMBER; v_ddate_process DATE:=(SYSDATE-1); BEGIN select MAX(ID_CURRENT) INTO ID_CURRENT from training.hld_serie_mes where periodo=extract(YEAR from v_ddate_process) and mes=extract(MONTH from v_ddate_process); IF ID_CURRENT IS NULL THEN ID_CURRENT:=0; END IF; SELECT COUNT(1) INTO NUM_ROWS FROM OPERA.FOLIO_TAX ft1, OPERA.NAME n, OPERA.RESERVATION_NAME res_n, OPERA.RESORT r, OPERA.NAME_view n2 WHERE TO_CHAR(ft1.BILL_GENERATION_DATE,'DD-MM-RRRR') = to_char(v_ddate_process,'DD-MM-RRRR') and res_n.RESORT(+) = ft1.RESORT and res_n.RESV_NAME_ID(+)= ft1.RESV_NAME_ID and n.NAME_ID(+)= ft1.PAYEE_NAME_ID and n2.NAME_ID(+)= ft1.NAME_ID and r.RESORT(+)= ft1.RESORT; ID_CURRENT_END:=NUM_ROWS+ID_CURRENT; update training.hld_serie_mes set ID_CURRENT =ID_CURRENT_END where periodo=extract(YEAR from v_ddate_process) and mes=extract(MONTH from v_ddate_process); DELETE FROM TRAINING.HLD_PASEOPCB; INSERT INTO TRAINING.HLD_PASEOPCB( RESORT, BILL_GENERATION_DATE, INSERT_DATE, INSERT_DATE_HHMM, FOLIO_TYPE_CODE, FOLIO_TYPE_DESC, FOLIO_TYPE, FISCAL_BILL_NO_SERIE, FISCAL_BILL_NO, CLIENT, TAX1_NO, BLANK, CURRENCY_CODE, TOTAL_NET_PNS, TAX1_AMT_PNS, TAX2_AMT_PNS, TOTAL_GROSS_PNS, EXCHANGE_RATE, TOTAL_NET_USD, TAX1_AMT_USD, TAX2_AMT_USD, TOTAL_GROSS_USD, STATUS, RESV_NAME_ID, ROOM, INSERT_USER, INSERT_USER_ID, BLANK_1, ID_TYPE_DOCUMENTO, NRO_DOCUMENTO, NAME_CLIENT ) SELECT rpad(ft1.resort,8) resort, to_char(ft1.BILL_GENERATION_DATE,'DD/MM/YYYY') BILL_GENERATION_DATE, to_char(ft1.INSERT_DATE,'DD/MM/YYYY') INSERT_DATE, rpad(to_char(ft1.INSERT_DATE,'HH24:MI:SS'),8) INSERT_DATE_HHMM, rpad(DECODE(ft1.folio_type,'BOLETA','03','BOLETA', '03','FACTURA','01','FAEXON', '01','FACEXSRV','01','FOL', '00','FOLEX','00','BOLNC', '07','NCBOLEXSRV','07','FACNC', '07','FAENC','07','NCFACEXSRV', '07','NCFOL','00','NCFOLEX', '00','??'),2) folio_type_code, rpad(DECODE(ft1.folio_type,'BOLETA','BV','BOLETA', 'BV','FACTURA','FA','FAEXON', 'FA','FACEXSRV','FA','FOL', 'FO','FOLEX','FO','BOLNC', 'NC','NCBOLEXSRV','NC','FACNC', 'NC','FAENC','NC','NCFACEXSRV', 'NC','NCFOL','NF','NCFOLEX', 'NF','??'),2) folio_type_desc, rpad(nvl(ft1.FOLIO_TYPE,' '),10) FOLIO_TYPE, rpad(nvl(ft1.FISCAL_BILL_NO,' '),4) FISCAL_BILL_NO_SERIE, LPAD(SUBSTR(FT1.FISCAL_BILL_NO,6,7),7,'0') FISCAL_BILL_NO, rpad(DECODE(n.NAME_TYPE,'COMPANY',upper(n.COMPANY||' '||n.NAME2||' '||n.NAME3),'TRAVEL_AGENT',upper(n.COMPANY||' '||n.NAME2||' '||n.NAME3),'S',upper(n.COMPANY||' '||n.NAME2||' '||n.NAME3),'G',upper(n.SNAME),'D',upper(n.SNAME||' '||n.FIRST),' '),60) CLIENT, rpad(nvl(n.TAX1_NO,' '),11) TAX1_NO, '-' blank, decode(r.CURRENCY_CODE,'USD','D','PNS','S', '??') CURRENCY_CODE, to_char(round(nvl(multi_currency.get_exchange_rate(r.CURRENCY_CODE,ft1.TOTAL_NET,'PNS', 'P',ft1.BILL_GENERATION_DATE,ft1.resort),0),2),'99999990D00') TOTAL_NET_PNS, to_char(round(nvl(multi_currency.get_exchange_rate(r.CURRENCY_CODE,ft1.TAX1_AMT,'PNS', 'P',ft1.BILL_GENERATION_DATE,ft1.resort),0),2),'99999990D00') TAX1_AMT_PNS, to_char(round(nvl(multi_currency.get_exchange_rate(r.CURRENCY_CODE,ft1.TAX2_AMT,'PNS', 'P',ft1.BILL_GENERATION_DATE,ft1.resort),0),2),'99999990D00') TAX2_AMT_PNS, to_char(round(nvl(multi_currency.get_exchange_rate(r.CURRENCY_CODE,ft1.TOTAL_GROSS,'PNS', 'P',ft1.BILL_GENERATION_DATE,ft1.resort),0),2),'99999990D00') TOTAL_GROSS_PNS, to_char(multi_currency.get_exchange_rate(R.CURRENCY_CODE,NULL,'PNS','P',ft1.BILL_GENERATION_DATE,ft1.RESORT), '9990D000') EXCHANGE_RATE, to_char(round(nvl(ft1.TOTAL_NET,0),2),'99999990D00') TOTAL_NET_USD, to_char(round(nvl(ft1.TAX1_AMT,0),2),'99999990D00') TAX1_AMT_USD, to_char(round(nvl(ft1.TAX2_AMT,0),2),'99999990D00') TAX2_AMT_USD, to_char(round(nvl(ft1.TOTAL_GROSS,0),2),'99999990D00') TOTAL_GROSS_USD, rpad(ft1.STATUS,4) STATUS, rpad(ft1.RESV_NAME_ID,8) RESV_NAME_ID, rpad(ft1.ROOM,4) ROOM, rpad(nvl(user_log.USER_NAME(ft1.INSERT_USER),' '),15) INSERT_USER, rpad(ft1.INSERT_USER,2) INSERT_USER_ID, '-' blank_1, (select nd.id_type from name_documents nd where nd.name_id = ft1.name_id and nd.primary_yn='Y') id_type_documento, '-' nro_documento, (n2.sfirst||' '||n2.sname) name_client FROM OPERA.FOLIO_TAX ft1, OPERA.NAME n, OPERA.RESERVATION_NAME res_n, OPERA.RESORT r, OPERA.NAME_view n2 WHERE TO_CHAR(ft1.BILL_GENERATION_DATE,'DD-MM-RRRR') = to_char(v_ddate_process,'DD-MM-RRRR') and res_n.RESORT(+) = ft1.RESORT and res_n.RESV_NAME_ID(+)= ft1.RESV_NAME_ID and n.NAME_ID(+)= ft1.PAYEE_NAME_ID and n2.NAME_ID(+)= ft1.NAME_ID and r.RESORT(+)= ft1.RESORT ORDER BY ft1.QUEUE_NAME, ft1.BILL_NO; COMMIT; END;
create or replace PROCEDURE TRAINING.HLD_SP_OPERA_SALES IS --M CURSOR C_HLD_PASEOPCB IS SELECT resort,--1 bill_generation_date,--2 insert_date,--3 insert_date_hhmm,--4 folio_type_code,--5 folio_type_desc,--6 folio_type,--7 fiscal_bill_no_serie,--8 fiscal_bill_no,--9 client,--10 tax1_no,--11 --> RUC blank,--12 currency_code,--13 total_net_pns,--14 tax1_amt_pns,--15 tax2_amt_pns,--16 total_gross_pns,--17 exchange_rate,--18 total_net_usd,--19 tax1_amt_usd,--20 tax2_amt_usd,--21 total_gross_usd,--22 status,--23 resv_name_id,--24 room,--25 insert_user,--26 insert_user_id,--27 blank_1,--28 id_type_documento,--29 nro_documento,--30 name_client--31 FROM training.hld_paseopcb WHERE TRIM(folio_type_desc) NOT IN ('FO','NF','??') AND fiscal_bill_no_serie IS NOT NULL AND fiscal_bill_no IS NOT NULL ORDER BY fiscal_bill_no_serie asc, fiscal_bill_no asc ; v_ddate_process DATE:=(SYSDATE-1); v_T NUMERIC(12,2); v_x VARCHAR2(10); v_TOTDOL NUMERIC(12,2); v_TOTSOL NUMERIC(12,2); xxtpc NUMERIC(19,4); flagco VARCHAR2(1); nuruc VARCHAR2(20); v_nucomp VARCHAR2(8); v_fecomp DATE; v_nrpcta VARCHAR2(9); v_tpmone VARCHAR2(1); v_dsglos VARCHAR2(500); v_tpdocu VARCHAR2(2); v_nuseri VARCHAR2(4); v_nudocu VARCHAR2(8); v_fedocu DATE; v_imafec VARCHAR2(1); v_tpmovi VARCHAR2(1); v_imdola NUMBER(19,2); v_imsole NUMBER(19,2); v_tpcamb NUMBER(19,4); v_nuruc VARCHAR2(20); v_tpccte VARCHAR2(2); v_nuccte VARCHAR2(6); v_bvnombre VARCHAR2(500); v_referen VARCHAR2(60); v_tidoci VARCHAR2(20); v_dociden VARCHAR2(20); v_tpdocr VARCHAR2(2); v_nuserr VARCHAR2(4); v_nudocr VARCHAR2(8); v_flagx VARCHAR2(1); v_flagco VARCHAR2(1); TMP_NUCOMP VARCHAR2(8); TMP_FECOMP DATE; TMP_NRPCTA VARCHAR2(9); TMP_TPMONE VARCHAR2(1); TMP_DSGLOS VARCHAR2(500); TMP_TPDOCU VARCHAR2(2); TMP_NUSERI VARCHAR2(4); TMP_NUDOCU VARCHAR2(8); TMP_FEDOCU DATE; TMP_IMAFEC VARCHAR2(1); TMP_TPMOVI VARCHAR2(1); TMP_IMDOLA NUMBER(19,2); TMP_IMSOLE NUMBER(19,2); TMP_TPCAMB NUMBER(5,3); TMP_NURUC VARCHAR2(20); TMP_TPCCTE VARCHAR2(2); TMP_NUCCTE VARCHAR2(6); TMP_BVNOMBRE VARCHAR2(500); TMP_REFEREN VARCHAR2(60); TMP_TIDOCI VARCHAR2(20); TMP_DOCIDEN VARCHAR2(20); TMP_TPDOCR VARCHAR2(2); TMP_NUSERR VARCHAR2(4); TMP_NUDOCR VARCHAR2(8); TMP_FLAGX VARCHAR2(1); TMP_FLAGCO VARCHAR2(1); TMP2_NUCOMP VARCHAR2(8); TMP2_FECOMP DATE; TMP2_NRPCTA VARCHAR2(9); TMP2_TPMONE VARCHAR2(1); TMP2_DSGLOS VARCHAR2(40); TMP2_TPDOCU VARCHAR2(2); TMP2_NUSERI VARCHAR2(4); TMP2_NUDOCU VARCHAR2(8); TMP2_FEDOCU DATE; TMP2_IMAFEC VARCHAR2(1); TMP2_TPMOVI VARCHAR2(1); TMP2_IMDOLA NUMBER(19,2); TMP2_IMSOLE NUMBER(19,2); TMP2_TPCAMB NUMBER(5,3); TMP2_NURUC VARCHAR2(11); TMP2_BVNOMBRE VARCHAR2(50); TMP2_REFEREN VARCHAR2(60); TMP2_TIDOCI VARCHAR2(20); TMP2_DOCIDEN VARCHAR2(20); TMP2_TPDOCR VARCHAR2(2); TMP2_NUSERR VARCHAR2(4); TMP2_NUDOCR VARCHAR2(8); vnum NUMERIC := 0 ;--XVNUMERO; CORRELATIVO xfecha DATE:=v_ddate_process; xnumeroc VARCHAR2(6); c_csubdia varchar2(10); c_ccompro varchar2(10); c_cfeccom varchar2(10); c_ccodmon varchar2(10); c_csitua varchar2(10); c_ctipcam number(6,2); c_cglosa varchar2(50); c_ctotal number(19,2); c_ctipo varchar2(10); c_cflag varchar2(10); c_cdate DATE; c_chora TIMESTAMP; c_cfeccam varchar2(10); c_cuser varchar2(10); c_corig varchar2(10); c_cform varchar2(10); c_ctipcom varchar2(10); c_cextor varchar2(10); znum NUMERIC:=0; d_DSUBDIA VARCHAR2(4); d_DCOMPRO VARCHAR2(6); d_DSECUE VARCHAR2(4); d_DFECCOM VARCHAR2(6); d_DCUENTA VARCHAR2(12); d_DCODANE VARCHAR2(18); d_DCENCOS VARCHAR2(6); d_DCODMON VARCHAR2(2); d_DDH VARCHAR2(1); d_DIMPORT NUMBER(19,2); d_DTIPDOC VARCHAR2(2); d_DNUMDOC VARCHAR2(20); d_DFECDOC VARCHAR2(6); d_DFECVEN VARCHAR2(6); d_DAREA VARCHAR2(3); d_DFLAG VARCHAR2(1); d_DXGLOSA VARCHAR2(50); d_DDATE DATE; d_DCODANE2 VARCHAR2(18); d_DUSIMPOR NUMBER(19,2); d_DMNIMPOR NUMBER(19,2); d_DCODARC VARCHAR2(2); d_FLAGX VARCHAR2(1); d_DMEDPAG VARCHAR2(8); d_DIGVCOM NUMBER(19,2); d_DTIDREF VARCHAR2(2); d_DNDOREF VARCHAR2(30); d_DFECREF DATE; d_DBIMREF NUMBER(19,2); d_DIGVREF NUMBER(19,2); d_DMAQREF VARCHAR2(20); x_AVANEXO VARCHAR2(1); x_ACODANE VARCHAR2(18); x_ADESANE VARCHAR2(40); x_AREFANE VARCHAR2(50); x_ARUC VARCHAR2(18); x_ACODMON VARCHAR2(2); x_AESTADO VARCHAR2(1); x_ADATE DATE; x_AHORA VARCHAR2(6); x_APATERNO VARCHAR2(20); x_AMATERNO VARCHAR2(20); x_ANOMBRE VARCHAR2(20); x_AFORMSUS VARCHAR2(8); x_ATELEFO VARCHAR2(30); x_ATIPTRA VARCHAR2(1); x_APROVIN VARCHAR2(30); x_ADEPART VARCHAR2(30); x_APAIS VARCHAR2(30); x_AZONPOS VARCHAR2(10); x_ANOMREP VARCHAR2(40); x_ACARREP VARCHAR2(20); x_AEMAIL VARCHAR2(80); x_AHOST VARCHAR2(80); x_ADOCIDE VARCHAR2(2); --//CONTADOR v_znumero NUMBER:=0; v_year number; v_month number; v_dyesterday_process DATE; v_yesterday_month NUMBER; v_znumero_ini NUMBER; v_znumero_fin NUMBER; --- CANT_ZNUM NUMBER:=0; -- V_NRO_DOCUMENTO VARCHAR(20); CANT_NRODOC NUMBER; BEGIN DELETE FROM TRAINING.hld_paseopdt WHERE TRIM(description)='Cuentas por Cobrar'; DELETE FROM TRAINING.hld_paseopdt WHERE TRIM(description)='Nota de Credito'; DELETE FROM TRAINING.hld_paseopdt WHERE TRIM(description)='Tarjeta de Debito Soles'; DELETE FROM TRAINING.hld_paseopdt WHERE TRIM(description)='Tarjeta de Debito Dolares'; DELETE FROM TRAINING.hld_paseopdt WHERE TRIM(description)='Currency Check Exch Paidout'; DELETE FROM TRAINING.hld_paseopdt WHERE TRIM(folio_type_desc)='FO'; DELETE FROM TRAINING.hld_paseopdt WHERE TRIM(folio_type_desc)='NF'; DELETE FROM TRAINING.hld_paseopdt WHERE TRIM(folio_type_desc)='??'; /* Filtrado en el cursor C_HLD_PASEOPCB DELETE FROM TRAINING.hld_paseopcb WHERE TRIM(folio_type_desc)='FO'; DELETE FROM TRAINING.hld_paseopcb WHERE TRIM(folio_type_desc)='NF'; DELETE FROM TRAINING.hld_paseopcb WHERE TRIM(folio_type_desc)='??'; DELETE FROM TRAINING.hld_paseopcb WHERE fiscal_bill_no_serie IS NULL AND fiscal_bill_no IS NULL; */ DELETE FROM TRAINING.T_TMP; DELETE FROM TRAINING.T_TMP2; xxtpc:=3.250997; v_tpcamb:=xxtpc; FOR M IN C_HLD_PASEOPCB LOOP CANT_NRODOC:=0; --DETALLE IF TRIM(M.FOLIO_TYPE_DESC) ='FO' THEN v_T:=0; ELSE v_TOTSOL:=0; v_TOTDOL:=0; FOR T_OPERA IN ( SELECT D.resort,--1 D.bill_generation_date,--2 D.insert_date,--3 D.insert_date_hhmm,--4 D.folio_type_code,--5 D.folio_type_desc,--6 D.fiscal_bill_no_serie,--7 D.fiscal_bill_no,--8 D.trx_date,--9 D.room,--10 D.resv_name,--11 D.tc_group,--12 D.tc_subgroup,--13 D.trx_code,--14 D.description,--15 D.quantity,--16 D.price_per_unit,--17 D.posted_amount,--18 D.currency,--19 D.exchange_rate,--20 D.bof_code1,--21 D.remark--22 FROM TRAINING.HLD_PASEOPDT D WHERE TRIM(M.FISCAL_BILL_NO_SERIE)=TRIM(D.FISCAL_BILL_NO_SERIE) AND TRIM(M.FISCAL_BILL_NO)=TRIM(D.FISCAL_BILL_NO) ORDER BY D.fiscal_bill_no_serie ASC,D.fiscal_bill_no ASC,D.bof_code1 ASC, D.posted_amount ASC )LOOP v_nucomp:=LPAD(TRIM(M.fiscal_bill_no),8,'0'); v_x:=TRIM(M.bill_generation_date); v_fecomp:=TO_DATE(v_x,'DD/RR/YYYY'); v_nrpcta:=TRIM(T_OPERA.bof_code1); v_tpmone:=TRIM(M.currency_code); v_dsglos:= CASE WHEN (TRIM(T_OPERA.trx_code) = '1507' OR TRIM(T_OPERA.trx_code) = '1095') THEN 'A-'||TRIM(T_OPERA.remark) ELSE TRIM(T_OPERA.description) END; v_tpdocu:= TRIM(T_OPERA.folio_type_desc); v_nuseri:=LPAD(TRIM(T_OPERA.fiscal_bill_no_serie),4,'0'); v_nudocu := LPAD(TRIM(T_OPERA.fiscal_bill_no),7,'0'); v_fedocu := TO_DATE(v_x,'DD/RR/YYYY'); v_imafec := ''; v_bvnombre := CASE WHEN (TRIM(M.client)='ALOJAMIENTO EXONERADO') THEN TRIM(M.name_client)||' ' ||TRIM(M.nro_documento) ELSE M.client END; v_referen := TRIM(T_OPERA.remark); v_tpdocr := CASE WHEN SUBSTR(TRIM(T_OPERA.remark),18,2)='BO' THEN 'BV' ELSE SUBSTR(TRIM(T_OPERA.remark),18,2) END; v_nuserr := SUBSTR(TRIM(T_OPERA.remark),21,4); v_nudocr := SUBSTR(TRIM(T_OPERA.remark),26,8); v_dociden := M.nro_documento; v_tidoci := M.id_type_documento; v_flagx := CASE WHEN TRIM(M.folio_type)='FAEXON' THEN '1' ELSE '' END; IF M.blank_1 IS NULL THEN v_tpccte := '04'; IF M.blank_1 IN ('SUMM','TRAV','HDO', 'HOT','GUL','TWEB','EXPE') THEN CASE TRIM(M.blank_1) WHEN 'SUMM' THEN v_nuccte :='003195'; WHEN 'TRAV' THEN v_nuccte :='008819'; WHEN 'HDO' THEN v_nuccte :='008820'; WHEN 'HOT' THEN v_nuccte :='008818'; WHEN 'GUL' THEN v_nuccte :='008822'; WHEN 'TWEB' THEN v_nuccte :='008821'; WHEN 'EXPE' THEN v_nuccte :='008076'; END CASE; ELSE v_tpccte := '04'; v_nuccte := '007870'; END IF; --m.nuruc = iif(SEEK(m.tpccte+m.nuccte,"COMCCT01"),COMCCT01.nuruc2,allt(m.campo11)) v_nuruc:=TRIM(M.tax1_no); ELSE v_nuruc := CASE WHEN M.tax1_no IS NULL THEN M.nro_documento ELSE M.tax1_no END; IF M.tax1_no IS NULL and M.nro_documento IS NULL and TRIM(M.folio_type_desc)='BV' THEN v_nuruc := '22222222222'; END IF; END IF; --// SELECT COUNT(1) INTO CANT_NRODOC FROM TRAINING.hld_registro_gosocket r where TRIM(r.serie)=TRIM(M.fiscal_bill_no_serie) and TRIM(r.numero)=TRIM(M.fiscal_bill_no); IF CANT_NRODOC>0 THEN SELECT MAX(r.nro_documento) INTO V_NRO_DOCUMENTO FROM TRAINING.hld_registro_gosocket r where TRIM(r.serie)=TRIM(M.fiscal_bill_no_serie) and TRIM(r.numero)=TRIM(M.fiscal_bill_no); v_nuruc:=TRIM(V_NRO_DOCUMENTO); END IF; nuruc :=v_nuruc; TMP_NURUC:=v_nuruc; --// IF TRIM(M.folio_type_desc)='NC' THEN if TRIM(T_OPERA.currency)='D' then v_imdola:=T_OPERA.posted_amount; else v_imdola:=T_OPERA.posted_amount/v_tpcamb; end if; if TRIM(T_OPERA.currency)='S' then v_imdola:=T_OPERA.posted_amount; else v_imsole:=T_OPERA.posted_amount*v_tpcamb; end if; v_tpmovi := 'D'; ELSE If TO_NUMBER(T_OPERA.posted_amount) < 0 then if TRIM(T_OPERA.currency)='D' then v_imdola:=ABS(TO_NUMBER(T_OPERA.posted_amount)); else v_imdola:=ABS(TO_NUMBER(T_OPERA.posted_amount)/v_tpcamb); end if; if TRIM(T_OPERA.currency)='S' then v_imdola:=ABS(TO_NUMBER(T_OPERA.posted_amount)); else v_imsole:=ABS(TO_NUMBER(T_OPERA.posted_amount)*v_tpcamb); end if; if TRIM(M.folio_type_desc)='FA' then v_tpmovi:='D'; else if TRIM(M.folio_type_desc)='BV' then v_tpmovi:='D'; else v_tpmovi:='H'; end if; end if; ELSE if TRIM(T_OPERA.currency)='D' then v_imdola:=T_OPERA.posted_amount; else v_imdola:=T_OPERA.posted_amount/v_tpcamb; end if; if TRIM(T_OPERA.currency)='S' then v_imdola:=ABS(TO_NUMBER(T_OPERA.posted_amount)); else v_imsole:=ABS(TO_NUMBER(T_OPERA.posted_amount)*v_tpcamb); end if; if TRIM(M.folio_type_desc)='FA' then v_tpmovi:='H'; else if TRIM(M.folio_type_desc)='BV' then v_tpmovi:='H'; else v_tpmovi:='D'; end if; end if; END IF; END IF; IF LPAD(TRIM(T_OPERA.bof_code1),2)!='10' THEN tmp_nucomp:=v_nucomp; tmp_Fecomp :=v_fecomp; tmp_Nrpcta :=TRIM(T_OPERA.bof_code1); tmp_Tpmone :=TRIM(M.currency_code); tmp_Dsglos :=TRIM(v_dsglos); tmp_Imafec :=v_imafec; tmp_Tpmovi :=v_tpmovi; tmp_Imdola :=v_imdola; tmp_Imsole :=v_imsole; tmp_Tpcamb :=v_tpcamb; tmp_flagx :=v_flagx; tmp_tpdocu :=v_tpdocu; tmp_nuseri :=v_nuseri; tmp_nudocu :=v_nudocu; If v_tpmovi = 'D' then if m.folio_type_desc='NC' then v_Totdol := v_Totdol + CASE WHEN TRIM(t_opera.currency)='D' THEN abs(TO_NUMBER(t_opera.posted_amount)) ELSE abs(TO_NUMBER(t_opera.posted_amount)/v_tpcamb) END; v_Totsol := v_Totsol + CASE WHEN TRIM(t_opera.currency)='S' THEN abs(TO_NUMBER(t_opera.posted_amount)) ELSE abs(TO_NUMBER(t_opera.posted_amount)*v_tpcamb) END; Else v_Totdol := v_Totdol - CASE WHEN TRIM(t_opera.currency)='D' THEN abs(TO_NUMBER(t_opera.posted_amount)) ELSE abs(TO_NUMBER(t_opera.posted_amount)/v_tpcamb) END; v_Totsol := v_Totsol - CASE WHEN TRIM(t_opera.currency)='S' THEN abs(TO_NUMBER(t_opera.posted_amount)) ELSE abs(TO_NUMBER(t_opera.posted_amount)*v_tpcamb) END; End If; Else-- v_tpmovi= H v_Totdol := v_Totdol + CASE WHEN TRIM(t_opera.currency)='D' THEN abs(TO_NUMBER(t_opera.posted_amount)) ELSE abs(TO_NUMBER(t_opera.posted_amount)/v_tpcamb) END; v_Totsol := v_Totsol + CASE WHEN TRIM(t_opera.currency)='S' THEN abs(TO_NUMBER(t_opera.posted_amount)) ELSE abs(TO_NUMBER(t_opera.posted_amount)*v_tpcamb) END; End if; INSERT INTO TRAINING.T_TMP( NUCOMP, FECOMP , NRPCTA , TPMONE , DSGLOS , IMAFEC , TPMOVI , IMDOLA , IMSOLE , TPCAMB , FLAGX , TPDOCU , NUSERI , NUDOCU ) VALUES ( tmp_nucomp, tmp_Fecomp, tmp_Nrpcta, tmp_Tpmone, SUBSTR(tmp_Dsglos,1,40), tmp_Imafec, tmp_Tpmovi, tmp_Imdola, tmp_Imsole, tmp_Tpcamb, tmp_flagx, tmp_tpdocu, tmp_nuseri, tmp_nudocu ); COMMIT; ELSE tmp2_Nucomp := v_nucomp; tmp2_Fecomp := v_fecomp; tmp2_Nrpcta := TRIM(t_opera.bof_code1); tmp2_Tpmone := TRIM(m.currency_code); tmp2_Dsglos := TRIM(v_dsglos); tmp2_Tpmovi := 'D'; If (TRIM(t_opera.bof_code1)='103103' or TRIM(t_opera.bof_code1)='103104' or TRIM(t_opera.bof_code1)='103105' or TRIM(t_opera.bof_code1)='103106') and TRIM(t_opera.currency)='D' then tmp2_imdola := CASE WHEN TRIM(t_opera.currency)='D' THEN (abs(to_number(t_opera.posted_amount))*3.10)/xxtpc ELSE abs(to_number(t_opera.posted_amount)/xxtpc) END; tmp2_imsole := CASE WHEN TRIM(t_opera.currency)='S' THEN abs(to_number(t_opera.posted_amount)) ELSE abs(to_number(t_opera.posted_amount)*3.1) END; tmp2_tpcamb := xxtpc; Else If (TRIM(t_opera.bof_code1)='103103' or TRIM(t_opera.bof_code1)='103104' or TRIM(t_opera.bof_code1)='103105' or TRIM(t_opera.bof_code1)='103106') and TRIM(t_opera.currency)='S' then tmp2_imdola := CASE WHEN TRIM(t_opera.currency)='D' THEN (abs(to_number(t_opera.posted_amount))*3.10)/xxtpc ELSE abs(to_number(t_opera.posted_amount)/xxtpc) END; tmp2_imsole := CASE WHEN TRIM(t_opera.currency)='S' THEN abs(to_number(t_opera.posted_amount)) ELSE abs(to_number(t_opera.posted_amount)*3.1) END; tmp2_tpcamb := xxtpc; Else tmp2_imdola := CASE WHEN TRIM(t_opera.currency)='D' THEN abs(to_number(t_opera.posted_amount)) ELSE abs(to_number(t_opera.posted_amount)/xxtpc) END; tmp2_imsole := CASE WHEN TRIM(t_opera.currency)='S' THEN abs(to_number(t_opera.posted_amount)) ELSE abs(to_number(t_opera.posted_amount)*xxtpc) END; tmp2_tpcamb := v_tpcamb; End If; end if; INSERT INTO TRAINING.T_TMP2( NUCOMP , FECOMP , NRPCTA , TPMONE , DSGLOS , TPMOVI , IMDOLA , IMSOLE , TPCAMB ) VALUES( tmp2_Nucomp, tmp2_Fecomp, tmp2_Nrpcta, tmp2_Tpmone, tmp2_Dsglos, tmp2_Tpmovi, tmp2_imdola, tmp2_imsole, tmp2_tpcamb ); COMMIT; END IF; END LOOP; tmp_Nucomp :=v_nucomp; tmp_Fecomp := v_fecomp; tmp_Nrpcta := '121202'; tmp_Tpmone := TRIM(m.currency_code); tmp_Dsglos := CASE WHEN TRIM(m.client)='ALOJAMIENTO EXONERADO' THEN TRIM(m.name_client)||' ' ||TRIM(m.name_client) ELSE TRIM(m.client) END; tmp_Tpdocu := TRIM(m.folio_type_desc); tmp_Nuseri := LPAD(TRIM(m.fiscal_bill_no_serie),4,'0'); tmp_Nudocu := LPAD(TRIM(m.fiscal_bill_no),7,'0'); tmp_Fedocu := v_fecomp; tmp_Tpmovi := CASE WHEN TRIM(m.folio_type_desc)='FA' THEN 'D' ELSE CASE WHEN TRIM(m.folio_type_desc)='BV' THEN 'D' ELSE 'H' END END; --REVISAR LOS DECIMALES tmp_Imdola := v_Totdol; tmp_Imsole := v_Totsol; tmp_tpcamb := v_tpcamb; tmp_bvnombre := CASE WHEN TRIM(m.client)='ALOJAMIENTO EXONERADO' THEN TRIM(m.name_client)||' ' ||TRIM(m.name_client) ELSE TRIM(m.client) END; tmp_referen := v_referen; tmp_tpdocr := v_tpdocr; tmp_nuserr := v_nuserr; tmp_nudocr :=v_nudocr; tmp_dociden := TRIM(m.nro_documento); tmp_tidoci := TRIM(m.id_type_documento); if TRIM(m.fiscal_bill_no) = 'ctacob' then flagco := '1'; else flagco := ''; end if; if m.blank_1 is null then v_tpccte := '04'; IF TRIM(m.blank_1) IN ('SUMM','TRAV','HDO', 'HOT','GUL','TWEB','EXPE') then CASE TRIM(M.blank_1) WHEN 'SUMM' THEN v_nuccte :='003195'; WHEN 'TRAV' THEN v_nuccte :='008819'; WHEN 'HDO' THEN v_nuccte :='008820'; WHEN 'HOT' THEN v_nuccte :='008818'; WHEN 'GUL' THEN v_nuccte :='008822'; WHEN 'TWEB' THEN v_nuccte :='008821'; WHEN 'EXPE' THEN v_nuccte :='008076'; END CASE; ELSE v_tpccte := '04'; v_nuccte := '007870'; END IF; --m.nuruc = iif(SEEK(m.tpccte+m.nuccte,"COMCCT01"),COMCCT01.nuruc2,allt(m.campo11)) v_nuruc:=TRIM(M.tax1_no); else v_nuruc := CASE WHEN m.tax1_no IS NULL THEN m.nro_documento ELSE m.tax1_no END; if m.tax1_no IS NULL and m.nro_documento is NULL and TRIM(m.folio_type_desc)='BV' then v_nuruc := '22222222222'; end if; End if; --// SELECT COUNT(1) INTO CANT_NRODOC FROM TRAINING.hld_registro_gosocket r where TRIM(r.serie)=TRIM(M.fiscal_bill_no_serie) and TRIM(r.numero)=TRIM(M.fiscal_bill_no); IF CANT_NRODOC>0 THEN SELECT MAX(r.nro_documento) INTO V_NRO_DOCUMENTO FROM TRAINING.hld_registro_gosocket r where TRIM(r.serie)=TRIM(M.fiscal_bill_no_serie) and TRIM(r.numero)=TRIM(M.fiscal_bill_no); v_nuruc:=TRIM(V_NRO_DOCUMENTO); END IF; nuruc :=v_nuruc; TMP_NURUC:=v_nuruc; --// INSERT INTO TRAINING.T_TMP( NUCOMP , FECOMP , NRPCTA , TPMONE , DSGLOS , TPDOCU , NUSERI , NUDOCU , FEDOCU , TPMOVI , IMDOLA , IMSOLE , TPCAMB , BVNOMBRE , REFEREN , TIDOCI , DOCIDEN , TPDOCR , NUSERR , NUDOCR , FLAGCO , NURUC ) VALUES ( tmp_Nucomp, tmp_Fecomp , tmp_Nrpcta , tmp_Tpmone , SUBSTR(tmp_Dsglos,1,40), tmp_Tpdocu , tmp_Nuseri , tmp_Nudocu , tmp_Fedocu , tmp_Tpmovi , tmp_Imdola , tmp_Imsole , tmp_tpcamb , SUBSTR(tmp_bvnombre,1,50), SUBSTR(tmp_referen,1,60), tmp_tidoci , tmp_dociden , tmp_tpdocr , tmp_nuserr , tmp_nudocr , tmp_flagco , tmp_nuruc ); COMMIT; END IF; END LOOP; UPDATE TRAINING.T_TMP SET nrpcta ='469203' WHERE TRIM(dsglos)='Currency Check Exch Paidout'; UPDATE TRAINING.T_TMP SET nrpcta ='469203' WHERE TRIM(dsglos)='Currency Check Exch Paidout'; UPDATE TRAINING.T_TMP SET nrpcta ='707101' WHERE TRIM(dsglos)='Delphos Cena Covers'; UPDATE TRAINING.T_TMP SET nrpcta ='707101' WHERE TRIM(dsglos)='Delphos Desayuno Covers'; UPDATE TRAINING.T_TMP SET nrpcta ='707101' WHERE TRIM(dsglos)='Delphos Almuerzo Covers'; UPDATE TRAINING.T_TMP SET nrpcta ='707101' WHERE TRIM(dsglos)='Dolphin Bar Covers'; UPDATE TRAINING.T_TMP SET nrpcta ='704131' WHERE TRIM(dsglos)='Knossos Almuerzo Covers'; UPDATE TRAINING.T_TMP SET nrpcta ='704131' WHERE TRIM(dsglos)='Knossos Cena Covers'; UPDATE TRAINING.T_TMP SET nrpcta ='103500' WHERE TRIM(dsglos)='Deposito en Banco Dolares'; UPDATE TRAINING.T_TMP SET nrpcta ='103500' WHERE TRIM(dsglos)='Deposito en Banco Soles'; DELETE FROM TRAINING.T_DETA; INSERT INTO TRAINING.T_DETA(tpdocu, nuseri, nucomp, fecomp, nrpcta,tpmovi, tpmone, dsglos, nudocu, fedocu, imafec, imdola, imsole, tpcamb, nuruc, tpccte, nuccte, bvnombre, dociden, tidoci, referen, tpdocr, nuserr, nudocr, flagx, flagco) SELECT tpdocu, nuseri, nucomp, fecomp, nrpcta, tpmovi, MAX(tpmone), MAX(dsglos), MAX(TRIM(nudocu)), MAX(fedocu), MAX(imafec), sum(imdola), sum(imsole), MAX(tpcamb), MAX(nuruc), MAX(tpccte), MAX(nuccte), MAX(bvnombre), MAX(dociden), MAX(tidoci), MAX(referen), MAX(tpdocr), MAX(nuserr), MAX(nudocr), MAX(flagx), MAX(flagco) FROM TRAINING.T_TMP GROUP BY tpdocu, nuseri, nucomp, fecomp, nrpcta, tpmovi; COMMIT; DELETE FROM TRAINING.T_CABE; INSERT INTO TRAINING.T_CABE(tpdocu, nuseri, nucomp, fecomp) SELECT DISTINCT tpdocu, nuseri, nucomp, fecomp FROM TRAINING.T_DETA; COMMIT; DELETE FROM TRAINING.T_FACT; INSERT INTO TRAINING.T_FACT(NUCOMP, FECOMP, NRPCTA, TPMONE, DSGLOS, TPDOCU, NUSERI, NUDOCU, FEDOCU, IMAFEC, TPMOVI, IMDOLA, IMSOLE, TPCAMB, NURUC, TPCCTE, NUCCTE, BVNOMBRE, REFEREN, TIDOCI, DOCIDEN, TPDOCR, NUSERR, NUDOCR, FLAGX, FLAGCO) select NUCOMP, FECOMP, NRPCTA, TPMONE, DSGLOS, TPDOCU, NUSERI, NUDOCU, FEDOCU, IMAFEC, TPMOVI, IMDOLA, IMSOLE, TPCAMB, NURUC, TPCCTE, NUCCTE, BVNOMBRE, REFEREN, TIDOCI, DOCIDEN, TPDOCR, NUSERR, NUDOCR, FLAGX, FLAGCO from TRAINING.T_DETA where SUBSTR(nrpcta,1,3)='121'; DELETE FROM TRAINING.T_CANC; INSERT INTO TRAINING.T_CANC(nrpcta,tpmovi, nucomp, fecomp, tpmone, dsglos, tpdocu, nuseri, nudocu, fedocu, imafec, imdola, imsole, tpcamb) select nrpcta,tpmovi, MAX(nucomp), MAX(fecomp), MAX(tpmone), MAX(dsglos), MAX(tpdocu), MAX(nuseri), MAX(nudocu), MAX(fedocu), MAX(imafec), sum(imdola), sum(imsole), MAX(tpcamb) from TRAINING.T_TMP2 group by nrpcta,tpmovi; --//CONTADOR:INICIO select EXTRACT(YEAR FROM (v_ddate_process)) into v_year FROM DUAL; select EXTRACT(MONTH FROM (v_ddate_process)) into v_month FROM DUAL; select (v_ddate_process-1) into v_dyesterday_process FROM DUAL; select EXTRACT(MONTH FROM (v_dyesterday_process)) into v_yesterday_month FROM DUAL; v_znumero_ini:=NULL; DELETE FROM TRAINING.ZNUMERO z WHERE to_char(z.zdate_process,'DD-MM-RRRR')=to_char(v_ddate_process,'DD-MM-RRRR'); IF v_month<>v_yesterday_month THEN v_znumero_ini:=1; ELSE SELECT COUNT(1) INTO CANT_ZNUM FROM TRAINING.ZNUMERO z WHERE to_char(z.zdate_process,'DD-MM-RRRR')=to_char(v_dyesterday_process, 'DD-MM-RRRR'); IF CANT_ZNUM<>0 THEN SELECT (z.znumero_fin+1) INTO v_znumero_ini FROM TRAINING.ZNUMERO z WHERE to_char(z.zdate_process,'DD-MM-RRRR')=to_char(v_dyesterday_process, 'DD-MM-RRRR'); ELSE v_znumero_ini:=1; END IF; END IF; IF v_znumero_ini IS NULL THEN v_znumero_ini:=1; END IF; v_znumero:=v_znumero_ini; --//CONTADOR:FIN DELETE FROM TRAINING.T_DREAL; DELETE FROM TRAINING.T_CREAL; FOR CABE IN ( SELECT NUCOMP, FECOMP, NRPCTA, TPMONE, DSGLOS, TPDOCU, NUSERI, NUDOCU, FEDOCU, IMAFEC, TPMOVI, IMDOLA, IMSOLE, TPCAMB, NURUC, TPCCTE, NUCCTE, BVNOMBRE, REFEREN, TIDOCI, DOCIDEN, TPDOCR, NUSERR, NUDOCR, FLAGX, FLAGCO FROM TRAINING.T_CABE ORDER BY NUSERI ASC,NUCOMP ASC )LOOP xnumeroc := LPAD(EXTRACT(month FROM xfecha),2,'0')||LPAD(v_znumero,4,'0'); c_csubdia :='05A'; c_ccompro :=xnumeroc; c_cfeccom :=SUBSTR(EXTRACT(YEAR FROM xfecha),-2,2)||LPAD(EXTRACT(MONTH FROM xfecha),2,'02')||LPAD(EXTRACT(DAY FROM xfecha),2, '0'); c_ccodmon :='US'; c_csitua :='F'; c_ctipcam :=0.00; c_cglosa :='VENTAS OPERA'; c_ctotal :=0.00; c_ctipo :='V'; c_cflag :='S'; c_cdate :=SYSDATE; c_chora :=SYSDATE; c_cfeccam :=SUBSTR(EXTRACT(YEAR FROM xfecha),-2,2)||LPAD(EXTRACT(MONTH FROM xfecha),2,'02')||LPAD(EXTRACT(DAY FROM xfecha),2, '0'); c_cuser :='IOPER'; c_corig :='OP'; c_cform :='A'; c_ctipcom :='V'; c_cextor :=''; INSERT INTO TRAINING.T_CREAL( CSUBDIA, CCOMPRO, CFECCOM, CCODMON, CSITUA, CTIPCAM, CGLOSA, CTOTAL, CTIPO, CFLAG, CDATE, CHORA, CFECCAM, CUSER, CORIG, CFORM, CTIPCOM, CEXTOR) VALUES( c_csubdia, c_ccompro, c_cfeccom, c_ccodmon, c_csitua, c_ctipcam, c_cglosa, c_ctotal, c_ctipo, c_cflag, c_cdate, c_chora, c_cfeccam, c_CUSER, c_CORIG, c_CFORM, c_CTIPCOM, c_CEXTOR); COMMIT; znum :=0; FOR DETA IN ( SELECT NUCOMP, FECOMP, NRPCTA, TPMONE, DSGLOS, TPDOCU, NUSERI, NUDOCU, FEDOCU, IMAFEC, TPMOVI, IMDOLA, IMSOLE, TPCAMB, NURUC, TPCCTE, NUCCTE, BVNOMBRE, REFEREN, TIDOCI, DOCIDEN, TPDOCR, NUSERR, NUDOCR, FLAGX, FLAGCO FROM TRAINING.T_DETA WHERE TRIM(CABE.tpdocu)||TRIM(CABE.nuseri)||TRIM(CABE.nucomp) = TRIM(tpdocu)||TRIM(nuseri)||TRIM(nucomp) ORDER BY NUSERI ASC,NUCOMP ASC,NRPCTA ASC,IMDOLA ASC )LOOP znum := znum +1; d_Dsubdia := '05A'; d_dcompro :=xnumeroc; d_dsecue :=LPAD(znum,4,'0'); d_dfeccom :=SUBSTR(EXTRACT(YEAR FROM xfecha),-2,2)||LPAD(EXTRACT(MONTH FROM xfecha),2,'02')||LPAD(EXTRACT(DAY FROM xfecha),2, '0'); if deta.flagx is not null and SUBSTR(deta.nrpcta,1,2)= '70' then d_dcuenta :='704114'; else d_dcuenta :=deta.nrpcta; end if; d_dcodane := CASE WHEN deta.dociden IS NOT NULL and (TRIM(deta.nuruc)='88888888888' or deta.tpdocu='BV' ) THEN deta.dociden ELSE deta.nuruc END; if substr(deta.nrpcta,1,2)='70' or substr(deta.nrpcta,1,2)= '75' then if substr(deta.nrpcta,1,5)='70410' or substr(deta.nrpcta,1,5)= '70411' or TRIM(deta.nrpcta)='754182' then d_dcencos := '100010'; else if TRIM(deta.nrpcta)='704131' then d_dcencos := '200031'; else if TRIM(deta.nrpcta)='704132' or TRIM(deta.nrpcta)= '704138' or TRIM(deta.nrpcta)='704139' then d_dcencos := '200030'; else if TRIM(deta.nrpcta)='704133' or TRIM(deta.nrpcta)= '704134' then d_dcencos := '200032'; else if TRIM(deta.nrpcta)='704135' or TRIM(deta.nrpcta)= '704137' then d_dcencos := '200033'; else if TRIM(deta.nrpcta)='704140' or TRIM(deta.nrpcta)= '754201' or TRIM(deta.nrpcta)='754501' then d_dcencos := '300010'; else if TRIM(deta.nrpcta)='704171' or TRIM(deta.nrpcta)= '754172' then d_dcencos := '400010'; else if TRIM(deta.nrpcta)='704151' then d_dcencos :='500010'; else if TRIM(deta.nrpcta)='704191' or TRIM(deta.nrpcta)= '704192' then d_dcencos := '600010'; else if (TRIM(deta.nrpcta)='704161' or TRIM(deta.nrpcta)='704183' or TRIM(deta.nrpcta)='754202' or TRIM(deta.nrpcta)='759202' or TRIM(deta.nrpcta)='759203' or TRIM(deta.nrpcta)='759205' or TRIM(deta.nrpcta)='704182') then d_dcencos := '800010'; else if TRIM(deta.nrpcta)='704181' then d_dcencos := '800015'; else d_dcencos := '100010'; end if; end if; end if; end if; end if; end if; end if; end if; end if; end if; end if; else d_dcencos := ''; end if; d_dcodmon :='US'; d_ddh := deta.tpmovi; --// IF TRIM(d_ddh)='D' THEN SELECT COUNT(1) INTO CANT_NRODOC FROM TRAINING.hld_registro_gosocket r where TRIM(r.serie)=TRIM(DETA.NUSERI) and TRIM(r.numero)=TRIM(DETA.NUDOCU); IF CANT_NRODOC>0 THEN SELECT MAX(r.nro_documento) INTO V_NRO_DOCUMENTO FROM TRAINING.hld_registro_gosocket r where TRIM(r.serie)=TRIM(DETA.NUSERI) and TRIM(r.numero)=TRIM(DETA.NUDOCU); d_dcodane:=TRIM(V_NRO_DOCUMENTO); END IF; END IF; --// d_dimport := deta.imdola; SELECT DECODE(SUBSTR(DETA.NRPCTA,1,2),'12',DECODE(deta.tpdocu,'FA', 'FT' ,DECODE(deta.tpdocu,'NC','NC','BV')), '') INTO d_dtipdoc FROM DUAL; d_dnumdoc := deta.nuseri||deta.nudocu; d_dfecdoc := SUBSTR(EXTRACT(YEAR FROM xfecha),-2,2)||LPAD(EXTRACT(MONTH FROM xfecha),2,'0')||LPAD(EXTRACT(DAY FROM xfecha),2, '0'); d_dfecven := SUBSTR(EXTRACT(YEAR FROM xfecha),-2,2)||LPAD(EXTRACT(MONTH FROM xfecha),2,'0')||LPAD(EXTRACT(DAY FROM xfecha),2, '0'); d_darea := ''; d_dflag := 'S'; d_dxglosa := TRIM(deta.dsglos); d_ddate := xfecha; d_dcodane2 := ''; d_dusimpor := deta.imdola; d_dmnimpor := deta.imsole; d_dcodarc := ''; INSERT INTO TRAINING.T_DREAL(DSUBDIA , DCOMPRO , DSECUE , DFECCOM , DCUENTA , DCODANE , DCENCOS , DCODMON , DDH , DIMPORT , DTIPDOC , DNUMDOC , DFECDOC , DFECVEN , DAREA , DFLAG , DXGLOSA , DDATE , DCODANE2 , DUSIMPOR , DMNIMPOR , DCODARC) VALUES( d_Dsubdia, d_dcompro, d_dsecue, d_dfeccom, d_dcuenta, d_dcodane, d_dcencos, d_dcodmon, d_ddh, d_dimport, d_dtipdoc, d_dnumdoc, d_dfecdoc, d_dfecven, d_darea, d_dflag, SUBSTR(d_dxglosa,1,30), d_ddate, d_dcodane2, d_dusimpor, d_dmnimpor, d_dcodarc); COMMIT; END LOOP; v_znumero:=v_znumero+1; END LOOP; INSERT INTO TRAINING.ZNUMERO( ZNUMERO_INI, ZNUMERO_FIN, ZDATE_PROCESS , ZDATE_AUDIT , ZMONTH_PROCESS , ZYEAR_PROCESS )VALUES( v_znumero_ini, (v_znumero-1), v_ddate_process, SYSDATE, v_month, v_year ); COMMIT; DELETE FROM TRAINING.T_CREAA; INSERT INTO TRAINING.T_CREAA( NUCOMP, FECOMP, NRPCTA, TPMONE, DSGLOS, TPDOCU, NUSERI, NUDOCU, FEDOCU, IMAFEC, TPMOVI , IMDOLA , IMSOLE , TPCAMB , NURUC , TPCCTE , NUCCTE , BVNOMBRE , REFEREN , TIDOCI , DOCIDEN , TPDOCR , NUSERR , NUDOCR , FLAGX , FLAGCO) select NUCOMP, FECOMP, NRPCTA, TPMONE, DSGLOS, TPDOCU, NUSERI, NUDOCU, FEDOCU, IMAFEC, TPMOVI , IMDOLA , IMSOLE , TPCAMB , NURUC , TPCCTE , NUCCTE , BVNOMBRE , REFEREN , TIDOCI , DOCIDEN , TPDOCR , NUSERR , NUDOCR , FLAGX , FLAGCO from TRAINING.T_deta where SUBSTR(nrpcta,1,2)='12'; COMMIT; DELETE FROM TRAINING.T_RANEXO; FOR creaa IN ( SELECT NUCOMP, FECOMP, NRPCTA, TPMONE, DSGLOS, TPDOCU, NUSERI, NUDOCU, FEDOCU, IMAFEC, TPMOVI, IMDOLA, IMSOLE, TPCAMB, NURUC, TPCCTE, NUCCTE, BVNOMBRE, REFEREN, TIDOCI, DOCIDEN, TPDOCR, NUSERR, NUDOCR, FLAGX, FLAGCO FROM TRAINING.T_creaa )LOOP x_AVANEXO := 'C'; x_ACODANE := TRIM(creaa.nuruc); x_ADESANE := SUBSTR(TRIM(creaa.bvnombre),1,40); x_AREFANE := ''; x_ARUC := TRIM(creaa.nuruc); x_ACODMON := ''; x_AESTADO := 'V'; x_ADATE := SYSDATE; x_AHORA := ''; x_APATERNO := ''; x_AMATERNO := ''; x_ANOMBRE := ''; x_AFORMSUS := ''; x_ATELEFO := ''; x_ATIPTRA := ''; x_APROVIN := ''; x_ADEPART := ''; x_APAIS := ''; x_AZONPOS := ''; x_ANOMREP := ''; x_ACARREP := ''; x_AEMAIL := ''; x_AHOST := ''; SELECT DECODE(TRIM(creaa.tidoci),'PAS','7', DECODE(TRIM(creaa.tidoci), 'DNI', '1',DECODE(TRIM(creaa.tidoci),'CI','4', '0'))) INTO x_ADOCIDE FROM DUAL; x_ADOCIDE := CASE WHEN ((SUBSTR(creaa.nuruc,1,2)='10' or SUBSTR(CREAA.nuruc,1,2)='15' or SUBSTR(CREAA.nuruc,1,2)= '20') and length(TRIM(CREAA.nuruc))=11) THEN '6' ELSE CASE WHEN TRIM(CREAA.tidoci)='PAS' THEN '7' ELSE CASE WHEN TRIM(creaa.tidoci)='DNI' THEN '1' ELSE CASE WHEN TRIM(creaa.tidoci)='CI' THEN 'A' ELSE '0' END END END END; --insert into ranexo from memvar INSERT INTO TRAINING.T_RANEXO( AVANEXO, ACODANE, ADESANE, AREFANE, ARUC, ACODMON, AESTADO, ADATE, AHORA, APATERNO, AMATERNO, ANOMBRE, AFORMSUS, ATELEFO, ATIPTRA, APROVIN, ADEPART, APAIS, AZONPOS, ANOMREP, ACARREP, AEMAIL, AHOST, ADOCIDE )VALUES( x_AVANEXO, x_ACODANE, x_ADESANE, x_AREFANE, x_ARUC, x_ACODMON, x_AESTADO, x_ADATE, x_AHORA, x_APATERNO, x_AMATERNO, x_ANOMBRE, x_AFORMSUS, x_ATELEFO, x_ATIPTRA, x_APROVIN, x_ADEPART, x_APAIS, x_AZONPOS, x_ANOMREP, x_ACARREP, x_AEMAIL, x_AHOST, x_ADOCIDE ); COMMIT; END LOOP; UPDATE TRAINING.T_DREAL SET dcuenta='419102' WHERE TRIM(dcuenta)='469201'; UPDATE TRAINING.T_DREAL SET dcuenta='759203' WHERE TRIM(dcuenta)='469203'; UPDATE TRAINING.T_DREAL SET dcuenta='759203' WHERE TRIM(dcuenta)='705405'; UPDATE TRAINING.T_DREAL SET dcuenta='759203' WHERE TRIM(dcuenta)='706902'; UPDATE TRAINING.T_DREAL SET dcuenta='759203' WHERE TRIM(dcuenta)='707201'; UPDATE TRAINING.T_DREAL SET dcuenta='704161' WHERE TRIM(dcuenta)='705100'; UPDATE TRAINING.T_DREAL SET dcuenta='754501' WHERE TRIM(dcuenta)='706302'; UPDATE TRAINING.T_DREAL SET dcuenta='704102' WHERE TRIM(dcuenta)='704112'; UPDATE TRAINING.T_DREAL SET dcuenta='704102' WHERE TRIM(dcuenta)='676200'; UPDATE TRAINING.T_DREAL SET dcuenta='703110' WHERE TRIM(dcuenta)='704101'; UPDATE TRAINING.T_DREAL SET dcuenta='703111' WHERE TRIM(dcuenta)='704102'; UPDATE TRAINING.T_DREAL SET dcuenta='703112' WHERE TRIM(dcuenta)='704107'; UPDATE TRAINING.T_DREAL SET dcuenta='703113' WHERE TRIM(dcuenta)='704109'; UPDATE TRAINING.T_DREAL SET dcuenta='703114' WHERE TRIM(dcuenta)='704111'; UPDATE TRAINING.T_DREAL SET dcuenta='703115' WHERE TRIM(dcuenta)='704112'; UPDATE TRAINING.T_DREAL SET dcuenta='703116' WHERE TRIM(dcuenta)='704114'; UPDATE TRAINING.T_DREAL SET dcuenta='703117' WHERE TRIM(dcuenta)='704115'; UPDATE TRAINING.T_DREAL SET dcuenta='703118' WHERE TRIM(dcuenta)='704116'; UPDATE TRAINING.T_DREAL SET dcuenta='703210' WHERE TRIM(dcuenta)='704131'; UPDATE TRAINING.T_DREAL SET dcuenta='703211' WHERE TRIM(dcuenta)='704132'; UPDATE TRAINING.T_DREAL SET dcuenta='703212' WHERE TRIM(dcuenta)='704133'; UPDATE TRAINING.T_DREAL SET dcuenta='703213' WHERE TRIM(dcuenta)='704134'; UPDATE TRAINING.T_DREAL SET dcuenta='703214' WHERE TRIM(dcuenta)='704135'; UPDATE TRAINING.T_DREAL SET dcuenta='703215' WHERE TRIM(dcuenta)='704137'; UPDATE TRAINING.T_DREAL SET dcuenta='703216' WHERE TRIM(dcuenta)='704138'; UPDATE TRAINING.T_DREAL SET dcuenta='703217' WHERE TRIM(dcuenta)='704140'; UPDATE TRAINING.T_DREAL SET dcuenta='703218' WHERE TRIM(dcuenta)='704151'; UPDATE TRAINING.T_DREAL SET dcuenta='703219' WHERE TRIM(dcuenta)='704161'; UPDATE TRAINING.T_DREAL SET dcuenta='703311' WHERE TRIM(dcuenta)='704171'; UPDATE TRAINING.T_DREAL SET dcuenta='703312' WHERE TRIM(dcuenta)='704172'; UPDATE TRAINING.T_DREAL SET dcuenta='703313' WHERE TRIM(dcuenta)='704181'; UPDATE TRAINING.T_DREAL SET dcuenta='703314' WHERE TRIM(dcuenta)='704182'; UPDATE TRAINING.T_DREAL SET dcuenta='703315' WHERE TRIM(dcuenta)='704183'; COMMIT; END;
package com.hotel.business; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import com.hotel.Empresa; import com.hotel.dao.ConnectionFactoryMicrosBat; import com.hotel.dao.ConnectionFactoryOperaBat; import com.hotel.vo.Cliente; import com.hotel.vo.OpSalesAnexo; import com.hotel.vo.OpSalesDetail; import com.hotel.vo.OpSalesHeader; public class RegistroOperaBo { public String getDate(){ String fecha=""; PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOperaBat.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append("SELECT TO_CHAR(SYSDATE-1,'DD/MM/RRRR') date_process FROM DUAL "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); if(rs.next()){ fecha=rs.getString("date_process"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace(); }} if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace(); }} } return fecha; } public void createOperaTMP(){ PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOperaBat.getInstance().getConnection(); CallableStatement callableStatement = conn.prepareCall("{CALL TRAINING.HLD_SP_OPERA_DBF_CONCAR}"); callableStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace(); } } if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace(); }} } } public List<OpSalesHeader> listaComprobante(String fechaComprobante){ OpSalesHeader obj = null; PreparedStatement ps=null; ResultSet rs=null; List<OpSalesHeader> lista=new LinkedList<>(); try { Connection conn = ConnectionFactoryOperaBat.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append("SELECT CSUBDIA, "); query.append("CCOMPRO, "); query.append("CFECCOM, "); query.append("CCODMON, "); query.append("CSITUA, "); query.append("CTIPCAM, "); query.append("CGLOSA, "); query.append("CTOTAL, "); query.append("CTIPO, "); query.append("CFLAG, "); query.append("TO_CHAR(CDATE, 'MM/DD/RRRR') CDATE, "); query.append("CHORA, "); query.append("CFECCAM, "); query.append("CUSER, "); query.append("CORIG, "); query.append("CFORM, "); query.append("CTIPCOM, "); query.append("CEXTOR "); query.append("FROM TRAINING.T_CREAL ORDER BY CCOMPRO ASC "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ obj=new OpSalesHeader(); obj.setCSUBDIA(rs.getString("CSUBDIA")); obj.setCCOMPRO(rs.getString("CCOMPRO")); obj.setCFECCOM(rs.getString("CFECCOM")); obj.setCCODMON(rs.getString("CCODMON")); obj.setCSITUA(rs.getString("CSITUA")); obj.setCTIPCAM(Util.formatDec(rs.getDouble("CTIPCAM")));//--DOUBLE obj.setCGLOSA(rs.getString("CGLOSA")); obj.setCTOTAL(Util.formatDec(rs.getDouble("CTOTAL")));//--DOUBLE obj.setCTIPO(rs.getString("CTIPO")); obj.setCFLAG(rs.getString("CFLAG")); obj.setCDATE(rs.getString("CDATE")); obj.setCHORA(rs.getString("CHORA")); obj.setCFECCAM(rs.getString("CFECCAM")); obj.setCUSER(rs.getString("CUSER")); obj.setCORIG(rs.getString("CORIG")); obj.setCFORM(rs.getString("CFORM")); obj.setCTIPCOM(rs.getString("CTIPCOM")); obj.setCEXTOR(rs.getString("CEXTOR")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace(); }} if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace(); }} } return lista; } public List<OpSalesDetail> obtenerComprobanteDetalleDBF(String fechaComprobante){ List<OpSalesDetail> lista = new ArrayList<OpSalesDetail>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOperaBat.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append("SELECT DSUBDIA, "); query.append("DCOMPRO, "); query.append("DSECUE, "); query.append("DFECCOM, "); query.append("DCUENTA, "); query.append("DCODANE, "); query.append("DCENCOS, "); query.append("DCODMON, "); query.append("DDH, "); query.append("DIMPORT, "); query.append("DTIPDOC, "); query.append("DNUMDOC, "); query.append("DFECDOC, "); query.append("DFECVEN, "); query.append("DAREA, "); query.append("DFLAG, "); query.append("DXGLOSA, "); query.append("TO_CHAR(DDATE, 'MM/DD/RRRR') DDATE, "); query.append("DCODANE2, "); query.append("DUSIMPOR, "); query.append("DMNIMPOR, "); query.append("DCODARC, "); query.append("FLAGX, "); query.append("DMEDPAG, "); query.append("DIGVCOM, "); query.append("DTIDREF, "); query.append("DNDOREF, "); query.append("DFECREF, "); query.append("DBIMREF, "); query.append("DIGVREF, "); query.append("DMAQREF "); query.append("FROM TRAINING.T_DREAL ORDER BY DCOMPRO ASC,DSECUE ASC "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ OpSalesDetail obj=new OpSalesDetail(); obj.setDSUBDIA(rs.getString("DSUBDIA")); obj.setDCOMPRO(rs.getString("DCOMPRO")); obj.setDSECUE(rs.getString("DSECUE")); obj.setDFECCOM(rs.getString("DFECCOM")); obj.setDCUENTA(rs.getString("DCUENTA")); obj.setDCODANE(rs.getString("DCODANE")); obj.setDCENCOS(rs.getString("DCENCOS")); obj.setDCODMON(rs.getString("DCODMON")); obj.setDDH(rs.getString("DDH")); obj.setDIMPORT(Util.formatDec(rs.getDouble("DIMPORT"))); //--DOUBLE obj.setDTIPDOC(rs.getString("DTIPDOC")); obj.setDNUMDOC(rs.getString("DNUMDOC")); obj.setDFECDOC(rs.getString("DFECDOC")); obj.setDFECVEN(rs.getString("DFECVEN")); obj.setDAREA(rs.getString("DAREA")); obj.setDFLAG(rs.getString("DFLAG")); obj.setDXGLOSA(rs.getString("DXGLOSA")); obj.setDDATE(rs.getString("DDATE")); obj.setDCODANE2(rs.getString("DCODANE2")); obj.setDUSIMPOR(Util.formatDec(rs.getDouble("DUSIMPOR"))); //--DOUBLE obj.setDMNIMPOR(Util.formatDec(rs.getDouble("DMNIMPOR"))); //--DOUBLE obj.setDCODARC(rs.getString("DCODARC")); obj.setFLAGX(rs.getString("FLAGX")); obj.setDMEDPAG(rs.getString("DMEDPAG")); obj.setDIGVCOM(rs.getString("DIGVCOM")); obj.setDTIDREF(rs.getString("DTIDREF")); obj.setDNDOREF(rs.getString("DNDOREF")); obj.setDFECREF(rs.getString("DFECREF")); obj.setDBIMREF(Util.formatDec(rs.getDouble("DBIMREF"))); //--DOUBLE obj.setDIGVREF(Util.formatDec(rs.getDouble("DIGVREF"))); //--DOUBLE obj.setDMAQREF(rs.getString("DMAQREF")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace(); }} if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace(); }} } return lista; } public List<OpSalesAnexo> obtenerComprobanteAnexoDBF(String fechaComprobante){ List<OpSalesAnexo> lista = new ArrayList<OpSalesAnexo>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOperaBat.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append("SELECT AVANEXO, "); query.append("ACODANE, "); query.append("ADESANE, "); query.append("AREFANE, "); query.append("ARUC, "); query.append("ACODMON, "); query.append("AESTADO, "); query.append("TO_CHAR(ADATE, 'MM/DD/RRRR') ADATE, "); query.append("AHORA, "); query.append("APATERNO, "); query.append("AMATERNO, "); query.append("ANOMBRE, "); query.append("AFORMSUS, "); query.append("ATELEFO, "); query.append("ATIPTRA, "); query.append("APROVIN, "); query.append("ADEPART, "); query.append("APAIS, "); query.append("AZONPOS, "); query.append("ANOMREP, "); query.append("ACARREP, "); query.append("AEMAIL, "); query.append("AHOST, "); query.append("ADOCIDE FROM TRAINING.T_RANEXO ORDER BY ACODANE ASC "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ OpSalesAnexo obj=new OpSalesAnexo(); obj.setAVANEXO(Util.isNull(rs.getString("AVANEXO"))); obj.setACODANE(Util.isNull(rs.getString("ACODANE"))); obj.setADESANE(Util.isNull(rs.getString("ADESANE"))); obj.setAREFANE(Util.isNull(rs.getString("AREFANE"))); obj.setARUC(Util.isNull(rs.getString("ARUC"))); obj.setACODMON(Util.isNull(rs.getString("ACODMON"))); obj.setAESTADO(Util.isNull(rs.getString("AESTADO"))); obj.setADATE(Util.isNull(rs.getString("ADATE"))); obj.setAHORA(Util.isNull(rs.getString("AHORA"))); obj.setAPATERNO(Util.isNull(rs.getString("APATERNO"))); obj.setAMATERNO(Util.isNull(rs.getString("AMATERNO"))); obj.setANOMBRE(Util.isNull(rs.getString("ANOMBRE"))); obj.setAFORMSUS(Util.isNull(rs.getString("AFORMSUS"))); obj.setATELEFO(Util.isNull(rs.getString("ATELEFO"))); obj.setATIPTRA(Util.isNull(rs.getString("ATIPTRA"))); obj.setAPROVIN(Util.isNull(rs.getString("APROVIN"))); obj.setADEPART(Util.isNull(rs.getString("ADEPART"))); obj.setAPAIS(Util.isNull(rs.getString("APAIS"))); obj.setAZONPOS(Util.isNull(rs.getString("AZONPOS"))); obj.setANOMREP(Util.isNull(rs.getString("ANOMREP"))); obj.setACARREP(Util.isNull(rs.getString("ACARREP"))); obj.setAEMAIL(Util.isNull(rs.getString("AEMAIL"))); obj.setAHOST(Util.isNull(rs.getString("AHOST"))); obj.setADOCIDE(Util.isNull(rs.getString("ADOCIDE"))); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace(); }} if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace(); }} } return lista; } }
package com.hotel.spring.controller; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.Properties; import com.hotel.business.ClienteBo; import com.hotel.business.RegistroMicrosBo; import com.hotel.business.RegistroOperaBo; import com.hotel.business.Util; import com.hotel.vo.Cliente; import com.hotel.vo.OpSalesAnexo; import com.hotel.vo.OpSalesDetail; import com.hotel.vo.OpSalesHeader; import com.linuxense.javadbf.DBFException; public class JavaOpera2DBFWrite { private static String sJdbURL; public static String getsJdbURL() { return sJdbURL; } public static void setsJdbURL(String sJdbURL) { JavaOpera2DBFWrite.sJdbURL = sJdbURL; } private String folderName; public String getFolderName() { return folderName; } public void setFolderName(String folderName) { this.folderName = folderName; } public JavaOpera2DBFWrite(String fechaComp){ try{ setFolderName(Util.path_OPERA_CONCAR+"\\"); setsJdbURL("jdbc:dbf://"+getFolderName()+"/?caseInsensitive=true"); }catch(Exception e){ e.printStackTrace(); setFolderName(Util.path_OPERA_CONCAR); setsJdbURL("jdbc:dbf://"+getFolderName()+"/?caseInsensitive=true"); } } public Integer createDBFOPERAConcar(String fechaComprobante)throws Exception,DBFException, IOException,ParseException { Integer cantidad=0; RegistroOperaBo bo=new RegistroOperaBo(); bo.createOperaTMP();// Integer periodo=Util.getYear(fechaComprobante); List<OpSalesHeader> lHeader=bo.listaComprobante(fechaComprobante); cantidad=lHeader.size(); if(cantidad>0){ List<OpSalesDetail> lDetail=bo.obtenerComprobanteDetalleDBF(fechaComprobante); List<OpSalesAnexo> lAnexo=bo.obtenerComprobanteAnexoDBF(fechaComprobante); createCabeceraDBF(periodo,lHeader); createDetalleDBF(periodo,lDetail); createAnexoDBF(lAnexo); } return cantidad; } public void createCabeceraDBF(Integer periodo,List<OpSalesHeader> lheader) throws DBFException, IOException,ParseException { try{ Class.forName("com.caigen.sql.dbf.DBFDriver"); Properties props = new Properties(); props.setProperty("delayedClose", "0"); props.setProperty("versionNumber", "F5"); Connection conn = DriverManager.getConnection(getsJdbURL(), props); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql="drop table if exists CC0002TEST"+String.valueOf(periodo)+";"; stmt.execute(sql); sql="create table if not exists CC0002TEST"+String.valueOf(periodo)+ "(CSUBDIA CHAR(4),CCOMPRO CHAR(6),CFECCOM CHAR(6),CCODMON CHAR(2),CSITUA CHAR(1),CTIPCAM NUMERIC(9,4),CGLOSA CHAR(40),CTOTAL NUMERIC(13,2),CTIPO CHAR(1),CFLAG CHAR(1), CDATE DATE,CHORA CHAR(6),CFECCAM CHAR(6),CUSER CHAR(5),CORIG CHAR(2),CFORM CHAR(1),CTIPCOM CHAR(2),CEXTOR CHAR(1) );"; stmt.execute(sql); for(OpSalesHeader header:lheader){ //ASIGNA DATA :: INICIO Object []rowObjects=new Object [18]; rowObjects[0]=header.getCSUBDIA();//CSUBDIA rowObjects[1]=header.getCCOMPRO();//CCOMPRO rowObjects[2]=header.getCFECCOM();//CFECCOM rowObjects[3]=header.getCCODMON();//CCODMON rowObjects[4]=header.getCSITUA();//CSITUA rowObjects[5]=header.getCTIPCAM();//CTIPCAM rowObjects[6]=header.getCGLOSA();//CGLOSA rowObjects[7]=header.getCTOTAL();//CTOTAL rowObjects[8]=header.getCTIPO();//CTIPO rowObjects[9]=header.getCFLAG();//CFLAG rowObjects[10]=header.getCDATE();//CDATE rowObjects[11]=header.getCHORA();//CHORA rowObjects[12]=header.getCFECCAM();//CFECCAM rowObjects[13]=header.getCUSER();//CUSER rowObjects[14]=header.getCORIG();//CORIG rowObjects[15]=header.getCFORM();//CFORM rowObjects[16]=header.getCTIPCOM();//CTIPCOM rowObjects[17]=header.getCEXTOR();//CEXTOR //ASIGNA DATA :: FIN StringBuilder query = new StringBuilder(); query.append("insert into CC0002TEST"+String.valueOf(periodo)+ "(CSUBDIA,CCOMPRO,CFECCOM,CCODMON,CSITUA,CTIPCAM,CGLOSA,CTOTAL,CTIPO,CFLAG,CDATE,CHORA,CFECCAM,CUSER,CORIG,CFORM,CTIPCOM,CEXTOR) values("); query.append("'"+rowObjects[0]+"',");//CSUBDIA 4 0 67 query.append("'"+rowObjects[1]+"',");//CCOMPRO 6 0 67 query.append("'"+rowObjects[2]+"',");//CFECCOM 6 0 67 query.append("'"+rowObjects[3]+"',");//CCODMON 2 0 67 query.append("'"+rowObjects[4]+"',");//CSITUA 1 0 67 query.append(new Double(rowObjects[5]==null?"0.0":rowObjects[5].toString())+ ",");// CTIPCAM 10 4 78 query.append("'"+rowObjects[6]+"',");//CGLOSA 40 0 67 query.append(new Double(rowObjects[7]==null?"0.0":rowObjects[7].toString())+ ",");//CTOTAL 14 2 78 query.append("'"+rowObjects[8]+"',");//CTIPO 1 0 67 query.append("'"+rowObjects[9]+"',");//CFLAG 1 0 67 if(rowObjects[10]!=null) { DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(df.parse(rowObjects[10].toString())); String year=String.valueOf(calendar.get(Calendar.YEAR)); String month=String.valueOf(calendar.get(Calendar.MONTH) + 1); month=fill(month,2); String day=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)); day=fill(day,2); query.append("CDATE('"+month+day+year+"','MMddyyyy'),");//CDATE 8 0 68 }else{ query.append("'',"); } query.append("'"+rowObjects[11]+"',");//CHORA CHAR(6), query.append("'"+rowObjects[12]+"',");//CFECCAM CHAR(6), query.append("'"+rowObjects[13]+"',");//CUSER CHAR(5), query.append("'"+rowObjects[14]+"',");//CORIG 2 0 67 query.append("'"+rowObjects[15]+"',");//CFORM 1 0 67 query.append("'"+rowObjects[16]+"',");//CTIPCOM 2 0 67 query.append("'"+rowObjects[17]+"'");//CEXTOR 1 0 67 query.append(");"); System.out.println(query.toString()); stmt.execute(query.toString()); } stmt.close(); conn.close(); } catch( SQLException sqle ) { do { System.out.println(sqle.getMessage()); System.out.println("Error Code:"+sqle.getErrorCode()); System.out.println("SQL State:"+sqle.getSQLState()); sqle.printStackTrace(); }while((sqle=sqle.getNextException())!= null); } catch( Exception e ) { System.out.println(e.getMessage()); e.printStackTrace(); } } public void createDetalleDBF(Integer periodo,List<OpSalesDetail> lDetalle) throws DBFException, IOException,ParseException { try{ Class.forName("com.caigen.sql.dbf.DBFDriver"); Properties props = new Properties(); props.setProperty("delayedClose", "0"); props.setProperty("versionNumber", "F5"); Connection conn = DriverManager.getConnection(getsJdbURL(), props); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql="drop table if exists CD0002TEST"+String.valueOf(periodo)+";"; stmt.execute(sql); sql="create table if not exists CD0002TEST"+String.valueOf(periodo)+ "(DSUBDIA CHAR(4),DCOMPRO CHAR(6),DSECUE CHAR(4),DFECCOM CHAR(6),DCUENTA CHAR(12),DCODANE CHAR(18),DCENCOS CHAR(6),DCODMON CHAR(2),DDH CHAR(1), DIMPORT NUMERIC(13,2),DTIPDOC CHAR(2),DNUMDOC VARCHAR(20),DFECDOC CHAR(6),DFECVEN CHAR(6),DAREA CHAR(3),DFLAG CHAR(1),DXGLOSA VARCHAR(30), DDATE DATE,DCODANE2 CHAR(18),DUSIMPOR NUMERIC(13,2),DMNIMPOR NUMERIC(13,2),DCODARC CHAR(2),FLAGX CHAR(1),DMEDPAG CHAR(8),DIGVCOM NUMERIC(13,2), DTIDREF CHAR(2),DNDOREF CHAR(30),DFECREF DATE,DBIMREF NUMERIC(13,2),DIGVREF NUMERIC(13,2),DMAQREF CHAR(20) );"; stmt.execute(sql); for(OpSalesDetail detalle:lDetalle){ //(1) //ASIGNA DATA :: INICIO Object []rowObjects=new Object [31]; rowObjects[0]=detalle.getDSUBDIA();//DSUBDIA rowObjects[1]=detalle.getDCOMPRO();//DCOMPRO rowObjects[2]=detalle.getDSECUE();//DSECUE 4 0 67 rowObjects[3]=detalle.getDFECCOM();//DFECCOM 6 0 67 rowObjects[4]=detalle.getDCUENTA();//DCUENTA 12 0 67 rowObjects[5]=detalle.getDCODANE();//DCODANE 18 0 67 rowObjects[6]=detalle.getDCENCOS();//DCENCOS 6 0 67 rowObjects[7]=detalle.getDCODMON();//DCODMON rowObjects[8]=detalle.getDDH();//DDH rowObjects[9]=detalle.getDIMPORT();//DIMPORT rowObjects[10]=detalle.getDTIPDOC();//DTIPDOC 2 0 67 rowObjects[11]=detalle.getDNUMDOC();//DNUMDOC 2 0 67 rowObjects[12]=detalle.getDFECDOC();//DFECDOC 2 0 67 rowObjects[13]=detalle.getDFECVEN();//DFECVEN 2 0 67 rowObjects[14]=detalle.getDAREA();//DAREA 2 0 67 rowObjects[15]=detalle.getDFLAG();//DFLAG FLAG DE CONVERSIÓN DE MONEDA (S, N) rowObjects[16]=detalle.getDXGLOSA();//DXGLOSA GLOSA DEL MOVIMIENTO rowObjects[17]=detalle.getDDATE();//DDATE FECHA DE ACTUALIZACIÓN rowObjects[18]=detalle.getDCODANE2();//DCODANE2 CÓDIGO DE ANEXO AUXILAR rowObjects[19]=detalle.getDUSIMPOR();//DUSIMPOR NUMERIC(14,2), rowObjects[20]=detalle.getDMNIMPOR();//DMNIMPOR NUMERIC(14,2), rowObjects[21]=detalle.getDCODARC();//DCODARC rowObjects[22]=detalle.getFLAGX();//FLAGX rowObjects[23]=detalle.getDMEDPAG();//DMEDPAG rowObjects[24]=detalle.getDIGVCOM();//DIGVCOM NUMERIC(14,2), rowObjects[25]=detalle.getDTIDREF();//DTIDREF rowObjects[26]=detalle.getDNDOREF();//DNDOREF rowObjects[27]=detalle.getDFECREF();//DFECREF rowObjects[28]=detalle.getDBIMREF();//DBIMREF rowObjects[29]=detalle.getDIGVREF();//DIGVREF rowObjects[30]=detalle.getDMAQREF();//DMAQREF //ASIGNA DATA :: FIN StringBuilder query = new StringBuilder(); query.append("insert into CD0002TEST"+String.valueOf(periodo)+ "(DSUBDIA,DCOMPRO,DSECUE,DFECCOM,DCUENTA,DCODANE,DCENCOS,DCODMON,DDH,DIMPORT,DTIPDOC,DNUMDOC,DFECDOC,DFECVEN,DAREA,DFLAG,DXGLOSA,DDATE,DCODANE2,DUSIMPOR, DMNIMPOR,DCODARC,FLAGX,DMEDPAG,DIGVCOM,DTIDREF,DNDOREF,DFECREF,DBIMREF,DIGVREF,DMAQREF) values("); query.append("'"+rowObjects[0]+"',");//DSUBDIA 4 0 67 query.append("'"+rowObjects[1]+"',");//DCOMPRO 6 0 67 query.append("'"+rowObjects[2]+"',");//DSECUE 4 0 67 query.append("'"+rowObjects[3]+"',");//DFECCOM 6 0 67 query.append("'"+rowObjects[4]+"',");//DCUENTA 12 0 67 query.append("'"+rowObjects[5]+"',");//DCODANE 18 0 67 query.append("'"+rowObjects[6]+"',");//DCENCOS 6 0 67 query.append("'"+rowObjects[7]+"',");//DCODMON 2 0 67 query.append("'"+rowObjects[8]+"',");//DDH 1 0 67 query.append(new Double(rowObjects[9]==null?"0.0":rowObjects[9].toString())+ ",");//DIMPORT 14 2 78 query.append("'"+rowObjects[10]+"',");//DTIPDOC 2 0 67 query.append("'"+rowObjects[11]+"',");//DNUMDOC 20 0 67 query.append("'"+rowObjects[12]+"',");//DFECDOC 6 0 67 query.append("'"+rowObjects[13]+"',");//DFECVEN 6 0 67 query.append("'"+rowObjects[14]+"',");//DAREA 3 0 67 query.append("'"+rowObjects[15]+"',");//DFLAG 1 0 67 query.append("'"+rowObjects[16]+"',");//DXGLOSA 30 0 67 if(rowObjects[17]!=null) { DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(df.parse(rowObjects[17].toString())); String year=String.valueOf(calendar.get(Calendar.YEAR)); String month=String.valueOf(calendar.get(Calendar.MONTH) + 1); month=fill(month,2); String day=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)); day=fill(day,2); query.append("CDATE('"+month+day+year+"','MMddyyyy'),");//CDATE 8 0 68 }else{ query.append("'',"); } query.append("'"+rowObjects[18]+"',");//DCODANE2 CHAR(18), query.append(new Double(rowObjects[19]==null?"0.0":rowObjects[19].toString())+ ",");//DUSIMPOR NUMERIC(14,2), query.append(new Double(rowObjects[20]==null?"0.0":rowObjects[20].toString())+ ",");//DMNIMPOR NUMERIC(14,2), query.append("'"+rowObjects[21]+"',");//DCODARC CHAR(2), query.append("'"+rowObjects[22]+"',");//FLAGX CHAR(1), query.append("'"+rowObjects[23]+"',");//DMEDPAG CHAR(8), query.append(new Double(rowObjects[24]==null?"0.0":rowObjects[24].toString())+ ",");//DIGVCOM NUMERIC(14,2), query.append("'"+rowObjects[25]+"',");//DTIDREF CHAR(2), query.append("'"+rowObjects[26]+"',");//DNDOREF CHAR(30), if(rowObjects[27]!=null) { DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(df.parse(rowObjects[27].toString())); String year=String.valueOf(calendar.get(Calendar.YEAR)); String month=String.valueOf(calendar.get(Calendar.MONTH) + 1); month=fill(month,2); String day=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)); day=fill(day,2); query.append("CDATE('"+day+month+year+"','ddMMyyyy'),");//DFECREF DATE, }else{ query.append("'',"); } query.append(new Double(rowObjects[28]==null?"0.0":rowObjects[28].toString())+ ",");//DBIMREF NUMERIC(14,2), query.append(new Double(rowObjects[29]==null?"0.0":rowObjects[29].toString())+ ",");//DIGVREF NUMERIC(14,2), query.append("'"+rowObjects[30]+"'");//DMAQREF CHAR(20) query.append(");"); System.out.println(query.toString()); stmt.execute(query.toString()); } stmt.close(); conn.close(); } catch( SQLException sqle ) { do { System.out.println(sqle.getMessage()); System.out.println("Error Code:"+sqle.getErrorCode()); System.out.println("SQL State:"+sqle.getSQLState()); sqle.printStackTrace(); }while((sqle=sqle.getNextException())!= null); } catch( Exception e ) { System.out.println(e.getMessage()); e.printStackTrace(); } } public void createAnexoDBF(List<OpSalesAnexo> lheader) throws DBFException, IOException,ParseException { try{ Class.forName("com.caigen.sql.dbf.DBFDriver"); Properties props = new Properties(); props.setProperty("delayedClose", "0"); props.setProperty("versionNumber", "F5"); Connection conn = DriverManager.getConnection(getsJdbURL(), props); Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); String sql="drop table if exists CAN02TEST;"; stmt.execute(sql); sql="create table if not exists CAN02TEST(AVANEXO CHAR(1),ACODANE CHAR(18),ADESANE CHAR(40),AREFANE CHAR(50),ARUC CHAR(18),ACODMON CHAR(2), AESTADO CHAR(1),ADATE DATE,AHORA CHAR(6),APATERNO CHAR(20),AMATERNO CHAR(20),ANOMBRE CHAR(20),AFORMSUS CHAR(8),ATELEFO CHAR(30),ATIPTRA CHAR(1),APROVIN CHAR(30),ADEPART CHAR(30), APAIS CHAR(30),AZONPOS CHAR(10),ANOMREP CHAR(40),ACARREP CHAR(20),AEMAIL CHAR(80),AHOST CHAR(80),ADOCIDE CHAR(2));"; stmt.execute(sql); for(OpSalesAnexo header:lheader){ //ASIGNA DATA :: INICIO Object []rowObjects=new Object [24]; rowObjects[0]=header.getAVANEXO();//AVANEXO 1 0 67 rowObjects[1]=header.getACODANE();//ACODANE 18 0 67 rowObjects[2]=header.getADESANE();//ADESANE 40 0 67 rowObjects[3]=header.getAREFANE();//AREFANE 50 0 67 rowObjects[4]=header.getARUC();//ARUC 18 0 67 rowObjects[5]=header.getACODMON();//ACODMON 2 0 67 rowObjects[6]=header.getAESTADO();//AESTADO 1 0 67 rowObjects[7]=header.getADATE();//ADATE 6 0 67 rowObjects[8]=header.getAHORA();//AHORA 6 0 67 rowObjects[9]=header.getAPATERNO();//APATERNO 20 0 67 rowObjects[10]=header.getAMATERNO();//AMATERNO 20 0 67 rowObjects[11]=header.getANOMBRE();//ANOMBRE 20 0 67 rowObjects[12]=header.getAFORMSUS();//AFORMSUS 8 0 67 rowObjects[13]=header.getATELEFO();//ATELEFO 30 0 67 rowObjects[14]=header.getATIPTRA();//ATIPTRA 1 0 67 rowObjects[15]=header.getAPROVIN();//APROVIN 30 0 67 rowObjects[16]=header.getADEPART();//ADEPART 30 0 67 rowObjects[17]=header.getAPAIS();//APAIS 30 0 67 rowObjects[18]=header.getAZONPOS();//AZONPOS 10 0 67 rowObjects[19]=header.getANOMREP();//ANOMREP 40 0 67 rowObjects[20]=header.getACARREP();//ACARREP 20 0 67 rowObjects[21]=header.getAEMAIL();//AEMAIL 80 0 67 rowObjects[22]=header.getAHOST();//AHOST 80 0 67 rowObjects[23]=header.getADOCIDE();//ADOCIDE 2 0 67 //ASIGNA DATA :: FIN /* create cursor Ranexo ( AVANEXO c(1),ACODANE C(18), ADESANE c(40),AREFANE c(50), ARUC c(18),ACODMON c(2),AESTADO c(1), ADATE d, AHORA c(6),; APATERNO c(20), AMATERNO c(20),ANOMBRE c(20), AFORMSUS c(8), ATELEFO c(30), ATIPTRA c(1), APROVIN c(30),ADEPART c(30),; APAIS c(30),AZONPOS c(10),ANOMREP c(40),ACARREP c(20),AEMAIL c(80),AHOST c(80),ADOCIDE c(2)) */ StringBuilder query = new StringBuilder(); query.append("insert into CAN02TEST(AVANEXO,ACODANE,ADESANE,AREFANE,ARUC,ACODMON,AESTADO,ADATE,AHORA,APATERNO,AMATERNO,ANOMBRE, AFORMSUS,ATELEFO,ATIPTRA,APROVIN,ADEPART,APAIS,AZONPOS,ANOMREP,ACARREP,AEMAIL,AHOST,ADOCIDE) values("); query.append("'"+rowObjects[0]+"',");//AVANEXO 1 0 67 query.append("'"+rowObjects[1]+"',");//ACODANE 18 0 67 query.append("'"+rowObjects[2]+"',");//ADESANE 40 0 67 query.append("'"+rowObjects[3]+"',");//AREFANE 50 0 67 query.append("'"+rowObjects[4]+"',");//ARUC 18 0 67 query.append("'"+rowObjects[5]+"',");//ACODMON 2 0 67 query.append("'"+rowObjects[6]+"',");//AESTADO 1 0 67 if(rowObjects[7]!=null) { DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(df.parse(rowObjects[7].toString())); String year=String.valueOf(calendar.get(Calendar.YEAR)); String month=String.valueOf(calendar.get(Calendar.MONTH) + 1); month=fill(month,2); String day=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH)); day=fill(day,2); query.append("CDATE('"+month+day+year+"','MMddyyyy'),");//CDATE 8 0 68 }else{ query.append("'',");//DDATE 8 0 68 } query.append("'"+rowObjects[8]+"',");//AHORA 6 0 67 query.append("'"+rowObjects[9]+"',");//APATERNO 20 0 67 query.append("'"+rowObjects[10]+"',");//AMATERNO 20 0 67 query.append("'"+rowObjects[11]+"',");//ANOMBRE 20 0 67 query.append("'"+rowObjects[12]+"',");//AFORMSUS 8 0 67 query.append("'"+rowObjects[13]+"',");//ATELEFO 30 0 67 query.append("'"+rowObjects[14]+"',");//ATIPTRA 1 0 67 query.append("'"+rowObjects[15]+"',");//APROVIN 30 0 67 query.append("'"+rowObjects[16]+"',");//ADEPART 30 0 67 query.append("'"+rowObjects[17]+"',");//APAIS 30 0 67 query.append("'"+rowObjects[18]+"',");//AZONPOS 10 0 67 query.append("'"+rowObjects[19]+"',");//ANOMREP 40 0 67 query.append("'"+rowObjects[20]+"',");//ACARREP 20 0 67 query.append("'"+rowObjects[21]+"',");//AEMAIL 80 0 67 query.append("'"+rowObjects[22]+"',");//AHOST 80 0 67 query.append("'"+rowObjects[23]+"'");//ADOCIDE 2 0 67 query.append(");"); System.out.println(query.toString()); stmt.execute(query.toString()); } stmt.close(); conn.close(); } catch( SQLException sqle ) { do { System.out.println(sqle.getMessage()); System.out.println("Error Code:"+sqle.getErrorCode()); System.out.println("SQL State:"+sqle.getSQLState()); sqle.printStackTrace(); }while((sqle=sqle.getNextException())!= null); } catch( Exception e ) { System.out.println(e.getMessage()); e.printStackTrace(); } } public static String fill(String text, int size) { StringBuilder builder = new StringBuilder(text); while (builder.length() < size) { builder.insert(0,'0'); } return builder.toString(); } }
create or replace PROCEDURE BI.SP_CREATE_MICROS_DBF IS --GRANT SELECT ON microsdb.fcr_invoice_data TO BI; v_ddate_process DATE:=(SYSDATE-1); CURSOR SC_INVOICE_DATA IS SELECT a.pcwsid, decode(length(a.customerid),11,'F','B') as tdoc, a.pcwsid ||'-' ||a.microschknum as correla, to_char(a.microsbsnzdate,'DD-MM-RRRR') as femision, '' as fvence, '07' as tipo, a.extrafield7 as serMaq, a.fcrinvnumber as numdoc, '1' as tipodoc, a.customerid as numdocident, a.extrafield1 as nombre, 0.00 as valorexport, a.subtotal1 as baseimponible, 0.00 as exonera, 0.00 as inafecta, 0.00 as isc, a.taxttl1 as igv, a.subtotal10 as servicio, a.subtotal11 as propina, a.subtotal8 as totaldoc, a.microsbsnzdate dfemision FROM microsdb.fcr_invoice_data a where to_char(a.microsbsnzdate,'DD-MM-RRRR')=to_char(v_ddate_process,'DD-MM-RRRR') order by a.pcwsid ,correla, tdoc, a.fcrinvnumber; v_znumero NUMBER; v_year number; v_month number; v_xnumeroc VARCHAR(6); v_vartcambio NUMBER(10,4); --cabecera v_CSUBDIA NVARCHAR2(4); v_CCOMPRO NVARCHAR2(6); v_CFECCOM NVARCHAR2(6); v_CCODMON NVARCHAR2(2); v_CSITUA NVARCHAR2(1); v_CTIPCAM NUMBER(10,4); v_CGLOSA NVARCHAR2(40); v_CTOTAL NUMBER(14,2); v_CTIPO NVARCHAR2(1); v_CFLAG NVARCHAR2(1); v_CDATE DATE; v_CHORA NVARCHAR2(6); v_CFECCAM NVARCHAR2(6); v_CUSER NVARCHAR2(5); v_CORIG NVARCHAR2(2); v_CFORM NVARCHAR2(1); v_CTIPCOM NVARCHAR2(2); v_CEXTOR NVARCHAR2(1); --detalle v_dsubdia NVARCHAR2(4):=''; v_dcompro NVARCHAR2(6):=''; v_dsecue NVARCHAR2(4):=''; v_dfeccom NVARCHAR2(6):=''; v_dcuenta NVARCHAR2(12):=''; v_dcodane NVARCHAR2(18):=''; v_dcencos NVARCHAR2(6):=''; v_dcodmon NVARCHAR2(2):=''; v_ddh NVARCHAR2(1):=''; v_dimport NUMBER(14,2):=0.0; v_dtipdoc NVARCHAR2(2):=''; v_dnumdoc NVARCHAR2(20):=''; v_dfecdoc NVARCHAR2(6):=''; v_dfecven NVARCHAR2(6):=''; v_darea NVARCHAR2(3):=''; v_dflag NVARCHAR2(1):=''; v_dxglosa NVARCHAR2(30):=''; v_ddate DATE:=SYSDATE; v_dcodane2 NVARCHAR2(18):=''; v_dusimpor NUMBER(14,2):=0.0; v_dmnimpor NUMBER(14,2):=0.0; v_dcodarc NVARCHAR2(2):=''; v_flagx NVARCHAR2(1):=''; v_dmedpag NVARCHAR2(8):=''; v_digvcom NUMBER(14,2):=NULL; v_dtidref NVARCHAR2(2):=''; v_dndoref NVARCHAR2(30):=''; v_dfecref DATE:=NULL; v_dbimref NUMBER(14,2):=NULL; v_digvref NUMBER(14,2):=NULL; v_dmaqref NVARCHAR2(20):=''; --anexos v_AVANEXO NVARCHAR2(1):='C'; v_ACODANE NVARCHAR2(18); v_ADESANE NVARCHAR2(40); v_ARUC NVARCHAR2(18); v_AESTADO NVARCHAR2(1):='V'; v_ADATE DATE:=SYSDATE; v_ADOCIDE NVARCHAR2(2);--= IIF(len(allt(m.numdociden))=8,"1","0") v_lennumdocident NUMBER; v_AREFANE NVARCHAR2(1); v_ACODMON NVARCHAR2(1); v_AHORA NVARCHAR2(1); v_APATERNO NVARCHAR2(1); v_AMATERNO NVARCHAR2(1); v_ANOMBRE NVARCHAR2(1); v_AFORMSUS NVARCHAR2(1); v_ATELEFO NVARCHAR2(1); v_ATIPTRA NVARCHAR2(1); v_APROVIN NVARCHAR2(1); v_ADEPART NVARCHAR2(1); v_APAIS NVARCHAR2(1); v_AZONPOS NVARCHAR2(1); v_ANOMREP NVARCHAR2(1); v_ACARREP NVARCHAR2(1); v_AEMAIL NVARCHAR2(1); v_AHOST NVARCHAR2(1); v_dyesterday_process DATE; v_yesterday_month NUMBER; v_znumero_ini NUMBER; v_znumero_fin NUMBER; BEGIN select EXTRACT(YEAR FROM (v_ddate_process)) into v_year FROM DUAL; select EXTRACT(MONTH FROM (v_ddate_process)) into v_month FROM DUAL; select (v_ddate_process-1) into v_dyesterday_process FROM DUAL; select EXTRACT(MONTH FROM (v_dyesterday_process)) into v_yesterday_month FROM DUAL; v_znumero_ini:=NULL; IF v_month<>v_yesterday_month THEN v_znumero_ini:=1; ELSE SELECT (z.znumero_fin+1) INTO v_znumero_ini FROM BI.ZNUMERO z WHERE to_char(z.zdate_process,'DD-MM-RRRR')=to_char(v_dyesterday_process, 'DD-MM-RRRR'); END IF; IF v_znumero_ini IS NULL THEN v_znumero_ini:=1; END IF; select 4.00 into v_vartcambio from dual; DELETE FROM BI.CREAL m; DELETE FROM BI.DREAL d; DELETE FROM BI.RANEXO a; DELETE FROM BI.ZNUMERO z WHERE to_char(z.zdate_process,'DDMMRRRR')=to_char(v_ddate_process,'DDMMRRRR'); v_znumero:=v_znumero_ini; FOR INVOICE IN SC_INVOICE_DATA LOOP v_xnumeroc:=LPAD(to_char(INVOICE.dfemision,'MM'),2,'0')||LPAD(v_znumero,4,'0'); --cabecera v_CSUBDIA:='05B'; v_CCOMPRO:=v_xnumeroc; v_CFECCOM:=to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_CCODMON:='MN'; v_CSITUA:='F'; v_CTIPCAM:=v_vartcambio; SELECT 'VENTAS AYB '||DECODE(INVOICE.pcwsid,31,'- DELPHOS BISTRO',DECODE(INVOICE.pcwsid,43, '- OCEANUS REST.','- OCEANUS BAR')) INTO v_CGLOSA FROM DUAL; v_CTOTAL:=INVOICE.TOTALDOC; v_CTIPO:='V'; v_CFLAG:='S'; v_CDATE:=SYSDATE; v_CHORA:=TO_CHAR(SYSDATE, 'HH24:MI'); v_CFECCAM:=to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_CUSER:=''; v_CORIG:='MC'; v_CFORM:='A'; v_CTIPCOM:='V'; v_CEXTOR:=''; INSERT INTO BI.CREAL( CSUBDIA, CCOMPRO, CFECCOM, CCODMON, CSITUA, CTIPCAM, CGLOSA, CTOTAL, CTIPO, CFLAG, CDATE, CHORA, CFECCAM, CUSER, CORIG, CFORM, CTIPCOM, CEXTOR, ZNUMERO, DFEMISION )VALUES( v_CSUBDIA, v_CCOMPRO, v_CFECCOM, v_CCODMON, v_CSITUA, v_CTIPCAM, v_CGLOSA, v_CTOTAL, v_CTIPO, v_CFLAG, v_CDATE, v_CHORA, v_CFECCAM, v_CUSER, v_CORIG, v_CFORM, v_CTIPCOM, v_CEXTOR, v_znumero, INVOICE.dfemision ); -- detalle -- Base imponible v_dsubdia := '05B'; v_dcompro := v_xnumeroc; v_dsecue := '0001'; v_dfeccom := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); SELECT DECODE(INVOICE.pcwsid,31,'703211',DECODE(INVOICE.pcwsid,43,'703210', '703212')) INTO v_dcuenta FROM DUAL; v_dcodane := ''; SELECT DECODE(INVOICE.pcwsid,31,'200030',DECODE(INVOICE.pcwsid,43,'200031', '200032')) INTO v_dcencos FROM DUAL; v_dcodmon := 'MN'; v_ddh := 'H'; v_dimport := INVOICE.baseimponible; v_dtipdoc := ''; v_dnumdoc := ''; v_dfecdoc := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_dfecven := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_darea := ''; v_dflag := 'S'; SELECT DECODE(INVOICE.pcwsid,31,'VENTA DELPHOS',DECODE(INVOICE.pcwsid,43,'VENTAS RESTAURANT', 'VENTAS OCEANUS BAR')) INTO v_dxglosa FROM DUAL; v_ddate := INVOICE.dfemision; v_dcodane2 := ''; v_dusimpor := INVOICE.baseimponible/v_vartcambio; v_dmnimpor := INVOICE.baseimponible; v_dcodarc := ''; INSERT INTO BI.DREAL( DSUBDIA, DCOMPRO, DSECUE, DFECCOM, DCUENTA, DCODANE, DCENCOS, DCODMON, DDH, DIMPORT, DTIPDOC, DNUMDOC, DFECDOC, DFECVEN, DAREA, DFLAG, DXGLOSA, DDATE, DCODANE2, DUSIMPOR, DMNIMPOR, DCODARC, FLAGX, DMEDPAG, DIGVCOM, DTIDREF, DNDOREF, DFECREF, DBIMREF, DIGVREF, DMAQREF, ZNUMERO, DFEMISION )VALUES( V_DSUBDIA, V_DCOMPRO, V_DSECUE, V_DFECCOM, V_DCUENTA, V_DCODANE, V_DCENCOS, V_DCODMON, V_DDH, V_DIMPORT, V_DTIPDOC, V_DNUMDOC, V_DFECDOC, V_DFECVEN, V_DAREA, V_DFLAG, V_DXGLOSA, V_DDATE, V_DCODANE2, V_DUSIMPOR, V_DMNIMPOR, V_DCODARC, V_FLAGX, V_DMEDPAG, V_DIGVCOM, V_DTIDREF, V_DNDOREF, V_DFECREF, V_DBIMREF, V_DIGVREF, V_DMAQREF, v_znumero, INVOICE.dfemision ); -- impuesto v_dsubdia := '05B'; v_dcompro := v_xnumeroc; v_dsecue := '0002'; v_dfeccom := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_dcuenta := '401111'; v_dcodane := ''; v_dcencos := ''; v_dcodmon := 'MN'; v_ddh := 'H'; v_dimport := INVOICE.igv; v_dtipdoc := ''; v_dnumdoc := ''; v_dfecdoc := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_dfecven := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_darea := ''; v_dflag := 'S'; v_dxglosa := 'IGV'; v_ddate := INVOICE.dfemision; v_dcodane2 := ''; v_dusimpor := INVOICE.igv/v_vartcambio; v_dmnimpor := INVOICE.igv; v_dcodarc := ''; INSERT INTO BI.DREAL( DSUBDIA, DCOMPRO, DSECUE, DFECCOM, DCUENTA, DCODANE, DCENCOS, DCODMON, DDH, DIMPORT, DTIPDOC, DNUMDOC, DFECDOC, DFECVEN, DAREA, DFLAG, DXGLOSA, DDATE, DCODANE2, DUSIMPOR, DMNIMPOR, DCODARC, FLAGX, DMEDPAG, DIGVCOM, DTIDREF, DNDOREF, DFECREF, DBIMREF, DIGVREF, DMAQREF, ZNUMERO, DFEMISION )VALUES( V_DSUBDIA, V_DCOMPRO, V_DSECUE, V_DFECCOM, V_DCUENTA, V_DCODANE, V_DCENCOS, V_DCODMON, V_DDH, V_DIMPORT, V_DTIPDOC, V_DNUMDOC, V_DFECDOC, V_DFECVEN, V_DAREA, V_DFLAG, V_DXGLOSA, V_DDATE, V_DCODANE2, V_DUSIMPOR, V_DMNIMPOR, V_DCODARC, V_FLAGX, V_DMEDPAG, V_DIGVCOM, V_DTIDREF, V_DNDOREF, V_DFECREF, V_DBIMREF, V_DIGVREF, V_DMAQREF, v_znumero, INVOICE.dfemision ); -- Servicio v_dsubdia := '05B'; v_dcompro := v_xnumeroc; v_dsecue := '0003'; v_dfeccom := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_dcuenta := '419101'; v_dcodane := ''; v_dcencos := ''; v_dcodmon := 'MN'; v_ddh := 'H'; v_dimport := INVOICE.servicio; v_dtipdoc := ''; v_dnumdoc := ''; v_dfecdoc := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_dfecven := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_darea := ''; v_dflag := 'S'; v_dxglosa := 'SERVICIO'; v_ddate := INVOICE.dfemision; v_dcodane2 := ''; v_dusimpor := INVOICE.servicio/v_vartcambio; v_dmnimpor := INVOICE.servicio; v_dcodarc := ''; INSERT INTO BI.DREAL( DSUBDIA, DCOMPRO, DSECUE, DFECCOM, DCUENTA, DCODANE, DCENCOS, DCODMON, DDH, DIMPORT, DTIPDOC, DNUMDOC, DFECDOC, DFECVEN, DAREA, DFLAG, DXGLOSA, DDATE, DCODANE2, DUSIMPOR, DMNIMPOR, DCODARC, FLAGX, DMEDPAG, DIGVCOM, DTIDREF, DNDOREF, DFECREF, DBIMREF, DIGVREF, DMAQREF, ZNUMERO, DFEMISION )VALUES( V_DSUBDIA, V_DCOMPRO, V_DSECUE, V_DFECCOM, V_DCUENTA, V_DCODANE, V_DCENCOS, V_DCODMON, V_DDH, V_DIMPORT, V_DTIPDOC, V_DNUMDOC, V_DFECDOC, V_DFECVEN, V_DAREA, V_DFLAG, V_DXGLOSA, V_DDATE, V_DCODANE2, V_DUSIMPOR, V_DMNIMPOR, V_DCODARC, V_FLAGX, V_DMEDPAG, V_DIGVCOM, V_DTIDREF, V_DNDOREF, V_DFECREF, V_DBIMREF, V_DIGVREF, V_DMAQREF, v_znumero, INVOICE.dfemision ); -- Propina IF INVOICE.propina<>0.00 THEN v_dsubdia := '05B'; v_dcompro := v_xnumeroc; v_dsecue := '0004'; v_dfeccom := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_dcuenta := '419102'; v_dcodane := ''; v_dcencos := ''; v_dcodmon := 'MN'; v_ddh := 'H'; v_dimport := INVOICE.propina; v_dtipdoc := ''; v_dnumdoc := ''; v_dfecdoc := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_dfecven := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_darea := ''; v_dflag := 'S'; v_dxglosa := 'PROPINA'; v_ddate := INVOICE.dfemision; v_dcodane2 := ''; v_dusimpor := INVOICE.propina/v_vartcambio; v_dmnimpor := INVOICE.propina; v_dcodarc := ''; INSERT INTO BI.DREAL( DSUBDIA, DCOMPRO, DSECUE, DFECCOM, DCUENTA, DCODANE, DCENCOS, DCODMON, DDH, DIMPORT, DTIPDOC, DNUMDOC, DFECDOC, DFECVEN, DAREA, DFLAG, DXGLOSA, DDATE, DCODANE2, DUSIMPOR, DMNIMPOR, DCODARC, FLAGX, DMEDPAG, DIGVCOM, DTIDREF, DNDOREF, DFECREF, DBIMREF, DIGVREF, DMAQREF, ZNUMERO, DFEMISION )VALUES( V_DSUBDIA, V_DCOMPRO, V_DSECUE, V_DFECCOM, V_DCUENTA, V_DCODANE, V_DCENCOS, V_DCODMON, V_DDH, V_DIMPORT, V_DTIPDOC, V_DNUMDOC, V_DFECDOC, V_DFECVEN, V_DAREA, V_DFLAG, V_DXGLOSA, V_DDATE, V_DCODANE2, V_DUSIMPOR, V_DMNIMPOR, V_DCODARC, V_FLAGX, V_DMEDPAG, V_DIGVCOM, V_DTIDREF, V_DNDOREF, V_DFECREF, V_DBIMREF, V_DIGVREF, V_DMAQREF, v_znumero, INVOICE.dfemision ); END IF; -- Total v_dsubdia := '05B'; v_dcompro := v_xnumeroc; SELECT CASE WHEN INVOICE.propina<>0 THEN '0005' ELSE '0004' END INTO v_dsecue FROM DUAL; v_dfeccom := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_dcuenta := '121201'; if INVOICE.numdocident IS NULL THEN SELECT DECODE(INVOICE.pcwsid,2,'11111111112',DECODE(INVOICE.pcwsid,5,'11111111115', '11111111117')) INTO v_dcodane FROM DUAL; else v_dcodane := INVOICE.numdocident; end if; v_dcencos := ''; v_dcodmon := 'MN'; v_ddh := 'D'; v_dimport := INVOICE.totaldoc; SELECT DECODE(INVOICE.tdoc,'B','BV',DECODE(INVOICE.tdoc,'F', 'FT','')) INTO v_dtipdoc FROM DUAL; v_dnumdoc := substr(INVOICE.numdoc,1,4)||substr(INVOICE.numdoc,6,7); v_dfecdoc := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_dfecven := to_char(INVOICE.dfemision,'RR')||to_char(INVOICE.dfemision,'MM')||to_char(INVOICE.dfemision, 'DD'); v_darea := ''; v_dflag := 'S'; v_dxglosa := TRIM(INVOICE.nombre); v_ddate := INVOICE.dfemision; v_dcodane2 := ''; v_dusimpor := INVOICE.totaldoc/v_vartcambio; v_dmnimpor := INVOICE.totaldoc; v_dcodarc := ''; INSERT INTO BI.DREAL( DSUBDIA, DCOMPRO, DSECUE, DFECCOM, DCUENTA, DCODANE, DCENCOS, DCODMON, DDH, DIMPORT, DTIPDOC, DNUMDOC, DFECDOC, DFECVEN, DAREA, DFLAG, DXGLOSA, DDATE, DCODANE2, DUSIMPOR, DMNIMPOR, DCODARC, FLAGX, DMEDPAG, DIGVCOM, DTIDREF, DNDOREF, DFECREF, DBIMREF, DIGVREF, DMAQREF, ZNUMERO, DFEMISION )VALUES( V_DSUBDIA, V_DCOMPRO, V_DSECUE, V_DFECCOM, V_DCUENTA, V_DCODANE, V_DCENCOS, V_DCODMON, V_DDH, V_DIMPORT, V_DTIPDOC, V_DNUMDOC, V_DFECDOC, V_DFECVEN, V_DAREA, V_DFLAG, V_DXGLOSA, V_DDATE, V_DCODANE2, V_DUSIMPOR, V_DMNIMPOR, V_DCODARC, V_FLAGX, V_DMEDPAG, V_DIGVCOM, V_DTIDREF, V_DNDOREF, V_DFECREF, V_DBIMREF, V_DIGVREF, V_DMAQREF, v_znumero, INVOICE.dfemision ); --Anexos v_AVANEXO:='C'; v_ACODANE:=INVOICE.numdocident; v_ADESANE:=INVOICE.nombre; v_ARUC:=INVOICE.numdocident; v_AESTADO:='V'; v_ADATE:=SYSDATE; --= IIF(len(allt(m.numdociden))=8,"1","0") v_lennumdocident:=LENGTH(RTRIM(LTRIM(INVOICE.numdocident))); v_ADOCIDE:='0'; IF v_lennumdocident=8 THEN v_ADOCIDE:='1'; END IF; v_AREFANE:=''; v_ACODMON:=''; v_AHORA:=''; v_APATERNO:=''; v_AMATERNO:=''; v_ANOMBRE:=''; v_AFORMSUS:=''; v_ATELEFO:=''; v_ATIPTRA:=''; v_APROVIN:=''; v_ADEPART:=''; v_APAIS:=''; v_AZONPOS:=''; v_ANOMREP:=''; v_ACARREP:=''; v_AEMAIL:=''; v_AHOST:=''; INSERT INTO BI.RANEXO( AVANEXO, ACODANE, ADESANE, AREFANE, ARUC, ACODMON, AESTADO, ADATE, AHORA, APATERNO, AMATERNO, ANOMBRE, AFORMSUS, ATELEFO, ATIPTRA, APROVIN, ADEPART, APAIS, AZONPOS, ANOMREP, ACARREP, AEMAIL, AHOST, ADOCIDE )VALUES ( v_AVANEXO, v_ACODANE, v_ADESANE, v_AREFANE, v_ARUC, v_ACODMON, v_AESTADO, v_ADATE, v_AHORA, v_APATERNO, v_AMATERNO, v_ANOMBRE, v_AFORMSUS, v_ATELEFO, v_ATIPTRA, v_APROVIN, v_ADEPART, v_APAIS, v_AZONPOS, v_ANOMREP, v_ACARREP, v_AEMAIL, v_AHOST, v_ADOCIDE ); v_znumero:=v_znumero+1; END LOOP; INSERT INTO BI.ZNUMERO( ZNUMERO_INI, ZNUMERO_FIN, ZDATE_PROCESS , ZDATE_AUDIT , ZMONTH_PROCESS , ZYEAR_PROCESS )VALUES( v_znumero_ini, (v_znumero-1), v_ddate_process, SYSDATE, v_month, v_year ); COMMIT; --execute BI.SP_CREATE_MICROS_DBF; END;
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ include file="/common/taglibs.jsp"%> <!DOCTYPE html> <html lang="en"> <head> <link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="description" content="" /> <meta name="author" content="" /> <link rel="icon" href="<c:url value="/resources/assets/images/favicon.ico"/>"> <title></title> <link rel="stylesheet" href="<c:url value=" /resources/assets/js/jquery-ui/css/no-theme/jquery-ui-1.10.3.custom.min.css"/>"> <link rel="stylesheet" href="<c:url value=" /resources/assets/css/font-icons/entypo/css/entypo.css"/>"> <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Noto+Sans:400,700,400italic"> <link rel="stylesheet" href="<c:url value="/resources/assets/css/bootstrap.css "/>"> <link rel="stylesheet" href="<c:url value="/resources/assets/css/neon-core.css "/>"> <link rel="stylesheet" href="<c:url value="/resources/assets/css/neon-theme.css "/>"> <link rel="stylesheet" href="<c:url value="/resources/assets/css/neon-forms.css "/>"> <link rel="stylesheet" href="<c:url value="/resources/assets/css/custom.css "/>"> <script src="./resources/assets/js/jquery-1.11.3.min.js"></script> <script type="text/javascript" src="<c:url value="/resources/js/fn_rooms.js?2 " />"></script> <style> .panel-brown > .panel-heading { background-color: #c97f7f; } .label-brown { background-color: #A52A2A; } </style> </head> <body class="page-body"> <div class="container"> <div class="panel-group"> <div class="panel panel-invert"> <div class="panel-heading clearfix"> <h4 class="panel-title pull-left"><b>Disponibilidad de habitaciones</b></h4> <div class="btn-group pull-right"> <img src="./resources/assets/img/logo.png" height="40px"> </div> </div> </div> <div class="panel panel-gradient"> <div class="col-md-6 col-sm-6 col-xs-6 col-sm-6 col-xs-6 "> <button id="cmdIngresar" style="width:100%" class= "btn btn-block btn-success ripple-effect" type="button" name="Submit" alt="sign in">Cambiar Password</button> </div> <div class="col-md-6 col-sm-6 col-xs-6 col-sm-6 col-xs-6 "> <button id="cmdSalir" style="width:100%" class= "btn btn-block btn-danger ripple-effect" type="button" name="Submit" alt="sign in">Salir</button> </div> </div> <div class="panel panel-gradient"> <div class="panel-heading clearfix"> <div class="panel-heading clearfix"> <input type="hidden" id="hIdBusinessDate"> <input id="txtBusinessDate" type="text" placeholder= "Desde" value="${name_day}" required="required" list="lBusinessDate" data-list='lBusinessDate' autocomplete="off" class="form-control k-textbox" data-role="text" > <datalist id="lBusinessDate"> <option data-value="0" id="0" value="Todos"></option> <c:forEach items="${items}" var="o" varStatus= "i" > <option data-value="${o.n}" id="${o.n}" value="${o.businessDate}"></option> </c:forEach> </datalist> </div> <c:forEach items="${lista}" var="o" varStatus="i" > <div class="col-sm-6 col-xs-12"> <div class="tile-stats tile-orange"> <div class="icon"><p style="font-weight: bold;" >${o.businssDate} ${o.diaSemana}</p></div> <c:if test="${(o.diaSemana eq 'Domingo') }"> <div class="icon"><i class="entypo-volume"></i></div> </c:if> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12 col-sm-12 col-xs-12"> <div class="form-group"> <P style="font-weight: bold;${o.availability<0?'color:#000000;':'font-weight: bold'}" class="col-md-4 col-md-4 col-sm-4 col-xs-4 col-xs-4">Disponible ${o.availability}</P> <P class="col-md-4 col-md-4 col-sm-4 col-xs-4 col-xs-4"></P> <P style="font-weight: bold;${o.avalCatPS<0?'color:#000000;':'font-weight: bold'}" class="col-md-4 col-md-4 col-sm-4 col-xs-4 col-xs-4">PS ${o.avalCatPS}</P> </div> </div> </div> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="form-group"> <P style="font-weight: bold;${o.avalCatSK<0?'color:#000000;':''}" class="col-md-4 col-sm-4 col-xs-4">SK ${o.avalCatSK}</P> <P style="font-weight: bold;${o.avalCatST<0?'color:#000000;':''}" class="col-md-4 col-sm-4 col-xs-4">ST ${o.avalCatST}</P> <P style="font-weight: bold;${o.avalCatPK<0?'color:#000000;':''}" class="col-md-4 col-sm-4 col-xs-4">PK ${o.avalCatPK}</P> </div> </div> </div> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="form-group"> <P style="font-weight: bold;${o.avalCatPT<0?'color:#000000;':''}" class="col-md-4 col-sm-4 col-xs-4">PT ${o.avalCatPT}</P> <P style="font-weight: bold;${o.avalCatEK<0?'color:#000000;':''}" class="col-md-4 col-sm-4 col-xs-4">EK ${o.avalCatEK}</P> <P style="font-weight: bold;${o.avalCatET<0?'color:#000000;':''}" class="col-md-4 col-sm-4 col-xs-4">ET ${o.avalCatET}</P> </div> </div> </div> <div class="row"> <div class="col-md-12 col-sm-12 col-xs-12"> <div class="form-group"> <P style="font-weight: bold;${o.avalCatJS<0?'color:#000000;':''}" class="col-md-4 col-sm-4 col-xs-4">JS ${o.avalCatJS}</P> <P style="font-weight: bold;${o.avalCatSS<0?'color:#000000;':''}" class="col-md-4 col-sm-4 col-xs-4">SS ${o.avalCatSS}</P> <P style="font-weight: bold;${o.avalCatDL<0?'color:#000000;':''}" class="col-md-4 col-sm-4 col-xs-4">DL ${o.avalCatDL}</P> </div> </div> </div> </div> </div> </c:forEach> </div> </div> </div> </div> <script> var baseURL=$('#contextPathHolder').attr('data-contextPath'); $("#txtBusinessDate").on('input', function () { var val = this.value; if($('#lBusinessDate option').filter(function(){ return this.value.toUpperCase() === val.toUpperCase(); }).length) { //send ajax request filter(); } }); $("#txtBusinessDate").keyup(function(event) { if (event.keyCode === 13) { var selectedOption = $("#lBusinessDate option[value='" + $(this).val() + "']"); var selectedPerson = parseInt(selectedOption.attr('data-value')); if (selectedPerson) { filter(); } else { rooms(); } } }); function rooms(){ var businessDate='Todos'; var idBusinessDate=0; if(idBusinessDate>=0){ $.ajax({ url : baseURL + "/setfilter", data : { id: idBusinessDate, day:businessDate }, async:false, type : "get", success : function(Id) { window.location.replace(baseURL+"/rooms"); }, error : function(err) { alert(err); } }); } } function filter(){ var businessDate=$("#txtBusinessDate").val(); var idBusinessDate=getIdBusinessDate($("#txtBusinessDate").val()); if(idBusinessDate>=0){ $.ajax({ url : baseURL + "/setfilter", data : { id: idBusinessDate, day:businessDate }, async:false, type : "get", success : function(Id) { window.location.replace(baseURL+"/rooms"); }, error : function(err) { alert(err); } }); } } function getIdBusinessDate(str){ var selectedOption = $("#lBusinessDate option[value='" + str + "']"); var selectedId = parseInt(selectedOption.attr('data-value')); if (selectedId>=0) { return selectedId; } else { return -1; } } </script> <!-- Imported styles on this page --> <link rel="stylesheet" href="<c:url value="/resources/assets/js/jvectormap/jquery-jvectormap-1.2.2.css" />"> <link rel="stylesheet" href="<c:url value="/resources/assets/js/rickshaw/rickshaw.min.css" />"> <link rel="stylesheet" href="<c:url value="/resources/assets/css/font-icons/font-awesome/css/font-awesome.min.css" />"> <!-- Bottom scripts (common) --> <script src="<c:url value="/resources/assets/js/gsap/TweenMax.min.js" />"></script> <script src="<c:url value="/resources/assets/js/jquery-ui/js/jquery-ui-1.10.3.minimal.min.js" />"></script> <script src="<c:url value="/resources/assets/js/bootstrap.js" />"></script> <script src="<c:url value="/resources/assets/js/joinable.js" />"></script> <script src="<c:url value="/resources/assets/js/resizeable.js" />"></script> <script src="<c:url value="/resources/assets/js/neon-api.js" />"></script> <script src="<c:url value="/resources/assets/js/jvectormap/jquery-jvectormap-1.2.2.min.js" />"></script> <!-- Imported scripts on this page --> <script src="<c:url value="/resources/assets/js/jvectormap/jquery-jvectormap-europe-merc-en.js" />"></script> <script src="<c:url value="/resources/assets/js/jquery.sparkline.min.js" />"></script> <script src="<c:url value="/resources/assets/js/rickshaw/vendor/d3.v3.js" />"></script> <script src="<c:url value="/resources/assets/js/rickshaw/rickshaw.min.js" />"></script> <script src="<c:url value="/resources/assets/js/raphael-min.js" />"></script> <script src="<c:url value="/resources/assets/js/morris.min.js" />"></script> <script src="<c:url value="/resources/assets/js/toastr.js" />"></script> <!-- JavaScripts initializations and stuff --> <script src="<c:url value="/resources/assets/js/neon-custom.js" />"></script> <!-- Demo Settings --> <script src="<c:url value="/resources/assets/js/neon-demo.js" />"></script> </body> </html>
package com.hotel.spring.controller; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.hotel.Constante; import com.hotel.dao.ConnectionFactoryOperaBat; import com.hotel.dao.ConnectionFactorySQLAWS; public class LoadDataBedsOpera2SQLAWS { public static void main(String[] args) { try{ LoadDataBedsOpera2SQLAWS load=new LoadDataBedsOpera2SQLAWS(); Integer qty=load.loadAvailabilityBeds(45); if(qty>0){ qty=load.loadDetailsRoomAvailBeds(45); if(qty>0){ load.enableBedAvailability(); } } System.out.println("Inserted "+qty); }catch(Exception e){ e.printStackTrace(); } } public Integer loadAvailabilityBeds(Integer days)throws Exception{ Integer qty = 1; ResultSet rs=null; Statement stmt=null; Connection conn=null; try { conn = ConnectionFactoryOperaBat.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT MAX(t.n) n,t.business_date,t.categoria,SUM(t.capacidad) capacity,SUM(t.ocupability) ocupability, SUM(t.capacidad-t.ocupability) availability FROM ( "); query.append(" SELECT ns.n,to_char((pms_p.business_date+ns.n-1),'DD/MM/RRRR') business_date,c.label categoria,c.capacidad,0 ocupability "); query.append(" FROM number_scale ns "); query.append(" INNER JOIN ( "); query.append(" SELECT c.label,count(1) capacidad FROM ( "); query.append(" SELECT HLD_GET_CANT_BEDS(r.room_category,r.room) label "); query.append(" FROM OPERA.ROOM r "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); query.append(" ) c GROUP BY c.label "); query.append(" ) c ON (1=1) "); query.append(" WHERE ns.n <= ( (pms_p.business_date+").append(days).append(") - pms_p.business_date+1) "); query.append(" UNION ALL "); query.append(" SELECT 0 n,t.considered_date,t.label categoria,0 capacidad,SUM(t.ocupability) ocupability from ( "); query.append(" SELECT TO_CHAR(a.CONSIDERED_DATE,'DD/MM/RRRR') CONSIDERED_DATE,HLD_GET_CANT_BEDS(b.room_category,b.room) label,1 ocupability "); query.append(" FROM reservation_summary a,reservation_general_view_hld b "); query.append(" where (a.CONSIDERED_DATE BETWEEN pms_p.business_date and pms_p.business_date+").append(days).append(") and "); query.append(" a.room_category>0 and a.event_type='R' and a.no_rooms>0 and ( a.resv_status is null or a.resv_status<>'PROSPECT') and "); query.append(" a.event_id=b.resv_name_id(+) "); query.append(" union all "); query.append(" SELECT TO_CHAR(a.CONSIDERED_DATE,'DD/MM/RRRR') CONSIDERED_DATE,'1' label, a.no_rooms ocupability "); query.append(" FROM reservation_summary a,sc_busblock_info b "); query.append(" where (a.CONSIDERED_DATE BETWEEN pms_p.business_date and pms_p.business_date+").append(days).append(") and "); query.append(" a.room_category>0 and a.event_type='B' and a.no_rooms>0 and ( a.resv_status is null or a.resv_status<>'PROSPECT') and "); query.append(" a.allotment_header_id=b.busblock_id and b.status<>'F' "); query.append(" ) t "); query.append(" group by t.CONSIDERED_DATE,t.label "); query.append(" )t WHERE t.categoria<>'0' "); query.append(" group by t.business_date,t.categoria "); query.append(" having SUM(t.capacidad)>0 "); query.append(" ORDER BY to_date(t.business_date,'DD/MM/RRRR'),t.categoria "); stmt=conn.createStatement(); rs=stmt.executeQuery(query.toString()); StringBuilder detail = new StringBuilder(); Integer seq=getCurrentId(); while(rs.next()){ detail.append("(") .append(rs.getInt("n")).append(",") .append("CONVERT(DATETIME,'").append(rs.getString("business_date")).append("',103)").append(",") .append("'").append(rs.getString("categoria")).append("'").append(",") .append(rs.getInt("capacity")).append(",") .append(rs.getInt("ocupability")).append(",") .append(rs.getInt("availability")).append(",") .append("getdate()").append(",") .append("0").append(",") .append(seq) .append("),"); if((qty%1000)==0){ insertAvailability(detail.toString().substring(0, detail.toString().length()-1)+";"); detail = new StringBuilder(); System.out.println(qty); } qty++; } if(qty>0){ insertAvailability(detail.toString().substring(0, detail.toString().length()-1)+";"); detail = new StringBuilder(); System.out.println(qty); } } catch (Exception e) { qty=0; throw new RuntimeException(e); } finally { if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}} if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return qty; } private void insertAvailability(String details)throws Exception{ Statement stmt=null; Connection conn=null; try { conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append("INSERT INTO dbo.bed_availability(n,business_date,category,capacity,ocupability,availability,auinsertdate,austate,seq_room_availability)VALUES "); query.append(details); stmt=conn.createStatement(); stmt.executeUpdate(query.toString()); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); }finally { if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}} if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}} } } public Integer loadDetailsRoomAvailBeds(Integer days)throws Exception{ Integer qty = 1; ResultSet rs=null; Statement stmt=null; Connection conn=null; try { conn = ConnectionFactoryOperaBat.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT MAX(t.n) n,t.business_date,t.room,t.label,t.room_category_label,SUM(t.ESTADO) ROOM_STATE,MAX(t.room_status) room_status,MAX(t.hk_status) hk_status FROM ( "); query.append(" SELECT ns.n,to_char((pms_p.business_date+ns.n-1),'DD/MM/RRRR') business_date,c.room,c.label,c.room_category_label,c.estado ,c.room_status,c.hk_status "); query.append(" FROM number_scale ns "); query.append(" INNER JOIN ( "); query.append(" SELECT r.room,HLD_GET_CANT_BEDS(r.room_category,r.room) label,c.label room_category_label, 0 ESTADO ,r.room_status,r.hk_status "); query.append(" FROM OPERA.ROOM r "); query.append(" INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); query.append(" ) c ON (1=1) "); query.append(" WHERE ns.n <= ( (pms_p.business_date+").append(days).append(") - pms_p.business_date+1) "); query.append(" UNION ALL "); query.append(" SELECT 0 n,TO_CHAR(a.CONSIDERED_DATE,'DD/MM/RRRR') CONSIDERED_DATE,b.room,HLD_GET_CANT_BEDS(b.room_category,b.room) label,b.room_category_label, 1 ESTADO, NULL room_status,NULL hk_status "); query.append(" FROM reservation_summary a,reservation_general_view_hld b "); query.append(" where (a.CONSIDERED_DATE BETWEEN pms_p.business_date and pms_p.business_date+").append(days).append(") and "); query.append(" a.room_category>0 and a.event_type='R' and a.no_rooms>0 and ( a.resv_status is null or a.resv_status<>'PROSPECT') and "); query.append(" a.event_id=b.resv_name_id(+) "); query.append(" ) t "); query.append(" GROUP BY t.business_date,t.room,t.label,t.room_category_label "); query.append(" order by to_date(t.business_date,'DD/MM/RRRR'),t.room "); stmt=conn.createStatement(); rs=stmt.executeQuery(query.toString()); StringBuilder detail = new StringBuilder(); while(rs.next()){ detail.append("(") .append(rs.getInt("n")).append(",") .append("CONVERT(DATETIME,'").append(rs.getString("business_date")).append("',103)").append(",") .append("'").append(rs.getString("room")).append("'").append(",") .append("'").append(rs.getString("label")).append("'").append(",") .append("'").append(rs.getString("room_category_label")).append("'").append(",") .append(rs.getInt("ROOM_STATE")).append(",") .append("'").append(rs.getString("room_status")).append("'").append(",") .append("'").append(rs.getString("hk_status")).append("'").append(",") .append("getdate()").append(",") .append("0").append("),"); if((qty%1000)==0){ insertAvailabilityDetails(detail.toString().substring(0, detail.toString().length()-1)+";"); detail = new StringBuilder(); System.out.println(qty); } qty++; } if(qty>0){ insertAvailabilityDetails(detail.toString().substring(0, detail.toString().length()-1)+";"); detail = new StringBuilder(); System.out.println("inserted details "+qty); } } catch (Exception e) { qty=0; throw new RuntimeException(e); } finally { if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}} if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return qty; } private void insertAvailabilityDetails(String details)throws Exception{ Statement stmt=null; Connection conn=null; try { conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append("INSERT INTO dbo.bed_availability_detail(n,business_date,room,label,category,room_state,room_status,hk_status,auinsertdate,austate)VALUES "); query.append(details); stmt=conn.createStatement(); stmt.executeUpdate(query.toString()); } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception e) { throw new RuntimeException(e); }finally { if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}} if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}} } } public Integer enableBedAvailability() throws Exception{ CallableStatement cs = null; Integer deleted=Constante.ID_INICIAL; try { Connection conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append("{ CALL dbo.update_bed_availability(?) }"); cs = conn.prepareCall(query.toString()); cs.registerOutParameter(1, java.sql.Types.INTEGER); cs.execute(); deleted=cs.getInt(1); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (cs != null) {try {cs.close();} catch (SQLException e) {e.printStackTrace();}} } return deleted; } public Integer getCurrentId(){ Integer result=Constante.ID_INICIAL; PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append("SELECT id_current FROM dbo.seq_room_availability"); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); if(rs.next()){ result=rs.getInt("id_current"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return result; } }
package com.hotel.business; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.hotel.dao.ConnectionFactorySQLAWS; import com.hotel.vo.AvalBedStatus; import com.hotel.vo.AvalBusinessDate; import com.hotel.vo.AvalCategoryStatus; import com.hotel.vo.Value; public class OperaRoomBo { public List<AvalCategoryStatus> listRoomCategoryStatus(){ List<AvalCategoryStatus> lista = new ArrayList<>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select r.n,MAX(convert(varchar(10),r.business_date,103)) business_date,MAX(dbo.GetDiaSemana(convert(date,r.business_date,103))) dia_semana, "); query.append(" SUM(CASE WHEN r.category='DL' THEN r.availability ELSE 0 END) category_dl, "); query.append(" SUM(CASE WHEN r.category='EK' THEN r.availability ELSE 0 END) category_ek, "); query.append(" SUM(CASE WHEN r.category='ET' THEN r.availability ELSE 0 END) category_et, "); query.append(" SUM(CASE WHEN r.category='JS' THEN r.availability ELSE 0 END) category_js, "); query.append(" SUM(CASE WHEN r.category='PK' THEN r.availability ELSE 0 END) category_pk, "); query.append(" SUM(CASE WHEN r.category='PS' THEN r.availability ELSE 0 END) category_ps, "); query.append(" SUM(CASE WHEN r.category='PT' THEN r.availability ELSE 0 END) category_pt, "); query.append(" SUM(CASE WHEN r.category='SK' THEN r.availability ELSE 0 END) category_sk, "); query.append(" SUM(CASE WHEN r.category='SS' THEN r.availability ELSE 0 END) category_ss, "); query.append(" SUM(CASE WHEN r.category='ST' THEN r.availability ELSE 0 END) category_st, "); query.append(" SUM(r.capacity) capacity, "); query.append(" SUM(r.ocupability) ocupability, "); query.append(" SUM(r.availability) availability "); query.append(" from dbo.room_availability r where r.austate=1 "); query.append(" group by r.n "); query.append(" order by r.n "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ AvalCategoryStatus obj=new AvalCategoryStatus(); obj.setN(rs.getInt("n")); obj.setBusinssDate(rs.getString("business_date")); obj.setDiaSemana(rs.getString("dia_semana")); obj.setAvalCatDL(rs.getInt("category_dl")); obj.setAvalCatEK(rs.getInt("category_ek")); obj.setAvalCatET(rs.getInt("category_et")); obj.setAvalCatJS(rs.getInt("category_js")); obj.setAvalCatPK(rs.getInt("category_pk")); obj.setAvalCatPS(rs.getInt("category_ps")); obj.setAvalCatPT(rs.getInt("category_pt")); obj.setAvalCatSK(rs.getInt("category_sk")); obj.setAvalCatSS(rs.getInt("category_ss")); obj.setAvalCatST(rs.getInt("category_st")); obj.setCapacity(rs.getInt("capacity")); obj.setOcupability(rs.getInt("ocupability")); obj.setAvailability(rs.getInt("availability")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<AvalCategoryStatus> listRoomCategoryStatus(Integer n){ List<AvalCategoryStatus> lista = new ArrayList<>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select r.n,MAX(convert(varchar(10),r.business_date,103)) business_date,MAX(dbo.GetDiaSemana(convert(date,r.business_date,103))) dia_semana, "); query.append(" SUM(CASE WHEN r.category='DL' THEN r.availability ELSE 0 END) category_dl, "); query.append(" SUM(CASE WHEN r.category='EK' THEN r.availability ELSE 0 END) category_ek, "); query.append(" SUM(CASE WHEN r.category='ET' THEN r.availability ELSE 0 END) category_et, "); query.append(" SUM(CASE WHEN r.category='JS' THEN r.availability ELSE 0 END) category_js, "); query.append(" SUM(CASE WHEN r.category='PK' THEN r.availability ELSE 0 END) category_pk, "); query.append(" SUM(CASE WHEN r.category='PS' THEN r.availability ELSE 0 END) category_ps, "); query.append(" SUM(CASE WHEN r.category='PT' THEN r.availability ELSE 0 END) category_pt, "); query.append(" SUM(CASE WHEN r.category='SK' THEN r.availability ELSE 0 END) category_sk, "); query.append(" SUM(CASE WHEN r.category='SS' THEN r.availability ELSE 0 END) category_ss, "); query.append(" SUM(CASE WHEN r.category='ST' THEN r.availability ELSE 0 END) category_st, "); query.append(" SUM(r.capacity) capacity, "); query.append(" SUM(r.ocupability) ocupability, "); query.append(" SUM(r.availability) availability "); query.append(" from dbo.room_availability r where r.austate=1 "); query.append(" and r.n>=? "); query.append(" group by r.n "); query.append(" order by r.n "); ps = conn.prepareStatement(query.toString()); ps.setInt(1, n); rs = ps.executeQuery(); while(rs.next()){ AvalCategoryStatus obj=new AvalCategoryStatus(); obj.setN(rs.getInt("n")); obj.setBusinssDate(rs.getString("business_date")); obj.setDiaSemana(rs.getString("dia_semana")); obj.setAvalCatDL(rs.getInt("category_dl")); obj.setAvalCatEK(rs.getInt("category_ek")); obj.setAvalCatET(rs.getInt("category_et")); obj.setAvalCatJS(rs.getInt("category_js")); obj.setAvalCatPK(rs.getInt("category_pk")); obj.setAvalCatPS(rs.getInt("category_ps")); obj.setAvalCatPT(rs.getInt("category_pt")); obj.setAvalCatSK(rs.getInt("category_sk")); obj.setAvalCatSS(rs.getInt("category_ss")); obj.setAvalCatST(rs.getInt("category_st")); obj.setCapacity(rs.getInt("capacity")); obj.setOcupability(rs.getInt("ocupability")); obj.setAvailability(rs.getInt("availability")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<AvalBusinessDate> listBusinessDate(){ List<AvalBusinessDate> lista = new ArrayList<>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select r.n,MAX(convert(varchar(10),r.business_date,103)) business_date,MAX(dbo.GetDiaSemana(convert(date,r.business_date,103))) dia_semana "); query.append(" from dbo.room_availability r where r.austate=1 "); query.append(" group by r.n "); query.append(" order by r.n "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ StringBuilder item = new StringBuilder(); item.append(rs.getString("business_date")).append(" ").append(rs.getString("dia_semana")); AvalBusinessDate obj=new AvalBusinessDate(); obj.setN(rs.getInt("n")); obj.setBusinessDate(item.toString()); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } /*** * */ public List<AvalBedStatus> listBedsCategoryStatus(){ List<AvalBedStatus> lista = new ArrayList<>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select r.n,MAX(convert(varchar(10),r.business_date,103)) business_date,MAX(dbo.GetDiaSemana(convert(date,r.business_date,103))) dia_semana, "); query.append(" SUM(CASE WHEN r.category='0' THEN r.availability ELSE 0 END) aval_0, "); query.append(" SUM(CASE WHEN r.category='1' THEN r.availability*1 ELSE 0 END) aval_1, "); query.append(" SUM(CASE WHEN r.category='2' THEN r.availability*2 ELSE 0 END) aval_2, "); query.append(" SUM(CASE WHEN r.category='3' THEN r.availability*3 ELSE 0 END) aval_3, "); query.append(" SUM(CASE WHEN r.category='4' THEN r.availability*4 ELSE 0 END) aval_4, "); query.append(" SUM(CASE WHEN r.category='0' THEN r.ocupability ELSE 0 END) ocup_0, "); query.append(" SUM(CASE WHEN r.category='1' THEN r.ocupability*1 ELSE 0 END) ocup_1, "); query.append(" SUM(CASE WHEN r.category='2' THEN r.ocupability*2 ELSE 0 END) ocup_2, "); query.append(" SUM(CASE WHEN r.category='3' THEN r.ocupability*3 ELSE 0 END) ocup_3, "); query.append(" SUM(CASE WHEN r.category='4' THEN r.ocupability*4 ELSE 0 END) ocup_4, "); query.append(" SUM(r.capacity) capacity, "); query.append(" SUM(r.ocupability) ocupability, "); query.append(" SUM(r.availability) availability "); query.append(" from dbo.bed_availability r where r.austate=1 "); query.append(" group by r.n "); query.append(" order by r.n "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ AvalBedStatus obj=new AvalBedStatus(); obj.setN(rs.getInt("n")); obj.setBusinssDate(rs.getString("business_date")); obj.setDiaSemana(rs.getString("dia_semana")); obj.setAvalCat0(rs.getInt("aval_0")); obj.setAvalCat1(rs.getInt("aval_1")); obj.setAvalCat2(rs.getInt("aval_2")); obj.setAvalCat3(rs.getInt("aval_3")); obj.setAvalCat4(rs.getInt("aval_4")); obj.setCapacity(rs.getInt("capacity")); obj.setOcupability(rs.getInt("ocupability")); obj.setAvailability(rs.getInt("availability")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<AvalBedStatus> listBedsCategoryStatus(Integer n){ List<AvalBedStatus> lista = new ArrayList<>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select r.n,MAX(convert(varchar(10),r.business_date,103)) business_date,MAX(dbo.GetDiaSemana(convert(date,r.business_date,103))) dia_semana, "); query.append(" SUM(CASE WHEN r.category='0' THEN r.availability ELSE 0 END) aval_0, "); query.append(" SUM(CASE WHEN r.category='1' THEN r.availability*1 ELSE 0 END) aval_1, "); query.append(" SUM(CASE WHEN r.category='2' THEN r.availability*2 ELSE 0 END) aval_2, "); query.append(" SUM(CASE WHEN r.category='3' THEN r.availability*3 ELSE 0 END) aval_3, "); query.append(" SUM(CASE WHEN r.category='4' THEN r.availability*4 ELSE 0 END) aval_4, "); query.append(" SUM(CASE WHEN r.category='0' THEN r.ocupability ELSE 0 END) ocup_0, "); query.append(" SUM(CASE WHEN r.category='1' THEN r.ocupability*1 ELSE 0 END) ocup_1, "); query.append(" SUM(CASE WHEN r.category='2' THEN r.ocupability*2 ELSE 0 END) ocup_2, "); query.append(" SUM(CASE WHEN r.category='3' THEN r.ocupability*3 ELSE 0 END) ocup_3, "); query.append(" SUM(CASE WHEN r.category='4' THEN r.ocupability*4 ELSE 0 END) ocup_4, "); query.append(" SUM(r.capacity) capacity, "); query.append(" SUM(r.ocupability) ocupability, "); query.append(" SUM(r.availability) availability "); query.append(" from dbo.bed_availability r where r.austate=1 "); query.append(" and r.n>=? "); query.append(" group by r.n "); query.append(" order by r.n "); ps = conn.prepareStatement(query.toString()); ps.setInt(1, n); rs = ps.executeQuery(); while(rs.next()){ AvalBedStatus obj=new AvalBedStatus(); obj.setN(rs.getInt("n")); obj.setBusinssDate(rs.getString("business_date")); obj.setDiaSemana(rs.getString("dia_semana")); obj.setAvalCat0(rs.getInt("aval_0")); obj.setAvalCat1(rs.getInt("aval_1")); obj.setAvalCat2(rs.getInt("aval_2")); obj.setAvalCat3(rs.getInt("aval_3")); obj.setAvalCat4(rs.getInt("aval_4")); obj.setCapacity(rs.getInt("capacity")); obj.setOcupability(rs.getInt("ocupability")); obj.setAvailability(rs.getInt("availability")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<AvalBusinessDate> listBusinessDateBeds(){ List<AvalBusinessDate> lista = new ArrayList<>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select r.n,MAX(convert(varchar(10),r.business_date,103)) business_date,MAX(dbo.GetDiaSemana(convert(date,r.business_date,103))) dia_semana "); query.append(" from dbo.bed_availability r where r.austate=1 "); query.append(" group by r.n "); query.append(" order by r.n "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ StringBuilder item = new StringBuilder(); item.append(rs.getString("business_date")).append(" ").append(rs.getString("dia_semana")); AvalBusinessDate obj=new AvalBusinessDate(); obj.setN(rs.getInt("n")); obj.setBusinessDate(item.toString()); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<Value> listaRoomsDetail(Integer n,String label){ List<Value> lista = new ArrayList<>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactorySQLAWS.getInstance().getConnection(); StringBuilder query = new StringBuilder(); if(label.equals("9")){ query.append(" SELECT room,category,n,label,(CASE WHEN n=1 THEN (ISNULL(room_status,'-') +'-'+ ISNULL(hk_status,'-')) ELSE '-' END) status,(CASE label WHEN 1 THEN 'SPL' WHEN 2 THEN 'DBL' WHEN 3 THEN 'TRP' WHEN 4 THEN 'CDP' ELSE '-' END) label_desc FROM dbo.bed_availability_detail where n=? and room_state=0 and austate=1 and label IN (1,2,3,4) order by room "); }else{ query.append(" SELECT room,category,n,label,(CASE WHEN n=1 THEN (ISNULL(room_status,'-') +'-'+ ISNULL(hk_status,'-')) ELSE '-' END) status,(CASE label WHEN 1 THEN 'SPL' WHEN 2 THEN 'DBL' WHEN 3 THEN 'TRP' WHEN 4 THEN 'CDP' ELSE '-' END) label_desc FROM dbo.bed_availability_detail where n=? and room_state=0 and austate=1 and label=? order by room "); } ps = conn.prepareStatement(query.toString()); ps.setInt(1, n); if(!label.equals("9")){ ps.setString(2, label); } rs = ps.executeQuery(); while(rs.next()){ Value obj=new Value(); obj.setId(rs.getInt("n")); obj.setCodigo(rs.getString("room")); obj.setDescripcion(rs.getString("category")); obj.setDenominacion(rs.getString("label_desc")); obj.setDescEstado(rs.getString("status")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } }
package com.hotel.spring.controller; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Conversion del xml ubl 2.0 a xml ubl 2.1 para micros 9700 HMS * @author master */ public class ConvertUBL20toUBL21Final { public static final String xmlFilePath_ubl20 = "D:\\test\\factura_micros_20.xml"; public static final String xmlFilePath_ubl21 = "D:\\test\\factura_micros9700_21_result.xml"; public static void main(String argv[]) { ConvertUBL20toUBL21Final t =new ConvertUBL20toUBL21Final(); t.convert(); } public void convert(){ try { File xmlFile = new File(xmlFilePath_ubl20); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nodeList = doc.getElementsByTagName("sac:AdditionalInformation"); System.out.println("==============================================================="); /* * create node <sac:AdditionalMonetaryTotal> <cbc:ID>2005</cbc:ID> <cbc:PayableAmount currencyID="PEN">0.0</cbc:PayableAmount> </sac:AdditionalMonetaryTotal> */ Node additionalInformation = doc.getElementsByTagName("sac:AdditionalInformation").item(0); Element addNode = doc.createElement("sac:AdditionalMonetaryTotal"); additionalInformation.appendChild(addNode); Element cbcID = doc.createElement("cbc:ID"); cbcID.appendChild(doc.createTextNode("2005")); addNode.appendChild(cbcID); Element cbcPayableAmount = doc.createElement("cbc:PayableAmount"); cbcPayableAmount.setAttributeNS(null, "currencyID", "PEN"); cbcPayableAmount.setIdAttributeNS(null, "currencyID", true); cbcPayableAmount.appendChild(doc.createTextNode("0.0")); NamedNodeMap attribute = cbcPayableAmount.getAttributes(); Node nodeAttr = attribute.getNamedItem("currencyID"); nodeAttr.setTextContent("PEN"); addNode.appendChild(cbcPayableAmount); /* * change value <cbc:UBLVersionID>2.1</cbc:UBLVersionID> */ Node UBLVersionID = doc.getElementsByTagName("cbc:UBLVersionID").item(0); UBLVersionID.setTextContent("2.1"); /* * change value * add attribute schemeAgencyName <cbc:CustomizationID schemeAgencyName="PE:SUNAT">2.0</cbc:CustomizationID> */ Node CustomizationID = doc.getElementsByTagName("cbc:CustomizationID").item(0); CustomizationID.setTextContent("2.0"); ((Element)CustomizationID).setAttribute("schemeAgencyName", "PE:SUNAT"); /* * create node into Invoice <cbc:IssueTime>14:56:12.0Z</cbc:IssueTime> */ Node Invoice = doc.getElementsByTagName("Invoice").item(0); Element IssueTime = doc.createElement("cbc:IssueTime"); IssueTime.appendChild(doc.createTextNode("16:00:00.0Z")); Invoice.appendChild(IssueTime); /* * add attribute * <cbc:InvoiceTypeCode listID="0101" listAgencyName="PE:SUNAT" listName="Tipo de Documento" name="Tipo de Operacion" listURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo01" listSchemeURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo51">01</cbc:InvoiceTypeCode> */ Node InvoiceTypeCode = doc.getElementsByTagName("cbc:InvoiceTypeCode").item(0); ((Element)InvoiceTypeCode).setAttribute("listID", "0101"); ((Element)InvoiceTypeCode).setAttribute("listAgencyName", "PE:SUNAT"); ((Element)InvoiceTypeCode).setAttribute("listName", "Tipo de Documento"); ((Element)InvoiceTypeCode).setAttribute("name", "Tipo de Operacion"); ((Element)InvoiceTypeCode).setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo01"); ((Element)InvoiceTypeCode).setAttribute("listSchemeURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo51"); /* * add attribute * <cbc:DocumentCurrencyCode listID="ISO 4217 Alpha" listAgencyName="United Nations Economic Commission for Europe" listName="Currency">PEN</cbc:DocumentCurrencyCode> */ Node DocumentCurrencyCode = doc.getElementsByTagName("cbc:DocumentCurrencyCode").item(0); ((Element)DocumentCurrencyCode).setAttribute("listID", "ISO 4217 Alpha"); ((Element)DocumentCurrencyCode).setAttribute("listAgencyName", "United Nations Economic Commission for Europe"); ((Element)DocumentCurrencyCode).setAttribute("listName", "Currency"); Node AccountingSupplierParty = doc.getElementsByTagName("cac:AccountingSupplierParty").item(0); NodeList nodeNodesSupplier = AccountingSupplierParty.getChildNodes(); if (nodeNodesSupplier != null) { for(int i=0;i<nodeNodesSupplier.getLength();i++){ Node childNode = nodeNodesSupplier.item(i); if(childNode.getNodeName().equals("cac:Party")){ Element PartyIdentification = doc.createElement("cac:PartyIdentification"); childNode.appendChild(PartyIdentification); Element cbcIDpi = doc.createElement("cbc:ID"); cbcIDpi.appendChild(doc.createTextNode("0000000000"));//RUC PROVEEDOR PartyIdentification.appendChild(cbcIDpi); cbcIDpi.setAttribute("schemeID", "6"); cbcIDpi.setAttribute("schemeName", "Documento de Identidad"); cbcIDpi.setAttribute("schemeAgencyName", "PE:SUNAT"); cbcIDpi.setAttribute("schemeURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo06"); NodeList nodeNodesParty=childNode.getChildNodes(); if (nodeNodesParty != null) { for(int j=0;j<nodeNodesParty.getLength();j++){ Node childNodeParty = nodeNodesParty.item(j); if(childNodeParty.getNodeName().equals("cac:PostalAddress")){ //<cbc:CitySubdivisionName>DEFAULT PARAMETER</cbc:CitySubdivisionName> Element CitySubdivisionName = doc.createElement("cbc:CitySubdivisionName"); CitySubdivisionName.appendChild(doc.createTextNode("DEFAULT PARAMETER")); childNodeParty.appendChild(CitySubdivisionName); //<cbc:CountrySubentity>SAN ISIDRO - LIMA</cbc:CountrySubentity> Element CountrySubentity = doc.createElement("cbc:CountrySubentity"); CountrySubentity.appendChild(doc.createTextNode("SAN ISIDRO - LIMA")); childNodeParty.appendChild(CountrySubentity); //<cbc:District>DEFAULT PARAMETER</cbc:District> Element District = doc.createElement("cbc:District"); District.appendChild(doc.createTextNode("DEFAULT PARAMETER")); childNodeParty.appendChild(District); } if(childNodeParty.getNodeName().equals("cac:PartyLegalEntity")){ //<cac:RegistrationAddress> Element RegistrationAddress = doc.createElement("cac:RegistrationAddress"); childNodeParty.appendChild(RegistrationAddress); //<cbc:AddressTypeCode listAgencyName="PE:SUNAT" listName="Establecimientos anexos">0000</cbc:AddressTypeCode> Element AddressTypeCode = doc.createElement("cbc:AddressTypeCode"); AddressTypeCode.appendChild(doc.createTextNode("0000")); RegistrationAddress.appendChild(AddressTypeCode); AddressTypeCode.setAttribute("listAgencyName", "PE:SUNAT"); AddressTypeCode.setAttribute("listName", "Establecimientos anexos"); //<cbc:CitySubdivisionName>DEFAULT PARAMETER</cbc:CitySubdivisionName> Element CitySubdivisionName = doc.createElement("cbc:CitySubdivisionName"); CitySubdivisionName.appendChild(doc.createTextNode("DEFAULT PARAMETER")); RegistrationAddress.appendChild(CitySubdivisionName); //<cbc:CityName>SAN ISIDRO - LIMA</cbc:CityName> Element CityName = doc.createElement("cbc:CityName"); CityName.appendChild(doc.createTextNode("SAN ISIDRO - LIMA")); RegistrationAddress.appendChild(CityName); //<cbc:CountrySubentity>SAN ISIDRO - LIMA</cbc:CountrySubentity> Element CountrySubentity = doc.createElement("cbc:CountrySubentity"); CountrySubentity.appendChild(doc.createTextNode("SAN ISIDRO - LIMA")); RegistrationAddress.appendChild(CountrySubentity); //<cbc:CountrySubentityCode listAgencyName="PE:INEI" listName="Ubigeos">150131</cbc:CountrySubentityCode> Element CountrySubentityCode = doc.createElement("cbc:CountrySubentityCode"); CountrySubentityCode.appendChild(doc.createTextNode("150131")); RegistrationAddress.appendChild(CountrySubentityCode); AddressTypeCode.setAttribute("listAgencyName", "PE:INEI"); AddressTypeCode.setAttribute("listName", "Ubigeos"); //<cbc:District>DEFAULT PARAMETER</cbc:District> Element District = doc.createElement("cbc:District"); District.appendChild(doc.createTextNode("DEFAULT PARAMETER")); RegistrationAddress.appendChild(District); /* <cac:AddressLine> <cbc:Line>CALLE NNN SAN ISIDRO - LIMA</cbc:Line> </cac:AddressLine> */ Element AddressLine = doc.createElement("cac:AddressLine"); RegistrationAddress.appendChild(AddressLine); Element Line = doc.createElement("cbc:Line"); Line.appendChild(doc.createTextNode("CALLE NNN SAN ISIDRO - LIMA")); AddressLine.appendChild(Line); /* <cac:Country> <cbc:IdentificationCode listID="ISO 3166-1" listAgencyName="United Nations Economic Commission for Europe" listName="Country">PE</cbc:IdentificationCode> </cac:Country> */ Element Country = doc.createElement("cac:Country"); RegistrationAddress.appendChild(Country); Element IdentificationCode = doc.createElement("cbc:IdentificationCode"); IdentificationCode.appendChild(doc.createTextNode("PE")); Country.appendChild(IdentificationCode); IdentificationCode.setAttribute("listID", "ISO 3166-1"); IdentificationCode.setAttribute("listAgencyName", "United Nations Economic Commission for Europe"); IdentificationCode.setAttribute("listName", "Country"); } } } } } } Node AccountingCustomerParty = doc.getElementsByTagName("cac:AccountingCustomerParty").item(0); NodeList nodeNodesCustomer = AccountingCustomerParty.getChildNodes(); if (nodeNodesCustomer != null) { for(int i=0;i<nodeNodesCustomer.getLength();i++){ Node childNode = nodeNodesCustomer.item(i); if(childNode.getNodeName().equals("cac:Party")){ /* * <cac:PartyIdentification> <cbc:ID schemeID="6" schemeName="Documento de Identidad" schemeAgencyName="PE:SUNAT" schemeURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo06">20559622193</cbc:ID> </cac:PartyIdentification> */ Element PartyIdentification = doc.createElement("cac:PartyIdentification"); childNode.appendChild(PartyIdentification); Element cbcIDpi = doc.createElement("cbc:ID"); cbcIDpi.appendChild(doc.createTextNode("9999999999"));//RUC CLIENTE PartyIdentification.appendChild(cbcIDpi); cbcIDpi.setAttribute("schemeID", "6"); cbcIDpi.setAttribute("schemeName", "Documento de Identidad"); cbcIDpi.setAttribute("schemeAgencyName", "PE:SUNAT"); cbcIDpi.setAttribute("schemeURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo06"); /* *<cac:PartyName> <cbc:Name>MAXIMA SEGURIDAD ATENAS SAC</cbc:Name> </cac:PartyName> */ Element PartyName = doc.createElement("cac:PartyName"); childNode.appendChild(PartyName); Element Name = doc.createElement("cbc:Name"); Name.appendChild(doc.createTextNode("CLIENTE S.A."));//RAZON SOCIAL CLIENTE PartyName.appendChild(Name); NodeList nodeNodesParty = childNode.getChildNodes(); if (nodeNodesParty != null) { for(int j=0;j<nodeNodesParty.getLength();j++){ Node childNodeParty = nodeNodesParty.item(j); if(childNodeParty.getNodeName().equals("cac:PartyLegalEntity")){ Element RegistrationAddress = doc.createElement("cac:RegistrationAddress"); childNodeParty.appendChild(RegistrationAddress); //<cbc:CityName>AREQUIPA</cbc:CityName> Element CityName = doc.createElement("cbc:CityName"); CityName.appendChild(doc.createTextNode("AREQUIPA")); RegistrationAddress.appendChild(CityName); /*<cac:AddressLine> *<cbc:Line>CALLE NNN - AREQUIPA</cbc:Line> *</cac:AddressLine> */ Element AddressLine = doc.createElement("cac:AddressLine"); RegistrationAddress.appendChild(AddressLine); Element Line = doc.createElement("cbc:Line"); Line.appendChild(doc.createTextNode("CALLE NNN - AREQUIPA")); AddressLine.appendChild(Line); } } } } } } NodeList nodesInvoice = Invoice.getChildNodes(); if (nodesInvoice != null) { for(int i=0;i<nodesInvoice.getLength();i++){ Node childNode = nodesInvoice.item(i); if(childNode.getNodeName().equals("cac:TaxTotal")){ NodeList nodesTaxTotal = childNode.getChildNodes(); if (nodesTaxTotal != null) { for(int m=0;m<nodesTaxTotal.getLength();m++){ Node childNodeTaxTotal = nodesTaxTotal.item(m); if(childNodeTaxTotal.getNodeName().equals("cac:TaxSubtotal")){ //<cbc:TaxableAmount currencyID="PEN">150.79</cbc:TaxableAmount> Element TaxableAmount = doc.createElement("cbc:TaxableAmount"); TaxableAmount.appendChild(doc.createTextNode("150.79")); childNodeTaxTotal.appendChild(TaxableAmount); TaxableAmount.setAttribute("currencyID", "PEN"); NodeList nodesTaxSubTotal = childNodeTaxTotal.getChildNodes(); if (nodesTaxSubTotal != null) { for(int j=0;j<nodesTaxSubTotal.getLength();j++){ Node childTaxTotal = nodesTaxSubTotal.item(j); if(childTaxTotal.getNodeName().equals("cac:TaxCategory")){ NodeList nodesTaxCategory = childTaxTotal.getChildNodes(); if (nodesTaxCategory != null) { for(int k=0;k<nodesTaxCategory.getLength();k++){ Node childTaxCategory = nodesTaxCategory.item(k); if(childTaxCategory.getNodeName().equals("cac:TaxScheme")){ //<cbc:ID schemeAgencyName="PE:SUNAT" schemeName="Codigo de tributos" schemeURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo05">1000</cbc:ID> NodeList nodesTaxSchema = childTaxCategory.getChildNodes(); if (nodesTaxSchema != null) { for(int x=0;x<nodesTaxSchema.getLength();x++){ Node childTaxScheme = nodesTaxSchema.item(x); if(childTaxScheme.getNodeName().equals("cbc:ID")){ ((Element)childTaxScheme).setAttribute("schemeAgencyName", "PE:SUNAT"); ((Element)childTaxScheme).setAttribute("schemeName", "Codigo de tributos"); ((Element)childTaxScheme).setAttribute("schemeURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo05"); } } } } } } } } } } } } } if(childNode.getNodeName().equals("cac:LegalMonetaryTotal")){ //<cbc:LineExtensionAmount currencyID="PEN">150.79</cbc:LineExtensionAmount> Element LineExtensionAmount = doc.createElement("cbc:LineExtensionAmount"); LineExtensionAmount.appendChild(doc.createTextNode("150.79")); childNode.appendChild(LineExtensionAmount); LineExtensionAmount.setAttribute("currencyID", "PEN"); } } } //Invoce Lines NodeList listInvoiceLine = doc.getElementsByTagName("cac:InvoiceLine"); if (listInvoiceLine != null) { for(int t=0;t<listInvoiceLine.getLength();t++){ Node nodeInvoiceLine = listInvoiceLine.item(t); NodeList nodesInvoiceLine = nodeInvoiceLine.getChildNodes(); if (nodesInvoiceLine != null) { for(int i=0;i<nodesInvoiceLine.getLength();i++){ Node node = nodesInvoiceLine.item(i); if(node.getNodeName().equals("cac:PricingReference")){ NodeList nodesPricingReference = node.getChildNodes(); if (nodesPricingReference != null) { for(int k=0;k<nodesPricingReference.getLength();k++){ Node nodePricingReference = nodesPricingReference.item(k); if(nodePricingReference.getNodeName().equals("cac:AlternativeConditionPrice")){ NodeList nodesAlternativeConditionPrice = nodePricingReference.getChildNodes(); if (nodesAlternativeConditionPrice != null) { for(int m=0;m<nodesAlternativeConditionPrice.getLength();m++){ Node nodeAlternativeConditionPrice = nodesAlternativeConditionPrice.item(m); if(nodeAlternativeConditionPrice.getNodeName().equals("cbc:PriceTypeCode")){ //<cbc:PriceTypeCode listAgencyName="PE:SUNAT" listName="Tipo de Precio" listURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo16">01</cbc:PriceTypeCode> ((Element)nodeAlternativeConditionPrice).setAttribute("listAgencyName", "PE:SUNAT"); ((Element)nodeAlternativeConditionPrice).setAttribute("listName", "Tipo de Precio"); ((Element)nodeAlternativeConditionPrice).setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo16"); } } } } } } } if(node.getNodeName().equals("cac:TaxTotal")){ NodeList nodesTaxTotal = node.getChildNodes(); if (nodesTaxTotal != null) { for(int k=0;k<nodesTaxTotal.getLength();k++){ Node nodeTaxTotal = nodesTaxTotal.item(k); if(nodeTaxTotal.getNodeName().equals("cac:TaxSubtotal")){ //<cbc:TaxableAmount currencyID="PEN">15.63</cbc:TaxableAmount> Element TaxableAmount = doc.createElement("cbc:TaxableAmount"); TaxableAmount.appendChild(doc.createTextNode("15.63")); nodeTaxTotal.appendChild(TaxableAmount); TaxableAmount.setAttribute("currencyID", "PEN"); NodeList nodesTaxSubtotal = nodeTaxTotal.getChildNodes(); if (nodesTaxSubtotal != null) { for(int m=0;m<nodesTaxSubtotal.getLength();m++){ Node nodeTaxSubtotal = nodesTaxSubtotal.item(m); if(nodeTaxSubtotal.getNodeName().equals("cac:TaxCategory")){ //<cbc:Percent>18.0</cbc:Percent> Element Percent = doc.createElement("cbc:Percent"); Percent.appendChild(doc.createTextNode("18.00")); nodeTaxSubtotal.appendChild(Percent); NodeList nodesTaxCategory = nodeTaxSubtotal.getChildNodes(); if (nodesTaxCategory != null) { for(int z=0;z<nodesTaxCategory.getLength();z++){ Node nodeTaxCategory = nodesTaxCategory.item(z); if(nodeTaxCategory.getNodeName().equals("cbc:TaxExemptionReasonCode")){ //<cbc:TaxExemptionReasonCode listAgencyName="PE:SUNAT" listName="Afectacion del IGV" listURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo07">10</cbc:TaxExemptionReasonCode> ((Element)nodeTaxCategory).setAttribute("listAgencyName", "PE:SUNAT"); ((Element)nodeTaxCategory).setAttribute("listName", "Afectacion del IGV"); ((Element)nodeTaxCategory).setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo07"); } if(nodeTaxCategory.getNodeName().equals("cac:TaxScheme")){ NodeList nodesTaxSchema = nodeTaxCategory.getChildNodes(); if (nodesTaxSchema != null) { for(int p=0;p<nodesTaxSchema.getLength();p++){ Node nodeTaxSchema = nodesTaxSchema.item(p); if(nodeTaxSchema.getNodeName().equals("cbc:ID")){ //<cbc:ID schemeAgencyName="PE:SUNAT" schemeName="Codigo de tributos" schemeURI="urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo05">1000</cbc:ID> ((Element)nodeTaxSchema).setAttribute("schemeAgencyName", "PE:SUNAT"); ((Element)nodeTaxSchema).setAttribute("schemeName", "Codigo de tributos"); ((Element)nodeTaxSchema).setAttribute("schemeURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo05"); } } } } } } } } } } } } } if(node.getNodeName().equals("cac:Item")){ /* * <cac:CommodityClassification> * <cbc:ItemClassificationCode listID="UNSPSC" listAgencyName="GS1 US" listName="Item Classification">90101501</cbc:ItemClassificationCode> * </cac:CommodityClassification> */ Element CommodityClassification = doc.createElement("cac:CommodityClassification"); node.appendChild(CommodityClassification); Element ItemClassificationCode = doc.createElement("cbc:ItemClassificationCode"); ItemClassificationCode.appendChild(doc.createTextNode("90101501"));//CODIGO DE PRODUCTO - 90101501-RESTAURANTES //90-SERVICIOS DE VIAJES, ALIMENTACIÓN, ALOJAMIENTO Y ENTRETENIMIENTO //9010-RESTAURANTES Y CATERING (SERVICIOS DE COMIDAS Y BEBIDAS) //901015-ESTABLECIMIENTOS PARA COMER Y BEBER CommodityClassification.appendChild(ItemClassificationCode); ItemClassificationCode.setAttribute("listID", "UNSPSC");//UNSPSC - Clasificador de Bienes y Servicios ItemClassificationCode.setAttribute("listAgencyName", "GS1 US"); ItemClassificationCode.setAttribute("listName", "Item Classification"); NodeList nodesItem = node.getChildNodes(); if (nodesItem != null) { for(int k=0;k<nodesItem.getLength();k++){ Node nodeItem = nodesItem.item(k); if(nodeItem.getNodeName().equals("cac:SellersItemIdentification")){ NodeList nodesSellersItemIdentification = nodeItem.getChildNodes(); if (nodesSellersItemIdentification != null) { for(int m=0;m<nodesSellersItemIdentification.getLength();m++){ Node nodeSellersItemIdentification = nodesSellersItemIdentification.item(m); if(nodeSellersItemIdentification.getNodeName().equals("cbc:ID")){ //<cbc:ID>2210004</cbc:ID> nodeSellersItemIdentification.appendChild(doc.createTextNode("2210004")); } } } } } } } } } } } // create the xml file //transform the DOM Object to an XML File TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource domSource = new DOMSource(doc); StreamResult streamResult = new StreamResult(new File(xmlFilePath_ubl21)); // If you use // StreamResult result = new StreamResult(System.out); // the output will be pushed to the standard output ... // You can use that for debugging transformer.transform(domSource, streamResult); System.out.println("Done creating XML File"); } catch (Exception e) { e.printStackTrace(); } } }
package com.hotel.spring.controller; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.StringWriter; import java.io.Writer; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.hotel.business.Util; /** * Conversion del xml ubl 2.0 a xml ubl 2.1 para micros 9700 HMS * @author master */ public class CorrectToUBL21SUNAT { public static void main(String argv[]) { String filename="01_2021-10-17 14-15-36.xml"; String fileFrom = xmlPathFrom+filename; String fileTo = xmlPathTo+filename.replaceAll(" ","-").replaceAll(".xml", "OK.xml"); /* CorrectToUBL21SUNAT t =new CorrectToUBL21SUNAT(); t.convert(fileFrom,fileTo,"2021-10-18"); */ try { CorrectToUBL21SUNAT t =new CorrectToUBL21SUNAT(); Document doc=t.convertDescuento(fileFrom); String text=t.getStringFromDocument(doc); ByteBuffer buffer = StandardCharsets.UTF_8.encode(text); String textEncoded = StandardCharsets.UTF_8.decode(buffer).toString(); BufferedWriter writer = new BufferedWriter(new FileWriter(fileTo)); writer.write(textEncoded); writer.close(); System.out.println("Done! "+fileTo); }catch(Exception ex){ ex.printStackTrace(); } } public String getStringFromDocument(Document doc){ try{ TransformerFactory tf = TransformerFactory.newInstance(); Transformer trans = tf.newTransformer(); StringWriter sw = new StringWriter(); trans.transform(new DOMSource(doc), new StreamResult(sw)); return sw.toString(); }catch(Exception ex){ ex.printStackTrace(); return null; } } public void convert(String fileFROM,String fileTO,String fechaHoyXML){ try { File xmlFile = new File(fileFROM); InputStreamReader r = new InputStreamReader(new FileInputStream(xmlFile)); String content = new String(Files.readAllBytes(Paths.get(fileFROM)), r.getEncoding()); String content1=new String(); String content2=new String(); String content3=new String(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); Boolean taxInclusiveAmount=haveTaxInclusiveAmount(doc); if(!taxInclusiveAmount){ //addTaxInclusiveAmount(doc); String sTaxInclusiveAmount=getPriceAmountFromAlternativeConditionPrice(doc); content1=content.replaceFirst("<cbc:ChargeTotalAmount currencyID=\"PEN\">", "<cbc:TaxInclusiveAmount currencyID=\"PEN\">"+sTaxInclusiveAmount+"</cbc:TaxInclusiveAmount>\n<cbc:ChargeTotalAmount currencyID=\"PEN\">"); }else{ content1=content; } Boolean paymentTerms=havePaymentTerms(doc); if(!paymentTerms){ //addPaymentTerms(doc); content2=content1.replaceFirst("<cac:TaxTotal>", "<cac:PaymentTerms><cbc:ID>FormaPago</cbc:ID><cbc:PaymentMeansID>Contado</cbc:PaymentMeansID></cac:PaymentTerms>\n<cac:TaxTotal>\n"); }else{ content2=content1; } Boolean allowanceCharge=haveAllowanceCharge(doc); if(!allowanceCharge){ //addAllowanceCharge(doc); String sChargeTotalAmount=getChargeTotalAmount(doc); content3=content2.replaceFirst("<cac:TaxTotal>", "<cac:AllowanceCharge><cbc:ChargeIndicator>true</cbc:ChargeIndicator><cbc:AllowanceChargeReasonCode listAgencyName=\"PE:SUNAT\" listName=\"Cargo/descuento\" listURI=\"urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo53\">46</cbc:AllowanceChargeReasonCode><cbc:MultiplierFactorNumeric>1</cbc:MultiplierFactorNumeric><cbc:Amount currencyID=\"PEN\">"+sChargeTotalAmount+"</cbc:Amount><cbc:BaseAmount currencyID=\"PEN\">"+sChargeTotalAmount+"</cbc:BaseAmount></cac:AllowanceCharge>\n<cac:TaxTotal>\n"); }else{ content3=content2; } //fuerza por el cambio de fecha del comprobante String sIssueDate=getIssueDate(doc); if(sIssueDate!=null&&sIssueDate.trim().length()>0){ content3=content3.replaceAll("<cbc:IssueDate>"+sIssueDate+"</cbc:IssueDate>", "<cbc:IssueDate>"+fechaHoyXML+"</cbc:IssueDate>"); } //System.out.println("to! "+fileTO); //System.out.println(content3); BufferedWriter writer = new BufferedWriter(new FileWriter(fileTO)); writer.write(content3); writer.close(); System.out.println("Done! "+fileTO); } catch (Exception e) { e.printStackTrace(); } } public Document convertDescuento(String fileFROM){ Document doc = null; try { File xmlFile = new File(fileFROM); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); doc = documentBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); Boolean allowanceTotalAmount=haveAllowanceTotalAmount(doc); if(allowanceTotalAmount){ fixAllowanceInvoiceLine(doc); addPaymentTerms(doc); addAllowanceCharge(doc); } } catch (Exception e) { e.printStackTrace(); } return doc; } public void addAllowanceCharge(Document doc){ String sChargeTotalAmount=getChargeTotalAmount(doc); Element AllowanceCharge = doc.createElement("cac:AllowanceCharge"); Element ChargeIndicator = doc.createElement("cbc:ChargeIndicator"); AllowanceCharge.appendChild(ChargeIndicator); ChargeIndicator.appendChild(doc.createTextNode("true")); Element AllowanceChargeReasonCode = doc.createElement("cbc:AllowanceChargeReasonCode"); AllowanceCharge.appendChild(AllowanceChargeReasonCode); AllowanceChargeReasonCode.appendChild(doc.createTextNode("46")); AllowanceChargeReasonCode.setAttribute("listAgencyName", "PE:SUNAT"); AllowanceChargeReasonCode.setAttribute("listName", "Cargo/descuento"); AllowanceChargeReasonCode.setAttribute("listURI", "urn:pe:gob:sunat:cpe:see:gem:catalogos:catalogo53"); Element MultiplierFactorNumeric = doc.createElement("cbc:MultiplierFactorNumeric"); AllowanceCharge.appendChild(MultiplierFactorNumeric); MultiplierFactorNumeric.appendChild(doc.createTextNode("1")); Element Amount = doc.createElement("cbc:Amount"); AllowanceCharge.appendChild(Amount); Amount.appendChild(doc.createTextNode(sChargeTotalAmount));/********************************/ Amount.setAttribute("currencyID", "PEN"); Element BaseAmount = doc.createElement("cbc:BaseAmount"); AllowanceCharge.appendChild(BaseAmount); BaseAmount.appendChild(doc.createTextNode(sChargeTotalAmount));/********************************/ BaseAmount.setAttribute("currencyID", "PEN"); Node Invoice = doc.getElementsByTagName("Invoice").item(0); Invoice.insertBefore(AllowanceCharge, getNode("cac:TaxTotal",Invoice.getChildNodes())); } public void addPaymentTerms(Document doc){ Element PaymentTerms = doc.createElement("cac:PaymentTerms"); Element ID = doc.createElement("cbc:ID"); PaymentTerms.appendChild(ID); ID.appendChild(doc.createTextNode("FormaPago")); Element PaymentMeansID = doc.createElement("cbc:PaymentMeansID"); PaymentTerms.appendChild(PaymentMeansID); PaymentMeansID.appendChild(doc.createTextNode("Contado")); Node Invoice = doc.getElementsByTagName("Invoice").item(0); Invoice.insertBefore(PaymentTerms, getNode("cac:TaxTotal",Invoice.getChildNodes())); } public void removeAllowanceCharge(Document doc){ Node Invoice = doc.getElementsByTagName("Invoice").item(0); NodeList targets = doc.getElementsByTagName("cac:AllowanceCharge"); int toDelete = targets.getLength(); for(int i = 0; i < toDelete; i++){ Invoice.removeChild(targets.item(i)); } } public void fixAllowanceInvoiceLine(Document doc){ Double multiplierAllowance=getMultiplierFactorNumeric(doc); removeAllowanceCharge(doc); NodeList listInvoiceLine = doc.getElementsByTagName("cac:InvoiceLine"); for(int i=0;i<listInvoiceLine.getLength();i++){ Node InvoiceLine = listInvoiceLine.item(i); if(InvoiceLine!=null){ Double PriceAmount=0.0; Double TaxPercent=0.0; Node Price= getNode("cac:Price",InvoiceLine.getChildNodes()); if(Price!=null){ PriceAmount=getPriceAmount(Price); } Node TaxTotal= getNode("cac:TaxTotal",InvoiceLine.getChildNodes()); if(TaxTotal!=null){ TaxPercent=getTaxPercent(TaxTotal); } /**Fix Allowance Invoice Line*/ Double Allowance=PriceAmount*multiplierAllowance; Double LineAmount=PriceAmount-Allowance; Double TaxAmount=LineAmount*TaxPercent/100; Double PriceReference=LineAmount+TaxAmount; /**Fix Allowance Invoice Line end*/ //<cbc:LineExtensionAmount Node LineExtensionAmount= getNode("cbc:LineExtensionAmount",InvoiceLine.getChildNodes()); if(LineExtensionAmount!=null){ LineExtensionAmount.setTextContent(Util.format(LineAmount)); } //<cac:PricingReference> Node PricingReference= getNode("cac:PricingReference",InvoiceLine.getChildNodes()); if(PricingReference!=null){ NodeList lChild = PricingReference.getChildNodes(); for(int n=0;n<lChild.getLength();n++){ Node child = lChild.item(n); if(child.getNodeName().equals("cac:AlternativeConditionPrice")){ NodeList lChild2 = child.getChildNodes(); for(int m=0;m<lChild2.getLength();m++){ Node child2 = lChild2.item(m); if(child2.getNodeName().equals("cbc:PriceAmount")){ child2.setTextContent(Util.format(PriceReference)); break; } } break; } } } //<cac:AllowanceCharge><!--ADD--> Element AllowanceCharge= doc.createElement("cac:AllowanceCharge"); //InvoiceLine.appendChild(AllowanceCharge); InvoiceLine.insertBefore(AllowanceCharge, getNode("cac:TaxTotal",InvoiceLine.getChildNodes())); Element ChargeIndicator= doc.createElement("cbc:ChargeIndicator"); AllowanceCharge.appendChild(ChargeIndicator); ChargeIndicator.setTextContent("false"); Element Amount= doc.createElement("cbc:Amount"); AllowanceCharge.appendChild(Amount); Amount.setTextContent(Util.format(Allowance)); Amount.setAttribute("currencyID", "PEN"); //<cac:TaxTotal> Node NodeTaxTotal= getNode("cac:TaxTotal",InvoiceLine.getChildNodes()); if(NodeTaxTotal!=null){ NodeList lChild = NodeTaxTotal.getChildNodes(); for(int n=0;n<lChild.getLength();n++){ Node child = lChild.item(n); if(child.getNodeName().equals("cbc:TaxAmount")){ child.setTextContent(Util.format(TaxAmount)); }else if(child.getNodeName().equals("cac:TaxSubtotal")){ NodeList lChild2 = child.getChildNodes(); for(int k=0;k<lChild2.getLength();k++){ Node child2 = lChild2.item(k); if(child2.getNodeName().equals("cbc:TaxableAmount")){ child2.setTextContent(Util.format(LineAmount)); }else if(child2.getNodeName().equals("cbc:TaxAmount")){ child2.setTextContent(Util.format(TaxAmount)); } } } } } } } } public Double getTaxPercent(Node TaxTotal){ Double Percent=0.0; NodeList lChildTaxTotal = TaxTotal.getChildNodes(); for(int j=0;j<lChildTaxTotal.getLength();j++){ Node childNode = lChildTaxTotal.item(j); if(childNode.getNodeName().equals("cac:TaxSubtotal")){ NodeList lChildTaxSubtotal = childNode.getChildNodes(); for(int n=0;n<lChildTaxSubtotal.getLength();n++){ Node childTaxSubtotal = lChildTaxSubtotal.item(n); if(childTaxSubtotal.getNodeName().equals("cac:TaxCategory")){ NodeList lChildTaxCategory = childTaxSubtotal.getChildNodes(); for(int m=0;m<lChildTaxCategory.getLength();m++){ Node childTaxCategory = lChildTaxCategory.item(m); if(childTaxCategory.getNodeName().equals("cbc:Percent")){ String txtPercent=childTaxCategory.getTextContent(); Percent=Util.stringToDouble(txtPercent); break; } } break; } } break; } } return Percent; } public Double getPriceAmount(Node Price){ Double PriceAmount=0.0; NodeList lChildPrice = Price.getChildNodes(); for(int j=0;j<lChildPrice.getLength();j++){ Node childNode = lChildPrice.item(j); if(childNode.getNodeName().equals("cbc:PriceAmount")){ String txtPriceAmount=childNode.getTextContent(); PriceAmount=Util.stringToDouble(txtPriceAmount); break;//ok } } return PriceAmount; } public Node getNode(String tagNode,NodeList listNode){ for(int i=0;i<listNode.getLength();i++){ Node child = listNode.item(i); if(child!=null){ if(child.getNodeName().equals(tagNode)){ return child; } } } return null; } public Double getMultiplierFactorNumeric(Document doc){ Double multiplierFactorNumeric=0.0; Node allowance=getAllowanceNode(doc); if(allowance!=null){ NodeList nodes = allowance.getChildNodes(); for(int j=0;j<nodes.getLength();j++){ Node childNode = nodes.item(j); if(childNode.getNodeName().equals("cbc:MultiplierFactorNumeric")){ String txtMultiplierFactorNumeric=childNode.getTextContent(); multiplierFactorNumeric=Util.stringToDouble(txtMultiplierFactorNumeric); break;//ok } } } return multiplierFactorNumeric; } public Node getAllowanceNode(Document doc){ //ok Node allowance=null; NodeList lAllowanceCharge = doc.getElementsByTagName("cac:AllowanceCharge"); for(int i=0;i<lAllowanceCharge.getLength();i++){ Node allowanceCharge = lAllowanceCharge.item(i); if(allowanceCharge!=null){ NodeList nodes = allowanceCharge.getChildNodes(); for(int j=0;j<nodes.getLength();j++){ Node childNode = nodes.item(j); if(childNode.getNodeName().equals("cbc:ChargeIndicator")){ String txtChargeIndicator=childNode.getTextContent(); Boolean chargeIndicator=Util.stringToBolean(txtChargeIndicator); if(chargeIndicator==Boolean.FALSE){//Allowance allowance=allowanceCharge; break; } } } } } return allowance; } public Boolean haveAllowanceTotalAmount(Document doc){ Node allowanceTotalAmount = doc.getElementsByTagName("cbc:AllowanceTotalAmount").item(0); if(allowanceTotalAmount!=null){ String totalAmount=allowanceTotalAmount.getTextContent(); Double dTotalAmount=Util.stringToDouble(totalAmount); if(dTotalAmount>0) return Boolean.TRUE; } return Boolean.FALSE; } public String getIssueDate(Document doc){ String dateInvoice=""; NodeList lIssueDate = doc.getElementsByTagName("cbc:IssueDate"); for(int i=0;i<lIssueDate.getLength();i++){ Node issueDate = lIssueDate.item(i); dateInvoice=issueDate.getTextContent(); } return dateInvoice; } public Boolean havePaymentTerms(Document doc){ Node lPaymentTerms = doc.getElementsByTagName("cac:PaymentTerms").item(0); if(lPaymentTerms!=null){ return Boolean.TRUE; } return Boolean.FALSE; } public Boolean haveTaxInclusiveAmount(Document doc){ Node legalMonetaryTotal = doc.getElementsByTagName("cac:LegalMonetaryTotal").item(0); NodeList nodes = legalMonetaryTotal.getChildNodes(); if (nodes != null) { for(int i=0;i<nodes.getLength();i++){ Node childNode = nodes.item(i); if(childNode.getNodeName().equals("cbc:TaxInclusiveAmount")){ return Boolean.TRUE; } } } return Boolean.FALSE; } public Boolean haveAllowanceCharge(Document doc){ Node lPaymentTerms = doc.getElementsByTagName("cac:AllowanceCharge").item(0); if(lPaymentTerms!=null){ return Boolean.TRUE; } return Boolean.FALSE; } public void addTaxInclusiveAmount(Document doc){ //<cac:PaymentTerms> //<cbc:ID>FormaPago</cbc:ID> //<cbc:PaymentMeansID>Contado</cbc:PaymentMeansID> //</cac:PaymentTerms> Node legalMonetaryTotal = doc.getElementsByTagName("cac:LegalMonetaryTotal").item(0); if(legalMonetaryTotal!=null){ String sTaxInclusiveAmount=getPriceAmountFromAlternativeConditionPrice(doc); Element addNode = doc.createElement("cbc:TaxInclusiveAmount"); legalMonetaryTotal.appendChild(addNode); addNode.appendChild(doc.createTextNode(sTaxInclusiveAmount)); addNode.setAttribute("currencyID", "PEN"); } } public String getPriceAmountFromAlternativeConditionPrice(Document doc){ Double TaxInclusiveAmount=0.0; NodeList listInvoiceLine = doc.getElementsByTagName("cac:InvoiceLine"); for(int i=0;i<listInvoiceLine.getLength();i++){ Double PriceAmount=0.0; Double InvoicedQuantity=0.0; Node invoiceLine = listInvoiceLine.item(i); NodeList nodes = invoiceLine.getChildNodes(); if (nodes != null) { for(int j=0;j<nodes.getLength();j++){ Node childNode = nodes.item(j); if(childNode.getNodeName().equals("cac:PricingReference")){ NodeList nodesPricingReference = childNode.getChildNodes(); if (nodesPricingReference != null) { for(int k=0;k<nodesPricingReference.getLength();k++){ Node childNode2 = nodesPricingReference.item(k); if(childNode2.getNodeName().equals("cac:AlternativeConditionPrice")){ NodeList nodesAlternativeConditionPrice = childNode2.getChildNodes(); if (nodesAlternativeConditionPrice != null) { for(int g=0;g<nodesAlternativeConditionPrice.getLength();g++){ Node childNode3 = nodesAlternativeConditionPrice.item(g); if(childNode3.getNodeName().equals("cbc:PriceAmount")){ String sPriceAmount=childNode3.getTextContent(); PriceAmount=Util.stringToDouble(sPriceAmount); } } } } } } }else if(childNode.getNodeName().equals("cbc:InvoicedQuantity")){ String sInvoicedQuantity=childNode.getTextContent(); InvoicedQuantity=Util.stringToDouble(sInvoicedQuantity); } } } TaxInclusiveAmount=TaxInclusiveAmount+PriceAmount*InvoicedQuantity; } return Util.format(TaxInclusiveAmount); } public String getChargeTotalAmount(Document doc){ Double ChargeTotalAmount=0.0; NodeList LegalMonetaryTotal = doc.getElementsByTagName("cac:LegalMonetaryTotal"); for(int i=0;i<LegalMonetaryTotal.getLength();i++){ Node legalMonetaryTotal = LegalMonetaryTotal.item(i); NodeList nodes = legalMonetaryTotal.getChildNodes(); if (nodes != null) { for(int j=0;j<nodes.getLength();j++){ Node childNode = nodes.item(j); if(childNode.getNodeName().equals("cbc:ChargeTotalAmount")){ String sChargeTotalAmount=childNode.getTextContent(); ChargeTotalAmount=Util.stringToDouble(sChargeTotalAmount); } } } } return Util.format(ChargeTotalAmount); } }
package read; import java.io.File; import java.util.Calendar; import java.util.Date; import java.util.Calendar; import java.util.Date; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.hotel.business.GosocketBo; import com.hotel.business.Util; import vo.DateUtil; public class LoadGosocket { public static void main(String[] args) { try{ GosocketBo go=new GosocketBo(); /** YESTERDAY*//**/ String year=go.getYEARd1(); String month=go.getMONTHd1(); String day=go.getDAYd1(); /** TODAY*//** String year=go.getYEAR(); String month=go.getMONTH(); String day=go.getDAY(); */ System.out.println("date "+year+"-"+month+"-"+day); go.deleteInvoice(year+"-"+month+"-"+day); LoadGosocket load=new LoadGosocket(); File folderMicros = new File(load.pathMicrosFrom); System.out.println("load xml from "+folderMicros.getAbsolutePath()); int cant=load.listFilesForFolder(folderMicros); System.out.println("Done! "+cant); }catch(Exception e){ e.printStackTrace(); } } public int listFilesForFolder(File folder) { int cant=0; try{ for (final File fileEntry : folder.listFiles()) { if (!fileEntry.isDirectory()) { int diff = DateUtil.diferenciasDeFechas(Calendar.getInstance().getTime(),(new Date(fileEntry.lastModified()))); if(diff==-1){/** YESTERDAY*//**/ String nroComprobante=""; String fechaComprobante=""; String tipoComprobante=""; String tipoMoneda=""; String montoPagar=""; File xmlFile = new File(fileEntry.getAbsolutePath()); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(xmlFile); doc.getDocumentElement().normalize(); Node invoice = doc.getElementsByTagName("Invoice").item(0); NodeList nodesinvoice = invoice.getChildNodes(); if (nodesinvoice != null) { for(int j=0;j<nodesinvoice.getLength();j++){ Node childTaxTotal = nodesinvoice.item(j); if(childTaxTotal.getNodeName().equals("cbc:ID")){ nroComprobante=childTaxTotal.getTextContent(); } if(childTaxTotal.getNodeName().equals("cbc:IssueDate")){ fechaComprobante=childTaxTotal.getTextContent(); } if(childTaxTotal.getNodeName().equals("cbc:InvoiceTypeCode")){ tipoComprobante=childTaxTotal.getTextContent(); } if(childTaxTotal.getNodeName().equals("cbc:DocumentCurrencyCode")){ tipoMoneda=childTaxTotal.getTextContent(); } if(childTaxTotal.getNodeName().equals("cac:LegalMonetaryTotal")){ NodeList nodesLegal = childTaxTotal.getChildNodes(); if (nodesLegal != null) { for(int l=0;l<nodesLegal.getLength();l++){ Node childLegal = nodesLegal.item(l); if(childLegal.getNodeName().equals("cbc:PayableAmount")){ montoPagar=childLegal.getTextContent(); } } } } } } GosocketBo go=new GosocketBo(); go.insertarInvoice(fileEntry.getName(),nroComprobante, fechaComprobante, tipoComprobante, tipoMoneda, montoPagar); cant++; } } } }catch(Exception e){ e.printStackTrace(); } return cant; } }
package com.hotel.business; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.hotel.Constante; import com.hotel.dao.ConnectionFactoryOpera; import com.hotel.vo.HkArrival; import com.hotel.vo.HkFloors; import com.hotel.vo.HkRoomStatus; import com.hotel.vo.HkValueStatus; public class OperaHkBo { public List<HkRoomStatus> listarHkRoomStatus(Integer floor){ List<HkRoomStatus> lista = new ArrayList<HkRoomStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, "); query.append(" CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status, "); query.append(" TO_CHAR(v.arrival,'DD/MM') arrival, "); query.append(" TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time "); query.append(" ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy "); query.append(" ,NVL(v.adults,0) adults,NVL(v.children,0)children,NVL(SUBSTR(v.company_name,1,15),'-') company_name "); query.append(" ,NVL(v.vip,' ') vip "); query.append(" FROM OPERA.ROOM r "); query.append(" INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) "); query.append(" LEFT JOIN ( "); query.append(" select r.room,MIN(r.resv_status) resv_status,min(r.arrival) arrival,max(r.departure) departure,max(r.departure_time) departure_time "); query.append(" ,SUM(case when r.resv_status ='CHECKED IN' then r.adults else 0 end) adults, "); query.append(" SUM(case when r.resv_status ='CHECKED IN' then r.children else 0 end) children, "); query.append(" MAX(case when r.resv_status ='CHECKED IN' then r.company_name else '' end) company_name "); query.append(" ,MIN(r.vip) vip "); query.append(" from reservation_general_view_hld r "); query.append(" where r.trunc_departure>=pms_p.business_date and r.room is not null "); query.append(" and r.resv_status IN ('CHECKED IN','CHECKED OUT') "); query.append(" group by r.room "); query.append(" ) v ON (v.room=r.room) "); query.append(" WHERE SUITE_TYPE<>'PSUEDO' "); query.append(" AND to_number(r.floor)=? "); query.append(" ORDER BY to_number(r.floor) ASC, to_number(r.room) ASC "); ps = conn.prepareStatement(query.toString()); ps.setInt(1, floor); rs = ps.executeQuery(); while(rs.next()){ HkRoomStatus obj=new HkRoomStatus(); obj.setRoom(rs.getString("room")); obj.setRoomStatus(rs.getString("room_status")); obj.setHkStatus(rs.getString("hk_status")); obj.setRoomType(rs.getString("label")); obj.setRoomTypeDescription(rs.getString("short_description")); // obj.setResvStatus(rs.getString("resv_status")); obj.setArrival(rs.getString("arrival")); obj.setDeparture(rs.getString("departure")); obj.setDepartureTime(rs.getString("departure_time")); // obj.setIsDiscrepancy(rs.getString("isdiscrepancy").equals("Y")?Boolean.TRUE:Boolean.FALSE); obj.setStatusDiscrepancy(Constante.STATUS_DISCREPANCY_N); obj.setStatusArrivalTime(Constante.STATUS_ARRIVALTIME_N); //-- obj.setAdults(rs.getInt("adults")); obj.setChildren(rs.getInt("children")); obj.setCompanyName(rs.getString("company_name")); obj.setVip(rs.getString("vip")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<HkFloors> listarHkFloors(){ List<HkFloors> lista = new ArrayList<HkFloors>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT TO_NUMBER(r.floor) id,LPAD(r.floor,2,'0') floor, "); query.append(" SUM(CASE WHEN r.hk_status='OCC' THEN 1 ELSE 0 END) CANTIDAD_OCC, "); query.append(" SUM(CASE WHEN r.hk_status='VAC' THEN 1 ELSE 0 END) CANTIDAD_VAC, "); query.append(" SUM(CASE WHEN r.hk_status<>r.fo_status THEN 1 ELSE 0 END) CANTIDAD_DISC, "); query.append(" SUM(CASE WHEN r.room_status='IP' THEN 1 ELSE 0 END) CANTIDAD_IP, "); query.append(" SUM(CASE WHEN r.room_status='DI' THEN 1 ELSE 0 END) CANTIDAD_DI, "); query.append(" SUM(CASE WHEN r.room_status='CL' THEN 1 ELSE 0 END) CANTIDAD_CL, "); query.append(" SUM(CASE WHEN r.room_status='OO' THEN 1 ELSE 0 END) CANTIDAD_OO, "); query.append(" SUM(CASE WHEN r.room_status='OS' THEN 1 ELSE 0 END) CANTIDAD_OS "); query.append(" ,SUM(o.adults) adults,SUM(o.children) children "); query.append(" FROM OPERA.ROOM r "); query.append(" LEFT JOIN ( "); query.append(" select v.room ,sum(v.adults) adults, sum(v.children) children "); query.append(" from reservation_general_view_hld v "); query.append(" where v.resv_status ='CHECKED IN' "); query.append(" group by v.room "); query.append(" ) o ON (o.room=r.room) "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); query.append(" GROUP BY TO_NUMBER(r.floor),LPAD(r.floor,2,'0') "); query.append(" ORDER BY ID ASC "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkFloors obj=new HkFloors(); obj.setId(rs.getInt("id")); obj.setCodigo(rs.getString("floor")); obj.setCantidadOcc(rs.getInt("CANTIDAD_OCC")); obj.setCantidadVac(rs.getInt("CANTIDAD_VAC")); obj.setCantidadDisc(rs.getInt("CANTIDAD_DISC")); obj.setCantidadIp(rs.getInt("CANTIDAD_IP")); obj.setCantidadDi(rs.getInt("CANTIDAD_DI")); obj.setCantidadCl(rs.getInt("CANTIDAD_CL")); obj.setCantidadOo(rs.getInt("CANTIDAD_OO")); obj.setCantidadOs(rs.getInt("CANTIDAD_OS")); //-- obj.setAdults(rs.getInt("adults")); obj.setChildren(rs.getInt("children")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<HkValueStatus> listarHkRoomStatus(){ List<HkValueStatus> lista = new ArrayList<HkValueStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT s.ROOM_STATUS_ID,s.ROOM_STATUS_CODE,s.ROOM_STATUS_DESC, t.cantidad,T.CANTIDAD_OCC,T.CANTIDAD_VAC,T.CANTIDAD_DISC "); query.append(" FROM OPERA.ROOM_STATUS_CODES_ALL_ORDER s "); query.append(" INNER JOIN ( "); query.append(" SELECT r.room_status, COUNT(1) CANTIDAD, "); query.append(" SUM(CASE WHEN r.hk_status='OCC' THEN 1 ELSE 0 END) CANTIDAD_OCC, "); query.append(" SUM(CASE WHEN r.hk_status='VAC' THEN 1 ELSE 0 END) CANTIDAD_VAC, "); query.append(" SUM(CASE WHEN r.hk_status<>r.fo_status THEN 1 ELSE 0 END) CANTIDAD_DISC "); query.append(" FROM OPERA.ROOM r "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); query.append(" GROUP BY r.room_status "); query.append(" )t ON (t.room_status=s.ROOM_STATUS_CODE) "); query.append(" ORDER BY s.ROOM_STATUS_ID ASC "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkValueStatus obj=new HkValueStatus(); obj.setId(rs.getInt("ROOM_STATUS_ID")); obj.setCodigo(rs.getString("ROOM_STATUS_CODE")); obj.setDenominacion(rs.getString("ROOM_STATUS_DESC")); obj.setCantidad(rs.getInt("cantidad")); // obj.setCantidadOcc(rs.getInt("CANTIDAD_OCC")); obj.setCantidadVac(rs.getInt("CANTIDAD_VAC")); obj.setCantidadDisc(rs.getInt("CANTIDAD_DISC")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<HkValueStatus> listarHkRoomDiscrepancy(){ List<HkValueStatus> lista = new ArrayList<HkValueStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT 99 ROOM_STATUS_ID,'DISC' room_status_code,'Discrepancy' room_status_desc, COUNT(1) CANTIDAD, "); query.append(" SUM(CASE WHEN r.hk_status='OCC' THEN 1 ELSE 0 END) CANTIDAD_OCC, "); query.append(" SUM(CASE WHEN r.hk_status='VAC' THEN 1 ELSE 0 END) CANTIDAD_VAC, "); query.append(" SUM(CASE WHEN r.hk_status<>r.room_status THEN 1 ELSE 0 END) CANTIDAD_DISC "); query.append(" FROM OPERA.ROOM r "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' and r.hk_status<>r.fo_status "); query.append(" HAVING COUNT(1)>0 "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkValueStatus obj=new HkValueStatus(); obj.setId(rs.getInt("ROOM_STATUS_ID")); obj.setCodigo(rs.getString("ROOM_STATUS_CODE")); obj.setDenominacion(rs.getString("ROOM_STATUS_DESC")); obj.setCantidad(rs.getInt("cantidad")); // obj.setCantidadOcc(rs.getInt("CANTIDAD_OCC")); obj.setCantidadVac(rs.getInt("CANTIDAD_VAC")); obj.setCantidadDisc(rs.getInt("CANTIDAD_DISC")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<HkRoomStatus> listarHkRoomStatusByStatus(Integer status){ List<HkRoomStatus> lista = new ArrayList<HkRoomStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, "); query.append(" CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status, "); query.append(" TO_CHAR(v.arrival,'DD/MM') arrival, "); query.append(" TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time "); query.append(" ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy "); query.append(" ,l.repair_remarks "); query.append(" ,x.reserved,x.arrival_next,x.arrival_next_time "); query.append(" ,NVL(v.vip,' ') vip "); query.append(" FROM OPERA.ROOM r "); query.append(" INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) "); query.append(" LEFT JOIN ( "); query.append(" select r.room,MIN(r.resv_status) resv_status,min(r.arrival) arrival,max(r.departure) departure,max(r.departure_time) departure_time,MIN(r.vip) vip "); query.append(" from reservation_general_view_hld r "); query.append(" where r.trunc_departure>=pms_p.business_date and r.room is not null "); query.append(" and r.resv_status IN ('CHECKED IN','CHECKED OUT') "); query.append(" group by r.room "); query.append(" ) v ON (v.room=r.room) "); query.append(" LEFT JOIN ( "); query.append(" SELECT r.room,(r.reason_code||' '||r.repair_remarks) repair_remarks "); query.append(" FROM opera.room_repairs r "); query.append(" WHERE R.END_DATE>=pms_p.business_date AND R.COMPLETED_DATE IS NULL "); query.append(" )l ON (l.room=r.room) "); query.append(" LEFT JOIN ( "); query.append(" SELECT V.ROOM,1 reserved,MIN(v.arrival) arrival_next,MIN(v.arrival_time) arrival_next_time "); query.append(" from reservation_general_view_hld v "); query.append(" where v.resv_status ='RESERVED' "); query.append(" and TO_CHAR(v.arrival,'DDMMRRRR')=TO_CHAR(pms_p.business_date,'DDMMRRRR') "); query.append(" GROUP BY V.ROOM "); query.append(" ) x ON (x.room=r.room) "); query.append(" WHERE SUITE_TYPE<>'PSUEDO' "); query.append(" AND r.room_status=? "); query.append(" ORDER BY r.hk_status DESC,to_number(r.floor) ASC, to_number(r.room) ASC "); ps = conn.prepareStatement(query.toString()); if(status==1){//DI Dirty ps.setString(1, "DI"); }else if(status==2){//CL Clean ps.setString(1, "CL"); }else if(status==3){//IP Inspected ps.setString(1, "IP"); }else if(status==4){//OS Out of Service ps.setString(1, "OS"); }else if(status==5){//OO Out of Order ps.setString(1, "OO"); } rs = ps.executeQuery(); while(rs.next()){ HkRoomStatus obj=new HkRoomStatus(); obj.setRoom(rs.getString("room")); obj.setRoomStatus(rs.getString("room_status")); obj.setHkStatus(rs.getString("hk_status")); obj.setRoomType(rs.getString("label")); obj.setRoomTypeDescription(rs.getString("short_description")); // obj.setResvStatus(rs.getString("resv_status")); obj.setArrival(rs.getString("arrival")); obj.setDeparture(rs.getString("departure")); obj.setDepartureTime(rs.getString("departure_time")); // obj.setIsDiscrepancy(rs.getString("isdiscrepancy").equals("Y")?Boolean.TRUE:Boolean.FALSE); obj.setStatusDiscrepancy(Constante.STATUS_DISCREPANCY_N); obj.setStatusArrivalTime(Constante.STATUS_ARRIVALTIME_N); // obj.setRepairRemarks(rs.getString("repair_remarks")); // obj.setReserved(rs.getInt("reserved")==1?Boolean.TRUE:Boolean.FALSE); obj.setArrivalNext(rs.getString("arrival_next")); obj.setArrivalNextTime(rs.getString("arrival_next_time")); // obj.setVip(rs.getString("vip")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<HkRoomStatus> listarHkRoomStatusByDiscrepancy(){ List<HkRoomStatus> lista = new ArrayList<HkRoomStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, "); query.append(" CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status, "); query.append(" TO_CHAR(v.arrival,'DD/MM') arrival, "); query.append(" TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time "); query.append(" ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy "); query.append(" ,NVL(v.vip,' ') vip "); query.append(" FROM OPERA.ROOM r "); query.append(" INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) "); query.append(" LEFT JOIN ( "); query.append(" select r.room,MIN(r.resv_status) resv_status,min(r.arrival) arrival,max(r.departure) departure,max(r.departure_time) departure_time,MIN(r.vip) vip "); query.append(" from reservation_general_view_hld r "); query.append(" where r.trunc_departure>=pms_p.business_date and r.room is not null "); query.append(" and r.resv_status IN ('CHECKED IN','CHECKED OUT') "); query.append(" group by r.room "); query.append(" ) v ON (v.room=r.room) "); query.append(" WHERE SUITE_TYPE<>'PSUEDO' "); query.append(" AND r.fo_status<>r.hk_status "); query.append(" ORDER BY r.hk_status DESC,to_number(r.floor) ASC, to_number(r.room) ASC "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkRoomStatus obj=new HkRoomStatus(); obj.setRoom(rs.getString("room")); obj.setRoomStatus(rs.getString("room_status")); obj.setHkStatus(rs.getString("hk_status")); obj.setRoomType(rs.getString("label")); obj.setRoomTypeDescription(rs.getString("short_description")); // obj.setResvStatus(rs.getString("resv_status")); obj.setArrival(rs.getString("arrival")); obj.setDeparture(rs.getString("departure")); obj.setDepartureTime(rs.getString("departure_time")); // obj.setIsDiscrepancy(rs.getString("isdiscrepancy").equals("Y")?Boolean.TRUE:Boolean.FALSE); obj.setStatusDiscrepancy(Constante.STATUS_DISCREPANCY_Y); obj.setStatusArrivalTime(Constante.STATUS_ARRIVALTIME_N); obj.setVip(rs.getString("vip")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } /** * Arrival Time * @return */ public List<HkRoomStatus> listarHkRoomStatusByArrivalTime(){ List<HkRoomStatus> lista = new ArrayList<HkRoomStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, "); query.append(" CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status, "); query.append(" TO_CHAR(v.arrival,'DD/MM') arrival, "); query.append(" TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time "); query.append(" ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy "); query.append(" ,v.arrival_time "); query.append(" ,NVL(v.vip,' ') vip "); query.append(" FROM OPERA.ROOM r "); query.append(" INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) "); query.append(" LEFT JOIN ( "); query.append(" select v.room,v.resv_status,v.departure,v.departure_time,v.arrival,v.arrival_time,v.vip "); query.append(" from reservation_general_view_hld v "); query.append(" inner join ( "); query.append(" SELECT V.ROOM,MIN(V.RESV_NAME_ID) RESV_NAME_ID "); query.append(" from reservation_general_view_hld v "); query.append(" where v.resv_status ='RESERVED' "); query.append(" and TO_CHAR(v.arrival,'DDMMRRRR')=TO_CHAR(pms_p.business_date,'DDMMRRRR') "); query.append(" GROUP BY V.ROOM "); query.append(" ) m ON (v.RESV_NAME_ID=m.RESV_NAME_ID) "); query.append(" where m.RESV_NAME_ID=v.RESV_NAME_ID "); query.append(" ) v ON (v.room=r.room) "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); query.append(" AND r.fo_status='VAC' AND r.room_status IN ('CL','DI','OS') "); query.append(" AND v.arrival_time IS NOT NULL "); query.append(" ORDER BY r.hk_status DESC,to_number(r.floor) ASC, to_number(r.room) ASC "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkRoomStatus obj=new HkRoomStatus(); obj.setRoom(rs.getString("room")); obj.setRoomStatus(rs.getString("room_status")); obj.setHkStatus(rs.getString("hk_status")); obj.setRoomType(rs.getString("label")); obj.setRoomTypeDescription(rs.getString("short_description")); // obj.setResvStatus(rs.getString("resv_status")); obj.setArrival(rs.getString("arrival")); obj.setDeparture(rs.getString("departure")); obj.setDepartureTime(rs.getString("departure_time")); // obj.setIsDiscrepancy(Boolean.FALSE); obj.setIsArrivalTime(Boolean.TRUE); obj.setStatusDiscrepancy(Constante.STATUS_DISCREPANCY_N); obj.setStatusArrivalTime(Constante.STATUS_ARRIVALTIME_Y); obj.setArrivalTime(rs.getString("arrival_time")); obj.setVip(rs.getString("vip")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<HkValueStatus> listarHkRoomArrivalTime(){ List<HkValueStatus> lista = new ArrayList<HkValueStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT 98 ROOM_STATUS_ID, "); query.append(" 'ARRT' room_status_code,'Arrival Time DI,CL,OS' room_status_desc, "); query.append(" COUNT(1) CANTIDAD, "); query.append(" 0 CANTIDAD_OCC, "); query.append(" COUNT(1) CANTIDAD_VAC, "); query.append(" 0 CANTIDAD_DISC "); query.append(" FROM OPERA.ROOM r "); query.append(" INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) "); query.append(" LEFT JOIN ( "); query.append(" select v.room,v.resv_status,v.departure,v.departure_time,v.arrival,v.arrival_time "); query.append(" from reservation_general_view_hld v "); query.append(" inner join ( "); query.append(" SELECT V.ROOM,MIN(V.RESV_NAME_ID) RESV_NAME_ID "); query.append(" from reservation_general_view_hld v "); query.append(" where v.resv_status ='RESERVED' "); query.append(" and TO_CHAR(v.arrival,'DDMMRRRR')=TO_CHAR(pms_p.business_date,'DDMMRRRR') "); query.append(" GROUP BY V.ROOM "); query.append(" ) m ON (v.RESV_NAME_ID=m.RESV_NAME_ID) "); query.append(" where m.RESV_NAME_ID=v.RESV_NAME_ID "); query.append(" ) v ON (v.room=r.room) "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); query.append(" AND r.fo_status='VAC' AND r.room_status IN ('CL','DI','OS') "); query.append(" AND v.arrival_time IS NOT NULL "); query.append(" GROUP BY r.fo_status "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkValueStatus obj=new HkValueStatus(); obj.setId(rs.getInt("ROOM_STATUS_ID")); obj.setCodigo(rs.getString("ROOM_STATUS_CODE")); obj.setDenominacion(rs.getString("ROOM_STATUS_DESC")); obj.setCantidad(rs.getInt("cantidad")); // obj.setCantidadOcc(rs.getInt("CANTIDAD_OCC")); obj.setCantidadVac(rs.getInt("CANTIDAD_VAC")); obj.setCantidadDisc(rs.getInt("CANTIDAD_DISC")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } /*** * Do Not Disturb */ public List<HkValueStatus> listarHkServiceStatus(String serviceStatus){ List<HkValueStatus> lista = new ArrayList<HkValueStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT 97 SERV_STATUS_ID,r.service_status serv_status_code,'Do Not Disturb' serv_status_desc, COUNT(1) CANTIDAD, "); query.append(" SUM(CASE WHEN r.hk_status='OCC' THEN 1 ELSE 0 END) CANTIDAD_OCC, "); query.append(" SUM(CASE WHEN r.hk_status='VAC' THEN 1 ELSE 0 END) CANTIDAD_VAC, "); query.append(" COUNT(1) CANTIDAD_SERVSTAT "); query.append(" FROM OPERA.ROOM r "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); query.append(" and r.service_status =? "); query.append(" group by r.service_status "); ps = conn.prepareStatement(query.toString()); ps.setString(1, serviceStatus); rs = ps.executeQuery(); while(rs.next()){ HkValueStatus obj=new HkValueStatus(); obj.setId(rs.getInt("SERV_STATUS_ID")); obj.setCodigo(rs.getString("serv_status_code")); obj.setDenominacion(rs.getString("serv_status_desc")); obj.setCantidad(rs.getInt("cantidad")); // obj.setCantidadOcc(rs.getInt("CANTIDAD_OCC")); obj.setCantidadVac(rs.getInt("CANTIDAD_VAC")); obj.setCantidadDisc(rs.getInt("CANTIDAD_SERVSTAT")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<HkRoomStatus> listarHkRoomServiceStatus(String serviceStatus){ List<HkRoomStatus> lista = new ArrayList<HkRoomStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, "); query.append(" CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status, "); query.append(" TO_CHAR(v.arrival,'DD/MM') arrival, "); query.append(" TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time "); query.append(" ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy "); query.append(" ,NVL(v.vip,' ') vip "); query.append(" FROM OPERA.ROOM r "); query.append(" INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) "); query.append(" LEFT JOIN ( "); query.append(" select r.room,MIN(r.resv_status) resv_status,min(r.arrival) arrival,max(r.departure) departure,max(r.departure_time) departure_time,MIN(r.vip) vip "); query.append(" from reservation_general_view_hld r "); query.append(" where r.trunc_departure>=pms_p.business_date and r.room is not null "); query.append(" and r.resv_status IN ('CHECKED IN','CHECKED OUT') "); query.append(" group by r.room "); query.append(" ) v ON (v.room=r.room) "); query.append(" WHERE SUITE_TYPE<>'PSUEDO' "); query.append(" AND r.service_status=? "); query.append(" ORDER BY r.hk_status DESC,to_number(r.floor) ASC, to_number(r.room) ASC "); ps = conn.prepareStatement(query.toString()); ps.setString(1, serviceStatus); rs = ps.executeQuery(); while(rs.next()){ HkRoomStatus obj=new HkRoomStatus(); obj.setRoom(rs.getString("room")); obj.setRoomStatus(rs.getString("room_status")); obj.setHkStatus(rs.getString("hk_status")); obj.setRoomType(rs.getString("label")); obj.setRoomTypeDescription(rs.getString("short_description")); // obj.setResvStatus(rs.getString("resv_status")); obj.setArrival(rs.getString("arrival")); obj.setDeparture(rs.getString("departure")); obj.setDepartureTime(rs.getString("departure_time")); // obj.setIsDiscrepancy(rs.getString("isdiscrepancy").equals("Y")?Boolean.TRUE:Boolean.FALSE); obj.setStatusDiscrepancy(Constante.STATUS_DISCREPANCY_N); obj.setStatusArrivalTime(Constante.STATUS_ARRIVALTIME_N); obj.setIsDoNotDisturb(Boolean.TRUE); obj.setVip(rs.getString("vip")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } /*** * TRACES FOR HK */ public List<HkValueStatus> listarHkTracesHK(){ List<HkValueStatus> lista = new ArrayList<HkValueStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT 96 SERV_STATUS_ID,'TRHK' serv_status_code,'Traces for HK' serv_status_desc, COUNT(1) CANTIDAD, "); query.append(" SUM(CASE WHEN r.hk_status='OCC' THEN 1 ELSE 0 END) CANTIDAD_OCC, "); query.append(" SUM(CASE WHEN r.hk_status='VAC' THEN 1 ELSE 0 END) CANTIDAD_VAC, "); query.append(" COUNT(1) CANTIDAD_SERVSTAT "); query.append(" FROM OPERA.ROOM r "); query.append(" INNER JOIN ( "); query.append(" select v.room,v.resv_status,v.departure,v.departure_time,v.arrival,v.arrival_time,g.trace_text "); query.append(" from reservation_general_view_hld v "); query.append(" INNER JOIN guest_rsv_traces t ON (v.resv_name_id=t.resv_name_id AND t.dept_id='HK') "); query.append(" INNER JOIN guest_traces g ON (g.trace_id=t.trace_id and g.dept_id='HK') "); query.append(" where v.room is not null and v.resv_status = 'RESERVED' "); query.append(" and TO_CHAR(t.trace_on,'DDMMRRRR')=TO_CHAR(pms_p.business_date,'DDMMRRRR') "); query.append(" and t.status_flag='N' "); query.append(" ) v ON (v.room=r.room) "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkValueStatus obj=new HkValueStatus(); obj.setId(rs.getInt("SERV_STATUS_ID")); obj.setCodigo(rs.getString("serv_status_code")); obj.setDenominacion(rs.getString("serv_status_desc")); obj.setCantidad(rs.getInt("cantidad")); // obj.setCantidadOcc(rs.getInt("CANTIDAD_OCC")); obj.setCantidadVac(rs.getInt("CANTIDAD_VAC")); obj.setCantidadDisc(rs.getInt("CANTIDAD_SERVSTAT")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<HkRoomStatus> listarHkTracesDetailsHK(){ List<HkRoomStatus> lista = new ArrayList<HkRoomStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, "); query.append(" CASE WHEN NVL(v.resv_status,'F')='CHECKED IN' THEN 'CI' WHEN NVL(v.resv_status,'F')='CHECKED OUT' THEN 'CO' ELSE '' END resv_status, "); query.append(" TO_CHAR(v.arrival,'DD/MM') arrival, "); query.append(" TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time "); query.append(" ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy "); query.append(" ,v.arrival_time "); query.append(" ,v.trace_text "); query.append(" ,NVL(v.vip,' ') vip "); query.append(" FROM OPERA.ROOM r "); query.append(" INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) "); query.append(" INNER JOIN ( "); query.append(" select v.room,v.resv_status,v.departure,v.departure_time,v.arrival,v.arrival_time,g.trace_text,v.vip "); query.append(" from reservation_general_view_hld v "); query.append(" INNER JOIN guest_rsv_traces t ON (v.resv_name_id=t.resv_name_id AND t.dept_id='HK') "); query.append(" INNER JOIN guest_traces g ON (g.trace_id=t.trace_id and g.dept_id='HK') "); query.append(" where v.room is not null and v.resv_status = 'RESERVED' "); query.append(" and TO_CHAR(t.trace_on,'DDMMRRRR')=TO_CHAR(pms_p.business_date,'DDMMRRRR') "); query.append(" and t.status_flag='N' "); query.append(" ) v ON (v.room=r.room) "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); query.append(" ORDER BY r.hk_status DESC,to_number(r.floor) ASC, to_number(r.room) ASC "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkRoomStatus obj=new HkRoomStatus(); obj.setRoom(rs.getString("room")); obj.setRoomStatus(rs.getString("room_status")); obj.setHkStatus(rs.getString("hk_status")); obj.setRoomType(rs.getString("label")); obj.setRoomTypeDescription(rs.getString("short_description")); // obj.setResvStatus(rs.getString("resv_status")); obj.setArrival(rs.getString("arrival")); obj.setDeparture(rs.getString("departure")); obj.setDepartureTime(rs.getString("departure_time")); // obj.setIsDiscrepancy(Boolean.FALSE); obj.setIsArrivalTime(Boolean.FALSE); obj.setStatusDiscrepancy(Constante.STATUS_DISCREPANCY_N); obj.setStatusArrivalTime(Constante.STATUS_ARRIVALTIME_N); obj.setArrivalTime(rs.getString("arrival_time")); // obj.setIsTracesHk(Boolean.TRUE); obj.setTraceTextHk(rs.getString("trace_text")); obj.setVip(rs.getString("vip")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } /** * Estadistica de habitaciones */ public List<HkFloors> listarHkEstadistica(){ List<HkFloors> lista = new ArrayList<HkFloors>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT SUM(CASE WHEN r.hk_status='OCC' THEN 1 ELSE 0 END) CANTIDAD_OCC, "); query.append(" SUM(CASE WHEN r.hk_status='VAC' THEN 1 ELSE 0 END) CANTIDAD_VAC, "); query.append(" SUM(CASE WHEN r.hk_status<>r.fo_status THEN 1 ELSE 0 END) CANTIDAD_DISC, "); query.append(" SUM(CASE WHEN r.room_status='IP' THEN 1 ELSE 0 END) CANTIDAD_IP, "); query.append(" SUM(CASE WHEN r.room_status='DI' THEN 1 ELSE 0 END) CANTIDAD_DI, "); query.append(" SUM(CASE WHEN r.room_status='CL' THEN 1 ELSE 0 END) CANTIDAD_CL, "); query.append(" SUM(CASE WHEN r.room_status='OO' THEN 1 ELSE 0 END) CANTIDAD_OO, "); query.append(" SUM(CASE WHEN r.room_status='OS' THEN 1 ELSE 0 END) CANTIDAD_OS "); query.append(" ,SUM(o.adults) adults,SUM(o.children) children "); query.append(" FROM OPERA.ROOM r "); query.append(" LEFT JOIN ( "); query.append(" select v.room ,sum(v.adults) adults, sum(v.children) children "); query.append(" from reservation_general_view_hld v "); query.append(" where v.resv_status ='CHECKED IN' "); query.append(" group by v.room "); query.append(" ) o ON (o.room=r.room) "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkFloors obj=new HkFloors(); obj.setCantidadOcc(rs.getInt("CANTIDAD_OCC")); obj.setCantidadVac(rs.getInt("CANTIDAD_VAC")); obj.setCantidadDisc(rs.getInt("CANTIDAD_DISC")); obj.setCantidadIp(rs.getInt("CANTIDAD_IP")); obj.setCantidadDi(rs.getInt("CANTIDAD_DI")); obj.setCantidadCl(rs.getInt("CANTIDAD_CL")); obj.setCantidadOo(rs.getInt("CANTIDAD_OO")); obj.setCantidadOs(rs.getInt("CANTIDAD_OS")); //-- obj.setAdults(rs.getInt("adults")); obj.setChildren(rs.getInt("children")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<HkArrival> listarHkArrivals(){ List<HkArrival> lista = new ArrayList<HkArrival>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select COUNT(v.RESV_NAME_ID) arrival_all, "); query.append(" SUM(case when v.room is null THEN 1 ELSE 0 end) arrival_room_n, "); query.append(" SUM(case when v.room is not null THEN 1 ELSE 0 end) arrival_room_y "); query.append(" from reservation_general_view_hld v "); query.append(" where v.resv_status ='RESERVED' "); query.append(" and TO_CHAR(v.arrival,'DDMMRRRR')=TO_CHAR(pms_p.business_date,'DDMMRRRR') "); query.append(" and v.shared_yn='N' "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkArrival obj=new HkArrival(); obj.setArrivalAll(rs.getInt("arrival_all")); obj.setArrivalRoomN(rs.getInt("arrival_room_n")); obj.setArrivalRoomY(rs.getInt("arrival_room_y")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } /** * Rate Pack * @return */ public List<HkRoomStatus> listarHkRatePack(){ List<HkRoomStatus> lista = new ArrayList<HkRoomStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT r.room,r.room_status,r.hk_status,c.label,c.short_description, "); query.append(" TO_CHAR(v.arrival,'DD/MM') arrival, "); query.append(" TO_CHAR(v.departure,'DD/MM') departure,TO_CHAR(v.departure_time) departure_time "); query.append(" ,CASE WHEN r.hk_status<>r.fo_status THEN 'Y' ELSE 'N' END isdiscrepancy "); query.append(" ,v.arrival_time "); query.append(" ,NVL(v.vip,' ') vip "); query.append(" ,v.rate_code "); query.append(" FROM OPERA.ROOM r "); query.append(" INNER JOIN OPERA.ROOM_CATEGORY_TEMPLATE c ON (r.room_category=c.room_category) "); query.append(" INNER JOIN ( "); query.append(" select v.room,MAX(v.departure) departure,MAX(v.departure_time) departure_time,MIN(v.arrival) arrival,MIN(v.arrival_time) arrival_time,MAX(v.vip) vip "); query.append(" ,MIN(v.rate_code) rate_code "); query.append(" from reservation_general_view_hld v "); query.append(" where v.resv_status ='RESERVED' "); query.append(" AND TO_CHAR(v.arrival,'DDMMRRRR')=TO_CHAR(pms_p.business_date,'DDMMRRRR') "); query.append(" AND v.rate_code in ('PQANI','PQBOH','PQREL','PQRFR','PQRNV') "); query.append(" AND v.room IS NOT NULL "); query.append(" GROUP BY v.room "); query.append(" ) v ON (v.room=r.room) "); query.append(" WHERE r.SUITE_TYPE<>'PSUEDO' "); query.append(" ORDER BY r.hk_status DESC,to_number(r.floor) ASC, to_number(r.room) ASC "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkRoomStatus obj=new HkRoomStatus(); obj.setRoom(rs.getString("room")); obj.setRoomStatus(rs.getString("room_status")); obj.setHkStatus(rs.getString("hk_status")); obj.setRoomType(rs.getString("label")); obj.setRoomTypeDescription(rs.getString("short_description")); // obj.setArrival(rs.getString("arrival")); obj.setDeparture(rs.getString("departure")); obj.setDepartureTime(rs.getString("departure_time")); // obj.setIsDiscrepancy(Boolean.FALSE); obj.setIsArrivalTime(Boolean.FALSE); obj.setStatusDiscrepancy(Constante.STATUS_DISCREPANCY_N); obj.setStatusArrivalTime(Constante.STATUS_ARRIVALTIME_N); obj.setArrivalTime(rs.getString("arrival_time")); // obj.setIsTracesHk(Boolean.FALSE); obj.setVip(rs.getString("vip")); // //rate_code obj.setIsRatePack(Boolean.TRUE); obj.setRateCode(rs.getString("rate_code")); lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public List<HkValueStatus> headerHkRatePack(){ List<HkValueStatus> lista = new ArrayList<HkValueStatus>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select 95 SERV_STATUS_ID,'RAT-PQ' serv_status_code,'Rate Code Package' serv_status_desc, COUNT(1) CANTIDAD "); query.append(" from ( "); query.append(" select v.room,COUNT(1) CANTIDAD "); query.append(" from reservation_general_view_hld v "); query.append(" where v.resv_status ='RESERVED' "); query.append(" AND TO_CHAR(v.arrival,'DDMMRRRR')=TO_CHAR(pms_p.business_date,'DDMMRRRR') "); query.append(" AND v.rate_code in ('PQANI','PQBOH','PQREL','PQRFR','PQRNV') "); query.append(" AND v.room IS NOT NULL "); query.append(" GROUP BY v.room ) "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ HkValueStatus obj=new HkValueStatus(); obj.setId(rs.getInt("SERV_STATUS_ID")); obj.setCodigo(rs.getString("serv_status_code")); obj.setDenominacion(rs.getString("serv_status_desc")); obj.setCantidad(rs.getInt("cantidad")); // lista.add(obj); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } }
package com.hotel.spring.controller; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /* * This sample demonstrate basic File support */ import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.io.FileUtils; import com.hotel.dao.ConnectionFactoryOperaBat; import com.hotel.vo.Arrival; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Font; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfImportedPage; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfReader; import com.lowagie.text.pdf.PdfWriter; //including this import makes the code easier to read import oracle.jdbc.driver.OracleResultSet; // needed for new BFILE class import oracle.sql.BFILE; public class FileAttachment { private String pathfile; private String mergefilename; public FileAttachment(String pathfile,String mergefilename){ this.pathfile=pathfile; this.mergefilename=mergefilename; } public void createFile(String fechaArrival)throws Exception{ PreparedStatement ps=null; ResultSet rs=null; try{ Connection conn = ConnectionFactoryOperaBat.getInstance().getConnection(); // Select the file from the table StringBuilder query = new StringBuilder(); query.append(" SELECT a.confirmation_no,a.guest_name,a.guest_first_name,TO_CHAR(a.arrival,'DD/MM/RR') arrival,TO_CHAR(a.departure,'DD/MM/RR') departure,a.guest_country,a.guest_country_desc,a.guest_name_id,o.problem_desc file_desc,o.bfile_locator, "); query.append(" (CASE WHEN o.bfile_locator IS NULL THEN 'NO' ELSE 'SI' END) IS_ATTACHMENT "); query.append(" FROM opera.reservation_general_view_hld a "); query.append(" LEFT JOIN ACC_CON_ALL_ATTACHMENTS_HLD t on (a.guest_name_id=t.link_id) "); query.append(" LEFT JOIN work_orders o on (o.wo_number=t.attach_id) "); query.append(" WHERE TO_CHAR(a.ARRIVAL,'DD/MM/RRRR')=? "); query.append(" AND (A.RESV_STATUS='RESERVED' OR A.RESV_STATUS='PROSPECT') "); query.append(" ORDER BY a.sguest_name ASC "); ps = conn.prepareStatement(query.toString()); ps.setString(1, fechaArrival); rs = ps.executeQuery(); List<InputStream> list = new ArrayList<InputStream>(); List<Arrival> lAtt_SI = new ArrayList<Arrival>(); List<Arrival> lAtt_NO = new ArrayList<Arrival>(); while (rs.next()) { String isAttachment = rs.getString("IS_ATTACHMENT"); if(isAttachment.equals("SI")){ String x = rs.getString("file_desc"); BFILE bfile = ((OracleResultSet) rs).getBFILE("bfile_locator"); // Dump the file contents dumpBfile(conn, bfile); list.add(new FileInputStream(new File(this.pathfile+bfile.getName()+".pdf"))); } Arrival att=new Arrival(); att.setConfirmationNo(rs.getString("confirmation_no")); att.setGuestName(rs.getString("guest_name")); att.setGuestFirstName(rs.getString("guest_first_name")); att.setArrival(rs.getString("arrival")); att.setDeparture(rs.getString("departure")); att.setGuestCountry(rs.getString("guest_country_desc")); att.setIsAttachment(rs.getString("IS_ATTACHMENT")); if(isAttachment.equals("SI")){ lAtt_SI.add(att); }else{ lAtt_NO.add(att); } } // Resulting pdf OutputStream out = new FileOutputStream(new File(this.pathfile+this.mergefilename)); doMerge(list,lAtt_SI,lAtt_NO, out); // Close all resources } catch (SQLException e) { throw new RuntimeException(e); } catch (Exception ex) { throw new Exception(ex); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } } // Utility function to dump the contents of a Bfile private void dumpBfile(Connection conn, BFILE bfile) throws Exception { bfile.openFile(); long length = bfile.length(); InputStream instream = bfile.getBinaryStream(); byte[] buffer = new byte[instream.available()]; instream.read(buffer); File targetFile = new File(this.pathfile+bfile.getName()+".pdf"); FileUtils.copyInputStreamToFile(instream, targetFile); //Files.write(buffer, targetFile); // Close input stream instream.close(); // close file handler bfile.closeFile(); } private void doMerge(List<InputStream> list,List<Arrival> lAtt_SI,List<Arrival> lAtt_NO, OutputStream outputStream) throws DocumentException, IOException { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfPTable table = new PdfPTable(7); PdfPCell cell = new PdfPCell(new Paragraph("WITH ATTACHMENTS")); cell.setColspan(7); table.addCell(cell); //-- table.addCell("Confirmation No"); table.addCell("Guest Name"); table.addCell("Guest First Name"); table.addCell("Arrival"); table.addCell("Departure"); table.addCell("Guest Country"); table.addCell("Att"); //-- for (Arrival att : lAtt_SI) { table.addCell(att.getConfirmationNo()); table.addCell(att.getGuestName()); table.addCell(att.getGuestFirstName()); table.addCell(att.getArrival()); table.addCell(att.getDeparture()); table.addCell(att.getGuestCountry()); table.addCell(att.getIsAttachment()); } document.add(table); PdfPTable tableN = new PdfPTable(7); tableN.setSpacingBefore(20); PdfContentByte cb = writer.getDirectContent(); for (InputStream in : list) { PdfReader reader = new PdfReader(in); for (int i = 1; i <= reader.getNumberOfPages(); i++) { document.newPage(); PdfImportedPage page = writer.getImportedPage(reader, i); cb.addTemplate(page, 0, 0); } } outputStream.flush(); document.close(); outputStream.close(); } public static void main(String args[]) throws Exception { FileAttachment s=new FileAttachment("D:\\etc\\","result.pdf"); s.createFile("14/11/2019"); } }
package com.hotel.business; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import com.hotel.dao.ConnectionFactoryOpera; import com.hotel.vo.Arrival; public class RecepcionBo { public List<Arrival> listArrivals(String fecha){ List<Arrival> lista = new ArrayList<Arrival>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT a.confirmation_no,a.guest_name,a.guest_first_name,TO_CHAR(a.arrival,'DD/MM/RR') arrival,TO_CHAR(a.departure,'DD/MM/RR') departure,a.guest_country,a.guest_country_desc,a.guest_name_id,o.problem_desc file_desc,o.bfile_locator, "); query.append(" (CASE WHEN o.bfile_locator IS NULL THEN 'NO' ELSE 'SI' END) IS_ATTACHMENT, "); query.append(" (select wm_concat(note_code||' '||notes) from name$notes where name_id=a.guest_name_id) notes "); query.append(" FROM reservation_general_view_hld a "); query.append(" LEFT JOIN ACC_CON_ALL_ATTACHMENTS_HLD t on (a.guest_name_id=t.link_id) "); query.append(" LEFT JOIN work_orders o on (o.wo_number=t.attach_id) "); query.append(" WHERE TO_CHAR(a.ARRIVAL,'DD/MM/RRRR')=? "); query.append(" AND (A.RESV_STATUS='RESERVED' OR A.RESV_STATUS='PROSPECT') "); query.append(" ORDER BY a.sguest_name ASC "); ps = conn.prepareStatement(query.toString()); ps.setString(1, fecha); rs = ps.executeQuery(); while(rs.next()){ Arrival att=new Arrival(); att.setConfirmationNo(rs.getString("confirmation_no")); att.setGuestName(rs.getString("guest_name")); att.setGuestFirstName(rs.getString("guest_first_name")); att.setArrival(rs.getString("arrival")); att.setDeparture(rs.getString("departure")); att.setGuestCountry(rs.getString("guest_country_desc")); att.setIsAttachment(rs.getString("IS_ATTACHMENT")); att.setNotes(rs.getString("notes")); lista.add(att); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public String getDate(){ String fecha=null; PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append("SELECT TO_CHAR(SYSDATE,'DD/MM/RRRR') FECHA FROM DUAL"); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); if(rs.next()){ fecha=rs.getString("FECHA"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return fecha; } public List<Arrival> listArrivalsSpecial(String fecha){ List<Arrival> lista = new ArrayList<Arrival>(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT a.resv_name_id,a.confirmation_no,TO_CHAR(a.arrival,'DD/MM/RR') arrival,TO_CHAR(a.departure,'DD/MM/RR') departure,a.room,a.room_category_label room_type,a.guest_name,a.guest_first_name,a.guest_country_desc,a.company_name, "); query.append(" TO_CHAR(a.actual_check_in_date,'DD/MM/RR') actual_check_in_date,TO_CHAR(a.actual_check_out_date,'DD/MM/RR') actual_check_out_date, "); query.append(" (case when a.nights=0 then 0 else ROUND(a.room_revenue/a.nights,2) end) revenue, "); query.append(" a.arrival_time,a.departure_time, "); query.append(" (select wm_concat(note_code||' '||notes) from name$notes where name_id=a.guest_name_id) notes, "); query.append(" (select wm_concat(' '||g.trace_text) trace_text from guest_rsv_traces t INNER JOIN guest_traces g ON (g.trace_id=t.trace_id ) where t.resv_name_id=a.resv_name_id) traces, "); query.append(" a.comments "); query.append(" FROM opera.reservation_general_view_hld a "); query.append(" INNER JOIN opera.reservation_special_requests s ON (a.resv_name_id=s.resv_name_id and s.special_request_id=12740) "); query.append(" WHERE TO_CHAR(a.ARRIVAL,'DD/MM/RRRR')=? "); query.append(" ORDER BY a.sguest_name ASC "); ps = conn.prepareStatement(query.toString()); ps.setString(1, fecha); rs = ps.executeQuery(); while(rs.next()){ Arrival att=new Arrival(); att.setResvNameId(rs.getInt("resv_name_id")); att.setConfirmationNo(rs.getString("confirmation_no")); att.setGuestName(rs.getString("guest_name")); att.setGuestFirstName(rs.getString("guest_first_name")); att.setArrival(rs.getString("arrival")); att.setDeparture(rs.getString("departure")); att.setGuestCountry(rs.getString("guest_country_desc")); att.setNotes(rs.getString("notes")); att.setRoom(rs.getString("room")); att.setRoomType(rs.getString("room_type")); att.setCompany(rs.getString("company_name")); att.setCheckIn(rs.getString("actual_check_in_date")); att.setCheckOut(rs.getString("actual_check_out_date")); att.setRevenue(rs.getDouble("revenue")); att.setsRevenue(String.valueOf(rs.getDouble("revenue"))); att.setArrivalTime(rs.getString("arrival_time")); att.setDepartureTime(rs.getString("departure_time")); att.setTraces(rs.getString("traces")); att.setComments(rs.getString("comments")); lista.add(att); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return lista; } public Arrival getReservation(Integer resvNameId){ Arrival att=null; PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT a.resv_name_id,a.confirmation_no,TO_CHAR(a.arrival,'DD/MM/RR') arrival,TO_CHAR(a.departure,'DD/MM/RR') departure,a.room,a.room_category_label room_type,a.guest_name,a.guest_first_name,a.guest_country_desc,a.company_name, "); query.append(" TO_CHAR(a.actual_check_in_date,'DD/MM/RR') actual_check_in_date,TO_CHAR(a.actual_check_out_date,'DD/MM/RR') actual_check_out_date, "); query.append(" (case when a.nights=0 then 0 else ROUND(a.room_revenue/a.nights,2) end) revenue, "); query.append(" a.arrival_time,a.departure_time, "); query.append(" (select wm_concat(note_code||' '||notes) from name$notes where name_id=a.guest_name_id) notes, "); query.append(" (select wm_concat(' '||g.trace_text) trace_text from guest_rsv_traces t INNER JOIN guest_traces g ON (g.trace_id=t.trace_id ) where t.resv_name_id=a.resv_name_id) traces, "); query.append(" a.comments "); query.append(" FROM opera.reservation_general_view_hld a "); query.append(" INNER JOIN opera.reservation_special_requests s ON (a.resv_name_id=s.resv_name_id and s.special_request_id=12740) "); query.append(" WHERE a.resv_name_id=? "); query.append(" ORDER BY a.sguest_name ASC "); ps = conn.prepareStatement(query.toString()); ps.setInt(1, resvNameId); rs = ps.executeQuery(); if(rs.next()){ att=new Arrival(); att.setResvNameId(rs.getInt("resv_name_id")); att.setConfirmationNo(rs.getString("confirmation_no")); att.setGuestName(rs.getString("guest_name")); att.setGuestFirstName(rs.getString("guest_first_name")); att.setArrival(rs.getString("arrival")); att.setDeparture(rs.getString("departure")); att.setGuestCountry(rs.getString("guest_country_desc")); att.setNotes(rs.getString("notes")); att.setRoom(rs.getString("room")); att.setRoomType(rs.getString("room_type")); att.setCompany(rs.getString("company_name")); att.setCheckIn(rs.getString("actual_check_in_date")); att.setCheckOut(rs.getString("actual_check_out_date")); att.setRevenue(rs.getDouble("revenue")); att.setsRevenue(String.valueOf(rs.getDouble("revenue"))); att.setArrivalTime(rs.getString("arrival_time")); att.setDepartureTime(rs.getString("departure_time")); att.setTraces(rs.getString("traces")); att.setComments(rs.getString("comments")); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) {try {ps.close();} catch (SQLException e) {e.printStackTrace();}} if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}} } return att; } }
Para el calculo del costo se requiere la consulta de la información de ventas del PMS Opera y del HMS Micros, ademas se requiere de los movimientos de las recetas y los productos entre los distintos almacenes administrados por el software Materials Control
package com.hotel.business; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.hotel.dao.ConnectionFactoryOpera; import com.hotel.dao.ConnectionFactoryCostos; public class OperaBo { public String getInsertSqlFinJrnlArticles(String date){ StringBuffer sql=new StringBuffer(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryOpera.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT TO_CHAR(ft.trx_date,'DD/MM/RRRR') trx_date,ft.quantity,ft.room,ft.article_id,ac.article_code,ac.description, ft.guest_account_debit,ft.guest_account_credit,
ft.cashier_id,ft.cashier_name "); query.append(" FROM opera.financial_transactions_view ft, "); query.append(" article$_codes ac "); query.append(" WHERE ft.resort = 'HOTEL' "); query.append(" AND ft.trx_date between TO_DATE(?,'DD/MM/RRRR') and TO_DATE(?,'DD/MM/RRRR') "); query.append(" AND ft.trx_type <> 'PACKAGE' "); query.append(" AND ft.is_internal_yn = 'N' "); query.append(" AND ft.article_id is not null "); query.append(" AND ft.article_id=ac.article_id(+) "); query.append(" AND ft.resort=ac.resort(+) "); query.append(" AND ft.trx_code=2420 "); query.append(" AND ft.posted_amount>0 "); ps = conn.prepareStatement(query.toString()); ps.setString(1, date); ps.setString(2, date); rs = ps.executeQuery(); while(rs.next()){ sql.append("("); sql.append(rs.getString("quantity")).append(","); sql.append("'").append(rs.getString("room")).append("',"); sql.append(rs.getString("article_id")).append(","); sql.append("'").append(rs.getString("article_code")).append("',"); sql.append("'").append(rs.getString("description")).append("',"); sql.append(rs.getString("guest_account_debit")).append(","); sql.append(rs.getString("guest_account_credit")).append(","); sql.append(rs.getString("cashier_id")).append(","); sql.append("'").append(rs.getString("cashier_name")).append("',"); sql.append("'").append(rs.getString("trx_date")).append("'"); sql.append("),"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace();} } if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace();} } } if(sql.toString().trim().length()>0) return sql.toString().substring(0, sql.toString().length()-1); else return null; } }
package com.hotel.business; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.hotel.dao.ConnectionFactoryOpera; import com.hotel.dao.ConnectionFactoryCostos; import com.hotel.dao.ConnectionFactoryMicros; public class MicrosBo { public String getInsertSqlCheck(String date){ StringBuffer sql=new StringBuffer(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryMicros.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select T.CHECKID,t.cf_cnumser,t.cf_cnumdoc,t.cf_dfecdoc,t.cf_dfecven,t.cf_ccodcli,t.cf_cnombre,t.cf_ccodmon,t.cf_ntipcam,t.cf_nprecio,t.cf_nigv,t.others, t.cf_nimport,t.descuento,t.DESC_ANTICIPO from ( "); query.append(" select to_char(c.checknumber) as cf_cnumser, "); query.append(" 'CARGO HAB' as cf_cnumdoc, "); query.append(" to_char(c.checkopen,'DD/MM/RRRR') as cf_dfecdoc, "); query.append(" to_char(c.checkclose,'DD/MM/RRRR') as cf_dfecven, "); query.append(" 'HAB '||to_char(t.OBJECTNUMBER) as cf_ccodcli, "); query.append(" 'CHK '||to_char(c.checknumber) as cf_cnombre, "); query.append(" 'MN' as cf_ccodmon, "); query.append(" 2.776 as cf_ntipcam, "); query.append(" round(c.subtotal,2) as cf_nprecio, "); query.append(" round(c.tax,2) as cf_nigv, "); query.append(" (round(c.other,2)+round(c.autogratuity,2)) as others, "); query.append(" round(c.payment,2) as cf_nimport "); query.append(" ,NVL((SELECT SUM(AMOUNT1) FROM MICROSDB.TOTALS WHERE FLAGS=6 AND CHECKID=c.checkid),0) descuento "); query.append(" ,c.CHECKID "); query.append(" ,(SELECT SUM(cd.total) FROM MICROSDB.check_detail CD inner join MICROSDB.DISCOUNT_DETAIL X on (X.CHECKDETAILID=cd.CHECKDETAILID) WHERE X.dscntid=144 AND CD.CHECKID =c.checkid) DESC_ANTICIPO "); query.append(" from microsdb.checks c "); query.append(" INNER JOIN MICROSDB.DINING_TABLE t on (c.diningtableid=t.diningtableid) "); query.append(" where c.checkopen >= TO_DATE('").append(date).append("'||'00:00:00', 'DD/MM/RRRR HH24:MI:SS') "); query.append(" AND c.checkopen <= TO_DATE('").append(date).append("'||'23:59:59', 'DD/MM/RRRR HH24:MI:SS') "); query.append(" AND c.revctrid!=4 "); query.append(" ) t WHERE t.descuento<>0 order by t.CHECKID ASC "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ sql.append("("); sql.append("'").append(rs.getString("CHECKID")).append("',"); sql.append("'").append(rs.getString("cf_cnumser")).append("',"); sql.append("'").append(rs.getString("cf_cnumdoc")).append("',"); sql.append("'").append(rs.getString("cf_dfecdoc")).append("',"); sql.append("'").append(rs.getString("cf_dfecven")).append("',"); sql.append("'").append(rs.getString("cf_ccodcli")).append("',"); sql.append("'").append(rs.getString("cf_cnombre")).append("',"); sql.append("'").append(rs.getString("cf_ccodmon")).append("',"); sql.append(rs.getString("cf_ntipcam")).append(","); sql.append(rs.getString("cf_nprecio")).append(","); sql.append(rs.getString("cf_nigv")).append(","); sql.append(rs.getString("others")).append(","); sql.append(rs.getString("cf_nimport")).append(","); sql.append(rs.getString("descuento")).append(","); sql.append(rs.getString("DESC_ANTICIPO")); sql.append("),"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace();} } if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace();} } } if(sql.toString().trim().length()>0) return sql.toString().substring(0, sql.toString().length()-1); else return null; } }
package com.hotel.business; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.hotel.dao.ConnectionFactoryMaterial; import com.hotel.dao.ConnectionFactoryOpera; import com.hotel.dao.ConnectionFactoryCostos; public class MaterialBo { public String getInsertSqlSParte(){ StringBuffer sql=new StringBuffer(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryMaterial.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select p.spa_id,p.spa_name,p.sgr_id from MCDATA.SPARTE p "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ sql.append("("); sql.append(rs.getString("spa_id")).append(","); sql.append("'").append(rs.getString("spa_name")).append("',"); sql.append(rs.getString("sgr_id")); sql.append("),"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace();} } if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace();} } } return sql.toString().substring(0, sql.toString().length()-1); } public String getInsertSqlSParteGR(){ StringBuffer sql=new StringBuffer(); PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryMaterial.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select p.sgr_id,p.sgr_name from MCDATA.SPARTEGR p "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); while(rs.next()){ sql.append("("); sql.append(rs.getString("sgr_id")).append(","); sql.append("'").append(rs.getString("sgr_name")).append("'"); sql.append("),"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace();} } if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace();} } } return sql.toString().substring(0, sql.toString().length()-1); } public void getInsertSqlProdukt(){ PreparedStatement ps=null; ResultSet rs=null; try { Connection conn = ConnectionFactoryMaterial.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" select p.PRO_PLU,P.PRO_NAME,p.pro_id,p.kst_id,p.kst_id2,p.spa_id,p.pro_preis1 from mcdata.produkt p "); ps = conn.prepareStatement(query.toString()); rs = ps.executeQuery(); CostosBo costos =new CostosBo(); while(rs.next()){ StringBuffer sql=new StringBuffer(); sql.append("("); sql.append(rs.getString("PRO_PLU")).append(","); sql.append("'").append(rs.getString("PRO_NAME")).append("',"); sql.append(rs.getString("pro_id")).append(","); sql.append(rs.getString("kst_id")).append(","); sql.append(rs.getString("kst_id2")).append(","); sql.append(rs.getString("spa_id")).append(","); sql.append(rs.getString("pro_preis1")); sql.append(")"); costos.insertarProdukt(sql.toString()); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace();} } if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace();} } } } public String getInsertSqlGuiasTransferenciaCosto(String fecha){ PreparedStatement ps=null; ResultSet rs=null; StringBuffer sql=new StringBuffer(); try { Connection conn = ConnectionFactoryMaterial.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT ? FECHA,K.KST_ID,K.KST_NAME,HL.LBW_NAME,hl.lbw_info,SUM(I.WES_MENGE*I.WES_ESP) total_guia "); query.append(" FROM MCDATA.INVWES I "); query.append(" INNER JOIN MCDATA.HIS_LAGERBEW HL ON (I.WES_ID1 = HL.LBW_ID) "); query.append(" INNER JOIN MCDATA.KOSTST K ON (K.KST_ID=HL.KST_ID) "); query.append(" WHERE ((HL.LBW_DATUM >= TO_DATE(?||'00:00:00', 'DD/MM/YYYY HH24:MI:SS')) "); query.append(" AND (HL.LBW_DATUM <= TO_DATE(?||'23:59:59', 'DD/MM/YYYY HH24:MI:SS'))) "); query.append(" AND hl.kst_id1 IN ( "); query.append(" SELECT KST_ID FROM MCDATA.kostst WHERE KST_NAME LIKE 'LOG%' "); query.append(" ) "); query.append(" AND I.WES_TYP=2 "); query.append(" GROUP BY K.KST_ID,K.KST_NAME,HL.LBW_NAME,hl.lbw_info "); query.append(" ORDER BY hl.lbw_info DESC "); ps = conn.prepareStatement(query.toString()); ps.setString(1, fecha); ps.setString(2, fecha); ps.setString(3, fecha); rs = ps.executeQuery(); while(rs.next()){ sql.append("("); sql.append("'").append(rs.getString("FECHA")).append("',"); sql.append(rs.getString("KST_ID")).append(","); sql.append("'").append(rs.getString("KST_NAME")).append("',"); sql.append("'").append(rs.getString("LBW_NAME")).append("',"); sql.append("'").append(rs.getString("lbw_info")).append("',"); sql.append(rs.getString("TOTAL_GUIA")); sql.append("),"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace();} } if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace();} } } if(sql.toString().trim().length()>0) return sql.toString().substring(0, sql.toString().length()-1); else return null; } public String getInsertSqlGuiasTransferenciaGasto(String fecha){ PreparedStatement ps=null; ResultSet rs=null; StringBuffer sql=new StringBuffer(); try { Connection conn = ConnectionFactoryMaterial.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT ? FECHA,K.KST_ID,K.KST_NAME,HL.LBW_NAME,hl.lbw_info,SUM(I.WES_MENGE*I.WES_ESP) total_guia "); query.append(" FROM MCDATA.INVWES I "); query.append(" INNER JOIN MCDATA.HIS_LAGERBEW HL ON (I.WES_ID1 = HL.LBW_ID) "); query.append(" INNER JOIN MCDATA.KOSTST K ON (K.KST_ID=HL.KST_ID) "); query.append(" WHERE ((HL.LBW_DATUM >= TO_DATE(?||'00:00:00', 'DD/MM/YYYY HH24:MI:SS')) "); query.append(" AND (HL.LBW_DATUM <= TO_DATE(?||'23:59:59', 'DD/MM/YYYY HH24:MI:SS'))) "); query.append(" AND hl.kst_id1 IN ( "); query.append(" SELECT KST_ID FROM MCDATA.kostst WHERE KST_NAME LIKE 'CC%' "); query.append(" ) "); query.append(" AND I.WES_TYP=2 "); query.append(" GROUP BY K.KST_ID,K.KST_NAME,HL.LBW_NAME,hl.lbw_info "); ps = conn.prepareStatement(query.toString()); ps.setString(1, fecha); ps.setString(2, fecha); ps.setString(3, fecha); rs = ps.executeQuery(); while(rs.next()){ sql.append("("); sql.append("'").append(rs.getString("FECHA")).append("',"); sql.append(rs.getString("KST_ID")).append(","); sql.append("'").append(rs.getString("KST_NAME")).append("',"); sql.append("'").append(rs.getString("LBW_NAME")).append("',"); sql.append("'").append(rs.getString("lbw_info")).append("',"); sql.append(rs.getString("TOTAL_GUIA")); sql.append("),"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace();} } if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace();} } } if(sql.toString().trim().length()>0) return sql.toString().substring(0, sql.toString().length()-1); else return null; } public String getInsertSqlGuiasMermaGasto(String fecha){ PreparedStatement ps=null; ResultSet rs=null; StringBuffer sql=new StringBuffer(); try { Connection conn = ConnectionFactoryMaterial.getInstance().getConnection(); StringBuilder query = new StringBuilder(); query.append(" SELECT ? FECHA,k.kst_id,k.kst_name,SUM(I.WES_MENGE*I.WES_ESP*-1) monto_total,HV.VBR_INFO,HV.VBR_NAME "); query.append(" FROM MCDATA.INVWES I, "); query.append(" MCDATA.kostst K, "); query.append(" MCDATA.HIS_VERBRAUCH HV "); query.append(" WHERE ( I.WES_TYP IN (30,31) ) "); query.append(" AND ( I.WES_ID1 = HV.VBR_ID ) "); query.append(" AND ( K.KST_ID=I.kst_id) "); query.append(" AND ( (HV.VBR_DATUM >= TO_DATE(?||'00:00:00', 'DD/MM/YYYY HH24:MI:SS')) "); query.append(" AND (HV.VBR_DATUM <= TO_DATE(?||'23:59:59', 'DD/MM/YYYY HH24:MI:SS')) ) "); query.append(" GROUP BY HV.VBR_ID,k.kst_id,k.kst_name,HV.VBR_INFO,HV.VBR_NAME "); query.append(" ORDER BY HV.VBR_NAME "); ps = conn.prepareStatement(query.toString()); ps.setString(1, fecha); ps.setString(2, fecha); ps.setString(3, fecha); rs = ps.executeQuery(); while(rs.next()){ sql.append("("); sql.append("'").append(rs.getString("FECHA")).append("',"); sql.append(rs.getString("KST_ID")).append(","); sql.append("'").append(rs.getString("KST_NAME")).append("',"); sql.append(rs.getString("monto_total")).append(","); sql.append("'").append(rs.getString("VBR_INFO")).append("',"); sql.append("'").append(rs.getString("VBR_NAME")).append("'"); sql.append("),"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace();} } if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace();} } } if(sql.toString().trim().length()>0) return sql.toString().substring(0, sql.toString().length()-1); else return null; } public String getInsertSqlGuiasTransferencia(String fecha){ PreparedStatement ps=null; ResultSet rs=null; StringBuffer sql=new StringBuffer(); try { Connection conn = ConnectionFactoryMaterial.getInstance().getConnection(); StringBuilder query = new StringBuilder(); /*query.append(" SELECT ? FECHA,K.KST_ID,K.KST_NAME,HL.LBW_NAME,K_TO.KST_NAME KST_NAME_TRANSFER_TO,K_TO.KST_ID KST_ID_TO,NVL(hl.lbw_info,'-')lbw_info, SUM(I.WES_MENGE*I.WES_ESP) total_guia,OW.BST_NAME "); query.append(" FROM MCDATA.INVWES I "); query.append(" INNER JOIN MCDATA.HIS_LAGERBEW HL ON (I.WES_ID1 = HL.LBW_ID) "); query.append(" LEFT JOIN MCDATA.BESTELLER OW ON (OW.BST_ID=HL.LBW_OWNER) "); query.append(" INNER JOIN MCDATA.KOSTST K ON (K.KST_ID=HL.KST_ID) "); query.append(" INNER JOIN MCDATA.KOSTST K_TO ON (K_TO.KST_ID=HL.KST_ID1) "); query.append(" WHERE ((HL.LBW_DATUM >= TO_DATE(?||'00:00:00', 'DD/MM/YYYY HH24:MI:SS')) "); query.append(" AND (HL.LBW_DATUM <= TO_DATE(?||'23:59:59', 'DD/MM/YYYY HH24:MI:SS'))) "); query.append(" AND I.WES_TYP=2 "); query.append(" GROUP BY K.KST_ID,K.KST_NAME,K_TO.KST_NAME,K_TO.KST_ID,HL.LBW_NAME,hl.lbw_info,OW.BST_NAME "); query.append(" ORDER BY hl.lbw_info DESC ");*/ query.append(" SELECT ? FECHA,K.KST_ID,K.KST_NAME,HL.LBW_NAME,K_TO.KST_NAME KST_NAME_TRANSFER_TO,K_TO.KST_ID KST_ID_TO,NVL(hl.lbw_info,'-')lbw_info, "); query.append(" (I.WES_MENGE*I.WES_ESP) total_guia "); query.append(" ,OW.BST_NAME "); query.append(" ,ar.art_name "); query.append(" ,SPG.SGR_NAME "); query.append(" FROM MCDATA.INVWES I "); query.append(" INNER JOIN MCDATA.HIS_LAGERBEW HL ON (I.WES_ID1 = HL.LBW_ID) "); query.append(" LEFT JOIN MCDATA.BESTELLER OW ON (OW.BST_ID=HL.LBW_OWNER) "); query.append(" INNER JOIN MCDATA.KOSTST K ON (K.KST_ID=HL.KST_ID) "); query.append(" INNER JOIN MCDATA.KOSTST K_TO ON (K_TO.KST_ID=HL.KST_ID1) "); query.append(" INNER JOIN MCDATA.artikel AR ON (AR.ART_ID=I.ART_ID) "); query.append(" INNER JOIN MCDATA.warengruppe WG ON (wg.wgr_id=ar.wgr_id) "); query.append(" INNER JOIN MCDATA.sparte SP ON (SP.SPA_ID=wg.spa_id) "); query.append(" INNER JOIN MCDATA.spartegr SPG ON (spg.sgr_id=sp.sgr_id) "); query.append(" WHERE ((HL.LBW_DATUM >= TO_DATE(?||'00:00:00', 'DD/MM/YYYY HH24:MI:SS')) "); query.append(" AND (HL.LBW_DATUM <= TO_DATE(?||'23:59:59', 'DD/MM/YYYY HH24:MI:SS'))) "); query.append(" AND I.WES_TYP=2 "); query.append(" ORDER BY hl.lbw_info DESC "); ps = conn.prepareStatement(query.toString()); ps.setString(1, fecha); ps.setString(2, fecha); ps.setString(3, fecha); rs = ps.executeQuery(); while(rs.next()){ sql.append("("); sql.append("'").append(rs.getString("FECHA")).append("',"); sql.append(rs.getString("KST_ID")).append(","); sql.append("'").append(rs.getString("KST_NAME")).append("',"); sql.append("'").append(rs.getString("LBW_NAME")).append("',"); sql.append("'").append(rs.getString("lbw_info")).append("',"); sql.append("'").append(rs.getString("KST_NAME_TRANSFER_TO")).append("',"); sql.append(rs.getString("KST_ID_TO")).append(","); sql.append(rs.getString("TOTAL_GUIA")).append(","); sql.append("'").append(rs.getString("BST_NAME")).append("',"); sql.append("'").append(rs.getString("art_name").replaceAll("'", "")).append("',"); sql.append("'").append(rs.getString("SGR_NAME")).append("'"); sql.append("),"); } } catch (SQLException e) { throw new RuntimeException(e); } finally { if (ps != null) { try {ps.close();} catch (SQLException e) {e.printStackTrace();} } if (rs != null) { try {rs.close();} catch (SQLException e) {e.printStackTrace(); }} } if(sql.toString().trim().length()>0) return sql.toString().substring(0, sql.toString().length()-1); else return null; } }
Opera PMS Oracle HandBook Property Management - Hotel and Hospitality Consulting, Support and Software Development in Opera PMS Oracle, Java Oracle and AWS Amazon Cloud
Specialist with more than 15 years of experience in developing information systems with Java JEE/Oracle-SQL Server/PowerBI on AWS Amazon Cloud for Government, Banking, Retail and Hospitality.
OPERA Property Management Suite (Opera PMS) is a hotel management system for operations, distribution and room allocation based on cloud technologies. Secure, scalable and mobile-enabled, the platform offers the comprehensive capabilities hotels need to deliver great guest experiences, improve operational efficiency and improve employee productivity. Real-time visibility is critical to success in the hospitality industry and OPERA (Oracle Hospitality) is the market leader in hospitality software for independent boutiques, independent hotels, hotel chains and multi-property hotel groups. Opera's property management system can handle everything from front-desk tasks like cancellations, operapmsbi.COM Cloud simplifies and efficiently enables information for mobile devices by making information accessible to everyone, anytime, anywhere, and from any device, with an open architecture, built-in integration services, and an open API to accelerate the innovation. operapmsbi.COM meets the needs of all hotels and redefines the Hotel management experience. We carry out consulting and development of web applications with Java & AWS Amazon Cloud technology for consulting and analyzing information on hotel operations in real time. Our solutions meet all the unique specifications and functionalities required for each of our clients in the hotel industry, providing real-time queries from your smartphone of your PMS information, giving you agility in making decisions about hotel operations.
For more information write to whatsapp: https://wa.link/cdgbzx
PMS solutions History & Forecast Report In today's competitive marketplace, the long-term success of your hotel depends on how well you make informed business decisions at the right time.
To discover trends and opportunities, you need to constantly analyze profit and loss reports, business analysis reports, market analysis reports, and many more.
The History And Forecast report gives you clarity on past occupancy levels along with the future occupancy level you may witness at the Hotel.
You can view Total Occupancy for any date (Occupancy), Arrival Rooms, Departure Rooms, Occupancy Percentage, Room Revenue, RevPAR , ADR, etc.
The following link shows the History And Forecast report in real time with data from Opera PMS Training:
History & Forecast Report from operapmsbi.com
Housekeeping Rooms Adequate communication of the state of the room helps the proper administration and distribution of the hotel rooms. The traditionally conflictive relationship between the reception and housekeeping departments is frequent and totally depends on the quality of communication between both departments, with real-time room status updates and instant communication allowing conflicts to be reduced. and cost management is more efficient. When a guest checks out, housekeeping can check the status of the room via smartphone, eliminating the need to wait or check in the PMS to see if they can prepare the room for the next guest. It is important to understand the information gaps and the solution through real-time hotel management systems that allow useful software integrations. Housekeeping Status Adequate communication of the state of the room helps the proper administration and distribution of the hotel rooms. The traditionally conflictive relationship between the reception and housekeeping departments is frequent and totally depends on the quality of communication between both departments, with real-time room status updates and instant communication allowing conflicts to be reduced. and cost management is more efficient. When a guest checks out, housekeeping can check the status of the room via smartphone, eliminating the need to wait or check in the PMS to see if they can prepare the room for the next guest. It is important to understand the information gaps and the solution through real-time hotel management systems that allow useful software integrations. Request your demo period for 30 days. The cost of each solution is 800.00 USD. (single payment per solution). The solution includes an automatic process that periodically retrieves the necessary data from the PMS and HMS of the Hotel, sends this data to a database in the Amazon AWS cloud, a database whose use is exclusive to the client or owner of the hotel. Hotel, these data are consulted through a web application by the client of the solution.
The solution can be deployed on web servers running Apache Tomcat/Java on SQL Server or Oracle databases on AWS Amazon, Windows Azure or your local servers.
published on April 18, 2022 | published April 18, 2022
Index of contents.
Issuance of receipts Invoices and Tickets from Opera PMS
Closing Process of Day or Audit with Opera PMS
Rate Strategy settings in Opera PMS
Credit Notes through Credit Bill in Opera PMS
Rate Strategy Setup and demo in Opera PMS
Creation of reports with Opera PMS and Oracle Reports Developer.
Opera PMS Data Dictionary - Oracle
Design and creation of Daily Payments report from Opera PMS
Creating ForeCast and History report in Opera PMS
Creation of Trial Balance Details By Transactions Report in Opera PMS
Room Status and Housekeeping Status in Opera PMS, Online web consultation from Smartphone
Ledger Accounts assigned to Transaction Codes in Opera PMS
Change Room Type Room Type in Opera PMS
Oracle SQL queries for sales management in Opera PMS
Event production.
List of blocked rooms
List of reserved rooms
Income by company and market (Market)
Forecast of rooms per day
Forecast by Marked Code Monthly
Reservations per day
Production by sales executive
production per room
Production by sales executive
Production by detailed sales executive.
Production per grouped sales executive
Forecast grouped by reservation date
Production by company and by type of room.
Monthly production by Market and by Executive
Production by executive, room and company.
Forecast by Market Code Detailed Monthly
Activity Search Notes by Executive and Guest
Canceled reservations
Contacts by company
Details of invoices associated with Transaction Codes by Invoice
Oracle SQL Query for Housekeeping in Opera PMS
List of rooms of the property by Occupancy
List of the flats of the property by State
List of rooms of the property by State
List of rooms of the property by Discrepancy
List of rooms of the property by Date / Time of Arrival
Creation of physical Kardex valued at Material Controls Micros Fidelio
Permissions and permission group in Opera PMS
Create reports using Opera Views Simple Report Writer
Sales Report generated from Micros 9700
Home guest list report
Issuance of receipts Invoices and Tickets from Opera PMS In order to issue a Ticket we must verify that the client has the "Tax Type" field as a TICKET in the Client's profile.
enter the “Front Desk” menu option “In House Guests” to list all the clients who are staying at the Hotel.
On the “In House Guest” screen, select the client whose profile you want to verify the Tax Type of and select the “Profile” option button.
The most important customer data is displayed on the “Individual Profile” screen. on this screen select the “More Fields” radio button.
On the “More Fields” screen, make sure the Tax Type field is set to the BOLETA option and select the OK radio button.
Returning to the “Individual Profile” screen select the “Save” radio button to save the changes made, then click the Ok and Close button.
With this we make sure that the client has the Tax Type as BOLETA, which will allow us to generate the proof of payment of type Boleta.
Enter the “Cashiering” menu, “Billing” option to show the clients who are staying for whom it is possible to generate a proof of payment for some concept of stay, consumption or services.
Previously, the Login screen will be displayed to request the cashier's access credentials.
In the “House Guest Search” screen, filter the “Due Outs” records, which are the records of clients pending departure, clients who are staying and consume the services that the Hotel offers, to which a proof of payment must be generated. , in this case a Ticket.
Select the “Due Outs” option and click the “Search” radio button
On the "House Guest Search" screen, select the customer record for which you want to generate the payment slip and then click on the "Select" button, the "Billing" screen will be displayed.
The "Billing" screen shows the data of the client's account. It is important to indicate that on this screen you can have up to 8 Windows, windows that will allow us to classify the client's accounts and generate receipts for each Window.
Let us observe that the Window (02) has an account account of 140.80 USD that has not yet been paid and that the Window (03) has an account of 32.00 USD that is paid through the VISA payment method.
We select the Windows (02) and click on the “Check Out” option button, the “Payment” screen will be displayed.
On the “Payment” screen, select the “Payment Code” option to “Cash Dollars”, the Currency option to USD, in the Amount field indicate the amount 140.80 and in the Reference field indicate a description of the account, then click on the Post option button with this the payment is charged to the system and the account is closed.
In the following PoPup screen, indicate No, to send the voucher to the digital tax document issuer program of your Country (or Electronic Invoicing of the Central Tax Administration)
This process of sending the voucher data to the central tax administration of your country, printing the voucher with the data of the voucher number, QR code.
At the end of the process, a record of -140.80 (negative) is shown in the account window, indicating the closing of the account.
Closing Process of Day or Audit with Opera PMS The closing of the day allows updating the business date (Business Date) to the current operation date, in addition the closing process is very important for the generation of hotel management reports.
Enter the “End of Day” option menu and select the “Night Audit” menu
The “End of Day Login” form will be displayed and we select the “Business Date” that we want to close.
The “End of Day Routine” screen will be displayed, which will validate the completion of the processes that allow the proper closure of the day.
Click the OK button and then click the Start button.
Opera shows you pending Check In arrivals or reservations not yet registered, which must be registered, this also alerts us about the status of pending arrivals.
To continue with the closing of the day, it is important to check in all the arrivals of the date that is closing in order to continue with the process.
After assigning the Room and the Rate, click on the Check In option button.
If the Check In is successful, the registration must leave the list of pending Check In. Continue with this process until you leave the Check In registration pending tray without records.
During the validation of pending Check Out records, the "Guests At Home" screen is displayed, for which the corresponding Check Out must be generated before continuing with the closing process.
Before proceeding with the Check outs it is important to configure the printtasks necessary for printing the CheckOuts.
Log in with the supervisor role, select the Configuration option, on the Configuration screen, select the Workstation menu option.
Select the WorkStatons corresponding to the current workstation, which is usually highlighted in blue.
Click the Print Tasks radio button to display the Print Task screen.
Within this screen click on the New button.
If the Printer Task is not shown on the screen, it must be registered on the Printers screen, select the Printers option menu, the screen will be displayed, and click on New
Create the required print task, then in the WorkStation add the necessary PrintTask.
Opera will start to close the day and complete all pending trades for a proper close.
The closing process also prints the pending reports of the day's operations.
At the end of the closing process on the day, the printing of the final report is requested.
Rate Strategy settings in Opera PMS The rate strategy allows us to control the price restrictions (discounts and surcharges) that we want to apply to room reservations according to the occupancy or availability of the hotel rooms.
For example, if the rooms of a certain category are sold at a discount until they exceed 10% occupancy, once this percentage of occupancy is exceeded, the discount is withdrawn and the remaining 90% is sold without any discount.
We want this restriction to be applied for check-ins from 05/01/2019 to 05/31/2019, we want to control the restrictions during the month of March and April, that is, from 03/01/2019 to 04/30/2019.
In Opera we enter the configuration module.
Then we select the Rate Strategy option
In the Rate Strategy screen we will define the rate strategy according to the established conditions.
Two strategy registers must always be defined: the rate strategy and its counterpart. that is to say, the rates for reservations greater than 10% occupancy and the registration of rate strategies for reservations less than 10% occupancy are defined.
Tariff strategy for a specific price code called CRESP.
For check-ins or arrivals from May 1, 2019 to May 31, 2019
whose sales or reservations are made from March 1 to April 30, we also define its counterpart of the restriction
therefore, in the Rate Strategy screen, there must be 2 registers per rate restriction.
We then tested the defined rate strategy at the time of booking.
Credit Notes through Credit Bill in Opera PMS We will make credit notes through CREDIT BILL, enter the Cashiering menu, Cashier Functions option
The Cashier Functions form will be displayed
Select the Folio History option the Folio History form will be displayed
** Consider that Credit Notes can only be issued through CREDIT BILL to vouchers that have been issued one day in advance, otherwise Opera disables the Credit Bill option button, for example today, March 12, only allows issuing credit notes through Credit Bill of vouchers issued until March 11.
** Another consideration to take into account is that the issuance of credit notes must correspond to the series category of the payment voucher, that is, if the series category is F010, credit notes must be issued with the series F010. if the series category is B011, credit notes must be issued with the series B011 in that correlation. If this correlation does not occur, there is a risk that the central tax administration will reject the credit note issued.
** For this correlation to occur, it is very important that when issuing credit notes, the Tax Type field of the Client Profile must be changed.
For example, for the issuance of credit notes for the INVOICE receipt of the client Liu, Fang
Enter the Reservations Menu, Profiles option, on the Profile Search screen search for and select Client Profile.
Click on the Edit option button to display the Individual Profile form with the customer data,
Select the More Fields radio button to display the Tax Type options
To properly generate the credit note of the INVOICE it is important to change the Tax Type of the Client Profile to INVOICE.
After changing the Tax Type field, we proceed to generate the Credit Bill of the invoice from the Folio History screen.
we will be asked for the cashier's credentials
You must indicate the Marked Code and Source Code values to then click on the Post option button.
We post the credit note for the same value but in negative.
Consider that for the realization of the CREDIT BILL, you must use the same market code and the same source that you used to make the reservation.
Rate Strategy Setup and demo in Opera PMS This guide configures the pricing strategies and demonstrates the application of their restrictions.
1. USER PROFILES
Consider the following permissions for the receiving and booking profiles:
Reception Profile
Permissions for profiles whose users must respect the restrictions of the pricing strategies. This is applicable for cashier or receptionist users.
You must not have the following permissions:
RESERVATIONS \ OVERRIDE RATECODE
BLOCKS \ OVERRIDE BLOCK RATE RESTRICTIONS
You must have the following permissions:
RESERVATION \ RATE CODE CHANGE
Profile Reservations
Permissions for the profiles whose users can authorize the breaking of the restrictions of the pricing strategies. This is applicable for supervisor users, senior cashiers, or senior reservations staff.
You must have the following permissions:
RESERVATION \ OVERRIDE RATECODE
BLOCKS \ OVERRIDE BLOCK RATE RESTRICTIONS
RESERVATION \ RATE CODE CHANGE
2. SYSTEM PARAMETERS
You must enter the following parameters in the “Application Settings” screen with the values “Y“.
Parameter
Worth
RATES \ SET RATE CATEGORY RESTRICTIONS
Y
RATES \ SET RATE CODE RESTRICTIONS
Y
3. DEFINITION OF PRICE STRATEGY
To configure the price strategies, enter the main menu "Configuration" the "Configuration" screen will be displayed, on this screen enter the menu option "Rate Management", option "Rate Strategy", the screen " Rate Strategy”.
Click on the “New” button.
Define the direct pricing strategy (<10% OPEN occupancy)
Also define the inverse pricing strategy (>10% occupancy CLOSED)
The dates in the “Restriction Dates” field correspond to the “Arrival” dates of the reservation to which the pricing strategies are applied.
The dates in the “Control Dates” field correspond to the dates on which the reservation is registered.
4. EMPLOYMENT LEVEL AND FORECAST PROCESSOR
Enter the occupancy level screen using the Shift + F1 key combination and observe that on May 02 there are no rooms reserved.
The adequate execution of the price strategy considers the level of employability to apply or not the price restrictions. This level of occupancy requires that the reserved rooms be deducted (Deduct) from the room inventory.
To activate room inventory deductions it is important that the forecast processor is running.
To activate it enter the main menu “Utilities”, the “Utilities” screen will be displayed. In this screen enter the “Processors” menu “Forecast Processor” submenu, the “Forecast Processor Status” screen will be displayed
´
On the “Forecast Processor Status” screen, the “Running” process should be shown, otherwise click on the “Start” button.
5. RATE CODE CONFIGURATION
We must verify the “Rate Code” configuration, enter the “Rate Management” menu, “Rate Classifications” menu option, “Rate Codes” option. Select the “Rate Code” involved in the “Rate Strategy” and click the “Edit” button.
In the “Rate Header” form, make sure that the “Room Types” field has the ST room type to which we are establishing the price strategy, also verify that the date range “Begin Sell Date” and “End Sell Date” is a range of dates according to the execution dates and control dates of the pricing strategy.
In the "Rate Detail" form, select the record corresponding to the "Room Types" ST considered in the pricing strategy, make sure that the "Start Date" and "End Date" date ranges are in accordance with the execution dates and the control dates defined in the pricing strategies.
We leave the records of the “Negotiated” form blank.
We leave the fields of the “More” form blank.
6. CONFIGURATION OF RESERVATION TYPES
We must verify the types of reservation "Reservation Types" and take into account those types of reservation that Deduct from the physical inventory of rooms, that is, they make a reservation confirmed and cannot be canceled.
This is very important because the Rate Strategy only counts the rooms reserved and deducted from the room inventory to verify the level of occupancy.
In the "Reservation Type" screen we must have at least one record as the type of reservation "Deduct".
7. MAKING RESERVATIONS
After proper verification of the preliminary parameter settings, we enter the “Reservations” option menu, select the “New Reservation” option button
In the “Profile Search” screen, we search for a specific client.
On the “Reservation” screen, the date in the “Arrival” field must be within the execution range of the pricing strategy, select the “Room Type” and the “Rate Code” defined in the pricing strategy.
**important** you must select a reservation type with Deduct in the “Res Type” field.
As long as the restriction rule does not reach the limit of the direct pricing strategy (<10% OPEN occupancy), reservations are made on a daily basis.
Once the reservation was made on the occupancy screen (Shift + F1) on May 2, we observed that there is 01 room reserved and deducted from the inventory (Deduct).
We make reservations with the Cashier profile for the number of rooms necessary to cover 10% of occupancy (limit of the price strategy).
The next booking intent will display the “Rate Query Details” screen with the price in the “Close” state, confirming that the price allocation is restricted by the pricing strategy.
If you wish to proceed with the allocation, the price allocation permission request screen will be displayed. This authorization is provided by a Supervisor user.
8. REPORTS ASSOCIATED WITH THE RATE STRATEGY
If you want to review the behavior of pricing strategies, use the following reports:
Report Name
.rep file
RestrictionsDetail
raterest.rep
Reservation Rate Check
res_rate_check.rep
Reservations made On by Ratecode
paris_reservationsmadeonbyratecode.rep
Creation of reports with Opera PMS and Oracle Reports Developer. To create custom reports in Opera, you must first create the SQL statement that will obtain the report data from the Opera Oracle database, and then design the report in the Oracle Reports Developer tool and at the end assign an option in the list of reports available from Opera.
It is very important to use the appropriate version of Oracle Reports Developer, this tool is usually installed by the Opera PMS provider.
Opera | Oracle Reports Developer
v5.0 | v10.1.2.0.2
v5.5 | v11.1.2.2.0
In this blog we will make a report that lists the relationship of hosted clients.
We make the SQL statement that extracts the data from the Oracle database of Opera.
SQL
SELECT a.room,trim(initcap(a.guest_first_name))||' '||trim(initcap(a.sname)) As Name,
trim(a.company_name)||' '||a.travel_agent_name As Company,
a.resv_status,a.arrival,a.departure
FROM reservation_general_view to
WHERE (a.resv_status='CHECKED IN' OR a.resv_status='DUE OUT')
ORDER BY a.room
We will use the "reservation_general_view" view, this view has the necessary query to extract the data of all the reservations of the clients, in their different states:
CHECKED-IN
PROSPECT
CANCELED
NO SHOW
CHECKED OUT
RESERVED
We execute this query in the Oracle SQL Developer development environment to validate that the query works properly
We run the design program Oracle Reports Developer
The Builder will be displayed
We connect the builder to the database, for this we select the menu “File” menu option “Connect...”,
The database connection wizard will be displayed where you must enter the User, Password and the instance name of the Oracle database. then click the “Connect” radio button to connect to the database.
Select the Menu “File” menu option “New” / “Report…”, the “New Report” wizard will be displayed. select the “Use the Report Wizard” option and click the OK radio button
The “Report Wizard!” will be displayed, click on the “Next >” option button
Keep the “Create both Web and Paper Layout” option selected by default and click the “Next >” button
We place the name of the report "Guests in property report" and click on the "Next >" button.
Select the “SQL Query” option and click on the “Next >” option.
In the Data Source definition screen we place the SQL Query that allows the extraction of data from the reservations and we click on the “Next >” option.
We select all the fields of the Query that will be shown in the report and click on the “Next >” option.
In the totalized fields calculation screen, it is not necessary to totalize for a certain field, we click on the “Next >” option.
On this screen we maintain the width of the labels and click on the “Next >” option
We select a report template and click on the “Next >” option
We click on finish to then preview the report design
The pre-design of the report will be displayed as follows
We compile the report by clicking on the “Compile” menu, menu option “All..”
Click Ok to confirm the build process.
After compiling the report, it is important to export the report file in .rep format, a format that can be used from Opera.
The .rep report files should be placed in the runtimes\ folder located at the following address: D:\MICROS\OPERA\production\runtimes\
We enter the Opera Configuration module.
We select the menu options “Setup”, Menu option “Report Setup” option “Reports”
The “Reports - Configuration” screen will be displayed, click on the “New” button
In the “Reports - New” screen we place the name of the report and select a specific “Report Group”.
We click on the list selections button associated with “File Name”. in the “File List” screen we look for the .rep report file.
We make sure that the custom_report_guespedes.rep report is in the “Reports - Configuration” screen
To display the new report, select the “Miscellaneous” option button, “Reports” option, the “Reports” screen will be displayed
In the “Reports” screen, look for the report “Custom Guest Report” and click on the Ok button
The “Report Parameters” screen will be displayed and click on the “Preview” button
The custom report will be displayed
Opera PMS Data Dictionary - Oracle Having access to the data dictionary of an information system is very important to start the entire development and maintenance process of the information system.
In order to access the Opera data dictionary, you must have access to the Oracle database from Oracle SQL Developer or another development environment for Oracle.
Use the following SQL statement to extract the Opera data dictionary:
For those who could not have access to the Opera Oracle database, I leave the Data Dictionary in Excel format and the description of the fields in English and their translation in Spanish.
Since Opera has more than 4,800 tables, this blog will describe the most important tables and fields for a maintenance and development process.
Opera PMS Data Dictionary – Oracle
Design and creation of Daily Payments report from Opera PMS We will make a report that shows the list of payments made per day, payments from the various forms of payment; cash, cards, etc This type of reports allow us to view and validate the charges made by ATMs per day of transaction.
The report will show the following columns:
- Transaction date - Transaction code - Description of the Transaction Code - Reservation number - Room number - Guest name - Voucher number - Total Billed in Dollars - Currency Code - Cashier User
To make this report, the tables related to financial transactions, customer folio and other associated tables will be used:
FINANCIAL_TRANSACTIONS: This table stores all the transactions related to the cash service, transactions for each reservation (guest book, deposit book, accounts receivable book and package book).
FOLIO_TAX: This table stores a summary of revenue information per invoice.
NAME: This table stores the profile information of guests, companies, travel agencies, sources and groups.
TRX$_CODES: This table stores all the transaction codes of the system, these transactions are the concepts that are selected at the time of POST.
APPLICATION$_USER: This table stores all the information of the user that operates the system.
We validate the SQL statement executing the query in the development environment "Oracle SQL Developer"
We run the “Oracle Reports Builder” report design program and create a new report using the “Report Wizard”.
In the “Report Style” screen we indicate the title of the report and select the “Group Left” format, this format will allow us to create groups in the report.
Confirmation for the creation of the P_BUSDATE report parameter will be presented on the “Data Source Definition” screen of the Report Wizard. This parameter will allow us to select from Opera the date for which we want the payment report to be generated.
We click on the OK button and continue with the default values of the other wizard screens.
In the "Field Grouping" screen we select the fields that will allow us to group the report records and calculate the subtotals of these groups. In our case, we select the TRX_CODE and TRX_DESCRIPTION fields, which will allow us to group and total by payment method.
In the “Select Fields to Display” screen we select all the fields of the Query that will be part of the report.
In the "Calculate Totals" screen, select the fields that will be totaled and the totalization form, in our case we will add the invoiced amount and count the number of receipts.
Sum(INVOICED_USD)
Count(NR_DOCUMENT)
we click on the “Next>” button and continue with the default values of the other wizard screens.
At the end of the wizard, the report will be displayed with the groupings and the totalized fields:
The “Oracle Reports Builder” design tool allows you to change the original design of the report, allowing a much more aesthetic design of the report.
Once the report is compiled, the file must be exported in .rep format “custom_reporte_pagos.rep”, this format will allow the report to be created from the “Reports - New” configuration screen of Opera.
From the “Configuration” screen select the menu option “Setup”, Sub Menu “Report Setup” option Reports.
On the “Reports - Configuration” screen, select the “New” radio button
In the “Reports - New” Screen we indicate the name of the report, in this case “Custom Payment Report”, in the “Report Group” field select the “Utilities” option and leave the other options as shown in the image.
In the “File Name” field we click on the List button, the “File List” Screen will be displayed, on this screen we select the .rep file that we have created from the “Oracle Reports Builder” in previous steps.
We select the report “custom_reporte_pagos.rep” and click on the “OK” button to select this file.
In the “Reports New” screen we select the “Parameter” button, the “Parameters” screen will be displayed to create the “P_BUSDATE” parameter that the payment report requires.
In the “Parameters” screen enter the following data of the parameter P_BUSDATE and click on the “OK” button.
To display the report as a user on the “PMS” screen, click on the “Miscellaneous” option button “Reports” option
In the “Reports” screen, look for the payment report created and click on the “OK” button
The “Report Parameters” screen will be displayed, on this screen indicate a certain date and click on the “Preview” button
The payment report designed in the “Oracle Reports Builder” will be displayed.
Creating ForeCast and History report in Opera PMS Revenue Management is a technique that consists of selling the right product, to the right customer, at the right time and at the right price, it is about predicting consumer behavior with the aim of maximizing revenue and minimizing costs.
Forecasting consists of estimating and analyzing future demand for a product or service using different variables such as historical data.
One of the main variables on which hotel forecasting is based is the analysis of statistical data of the property in previous periods, with this we can predict future income and make the appropriate commercial decisions to correct deviations with the purpose of maximizing income. and minimize costs.
Being clear about the importance of a forecast tool, especially online, in real time and from a smartphone that consults data directly from the Opera PMS, it would be a very useful tool for efficient Property management.
It is important to consider that the online forecast tool must include the following data whose descriptions are kept from the original Opera documentation:
Date. Date to which the statistics apply.
Total Occupancy. Total occupied rooms (non-deduct, deduct, individual and group).
Arrival Rooms. Rooms with guests arriving this date. For arrivals, component rooms count as 1 and not the number of physical rooms making up the component room.
CompRooms. Complementary rooms (rooms attached to reservations having a rate code that is flagged Complimentary).
House Use. House use rooms (rooms attached to reservations having a rate code that is flagged House Use).
Individual Deduction. Individual reservations having a reservation type that is flagged Deduct from inventory.
Non-Deduct Individual. Individual reservations having a reservation type that is not flagged Deduct from inventory.
Deduction Group. Group reservations having a reservation type that is flagged Deduct from inventory.
Non-Deduct Group. Group reservations having a reservation type that is not flagged Deduct from inventory.
Occupancy %. (Total Occupied Rooms / Number of Rooms in Property) x 100).
Room Revenue. Total revenue for this date associated with Lodging transaction codes for deduct, non-deduct, individual, and group reservations.
Average Rate. Total Room Revenue / Number of Occupied rooms.
Departure Rooms. Rooms due out this date. For departures, component rooms count as 1 and not the number of physical rooms making up the component room.
Day Use Rooms. Day Use Rooms for the date.
No Show Rooms. No Show Rooms for the date.
For this purpose, the following SQL Query for Oracle is built, which obtains the forecast with the income of the current month (HISTORY) towards the estimated annual income (FORECAST).
This Query will be the basis to start building the online forecast tool for smartphones.
Creation of Trial Balance Details By Transactions Report in Opera PMS It is important to tell you that just as we did in HouseKeeping to show the status of the rooms from the smartphone, analytical reports can be developed based on the Trial Balance to have the income status online.
This report shows the detail of all the transactions posted to the host and the classification of these transactions.
Because the Balance terms cannot be translated directly into Spanish without distorting their meaning, I will keep the definitions in English on this blog.
The Trial Balance reprt includes all transactions posted, and then a breakdown of business within each of the five Ledgers (Guest Ledger, AR Ledger, Deposit Ledger, Package Ledger, and Inter Hotel Ledger). The Trial Balance may be used to assist in ensuring your property's accounts are balanced and in good standing.
Summary of Other Reports That May Be Used For Balancing
Report Title
.REP File name
Additional Information
Aging Summary by Types
araging
May be run for a specific date.
Detailed Aging Report
aragingdet
May be run for a specific date.
AR Ledger
arledger
Continuously updating
Deposit Activity Report
deposit_activity
May be run for a specific date but should be run by Activity Date if used for balancing.
NA Deposit Ledger
deposit_ledger
Continuously updating.
Financial Payments and Revenue Postings
findeptcodes
May be run for a specific date but should always be run for NET revenue if used for balancing.
Journal by Cashier and Transaction Code
finjrnlbytrans
May be run for a specific date but should always be run for NET revenue if used for balancing.
Financial Transactions with Generate
finjrnlbytrans2
May be run for a specific date but should always be run for NET revenue if used for balancing.
Package Postings
finpkgposting
Captures data for the current business date, must be attached to Night Audit Report Group if used for balancing.
Guest Trial Balance
gl_trial_balance
May be run for a specific date.
manager report
manager_report
May be run for a specific date.
Deposits Transferred at C/I
nadeptransci
Captures data for the current business date, must be run with the Night Audit if used for balancing to trial_balance.
Package Ledger Detail
napkgledger
Captures data for the current business date, must be run with the Night Audit if used for balancing to trial_balance.
TrialBalance
trial_balance
May be run for a specific date.
The Trial Balance Detail has the following structure:
Room. Room number of the reservation.
Guest Name. Name of the guest.
Arrangement Desc. Name of transaction classification.
TrxCode. CodeTransaction
Trx No. Transaction sequential number.
Description. Transaction description.
Old Balance (Opening Balance). Total balance of the guest account for the date in which the report was ran.
Credits. Total Amount that has been paid against the account by the guest.
Debits. Total Amount that has been charged to the guests account.
Transferred Credits. Any amounts that have been transferred to the guests account and that is considered a credit.
Transferred Debits. Any amounts charged to the guest account as a result of a transfer.
New Balance (Closing Balance). Closing balance for the account. This column is calculated by the following formula: Opening Balance + Debits + Transfer Debit - Credits - Transfer Credits.
The SQL query for Oracle:
It is important to tell you that just as we did in HouseKeeping to show the status of the rooms from the smartphone, analytical reports can be developed based on the Trial Balance to have the income status online.
Room Status and Housekeeping Status in Opera PMS, Online web consultation from Smartphone In this blog we show the development of a responsive web system that shows the status of the rooms of a property, this web system is very important for the agile operation of the room supervisors, the supervisors constantly check the status of the rooms online from their cell phones and avoid having to go to a desktop PC to consult the opera report on the status of the rooms.
The states of the rooms to consider are the following:
SELECT ROOM_STATUS_ID,ROOM_STATUS_CODE,ROOM_STATUS_DESC FROM OPERA . ROOM_STATUS_CODES_ALL
ROOM_STATUS_ID
ROOM_STATUS_CODE
ROOM_STATUS_DESC
1
CL
Clean
two
GAVE
Dirty
3
IP
surveyed
4
YOU
out-of-service
5
OO
out of order
SELECT DISTINCT HK_STATUS FROM OPERA . ROOM
OCC : busy
VAC : vacant
SELECT DISTINCT HK_STATUS FROM OPERA . ROOM
OCC : busy
VAC : vacant
Use the following Query to display the current status of the rooms of a given Floor:
The screens of the web system that consults the status of the rooms that are viewed from a smartphone device are shown as follows:
Discrepancies:
Discrepancies can be seen in Opera's “Room Discrepancy” report:
in the PMS module enter the “Miscellaneous” menu, “Reports” submenu, look for the “Room Discrepancy” report and click on “OK”.
The “Report Parameters” screen will be displayed, on this screen select the “Room Status” you wish to view.
In the “Room Status” selections, note the 2 different discrepancy states:
“Skip/Sleep Discrepant”: Discrepancies based on room status.
“Persons Discrepant”: Discrepancies based on number of guests per room.
In this example we select the “ALL Rooms” option, it will show us all the discrepancies of the property.
Note that Skip or Sleep discrepancies appear if the FO Status field is different from the HK Status field.
Discrepancies in room statuses occur for the following reasons:
Sleep.-
FO_STATUS Indicates VAC (front office records guest check out)
HK_STATUS indicates OCC (hk indicates someone is still in the room)
Skip.-
FO_STATUS Indicates OCC (guest leaves the room without officially checking out)
HK_STATUS Indicates VAC (HK indicates that the room is vacant)
To resolve the discrepancies, enter the Rooms Management menu, select the “Housekeeping” item, the Housekeeping screen will be displayed with the options to be carried out. We select the option “Rm. Discrepancies”
In the “Room Discrepancies” screen, you can see the status discrepancy between the “FO Status” (Front Office Status) and “HK Status” (HouseKeeping Status) fields. To resolve the discrepancy, both statuses must match.
Ledger Accounts assigned to Transaction Codes in Opera PMS It is important to know that the "Transaction Codes" that we use during the "Post" in "Billing" are associated with certain accounting accounts that the tax administration of the country of residence requires us.
To show the correspondence or mapping between the “Transaction Codes” and the Accounting Accounts, they are shown in the “BackOffice Interface Transaction Codes Mapping” report. In the “Miscellaneous” Menu enter the option “Reports”
In the “Reports” screen, look for the “BackOffice Interface Transaction Codes Mapping” report and then click OK. The report is previewed with the correspondence between the “Transaction Codes” and the Accounting Accounts.
If you need to assign a certain Accounting Account to a "Transaction Code" enter in Configuration to the "External" menu, submenu "Back Office" option "Configuration"
On the “Back Office Configuration” screen, select the “Transaction codes” option and click OK
The “Transaction Codes” screen will be shown, we will select a certain Code and click on the “Edit” button
The Ledger Account assignment screen will be displayed, assign the appropriate ledger account and click Ok.
Change Room Type Room Type in Opera PMS This Post will show the procedure to change the Room Type of a room in Opera PMS.
We list the rooms of the property with their respective statuses, from this list we filter only the rooms with statuses Empty “VAC” and Inspected “IP”, we can only change the Room Type of rooms that are not reserved and are not occupied.
SELECT r . room,r . room_status,r . suite_type,r . fo_status,r . hk_status,r . description,c . label ,c . short_description
FROM OPERA . ROOM r
INNER JOIN OPERA . ROOM_CATEGORY_TEMPLATE c ON (r . room_category = c . room_category)
WHERE r . fo_status = 'VAC' AND r . room_status = ' IP
In the Configuration module enter the menu option “Reservations” submenu “Room Classifications” item “Rooms”
In the “Room List” form we locate the room to which we want to change the Room Type “Room Type”
On this screen we can verify the status and characteristics of each of the rooms and select the rooms that we want to change the status of.
In “Utilities”, enter “Utilies” menu, “Property Config” submenu, “Change Rooms” submenu item “Change Room Type for a Room Number”
The “Change Room Type” screen is displayed.
On this screen, select the Room Number, to which you want to change the “Room Type”, it is important to consider that the rooms can only be changed if they are in the following states:
FO_STATUS : VAC (Empty)
ROOM_STATUS : IP (Inspected)
We indicate the number of the room and select the new type of room to assign.
If the room is occupied or reserved, the following error message will be displayed, thus avoiding the reassignment of the room type.
We review the room reservation in the Room Plan, to display the Room Plan screen press the Ctrl + F3 key, if we place the mouse pointer over the >> icon you will see a summary.
We await the release of the room reservation.
To continue with the example we locate a room not reserved and not occupied through the Room Plan, in our case room 1018.
We click on the “Yes” button. The change of the Room Type will be made.
Oracle SQL queries for sales management in Opera PMS Event production.
Forecast by Market Code Detailed Monthly
Details of invoices associated with Transaction Codes by Invoice
Oracle SQL Query for Housekeeping in Opera PMS List of rooms of the property by Occupancy
List of rooms of the property by State
List of rooms of the property by Discrepancy
List of rooms of the property by Date / Time of Arrival
Creation of physical Kardex valued at Material Controls Micros Fidelio create or replace PROCEDURE SP_KARDEX_FISICO_VALORADO(
Permissions and permission group in Opera PMS During the review of the functionalities that Opera offers, the permissions granted to users must be considered, permissions that can be so decisive that if the permissions are not assigned to the user's profile, it would give the impression that a certain functionality does not work correctly or does not work at all. as indicated in the opera help, for example users whose profile applies the restrictions defined in "Rate Strategy" during the Check In process and users who can bypass these restrictions.
Use the following SQL statement to extract all the permissions available in the Opera PMS.
SELECT permission_group,permission_display,description
FROM OPERA.APP_PERMISSIONS
ORDER BY permission_group,permission_display
In the following link you can find the list of all permits in Excel format and the description of the permit in English and its translation in Spanish.
User Profile Permissions in Opera PMS - Oracle
Permissions are assigned to user profiles in the “Setup” menu, “User Configuration” submenu, “User Groups” option.
In the “User Groups” screen, select a certain profile and then click the “Permission” button
The “User Group and Permissions for Group” permissions assignment screen will be displayed where you can assign the permissions to the selected profile.
Permissions can be assigned to the selected profile individually for each permission or the group of permissions associated with another profile or group of users can be assigned.
Create reports using Opera Views Simple Report Writer The following video shows the creation of reports from Opera using the OSR (Opera Simple Report) views.
https://www.youtube.com/watch?v=fFnlAHHarys&t=16s
To create these reports it is not necessary to know Oracle Transact-SQL programming, you only need to know the columns of the views associated with the OSR wizard:
view
View in Database
Reservations
RESERVATION_GENERAL_VIEW
profiles
PROFILE_VIEW
Financial Transactions
FINANCIAL_TRANSACTIONS_VIEW
Business Blocks
EXP_SCBUSBLOCK_VIEW
Events
EXP_SCEVENT_VIEW
Activities
ACTIVITY_VIEW
The detail of the columns of the Opera Simple Report (OSR) views is detailed in the following link:
Opera Views Simple Report Writer
Next we will create a customer information report using the Views and the Opera Simple Report Writer wizard.
Enter the Opera settings section.
Go to the Menu option “Setup”, submenu “Report Setup” option “Reports”
In the “Report - Configuration” screen, click on the “New” button to create a new report.
The “Reports - New” screen will be displayed, assign the name “checkouts” and select the Report Group “Arrival”, and then click on the “Customize” button
On the “Opera Simple Reports” screen select views “Reservations” and “Profile”
Click on the “Columns” button. On the column selection screen, select the following columns in the order indicated in the image:
Click on the “Filters” button. In the filter definition screen create the following filters:
Arrival Date = BUSINESS DATE
Or Arrival Date > BUSINESS DATE
Or Departure Date = BUSINESS DATE
Or Departure Date > BUSINESS DATE
To create the "checkouts" report, click on the "OK" button, this report will be found in the report browser.
Sales Report generated from Micros 9700
This Query allows obtaining information on F&B sales (Hotel Food and Beverages) made from Micros 9700, sales that could be billed directly from Micros or sales that were charged to a certain hotel room, room charges are displayed and they are billed from the PMS Opera generally when the client checks out. This Query to obtain sales information can be automated by means of a task to obtain the sales revenue of A&B Online.
The information obtained from this Query can be used to carry out Business Intelligence reports that allow us additional analytics to those presented in Oracle tools such as MyMicros.
This Query allows to obtain the information of all the Checks that are made from the Micros 9700 regardless of whether it generates a proof of payment or a room charge, this information can be used to generate income analysis reports in real time for each Revenue Center defined in the Micros 9700
New Fiscal Tables Added
Internationally, businesses are often required to report fiscal information
over and above that which is currently supported by RES. This is done in a
variety of ways and is specific to each country's requirements.
With this release, MICROS has added four new tables that can be used by an
integrater to store fiscal information directly in the RES database. They are:
RCF_Invoice_Control
FCR_Customer_Data
FCR_Invoice_Data
FCR_TTL_Data
As part of the RES database schema, these tables are automatically included
in the RES installation. This simplifies support while allowing sites to save
and protect the fiscal data mandated by their local government authorities.
In the future this information will be sent to mymicros.net.
change of the RUC document type in micros
update microsdb.FCR_Customer_Data set custinfo6=6 where customerid='20461851887' --and custinfo1='SAC Magnetic and Vibratory Equipment'
Home guest list report This report shows all the guests that are registered in the hotel at this moment. This report shows the room occupied by the guest, the status of the reservation, the date of departure and the important main telephone number to communicate with the client through digital means such as WhatsApp.
We will use the "reservation_general_view" view, this view has the necessary query to extract the data of all the reservations of the clients, in their different states:
We run this query in the Oracle SQL Developer development environment to validate that the query works properly.
It is important to indicate that the guest's phone number must be properly registered in the “ Communications ” section of the guest's “ Profile ”.
We run the design program Oracle Reports Developer
The Builder will be displayed
We connect the builder to the database, for this we select the menu “File” menu option “Connect...”,
The database connection wizard will be displayed where you must enter the User, Password and the instance name of the Oracle database. then click the “Connect” radio button to connect to the database.
Select the Menu “File” menu option “New” / “Report…”, the “New Report” wizard will be displayed. select the “Use the Report Wizard” option and click the OK radio button
The “Report Wizard!” will be displayed, click on the “Next >” option button
Keep the “Create both Web and Paper Layout” option selected by default and click the “Next >” button
We place the name of the report "House guest list report" and click on the "Next >" button.
Select the “SQL Query” option and click on the “Next >” option.
In the Data Source definition screen we place the SQL Query that allows the extraction of data from the reservations and we click on the “Next >” option.
We select all the fields of the Query that will be shown in the report and click on the “Next >” option.
In the totalized fields calculation screen, it is not necessary to totalize for a certain field, we click on the “Next >” option.
On this screen we maintain the width of the labels and click on the “Next >” option
We select a report template and click on the “Next >” option
We click on finish to then preview the report design
The pre-design of the report will be displayed as follows
We compile the report by clicking on the “Compile” menu, menu option “All..”
Click Ok to confirm the build process.
After compiling the report, it is important to export the report file in .rep format, a format that can be used from Opera.
The .rep report files should be placed in the runtimes\ folder located at the following address: D:\MICROS\OPERA\production\runtimes\
We enter the Opera Configuration module.
We select the menu options “Setup”, Menu option “Report Setup” option “Reports”
The “Reports - Configuration” screen will be displayed, click on the “New” button
In the “Reports - New” screen we place the name of the report and select a specific “Report Group”.
We click on the list selections button associated with “File Name”. in the “File List” screen we look for the .rep report file.
We make sure that the custom_report_guespedes.rep report is in the “Reports - Configuration” screen
To display the new report, select the “Miscellaneous” option button, “Reports” option, the “Reports” screen will be displayed
In the “Reports” screen, look for the report “Custom Guest Report” and click on the Ok button
The “Report Parameters” screen will be displayed and click on the “Preview” button
The custom report will be displayed
Download the article in PDF at the following link