# Public API get methods

This will cover all the retrieving data Javascript methods of the `joyInstance` object. These methods will request our Public API and get the data to your client side.

### Customer

Getting customer info via Joy API. This will get the customer info of the currently logged-in user on the store.

```javascript
joyInstance.customer().then(function(resp){
    console.log(resp)
});
```

Sample response:

```json

{
    "id": "avsu0TQoHYd4Zq5TZ123", 
    "shopifyCustomerId": 123123123,
    "earnSignUp": true,
    "name": "admin super",
    "hasPoint": true,
    "state": "enabled",
    "shopId": "7vqeDbhZtyofeuH7l123",
    "type": "member",
    "acceptsMarketing": false,
    "urlReferral": "https://inviteee.to/i/1234",
    "email": "avada@avada.email",
    "createdAt": "2023-04-04T07:03:32.119Z",
    "totalSpent": 22, 
    "latestActivity": "2023-06-14T04:45:55.465Z",
    "point": 100,
    "updatedAt": "2023-08-08T04:10:06.186Z",
    "appliedCollectionIds": []
}
```

### Shop

This method will get the shop data from Joy's public API and return a Promise resolving the shop data.

```javascript
joyInstance.shop().then(function(resp){
    console.log(resp)
});
```

Sample response:

```json
{
    disableWatermark: true,
    plan:'free',
    isAvailableProPlan :false,
    placeCurrencySymbol :true,
    currency:'VND',
}
```

### Translations

This method will get the translation dictionary data from our app via Public API.

```javascript
joyInstance.translation().then(function(resp){
    console.log(resp)
});
```

Sample response:

```json
{
    "Admin adjusted points": "Admin adjusted points",
    "Admin redeemed a reward": "Admin redeemed a reward",
    "Already a member?": "Already a member?",
    "Applicable for collections: {{collections}}": "Applicable for collections: {{collections}}",
    "Applicable for {{request_amount}} minimum orders": "Applicable for {{request_amount}} minimum orders",
    "Apply coupon now": "Apply coupon now",
    "Back": "Back",
    "Copy coupon": "Copy coupon",
    "Copy invite link": "Copy invite link",
    "Copy": "Copy",
    "Coupon Code: {{coupon_code}}": "Coupon Code: {{coupon_code}}",
    "Current balance is insufficient": "Current balance is insufficient",
    "Description": "Description",
    "Discount {{earning_discount}} for every {{redeeming_points}}": "Discount {{earning_discount}} for every {{redeeming_points}}",
    "Discount {{earning_discount}} for {{redeeming_points}}": "Discount {{earning_discount}} for {{redeeming_points}}",
    "Discount {{percentage}}% for {{redeeming_points}}": "Discount {{percentage}}% for {{redeeming_points}}",
    "Earn {{earning_points}} for each review from 3 stars & has photo or video": "Earn {{earning_points}} for each review from 3 stars & has photo or video",
    "Earn {{earning_points}} for every order": "Earn {{earning_points}} for every order",
    "Earn {{earning_points}} for every review": "Earn {{earning_points}} for every review",
    "Earn {{earning_points}} for every {{amount_spent}} spent": "Earn {{earning_points}} for every {{amount_spent}} spent",
    "Earn {{earning_points}}": "Earn {{earning_points}}",
    "Earn": "Earn",
    "Spend": "Spend",
    "Expired on: {{expired_date}}": "Expired on: {{expired_date}}",
    "Expired points": "Expired points",
    "Expired": "Expired",
    "Free gift on": "Free gift on",
    "Free shipping on": "Free shipping on",
    "Get Link": "Get Link",
    "Get rewards for being our customers": "Get rewards for being our customers",
    "How to Earn Point": "How to earn points",
    "How to Redeem": "How to redeem points",
    "Earn points": "Earn points",
}

```

### Redeeming programs

This method will get the list of redeeming programs from the public API.

```javascript
joyInstance.redeemPrograms().then(function(resp){
    console.log(resp)
});
```

Sample response:

```json
[
    {
        "id": "MuvzQblxTj4b7jsUUJzM",
        "spendPoint": 200,
        "isUsePrefixDiscountCode": false,
        "earnAmount": 48,
        "title": "Free product",
        "type": "spending",
        "priority": 1,
        "appliedCollectionIds": [],
        "specificProductIds": [
            44728173330719
        ],
        "redeemType": "fixed",
        "appliedTo": "sf_product",
        "shopId": "7vqeDbhZtyofeuH7l1ky",
        "event": "free_gift",
        "status": true,
        "specificProducts": [],
        "redeemIn": "available_in_online_store",
        "createdAt": "2023-06-14T04:45:26.580Z",
        "updatedAt": "2023-06-14T04:45:26.580Z"
        }
]
```

