I searched the other instances of people reporting a "getRange" of null error, but none of them solved my issue. I had a form built in Google Sheets, and the code worked perfectly this morning until I made an inadvertent edit, tried to undo the change, but nonetheless I must have done something because the script stopped working.
The script is meant to:
Allow a user to create a record by inputing information using code 1000 on the Form sheet, and to save such information to the Data sheet
Display a record's information from the Data sheet on the Form sheet when the user enters a code greater than 1000 (a record locator ID)
Permit the user to update and save information for the record displayed
Reset the form to blank when either the new record is created, or the existing record has been updated.
It worked perfectly this morning, then kaput. I've been trying to debug unsuccessfully for hours, and here are error messages by function:
submitData
TypeError: Cannot read property 'getRange' of null (line 98, file
"Code")
getMember
Exception: Range not found (line 249, file "Code")
onEdit
TypeError: Cannot read property 'getActiveCell' of null (line 378,
file "Code")
I've been through every line of code, and I am stuck. I humbly request another pair of eyes to help me fix it. Below is the code, and here is a link to a copy of the form and data table I created with a sample row of data. Please ignore the data validation errors since I deleted proprietary information to create this copy, and please let me know if you have any questions. Thank you.
'''
//array for setValue on Data Centre and getValue by column from database
var cellId = ["J3","A"];
var cellPhoto = ["J32","B"];
//Location
var cellStreetAddress = ["D7","C"];
var cellCity = ["D8","D"];
var cellState = ["D9","E"];
var cellZip = ["D10","F"];
var cellCounty = ["D11","G"];
//Program data
var cellfiftyfive = ["H7","H"];
var cellIL = ["H8","I"];
var cellAL = ["H9","J"];
var cellMC = ["H10","K"];
var cellBeds = ["H12","L"];
//Property Summary
var cellPhase = ["K7","M"];
var cellLand = ["K8","N"];
var cellBuildable = ["K9","O"];
var cellPrice = ["K10","P"];
var cellGrade = ["K11","Q"];
var cellSource = ["K12","R"];
var cellClassification = ["K13","S"];
//Description
var cellSiteDescription = ["D16","T"];
var cellProjDescription = ["D21","U"];
//Site Information
var cellSiteVisit = ["L16","V"];
var cellTeamsLink = ["K17","W"];
var cellGoogleMap = ["K18","X"];
//Zoning
var cellZoningClass = ["K21","Y"];
var cellZoningDesc = ["K22","Z"];
var cellEntitlements = ["K23","AA"];
//Construction
var cellParkingType = ["K26","AB"];
var cellConstType = ["K27","AC"];
var cellUnitSizeRange = ["K28","AD"];
var cellTotalSqFt = ["K29","AE"];
//Financial
var cellTotalCost = ["D32","AF"];
var cellTotalCostDoor = ["D33","AG"];
var cellTotalCostSF = ["D34","AH"];
var cellTotalDebt = ["D35","AI"];
var cellTotalEquity = ["D36","AJ"];
var cellFDGEquity = ["D37","AK"];
var cellCapitalStructure = ["D38","AL"];
//EARLY
var cellDateProcessed = ["H42","AM"];
var cellMarketStudyLink = ["H43","AN"];
//Site Photo
var cellPhotoLibrary = ["K43","AO"];
//Stakeholders
var cellCoDev = ["D46","AP"];
var cellFeeDev = ["D47","AQ"];
var cellOperator = ["D48","AR"];
var cellPartner = ["D49","AS"];
var cellArchitect = ["D50","AT"];
var cellEngineer = ["D51","AU"];
var cellContractor = ["D52","AV"];
var cellBroker = ["D53","AW"];
//Schedule
var cellRezoning = ["H46","AX"];
var cellSitePlan = ["H48","AY"];
var cellPlanPermit = ["H49","AZ"];
var cellClosing = ["H50","BA"];
var cellExtensions = ["H51","BB"];
var cellTimeToClose = ["H52","BC"];
var cellEstConstStart = ["H54","BD"];
var cellEstConstLength = ["H55","BE"];
var cellEstConstFinish = ["H56","BF"];
//Additional Notes
var cellNotes = ["J46","BG"];
var cellDropped = ["J55","BH"];
//Date Stamps
var cellInputDate = ["L3","BI"];//var cellInputDate = ["D23","K"];
var cellUpdateDate = ["L4","BJ"];//var cellUpdateDate = ["H23","L"];
function submitData() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var formSS = ss.getSheetByName("Form");
var datasheet = ss.getSheetByName("Data");
var lastrow = datasheet.getLastRow();
var myId = formSS.getRange(cellId[0]).getValue();
var maxId = findMaxId(datasheet.getRange("A2:" + "A" + lastrow).getValues());
var nextId = increaseId(maxId);
var lastRowId = datasheet.getRange(lastrow,1,1,1).getValue();
var nextId = increaseId(lastRowId);
var myId = formSS.getRange(cellId[0]).getValue();
var now = new Date();
//Location
var my_StreetAddress = formSS.getRange(cellStreetAddress[0]).getValue();
var my_City = formSS.getRange(cellCity[0]).getValue();
var my_State = formSS.getRange(cellState[0]).getValue();
var my_Zip = formSS.getRange(cellZip[0]).getValue();
var my_County = formSS.getRange(cellCounty[0]).getValue();
//Program
var my_fiftyfive = formSS.getRange(cellfiftyfive[0]).getValue();
var my_IL = formSS.getRange(cellIL[0]).getValue();
var my_AL = formSS.getRange(cellAL[0]).getValue();
var my_MC = formSS.getRange(cellMC[0]).getValue();
var my_Beds = formSS.getRange(cellBeds[0]).getValue();
//Property Summary
var my_Phase = formSS.getRange(cellPhase[0]).getValue();
var my_Land = formSS.getRange(cellLand[0]).getValue();
var my_Buildable = formSS.getRange(cellBuildable[0]).getValue();
var my_Price = formSS.getRange(cellPrice[0]).getValue();
var my_Grade = formSS.getRange(cellGrade[0]).getValue();
var my_Source = formSS.getRange(cellSource[0]).getValue();
var my_Classification = formSS.getRange(cellClassification[0]).getValue();
//Description
var my_SiteDescription = formSS.getRange(cellSiteDescription[0]).getValue();
var my_ProjDescription = formSS.getRange(cellProjDescription[0]).getValue();
//Site Information
var my_SiteVisit = formSS.getRange(cellSiteVisit[0]).getValue();
var my_TeamsLink = formSS.getRange(cellTeamsLink[0]).getValue();
var my_GoogleMap = formSS.getRange(cellGoogleMap[0]).getValue();
//Zoning
var my_ZoningClass = formSS.getRange(cellZoningClass[0]).getValue();
var my_ZoningDesc = formSS.getRange(cellZoningDesc[0]).getValue();
var my_Entitlements = formSS.getRange(cellEntitlements[0]).getValue();
//Construction
var my_ParkingType = formSS.getRange(cellParkingType[0]).getValue();
var my_ConstType = formSS.getRange(cellConstType[0]).getValue();
var my_UnitSizeRange = formSS.getRange(cellUnitSizeRange[0]).getValue();
var my_TotalSqFt = formSS.getRange(cellTotalSqFt[0]).getValue();
//Financial
var my_TotalCost = formSS.getRange(cellTotalCost[0]).getValue();
var my_TotalCostDoor = formSS.getRange(cellTotalCostDoor[0]).getValue();
var my_TotalCostSF = formSS.getRange(cellTotalCostSF[0]).getValue();
var my_TotalDebt = formSS.getRange(cellTotalDebt[0]).getValue();
var my_TotalEquity = formSS.getRange(cellTotalEquity[0]).getValue();
var my_FDGEquity = formSS.getRange(cellTotalEquity[0]).getValue();
var my_CapitalStructure = formSS.getRange(cellCapitalStructure[0]).getValue();
//EARLY
var my_DateProcessed = formSS.getRange(cellDateProcessed[0]).getValue()
var my_MarketStudyLink = formSS.getRange(cellMarketStudyLink[0]).getValue()
//Site Photo
var my_Photo = formSS.getRange(cellPhoto[0]).getValue();
var my_PhotoLibrary = formSS.getRange(cellPhotoLibrary[0]).getValue();
//Stakeholders
var my_CoDev = formSS.getRange(cellCoDev[0]).getValue();
var my_FeeDev = formSS.getRange(cellFeeDev[0]).getValue();
var my_Operator = formSS.getRange(cellOperator[0]).getValue();
var my_Partner = formSS.getRange(cellPartner[0]).getValue();
var my_Architect = formSS.getRange(cellArchitect[0]).getValue();
var my_Engineer = formSS.getRange(cellEngineer[0]).getValue();
var my_Contractor = formSS.getRange(cellContractor[0]).getValue();
var my_Broker = formSS.getRange(cellBroker[0]).getValue();
//Schedule
var my_Rezoning = formSS.getRange(cellRezoning[0]).getValue();
var my_SitePlan = formSS.getRange(cellSitePlan[0]).getValue();
var my_PlanPermit = formSS.getRange(cellPlanPermit[0]).getValue();
var my_Closing = formSS.getRange(cellClosing[0]).getValue();
var my_Extensions = formSS.getRange(cellExtensions[0]).getValue();
var my_TimeToClose = formSS.getRange(cellTimeToClose[0]).getValue();
var my_EstConstStart = formSS.getRange(cellEstConstStart[0]).getValue();
var my_EstConstLength = formSS.getRange(cellEstConstLength[0]).getValue();
var my_EstConstFinish = formSS.getRange(cellEstConstFinish[0]).getValue();
//Additional Notes
var my_Notes = formSS.getRange(cellNotes[0]).getValue();
var my_Dropped = formSS.getRange(cellDropped[0]).getValue();
if (myId == 1000) { //input mode
var values = [
nextId,'',my_StreetAddress,my_City,my_State,my_Zip,my_County,my_fiftyfive,my_IL,my_AL,my_MC,my_Beds,my_Phase,my_Land,my_Buildable,my_Price,my_Grade,
my_Source,my_Classification,my_SiteDescription,my_ProjDescription,my_SiteVisit,my_TeamsLink,my_GoogleMap,my_ZoningClass,my_ZoningDesc,my_Entitlements,
my_ParkingType,my_ConstType,my_UnitSizeRange,my_TotalSqFt,my_TotalCost,my_TotalCostDoor,my_TotalCostSF,my_TotalDebt,my_TotalEquity,my_FDGEquity,my_CapitalStructure,
my_DateProcessed,my_MarketStudyLink,my_PhotoLibrary,my_CoDev,my_FeeDev,my_Operator,my_Partner,my_Architect,my_Engineer,
my_Contractor,my_Broker,my_Rezoning,my_SitePlan,my_PlanPermit,my_Closing,my_Extensions,my_TimeToClose,
my_EstConstStart,my_EstConstLength,my_EstConstFinish,my_Notes,my_Dropped,now
];
datasheet.getRange(datasheet.getLastRow()+1, 1, 1, 61).setValues(values);
clear_screen();
} else { //update mode
var rowIndex = findInRow(myId);
var rangesToSetValues = [cellStreetAddress[1], cellCity[1], cellState[1], cellZip[1], cellCounty[1], cellfiftyfive[1], cellIL[1],
cellAL[1], cellMC[1], cellBeds[1], cellPhase[1], cellLand[1], cellBuildable[1],
cellPrice[1], cellGrade[1], cellSource[1], cellClassification[1], cellSiteDescription[1], cellProjDescription[1],
cellSiteVisit[1], cellTeamsLink[1], cellGoogleMap[1], cellZoningClass[1], cellZoningDesc[1], cellEntitlements[1],
cellParkingType[1], cellConstType[1], cellUnitSizeRange[1], cellTotalSqFt[1],cellTotalCost[1], cellTotalCostDoor[1], cellTotalCostSF[1],
cellTotalDebt[1], cellTotalEquity[1], cellFDGEquity[1], cellCapitalStructure[1], cellDateProcessed[1], cellMarketStudyLink[1], cellPhotoLibrary[1],
cellCoDev[1], cellFeeDev[1], cellOperator[1], cellPartner[1], cellArchitect[1], cellEngineer[1],
cellContractor[1], cellBroker[1], cellRezoning[1], cellSitePlan[1], cellPlanPermit[1], cellClosing[1],
cellExtensions[1], cellTimeToClose[1], cellEstConstStart[1], cellEstConstLength[1], cellEstConstFinish[1], cellNotes[1],cellDropped[1]];
var values = [
my_StreetAddress,my_City,my_State,my_Zip,my_County,my_fiftyfive,my_IL,my_AL,my_MC,my_Beds,my_Phase,my_Land,my_Buildable,my_Price,my_Grade,
my_Source,my_Classification,my_SiteDescription,my_ProjDescription,my_SiteVisit,my_TeamsLink,my_GoogleMap,my_ZoningClass,my_ZoningDesc,my_Entitlements,
my_ParkingType,my_ConstType,my_UnitSizeRange,my_TotalSqFt,my_TotalCost,my_TotalCostDoor,my_TotalCostSF,my_TotalDebt,my_TotalEquity,my_FDGEquity,my_CapitalStructure,
my_DateProcessed,my_MarketStudyLink,my_PhotoLibrary,my_CoDev,my_FeeDev,my_Operator,my_Partner,my_Architect,my_Engineer,
my_Contractor,my_Broker,my_Rezoning,my_SitePlan,my_PlanPermit,my_Closing,my_Extensions,my_TimeToClose,my_EstConstStart,my_EstConstLength,
my_EstConstFinish,my_Notes,my_Dropped
];
for (var i=0; i<rangesToSetValues.length; i++) {
datasheet.getRange(rangesToSetValues[i]+rowIndex).setValue(values[i]);
}
//set lastupdateDate value
datasheet.getRange(cellUpdateDate[1]+rowIndex).setValue(now);
getMember(myId);
}
}
function getMember(id) {
var sheetData = SpreadsheetApp.getActive().getSheetByName('Form');
var rangesToSetValues = [cellStreetAddress[0], cellCity[0], cellState[0], cellZip[0], cellCounty[0], cellfiftyfive[0], cellIL[0],
cellAL[0], cellMC[0], cellBeds[0], cellPhase[0], cellLand[0], cellBuildable[0],
cellPrice[0], cellGrade[0], cellSource[0], cellClassification[0], cellSiteDescription[0], cellProjDescription[0],
cellSiteVisit[0], cellTeamsLink[0], cellGoogleMap[0], cellZoningClass[0], cellZoningDesc[0], cellEntitlements[0],
cellParkingType[0], cellConstType[0], cellUnitSizeRange[0], cellTotalSqFt[0], cellTotalCost[0], cellTotalCostDoor[0], cellTotalCostSF[0],
cellTotalDebt[0], cellTotalEquity[0], cellFDGEquity[0], cellCapitalStructure[0], cellDateProcessed[0], cellMarketStudyLink[0], cellPhotoLibrary[0],
cellCoDev[0], cellFeeDev[0], cellOperator[0], cellPartner[0], cellArchitect[0], cellEngineer[0],
cellContractor[0], cellBroker[0], cellRezoning[0], cellSitePlan[0], cellPlanPermit[0], cellClosing[0],
cellExtensions[0], cellTimeToClose[0], cellEstConstStart[0], cellEstConstLength[0], cellEstConstFinish[0], cellNotes[0], cellDropped[0],
cellInputDate[0], cellUpdateDate[0]];
var rowIndex = findInRow(id);
var sheetDatabase = SpreadsheetApp.getActive().getSheetByName('Data');
var values = [
//Location
sheetDatabase.getRange(cellStreetAddress[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellCity[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellState[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellZip[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellCounty[1]+rowIndex).getValue(),
//Program data
sheetDatabase.getRange(cellfiftyfive[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellIL[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellAL[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellMC[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellBeds[1]+rowIndex).getValue(),
//Property Summary
sheetDatabase.getRange(cellPhase[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellLand[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellBuildable[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellPrice[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellGrade[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellSource[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellClassification[1]+rowIndex).getValue(),
//Description
sheetDatabase.getRange(cellSiteDescription[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellProjDescription[1]+rowIndex).getValue(),
//Site Information
sheetDatabase.getRange(cellSiteVisit[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellTeamsLink[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellGoogleMap[1]+rowIndex).getValue(),
//Zoning
sheetDatabase.getRange(cellZoningClass[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellZoningDesc[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellEntitlements[1]+rowIndex).getValue(),
//Construction
sheetDatabase.getRange(cellParkingType[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellConstType[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellUnitSizeRange[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellTotalSqFt[1]+rowIndex).getValue(),
//Financial
sheetDatabase.getRange(cellTotalCost[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellTotalCostDoor[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellTotalCostSF[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellTotalDebt[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellTotalEquity[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellFDGEquity[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellCapitalStructure[1]+rowIndex).getValue(),
//EARLY
sheetDatabase.getRange(cellDateProcessed[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellMarketStudyLink[1]+rowIndex).getValue(),
//Site Photo
//sheetDatabase.getRange(cellPhoto[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellPhotoLibrary[1]+rowIndex).getValue(),
//Stakeholders
sheetDatabase.getRange(cellCoDev[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellFeeDev[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellOperator[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellPartner[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellArchitect[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellEngineer[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellContractor[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellBroker[1]+rowIndex).getValue(),
//Schedule
sheetDatabase.getRange(cellRezoning[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellSitePlan[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellPlanPermit[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellClosing[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellExtensions[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellTimeToClose[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellEstConstStart[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellEstConstLength[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellEstConstFinish[1]+rowIndex).getValue(),
//Additional Notes
sheetDatabase.getRange(cellNotes[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellDropped[1]+rowIndex).getValue(),
//Data Stamps
sheetDatabase.getRange(cellInputDate[1]+rowIndex).getValue(),
sheetDatabase.getRange(cellUpdateDate[1]+rowIndex).getValue()
];
for (var i=0; i<rangesToSetValues.length; i++) {
sheetData.getRange(rangesToSetValues[i]).setValue(values[i]);
}
}
function findInRow(id) {
var sheetDatabase = SpreadsheetApp.getActive().getSheetByName('Data');
var rows = sheetDatabase.getRange("A2:A").getValues();
for (var r=0; r<rows.length; r++) {
if ( rows[r][0] === id ) {
return r+2;
}
}
return -1;
}
function increaseId(id) {
if(id>0) {
var returnId;
returnId = id + 1;
return returnId;
}
}
function findMaxId(myvalues){
return Math.max.apply(null, myvalues);
}
function onOpen(e) {
//initialization
/*var sheet = SpreadsheetApp.getActive().getSheetByName('Form'); //var sheet = SpreadsheetApp.getActive().getSheetByName('Reception');
sheet.getRange(cellId[0]).setValue(1000);
clear_screen();*/
}
function onEdit(e) {
//e.source.setActiveSelection(e.range.offset(2, 0));
var sheet = SpreadsheetApp.getActive().getSheetByName('Form');
var rangeRowId = sheet.getActiveCell().getRow();
var rangeColId = sheet.getActiveCell().getColumn();
//Browser.msgBox("Row Id: " + rangeRowId + " Column Id: " + rangeColId );
if(rangeRowId == 3 && rangeColId == 10) {
var myId = sheet.getRange(cellId[0]).getValue();
lookUpId(myId);
}
}
function clear_screen() {
var sheet = SpreadsheetApp.getActive().getSheetByName('Form');
var rangesToClear = [cellStreetAddress[0], cellCity[0], cellState[0], cellZip[0], cellCounty[0], cellfiftyfive[0], cellIL[0],
cellAL[0], cellMC[0], cellBeds[0], cellPhase[0], cellLand[0], cellBuildable[0],
cellPrice[0], cellGrade[0], cellSource[0], cellClassification[0], cellSiteDescription[0], cellProjDescription[0],
cellSiteVisit[0], cellTeamsLink[0], cellGoogleMap[0], cellZoningClass[0], cellZoningDesc[0], cellEntitlements[0],
cellParkingType[0], cellConstType[0], cellUnitSizeRange[0], cellTotalSqFt[0], cellTotalCost[0], cellTotalCostDoor[0], cellTotalCostSF[0],
cellTotalDebt[0], cellTotalEquity[0], cellFDGEquity[0], cellCapitalStructure[0], cellDateProcessed[0], cellMarketStudyLink[0], cellPhotoLibrary[0], cellCoDev[0],
cellFeeDev[0], cellOperator[0], cellPartner[0], cellArchitect[0], cellEngineer[0], cellContractor[0], cellBroker[0], cellRezoning[0],
cellSitePlan[0], cellPlanPermit[0], cellClosing[0], cellExtensions[0], cellTimeToClose[0], cellEstConstStart[0], cellEstConstLength[0],
cellEstConstFinish[0], cellNotes[0], cellDropped[0], cellInputDate[0], cellUpdateDate[0]];
for (var i=0; i<rangesToClear.length; i++) {
sheet.getRange(rangesToClear[i]).clearContent();
}
var myCellStreetAddress = sheet.getRange(cellStreetAddress[0]);
myCellStreetAddress.activateAsCurrentCell();
}
function lookUpId(id) {
if (id==1000) { //Data Centre mode
clear_screen();
}
if (id>1000) { //lookup mode
getMember(id);
}
}
'''
I am getting the following error in my controller:
angular.module('bcpBackOffice').controller('assetsCtrl', ['$scope', '$state', '$log', '$filter', '$compile', 'ApplicationConfig', '$mdDialog', 'RoomManagerFactory',
The error is showing for the variable authDetails.access_token in my controller.
Here is my controller
'use strict';
/**
* #ngdoc function
* #name bcpBackOffice.controller:assetsCtrl
* #description
* # assetsCtrl
* Controller of the bcpBackOffice
*/
angular.module('bcpBackOffice').controller('assetsCtrl', ['$scope', '$state', '$log', '$filter', '$compile', 'ApplicationConfig', '$mdDialog', 'RoomManagerFactory',
'RoomService', 'DataService', 'RoomServicesVO', 'RoomPricingVO','BcpBase64ImageDataEncodedMultipartFileVO','ImagePath','RoomVO','ImageFileExtensionPattern', assetsCtrl]);
function assetsCtrl($scope, $state, $log, $filter, $compile, ApplicationConfig, $mdDialog, RoomManagerFactory, RoomService, DataService,
RoomServicesVO, RoomPricingVO, BcpBase64ImageDataEncodedMultipartFileVO, ImagePath, RoomVO, ImageFileExtensionPattern) {
// Variable definition
var authDetails = ApplicationConfig.loggedInUserData.authDetails;
var accessToken = authDetails.access_token;
$scope.selectedTabIndex = 0;
$scope.masterData = "";
$scope.roomAttributes = [];
$scope.roomServiceRateUnits = [];
$scope.roomServices = [];
$scope.dayHours = null;
$scope.propertyId = ApplicationConfig.loggedInUserData.propertyId;
$scope.rooms = [];
$scope.populateMasterAttributeData = [];
$scope.attributeValue = [];
$scope.assetServices = new RoomServicesVO();
$scope.editAssetServicesFlag = false;
$scope.editAssetServicesIndex = '';
$scope.imageRoomPicturesPath = ImagePath.RoomImagePicturePath;
$scope.imageFloorPlanPath = ImagePath.RoomImageFloorPlanPath;
$scope.validateUploadedFile = validateUploadedFile;
$scope.assetsFromDateContainer = {};
$scope.weekdaySlot = [];
var weekdayPricingVO = new RoomPricingVO();
weekdayPricingVO.slotType = 'WEEKDAY';
$scope.weekdaySlot.push(weekdayPricingVO);
$scope.weekendSlot = [];
var weekendPricingVO = new RoomPricingVO();
weekendPricingVO.slotType = 'WEEKEND';
$scope.weekendSlot.push(weekendPricingVO);
// Function definition
$scope.increaseCounter = increaseCounter;
$scope.decreaseCounter = decreaseCounter;
$scope.loadDataForAssets = loadDataForAssets;
$scope.addWeekdaySlot = addWeekdaySlot;
$scope.addWeekendSlot = addWeekendSlot;
$scope.deleteWeekdaySlot = deleteWeekdaySlot;
$scope.deleteWeekendSlot = deleteWeekendSlot;
$scope.addInclusiveServices = addInclusiveServices;
$scope.closePopup = closePopup;
$scope.saveInclusiveServices = saveInclusiveServices;
$scope.getAssetsMasterData = getAssetsMasterData;
$scope.switchToAssetsServiceTab = switchToAssetsServiceTab;
$scope.saveRoomData = saveRoomData;
$scope.getDayHours = getDayHours;
$scope.addAdditionalServicesToRoom = addAdditionalServicesToRoom;
$scope.populateAttributeData = populateAttributeData;
$scope.getAllAssetsOfProperty = getAllAssetsOfProperty;
$scope.setWorkingHoursToTime = setWorkingHoursToTime;
$scope.disabledToDate = disabledToDate;
$scope.validatePricingSlot = validatePricingSlot;
$scope.editAssetService = editAssetService;
$scope.deleteAssetService = deleteAssetService;
$scope.reloadAssetServiceVO = reloadAssetServiceVO;
$scope.uploadFloorPlan = uploadFloorPlan;
$scope.uploadRoomImage = uploadRoomImage;
$scope.imagesDataParser = imagesDataParser;
/**
* RoomVO Object Contains Data.
*/
$scope.roomVO = RoomManagerFactory.retrieveInstance();
$scope.roomServicesVO = new RoomServicesVO();
$scope.roomPricingVO = new RoomPricingVO();
/**
* Save Room Data.(create new Asset.)
*/
function saveRoomData() {
$scope.roomVO.availableFromDate = $filter('date')(new Date($scope.assetsFromDateContainer.availableFromDate), "yyyy-MM-dd HH:mm:ss");
$log.debug($scope.roomVO);
if (typeof $scope.roomVO.roomType == "string" || $scope.roomVO.roomType instanceof String) {
$scope.roomVO.roomType = JSON.parse($scope.roomVO.roomType);
}
addWeekdayAndWeekendSlotToAsset();
RoomService.createRoomOfProperty($scope.roomVO, $scope.propertyId, accessToken).then(function (response) {
$scope.rooms.push(response.data);
$scope.roomVO = new RoomVO();
$state.go('template.' + ApplicationConfig.urlBasedOnUserRole + '.assets.show-assets');
},function(error){
$log.error(error);
});
}
/**
* Add Additional Services to Room.
*/
function addAdditionalServicesToRoom() {
$scope.roomServicesVO = $scope.assetServices;
if($scope.editAssetServicesFlag == true){
$scope.roomVO.editRoomServices($scope.editAssetServicesIndex,$scope.roomServicesVO);
}
else {
$scope.roomVO.addRoomServices($scope.roomServicesVO);
}
$scope.editAssetServicesFlag = false;
$scope.assetServices = new RoomServicesVO();
return true;
}
function getDayHours() {
DataService.getDayHoursFromJson().then(function (response) {
$scope.dayHours = response.data;
});
}
function setWorkingHoursToTime(fromTime) {
angular.forEach($scope.dayHours, function (dayHour, index) {
if (fromTime == dayHour.value) {
$scope.totimeIndex = index;
}
});
}
function reloadAssetServiceVO(){
$scope.editAssetServicesFlag = false;
$scope.assetServices = new RoomServicesVO();
}
function editAssetService(index){
$scope.editAssetServicesFlag = true;
$scope.editAssetServicesIndex = index;
$scope.roomServicesVO = $scope.roomVO.roomServices[index];
angular.copy($scope.roomServicesVO, $scope.assetServices);
}
function deleteAssetService(index){
$scope.roomVO.roomServices.splice(index,1);
}
function disabledToDate(fromTime, index, dayType) {
var selectOptions;
if (dayType == 'weekday') {
selectOptions = document.getElementsByClassName('toTimeSelectWeekday_' + index)[0].options;
}
if (dayType == 'weekend') {
selectOptions = document.getElementsByClassName('toTimeSelectWeekend_' + index)[0].options;
}
if (selectOptions.length > 0) {
angular.forEach(selectOptions, function (selectOption) {
selectOption.removeAttribute('disabled');
var value = $filter('date')(selectOption.value, 'HH:mm:ss');
var fromTimeFilter = $filter('date')(fromTime, 'HH:mm:ss');
console.log(value-fromTimeFilter);
if (value <= fromTimeFilter) {
selectOption.setAttribute('disabled', true);
}
});
}
}
/**
* get master data while adding new assets
*/
function getAssetsMasterData() {
switchToAssetsServiceTab(0);
var masterDataPromise = RoomService.getMasterDataOfRoom(accessToken);
masterDataPromise.then(function (promise) {
$scope.masterData = promise.data;
//$scope.roomAttributes = $scope.masterData.roomAttributes;
angular.copy($scope.masterData.roomAttributes, $scope.roomAttributes);
angular.copy($scope.masterData.roomServiceRateUnits, $scope.roomServiceRateUnits);
angular.copy($scope.masterData.roomServices, $scope.roomServices);
$scope.attributeValue = [];
populateAttributeData();
$log.debug($scope.masterData.roomAttributes);
$state.go('template.' + ApplicationConfig.urlBasedOnUserRole + '.assets.add-asset');
});
}
function getAllAssetsOfProperty() {
RoomService.getAllRoomsOfProperty(accessToken, $scope.propertyId).then(function (response) {
$scope.rooms = response.data;
});
}
function populateAttributeData() {
$scope.populateMasterAttributeData = [];
angular.forEach($scope.roomAttributes, function (attributeObject) {
if (typeof attributeObject.value == "string" || attributeObject.value instanceof String) {
var parsedAttributeValue = JSON.parse(attributeObject.value);
} else {
var parsedAttributeValue = attributeObject.value;
}
angular.forEach(parsedAttributeValue, function (attribute) {
var tempAttributeObject = {};
tempAttributeObject.id = attributeObject.id;
tempAttributeObject.label = attribute;
tempAttributeObject.checked = false;
$scope.populateMasterAttributeData.push(tempAttributeObject);
});
}, $scope.populateMasterAttributeData);
}
/**
* load the data after loading the page for Assets Page
*/
function loadDataForAssets() {
$scope.assetsFromDateContainer.availableFromDate = $filter('date')(new Date(), "yyyy-MM-dd HH:mm:ss");
$scope.roomVO.guestCapacity = 1;
$scope.roomVO.minimumBookingHours = 1;
}
/**
* Increase counter value on click on item/element
* #param value
*/
function increaseCounter(value) {
var countEle = document.getElementById(value);
countEle.value = +countEle.value + 1;
if (value == "countFld") {
$scope.roomVO.guestCapacity = countEle.value;
} else {
if (value == "countFld2") {
$scope.roomVO.minimumBookingHours = countEle.value;
}
}
}
/**
* Decrease counter value on click on item/element
* #param value
*/
function decreaseCounter(value) {
var countEle = document.getElementById(value);
if (countEle.value > 1) {
countEle.value = countEle.value - 1;
if (value == "countFld") {
$scope.roomVO.guestCapacity = countEle.value;
} else {
if (value == "countFld2") {
$scope.roomVO.minimumBookingHours = countEle.value;
}
}
}
else {
}
}
/**
* add time slot for weekday
*/
function addWeekdaySlot() {
var roomPricingVO = new RoomPricingVO();
roomPricingVO.slotType = 'WEEKDAY';
$scope.weekdaySlot.push(roomPricingVO);
var currentIndex = ($scope.weekdaySlot.length - 1);
var weekdaytbl = document.getElementById("weekdaySlotsTbl");
var lasti = weekdaytbl.rows.length;
var row = weekdaytbl.insertRow(lasti);
var cell1 = row.insertCell(0);
cell1.setAttribute("style", "width:80px;");
var cell2 = row.insertCell(1);
cell2.setAttribute("style", "width:80px;");
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
$log.debug($scope.weekdaySlot.length - 1);
var formTimeModel = "weekdaySlot[" + currentIndex + "].fromTime";
var toTimeModel = "weekdaySlot[" + currentIndex + "].toTime";
var rateModel = "weekdaySlot[" + currentIndex + "].rate";
cell1.innerHTML = document.getElementById("weekdays_fromTime").innerHTML;
cell1.getElementsByTagName("select")[0].setAttribute("ng-model", formTimeModel);
var disabledToDateFunction = 'disabledToDate(weekdaySlot[' + currentIndex + '].fromTime,' + currentIndex + ',\'weekday\')';
cell1.getElementsByTagName("select")[0].setAttribute("ng-change", disabledToDateFunction);
cell2.innerHTML = document.getElementById("weekdays_toTime").innerHTML;
cell2.getElementsByTagName("select")[0].setAttribute("ng-model", toTimeModel);
cell2.getElementsByTagName("select")[0].setAttribute("class", cell2.getElementsByTagName("select")[0].getAttribute("class") + ' toTimeSelectWeekday_' + currentIndex);
cell3.innerHTML = document.getElementById("weekdays_price").innerHTML;
cell3.getElementsByTagName("input")[0].setAttribute("ng-model", rateModel);
var deleteFunction = 'deleteWeekdaySlot($event,' + currentIndex + ')';
cell4.innerHTML = "<img src='assets/images/icons/close_icon.png'>";
disabledToDate($scope.weekdaySlot[currentIndex].fromTime, currentIndex,'weekday');
$compile($(row).contents())($scope);
}
/**
* add time slot for weekend
*/
function addWeekendSlot() {
var roomPricingVO = new RoomPricingVO();
roomPricingVO.slotType = 'WEEKEND';
$scope.weekendSlot.push(roomPricingVO);
var currentIndex = ($scope.weekendSlot.length - 1);
var weekdaytbl = document.getElementById("weekendSlotsTbl");
var lasti = weekdaytbl.rows.length;
var row = weekdaytbl.insertRow(lasti);
var cell1 = row.insertCell(0);
cell1.setAttribute("style", "width:80px;");
var cell2 = row.insertCell(1);
cell2.setAttribute("style", "width:80px;");
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var formTimeModel = "weekendSlot[" + currentIndex + "].fromTime";
var toTimeModel = "weekendSlot[" + currentIndex + "].toTime";
var rateModel = "weekendSlot[" + currentIndex + "].rate";
cell1.innerHTML = document.getElementById("weekdays_fromTime").innerHTML;
cell1.getElementsByTagName("select")[0].setAttribute("ng-model", formTimeModel);
var disabledToDateFunction = 'disabledToDate(weekendSlot[' + currentIndex + '].fromTime,' + currentIndex + ',\'weekend\')';
cell1.getElementsByTagName("select")[0].setAttribute("ng-change", disabledToDateFunction);
cell2.innerHTML = document.getElementById("weekdays_toTime").innerHTML;
cell2.getElementsByTagName("select")[0].setAttribute("ng-model", toTimeModel);
cell2.getElementsByTagName("select")[0].setAttribute("class", cell2.getElementsByTagName("select")[0].getAttribute("class") + ' toTimeSelectWeekend_' + currentIndex);
cell3.innerHTML = document.getElementById("weekdays_price").innerHTML;
cell3.getElementsByTagName("input")[0].setAttribute("ng-model", rateModel);
var deleteFunction = 'deleteWeekendSlot($event,' + currentIndex + ')';
cell4.innerHTML = "<img src='assets/images/icons/close_icon.png'>";
disabledToDate($scope.weekendSlot[currentIndex].fromTime, currentIndex, 'weekend');
$compile($(row).contents())($scope);
}
function addWeekdayAndWeekendSlotToAsset() {
var mergedWeekdayWeekendPricing = [];
mergedWeekdayWeekendPricing = $scope.weekdaySlot.concat($scope.weekendSlot);
$scope.roomVO.roomPricings = mergedWeekdayWeekendPricing;
}
/**
* delete weekday slots
* #param $event
*/
function deleteWeekdaySlot($event, currentIndex) {
var index = $event.currentTarget.parentNode.parentNode.rowIndex;
document.getElementById("weekdaySlotsTbl").deleteRow(index);
delete($scope.weekdaySlot[currentIndex]);
}
/**
* delete weekend slots
* #param $event
*/
function deleteWeekendSlot($event, currentIndex) {
var index = $event.currentTarget.parentNode.parentNode.rowIndex;
document.getElementById("weekendSlotsTbl").deleteRow(index);
delete($scope.weekendSlot[currentIndex]);
}
/**
* add Inclusive Services for Assets popup
*/
function addInclusiveServices() {
$mdDialog.show({
templateUrl: 'app/templates/views/' + ApplicationConfig.urlBasedOnUserRole + '/fragments/add-inclusive-assets-services.html',
scope: $scope,
preserveScope: true,
overlay: true,
clickOutsideToClose: false,
parent:angular.element('#addInclusiveServices')
});
}
/**
* Save added inclusive services for Assets
*/
function saveInclusiveServices() {
addAttributeToAsset();
$mdDialog.hide();
}
function addAttributeToAsset() {
$scope.attributeValue = [];
$scope.roomVO.roomAttributes = $scope.masterData.roomAttributes;
$log.debug($scope.populateMasterAttributeData);
if (typeof $scope.roomVO.roomAttributes == "string" || $scope.roomVO.roomAttributes instanceof String) {
$scope.roomVO.roomAttributes = JSON.parse($scope.roomVO.roomAttributes);
}
if ($scope.roomVO.roomAttributes.length != 0) {
angular.forEach($scope.roomVO.roomAttributes, function (roomAttribute) {
var filteredSelectedAttr = $filter('filter')($scope.populateMasterAttributeData, function (populateMasterAttributeData) {
return ((roomAttribute.id == populateMasterAttributeData.id)&&(populateMasterAttributeData.checked == true));
});
var tempAttributeValueArray = [];
angular.forEach(filteredSelectedAttr, function (filteredAttributeLabel) {
tempAttributeValueArray.push(filteredAttributeLabel.label);
$scope.attributeValue.push(filteredAttributeLabel.label);
});
roomAttribute.value = tempAttributeValueArray;
});
}
$scope.roomVO.roomAttributes = JSON.stringify($scope.roomVO.roomAttributes);
}
/**
* close the popup window
*/
function closePopup() {
$mdDialog.hide();
}
/**
* after adding new asset switch to next tab
* to add assets service
* #param index
*/
function switchToAssetsServiceTab(index) {
$scope.selectedTabIndex = index;
}
function validatePricingSlot(){
createDummyTimeSlots();
//var sortByStartTime = $filter('orderBy')($scope.weekdaySlot, expression, comparator);
return false;
}
function createDummyTimeSlots(){
var listOfHours = $filter('getValueArrayOfKey')($scope.dayHours)('value');
var operableHours = $filter('filter')(listOfHours, function(hour){
return (hour >= $scope.roomVO.operableHoursStartTime && hour <= $scope.roomVO.operableHoursEndTime);
});
var sortedByFromTimeAndToTime = $filter('orderBy')($scope.weekdaySlot, ['fromTime', 'toTime']);
angular.forEach(sortedByFromTimeAndToTime, function(sortedObject){
angular.forEach(operableHours, function(hour, index){
if(hour >= sortedObject.fromTime && hour <= sortedObject.toTime){
operableHours.splice(index, 1);
}
});
});
console.log("+++++++++++++++++operableHours++++++++++++++++++++");
console.log(operableHours);
}
function uploadFloorPlan(files) {
if(validateUploadedFile()) {
var roomFloorPlanVO = new BcpBase64ImageDataEncodedMultipartFileVO().getRoomFloorPlanVO();
roomFloorPlanVO.originalFileName = files[0].name;
roomFloorPlanVO.size = files[0].size;
roomFloorPlanVO.contentType = files[0].type;
if (files && files[0]) {
setImageBase64ToBase64VO(roomFloorPlanVO, files[0]);
}
$scope.roomVO.floorPlanImageData = roomFloorPlanVO;
$log.debug($scope.roomVO);
}
}
function uploadRoomImage(files) {
if (validateUploadedFile()) {
console.log(files);
angular.forEach(files, function (file) {
var roomImageVO = new BcpBase64ImageDataEncodedMultipartFileVO().getRoomImageVO();
roomImageVO.originalFileName = file.name;
roomImageVO.size = file.size;
roomImageVO.contentType = file.type;
if (files && files[0]) {
setImageBase64ToBase64VO(roomImageVO, file);
}
$scope.roomVO.addRoomImageData(roomImageVO);
});
$log.debug($scope.roomVO);
}
}
function setImageBase64ToBase64VO(roomFloorPlanAndImageDataVO, file) {
var FR = new FileReader();
FR.onload = function (e) {
roomFloorPlanAndImageDataVO.base64EncodedImageData = e.target.result;
};
FR.readAsDataURL(file);
}
function imagesDataParser(roomImages, index){
if (typeof roomImages == "string" || roomImages instanceof String) {
$scope.rooms[index].images = JSON.parse(roomImages);
}
}
function validateUploadedFile() {
var allowedFiles = [".jpg", ".jpeg", ".gif", ".png"];
var fileUpload = document.getElementById("myfile");
var myPicture = document.getElementById("myPicture");
var lblError = document.getElementById("lblError");
var errorMyPicture = document.getElementById("errorMyPicture");
if (fileUpload.files.length > 0) {
if (!(ImageFileExtensionPattern).test(fileUpload.value.toLowerCase())) {
lblError.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
return false;
}
}
if (myPicture.files.length > 0) {
var flag = false;
for(var readFile = 0; readFile < myPicture.files.length;readFile ++) {
if (!(ImageFileExtensionPattern).test(myPicture.files[readFile].name.toLowerCase())) {
errorMyPicture.innerHTML = "Please upload files having extensions: <b>" + allowedFiles.join(', ') + "</b> only.";
flag = true;
break;
}
}
if(flag){return false;}
if (myPicture.files.length > 5) {
errorMyPicture.innerHTML = "Oops!! You can upload max 5 files";
return false;
}
}
lblError.innerHTML = "";
errorMyPicture.innerHTML = "";
return true;
}
// called function on load
$scope.getDayHours();
$scope.getAllAssetsOfProperty();
}
**Here is my test case :**
'use strict';
describe('Controller: assetsCtrl', function () {
beforeEach(module('bcpBackOffice'));
beforeEach(module('BcpUIServices'));
beforeEach(module('ui.router'));
var assetsCtrl,
state,
log,
filter,
compile,
ApplicationConfig,
mdDialog,
RoomManagerFactory,
RoomService,
DataService,
RoomServicesVO,
RoomPricingVO,
$rootScope,
scope,
$httpBackend;
//Mock Data
var mockDayHours= [{
"label": "06:00 AM",
"value": "06:00:00"
},
{
"label": "07:00 AM",
"value": "07:00:00"
}];
beforeEach(inject(function(_$rootScope_, $controller, _$state_, _$log_, _$filter_, _$compile_, _ApplicationConfig_, _$mdDialog_, _RoomManagerFactory_, _RoomService_, _DataService_,
_RoomServicesVO_, _RoomPricingVO_, _$httpBackend_){
$rootScope = _$rootScope_;
scope = $rootScope.$new();
state = _$state_;
log = _$log_;
filter = _$filter_;
compile = _$compile_;
ApplicationConfig = _ApplicationConfig_;
mdDialog = _$mdDialog_;
RoomManagerFactory = _RoomManagerFactory_;
RoomService = _RoomService_;
DataService = _DataService_;
RoomServicesVO = _RoomServicesVO_;
RoomPricingVO = _RoomPricingVO_;
$httpBackend = _$httpBackend_;
assetsCtrl = $controller('assetsCtrl', {
$scope:scope,
$state:state,
$log:log,
$filter:filter,
$compile:compile,
ApplicationConfig:ApplicationConfig,
$mdDialog:mdDialog,
RoomManagerFactory:RoomManagerFactory,
RoomService:RoomService,
DataService:DataService,
RoomServicesVO:RoomServicesVO,
RoomPricingVO:RoomPricingVO
});
}));
beforeEach(function(){
ApplicationConfig.loggedInUserData.authDetails = {
access_token: "0e45e276-89ff-403f-8e02-7f85a41c2d26",
token_type: "bearer",
refresh_token: "ce872f46-5877-4266-9a0e-5199b63ac247",
expires_in: 10430,
scope: "read write"
};
$httpBackend.whenGET("app/mock_data/dayHours.json").respond(mockDayHours);
});
beforeEach(function(){
$rootScope.$digest();
});
it('should get day hours', function(){
scope.getDayHours();
$httpBackend.flush();
expect(scope.dayHours).toBe(mockDayHours);
});