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

Refactor request #4

Open
wants to merge 27 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
f998880
refactor requests
Nov 10, 2022
504948c
Change "attachEndpointsStackingPromotions" to "addStackingPromotionRo…
weronika-kurczyna Nov 14, 2022
dc0b21a
Add validateStackableParams and redeemStackableParams
weronika-kurczyna Nov 15, 2022
99478ab
Add check if campaign 'Reward Promotion' exists
weronika-kurczyna Nov 15, 2022
4cb59c0
Add alert with information about lack of the campaign
weronika-kurczyna Nov 15, 2022
a7c78cb
Reduction of the code
weronika-kurczyna Nov 16, 2022
241c9f8
add cURL
weronika-kurczyna Nov 17, 2022
4ff1ab2
reformat cURL
weronika-kurczyna Nov 17, 2022
b17d1ad
Update README.md
weronika-kurczyna Nov 17, 2022
11ea819
Add information in server.js
weronika-kurczyna Nov 17, 2022
c3b45b1
Delete the alert message
weronika-kurczyna Nov 17, 2022
56bd737
Refactor other endpoints
weronika-kurczyna Nov 17, 2022
fa12e78
Update README.md
weronika-kurczyna Nov 17, 2022
1eedf2d
Add creating missing campaign JS file
weronika-kurczyna Nov 21, 2022
84c1b30
Change the structure of the functions
weronika-kurczyna Nov 21, 2022
9978cef
Update server.js
weronika-kurczyna Nov 21, 2022
70a50ff
Update README.md
weronika-kurczyna Nov 21, 2022
0b20547
Change readme and main server.js file
weronika-kurczyna Nov 23, 2022
08fecd3
Change the structure and naming a bit
weronika-kurczyna Nov 23, 2022
4606749
update missing-campaign
weronika-kurczyna Nov 23, 2022
d2b8fb1
naming change
weronika-kurczyna Nov 23, 2022
d55f8fd
Change the way errors are displayed
weronika-kurczyna Nov 23, 2022
d3e5745
Refactor - move functions, change naming and readme
weronika-kurczyna Dec 6, 2022
1679892
Change the way of running "add-missing-campaign.js" script
weronika-kurczyna Dec 12, 2022
43bcca6
Little change in message
weronika-kurczyna Dec 12, 2022
e5f79d4
Change format of the message in server.js (better readability)
weronika-kurczyna Dec 12, 2022
6f180eb
Change the formatting of the console message using EOL
weronika-kurczyna Jan 10, 2023
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ npm run start / npm run dev || yarn start / yarn run dev
```
7. Go to [http://localhost:3000](http://localhost:3000/) in your browser.

Note: The application should automatically add the missing campaign "Reward Promotion" by using script called "missing-campaign.js", so there is no need to add it manually.
Copy link
Collaborator

Choose a reason for hiding this comment

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

node missing-campaign? Also, it would be great to add a verb into the script name as we do some action, so maybe node add-missing-campaign?


## Get support <a id="support"></a>

If you found a bug or want to suggest a new sample, please file an issue.
Expand Down
218 changes: 218 additions & 0 deletions missing-campaign.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
export const createMissingCampaign = async (client) => {

const createRewardPromotionObject = (firstValidationRule, secondValidationRule, thirdValidationRule) => {
return {
"name": "Reward Promotion",
"start_date": null,
"expiration_date": null,
"campaign_type": "PROMOTION",
"type": "STATIC",
"metadata": {},
"use_voucher_metadata_schema": false,
"promotion": {
"tiers": [
{
"id": null,
"name": "Reward Promotion Tier 1",
"banner": "Add products worth $100+ to get Free Shipping",
"action": {
"discount": {
"type": "UNIT",
"amount_off": null,
"unit_off": 1,
"unit_type": "prod_5h1pp1ng",
"effect": "ADD_MISSING_ITEMS"
}
},
"metadata": {},
"hierarchy": 1,
"__id": "16ee1b96-0baf-4431-84a7-7dd4a7ffd46f",
"active": true,
"start_date": null,
"expiration_date": null,
"validation_rules": [
firstValidationRule ? firstValidationRule : null
]
},
{
"id": null,
"name": "Reward Promotion Tier 2",
"banner": "Add products worth $250+ for 3% discount",
"action": {
"discount": {
"type": "PERCENT",
"amount_off": null,
"percent_off": 3,
"effect": "APPLY_TO_ORDER"
}
},
"metadata": {},
"hierarchy": 2,
"__id": "d3a1e546-90bc-4549-b5f2-6b6962a53b9f",
"active": true,
"start_date": null,
"expiration_date": null,
"validation_rules": [
secondValidationRule ? secondValidationRule : null
]
},
{
"id": null,
"name": "Reward Promotion Tier 3",
"banner": "Add products worth $500+ for 6% discount",
"action": {
"discount": {
"type": "PERCENT",
"amount_off": null,
"percent_off": 6,
"effect": "APPLY_TO_ORDER"
}
},
"metadata": {},
"hierarchy": 3,
"__id": "a1b2c70c-3206-4c7d-84b2-614e4c43d07d",
"active": true,
"start_date": null,
"expiration_date": null,
"validation_rules": [
thirdValidationRule ? thirdValidationRule : null
]
}
]
}
}
}

const firstValidationRule = {
"id": null,
"name": "Validation Rule - Reward Promotion Tier 1",
"rules": {
"1": {
"name": "order.amount",
"property": null,
"conditions": {
"$more_than": [
10000
]
}
},
"2": {
"name": "order.amount",
"property": null,
"conditions": {
"$is": [
10000
]
}
},
"logic": "(1 or 2)"
},
"error": null,
"applicable_to": {
"included": [],
"excluded": [],
"included_all": false
},
"type": "advanced",
"context_type": "campaign.promotion"
}

const secondValidationRule = {
"id": null,
"name": "Validation Rule - Reward Promotion Tier 2",
"rules": {
"1": {
"name": "order.amount",
"property": null,
"conditions": {
"$more_than": [
25000
]
}
},
"2": {
"name": "order.amount",
"property": null,
"conditions": {
"$is": [
25000
]
}
},
"logic": "(1 or 2)"
},
"error": null,
"applicable_to": {
"included": [],
"excluded": [],
"included_all": false
},
"type": "advanced",
"context_type": "campaign.promotion.discount.apply_to_order"
}

const thirdValidationRule = {
"id": null,
"name": "Validation Rule - Reward Promotion Tier 3",
"rules": {
"1": {
"name": "order.amount",
"property": null,
"conditions": {
"$more_than": [
50000
]
}
},
"2": {
"name": "order.amount",
"property": null,
"conditions": {
"$is": [
50000
]
}
},
"logic": "(1 or 2)"
},
"error": null,
"applicable_to": {
"included": [],
"excluded": [],
"included_all": false
},
"type": "advanced",
"context_type": "campaign.promotion.discount.apply_to_order"
}

// const createRewardPromotion = async () => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

do not leave the code that is commented out

// await Promise.all([
// client.validationRules.create(firstValidationRule),
// client.validationRules.create(secondValidationRule),
// client.validationRules.create(thirdValidationRule)
// ])
// .then(([firstPromise, secondPromise, thirdPromise]) => {
// const rewardPromotion = createRewardPromotionObject(firstPromise.id, secondPromise.id, thirdPromise.id);
// const response = client.campaigns.create(rewardPromotion);
// if (response.code !== 200) {
// return new Error;
// }
// })
// }

const createValidationRulesAndCampaign = async () => {
const validationRules = await Promise.all([
client.validationRules.create(firstValidationRule),
client.validationRules.create(secondValidationRule),
client.validationRules.create(thirdValidationRule),
])
const rewardPromotion = createRewardPromotionObject(validationRules[0].id, validationRules[1].id, validationRules[2].id);

const createCampaignResponse = await client.campaigns.create(rewardPromotion);
console.log("The Reward Campaign was successfully created.");

}
await createValidationRulesAndCampaign();
}


80 changes: 53 additions & 27 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import express from "express";
import { accessToStackingPromotionsApp, attachEndpointsStackingPromotions } from "./stacking-promotions/server.js";
import { accessToVoucherCodeRedemptionApp, attachEndpointsVoucherCodeRedemption } from "./voucher-code-redemption/server.js";
import { accessTotieredPromotionsApp, attachEndpointsTieredCartPromotions } from "./tiered-cart-promotions/server.js";
import { addStackingPromotionRoutes } from "./stacking-promotions/server.js";
import { addEndpointsVoucherCodeRedemption } from "./voucher-code-redemption/server.js";
import { addEndpointsTieredCartPromotions } from "./tiered-cart-promotions/server.js";
import { fileURLToPath } from "url";
import "dotenv/config";
import pkg from "@voucherify/sdk";
import path from "path";
import bodyParser from "body-parser";
import { createMissingCampaign } from "./missing-campaign.js";
const { VoucherifyServerSide } = pkg;
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();

export const client = VoucherifyServerSide({
applicationId: `${process.env.VOUCHERIFY_APP_ID}`,
secretKey : `${process.env.VOUCHERIFY_SECRET_KEY}`,
// apiUrl: 'https://<region>.api.voucherify.io'
applicationId: `${process.env.VOUCHERIFY_APP_ID}`,
secretKey: `${process.env.VOUCHERIFY_SECRET_KEY}`,
// apiUrl: 'https://<region>.api.voucherify.io'
});

app.use(bodyParser.json());
Expand All @@ -24,36 +25,61 @@ app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "./welcome-screen")));

app.use((req, res, next) => {
res.append("Access-Control-Allow-Origin", [ "*" ]);
res.append("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.append("Access-Control-Allow-Headers", "Content-Type");
next();
res.append("Access-Control-Allow-Origin", ["*"]);
res.append("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.append("Access-Control-Allow-Headers", "Content-Type");
next();
});

const checkCredentials = async () => {
try {
await client.vouchers.list();
} catch (error) {
if (error.code === 401) {
const msg = "Your API credentials are incorrect, please check your applicationId and secretKey or visit `https://docs.voucherify.io/docs/authentication` to complete your app configuration.";
throw new Error(msg);
}
throw new Error(error);
try {
await client.vouchers.list();
} catch (error) {
if (error.code === 401) {
const msg = "Your API credentials are incorrect, please check your applicationId and secretKey or visit `https://docs.voucherify.io/docs/authentication` to complete your app configuration.";
throw new Error(msg);
}
throw new Error(error);
}
};