### Earning programs

This method will get the list of earning programs from the public API.

```javascript
joyInstance.earnPrograms().then(function(resp){
    console.log(resp)
});
```

Sample response:

```json
[
    {
        "id": "R3GMi0Ijytcm2emw1hGw",
        "limitUnit": "minute",
        "includeProducts": [],
        "autoRemovePoints": true,
        "earnBy": "price",
        "type": "earning",
        "title": "Place Order",
        "productPointsCalculator": {
            "color": "#8F00C1",
            "fontSize": 14,
            "type": "congratulation",
            "font": "Noto+Sans"
        },
        "earnPoint": 10,
        "hasLimit": false,
        "typeProductMatch": "all",
        "typeCondition": "all",
        "statusProductPointsCalculator": false,
        "shopId": "7vqeDbhZtyofeuH7l1ky",
        "event": "place_order",
        "conditions": [
            {
                "field": "title",
                "typeMatch": "contains",
                "content": ""
            }
        ],
        "enableCardPage": false,
        "excludeProducts": [],
        "statusUseCondition": false,
        "limitInterval": 1,
        "createdAt": "2023-04-04T06:51:59.639Z",
        "rateMoney": 1,
        "priority": 1,
        "priorityPlaceOrder": 1,
        "giftStatus": "none",
        "status": true,
        "appliedCollectionIds": [],
        "hasEarnRateForTier": true,
        "earnRateTiers": {
            "nJjsaiV4Q3P61ZqqLFlL": "",
            "f8QjhfgLDJhMrbjuX9Pa": ""
        },
        "updatedAt": "2023-07-27T10:00:31.598Z"
    }
]

```

### Customer activities

This method will get a list of customer activity history. This will paginate by `before` and `after` parameters.

```javascript
joyInstance.customerHistory({before: '', after: ''}).then(function(resp){
    console.log(resp)
});
```

Sample response:

```json
{
    "data": [
        {
            "id": "pIHrNxusdjoMZnv9xXlM",
            "statusSentNotification": false,
            "oldPoint": 300,
            "source": "user",
            "type": "redeem_point",
            "priceRuleId": 1387420942623,
            "programTitle": "Free product",
            "newPoint": 100,
            "customerId": "avsu0TQoHYd4Zq5TZnJg",
            "shopId": "7vqeDbhZtyofeuH7l1ky",
            "discountId": 17813899542815,
            "couponCode": "JOY-5KMCUB0L26KA",
            "email": "anhth@avada.email",
            "programId": "MuvzQblxTj4b7jsUUJzM",
            "createdAt": "2023-06-14T04:45:55.341Z",
            "updatedAt": "2023-06-14T04:45:55.341Z",
            "appliedCollectionIds": []
        },
        {
            "id": "5uqHhphWxR7XVgybA2Pm",
            "newPoint": 100,
            "statusSentNotification": false,
            "customerId": "avsu0TQoHYd4Zq5TZnJg",
            "oldPoint": 0,
            "shopId": "7vqeDbhZtyofeuH7l1ky",
            "source": "user",
            "type": "earn_point",
            "event": "sign_up",
            "email": "anhth@avada.email",
            "createdAt": "2023-04-04T07:03:32.210Z",
            "updatedAt": "2023-04-04T07:03:32.210Z",
            "appliedCollectionIds": []
        }
    ],
    "count": 2,
    "total": 0,
    "pageInfo": {
        "hasPre": false,
        "hasNext": false,
        "totalPage": 0
    }
}
```

### Coupon list

This method will get a list of customer coupons that they redeemed. This will paginate by `before` and `after` parameters.

```javascript
joyInstance.rewardList({before: '', after: '', isAvailableCoupon: true}).then(function(resp){
    console.log(resp)
});
```

Sample response:

