All files / src/features/experiments/components/guided-setup GuidedSetupWizard.vue

97.05% Statements 231/238
77.58% Branches 135/174
98.07% Functions 51/52
97.69% Lines 212/217

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703                                                                                                                                                                                                                                                              2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                               121x                                                                         166x     160x 137x   23x 13x   10x 6x   4x 4x                     166x 147x   19x 8x   11x 1x   10x 18x   10x 1x   17x 17x 17x 9x 2x   7x     20x 37x         121x     121x         241x                 44x 44x         4x 4x           122x 3x             121x 121x 121x   121x 121x 2x 119x 119x         3x 3x 1x 2x 1x   3x     5x     8x 3x 1x       7x 2x 1x       6x 1x 1x       5x 1x 1x       4x 3x 3x       3x 2x 2x 2x 2x 2x   2x       2x 2x 2x       1x     1x 1x     1x     1x         1x 1x 1x 1x     1x 1x   1x 1x     1x               1x   1x 1x     6x 6x 2x   6x 2x   6x 6x     4x 4x 2x   4x 4x     5x 5x 2x   5x 5x     9x 9x 1x   9x 3x   9x 4x   9x 5x   9x 6x 3x       1x 2x           9x 9x     17x   17x 2x 2x 2x     15x 28x   15x 1x 1x 1x     14x 26x   14x 2x 2x 2x     12x 1x 1x 1x     22x 11x 22x   11x 1x 1x 1x     20x 10x 20x   10x 20x   10x 20x     10x 1x 9x 1x 8x 1x 7x 1x     10x 10x     14x 5x 1x 1x 1x 1x   4x 4x 3x       58x 11x           10x                     5x     5x   5x                                                         5x             4x 10x     5x   10x       1x     5x 5x 5x 5x                                                       5x     129x                                                                                                                          
<template>
  <FormSlideout
    id="guided-setup-wizard"
    ref="slideoutRef"
    title="Guided Experiment Setup"
    submit-button-text="Create Experiment"
    cancel-button-text="Cancel"
    reset-button-text=""
    :show-reset-button="false"
    :show-footer="currentStep === 5"
    :use-sections="false"
    :fields="[]"
    width="50vw"
    :loading="isCreating"
    :disable-submit="!canSubmit"
    @submit="handleSubmit"
    @cancel="handleCancel"
    @close="handleClose"
  >
    <template #form-content>
      <div class="wizard-container">
        <div class="wizard-progress margin-bottom-l">
          <ProgressBar
            :value="progressValue"
            :bar-type="'multistep'"
            :steps="stepLabels"
            :current-step="currentStep"
          />
        </div>
 
        <div class="wizard-content">
          <WizardStep1Setup
            v-show="currentStep === 1"
            :form-data="formData"
            @update:setup-method="handleSetupMethodUpdate"
            @update:environment="handleEnvironmentUpdate"
          />
 
          <WizardStep2Target
            v-show="currentStep === 2"
            ref="targetSetupRef"
            :form-data="formData"
            :validation-errors="validationErrors"
            @update:target="handleTargetUpdate"
            @update:target-choice="handleTargetChoiceUpdate"
            @open:target-form="openTargetForm"
            @open:target-form-template="openTargetFormFromTemplate"
          />
 
          <WizardStep3Experiment
            v-show="currentStep === 3"
            :form-data="formData"
            :validation-errors="validationErrors"
            @update:field="handleFieldUpdate"
          />
 
          <WizardStep4Details
            v-show="currentStep === 4"
            :form-data="formData"
            :validation-errors="validationErrors"
            :max-end-date="maxEndDate"
            @update:field="handleFieldUpdate"
          />
 
          <WizardStep5Recipes
            v-show="currentStep === 5"
            :form-data="formData"
            :validation-errors="validationErrors"
            @update:field="handleFieldUpdate"
            @add:recipe="handleAddRecipe"
            @remove:recipe="handleRemoveRecipe"
            @update:recipe="handleUpdateRecipe"
          />
        </div>
 
        <div
          v-if="currentStep < 5"
          class="wizard-navigation margin-top-l"
        >
          <div class="nav-left">
            <Button
              v-if="currentStep > 1"
              variant="secondary"
              @click="previousStep"
            >
              Back
            </Button>
          </div>
          <div class="nav-right">
            <Button
              variant="secondary"
              class="cancel-nav-button"
              @click="handleCancel"
            >
              Cancel
            </Button>
            <Button
              variant="primary"
              :disabled="!canGoNext"
              @click="nextStep"
            >
              Next
            </Button>
          </div>
        </div>
      </div>
    </template>
 
    <template #footer-prepend>
      <Button
        v-if="currentStep === 5"
        variant="secondary"
        class="footer-back-button"
        @click="previousStep"
      >
        Back
      </Button>
    </template>
  </FormSlideout>
 
  <TargetFormSlideout
    ref="targetFormSlideoutRef"
    @submit="handleTargetCreated"
  />
</template>
 
<script>
import Button from '@atomic-ui/button';
import ProgressBar from '@atomic-ui/progressBar';
import $http from '@common-vue/util/src/modules/http';
import FormSlideout from '../../../../components/FormSlideout';
import { AUTH_FQ, EXP_FQ } from '../../../../store/types';
import { getDefaultEnvironment } from '../../../../utils/environmentHelper';
import TargetFormSlideout from '../../../targets/components/TargetFormSlideout';
import { getMaxEndDate } from '../../utils/experimentEndDateLimit';
import WizardStep1Setup from './WizardStep1Setup';
import WizardStep2Target from './WizardStep2Target';
import WizardStep3Experiment from './WizardStep3Experiment';
import WizardStep4Details from './WizardStep4Details';
import WizardStep5Recipes from './WizardStep5Recipes';I
 
export default {
  name: 'GuidedSetupWizard',
  components: {
    Button,
    ProgressBar,
    FormSlideout,
    TargetFormSlideout,
    WizardStep1Setup,
    WizardStep2Target,
    WizardStep3Experiment,
    WizardStep4Details,
    WizardStep5Recipes,
  },
  data() {
    return {
      currentStep: 1,
      stepLabels: ['Setup', 'Target', 'Experiment', 'Details', 'Recipes'],
      formData: {
        setupMethod: null,
        targetChoice: null,
        targetId: null,
        targetName: null,
        env: null,
        pdmMail: '',
        goal: '',
        notificationRecipients: [],
        mvpName: '',
        mvpNumber: '',
        domainId: null,
        experimentType: 'clientSide',
        name: '',
        description: '',
        confluenceLink: '',
        startDate: null,
        endDate: null,
        adobeAutoTagging: true,
        additionalQualificationRequired: false,
        version: '',
        includedEnvironments: '',
        includeAllEnvironments: true,
        recipes: [],
        salt: this.generateSalt(),
        allowSwitchRecipes: false,
        isActive: false,
      },
      validationErrors: {},
      isCreating: false,
    };
  },
  computed: {
    progressValue() {
      return (this.currentStep / 5) * 100;
    },
    canGoNext() {
      if (this.currentStep === 1) {
        return !!(this.formData.setupMethod && this.formData.env);
      }
      if (this.currentStep === 2) {
        return !!this.formData.targetId;
      }
      if (this.currentStep === 3) {
        return !!this.formData.domainId;
      }
      if (this.currentStep === 4) {
        return !!(
          this.formData.experimentType
          && this.formData.name
          && this.formData.description
          && this.formData.startDate
          && this.formData.endDate
        );
      }
      return true;
    },
    canSubmit() {
      if (this.currentStep !== 5) {
        return false;
      }
      if (this.formData.recipes.length === 0) {
        return false;
      }
      if (this.totalWeight !== 100) {
        return false;
      }
      const hasEmptyNames = this.formData.recipes.some(
        (r) => !r.name || !r.name.trim(),
      );
      if (hasEmptyNames) {
        return false;
      }
      const recipeTypes = this.formData.recipes.map((r) => r.recipeType);
      const controlCount = recipeTypes.filter((t) => t === 'Control').length;
      const treatmentCount = recipeTypes.filter((t) => t === 'Treatment').length;
      if (controlCount !== 1 || treatmentCount < 1) {
        return false;
      }
      return true;
    },
    totalWeight() {
      return this.formData.recipes.reduce(
        (sum, recipe) => sum + (recipe.weight || 0),
        0,
      );
    },
    userRoles() {
      return this.$store.getters[AUTH_FQ.getters.roles] || [];
    },
    endDateCapEnabled() {
      return (
        this.$store.getters.pageData?.killswitches?.endDateCapEnabled === true
      );
    },
    maxEndDate() {
      return getMaxEndDate({
        env: this.formData.env,
        userRoles: this.userRoles,
        recipes: this.formData.recipes,
        enabled: this.endDateCapEnabled,
      });
    },
  },
  watch: {
    currentStep(newStep) {
      if (
        newStep === 2
        && this.formData.setupMethod === 'reuseExisting'
        && this.formData.env
      ) {
        this.$nextTick(() => {
          this.$refs.targetSetupRef?.loadTargets(this.formData.env);
        });
      }
    },
    '$route.query.env': {
      handler(newEnv) {
        if (newEnv) {
          this.formData.env = newEnv;
        }
      },
      immediate: true,
    },
  },
  mounted() {
    const user = this.$store.getters['auth/user'];
    const userEmail = user?.email || user?.mail || '';
    this.formData.pdmMail = userEmail;
 
    const envFromUrl = this.$route?.query?.env;
    if (envFromUrl) {
      this.formData.env = envFromUrl;
    } else if (!this.formData.env) {
      this.formData.env = getDefaultEnvironment();
    }
  },
  methods: {
    open() {
      const envFromUrl = this.$route?.query?.env;
      if (envFromUrl) {
        this.formData.env = envFromUrl;
      } else if (!this.formData.env) {
        this.formData.env = getDefaultEnvironment();
      }
      this.$store.commit('slideoutStore/TOGGLE', 'guided-setup-wizard');
    },
    closeSlideout() {
      this.$store.commit('slideoutStore/TOGGLE', 'guided-setup-wizard');
    },
    nextStep() {
      if (this.currentStep === 1) {
        if (!this.validateStep1()) {
          return;
        }
      }
 
      if (this.currentStep === 2) {
        if (!this.validateStep2()) {
          return;
        }
      }
 
      if (this.currentStep === 3) {
        if (!this.validateStep3()) {
          return;
        }
      }
 
      if (this.currentStep === 4) {
        if (!this.validateStep4()) {
          return;
        }
      }
 
      if (this.currentStep < 5) {
        this.validationErrors = {};
        this.currentStep++;
      }
    },
    previousStep() {
      if (this.currentStep > 1) {
        if (this.currentStep === 2) {
          this.formData.targetChoice = null;
          this.formData.targetId = null;
          this.formData.targetName = null;
          this.$refs.targetSetupRef?.resetTargetChoice();
        }
        this.currentStep--;
      }
    },
    handleSetupMethodUpdate(method) {
      this.formData.setupMethod = method;
      if (method === 'reuseExisting') {
        this.formData.targetChoice = null;
      }
    },
    handleEnvironmentUpdate(env) {
      this.formData.env = env;
    },
    handleTargetChoiceUpdate(choice) {
      this.formData.targetChoice = choice;
      this.formData.targetId = null;
    },
    openTargetForm() {
      this.$refs.targetFormSlideoutRef?.openCreate(this.formData.env);
    },
    openTargetFormFromTemplate(template) {
      this.$refs.targetFormSlideoutRef?.openFromTemplate(
        template,
        this.formData.env,
      );
    },
    handleTargetCreated({ data }) {
      this.formData.targetId = data.id;
      this.formData.targetName = data.name;
      this.nextStep();
    },
    handleTargetUpdate(target) {
      this.formData.targetId = target.id;
      this.formData.targetName = target.name;
    },
    handleFieldUpdate({ field, value }) {
      this.formData[field] = value;
    },
    handleAddRecipe() {
      this.formData.recipes.push({
        name: '',
        description: '',
        recipeType: 'Control',
        weight: 0,
      });
    },
    handleRemoveRecipe(index) {
      this.formData.recipes.splice(index, 1);
    },
    handleUpdateRecipe({ index, field, value }) {
      this.formData.recipes[index][field] = value;
    },
    validateStep1() {
      const errors = {};
      if (!this.formData.env) {
        errors.env = 'Environment is required';
      }
      if (!this.formData.setupMethod) {
        errors.setupMethod = 'Please select a setup method';
      }
      this.validationErrors = errors;
      return Object.keys(errors).length === 0;
    },
    validateStep2() {
      const errors = {};
      if (!this.formData.targetId) {
        errors.target = 'Please select or create a target';
      }
      this.validationErrors = errors;
      return Object.keys(errors).length === 0;
    },
    validateStep3() {
      const errors = {};
      if (!this.formData.domainId) {
        errors.domainId = 'Domain is required';
      }
      this.validationErrors = errors;
      return Object.keys(errors).length === 0;
    },
    validateStep4() {
      const errors = {};
      if (!this.formData.experimentType) {
        errors.experimentType = 'Experiment Type is required';
      }
      if (!this.formData.name) {
        errors.name = 'Experiment Name is required';
      }
      if (!this.formData.description) {
        errors.description = 'Experiment Description is required';
      }
      if (!this.formData.startDate) {
        errors.startDate = 'Start Date is required';
      }
      if (!this.formData.endDate) {
        errors.endDate = 'End Date is required';
      } else if (
        this.formData.startDate
        && this.formData.endDate < this.formData.startDate
      ) {
        errors.endDate = 'End Date must be after Start Date';
      } else Iif (
        this.maxEndDate
        && new Date(this.formData.endDate) > this.maxEndDate
      ) {
        errors.endDate = 'For fully ramped-up production experiments, end date cannot exceed 6 weeks from today.';
      }
      this.validationErrors = errors;
      return Object.keys(errors).length === 0;
    },
    validateStep5() {
      const errors = {};
 
      if (this.formData.recipes.length === 0) {
        errors.recipes = 'At least one recipe is required';
        this.validationErrors = errors;
        return false;
      }
 
      const emptyRecipes = this.formData.recipes.filter(
        (r) => !r.name || !r.name.trim(),
      );
      if (emptyRecipes.length > 0) {
        errors.recipes = 'All recipes must have a name';
        this.validationErrors = errors;
        return false;
      }
 
      const invalidWeights = this.formData.recipes.some(
        (r) => r.weight < 0 || r.weight > 100,
      );
      if (invalidWeights) {
        errors.recipes = 'Each recipe weight must be between 0 and 100';
        this.validationErrors = errors;
        return false;
      }
 
      if (this.totalWeight !== 100) {
        errors.recipes = `Total recipe weight must equal 100 (current: ${this.totalWeight})`;
        this.validationErrors = errors;
        return false;
      }
 
      const recipeNames = this.formData.recipes.map((r) => r.name);
      const duplicateNames = recipeNames.filter(
        (name, index) => recipeNames.indexOf(name) !== index,
      );
      if (duplicateNames.length > 0) {
        errors.recipes = `Recipe names must be unique. Duplicate found: ${duplicateNames[0]}`;
        this.validationErrors = errors;
        return false;
      }
 
      const recipeTypes = this.formData.recipes.map((r) => r.recipeType);
      const controlCount = recipeTypes.filter(
        (type) => type === 'Control',
      ).length;
      const controlHoldOutCount = recipeTypes.filter(
        (type) => type === 'ControlHoldOut',
      ).length;
      const treatmentCount = recipeTypes.filter(
        (type) => type === 'Treatment',
      ).length;
 
      if (controlCount > 1) {
        errors.recipes = 'Only one Control recipe is allowed';
      } else if (controlHoldOutCount > 1) {
        errors.recipes = 'Only one Control Hold Out recipe is allowed';
      } else if (controlCount === 0) {
        errors.recipes = 'At least one Control recipe is required';
      } else if (treatmentCount === 0) {
        errors.recipes = 'At least one Treatment recipe is required';
      }
 
      this.validationErrors = errors;
      return Object.keys(errors).length === 0;
    },
    formatDateToISO(date) {
      if (!date) return null;
      if (date instanceof Date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}T00:00:00`;
      }
      if (typeof date === 'string') {
        if (date.includes('T')) return date;
        return `${date}T00:00:00`;
      }
      return null;
    },
    async handleSubmit() {
      if (!this.validateStep5()) {
        return;
      }
      if (
        this.maxEndDate
        && this.formData.endDate
        && new Date(this.formData.endDate) > this.maxEndDate
      ) {
        this.validationErrors = {
          ...this.validationErrors,
          endDate:
            'For fully ramped-up production experiments, end date cannot exceed 6 weeks from today.',
        };
        this.currentStep = 4;
        return;
      }
 
      this.isCreating = true;
 
      try {
        const { targetId } = this.formData;
 
        const experimentData = {
          env: this.formData.env,
          pdmMail: this.formData.pdmMail,
          goal: this.formData.goal || null,
          emailDistro: this.formData.notificationRecipients,
          mvpName: this.formData.mvpName,
          mvpNumber: this.formData.mvpNumber,
          domainId: parseInt(this.formData.domainId, 10),
          experimentType: this.formData.experimentType,
          name: this.formData.name,
          description: this.formData.description,
          campaignConfLink: this.formData.confluenceLink || null,
          startDate: this.formatDateToISO(this.formData.startDate),
          endDate: this.formatDateToISO(this.formData.endDate),
          adobeAutoTagging: this.formData.adobeAutoTagging,
          additionalQualificatioRequired:
            this.formData.additionalQualificationRequired,
          version: this.formData.version || null,
          includedEnvironments: this.formData.includeAllEnvironments
            ? 'all'
            : this.formData.includedEnvironments || null,
          excludedEnvironments: null,
          targetIds: [targetId],
          recipes: this.formData.recipes,
          salt: this.formData.salt,
          allowSwitchRecipes: this.formData.allowSwitchRecipes ? 1 : 0,
          isActive: this.formData.isActive,
          isArchived: false,
          affectedPageType: 'All',
        };
 
        await this.$store.dispatch(EXP_FQ.actions.create, {
          api: $http,
          experimentData,
        });
 
        this.$emit('experiment-created');
        this.closeSlideout();
      } catch (error) {
        // eslint-disable-next-line no-unused-vars
        const ignoredError = error;
      } finally {
        this.isCreating = false;
      }
    },
    handleCancel() {
      this.closeSlideout();
    },
    handleClose() {
      this.currentStep = 1;
      const user = this.$store.getters['auth/user'];
      const userEmail = user?.email || user?.mail || '';
      this.formData = {
        setupMethod: null,
        targetChoice: null,
        targetId: null,
        targetName: null,
        env: null,
        pdmMail: userEmail,
        goal: '',
        notificationRecipients: [],
        mvpName: '',
        mvpNumber: '',
        domainId: null,
        experimentType: 'clientSide',
        name: '',
        description: '',
        confluenceLink: '',
        startDate: null,
        endDate: null,
        adobeAutoTagging: true,
        additionalQualificationRequired: false,
        version: '',
        includedEnvironments: '',
        includeAllEnvironments: true,
        recipes: [],
        salt: this.generateSalt(),
        allowSwitchRecipes: false,
        isActive: false,
      };
      this.validationErrors = {};
    },
    generateSalt() {
      return `exp_${Date.now()}_${Math.random().toString(36).substring(2, 15)}`;
    },
  },
};
</script>
 
<style scoped lang="scss">
.wizard-container {
  padding: 1rem;
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 200px);
}
 
.wizard-progress {
  margin-top: -0.5rem;
  margin-bottom: 2rem;
}
 
.wizard-content {
  flex: 1;
  min-height: 400px;
  padding-bottom: 20px;
}
 
.wizard-navigation {
  position: sticky;
  bottom: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  margin: 0 -1rem -1rem -1rem;
  border-top: 1px solid #e0e0e0;
  background-color: white;
  z-index: 10;
}
 
.nav-left,
.nav-right {
  display: flex;
  gap: 0.75rem;
}
 
.cancel-nav-button.button {
  background-color: #c62828;
  color: white;
 
  &:hover:not(:disabled) {
    background-color: #b71c1c;
  }
 
  &:active {
    background-color: #a31919;
  }
}
 
.footer-back-button {
  margin-right: auto;
}
</style>