Files
z_00_124_ss25_restaurant/webapp/controller/tablePos.controller.js
2025-05-21 15:00:13 +00:00

267 lines
11 KiB
JavaScript

sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/m/MessageBox",
"sap/ui/core/format/DateFormat",
], function (Controller, MessageBox, DateFormat) {
"use strict";
return Controller.extend("restaurant.z00124ss25restaurant.controller.tablePos", {
onInit: function () {
// Initialize your controller logic here
var oDatePicker = this.byId("booked-date");
oDatePicker.setDateValue(new Date());
// Set default time value (e.g., 18:00 for dinner)
var oTimePicker = this.byId("booked-time");
var oDefaultTime = new Date();
oDefaultTime.setHours(18, 0, 0);
oTimePicker.setDateValue(oDefaultTime);
// Set default booking period (120 minutes = 2 hours)
this.byId("booked-period").setValue("120");
},
_padAndEncodeId: function (id) {
id = id.toString(); // Ensure it's a string
if (id.length === 9) {
return id;
}
var padding = 9 - id.length;
return "%20".repeat(padding) + id;
},
handleChange: function (oEvent) {
// Handle date selection change if needed
var oDatePicker = oEvent.getSource();
var oSelectedDate = oDatePicker.getDateValue();
// Additional validation could go here
// For example, prevent past dates
if (oSelectedDate && oSelectedDate < new Date()) {
MessageBox.warning("Please select a future date for your reservation");
oDatePicker.setDateValue(new Date());
}
},
onSaveReservation: function () {
// Get values from the form
var sReservationName = this.byId("res-name").getValue();
var iNumGuests = parseInt(this.byId("num-guests").getValue(), 10);
var oBookedTime = this.byId("booked-time").getDateValue();
var oBookedDate = this.byId("booked-date").getDateValue();
var sBookedPeriod = this.byId("booked-period").getValue();
var sComments = this.byId("comments").getValue();
// Get the selected TableId from the Select control
var oTableSelect = this.byId("table-id");
var oSelectedItem = oTableSelect.getSelectedItem();
var sSelectedTableId = oSelectedItem ? oSelectedItem.getKey().trim() : null;
// Minimal validation for required fields
if (!sReservationName) {
MessageBox.error("Please enter a reservation name");
return;
}
if (!oBookedDate) {
MessageBox.error("Please select a date for your reservation");
return;
}
if (!oBookedTime) {
MessageBox.error("Please select a time for your reservation");
return;
}
if (!sBookedPeriod) {
MessageBox.error("Please enter a booking period");
return;
}
if (!sSelectedTableId) {
MessageBox.error("Please select a table");
return;
}
// Format time for backend (HHMMSS format for ABAP TIMS)
var sFormattedTime = this._formatTimeForABAP(oBookedTime);
// Combine date and time into a single date object
const oCombinedDateTime = new Date(
oBookedDate.getFullYear(),
oBookedDate.getMonth(),
oBookedDate.getDate(),
oBookedTime.getHours(),
oBookedTime.getMinutes(),
oBookedTime.getSeconds()
);
// Format using DateTimeOffset type
const oDateTimeFormat = DateFormat.getDateTimeInstance({
pattern: "yyyy-MM-dd'T'HH:mm:ss",
UTC: true // Use UTC to avoid timezone issues
});
const sFormattedDateTime = oDateTimeFormat.format(oCombinedDateTime);
// Create payload for OData service - matching your table structure
var oPayload = {
NumOfGuests: iNumGuests,
ReservationName: sReservationName,
CommentSection: sComments || "",
BookedDate: sFormattedDateTime,
BookedTime: sFormattedTime,
BookedPeriod: parseInt(sBookedPeriod, 10) || 0
// Created_by and other administrative fields will be handled by the backend
};
// Get the OData model
var oModel = this.getOwnerComponent().getModel();
// Show busy indicator
this.getView().setBusy(true);
// FIX: Correct the endpoint format based on your OData service structure
// Get the full service path from the model
var sServiceUrl = oModel.sServiceUrl;
console.log("Service URL:", sServiceUrl);
// Try different path formats - the correct format depends on your OData service definition
// Option 1: Original path from your code, but with proper formatting
console.log(sSelectedTableId);
var encoded = this._padAndEncodeId(sSelectedTableId);
var endPoint = "/tablePos('" + encoded + "')/to_rese";
oModel.create(endPoint, oPayload, {
success: function (oData, oResponse) {
this.getView().setBusy(false);
MessageBox.success("Reservation created successfully", {
onClose: this._resetForm.bind(this)
});
}.bind(this),
error: function (oError) {
this.getView().setBusy(false);
// Extract error message from backend response
var sErrorMessage = "Error creating reservation";
try {
if (oError.responseText) {
var oErrorResponse = JSON.parse(oError.responseText);
sErrorMessage = oErrorResponse.error.message.value ||
(oErrorResponse.error.innererror &&
oErrorResponse.error.innererror.errordetails &&
oErrorResponse.error.innererror.errordetails.length > 0 ?
oErrorResponse.error.innererror.errordetails[0].message :
sErrorMessage);
}
} catch (e) {
// Use default error message if parsing fails
console.error("Error parsing error response:", e);
}
// Log detailed error information for debugging
console.error("Error status:", oError.statusCode);
console.error("Error message:", sErrorMessage);
console.error("Request URL:", oError.request ? oError.request.requestUri : "unknown");
console.error("Full error object:", oError);
MessageBox.error(sErrorMessage);
// Test with a different endpoint if this fails
if (oError.statusCode === 404) {
console.log("Trying alternative endpoint format...");
this._tryAlternativeEndpoint(oPayload);
}
}.bind(this)
});
},
onCancelPress: function () {
// Ask for confirmation before resetting
MessageBox.confirm("Are you sure you want to cancel? All entered data will be lost.", {
title: "Confirmation",
actions: [MessageBox.Action.YES, MessageBox.Action.NO],
emphasizedAction: MessageBox.Action.YES,
onClose: function (sAction) {
if (sAction === MessageBox.Action.YES) {
this._resetForm();
}
}.bind(this)
});
},
onTableItemChange: function (oEvent) {
var oSelectedItem = oEvent.getParameter("selectedItem");
if (oSelectedItem) {
var sSelectedItemId = oSelectedItem.getKey();
var sSelectedItemText = oSelectedItem.getText();
console.log("Selected Item ID:", sSelectedItemId);
console.log("Selected Item Text:", sSelectedItemText);
// Perform further actions based on the selected item
}
},
_resetForm: function () {
this.byId("res-name").setValue("");
this.byId("num-guests").setValue(1);
this.byId("booked-date").setDateValue(new Date());
// Reset time to default (6:00 PM)
var oDefaultTime = new Date();
oDefaultTime.setHours(18, 0, 0);
this.byId("booked-time").setDateValue(oDefaultTime);
this.byId("booked-period").setValue("120");
this.byId("comments").setValue("");
},
_formatDateForAbapDats: function (oDate) {
var oType = new TypeDateTime();
if (!oDate) return null;
// Use UI5's built-in ISO date formatting
const oDateFormat = DateFormat.getDateInstance({
pattern: "yyyy-MM-dd",
UTC: true // Critical for ABAP compatibility
});
return oDateFormat.format(oDate);
},
_formatTimeForABAP: function (oTime) {
if (!oTime) {
return "PT00H00M00S";
}
var oTimeFormat = sap.ui.core.format.DateFormat.getTimeInstance({ pattern: "HH:mm:ss" });
var oTimeFormatString = "PT" + oTimeFormat.format(oTime);
oTimeFormatString = oTimeFormatString.replace(":", "H");
// Replace the next colon with 'M'
oTimeFormatString = oTimeFormatString.replace(":", "M");
// Add 'S' at the end to mark seconds
oTimeFormatString = oTimeFormatString + "S";
console.log(oTimeFormatString);
return oTimeFormatString;
},
onManagerPress: function () {
console.log("yes you clicked the button of manager");
let man_id = prompt("Please enter manager id:");
if (man_id != "z00124") {
alert("You are not manager or typed it wrong try again");
} else {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("RouteManagerReservation"); // make sure this route is defined in your manifest.json
// visible="{= ${isManager} }" // do it when it is implemented
}
}
});
});