```json
{
    "data": [
        {
            "id": "8zXV8ujMn2IEvZuv3CXh",
            "programTitle": "Coupon 10% off",
            "orderReqAmount": null,
            "appliedCollectionIds": [],
            "expiredAt": null,
            "programDescription": "Referral Program",
            "customerId": "avsu0TQoHYd4Zq5TZnJg",
            "shopId": "7vqeDbhZtyofeuH7l1ky",
            "discountId": 17780573569311,
            "couponCode": "JOY-IF5F1SL4G2QC",
            "email": "anhth@avada.email",
            "priceRuleId": 1381868568863,
            "programId": "C9AxToCOBRE5z0gQvsTJ",
            "createdAt": "2023-04-04T07:18:45.805Z",
            "updatedAt": "2023-04-04T07:18:45.805Z"
        }
    ],
    "count": 1,
    "total": 0,
    "pageInfo": {
        "hasPre": false,
        "hasNext": false,
        "totalPage": 0
    }
}
```

### Tiers

This method will get a list of all VIP tiers available in your programs.

```javascript
joyInstance.tiers().then(function(resp){
    console.log(resp)
});
```

Sample response:

```json
[
    {
        "id": "f8QjhfgLDJhMrbjuX9Pa",
        "isSystemTier": true,
        "icon": "https://imgur.com/atrkLg3.png",
        "rateMoney": "",
        "iconCustom": "",
        "placedOrderReward": false,
        "earnPoint": "",
        "createdAt": "2023-04-04T07:05:30.589Z",
        "targetPoint": 0,
        "members": 0,
        "name": "Bronze",
        "systemType": "bronze",
        "shopId": "7vqeDbhZtyofeuH7l1ky",
        "updatedAt": "2023-04-04T07:05:30.589Z",
        "isTierActive": false,
        "tierRewards": []
    },
    {
        "id": "nJjsaiV4Q3P61ZqqLFlL",
        "isSystemTier": true,
        "icon": "https://imgur.com/A2rT5G0.png",
        "rateMoney": "",
        "iconCustom": "",
        "placedOrderReward": false,
        "earnPoint": "",
        "createdAt": "2023-04-04T07:05:30.590Z",
        "targetPoint": 200,
        "members": 0,
        "name": "Silver",
        "systemType": "silver",
        "shopId": "7vqeDbhZtyofeuH7l1ky",
        "updatedAt": "2023-04-04T07:05:30.590Z",
        "isTierActive": false,
        "tierRewards": []
    },
]
```

### Branding

This method will get the branding setting of the floating widget:

```javascript
joyInstance.settingsBranding().then(function(resp){
    console.log(resp)
});
```

Sample response:

```json
{
    "widgetButtonColor": "#781EC6",
    "headlineTextColor": "#FFF",
    "headingTextColor": "#781EC6",
    "actionTextColor": "#FFF",
    "actionBgColor": "#781EC6",
    "customSolidColor": "#781EC6",
    "customGradientColorA": "#781EC6",
    "customGradientColorB": "#781EC6",
    "brandColor": "#781EC6",
    "textColor": "#781EC6",
    "type": "branding_points",
    "actionColor": "#FFF",
    "pointSingular": "point",
    "pointPlural": "points",
    "pointPosition": "after",
    "currencyPosition": "before",
    "contentHeader": "Welcome to our store",
    "signUpTitle": "Join and Earn Rewards",
    "signUpDesc": "Get rewards for being our customers",
    "signUpBtnLabel": "Join program",
    "signInLabel": "Already a member?",
    "signInBtnLabel": "Sign in",
    "redeemBtnLabel": "Redeem",
    "applyCouponBtnLabel": "Apply coupon now",
    "floatBtnLabel": "Rewards",
    "earnPointLabel": "How to Earn Points",
    "redeemPointLabel": "How to Redeem",
    "rewardListLabel": "Reward List",
    "pointHistoryLabel": "Points History",
    "backBtnLabel": "Back",
    "floatBtnPosition": "right-bottom",
    "hideOnMobile": false,
    "hideFloatButton": false,
    "iconPopup": "popup_gift",
    "autoShowPopup": true,
    "autoShowWithHash": false,
    "showWithHash": "",
    "appCss": "",
    "themeTextFont": "Roboto",
    "headlineTextFont": "Roboto",
    "headingTextFont": "Roboto",
    "actionTextFont": "Roboto",
    "positionMenu": [
        {
            "isParent": true,
            "showBeforeLogin": true,
            "id": "points",
            "childItems": [
                {
                    "nextPage": "howToEarn",
                    "showBeforeLogin": true,
                    "id": "earn-point",
                    "title": "How to Earn Point",
                    "isShow": true
                },
                {
                    "nextPage": "howToRedeem",
                    "showBeforeLogin": true,
                    "id": "redeem-point",
                    "title": "How to Redeem",
                    "isShow": true
                }
            ],
            "title": "Points",
            "isShow": true
        },
        {
            "nextPage": "referralStep1",
            "showBeforeLogin": true,
            "id": "refer",
            "title": "Refer your friends",
            "isShow": true
        },
        {
            "nextPage": "tierLogin1",
            "showBeforeLogin": true,
            "id": "vip",
            "title": "VIP Tier",
            "isShow": true
        },
        {
            "nextPage": "rewards",
            "id": "reward-list",
            "title": "Reward list",
            "isShow": true
        },
        {
            "nextPage": "activities",
            "id": "history",
            "title": "Point History",
            "isShow": true
        }
    ],
    "id": "7vqeDbhZtyofeuH7l1ky",
    "shopId": "7vqeDbhZtyofeuH7l1ky",
    "firstSave": true
}
```