/*
Important!
Copy link
Collaborator

Choose a reason for hiding this comment

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

This comment is outdated.

The 'Reward Promotion' campaign is required for this project to work properly.
If it doesn't exist you will see an error in the console.
Visit https://github.com/voucherifyio/voucherify-examples/tree/main/tiered-cart-promotions#creating-a-reward-promotion-campaign
for getting instructions on how to create the missing campaign.
*/

const checkCampaign = async () => {
Copy link
Collaborator

Choose a reason for hiding this comment

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

The checkCampaign function actually adds a campaign to the V% account if it does not exists, which may be a little dangerous if someone by accident connects the production account. I suggest does not allow to run the example (like for checkCredentials) and displaying the message that you have already in the catch block.

try {
await client.campaigns.get("Reward Promotion");
} catch (error) {
if (error.code === 404) {
try {
createMissingCampaign(client);
}
catch (error) {
const msg = `The 'Reward Promotion' campaign not found. This campaign is required for 'tiered-cart-promotion' to work properly.
\r\nPlease create a 'Reward Promotion' campaign first.
\r\nThe 'missing-campaign.js' is the script that should automatically create this campaign when the application starts (createMissingCampaign() function).
\r\nIf the script doesn't work you can check the details by visiting: https://github.com/voucherifyio/voucherify-examples/tree/main/tiered-cart-promotions#creating-a-reward-promotion-campaign
or you can get additional support here: https://github.com/voucherifyio/voucherify-examples/tree/main#get-support- `;
throw new Error(msg);
}
}
}
}

checkCredentials();
checkCampaign();

const port = process.env.PORT || 8080;

app.listen(port, () => {
console.log(`Hot beans app listening on port ${port}`);
console.log(`Hot beans app listening on port ${port}`);
});

accessToStackingPromotionsApp(app);
attachEndpointsStackingPromotions(app, client);

accessToVoucherCodeRedemptionApp(app);
attachEndpointsVoucherCodeRedemption(app, client);

accessTotieredPromotionsApp(app);
attachEndpointsTieredCartPromotions(app, client);
addStackingPromotionRoutes(app, client);
addEndpointsVoucherCodeRedemption(app, client);
addEndpointsTieredCartPromotions(app, client);
2 changes: 1 addition & 1 deletion stacking-promotions/public/js/lib.js
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export const filterAndReduceProducts = products => {
};

export const getDefaultItemsNameAndPrice = async () => {
const response = await fetch("/stacking-promotions/default-items", {
const response = await fetch("/stacking-promotions/default-cart-items", {
method : "GET",
headers: {
"Accept" : "application/json",
Expand Down
Loading