Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

project type config simplified #1539

Merged
merged 3 commits into from
Oct 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -85,42 +85,92 @@ function reverseDeliveryRemap(data, t) {
let currentCycleIndex = null;
let currentCycle = null;

// data.forEach((item, index) => {
// if (currentCycleIndex !== item.cycleNumber) {
// currentCycleIndex = item.cycleNumber;
// currentCycle = {
// cycleIndex: currentCycleIndex.toString(),
// startDate: item?.startDate ? Digit.Utils.date.convertEpochToDate(item?.startDate) : null,
// endDate: item?.endDate ? Digit.Utils.date.convertEpochToDate(item?.endDate) : null,
// active: index === 0, // Initialize active to false
// deliveries: [],
// };
// reversedData.push(currentCycle);
// }
const operatorMapping = {
"<=": "LESS_THAN_EQUAL_TO",
">=": "GREATER_THAN_EQUAL_TO",
"<": "LESS_THAN",
">": "GREATER_THAN",
"==": "EQUAL_TO",
"!=": "NOT_EQUAL_TO",
IN_BETWEEN: "IN_BETWEEN",
};

// const deliveryIndex = item.deliveryNumber.toString();
const cycles = data?.[0]?.cycles || [];
const mapProductVariants = (productVariants) => {
return productVariants.map((variant, key) => ({
key: key + 1,
count: 1,
value: variant.productVariantId,
name: variant.name,
}));
};

// let delivery = currentCycle.deliveries.find((delivery) => delivery.deliveryIndex === deliveryIndex);
const parseConditionAndCreateRules = (condition, ruleKey, products) => {
const conditionParts = condition.split("and").map((part) => part.trim());
let rules = [];

conditionParts.forEach((part) => {
const parts = part.split(" ").filter(Boolean);
let attributes = [];

// Handle "IN_BETWEEN" operator
if (parts.length === 5 && (parts[1] === "<=" || parts[1] === "<") && (parts[3] === "<" || parts[3] === "<=")) {
const toValue = parts[0];
const fromValue = parts[4];
attributes.push({
key: 1,
operator: { code: operatorMapping["IN_BETWEEN"] },
attribute: { code: parts[2] },
fromValue,
toValue,
});
} else {

const match = part.match(/(.*?)\s*(<=|>=|<|>|==|!=)\s*(.*)/);
if (match) {
const attributeCode = match[1].trim();
const operatorSymbol = match[2].trim();
const value = match[3].trim();
attributes.push({
key: attributes.length + 1,
value,
operator: { code: operatorMapping[operatorSymbol] },
attribute: { code: attributeCode },
});
}
}
rules.push({
ruleKey: ruleKey + 1,
delivery: {},
products,
attributes,
});
});

// if (!delivery) {
// delivery = {
// deliveryIndex: deliveryIndex,
// active: item.deliveryNumber === 1, // Set active to true only for the first delivery
// deliveryRules: [],
// };
// currentCycle.deliveries.push(delivery);
// }
return rules;
};
const mapDoseCriteriaToDeliveryRules = (doseCriteria) => {
return doseCriteria?.flatMap((criteria, ruleKey) => {
const products = mapProductVariants(criteria.ProductVariants);
return parseConditionAndCreateRules(criteria.condition, ruleKey, products);
});
};

const mapDeliveries = (deliveries) => {
return deliveries?.map((delivery, deliveryIndex) => ({
active: true,
deliveryIndex: String(deliveryIndex + 1),
deliveryRules: mapDoseCriteriaToDeliveryRules(delivery.doseCriteria),
}));
};

// delivery.deliveryRules.push({
// ruleKey: item.deliveryRuleNumber,
// delivery: {},
// attributes: loopAndReturn(item.conditions, t),
// products: [...item.products],
// });
// });
return data;
const transformedCycles = cycles.map((cycle) => ({
active: true,
cycleIndex: String(cycle.id),
deliveries: mapDeliveries(cycle.deliveries),
}));

return reversedData;
return transformedCycles;
}