### Point calculators

We have two methods that act as two API endpoints to get the number of points for a customer can get for one product, or a cart.

This API endpoint will return data like this:

```json
{
    "html": "<style>\n.Avada-PointsCalculator__Link:hover {\n  opacity: 0.8;\n}\n.Avada-PointsCalculator__Icon svg {\n  display: block;\n  width: 100%;\n  height: 100%;\n}\n.Avada-PointsCalculator__Icon img {\n  display: block;\n  width: 100%;\n  height: 100%;\n  object-fit: contain;\n}\n</style>\n<div style=\"display: inline-flex; align-items: center; color: #303030; font-size: 14px; font-family: inherit;\">\n  <span class=\"Avada-PointsCalculator__Icon\" style=\"display: inline-block; width: 24px; height: 24px; margin-right: 8px; vertical-align: middle;\"><img src=\"https:&#x2F;&#x2F;cdn.shopify.com&#x2F;s&#x2F;files&#x2F;1&#x2F;0961&#x2F;2312&#x2F;6078&#x2F;files&#x2F;media_joy_doodle-art-fill.svg?v=1760468630\" alt=\"icon\" style=\"width: 30px; height: 30px; object-fit: contain;\" /></span>\n  <span style=\"display: inline; margin: 0; line-height: 1.5;\">\n    Receive 699 points for buying this item.\n  </span>\n</div>",
    "points": 699,
    "pointCurrencyName": {
        "singular": "point",
        "plural": "points"
    },
    "fromCache": false
}
```

#### Product calculator

You need to pass the variantId and the productId. The customerId will be automatically retrieved.

```javascript
(async () => {
	const variantId = ShopifyAnalytics.meta.product.variants[0].id;
	const productId = ShopifyAnalytics.meta.product.id;
	
	const result = await joyInstance.calculateProductPoints({variantId, productId});
	console.log("Result ", result);
})()
```

Here is the direct API implementation:

```javascript
(async () => {
	const variantId = ShopifyAnalytics.meta.product.variants[0].id;
	const productId = ShopifyAnalytics.meta.product.id;
	const customerId = window.ShopifyAnalytics.meta.page.customerId;
	
	
  // 2. Send to your endpoint
  const apiRes = await fetch(`https://joy.avada.io/app/api/v1/widgets/points-calculator/product?domain=${Shopify.shop}&productId=${productId}&variantId=${variantId}&q=1&customerId=${customerId}`, {
    method: 'GET'
  });

  const { data } = await apiRes.json();
  console.log('API Response:', data);
})();
```

#### Cart calculator

If this method takes `autoFetchCart` true, it will call to `/cart.js` AJAX API itself. If you have the items because you called the API beforehand, you can pass them manually via the `items` parameter.

```
(async () => {
	const result = await joyInstance.calculateCartPoints({autoFetchCart: true});
	console.log("Result ", result);
})()
```

Here is the API version:

```javascript
(async () => {
  // 1. Fetch cart
  const cartRes = await fetch('/cart.js');
  const cartData = await cartRes.json();
  console.log('Cart Data:', cartData);

  // 2. Send to your endpoint
  const apiRes = await fetch(`https://joy.avada.io/app/api/v1/widgets/points-calculator/cart?domain=${Shopify.shop}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      items: cartData.items
    })
  });

  const { data } = await apiRes.json();
  console.log('API Response:', data);
})()
```
