How to use variant method in wpt

Best JavaScript code snippet using wpt

variant-editor.controller.js

Source:variant-editor.controller.js Github

copy

Full Screen

1angular.module('umbraco').controller('TeaCommerce.VariantEditor.Controller', [2'$scope',3'$rootScope',4'$timeout',5'$routeParams',6'contentResource',7'editorState',8'assetsService',9'entityResource',10function ($scope, $rootScope, $timeout, $routeParams, contentResource, editorState, assetsService, entityResource) {11 $scope.ui = {12 creating: false13 };14 $scope.settings = {15 xPath: $scope.model.config.xpathOrNode ? $scope.model.config.xpathOrNode.query : '',//Xpath to variant group parent16 contentId: $scope.model.config.xpathOrNode ? $scope.model.config.xpathOrNode.contentId : '',//Content id of variant group parent17 showXPath: $scope.model.config.xpathOrNode ? $scope.model.config.xpathOrNode.showXPath : '',//Use xpath instead op content id18 docTypeAlias: $scope.model.config.variantDocumentType,//Doc type alias for the variant properties19 hideLabel: $scope.model.config.hideLabel == 1,//Hide Umbraco label20 forceEditorToChooseAllVariantGroups: $scope.model.config.forceEditorToChooseAllVariantGroups == 1,//Validation rule will force editor to choose from all variant groups21 extraListInformation: splitString($scope.model.config.extraListInformation, ','),//Extra property aliases to display in variant table22 variantGroupDocumentTypes: splitString($scope.model.config.variantGroupDocumentTypes, ','),//Specific variant group doc types to use in this particular editor23 variantGroupNodeName: splitString($scope.model.config.variantGroupNodeName, ','),//Specific variant group node names to use in this particular editor24 };25 //Set defaults26 if (!$scope.model.value) {27 $scope.model.value = {};28 }29 if (!$scope.model.value.variants || $scope.model.value.variants.length === 0) {30 $scope.model.value.variants = [];31 $scope.variantGroupsOpen = true;32 }33 $scope.variants = [];34 $scope.model.hideLabel = $scope.settings.hideLabel;35 $scope.variantGroupsClosedCookieName = 'teaCommerceVariantGroupsDisabledDefault' + editorState.current.contentTypeAlias;36 //Set which variant groups should be open if it has not been saved on this product node37 if (!$scope.model.value.variantGroupsOpen) {38 //Get settings from cookie39 $scope.model.value.variantGroupsOpen = Cookies.getJSON($scope.variantGroupsClosedCookieName);40 if (!$scope.model.value.variantGroupsOpen) {41 //None will be opened42 $scope.model.value.variantGroupsOpen = {};43 }44 }45 if ($routeParams.create) {46 $scope.ui.creating = true;47 }48 //Will create and add variant option from the UI selection made by the editor49 //The already existing combinations wil not be created againg50 $scope.addVariantOptions = function () {51 //Get all checked variant groups as a dictionary52 var checkedGroups = $scope.getCheckedVariantGroups(),53 indices = [];54 //Add all group id's to indices list for later use55 for (var checkedGroupKey in checkedGroups) {56 indices.push(checkedGroupKey);57 }58 //Find all variant type combinations from the checked groups and their indices59 var combinations = findCombinations({60 mapping: checkedGroups.slice(0),61 indices: indices62 });63 //Use combinations64 for (var i = 0; i < combinations.length; i++) {65 var combination = combinations[i],66 variant = findVariantByCombination(combination);67 if (!variant) {68 //Create new and add to data69 loadVariant({70 id: guid(),71 docTypeAlias: $scope.settings.docTypeAlias,72 properties: {},73 combination: combination74 });75 }76 }77 //Run though all variants and update the information needed to create the columns of the variants table78 setVariantColumns();79 //Close all variant groups80 $scope.variantGroupsOpen = false;81 //Uncheck all variant types82 $scope.setCheckedStatusOnAllVariantGroups(false);83 };84 //Event hook when combinations have changed on a variant85 $scope.combinationChanged = function (e) {86 //variant, variantGroup87 var oldCombination = {},88 variantGroupItem = null;89 //Copy values to old combination90 oldCombination.id = e.variant.combinationDictionary[e.variantGroup.id].id;91 oldCombination.name = e.variant.combinationDictionary[e.variantGroup.id].id;92 oldCombination.groupId = e.variant.combinationDictionary[e.variantGroup.id].id;93 oldCombination.groupName = e.variant.combinationDictionary[e.variantGroup.id].id;94 //Run through all items on the variant group and find the new item95 for (var i = 0; i < e.variantGroup.items.length; i++) {96 var item = e.variantGroup.items[i];97 if (item.id === oldCombination.id) {98 variantGroupItem = item;99 break;100 }101 }102 //If an item was found start doing stuff103 if (variantGroupItem) {104 //Create the new combination105 var combination = { name: variantGroupItem.name, id: variantGroupItem.id, groupName: e.variantGroup.name, groupId: e.variantGroup.id },106 combinationExists = false,107 combinationIndex = -1;108 //Add the combination to the variant109 e.variant.combinationDictionary[e.variantGroup.id] = combination;110 //Run through existing combinations and update if on is found with the variant group id111 for (var i = 0; i < e.variant.combination.length; i++) {112 var variantGroupItem = e.variant.combination[i];113 if (variantGroupItem && variantGroupItem.groupId === combination.groupId) {114 oldCombination = e.variant.combination[i];115 e.variant.combination[i] = combination;116 combinationIndex = i;117 combinationExists = true;118 break;119 }120 }121 122 if (!combinationExists) {123 //The combination did not so we add it to the variant124 e.variant.combination.push(combination);125 combinationIndex = e.variant.combination.length - 1;126 }127 //See if the combination already exists on another variant128 var matchingVariant = findVariantByCombination(e.variant.combination, e.variant.id);129 e.variant.combinationExists = !!matchingVariant;130 e.variant.combinationName = '';131 for (var i = 0; i < e.variant.combination.length; i++) {132 var variantGroupItem = e.variant.combination[i];133 if (e.variant.combinationName) {134 e.variant.combinationName += ' | ';135 }136 e.variant.combinationName += variantGroupItem.groupName + ': ' + variantGroupItem.name;137 }138 139 }140 //Run though all variants and update the information needed to create the columns of the variants table141 setVariantColumns();142 };143 //Will order variant table by the specified column144 $scope.setOrder = function (variantColumnId) {145 if (!$scope.orderByColumn) {146 $scope.orderByColumn = {147 column: variantColumnId,148 reverse: true149 };150 } else {151 $scope.orderByColumn.column = variantColumnId;152 $scope.orderByColumn.reverse = $scope.orderByColumn.column === variantColumnId ? !$scope.orderByColumn.reverse : false;153 }154 };155 //Get the order by value for a given variant depending on the current ordering settings156 $scope.getOrderByValue = function (variant) {157 return variant.combinationDictionary[$scope.orderByColumn.column] ? variant.combinationDictionary[$scope.orderByColumn.column].name : '';158 };159 //Gets all checked variant groups as a dictionary160 $scope.getCheckedVariantGroups = function () {161 var checkedGroups = [];162 //Find all checked variant groups and items163 if ($scope.variantGroups) {164 for (var i = 0; i < $scope.variantGroups.length; i++) {165 var variantGroup = $scope.variantGroups[i];166 for (var y = 0; y < variantGroup.items.length; y++) {167 var item = variantGroup.items[y];168 if (item.checked) {169 if (!checkedGroups[variantGroup.id]) {170 checkedGroups[variantGroup.id] = [];171 }172 checkedGroups[variantGroup.id].push({ name: item.name, id: item.id, groupName: variantGroup.name, groupId: variantGroup.id });173 }174 }175 }176 }177 return checkedGroups;178 };179 //Will check or uncheck all variant types180 $scope.setCheckedStatusOnAllVariantGroups = function (checked) {181 if ($scope.variantGroups) {182 for (var i = 0; i < $scope.variantGroups.length; i++) {183 var variantGroup = $scope.variantGroups[i];184 for (var y = 0; y < variantGroup.items.length; y++) {185 variantGroup.items[y].checked = checked;186 }187 }188 }189 };190 //Check if all variant types are currently checked191 $scope.isVariantGroupsChecked = function () {192 var checkedGroups = $scope.getCheckedVariantGroups();193 var validated = checkedGroups && checkedGroups.length > 0;194 if (validated && $scope.settings.forceEditorToChooseAllVariantGroups) {195 for (var i = 0; i < $scope.variantGroups.length; i++) {196 var variantGroup = $scope.variantGroups[i];197 var found = false;198 for (var key in checkedGroups) {199 found = key == variantGroup.id;200 if (found) {201 break;202 }203 }204 if (!found) {205 validated = false;206 break;207 }208 }209 }210 return validated;211 };212 //Open or close a specific variant group and save the state in a cookie213 $scope.setVariantGroupClosedState = function (variantGroup) {214 $scope.model.value.variantGroupsOpen[variantGroup.id] = !$scope.model.value.variantGroupsOpen[variantGroup.id];215 var expireDate = new Date();216 expireDate.setFullYear(expireDate.getFullYear() + 6);217 Cookies.set($scope.variantGroupsClosedCookieName, $scope.model.value.variantGroupsOpen, { expires: expireDate });218 };219 //Will open all variants in table if they are all currently closed.220 //If some or all are open they will be closed221 $scope.openOrCloseAllVariants = function () {222 var allAreClosed = true;223 for (var i = 0; i < $scope.variants.length; i++) {224 var variant = $scope.variants[i];225 if (variant.open) {226 allAreClosed = false;227 break;228 }229 }230 for (var i = 0; i < $scope.variants.length; i++) {231 $scope.variants[i].open = allAreClosed;232 }233 return false;234 };235 //Will open all variants groups in table if they are all currently closed.236 //If some or all are open they will be closed237 //The state will be saved in a cookie238 $scope.openOrCloseAllVariantGroups = function (force) {239 var allAreClosed = force === undefined || force === 'open';240 if (!force) {241 allAreClosed = $scope.checkIfAllVariantGroupsAreClosed();242 }243 for (var i = 0; i < $scope.variantGroups.length; i++) {244 $scope.model.value.variantGroupsOpen[$scope.variantGroups[i].id] = allAreClosed;245 }246 var expireDate = new Date();247 expireDate.setFullYear(expireDate.getFullYear() + 6);248 Cookies.set($scope.variantGroupsClosedCookieName, $scope.model.value.variantGroupsOpen, { expires: expireDate });249 return false;250 };251 //Check if all variant groups types are currently closed252 $scope.checkIfAllVariantGroupsAreClosed = function () {253 var allAreClosed = true;254 if ($scope.variantGroups) {255 for (var i = 0; i < $scope.variantGroups.length; i++) {256 var variantGroup = $scope.variantGroups[i];257 if ($scope.model.value.variantGroupsOpen[variantGroup.id]) {258 allAreClosed = false;259 break;260 }261 }262 }263 return allAreClosed;264 };265 //Check if all variant types are currently closed266 $scope.checkIfAllVariantAreClosed = function () {267 var allAreClosed = true;268 if ($scope.variantGroups) {269 for (var i = 0; i < $scope.variants.length; i++) {270 var variant = $scope.variants[i];271 if (variant.open) {272 allAreClosed = false;273 break;274 }275 }276 }277 return allAreClosed;278 };279 //Will check all variants types if they are all currently unchecked.280 //If some or all are checked they will be unchecked281 $scope.selectOrDeselectAllVariantTypes = function () {282 var allAreAreUnChecked = $scope.checkIfAllVariantTypesAreUnchecked();283 for (var i = 0; i < $scope.variantGroups.length; i++) {284 var variantGroup = $scope.variantGroups[i];285 for (var y = 0; y < variantGroup.items.length; y++) {286 variantGroup.items[y].checked = allAreAreUnChecked;287 }288 }289 $scope.openOrCloseAllVariantGroups('open');290 return false;291 };292 //Check if all variant types are currently unchecked293 $scope.checkIfAllVariantTypesAreUnchecked = function () {294 var allAreAreUnChecked = true;295 if ($scope.variantGroups) {296 for (var i = 0; i < $scope.variantGroups.length; i++) {297 var variantGroup = $scope.variantGroups[i];298 for (var y = 0; y < variantGroup.items.length; y++) {299 var item = variantGroup.items[y];300 if (item.checked) {301 allAreAreUnChecked = false;302 break;303 }304 }305 if (allAreAreUnChecked) {306 break;307 }308 }309 }310 return allAreAreUnChecked;311 };312 //Will delete a variant without warning313 $scope.deleteVariant = function (variant) {314 var index = -1;315 for (var i = 0; i < $scope.variants.length; i++) {316 if ($scope.variants[i].id === variant.id) {317 index = i;318 break;319 }320 }321 if (index > -1) {322 removeFromArray($scope.variants, index);323 }324 };325 //Will delete all variants after a confirm box have been displayed326 $scope.deleteAllVariants = function () {327 if (confirm('Are you sure you want to delete all variants?')) {328 $scope.variants = [];329 }330 };331 //Will run validation on all variants332 //Each variant must have no unselected variant types comparing to all other variants333 //There must be no duplicates to a specific variant334 $scope.validateVariants = function () {335 var variantGroups = [],336 isValid = { holesInVariants: false, duplicatesFound: false };337 //Loop though all variants338 for (var i = 0; i < $scope.variants.length; i++) {339 var variant = $scope.variants[i];340 //Reset variant validation status341 variant.validation = {};342 //First variant will trigger a creation of a base set of variant groups that must be filled out343 if (variantGroups.length === 0) {344 for (var y = 0; y < $scope.variantColumns.length; y++) {345 var variantColumn = $scope.variantColumns[y];346 if (!variantColumn.extra) {347 variantGroups.push(variantColumn.id);348 }349 }350 }351 //Count the combination making up this variant352 var combinationsCount = 0;353 for (var key in variant.combinationDictionary) {354 //If the combination have an variant type id it's regarded as selected on this variant355 if (variant.combinationDictionary[key].id > 0) {356 combinationsCount++;357 }358 }359 //Check number of combinations. If there's too few on this variant it does not validate.360 variant.validation.holesInVariants = variantGroups.length !== combinationsCount;361 isValid.holesInVariants = isValid.holesInVariants || variant.validation.holesInVariants;362 //Chek for duplicate variants363 var matchingVariant = findVariantByCombination(variant.combination, variant.id);364 variant.validation.duplicatesFound = !!matchingVariant;365 isValid.duplicatesFound = isValid.duplicatesFound || variant.validation.duplicatesFound;366 }367 $scope.hasError = !isValid.holesInVariants && !isValid.duplicatesFound;368 return isValid;369 };370 //Will find all combinations in a given set of data371 function findCombinations(o) {372 var current = [],373 combinations = [];374 function step() {375 if (current.length === o.indices.length) {376 combinations.push(current.slice(0));377 return;378 }379 o.mapping[o.indices[current.length]].forEach(function (x) {380 current.push(x);381 step();382 current.pop();383 });384 }385 step(); // start recursion386 return combinations;387 }388 //Will find a single variant by it's combination of variant types389 //If there are more than one variant matching the combination only the first one will be returned390 function findVariantByCombination(combination, excludeVariantId) {391 var rtnVariant = null,392 numberOfVariantTypes = 0;393 //Check the number of combinations394 for (var i = 0; i < combination.length; i++) {395 if (combination[i].id) {396 numberOfVariantTypes++;397 }398 }399 //Loop through all variants400 for (var y = 0; y < $scope.variants.length; y++) {401 var variant = $scope.variants[y],402 numberOfVariantTypesTmp = 0,403 combinationFound = true;404 //If we found a variant that should be excluded from the set we continue to the next variant405 if (variant.id === excludeVariantId) {406 continue;407 }408 //Find the variants number of combinations409 for (var i = 0; i < variant.combination.length; i++) {410 if (variant.combination[i].id) {411 numberOfVariantTypesTmp++;412 }413 }414 415 //If the number of combinations match we will need to check that it's the right combinations416 if (numberOfVariantTypes === numberOfVariantTypesTmp) {417 for (var i = 0; i < combination.length; i++) {418 var variantGroupItem = combination[i],419 variantGroupItemFound = false;420 for (var x = 0; x < variant.combination.length; x++) {421 var tmpCombination = variant.combination[x];422 if (tmpCombination.id === variantGroupItem.id) {423 variantGroupItemFound = true;424 break;425 }426 }427 if (!variantGroupItemFound) {428 //Not this variant429 combinationFound = false;430 break;431 }432 }433 } else {434 //Not this variant435 combinationFound = false;436 }437 if (combinationFound) {438 //We found it. Let's break and get on with our lives439 rtnVariant = variant;440 break;441 }442 }443 return rtnVariant;444 }445 //Load all variants from the saved data446 function loadVariants() {447 for (var i = 0; i < $scope.model.value.variants.length; i++) {448 var modelVariant = $scope.model.value.variants[i];449 loadVariant(modelVariant);450 };451 }452 //Load a single variant453 //Properties and property meta data will be added using the variant document type454 //Combinations will be found and enriched with extra data455 function loadVariant(modelVariant) {456 //Create UI variant457 var stockProp = null,458 skuProp = null,459 variant = {460 properties: [],461 id: modelVariant.id,462 combination: modelVariant.combination463 };464 //Run through the properties on the document type and add each of them to the variant465 for (var p = 0; p < $scope.doctypeProperties.length; p++) {466 var prop = $scope.doctypeProperties[p],467 //Copy the property settings468 variantProp = {469 'label': prop.label,470 'description': prop.description,471 'view': prop.view,472 'config': prop.config,473 'hideLabel': prop.hideLabel,474 'validation': prop.validation,475 'id': prop.id,476 'value': prop.value,477 'alias': prop.alias,478 'editor': prop.editor479 };480 if (modelVariant.properties[prop.alias]) {481 //Merge current value482 variantProp.value = modelVariant.properties[prop.alias];483 }484 //Add property to UI variant485 variant.properties.push(variantProp);486 487 //The stock property is special488 if (prop.editor === 'TeaCommerce.StockManagement') {489 //We add extra information the stock property editor will need490 variantProp.variantId = variant.id;491 stockProp = variantProp;492 variantProp.isVariantProp = true;493 }494 //The sku property is also special495 if (prop.alias === 'sku') {496 skuProp = variantProp;497 }498 }499 if (skuProp && stockProp) {500 //Add the sku to the stock property501 //If the variant have a custom sku it can also have a custom stock502 stockProp.skuProp = skuProp;503 }504 variant.combinationDictionary = {};505 variant.combinationName = '';506 //Run through combinations for this variant and collect extra data507 for (var i = 0; i < variant.combination.length; i++) {508 var variantGroupItem = variant.combination[i];509 if (variant.combinationName) {510 variant.combinationName += ' | ';511 }512 variant.combinationDictionary[variantGroupItem.groupId] = variantGroupItem;513 variant.combinationName += variantGroupItem.groupName + ': ' + variantGroupItem.name;514 }515 //Make sure there are no holes in the variant combination dictionary516 //Holes would make the angular code toss around nullpointer exceptions517 for (var i = 0; i < $scope.variantGroups.length; i++) {518 var variantGroup = $scope.variantGroups[i],519 found = false;520 for (combinationVariantGroupId in variant.combinationDictionary) {521 if (combinationVariantGroupId == variantGroup.id) {522 found = true;523 break;524 }525 }526 if (!found) {527 variant.combinationDictionary[variantGroup.id] = { id: 0 };528 } 529 }530 //Push to UI array531 $scope.variants.push(variant);532 };533 if (!$routeParams.create) {534 //On the form submitting event we need to prepare the variant data for save535 $scope.$on("formSubmitting", function () {536 saveVariantsToValue();537 });538 }539 //This will prepare variant data for save and move them to model.value540 //We save a much more simple version of the data than we use to display the angular UI541 function saveVariantsToValue() {542 var entityVariants = [];543 //Run through all variants544 for (var i = 0; i < $scope.variants.length; i++) {545 var variant = $scope.variants[i],546 //Create an entity of the variant data547 entityVariant = { id: variant.id, documentTypeAlias: variant.documentTypeAlias, validation: variant.validation, properties: {}, combination: variant.combination };548 //Run through variant properties and add them to the entity549 for (var p = 0; p < variant.properties.length; p++) {550 var prop = variant.properties[p];551 entityVariant.properties[prop.alias] = prop.value;552 }553 //Push the entity to the result set554 entityVariants.push(entityVariant);555 };556 //Add result to model value. It is now ready to save557 $scope.model.value.variants = entityVariants;558 };559 //Will run though all variants and update the information needed to create the columns of the variants table560 function setVariantColumns() {561 $scope.variantColumns = [];562 for (var i = 0; i < $scope.variantGroups.length; i++) {563 var variantGroup = $scope.variantGroups[i],564 found = false;565 for (var y = 0; y < $scope.variants.length; y++) {566 var variant = $scope.variants[y];567 if (variant.combinationDictionary[variantGroup.id] && variant.combinationDictionary[variantGroup.id].id) {568 found = true;569 break;570 }571 }572 if (found) {573 $scope.variantColumns.push(variantGroup);574 }575 }576 //Order columns by name577 $scope.variantColumns.sort(function (a, b) {578 return a.name < b.name ? -1 : 1;579 });580 //Add columns for extra variant properties581 for (var i = 0; i < $scope.extraPropertiesForColumn.length; i++) {582 var prop = $scope.extraPropertiesForColumn[i];583 $scope.variantColumns.push({ name: prop.label, id: prop.alias, extra: true });584 }585 //Loop through variants and add column information on each of them586 for (var i = 0; i < $scope.variants.length; i++) {587 var variant = $scope.variants[i];588 variant.columns = {};589 variant.documentTypeAlias = $scope.settings.docTypeAlias;590 for (var y = 0; y < $scope.variantColumns.length; y++) {591 var column = $scope.variantColumns[y];592 if (column.extra) {593 //Extra property594 for (var x = 0; x < variant.properties.length; x++) {595 var prop = variant.properties[x];596 if (prop.alias === column.id) {597 variant.columns[column.id] = prop;598 break;599 }600 }601 } else {602 //Variant group603 if (variant.combinationDictionary[column.id] && variant.combinationDictionary[column.id].id) {604 variant.columns[column.id] = variant.combinationDictionary[column.id].name;605 } else {606 variant.columns[column.id] = '';607 }608 }609 }610 }611 }612 //Ready the templates for all variant groups, variant types and variants613 //The templates come from the Umbraco document types614 function readyScaffolding() {615 //Either use the xpath or the content id from the settings to find the root of the variant groups616 if ($scope.settings.showXPath && $scope.settings.xPath) {617 //Find the variant group root using xpath618 entityResource.getByQuery($scope.settings.xPath, $routeParams.id, "Document").then(function (ent) {619 //Get all variant groups620 getChildren(ent);621 });622 } else if (!$scope.settings.showXPath && $scope.settings.contentId) {623 //Find the variant group root using the content id624 entityResource.getById($scope.settings.contentId, "Document").then(function (ent) {625 //Get all variant groups626 getChildren(ent);627 });628 }629 };630 //Will fetch the document type for the variants and start loading the variants631 function readyVariantScaffolding() {632 $scope.doctypeProperties = [];633 $scope.extraPropertiesForColumn = [];634 if ($scope.settings.docTypeAlias) {635 //There's a document type from the settings to load636 contentResource.getScaffold(-20, $scope.settings.docTypeAlias).then(function (data) {637 // Remove the last tab638 $scope.doctype = data.tabs.pop();639 //Run through all tabs and get all properties for the variants640 for (var t = 0; t < data.tabs.length; t++) {641 var tab = data.tabs[t];642 for (var p = 0; p < tab.properties.length; p++) {643 var prop = tab.properties[p];644 $scope.doctypeProperties.push(prop);645 //Check if this property should be added to the list of extra columns in the variants table646 for (var i = 0; i < $scope.settings.extraListInformation.length; i++) {647 if ($scope.settings.extraListInformation[i] === prop.alias) {648 $scope.extraPropertiesForColumn.push(prop);649 $scope.extraPropertiesForColumn.sort(function (a, b) {650 return a.name < b.name ? -1 : 1;651 });652 break;653 }654 }655 }656 }657 //Load all variants658 loadVariants();659 //Run though all variants and update the information needed to create the columns of the variants table660 setVariantColumns();661 });662 } else {663 //Load all variants664 loadVariants();665 //Run though all variants and update the information needed to create the columns of the variants table666 setVariantColumns();667 }668 }669 function checkDocumentTypeFromFilter(content) {670 var rtn = $scope.settings.variantGroupDocumentTypes.length === 0 || ($scope.settings.variantGroupDocumentTypes.length === 1 && $scope.settings.variantGroupDocumentTypes[0] === '');671 for (var i = 0; i < $scope.settings.variantGroupDocumentTypes.length; i++) {672 if ($scope.settings.variantGroupDocumentTypes[i] === content.contentTypeAlias) {673 rtn = true;674 break;675 }676 }677 return rtn;678 }679 function checkNodeNameFromFilter(content) {680 var rtn = $scope.settings.variantGroupNodeName.length === 0 || ($scope.settings.variantGroupNodeName.length === 1 && $scope.settings.variantGroupNodeName[0] === '');681 for (var i = 0; i < $scope.settings.variantGroupNodeName.length; i++) {682 if ($scope.settings.variantGroupNodeName[i] === content.name) {683 rtn = true;684 break;685 }686 }687 return rtn;688 }689 //Get all variant groups690 function getChildren(ent) {691 //Using the umbraco content resource we fetch all variant groups692 contentResource.getChildren(ent.id).then(function (data) {693 $scope.variantGroups = [];694 var variantGroups = jQuery(data.items),695 legalVariantGroups = [],696 answersReciewed = 0;697 //Check how many variant groups that is legal698 variantGroups.each(function (i) {699 var variantGroup = this;700 //Run the variant group through the filters from the settings701 if (checkDocumentTypeFromFilter(variantGroup) && checkNodeNameFromFilter(variantGroup)) {702 legalVariantGroups.push(variantGroup);703 }704 });705 var endCount = legalVariantGroups.length;706 //Run through each variant groups707 variantGroups.each(function (i) {708 var variantGroup = this;709 variantGroup.label = variantGroup.name;710 711 //Get all variant types for the variant group712 contentResource.getChildren(variantGroup.id, $scope.options).then(function (data) {713 //The items is the variant types714 variantGroup.items = data.items;715 //Set the open state of the variant group716 var savedOpenOptions = $scope.model.value.variantGroupsOpen[variantGroup.id];717 variantGroup.open = savedOpenOptions === undefined ? $scope.variantGroupsOpen : savedOpenOptions;718 //Add to the set of variant groups719 $scope.variantGroups.push(variantGroup);720 answersReciewed++;721 if (answersReciewed === endCount) {722 //After the last answer from the server have been recieved var ready the variant scaffolding723 readyVariantScaffolding();724 }725 });726 727 });728 });729 }730 $scope.setOrder(0);731 readyScaffolding();732 function guid() {733 function s4() {734 return Math.floor((1 + Math.random()) * 0x10000)735 .toString(16)736 .substring(1);737 }738 return s4() + s4() + '-' + s4() + '-' + s4() + '-' +739 s4() + '-' + s4() + s4() + s4();740 }741 // Array Remove - By John Resig (MIT Licensed)742 function removeFromArray(arr, from, to) {743 var rest = arr.slice((to || from) + 1 || arr.length);744 arr.length = from < 0 ? arr.length + from : from;745 return arr.push.apply(arr, rest);746 };747 // Array Remove - By John Resig (MIT Licensed)748 function splitString(str, delimiter) {749 if (!str) {750 return [];751 }752 var arr = str.split(',');753 for (var i = 0; i < arr.length; i++) {754 arr[i] = arr[i].trim();755 }756 return arr;757 };...

Full Screen

Full Screen

variantList.js

Source:variantList.js Github

copy

Full Screen

1import React, { Component } from "react";2import PropTypes from "prop-types";3import { Session } from "meteor/session";4import { Meteor } from "meteor/meteor";5import { composeWithTracker, Components } from "@reactioncommerce/reaction-components";6import { Catalog, ReactionProduct } from "/lib/api";7import { Reaction, i18next } from "/client/api";8import { getChildVariants } from "../selectors/variants";9import { Products } from "/lib/collections";10import update from "immutability-helper";11import { getVariantIds } from "/lib/selectors/variants";12import { Media } from "/imports/plugins/core/files/client";13function variantIsSelected(variantId) {14 const current = ReactionProduct.selectedVariant();15 if (16 current &&17 typeof current === "object" &&18 (variantId === current._id || current.ancestors.indexOf(variantId) >= 0)19 ) {20 return true;21 }22 return false;23}24function variantIsInActionView(variantId) {25 const actionViewVariant = Reaction.getActionView().data;26 if (actionViewVariant) {27 // Check if the variant is selected, and also visible & selected in the action view28 return variantIsSelected(variantId) && variantIsSelected(actionViewVariant._id) && Reaction.isActionViewOpen();29 }30 return false;31}32function getTopVariants() {33 let inventoryTotal = 0;34 const variants = ReactionProduct.getTopVariants();35 if (variants.length) {36 // calculate inventory total for all variants37 for (const variant of variants) {38 if (variant.inventoryManagement) {39 const qty = ReactionProduct.getVariantQuantity(variant);40 if (typeof qty === "number") {41 inventoryTotal += qty;42 }43 }44 }45 // calculate percentage of total inventory of this product46 for (const variant of variants) {47 const qty = ReactionProduct.getVariantQuantity(variant);48 variant.inventoryTotal = inventoryTotal;49 if (variant.inventoryManagement && inventoryTotal) {50 variant.inventoryPercentage = parseInt(qty / inventoryTotal * 100, 10);51 } else {52 // for cases when sellers doesn't use inventory we should always show53 // "green" progress bar54 variant.inventoryPercentage = 100;55 }56 if (variant.title) {57 variant.inventoryWidth = parseInt(variant.inventoryPercentage - variant.title.length, 10);58 } else {59 variant.inventoryWidth = 0;60 }61 }62 // sort variants in correct order63 variants.sort((a, b) => a.index - b.index);64 return variants;65 }66 return [];67}68function isSoldOut(variant) {69 return ReactionProduct.getVariantQuantity(variant) < 1;70}71class VariantListContainer extends Component {72 componentWillReceiveProps() {73 this.setState({});74 }75 get variants() {76 return (this.state && this.state.variants) || this.props.variants;77 }78 get productHandle() {79 const selectedProduct = ReactionProduct.selectedProduct();80 return (selectedProduct.__published && selectedProduct.__published.handle) || selectedProduct.handle;81 }82 handleCreateVariant = () => {83 const selectedProduct = ReactionProduct.selectedProduct();84 Meteor.call("products/createVariant", selectedProduct._id, (error) => {85 if (error) {86 Alerts.alert({87 text: i18next.t("productDetailEdit.addVariantFail", { title: selectedProduct.title }),88 confirmButtonText: i18next.t("app.close", { defaultValue: "Close" })89 });90 }91 });92 };93 handleVariantClick = (event, variant, ancestors = -1) => {94 this.handleEditVariant(event, variant, ancestors);95 };96 handleEditVariant = (event, variant, ancestors = -1) => {97 let editVariant = variant;98 if (ancestors >= 0) {99 editVariant = Products.findOne(variant.ancestors[ancestors]);100 }101 const cardName = `variant-${variant._id}`;102 Reaction.state.set("edit/focus", cardName);103 ReactionProduct.setCurrentVariant(variant._id);104 Session.set(`variant-form-${editVariant._id}`, true);105 if (Reaction.hasPermission("createProduct") && !Reaction.isPreview()) {106 Reaction.showActionView({107 label: "Edit Variant",108 i18nKeyLabel: "productDetailEdit.editVariant",109 template: "variantForm",110 data: editVariant111 });112 }113 // Prevent the default edit button `onEditButtonClick` function from running114 return false;115 };116 handleVariantVisibilityToggle = (event, variant, variantIsVisible) => {117 Meteor.call("products/updateProductField", variant._id, "isVisible", variantIsVisible);118 };119 handleMoveVariant = (dragIndex, hoverIndex) => {120 const variant = this.props.variants[dragIndex];121 // Apply new sort order to variant list122 const newVariantOrder = update(this.props.variants, {123 $splice: [[dragIndex, 1], [hoverIndex, 0, variant]]124 });125 // Set local state so the component does't have to wait for a round-trip126 // to the server to get the updated list of variants127 this.setState({128 variants: newVariantOrder129 });130 // Save the updated positions131 Meteor.defer(() => {132 Meteor.call("products/updateVariantsPosition", getVariantIds(newVariantOrder));133 });134 };135 render() {136 return (137 <Components.DragDropProvider>138 <Components.VariantList139 onEditVariant={this.handleEditVariant}140 onMoveVariant={this.handleMoveVariant}141 onVariantClick={this.handleVariantClick}142 onVariantVisibiltyToggle={this.handleVariantVisibilityToggle}143 onCreateVariant={this.handleCreateVariant}144 {...this.props}145 variants={this.variants}146 />147 </Components.DragDropProvider>148 );149 }150}151function composer(props, onData) {152 let childVariantMedia = [];153 const childVariants = getChildVariants();154 if (Array.isArray(childVariants)) {155 childVariantMedia = Media.findLocal(156 {157 "metadata.variantId": {158 $in: getVariantIds(childVariants)159 }160 },161 {162 sort: {163 "metadata.priority": 1164 }165 }166 );167 }168 let editable;169 if (Reaction.isPreview() === true) {170 editable = false;171 } else {172 editable = Reaction.hasPermission(["createProduct"]);173 }174 onData(null, {175 variants: getTopVariants(),176 variantIsSelected,177 variantIsInActionView,178 childVariants,179 childVariantMedia,180 displayPrice: (variantId) => Catalog.getVariantPriceRange(variantId),181 isSoldOut,182 editable183 });184}185VariantListContainer.propTypes = {186 variants: PropTypes.arrayOf(PropTypes.object)187};...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var options = {3 videoParams: {4 }5};6var test = new wpt('www.webpagetest.org', options.key);7test.runTest(testURL, options, function(err, data) {8 if (err) return console.error(err);9 console.log('Test status:', data.statusText);10 if (data.statusCode === 200) {11 console.log('Test completed:', data.data.summary);12 }13});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = wpt('www.webpagetest.org');3 if(err) {4 console.log(err);5 } else {6 console.log(data);7 }8});9var wpt = require('webpagetest');10var test = wpt('www.webpagetest.org');11 .then(function(data) {12 console.log(data);13 })14 .catch(function(err) {15 console.log(err);16 });17var wpt = require('webpagetest');18var test = wpt('www.webpagetest.org');19async function runTest() {20 try {21 console.log(data);22 } catch(err) {23 console.log(err);24 }25}26runTest();27### `wpt(apiKey, options)`28var wpt = require('webpagetest');29var test = wpt('www.webpagetest.org');30### `wpt.runTest(url, options, callback)`31var wpt = require('webpagetest');32var test = wpt('www.webpagetest.org');33 if(err) {34 console.log(err);35 } else {36 console.log(data);37 }38});39### `wpt.getTestResults(testId

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var wpt = new WebPageTest('www.webpagetest.org');3var location = 'Dulles:Chrome';4var options = {5};6wpt.runTest(url, options, function(err, data) {7 if (err) return console.error(err);8 console.log('Test submitted successfully. View your test at: %s', data.data.userUrl);9 wpt.getTestResults(data.data.testId, function(err, data) {10 if (err) return console.error(err);11 console.log('Test completed successfully. Results: %s', data.data.summary);12 });13});14var wpt = require('webpagetest');15var wpt = new WebPageTest('www.webpagetest.org');16var location = 'Dulles:Chrome';17var options = {18};19wpt.runTest(url, options)20 .then(function(data) {21 console.log('Test submitted successfully. View your test at: %s', data.data.userUrl);22 return wpt.getTestResults(data.data.testId);23 })24 .then(function(data) {25 console.log('Test completed successfully. Results: %s', data.data.summary);26 })27 .catch(function(err) {28 console.error(err);29 });30var wpt = require('webpagetest');31var wpt = new WebPageTest('www.webpagetest.org');32var location = 'Dulles:Chrome';33var options = {34};35async function runTest() {36 try {37 var data = await wpt.runTest(url, options);38 console.log('Test submitted successfully. View your test at: %s', data.data.userUrl);39 var data = await wpt.getTestResults(data.data.testId);40 console.log('Test completed successfully. Results: %

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var client = wpt('www.webpagetest.org');3client.runTest('www.google.com', {4}, function(err, data) {5 if (err) return console.error(err);6 console.log(data);7});8var wpt = require('webpagetest');9var client = wpt('www.webpagetest.org');10client.runTest('www.google.com', {11}, function(err, data) {12 if (err) return console.error(err);13 console.log(data);14});15var wpt = require('webpagetest');16var client = wpt('www.webpagetest.org');17client.runTest('www.google.com', {18}, function(err, data) {19 if (err) return console.error(err);20 console.log(data);21});22var wpt = require('webpagetest');23var client = wpt('www.webpagetest.org');24client.runTest('www.google.com', {25}, function(err, data) {26 if (err) return console.error(err);27 console.log(data);28});29var wpt = require('webpagetest');30var client = wpt('www.webpagetest.org');31client.runTest('www.google.com', {32}, function(err, data) {33 if (err) return

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var api = new wpt('www.webpagetest.org', 'A.2c0e2a2c0e2a2c0e2a2c0e2a2c0e2a2c');3 if (err) return console.error(err);4 console.log(data);5 api.getTestResults(data.data.testId, function(err, data) {6 if (err) return console.error(err);7 console.log(data);8 });9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var test = new wpt('www.webpagetest.org', 'A.6d7a6f0b8b7f0d1c1d1f1c1d1e2a2b2e');3 if (err) {4 console.log('Error: ' + err.message);5 } else {6 console.log('Test status: ' + data.statusText);7 console.log('Test results: ' + data.data.summary);8 }9});10var wpt = require('webpagetest');11var test = new wpt('www.webpagetest.org', 'A.6d7a6f0b8b7f0d1c1d1f1c1d1e2a2b2e');12 .then(function(data) {13 console.log('Test status: ' + data.statusText);14 console.log('Test results: ' + data.data.summary);15 })16 .catch(function(err) {17 console.log('Error: ' + err.message);18 });19var wpt = require('webpagetest');20var test = new wpt('www.webpagetest.org', 'A.6d7a6f0b8b7f0d1c1d1f1c1d1e2a2b2e');21 .then(function(data) {22 console.log('Test status: ' + data.statusText);23 console.log('Test results: ' + data.data.summary);24 })25 .catch(function(err) {26 console.log('Error: ' + err.message);27 });28var wpt = require('webpagetest');29var test = new wpt('

Full Screen

Using AI Code Generation

copy

Full Screen

1var wpt = require('webpagetest');2var options = {3};4var WebPageTest = new wpt('www.webpagetest.org', options.key);5var testOptions = {6 videoParams: {7 }8};9WebPageTest.runTest(testUrl, testOptions, function (err, data) {10 if (err) {11 console.log(err);12 } else {13 console.log(data);14 }15});

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful