/** * External dependencies */ import type { Goal, GoalId, ECommercePlugin, Experiment, ExperimentId, Maybe, } from '@nab/types'; /** * Internal dependencies */ import { State } from '../types'; export function getExperiment( state: State, key?: ExperimentId ): Maybe< Experiment > { return key ? state.experiments[ key ] : undefined; } export type GetExperimentAttributeFunction = < K extends keyof Experiment >( key: ExperimentId, attribute: K ) => Maybe< Experiment[ K ] >; type GetExperimentAttribute = typeof _getExperimentAttribute & { CurriedSignature: < K extends keyof Experiment >( key: ExperimentId, attribute: K ) => Maybe< Experiment[ K ] >; }; export const getExperimentAttribute = _getExperimentAttribute as GetExperimentAttribute; function _getExperimentAttribute< K extends keyof Experiment >( state: State, key: ExperimentId, attribute: K ): Maybe< Experiment[ K ] > { const experiment = getExperiment( state, key ); if ( ! experiment ) { return; } return experiment[ attribute ]; } export function getDefaultGoal( state: State, key: ExperimentId ): Maybe< Goal > { const experiment = getExperiment( state, key ); if ( ! experiment ) { return; } return experiment.goals[ 0 ]; } export function getECommercePlugin( state: State, key: ExperimentId, goalId?: GoalId ): Maybe< ECommercePlugin > { if ( isWooCommerceGoal( state, key, goalId ) ) { return 'woocommerce'; } if ( isEddGoal( state, key, goalId ) ) { return 'edd'; } return undefined; } // ======== // INTERNAL // ======== function isWooCommerceGoal( state: State, key: ExperimentId, goalId?: GoalId ): boolean { const experiment = getExperiment( state, key ); if ( ! experiment ) { return false; } goalId = goalId ?? getDefaultGoal( state, key )?.id; const goal = experiment.goals.find( ( g ) => g.id === goalId ); if ( ! goal ) { return false; } const actions = goal?.conversionActions ?? []; return ( 0 < actions.length && actions.every( ( { type } ) => type === 'nab/wc-order' ) ); } function isEddGoal( state: State, key: ExperimentId, goalId?: GoalId ): boolean { const experiment = getExperiment( state, key ); if ( ! experiment ) { return false; } goalId = goalId ?? getDefaultGoal( state, key )?.id; const goal = experiment.goals.find( ( g ) => g.id === goalId ); if ( ! goal ) { return false; } const actions = goal?.conversionActions ?? []; return ( 0 < actions.length && actions.every( ( { type } ) => type === 'nab/edd-order' ) ); }