function boundaryDataGrp(boundaryData) {
Expand Down Expand Up @@ -272,18 +322,18 @@ const CampaignSummary = (props) => {
// }, [props?.props?.summaryErrors]);

useEffect(() => {
const fun = async () => {
let temp = await fetchcd(tenantId, projectId);
if (temp) {
await new Promise((resolve) => {
setStartDate(temp?.startDate);
setEndDate(temp?.endDate);
setCycles(temp?.additionalDetails?.projectType?.cycles);
resolve();
});
}
};
fun();
const fun = async () => {
let temp = await fetchcd(tenantId, projectId);
if (temp) {
await new Promise((resolve) => {
setStartDate(temp?.startDate);
setEndDate(temp?.endDate);
setCycles(temp?.additionalDetails?.projectType?.cycles);
resolve();
});
}
};
fun();
}, [projectId]);

const { isLoading, data, error, refetch } = Digit.Hooks.campaign.useSearchCampaign({
Expand All @@ -308,7 +358,7 @@ const CampaignSummary = (props) => {
const target = data?.[0]?.deliveryRules;
const boundaryData = boundaryDataGrp(data?.[0]?.boundaries);
const cycleData = reverseDeliveryRemap(target, t);
const hierarchyType= data?.[0]?.hierarchyType;
const hierarchyType = data?.[0]?.hierarchyType;
return {
cards: [
{
Expand Down Expand Up @@ -372,8 +422,8 @@ const CampaignSummary = (props) => {
{
name: `HIERARCHY_${index + 1}`,
type: "COMPONENT",
cardHeader: { value: `${t(( hierarchyType + "_" + item?.type).toUpperCase())}` , inlineStyles: { color : "#0B4B66" } },

cardHeader: { value: `${t((hierarchyType + "_" + item?.type).toUpperCase())}`, inlineStyles: { color: "#0B4B66" } },

// cardHeader: { value: t("item?.boundaries?.type") },
component: "BoundaryDetailsSummary",
Expand Down Expand Up @@ -406,17 +456,15 @@ const CampaignSummary = (props) => {
values: [
{
key: "CAMPAIGN_NO_OF_CYCLES",
value:
data?.[0]?.deliveryRules && data?.[0]?.deliveryRules.map((item) => item.cycleIndex)?.length > 0
? Math.max(...data?.[0]?.deliveryRules.map((item) => item.cycleIndex))
: t("CAMPAIGN_SUMMARY_NA"),
value: data?.[0]?.additionalDetails?.cycleData?.cycleConfgureDate?.cycle
? data?.[0]?.additionalDetails?.cycleData?.cycleConfgureDate?.cycle
: t("CAMPAIGN_SUMMARY_NA"),
},
{
key: "CAMPAIGN_NO_OF_DELIVERIES",
value:
data?.[0]?.deliveryRules && data?.[0]?.deliveryRules?.flatMap((rule) => rule?.deliveries?.map((delivery) => delivery?.deliveryIndex))?.length > 0
? Math.max(...data?.[0]?.deliveryRules?.flatMap((rule) => rule?.deliveries?.map((delivery) => delivery?.deliveryIndex)))
: t("CAMPAIGN_SUMMARY_NA"),
value: data?.[0]?.additionalDetails?.cycleData?.cycleConfgureDate?.deliveries
? data?.[0]?.additionalDetails?.cycleData?.cycleConfgureDate?.deliveries
: t("CAMPAIGN_SUMMARY_NA"),
},
],
},
Expand Down Expand Up @@ -626,31 +674,30 @@ const CampaignSummary = (props) => {

const updatedObject = { ...data };

useEffect(()=> {
useEffect(() => {
// Update startDate and endDate in the `data` object
updatedObject.data.startDate = startDate;
updatedObject.data.endDate = endDate;
updatedObject.cards[1].sections[0].values[2].value=Digit.Utils.date.convertEpochToDate(startDate);
updatedObject.cards[1].sections[0].values[3].value=Digit.Utils.date.convertEpochToDate(endDate);
updatedObject.data.startDate = startDate;
updatedObject.data.endDate = endDate;
updatedObject.cards[1].sections[0].values[2].value = Digit.Utils.date.convertEpochToDate(startDate);
updatedObject.cards[1].sections[0].values[3].value = Digit.Utils.date.convertEpochToDate(endDate);
}, [startDate, endDate]);

if(updatedObject?.cards?.[1]?.sections?.[0]?.values?.[0]?.value==t("MR-DN"))
{
if (updatedObject?.cards?.[1]?.sections?.[0]?.values?.[0]?.value == t("MR-DN")) {
updatedObject.cards.forEach((card) => {
if (card.name && card.name.startsWith("CYCLE_")) {
const cycleId = card.name.split("_")[1];
const cycleData = cycles.find((cycle) => cycle.id === cycleId);

if (cycleData) {
card.sections.forEach((section) => {
if (section.props && section.props.data) {
section.props.data.startDate = new Date(cycleData.startDate).toLocaleDateString('en-GB');
// section.props.data.startDate = Digit.Utils.date.convertEpochToDate(cycleData.startDate) || t("CAMPAIGN_SUMMARY_NA");
section.props.data.endDate = new Date(cycleData.endDate).toLocaleDateString('en-GB');
// section.props.data.startDate = Digit.Utils.date.convertEpochToDate(cycleData.endDate) || t("CAMPAIGN_SUMMARY_NA");
}
});
}
const cycleId = card.name.split("_")[1];
const cycleData = cycles.find((cycle) => cycle.id === cycleId);

if (cycleData) {
card.sections.forEach((section) => {
if (section.props && section.props.data) {
section.props.data.startDate = new Date(cycleData.startDate).toLocaleDateString("en-GB");
// section.props.data.startDate = Digit.Utils.date.convertEpochToDate(cycleData.startDate) || t("CAMPAIGN_SUMMARY_NA");
section.props.data.endDate = new Date(cycleData.endDate).toLocaleDateString("en-GB");
// section.props.data.startDate = Digit.Utils.date.convertEpochToDate(cycleData.endDate) || t("CAMPAIGN_SUMMARY_NA");
}
});
}
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ const CampaignUpdateSummary = (props) => {
},
cardHeader: { value: t("TARGET_DETAILS"), inlineStyles: { marginTop: 0, fontSize: "1.5rem" } },
cardSecondaryAction: noAction !== "false" && (
<div className="campaign-preview-edit-container" onClick={() => handleRedirect(2)}>
<div className="campaign-preview-edit-container" onClick={() => handleRedirect(4)}>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick (assertive)

Approve changes to handleRedirect function with a minor suggestion.

The updates to the handleRedirect function improve URL parameter handling using URLSearchParams. This approach is more robust and maintainable. However, consider extracting the URL parameter update logic into a separate function for better readability and reusability.

Consider refactoring the URL parameter update logic into a separate function:

const updateUrlParams = (params) => {
  const urlParams = new URLSearchParams(window.location.search);
  Object.entries(params).forEach(([key, value]) => urlParams.set(key, value));
  return `${window.location.pathname}?${urlParams.toString()}`;
};

const handleRedirect = (step, activeCycle) => {
  const params = { key: step, preview: false };
  if (activeCycle) params.activeCycle = activeCycle;
  const newUrl = updateUrlParams(params);
  history.push(newUrl);
};

This refactoring improves code organization and makes it easier to update URL parameters consistently across the component.

Also applies to: 237-237, 257-257

🧰 Tools
🪛 Biome

[error] 217-217: Enforce to have the onClick mouse event with the onKeyUp, the onKeyDown, or the onKeyPress keyboard event.

Actions triggered using mouse events should have corresponding keyboard events to account for keyboard-only navigation.

(lint/a11y/useKeyWithClickEvents)


⚠️ Potential issue

Update redirection steps and improve accessibility for secondary actions.

The changes to the redirection steps in the onClick handlers for "target", "facility", and "user" sections appear to be intentional, likely reflecting a reorganization of the campaign setup process. However, there are accessibility concerns that need to be addressed.

To improve accessibility, add keyboard event handlers to these clickable div elements. Here's an example of how to modify the "target" section (apply similar changes to "facility" and "user" sections):

<div 
  className="campaign-preview-edit-container" 
  onClick={() => handleRedirect(4)}
  onKeyDown={(e) => e.key === 'Enter' && handleRedirect(4)}
  tabIndex={0}
  role="button"
  aria-label={t("CAMPAIGN_EDIT_TARGET")}
>
  <span>{t(`CAMPAIGN_EDIT`)}</span>
  <EditIcon />
</div>

These changes ensure that the edit actions are accessible to keyboard users, improving the overall accessibility of the component.

Also applies to: 237-237, 257-257

🧰 Tools
🪛 Biome

[error] 217-217: Enforce to have the onClick mouse event with the onKeyUp, the onKeyDown, or the onKeyPress keyboard event.

Actions triggered using mouse events should have corresponding keyboard events to account for keyboard-only navigation.

(lint/a11y/useKeyWithClickEvents)

<span>{t(`CAMPAIGN_EDIT`)}</span>
<EditIcon />
</div>
Expand All @@ -235,7 +235,7 @@ const CampaignUpdateSummary = (props) => {
},
cardHeader: { value: t("FACILITY_DETAILS"), inlineStyles: { marginTop: 0, fontSize: "1.5rem" } },
cardSecondaryAction: noAction !== "false" && (
<div className="campaign-preview-edit-container" onClick={() => handleRedirect(3)}>
<div className="campaign-preview-edit-container" onClick={() => handleRedirect(2)}>
<span>{t(`CAMPAIGN_EDIT`)}</span>
<EditIcon />
</div>
Expand All @@ -255,7 +255,7 @@ const CampaignUpdateSummary = (props) => {
},
cardHeader: { value: t("USER_DETAILS"), inlineStyles: { marginTop: 0, fontSize: "1.5rem" } },
cardSecondaryAction: noAction !== "false" && (
<div className="campaign-preview-edit-container" onClick={() => handleRedirect(4)}>
<div className="campaign-preview-edit-container" onClick={() => handleRedirect(3)}>
<span>{t(`CAMPAIGN_EDIT`)}</span>
<EditIcon />
</div>
Expand Down
Loading