Best JavaScript code snippet using sinon
assetutils.js
Source:assetutils.js
1import {2 db,3 assetRef,4 racksRef,5 modelsRef,6 usersRef,7 firebase,8 datacentersRef,9 changeplansRef,10 bladeRef,11 offlinestorageRef12} from './firebaseutils'13import * as rackutils from './rackutils'14import * as modelutils from './modelutils'15import * as userutils from './userutils'16import * as assetIDutils from './assetidutils'17import * as datacenterutils from './datacenterutils'18import * as assetnetworkportutils from './assetnetworkportutils'19import * as assetpowerportutils from './assetpowerportutils'20import * as logutils from './logutils'21import * as bladeutils from './bladeutils'22import * as changeplanutils from './changeplanutils'23import * as changeplanconflictutils from '../utils/changeplanconflictutils'24import * as offlinestorageutils from './offlinestorageutils'25const algoliasearch = require('algoliasearch')26const client = algoliasearch('V7ZYWMPYPA', '26434b9e666e0b36c5d3da7a530cbdf3')27const index = client.initIndex('assets')28function getAsset(callback, field = null, direction = null, selected = null, storageSite = null) {29 console.log(storageSite)30 let query = storageSite ? ((field && direction !== null) ? (direction ? offlinestorageRef.doc(storageSite).collection("offlineAssets").limit(25).orderBy(field) : offlinestorageRef.doc(storageSite).collection("offlineAssets").limit(25).orderBy(field, "desc")) : offlinestorageRef.doc(storageSite).collection("offlineAssets").limit(25)) : ((field && direction !== null) ? (direction ? assetRef.limit(25).orderBy(field) : assetRef.limit(25).orderBy(field, "desc")) : assetRef.limit(25));31 let assets = [];32 let count = 0;33 console.log(query)34 query.get().then(docSnaps => {35 if (docSnaps.empty) {36 callback(null, [], true);37 } else {38 console.log(docSnaps)39 const startAfter = docSnaps.docs[docSnaps.docs.length - 1];40 bladeutils.getBladeIds(idToVendor => {41 docSnaps.docs.forEach(doc => {42 assets.push({43 asset_id: doc.id,44 ...doc.data(),45 checked: selected && selected.includes(doc.id),46 bladeInfo: idToVendor[doc.id] ? idToVendor[doc.id] : null,47 //add here to get variance data48 displayColor: doc.data().variances.displayColor,49 cpu: doc.data().variances.cpu,50 memory: doc.data().variances.memory,51 storage: doc.data().variances.storage52 });53 count++;54 if (count === docSnaps.docs.length) {55 callback(startAfter, assets, false);56 }57 })58 })59 }60 }).catch(function (error) {61 console.log(error);62 callback(null, null, null)63 })64}65function getAssetAt(start, callback, field = null, direction = null, selected = null, selectAll = null, storageSite = null) {66 let query;67 let ref = storageSite ? offlinestorageRef.doc(storageSite).collection("offlineAssets") : assetRef68 if (field && direction !== null) {69 query = direction ? ref.limit(25).orderBy(field).startAfter(start) : ref.limit(25).orderBy(field, "desc").startAfter(start);70 } else {71 query = ref.limit(25).startAfter(start);72 }73 let assets = [];74 let count = 0;75 query.get().then(docSnaps => {76 const newStart = docSnaps.docs[docSnaps.docs.length - 1];77 bladeutils.getBladeIds(idToVendor => {78 docSnaps.docs.forEach(doc => {79 assets.push({80 asset_id: doc.id,81 ...doc.data(),82 checked: selectAll || (selected && selected.includes(doc.id)),83 bladeInfo: idToVendor[doc.id] ? idToVendor[doc.id] : null,84 displayColor: doc.data().variances.displayColor,85 cpu: doc.data().variances.cpu,86 memory: doc.data().variances.memory,87 storage: doc.data().variances.storage88 });89 count++;90 if (count === docSnaps.docs.length) {91 callback(newStart, assets);92 }93 })94 })95 }).catch(function (error) {96 callback(null, null);97 })98}99function getAllAssetIDs(callback, field = null, direction = null, storageSite = null) {100 let query101 let ref = storageSite ? offlinestorageRef.doc(storageSite).collection("offlineAssets") : assetRef102 if (field && direction !== null) {103 query = direction ? ref.orderBy(field) : ref.orderBy(field, "desc")104 } else {105 query = ref106 }107 let assetIDs = []108 let count = 0109 query.get().then(docSnaps => {110 if (docSnaps.empty) {111 callback([])112 } else {113 docSnaps.docs.forEach(doc => {114 assetIDs.push(doc.id)115 count++;116 if (count === docSnaps.docs.length) {117 callback(assetIDs)118 }119 })120 }121 }).catch(function (error) {122 console.log(error);123 callback([])124 })125}126function validateAssetVariances(displayColor, cpu, memory, storage, callback) {127 if (memory.trim() !== '' &&128 (isNaN(memory.trim()) || !Number.isInteger(parseFloat(memory.trim())) || parseInt(memory.trim()) < 0 || parseInt(memory.trim()) > 1000)) {129 callback('Memory should be a non-negative integer less than 1000')130 }131 // else if (memory.trim() !== '') {132 // memory = parseInt(memory)133 // }134 else {135 if (storage.trim() !== '' && storage.trim().length > 50) {136 callback('Storage should be less than 50 characters long')137 } else {138 if (cpu.trim() !== '' && cpu.trim().length > 50) {139 callback("CPU should be less than 50 characters long")140 } else {141 callback(null)142 }143 }144 }145}146function addAsset(overrideAssetID, model, hostname, rack, racku, owner, comment, datacenter, macAddresses, networkConnectionsArray, powerConnections, displayColor, memory, storage, cpu, callback, changePlanID = null, changeDocID = null, chassis = null, noLog = false, offlineStorageName = null) {147console.log(rack, racku)148 let splitRackArray = rack.split(/(\d+)/).filter(Boolean)149 let rackRow = splitRackArray[0]150 let rackNum = parseInt(splitRackArray[1])151 console.log(offlineStorageName)152 validateAssetForm(null, model, hostname, rack, racku, owner, datacenter, offlineStorageName).then(153 _ => {154 validateAssetVariances(displayColor, cpu, memory, storage, errorMsg => {155 if (errorMsg) {156 callback(errorMsg)157 } else {158 //everything else....goes in here159 // }160 // })161 datacenterutils.getDataFromName(datacenter, (datacenterID, datacenterAbbrev) => {162 modelutils.getModelByModelname(model, doc => {163 if (!doc) {164 var errMessage = "Model does not exist"165 callback(errMessage)166 } else {167 if (userutils.isLoggedInUserAdmin() || userutils.doesLoggedInUserHaveAssetPerm(datacenterAbbrev) || userutils.doesLoggedInUserHaveAssetPerm(null)) {168 assetFitsOnRack(rack, racku, model, datacenter, (errorMessage, modelNum, modelVendor, rackID) => {169 console.log(errorMessage)170 console.log(modelNum)171 console.log(modelVendor)172 console.log(rackID)173 if (errorMessage) {174 callback(errorMessage)175 }176 //Go one level deeper of validation177 else {178 //if field assetID has been left empty, then call generate179 //otherwise, use override method and throw correct errors180 //TODO: refactor this. Seems inefficient/error prone to have the .set duplicated181 // let assetID = overrideAssetID.trim()==="" ? generateAssetID() : overrideAssetID()182 assetnetworkportutils.validateNetworkConnections(model, networkConnectionsArray, ncStatus => {183 console.log(ncStatus)184 assetnetworkportutils.networkConnectionsToMap(networkConnectionsArray, result => {185 let networkConnections = result;186 console.log(networkConnections);187 //let powerConnections = assetpowerportutils.formatPowerConnections(powerConnectionsInput)188 console.log(powerConnections)189 if (ncStatus) {190 callback(ncStatus)191 } else {192 console.log("big booty bitch")193 assetpowerportutils.validatePowerConnections(datacenter, rack, racku, powerConnections, model, ppStatus => {194 console.log("big booty bitch back")195 if (ppStatus) {196 console.log("breakpoint")197 callback(ppStatus)198 } else {199 console.log("HERE and power connections validated")200 if (overrideAssetID.trim() != "") {201 assetIDutils.overrideAssetID(overrideAssetID).then(202 _ => {203 let assetObject = {204 assetId: overrideAssetID,205 modelId: doc.id,206 model: model,207 hostname: hostname,208 owner: owner,209 comment: comment,210 macAddresses,211 networkConnections,212 powerConnections,213 datacenter: offlineStorageName ? offlineStorageName : datacenter,214 //This is for rack usage reports215 modelNumber: offlineStorageName ? doc.data().modelNumber : modelNum,216 vendor: offlineStorageName ? doc.data().vendor : modelVendor,217 //This is for sorting218 //this is for asset variances219 variances: {220 displayColor: displayColor,221 memory: memory,222 cpu: cpu,223 storage: storage224 }225 }226 if(!offlineStorageName){227 assetObject = {228 ...assetObject,229 rack: rack,230 rackU: racku,231 rackRow: rackRow,232 rackNum: rackNum,233 rackID: rackID,234 datacenterID: datacenterID,235 datacenterAbbrev: datacenterAbbrev236 }237 }238 if (!changePlanID) {239 let suffixes_list = []240 let _model = assetObject.model241 while (_model.length > 1) {242 _model = _model.substr(1)243 suffixes_list.push(_model)244 }245 let _hostname = assetObject.hostname246 while (_hostname.length > 1) {247 _hostname = _hostname.substr(1)248 suffixes_list.push(_hostname)249 }250 if(!offlineStorageName){251 let _datacenter = assetObject.datacenter252 while (_datacenter.length > 1) {253 _datacenter = _datacenter.substr(1)254 suffixes_list.push(_datacenter)255 }256 let _datacenterAbbrev = assetObject.datacenterAbbrev257 while (_datacenterAbbrev.length > 1) {258 _datacenterAbbrev = _datacenterAbbrev.substr(1)259 suffixes_list.push(_datacenterAbbrev)260 }261 }262 let _owner = assetObject.owner263 while (_owner.length > 1) {264 _owner = _owner.substr(1)265 suffixes_list.push(_owner)266 }267 if(!offlineStorageName){268 index.saveObject({269 ...assetObject,270 objectID: overrideAssetID,271 suffixes: suffixes_list.join(' ')272 })273 }274 if(!offlineStorageName){275 assetRef.doc(overrideAssetID).set(assetObject).then(function (docRef) {276 assetnetworkportutils.symmetricNetworkConnectionsAdd(networkConnectionsArray, overrideAssetID);277 if (powerConnections.length != 0) {278 racksRef.doc(String(rackID)).get().then(doc => {279 racksRef.doc(String(rackID)).update({280 assets: chassis ? doc.data().assets : firebase.firestore.FieldValue.arrayUnion(overrideAssetID),281 powerPorts: chassis ? doc.data().powerPorts : firebase.firestore.FieldValue.arrayUnion(...powerConnections.map(obj => ({282 ...obj,283 assetID: overrideAssetID284 })))285 }).then(function () {286 console.log("Document successfully updated in racks");287 if (!noLog) {288 logutils.addLog(overrideAssetID, logutils.ASSET(), logutils.CREATE())289 }290 callback(null, overrideAssetID);291 })292 })293 } else {294 racksRef.doc(String(rackID)).get().then(doc => {295 racksRef.doc(String(rackID)).update({296 assets: chassis ? doc.data().assets : firebase.firestore.FieldValue.arrayUnion(overrideAssetID)297 }).then(function () {298 console.log("Document successfully updated in racks");299 if (!noLog) {300 logutils.addLog(overrideAssetID, logutils.ASSET(), logutils.CREATE())301 }302 callback(null, overrideAssetID);303 })304 })305 }306 }).catch(function (error) {307 // callback("Error");308 console.log(error)309 })310 } else {311 console.log(assetObject)312 offlinestorageRef.where("name", "==", offlineStorageName).get().then(function (offlineQuerySnap) {313 if(offlineQuerySnap.empty){314 callback("Couldn't find the offline storage site.");315 } else {316 offlinestorageRef.doc(offlineQuerySnap.docs[0].id).collection("offlineAssets").doc(overrideAssetID).set(assetObject).then(function () {317 let offlineIndex = client.initIndex(offlineQuerySnap.docs[0].data().abbreviation + "_index");318 offlineIndex.saveObject({319 ...assetObject,320 objectID: overrideAssetID,321 suffixes: suffixes_list.join(' ')322 })323 logutils.addLog(overrideAssetID, logutils.OFFLINE(), logutils.CREATE(),{datacenterAbbrev: offlineQuerySnap.docs[0].data().abbreviation})324 callback(null,overrideAssetID)325 }).catch(function (error) {326 console.log(error);327 callback("Couldn't add to the offline storage site.");328 })329 }330 }).catch(function (error) {331 console.log(error);332 callback("Couldn't find the offline storage site.");333 })334 }335 } else {336 assetObject.networkConnections = networkConnectionsArray;337 if(chassis){338 assetObject = {339 ...assetObject,340 chassisHostname: chassis.hostname,341 chassisSlot: chassis.slot342 };343 }344 changeplanutils.addAssetChange(assetObject, overrideAssetID, changePlanID, (result) => {345 if (result) {346 callback(null)347 } else {348 callback("Error adding asset to the specified change plan.")349 }350 }, changeDocID)351 }352 }).catch(errMessage => {353 callback(errMessage)354 })355 } else {356 assetIDutils.generateAssetID().then(newID => {357 console.log("generated the new asset id", newID)358 let assetObject = {359 assetId: newID,360 modelId: doc.id,361 model: model,362 hostname: hostname,363 owner: owner,364 comment: comment,365 macAddresses,366 networkConnections,367 powerConnections,368 datacenter: offlineStorageName ? offlineStorageName : datacenter,369 // This is for rack usage reports370 modelNumber: offlineStorageName ? doc.data().modelNumber : modelNum,371 vendor: offlineStorageName ? doc.data().vendor : modelVendor,372 //This is for sorting373 //this is for assetvariances374 variances: {375 displayColor: displayColor,376 memory: memory,377 cpu: cpu,378 storage: storage379 }380 }381 if(!offlineStorageName){382 assetObject = {383 ...assetObject,384 rack: rack,385 rackU: racku,386 rackRow: rackRow,387 rackNum: rackNum,388 rackID: rackID,389 datacenterID: datacenterID,390 datacenterAbbrev: datacenterAbbrev391 }392 }393 if (!changePlanID) {394 let suffixes_list = []395 let _model = assetObject.model396 while (_model.length > 1) {397 _model = _model.substr(1)398 suffixes_list.push(_model)399 }400 let _hostname = assetObject.hostname401 while (_hostname.length > 1) {402 _hostname = _hostname.substr(1)403 suffixes_list.push(_hostname)404 }405 if(!offlineStorageName){406 let _datacenter = assetObject.datacenter407 while (_datacenter.length > 1) {408 _datacenter = _datacenter.substr(1)409 suffixes_list.push(_datacenter)410 }411 let _datacenterAbbrev = assetObject.datacenterAbbrev412 while (_datacenterAbbrev.length > 1) {413 _datacenterAbbrev = _datacenterAbbrev.substr(1)414 suffixes_list.push(_datacenterAbbrev)415 }416 }417 let _owner = assetObject.owner418 while (_owner.length > 1) {419 _owner = _owner.substr(1)420 suffixes_list.push(_owner)421 }422 if(!offlineStorageName){423 index.saveObject({424 ...assetObject,425 objectID: newID,426 suffixes: suffixes_list.join(' ')427 })428 }429 console.log(offlineStorageName)430 if(offlineStorageName){431 console.log(assetObject)432 offlinestorageRef.where("name", "==", offlineStorageName).get().then(function (offlineQuerySnap) {433 if(offlineQuerySnap.empty){434 callback("Couldn't find the offline storage site.");435 } else {436 console.log(offlineStorageName)437 console.log(offlineQuerySnap.docs[0].id)438 offlinestorageRef.doc(offlineQuerySnap.docs[0].id).collection("offlineAssets").doc(newID).set(assetObject).then(function () {439 let offlineIndex = client.initIndex(offlineQuerySnap.docs[0].data().abbreviation + "_index");440 offlineIndex.saveObject({441 ...assetObject,442 objectID: overrideAssetID,443 suffixes: suffixes_list.join(' ')444 })445 logutils.addLog(newID, logutils.OFFLINE(), logutils.CREATE(),{datacenterAbbrev: offlineQuerySnap.docs[0].data().abbreviation})446 callback(null,newID)447 }).catch(function () {448 callback("Couldn't add to the offline storage site.");449 })450 }451 }).catch(function (error) {452 console.log(error);453 callback("Couldn't find the offline storage site.");454 })455 } else {456 assetRef.doc(newID)457 .set(assetObject).then(function (docRef) {458 console.log("set the itme")459 assetnetworkportutils.symmetricNetworkConnectionsAdd(networkConnectionsArray, newID);460 if (powerConnections.length != 0) {461 racksRef.doc(String(rackID)).get().then(doc => {462 racksRef.doc(String(rackID)).update({463 assets: chassis ? doc.data().assets : firebase.firestore.FieldValue.arrayUnion(newID),464 powerPorts: chassis ? doc.data().powerPorts : firebase.firestore.FieldValue.arrayUnion(...powerConnections.map(obj => ({465 ...obj,466 assetID: newID467 })))468 }).then(function () {469 console.log("Document successfully updated in racks");470 if (!noLog) {471 logutils.addLog(newID, logutils.ASSET(), logutils.CREATE())472 }473 callback(null, newID);474 })475 })476 } else {477 racksRef.doc(String(rackID)).get().then(doc => {478 racksRef.doc(String(rackID)).update({479 assets: chassis ? doc.data().assets : firebase.firestore.FieldValue.arrayUnion(newID)480 }).then(function () {481 console.log("Document successfully updated in racks");482 if (!noLog) {483 logutils.addLog(newID, logutils.ASSET(), logutils.CREATE())484 }485 callback(null, newID);486 })487 })488 }489 }).catch(function (error) {490 // callback("Error");491 console.log(error)492 })493 }494 } else {495 delete assetObject["assetId"];496 //duplicate this!!497 assetObject.networkConnections = networkConnectionsArray;498 if(chassis){499 assetObject = {500 ...assetObject,501 chassisHostname: chassis.hostname,502 chassisSlot: chassis.slot503 };504 }505 changeplanutils.addAssetChange(assetObject, "", changePlanID, (result) => {506 if (result) {507 callback(null)508 } else {509 callback("Error adding asset to the specified change plan.")510 }511 }, changeDocID)512 }513 }).catch("Ran out of tries to generate unique ID")514 }515 }516 }, null, offlineStorageName)517 }518 }, offlineStorageName)519 }, null, offlineStorageName, chassis)520 }521 }, null, offlineStorageName, chassis)522 } else {523 callback("You do not have permissions for this datacenter");524 }525 //checkInstanceFits in rackutils will check against self if instance id is passed in526 }527 })528 }, offlineStorageName)529 }530 })531 }).catch(errMessage => {532 callback(errMessage)533 console.log(errMessage)534 })535}536// rackAsc should be a boolean corresponding to true if rack is ascending537// rackUAsc should be a boolean corresponding to true if rackU is ascending538function sortAssetsByRackAndRackU(rackAsc, rackUAsc, callback, selected = null, offlineStorage = null) {539 var vendorArray = []540 var query;541 let ref = offlineStorage ? offlinestorageRef.doc(offlineStorage).collection("offlineAssets") : assetRef;542 if (!rackAsc && !rackUAsc) {543 query = ref.orderBy("rackRow", "desc").orderBy("rackNum", "desc").orderBy("rackU", "desc")544 } else if (rackAsc && !rackUAsc) {545 query = ref.orderBy("rackRow").orderBy("rackNum").orderBy("rackU", "desc")546 } else if (!rackAsc && rackUAsc) {547 query = ref.orderBy("rackRow", "desc").orderBy("rackNum", "desc").orderBy("rackU")548 } else {549 query = ref.orderBy("rackRow").orderBy("rackNum").orderBy("rackU")550 }551 query.get().then(querySnapshot => {552 let count = 0;553 bladeutils.getBladeIds(idToVendor => {554 querySnapshot.forEach(doc => {555 datacenterutils.getAbbreviationFromID(doc.data().datacenterID, datacenterAbbrev => {556 if (datacenterAbbrev) {557 vendorArray.push({558 asset_id: doc.id,559 ...doc.data(),560 checked: selected && selected.includes(doc.id),561 bladeInfo: idToVendor[doc.id] ? idToVendor[doc.id] : null,562 displayColor: doc.data().variances.displayColor,563 cpu: doc.data().variances.cpu,564 memory: doc.data().variances.memory,565 storage: doc.data().variances.storage566 });567 count++;568 if (count === querySnapshot.size) {569 callback(vendorArray);570 }571 } else {572 callback(null);573 }574 })575 })576 })577 }).catch(error => {578 console.log("Error getting documents: ", error)579 callback(null)580 })581}582/*// rackAsc should be a boolean corresponding to true if rack is ascending583// rackUAsc should be a boolean corresponding to true if rackU is ascending584function sortAssetsByRackAndRackUFilter(rackAsc, rackUAsc, datacenter, rowStart, rowEnd, numberStart, numberEnd, callback) {585 var vendorArray = []586 var query = assetRef587 if (!rackAsc && !rackUAsc) {588 query = assetRef.orderBy("rackRow", "desc").orderBy("rackNum", "desc").orderBy("rackU", "desc")589 } else if (rackAsc && !rackUAsc) {590 query = assetRef.orderBy("rackRow").orderBy("rackNum").orderBy("rackU", "desc")591 } else if (!rackAsc && rackUAsc) {592 query = assetRef.orderBy("rackRow", "desc").orderBy("rackNum", "desc").orderBy("rackU")593 } else {594 query = assetRef.orderBy("rackRow").orderBy("rackNum").orderBy("rackU")595 }596 query.get().then(querySnapshot => {597 let count = 0;598 querySnapshot.forEach(doc => {599 datacenterutils.getAbbreviationFromID(doc.data().datacenterID, datacenterAbbrev => {600 if (datacenterAbbrev) {601 vendorArray.push({602 asset_id: doc.id,603 model: doc.data().model,604 hostname: doc.data().hostname,605 rack: doc.data().rack,606 rackU: doc.data().rackU,607 owner: doc.data().owner,608 datacenterAbbreviation: datacenterAbbrev609 });610 count++;611 if (count === querySnapshot.size) {612 callback(vendorArray);613 }614 } else {615 callback(null);616 }617 })618 })619 }).catch(error => {620 console.log("Error getting documents: ", error)621 callback(null)622 })623}*/624// This will check if the instance fits on rack (after checking rack exists): fits within in the height of rack, and does not conflict with other instances625// The echo param was added by Anshu and will be passed back via callback to the import functions as-is626// The param does NOT affect this function at all627function assetFitsOnRack(assetRack, rackU, model, datacenter, callback, asset_id = null, offlineStorage = null, chassis = null, echo = -1) {628 if (offlineStorage) {629 callback(null);630 } else {631 let splitRackArray = assetRack.split(/(\d+)/).filter(Boolean)632 let rackRow = splitRackArray[0]633 let rackNum = parseInt(splitRackArray[1])634 rackutils.getRackID(rackRow, rackNum, datacenter, rackID => {635 datacenterutils.getDataFromName(datacenter, datacenterID => {636 if (datacenterID) {637 let ref = chassis ? racksRef.doc(rackID).collection('blades') : racksRef638 ref.where("letter", "==", chassis ? chassis.hostname : rackRow).where("number", "==", chassis ? 1 : rackNum).where("datacenter", "==", datacenterID).get().then(function (querySnapshot) {639 if (!querySnapshot.empty && querySnapshot.docs[0].data().letter && querySnapshot.docs[0].data().number) {640 let rackHeight = querySnapshot.docs[0].data().height641 console.log(model)642 modelutils.getModelByModelname(model, doc => {643 //doc.data().height refers to model height644 if (rackHeight + 1 >= parseInt(chassis ? chassis.slot : rackU) + doc.data().height) {645 //We know the instance will fit on the rack, but now does it conflict with anything?646 rackutils.checkAssetFits(chassis ? chassis.slot : rackU, doc.data().height, rackID, function (status) {647 //can check length. If length > 0, then conflicting instances were returned648 //means that there are conflicts.649 if (status && status.length) {650 let height = doc.data().height651 let rackedAt = chassis ? chassis.slot : rackU652 let conflictNew = [];653 let conflictCount = 0;654 status.forEach(assetID => {655 getAssetDetails(assetID, result => {656 conflictNew.push(result.model + " " + result.hostname + ", ");657 conflictCount++;658 if (conflictCount === status.length) {659 console.log(conflictNew)660 var errMessage = "Asset of height " + height + (chassis ? " slotted at " : " racked at ") + rackedAt + (chassis ? "" : "U") + " conflicts with asset(s) " + conflictNew.join(', ').toString();661 if (echo < 0) {662 callback(errMessage);663 } else {664 callback({ error: errMessage, echo: echo })665 }666 }667 });668 })669 } else {//status callback is null, no conflits670 if (echo < 0) {671 callback(null, doc.data().modelNumber, doc.data().vendor, rackID)672 } else {673 callback({ error: null, echo: echo })674 }675 }676 }, asset_id, chassis) //if you pass in a null to checkInstanceFits677 } else {678 var errMessage = "Asset of this model at this "+(chassis ? "Slot" : "RackU")+" will not fit on this "+(chassis ? "chassis" : "rack");679 if (echo < 0) {680 callback(errMessage);681 } else {682 callback({ error: errMessage, echo: echo })683 }684 }685 })686 } else {687 var errMessage2 = (chassis ? "Chassis" : "Rack") + " does not exist"688 if (echo < 0) {689 callback(errMessage2)690 } else {691 callback({ error: errMessage2, echo: echo })692 }693 }694 })695 } else {696 var errMessage = "Datacenter does not exist.";697 if (echo < 0) {698 callback(errMessage);699 } else {700 callback({ error: errMessage, echo: echo })701 }702 }703 })704 })705 }706}707function deleteAsset(assetID, callback, isDecommission = false, offlineStorage = null) {708 let query = offlineStorage ? db.collectionGroup("offlineAssets").where("assetId", "==", String(assetID)) : assetRef.doc(assetID);709 query.get().then(function (snap) {710 console.log("checkpoint 1", snap, assetID)711 let doc = offlineStorage ? snap.docs[0] : snap;712 //This is so I can go into racks collection and delete instances associated with the rack713 if (doc.exists) {714 let rackID, rackRow, rackNum, datacenter;715 if (!offlineStorage) {716 let assetRack = doc.data().rack717 let splitRackArray = assetRack.split(/(\d+)/).filter(Boolean)718 rackRow = splitRackArray[0]719 rackNum = parseInt(splitRackArray[1])720 datacenter = doc.data().datacenter;721 }722 rackutils.getRackID(rackRow, rackNum, datacenter, id => {723 if (id) {724 console.log("checkpoint 2")725 rackID = id726 console.log(rackID)727 let docData = doc.data()728 let deleteAssetConnections = docData.powerConnections729 console.log(deleteAssetConnections)730 if (deleteAssetConnections.length != 0 && !offlineStorage) {//731 console.log("THere are asset connections to delete")732 //need to get the datacenter, rack that the asset it on733 racksRef.doc(String(rackID)).update({734 //Can you do this??735 powerPorts: firebase.firestore.FieldValue.arrayRemove(...deleteAssetConnections)736 }).then(function () {737 //THIS RETURNS A NULL738 //so if there are network connections, won't ever delete the asset739 assetnetworkportutils.symmetricNetworkConnectionsDelete(assetID, result => {740 console.log(result)741 if (result) {742 assetRef.doc(assetID).delete().then(function () {743 racksRef.doc(String(rackID)).update({744 assets: firebase.firestore.FieldValue.arrayRemove(assetID)745 }).then(function () {746 console.log("Document successfully deleted!");747 if (!isDecommission) {748 logutils.addLog(assetID, logutils.ASSET(), logutils.DELETE(), docData)749 }750 index.deleteObject(assetID)751 callback(assetID);752 })753 }).catch(function (error) {754 console.log(error)755 callback(null);756 })757 } else {758 callback(null);759 }760 })761 })762 } else {763 //MY b, duplicated code again764 //There were no powerConnections made in the asset in the first place765 assetnetworkportutils.symmetricNetworkConnectionsDelete(assetID, result => {766 if (result) {767 console.log("checkpoint 3")768 if (offlineStorage) {769 console.log("here1")770 offlinestorageutils.getInfoFromAbbrev(offlineStorage, (offlineName, offlineID) => {771 if (offlineName) {772 offlinestorageRef.doc(offlineID).collection("offlineAssets").doc(assetID).delete().then(function () {773 console.log("Document successfully deleted!");774 if (!isDecommission) {775 logutils.addLog(assetID, logutils.OFFLINE(), logutils.DELETE(), docData)776 }777 index.deleteObject(assetID)778 callback(assetID);779 })780 } else {781 callback(null);782 }783 })784 } else {785 console.log("here2")786 assetRef.doc(assetID).delete().then(function () {787 racksRef.doc(String(rackID)).update({788 assets: firebase.firestore.FieldValue.arrayRemove(assetID)789 }).then(function () {790 console.log("Document successfully deleted!");791 if (!isDecommission) {792 logutils.addLog(assetID, logutils.ASSET(), logutils.DELETE(), docData)793 }794 index.deleteObject(assetID)795 callback(assetID);796 })797 }).catch(function (error) {798 console.log(error)799 callback(null);800 })801 }802 } else {803 callback(null);804 }805 }, offlineStorage);806 }807 } else {808 console.log("no rack for this letter and number")809 callback(null)810 }811 }, offlineStorage)812 } else {813 console.log("doc doesnt exist")814 callback(null);815 }816 })817}818//TODO: double check this still works:819//hostname updating works, owner updating works, conflicts, etc.820function updateAsset(assetID, model, hostname, rack, rackU, owner, comment, datacenter, macAddresses,821 networkConnectionsArray, deletedNCThisPort, powerConnections, displayColor, memory, storage, cpu, callback, changePlanID = null, changeDocID = null, chassis = null, offlineStorageAbbrev = null) {822 console.log(rack, rackU)823 validateAssetForm(assetID, model, hostname, rack, rackU, owner, datacenter, offlineStorageAbbrev).then(824 _ => {825 console.log("checkpoint", datacenter)826 validateAssetVariances(displayColor, cpu, memory, storage, errorMsg => {827 if (errorMsg) {828 callback(errorMsg)829 } else {830 datacenterutils.getDataFromName(datacenter, (datacenterID, datacenterAbbrev) => {831 if (datacenterID) {832 console.log("checkpoint2")833 modelutils.getModelByModelname(model, doc => {834 if (!doc) {835 var errMessage = "Model does not exist"836 callback(errMessage)837 } else {838 console.log("checkpoint3", doc)839 if (userutils.isLoggedInUserAdmin() || (!offlineStorageAbbrev && userutils.doesLoggedInUserHaveAssetPerm(datacenterAbbrev)) || userutils.doesLoggedInUserHaveAssetPerm(null)) {840 assetFitsOnRack(rack, rackU, model, datacenter, stat => {841 //returned an error message842 if (stat) {843 var errMessage = stat844 //need to pass up errormessage if model updated and instance no longer fits845 callback(errMessage)846 }847 //returns null if no issues/conflicts.848 else {849 console.log("No conflictss updates")850 let splitRackArray = offlineStorageAbbrev ? null : rack.split(/(\d+)/).filter(Boolean)851 let rackRow = offlineStorageAbbrev ? null : splitRackArray[0]852 let rackNum = offlineStorageAbbrev ? null : parseInt(splitRackArray[1])853 //get new rack document854 rackutils.getRackID(rackRow, rackNum, datacenter, result => {855 if (result) {856 console.log("checkpoint4")857 //get old rack document858 let query = offlineStorageAbbrev ? db.collectionGroup("offlineAssets").where("assetId", "==", assetID) : assetRef.doc(assetID);859 query.get().then(snapShot => {860 console.log("checkpoint5")861 let docSnap = offlineStorageAbbrev ? snapShot.docs[0] : snapShot;862 console.log(assetID, docSnap)863 let oldRack = offlineStorageAbbrev ? null : docSnap.data().rack;864 let oldSplitRackArray = offlineStorageAbbrev ? null : oldRack.split(/(\d+)/).filter(Boolean)865 let oldRackRow = offlineStorageAbbrev ? null : oldSplitRackArray[0]866 let oldRackNum = offlineStorageAbbrev ? null : parseInt(oldSplitRackArray[1])867 let oldDatacenter = offlineStorageAbbrev ? null : docSnap.data().datacenter868 let oldPowerConnections = docSnap.data().powerConnections;869 let oldNetworkConnections = docSnap.data().networkConnections;870 var modelStuff = []871 modelutils.getVendorAndNumberFromModel(model, name => modelStuff = name)872 var rackId = ''873 console.log("checkpoint6")874 if (!offlineStorageAbbrev) {875 rackutils.getRackID(rack.slice(0, 1), rack.slice(1, rack.length), datacenter, name => rackId = name)876 }877 var modelId = ''878 modelutils.getModelIdFromModelName(model, name => modelId = name)879 rackutils.getRackID(oldRackRow, oldRackNum, oldDatacenter, oldResult => {880 console.log("checkpoint7")881 console.log(oldRackRow, oldRackNum, oldDatacenter, oldResult)882 if (oldResult) {883 console.log("up in this bitch")884 console.log("checkpoint8")885 //get new rack document886 //get instance id887 console.log(powerConnections);888 replaceAssetRack(oldResult, result, oldPowerConnections, powerConnections, assetID, changePlanID, result => {889 logutils.getObjectData(String(assetID), offlineStorageAbbrev ? logutils.OFFLINE() : logutils.ASSET(), assetData => {890 console.log("checkpoint9")891 //console.log(assetnetworkportutils.networkConnectionsToArray(networkConnections))892 //the reason why we have networkConnections to array is because validateNetworkConnections expects an array. networkConnections is a JSON object because we got in from the db, and to send connectiosn to the db, it must be transformed into a JSON obj first893 assetnetworkportutils.validateNetworkConnections(model, networkConnectionsArray, ncStatus => {894 assetnetworkportutils.networkConnectionsToMap(networkConnectionsArray, mapResult => {895 console.log("checkpoint10")896 let networkConnections = mapResult;897 //console.log("In updateAsset: " + powerConnectionsInput)898 // let powerConnections = assetpowerportutils.formatPowerConnections(powerConnectionsInput)899 console.log(ncStatus)900 if (ncStatus) {901 console.log("Couldn't hang")902 callback(ncStatus)903 } else {904 console.log("checkpoint11")905 console.log(powerConnections)906 assetpowerportutils.validatePowerConnections(datacenter, rack, rackU, powerConnections, model, ppStatus => {907 console.log("checkpoint12")908 console.log(ppStatus)909 if (ppStatus) {910 console.log("breakpoint")911 callback(ppStatus)912 } else {913 let assetObject = {914 assetId: assetID,915 model: model,916 modelId: modelId,917 vendor: modelStuff[0],918 modelNumber: modelStuff[1],919 hostname: hostname,920 owner: owner,921 comment: comment,922 rackRow: rackRow,923 rackNum: rackNum,924 macAddresses,925 networkConnections,926 powerConnections,927 variances: {928 displayColor: displayColor,929 memory: memory,930 cpu: cpu,931 storage: storage932 }933 //these are the fields in the document to update934 };935 if (!offlineStorageAbbrev) {936 assetObject = {937 ...assetObject,938 rack: rack,939 rackU: rackU,940 rackID: rackId,941 datacenter: datacenter,942 datacenterID: datacenterID,943 datacenterAbbrev: datacenterAbbrev944 }945 }946 if (!changePlanID) {947 console.log("checkpoint13")948 assetnetworkportutils.symmetricNetworkConnectionsDelete(assetID, deleteResult => {949 if (deleteResult) {950 assetnetworkportutils.symmetricNetworkConnectionsAdd(networkConnectionsArray, assetID);951 console.log("checkpoint14")952 let suffixes_list = []953 let _model = assetObject.model954 while (_model.length > 1) {955 _model = _model.substr(1)956 suffixes_list.push(_model)957 }958 let _hostname = assetObject.hostname959 while (_hostname.length > 1) {960 _hostname = _hostname.substr(1)961 suffixes_list.push(_hostname)962 }963 if (!offlineStorageAbbrev) {964 let _datacenter = assetObject.datacenter965 while (_datacenter.length > 1) {966 _datacenter = _datacenter.substr(1)967 suffixes_list.push(_datacenter)968 }969 let _datacenterAbbrev = assetObject.datacenterAbbrev970 while (_datacenterAbbrev.length > 1) {971 _datacenterAbbrev = _datacenterAbbrev.substr(1)972 suffixes_list.push(_datacenterAbbrev)973 }974 }975 let _owner = assetObject.owner976 index.saveObject({977 ...assetObject,978 objectID: assetID,979 suffixes: suffixes_list.join(' ')980 })981 if (offlineStorageAbbrev) {982 console.log("checkpoint15")983 offlinestorageutils.getInfoFromAbbrev(offlineStorageAbbrev, (offlineName, offlineID) => {984 console.log(offlineName, offlineID)985 if (offlineName) {986 console.log(offlineID)987 offlinestorageRef.doc(offlineID).collection("offlineAssets").doc(String(assetID)).update(assetObject).then(function () {988 console.log("checkpoint16")989 console.log("Updated model successfully")990 // log needs to be added before calling back for DetailedAssetScreen991 logutils.addLog(String(assetID), logutils.OFFLINE(), logutils.MODIFY(), {...assetData,datacenterAbbrev: offlineStorageAbbrev}, () => callback(null, String(assetID),modelStuff[0]))992 }).catch(function (error) {993 callback(error);994 })995 } else {996 callback("Error getting offline storage site info.")997 }998 })999 } else {1000 assetRef.doc(String(assetID)).update(assetObject).then(function () {1001 console.log("Updated model successfully")1002 // log needs to be added before calling back for DetailedAssetScreen1003 logutils.addLog(String(assetID), logutils.ASSET(), logutils.MODIFY(), assetData, () => callback(null, String(assetID),modelStuff[0]))1004 }).catch(function (error) {1005 callback(error);1006 })1007 }1008 } else {1009 callback("Couldn't delete existing network connections.");1010 }1011 }, offlineStorageAbbrev)1012 } else {1013 console.log(changeDocID);1014 if(chassis){1015 assetObject = {1016 ...assetObject,1017 chassisHostname: chassis.hostname,1018 chassisSlot: chassis.slot1019 };1020 }1021 assetObject.networkConnections = networkConnectionsArray;1022 changeplanutils.editAssetChange(assetObject, assetID, changePlanID, (result) => {1023 if (result) {1024 callback(null)1025 } else {1026 callback("Error adding asset to the specified change plan.")1027 }1028 //assetnetworkportutils.symmetricNetworkConnectionsAdd(networkConnectionsArray, assetID);1029 }, changeDocID, offlineStorageAbbrev);1030 }1031 }1032 }, assetID, offlineStorageAbbrev)1033 }1034 }, offlineStorageAbbrev)1035 }, oldNetworkConnections, offlineStorageAbbrev, chassis, assetID)1036 })1037 }, offlineStorageAbbrev, chassis)1038 }1039 }, offlineStorageAbbrev)1040 })1041 }1042 }, offlineStorageAbbrev)1043 }1044 }, assetID, offlineStorageAbbrev, chassis)1045 } else {1046 callback("You don't have the permissions for this datacenter");1047 }1048 }1049 })1050 }1051 }, offlineStorageAbbrev)1052 }1053 })1054 }).catch(errMessage => {1055 console.log(errMessage)1056 callback(errMessage)1057 })1058}1059function getAssetFromModel(model, callback) {1060 assetRef.where('model', '==', model).get().then(docSnaps => {1061 const assets = docSnaps.docs.map(doc => (1062 { id: doc.id, ...doc.data() }1063 ))1064 callback(assets)1065 })1066 .catch(error => {1067 callback(null)1068 })1069}1070function sortByKeyword(keyword, callback) {1071 // maybe add limit by later similar to modelutils.getModels()1072 assetRef.orderBy(keyword.toLowerCase()).get().then(1073 docSnaps => {1074 const assets = docSnaps.docs.map(doc => (1075 { id: doc.id }1076 ))1077 callback(assets)1078 })1079 .catch(error => {1080 callback(null)1081 })1082}1083function getSuggestedModels(userInput, callback) {1084 // https://stackoverflow.com/questions/46573804/firestore-query-documents-startswith-a-string/465741431085 var modelArray = []1086 modelsRef.orderBy('modelName').get().then(querySnapshot => {1087 querySnapshot.forEach(doc => {1088 const data = doc.data().modelName1089 if (shouldAddToSuggestedItems(modelArray, data, userInput)) {1090 modelArray.push(data)1091 }1092 })1093 callback(modelArray)1094 })1095 .catch(error => {1096 callback(null)1097 })1098}1099function getSuggestedOwners(userInput, callback) {1100 // https://stackoverflow.com/questions/46573804/firestore-query-documents-startswith-a-string/465741431101 var modelArray = []1102 usersRef.orderBy('username').get().then(querySnapshot => {1103 querySnapshot.forEach(doc => {1104 const data = doc.data().username1105 if (shouldAddToSuggestedItems(modelArray, data, userInput)) {1106 modelArray.push(data)1107 }1108 })1109 callback(modelArray)1110 })1111 .catch(error => {1112 callback(null)1113 })1114}1115function getSuggestedRacks(datacenter, userInput, callback) {1116 // https://stackoverflow.com/questions/46573804/firestore-query-documents-startswith-a-string/465741431117 var modelArray = []1118 datacentersRef.where('name', '==', datacenter).get().then(docSnaps => {1119 const datacenterID = docSnaps.docs[0].id1120 racksRef.where('datacenter', '==', datacenterID).orderBy('letter').orderBy('number').get().then(querySnapshot => {1121 querySnapshot.forEach(doc => {1122 const data = doc.data().letter + doc.data().number.toString()1123 if (shouldAddToSuggestedItems(modelArray, data, userInput)) {1124 modelArray.push(data)1125 }1126 })1127 callback(modelArray)1128 })1129 .catch(error => {1130 callback(null)1131 })1132 })1133 .catch(error => {1134 callback(null)1135 })1136}1137function getNetworkPorts(model, userInput, callback) {1138 var modelArray = []1139 // https://stackoverflow.com/questions/46573804/firestore-query-documents-startswith-a-string/465741431140 modelsRef.where('modelName', '==', model ? model : '').get().then(docSnaps => {1141 var port;1142 const data = docSnaps.docs[0].data().networkPorts1143 for (port in data) {1144 if (shouldAddToSuggestedItems(modelArray, data[port].trim(), userInput)) {1145 modelArray.push(data[port])1146 }1147 }1148 callback(modelArray)1149 })1150 .catch(error => {1151 callback([])1152 })1153}1154function getAllAssetsList(callback) {1155 let assetArray = [];1156 let assetData = new Map();1157 let count = 0;1158 assetRef.get().then(function (querySnapshot) {1159 if (querySnapshot.empty) {1160 callback(null);1161 } else {1162 db.collectionGroup("offlineAssets").get().then(function (offlineQuerySnapshot) {1163 querySnapshot.forEach(doc => {1164 if (userutils.isLoggedInUserAdmin() || userutils.doesLoggedInUserHaveAssetPerm(null) || userutils.doesLoggedInUserHaveAssetPerm(doc.data().datacenterAbbrev)) {1165 assetArray.push(doc.data().assetId + " - " + doc.data().model + " - " + doc.data().hostname);1166 assetData.set(doc.data().assetId + " - " + doc.data().model + " - " + doc.data().hostname, {...doc.data(), location: "rack"});1167 }1168 count++;1169 if (count === querySnapshot.size) {1170 count = 0;1171 if(offlineQuerySnapshot.empty){1172 callback(assetArray, assetData);1173 } else {1174 offlineQuerySnapshot.forEach(offlineDoc => {1175 let parent = offlineDoc.ref.parent.parent;1176 parent.get().then(function (parentDoc) {1177 if(parentDoc.exists){1178 if(userutils.isLoggedInUserAdmin() || userutils.doesLoggedInUserHaveAssetPerm(null) || userutils.doesLoggedInUserHaveAssetPerm(parentDoc.data().abbreviation, true)){1179 assetArray.push(offlineDoc.data().assetId + " - " + offlineDoc.data().model + " - " + offlineDoc.data().hostname);1180 assetData.set(offlineDoc.data().assetId + " - " + offlineDoc.data().model + " - " + offlineDoc.data().hostname, {...offlineDoc.data(), location: "offline", offlineAbbrev: parentDoc.data().abbreviation});1181 }1182 count++;1183 if(count === offlineQuerySnapshot.size){1184 callback(assetArray, assetData);1185 }1186 } else {1187 callback(null);1188 }1189 });1190 });1191 }1192 }1193 })1194 })1195 }1196 }).catch(function () {1197 callback(null);1198 })1199}1200// need to change logic here for editing asset, don't allow to pick own name1201function getSuggestedAssetIds(datacenter, userInput, callback, self = '') {1202 var modelArray = []1203 // https://stackoverflow.com/questions/46573804/firestore-query-documents-startswith-a-string/465741431204 assetRef.where('datacenter', '==', datacenter ? datacenter : '').get().then(querySnapshot => {1205 bladeRef.get().then(docSnaps => {1206 var bladeIds = []1207 docSnaps.forEach(doc => {1208 bladeIds.push(doc.id)1209 })1210 querySnapshot.forEach(doc => {1211 const data = doc.data().assetId;1212 if (!bladeIds.includes(data) && data !== self && shouldAddToSuggestedItems(modelArray, data, userInput)) {1213 modelArray.push(data + ' - ' + doc.data().model + ' ' + doc.data().hostname)1214 }1215 })1216 callback(modelArray)1217 })1218 })1219 .catch(error => {1220 callback([])1221 })1222}1223function getSuggestedOtherAssetPorts(assetId, userInput, callback) {1224 var modelArray = []1225 // https://stackoverflow.com/questions/46573804/firestore-query-documents-startswith-a-string/465741431226 assetRef.where('assetId', '==', assetId ? assetId : '').get().then(docSnaps => {1227 modelsRef.doc(docSnaps.docs[0].data().modelId).get().then(doc => {1228 var port;1229 const data = doc.data().networkPorts1230 for (port in data) {1231 if (shouldAddToSuggestedItems(modelArray, data[port].trim(), userInput)) {1232 modelArray.push(data[port])1233 }1234 }1235 callback(modelArray)1236 })1237 .catch(error => {1238 callback([])1239 })1240 })1241 .catch(error => {1242 callback([])1243 })1244}1245function getSuggestedDatacenters(userInput, callback) {1246 // https://stackoverflow.com/questions/46573804/firestore-query-documents-startswith-a-string/465741431247 var modelArray = []1248 datacentersRef.orderBy('name').orderBy('abbreviation').get().then(querySnapshot => {1249 querySnapshot.forEach(doc => {1250 const data = doc.data().name;1251 if (userutils.doesLoggedInUserHaveAssetPerm(doc.data().abbreviation) && shouldAddToSuggestedItems(modelArray, data, userInput)) {1252 modelArray.push(data)1253 }1254 })1255 callback(modelArray)1256 })1257 .catch(error => {1258 console.log("fuck my fucking life", error)1259 callback(null)1260 })1261}1262function shouldAddToSuggestedItems(array, data, userInput) {1263 const name = data.toLowerCase()1264 const lowerUserInput = userInput ? userInput.toLowerCase() : userInput1265 return !array.includes(data) && (!userInput1266 || (name >= lowerUserInput1267 && name < lowerUserInput.slice(0, lowerUserInput.length - 1)1268 + String.fromCharCode(lowerUserInput.slice(lowerUserInput.length - 1, lowerUserInput.length).charCodeAt(0) + 1)))1269}1270function getAssetDetails(assetID, callback, offlineStorageAbbrev = null) {1271console.log(assetID)1272 if (offlineStorageAbbrev) {1273 console.log(assetID)1274 db.collectionGroup("offlineAssets").where("assetId", "==", String(assetID)).get().then(function (querySnapshot) {1275 if(querySnapshot.empty){1276 callback(null);1277 } else {1278 callback({1279 assetID: assetID,1280 ...querySnapshot.docs[0].data(),1281 modelNum: querySnapshot.docs[0].data().modelNumber.trim(),1282 })1283 }1284 })1285 } else {1286 assetRef.doc(assetID).get().then((doc) => {1287 let inst = {1288 assetID: assetID.trim(),1289 model: doc.data().model.trim(),1290 hostname: doc.data().hostname.trim(),1291 rack: doc.data().rack.trim(),1292 rackNum: doc.data().rackNum,1293 rackU: doc.data().rackU,1294 rackRow: doc.data().rackRow,1295 owner: doc.data().owner.trim(),1296 comment: doc.data().comment.trim(),1297 modelNum: doc.data().modelNumber.trim(),1298 vendor: doc.data().vendor.trim(),1299 datacenter: doc.data().datacenter.trim(),1300 datacenterAbbrev: doc.data().datacenterAbbrev.trim(),1301 powerConnections: doc.data().powerConnections,1302 macAddresses: doc.data().macAddresses,1303 networkConnections: doc.data().networkConnections,1304 variances: doc.data().variances1305 }1306 callback(inst)1307 });1308 }1309}1310//REFACTORED to be a promise. Combined checkHostnameExists into this function1311function validateAssetForm(assetID, model, hostname, rack, racku, owner, datacenter, offlineStorage = null) {1312 return new Promise((resolve, reject) => {1313 assetRef.where("hostname", "==", hostname).get().then(function (docSnaps) {1314 if (!docSnaps.empty && assetID !== docSnaps.docs[0].id && hostname !== "") {1315 console.log("Made it here " + assetID + " " + docSnaps.docs[0].id)1316 reject("Hostname already exists")1317 }1318 if (owner !== "") {1319 let username = owner;1320 usersRef.where('username', '==', username).get().then(querySnapshot => {1321 if (!querySnapshot.empty) {1322 console.log("Up in this bitch")1323 resolve(null)1324 } else {1325 reject("This user does not exist in the system")1326 }1327 })1328 }1329 if (!offlineStorage && datacenter !== "") {1330 datacenterutils.getDataFromName(datacenter, datacenterID => {1331 if (datacenterID) {1332 //TODO: FIX NESTING?1333 resolve(null);1334 } else {1335 reject("Datacenter does not exist")1336 }1337 })1338 } else if (model.trim() === "" || (!offlineStorage && (rack.trim() === "" || racku == null))) {1339 reject("Required fields cannot be empty")1340 } else {1341 console.log("up in this bitch too")1342 resolve(null)1343 }1344 })1345 })1346}1347function replaceAssetRack(oldRack, newRack, oldPowerPorts, newPowerPorts, id, changePlanID, callback, offlineStorage = null, chassis = null) {1348 if (offlineStorage) {1349 callback(true);1350 } else {1351 if (!changePlanID) {1352 if (String(oldRack) === String(newRack)) {1353 console.log(oldPowerPorts);1354 console.log(newPowerPorts);1355 if (!oldPowerPorts.length && !newPowerPorts.length) {1356 callback(true);1357 } else if (!oldPowerPorts.length && newPowerPorts.length) {1358 //old is empty1359 racksRef.doc(String(oldRack)).update({1360 powerPorts: firebase.firestore.FieldValue.arrayUnion(...newPowerPorts.map(obj => ({1361 ...obj,1362 assetID: id1363 })))1364 }).then(function () {1365 callback(true);1366 }).catch(function () {1367 callback(null);1368 })1369 } else if (!newPowerPorts.length && oldPowerPorts.length) {1370 racksRef.doc(String(oldRack)).update({1371 powerPorts: firebase.firestore.FieldValue.arrayRemove(...oldPowerPorts.map(obj => ({1372 ...obj,1373 assetID: id1374 })))1375 }).then(function () {1376 callback(true);1377 }).catch(function () {1378 callback(null);1379 })1380 } else {1381 racksRef.doc(String(oldRack)).update({1382 powerPorts: firebase.firestore.FieldValue.arrayRemove(...oldPowerPorts.map(obj => ({1383 ...obj,1384 assetID: id1385 })))1386 }).then(function () {1387 racksRef.doc(String(oldRack)).update({1388 powerPorts: firebase.firestore.FieldValue.arrayUnion(...newPowerPorts.map(obj => ({1389 ...obj,1390 assetID: id1391 })))1392 }).then(function () {1393 callback(true);1394 }).catch(function () {1395 callback(null);1396 })1397 }).catch(function () {1398 callback(null);1399 })1400 }1401 } else {1402 if (chassis) {1403 callback(true)1404 return1405 }1406 if (oldPowerPorts.length && newPowerPorts.length) {1407 racksRef.doc(String(oldRack)).update({1408 assets: firebase.firestore.FieldValue.arrayRemove(id),1409 powerPorts: firebase.firestore.FieldValue.arrayRemove(...oldPowerPorts.map(obj => ({1410 ...obj,1411 assetID: id1412 })))1413 }).then(() => {1414 racksRef.doc(String(newRack)).update({1415 assets: firebase.firestore.FieldValue.arrayUnion(id),1416 powerPorts: firebase.firestore.FieldValue.arrayUnion(...newPowerPorts.map(obj => ({1417 ...obj,1418 assetID: id1419 })))1420 }).then(() => {1421 callback(true);1422 return1423 }).catch(function (error) {1424 callback(false);1425 return1426 })1427 }).catch(function (error) {1428 callback(false);1429 return1430 })1431 } else if (!oldPowerPorts.length && newPowerPorts.length) {1432 racksRef.doc(String(oldRack)).update({1433 assets: firebase.firestore.FieldValue.arrayRemove(id),1434 }).then(() => {1435 racksRef.doc(String(newRack)).update({1436 assets: firebase.firestore.FieldValue.arrayUnion(id),1437 powerPorts: firebase.firestore.FieldValue.arrayUnion(...newPowerPorts.map(obj => ({1438 ...obj,1439 assetID: id1440 })))1441 }).then(() => {1442 callback(true);1443 return1444 }).catch(function (error) {1445 callback(false);1446 return1447 })1448 }).catch(function (error) {1449 callback(false);1450 return1451 })1452 } else if (oldPowerPorts.length && !newPowerPorts.length) {1453 racksRef.doc(String(oldRack)).update({1454 assets: firebase.firestore.FieldValue.arrayRemove(id),1455 powerPorts: firebase.firestore.FieldValue.arrayRemove(...oldPowerPorts.map(obj => ({1456 ...obj,1457 assetID: id1458 })))1459 }).then(() => {1460 racksRef.doc(String(newRack)).update({1461 assets: firebase.firestore.FieldValue.arrayUnion(id),1462 }).then(() => {1463 callback(true);1464 return1465 }).catch(function (error) {1466 callback(false);1467 return1468 })1469 }).catch(function (error) {1470 callback(false);1471 return1472 })1473 } else {1474 racksRef.doc(String(oldRack)).update({1475 assets: firebase.firestore.FieldValue.arrayRemove(id),1476 }).then(() => {1477 racksRef.doc(String(newRack)).update({1478 assets: firebase.firestore.FieldValue.arrayUnion(id),1479 }).then(() => {1480 callback(true);1481 return1482 }).catch(function (error) {1483 callback(false);1484 return1485 })1486 }).catch(function (error) {1487 callback(false);1488 return1489 })1490 }1491 }1492 } else {1493 callback(true);1494 }1495 }1496}1497/*1498function checkHostnameExists(hostname, id, callback) {1499 assetRef.where("hostname", "==", hostname).get().then(function (docSnaps) {1500 callback(!docSnaps.empty && id !== docSnaps.docs[0].id)1501 })1502}1503*/1504function getAssetByHostname(hostname, callback, echo = null) {1505 assetRef.where("hostname", "==", hostname).get().then(function (docSnaps) {1506 if (!docSnaps.empty) {1507 callback({ ...docSnaps.docs[0].data(), found: true, echo: echo, id: docSnaps.docs[0].id })1508 } else {1509 callback({ found: false, echo: echo, id: null })1510 }1511 })1512}1513function getAssetsForExport(callback) {1514 assetRef.orderBy('hostname').get().then(qs => {1515 var rows = [1516 ["hostname", "rack", "rack_position", "vendor", "model_number", "owner", "comment"]1517 ]1518 for (var i = 0; i < qs.size; i++) {1519 rows = [...rows, [1520 modelutils.escapeStringForCSV(qs.docs[i].data().hostname),1521 modelutils.escapeStringForCSV(qs.docs[i].data().rack),1522 '' + qs.docs[i].data().rackU,1523 modelutils.escapeStringForCSV(qs.docs[i].data().vendor),1524 modelutils.escapeStringForCSV(qs.docs[i].data().modelNumber),1525 modelutils.escapeStringForCSV(qs.docs[i].data().owner),1526 modelutils.escapeStringForCSV(qs.docs[i].data().comment)1527 ]]1528 if (rows.length === qs.size + 1) {1529 callback(rows)1530 }1531 }1532 })1533}1534function validateImportedAssets(data, callback) {1535 modelutils.getAllModels(listOfModels => {1536 userutils.getAllUsers(listOfUsers => {1537 console.log(listOfModels)1538 console.log(listOfUsers)1539 var errors = []1540 var toBeAdded = []1541 var toBeModified = []1542 var toBeIgnored = []1543 var assetsSeen = {}1544 var assetsProcessed = 01545 function checkAndCallback() {1546 assetsProcessed++1547 if (assetsProcessed === data.length) {1548 callback({ errors, toBeAdded, toBeModified, toBeIgnored })1549 }1550 }1551 for (var i = 0; i < data.length; i++) {1552 const datum = data[i]1553 var canProceedWithDbValidation = true1554 var vendorAndModelFound = true1555 if (!datum.vendor || String(datum.vendor).trim() === '') {1556 errors = [...errors, [i + 1, 'Vendor not found']]1557 canProceedWithDbValidation = false1558 vendorAndModelFound = false1559 }1560 if (!datum.model_number || String(datum.model_number).trim() === '') {1561 errors = [...errors, [i + 1, 'Model number not found']]1562 canProceedWithDbValidation = false1563 vendorAndModelFound = false1564 }1565 if (!datum.hostname || String(datum.hostname).trim() === '') {1566 errors = [...errors, [i + 1, 'Hostname not found']]1567 canProceedWithDbValidation = false1568 } else {1569 if (!/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]$/.test(datum.hostname)) {1570 //not a valid hostname1571 errors = [...errors, [i + 1, 'Invalid hostname (does not follow RFC-1034 specs)']]1572 canProceedWithDbValidation = false1573 }1574 if (!(datum.hostname in assetsSeen)) {1575 assetsSeen[datum.hostname] = i1576 } else {1577 canProceedWithDbValidation = false1578 errors = [...errors, [i + 1, 'Duplicate row (an asset with this hostname already exists on row ' + (assetsSeen[datum.hostname] + 1) + ')']]1579 }1580 }1581 if (!datum.rack_position || String(datum.rack_position).trim() === '') {1582 errors = [...errors, [i + 1, 'Rack position not found']]1583 canProceedWithDbValidation = false1584 } else if (isNaN(String(datum.rack_position).trim()) || !Number.isInteger(parseFloat(String(datum.rack_position).trim())) || parseInt(String(datum.rack_position).trim()) <= 0) {1585 errors = [...errors, [i + 1, 'Rack position is not a positive integer']]1586 canProceedWithDbValidation = false1587 }1588 if (!datum.rack || String(datum.rack).trim() === '') {1589 errors = [...errors, [i + 1, 'Rack field missing']]1590 canProceedWithDbValidation = false1591 } else if (!/[A-Z]\d+/.test(datum.rack)) {1592 //not a valid rack1593 errors = [...errors, [i + 1, 'Invalid rack']]1594 canProceedWithDbValidation = false1595 }1596 if (!datum.owner || String(datum.owner).trim() === '') {1597 // errors = [...errors, [i+1, 'Owner field missing']]1598 // canProceedWithDbValidation = false1599 } else if (!listOfUsers.includes(datum.owner)) {1600 errors = [...errors, [i + 1, 'Owner does not exist']]1601 canProceedWithDbValidation = false1602 }1603 if (!(vendorAndModelFound && String(datum.vendor).trim() in listOfModels && listOfModels[String(datum.vendor).trim()].includes(String(datum.model_number).trim()))) {1604 errors = [...errors, [i + 1, 'Model does not exist']]1605 canProceedWithDbValidation = false1606 }1607 if (canProceedWithDbValidation) {1608 data[i].hostname = String(datum.hostname).trim()1609 data[i].vendor = String(datum.vendor).trim()1610 data[i].rack = String(datum.rack).trim()1611 data[i].model_number = String(datum.model_number).trim()1612 data[i].owner = (datum.owner ? String(datum.owner) : "")1613 data[i].comment = (datum.comment ? String(datum.comment) : "")1614 getAssetByHostname(datum.hostname.trim(), asset => {1615 const datum = data[asset.echo]1616 const datumOwner = (!datum.owner ? "" : datum.owner.trim())1617 const datumComment = (!datum.comment ? "" : datum.comment.trim())1618 const assetOwner = (!asset.owner ? "" : asset.owner.trim())1619 const assetComment = (!asset.comment ? "" : asset.comment.trim())1620 if (asset.found) {1621 if (asset.vendor.trim() !== datum.vendor.trim() || asset.modelNumber.trim() !== datum.model_number.trim()) {1622 errors = [...errors, [asset.echo + 1, 'Another asset (of a different model) that has the same hostname exists']]1623 checkAndCallback()1624 } else if (datum.rack_position === asset.rackU && datum.rack.trim() === asset.rack.trim()1625 && datumOwner === assetOwner && datumComment === assetComment) {1626 // IGNORE CASE1627 toBeIgnored = [...toBeIgnored, datum]1628 checkAndCallback()1629 } else {1630 // MODIFY CASE1631 assetFitsOnRack(datum.rack, datum.rack_position, datum.vendor + ' ' + datum.model_number, ({ error, echo }) => {1632 const datum = data[asset.echo]1633 if (error) {1634 errors = [...errors, [asset.echo + 1, 'This asset could not be placed at the requested location']]1635 checkAndCallback()1636 } else {1637 toBeModified = [...toBeModified, {1638 ...datum,1639 row: asset.echo + 1,1640 assetIdInDb: asset.id1641 }]1642 checkAndCallback()1643 }1644 }, asset.id, asset.echo)1645 }1646 } else {1647 // ADDITION CASE1648 assetFitsOnRack(datum.rack, datum.rack_position, datum.vendor + ' ' + datum.model_number, ({ error, echo }) => {1649 const datum = data[asset.echo]1650 if (error) {1651 errors = [...errors, [asset.echo + 1, 'This asset could not be placed at the requested location']]1652 checkAndCallback()1653 } else {1654 toBeAdded = [...toBeAdded, datum]1655 checkAndCallback()1656 }1657 }, null, asset.echo)1658 }1659 }, i)1660 } else {1661 checkAndCallback()1662 }1663 }1664 })1665 })1666}1667export {1668 getAsset,1669 getAllAssetIDs,1670 addAsset,1671 deleteAsset,1672 assetFitsOnRack,1673 updateAsset,1674 sortByKeyword,1675 getSuggestedModels,1676 getAssetDetails,1677 getAssetFromModel,1678 getSuggestedOwners,1679 getSuggestedRacks,1680 getSuggestedAssetIds,1681 getSuggestedOtherAssetPorts,1682 shouldAddToSuggestedItems,1683 getNetworkPorts,1684 getAssetAt,1685 validateAssetForm,1686 getAssetsForExport,1687 validateImportedAssets,1688 sortAssetsByRackAndRackU,1689 getSuggestedDatacenters,1690 getAllAssetsList,1691 replaceAssetRack...
Using AI Code Generation
1const userUtils = require('./userUtils');2const sinon = require('sinon');3const chai = require('chai');4const sinonChai = require('sinon-chai');5chai.use(sinonChai);6const expect = chai.expect;7describe('Test getAllUsers', () => {8 it('should return all users', () => {9 const getAllUsersStub = sinon.stub(userUtils, 'getAllUsers');10 getAllUsersStub.returns(['user1', 'user2']);11 const result = userUtils.getAllUsers();12 expect(result).to.be.an('array');13 expect(result).to.have.lengthOf(2);14 expect(result).to.include('user1');15 expect(result).to.include('user2');16 getAllUsersStub.restore();17 });18});19const getAllUsers = () => {20 return ['user1', 'user2'];21};22module.exports = { getAllUsers };231 passing (11ms)
Using AI Code Generation
1var userUtils = require('./userUtils');2var expect = require('chai').expect;3describe('userUtils.getAllUsers', function() {4 it('should return an array of users', function() {5 var allUsers = userUtils.getAllUsers();6 expect(allUsers).to.be.an('array');7 expect(allUsers).to.have.length(3);8 });9});10 { username: 'jdoe', email: '
Using AI Code Generation
1const { getAllUsers } = require('../src/userUtils');2const sinon = require('sinon');3const axios = require('axios');4const expect = require('chai').expect;5describe('getAllUsers', () => {6 it('should return all users', async () => {7 const users = [{ name: 'Bob' }];8 const response = { data: users };9 sinon.stub(axios, 'get').resolves(response);10 const allUsers = await getAllUsers();11 expect(allUsers).to.deep.equal(users);12 });13});14const axios = require('axios');15const getAllUsers = () => {16 return axios.get('/users.json').then(response => response.data);17};18module.exports = {19};20{21 "dependencies": {22 }23}24const { getAllUsers } = require('../src/userUtils');25const sinon = require('sinon');26const expect = require('chai').expect;27describe('getAllUsers', () => {28 it('should return all users', () => {29 const users = [{ name: 'Bob' }];30 const server = sinon.fakeServer.create();31 server.respondWith('GET', '/users.json', [32 { 'Content-Type': 'application/json' },33 JSON.stringify(users)34 ]);35 getAllUsers().then(allUsers => {36 expect(allUsers).to.deep.equal(users);37 server.restore();38 });39 });40});41const axios = require('axios');42const getAllUsers = () => {43 return axios.get('/users.json').then(response => response.data);44};45module.exports = {46};47{48 "dependencies": {
Using AI Code Generation
1const userUtils = require('./userUtils');2const sinon = require('sinon');3const chai = require('chai');4const expect = chai.expect;5describe('Test getAllUsers', function() {6 let stub;7 beforeEach(() => {8 stub = sinon.stub(userUtils, 'getAllUsers');9 });10 afterEach(() => {11 stub.restore();12 });13 it('should return all users', function() {14 stub.returns(['user1', 'user2']);15 expect(userUtils.getAllUsers()).to.eql(['user1', 'user2']);16 });17});18const getAllUsers = () => {19 return ['user1', 'user2'];20};21module.exports = {22};23"devDependencies": {24}
Using AI Code Generation
1var sinon = require('sinon'),2 userUtils = require('../utils/userUtils');3var stub = sinon.stub(userUtils, 'getAllUsers', function(){4 return ['user1', 'user2'];5});6var users = userUtils.getAllUsers();7stub.restore();8var sinon = require('sinon'),9 userUtils = require('../utils/userUtils');10var mock = sinon.mock(userUtils);11mock.expects('getAllUsers').once().returns(['user1', 'user2']);12var users = userUtils.getAllUsers();13mock.verify();14var sinon = require('sinon'),15 userUtils = require('../utils/userUtils');16var spy = sinon.spy(userUtils, 'getAllUsers');17var users = userUtils.getAllUsers();18spy.restore();19exports.getAllUsers = function(){20 return ['user1', 'user2'];21};22var sinon = require('sinon'),23 userUtils = require('../utils/userUtils');24var stub = sinon.stub(userUtils, 'getAllUsers', function(){25 return ['user1', 'user2'];26});27var users = userUtils.getAllUsers();28stub.restore();29var mock = sinon.mock(userUtils);30mock.expects('getAllUsers').once().returns(['user1', 'user2']);31var users = userUtils.getAllUsers();32mock.verify();33var spy = sinon.spy(userUtils, 'getAllUsers');34var users = userUtils.getAllUsers();35spy.restore();36exports.getAllUsers = function(){37 return ['user1', 'user2'];38};39var sinon = require('sinon'),40 userUtils = require('../utils/userUtils');41var stub = sinon.stub(userUtils, 'getAllUsers', function(){
Using AI Code Generation
1const userUtils = require("./userUtils");2const sinon = require("sinon");3const chai = require("chai");4const expect = chai.expect;5describe("Test getAllUsers", () => {6 it("should return all users", () => {7 const users = [{ name: "John" }, { name: "Jane" }];8 const stub = sinon.stub(userUtils, "getAllUsers").returns(users);9 const allUsers = userUtils.getAllUsers();10 expect(allUsers).to.deep.equal(users);11 });12});13const getAllUsers = () => {14 return [{ name: "John" }, { name: "Jane" }];15};16module.exports = {17};18{19 "scripts": {20 },21 "devDependencies": {22 }23}24 1 passing (8ms)25const userUtils = require("./userUtils");26const sinon = require("sinon");27const chai = require("chai");28const expect = chai.expect;29describe("Test getAllUsers", () => {30 it("should return all users", () => {31 const users = [{ name: "John" }, { name: "Jane" }];32 const stub = sinon.stub(userUtils, "getAllUsers").returns(users);33 const allUsers = userUtils.getAllUsers();34 expect(allUsers).to.deep.equal(users);35 });36});
Using AI Code Generation
1var users = userUtils.getAllUsers();2assert.equal(users, [user1, user2, user3]);3assert.equal(userUtils.getAllUsers.calledOnce, true);4assert.equal(userUtils.getAllUsers.calledWith(), true);5assert.equal(userUtils.getAllUsers.calledWith('abc'), false);6assert.equal(userUtils.getAllUsers.calledWith('abc', 'xyz'), false);7assert.equal(userUtils.getAllUsers.calledWith('abc', 'xyz', 'pqr'), false);8assert.equal(userUtils.getAllUsers.calledWith('abc', 'xyz', 'pqr', 'xyz'), false);9assert.equal(userUtils.getAllUsers.calledWith('abc', 'xyz', 'pqr', 'xyz', 'pqr'), false);10assert.equal(userUtils.getAllUsers.calledWith('abc', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz'), false);11assert.equal(userUtils.getAllUsers.calledWith('abc', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz', 'pqr'), false);12assert.equal(userUtils.getAllUsers.calledWith('abc', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz'), false);13assert.equal(userUtils.getAllUsers.calledWith('abc', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz', 'pqr'), false);14assert.equal(userUtils.getAllUsers.calledWith('abc', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz'), false);15assert.equal(userUtils.getAllUsers.calledWith('abc', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz', 'pqr', 'xyz', 'pq
Using AI Code Generation
1const sinon = require('sinon');2const userUtils = require('./user');3const assert = require('assert');4describe('test user.js', function() {5 describe('getAllUsers', function() {6 it('should return an array of users', function() {7 const getAllUsersStub = sinon.stub(userUtils, 'getAllUsers');8 getAllUsersStub.returns([{name: 'Bob'}, {name: 'Alice'}]);9 const users = userUtils.getAllUsers();10 assert(getAllUsersStub.called);11 assert(getAllUsersStub.calledWith());12 assert.deepEqual(users, [{name: 'Bob'}, {name: 'Alice'}]);13 getAllUsersStub.restore();14 });15 });16});17exports.getAllUsers = function() {18 return [{name: 'Bob'}, {name: 'Alice'}];19};20const sinon = require('sinon');21const userUtils = require('./user');22const assert = require('assert');23describe('test user.js', function() {24 describe('getUserById', function() {25 it('should return a single user', function() {26 const getUserByIdStub = sinon.stub(userUtils, 'getUserById');27 getUserByIdStub.returns({name: 'Bob'});28 const user = userUtils.getUserById(1);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!