Sat Feb 13 2021
Copied to clipboard! Copy reply
  • 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
import prettyjson from 'json-stringify-pretty-compact'
import { createFile } from './fileHandler';

/**
 * This function creates a pages.json file
 * First we format the RSI objects to how
 * we want. Then write to file.
 *
 * @param {Array} rsiArray - A copy of the array of RSI objects
 * @param {Obj} promosArray - Object with all  promocodes.
 * @param {Object} config - App's config obj
 */

const createPagesFile = (rsiArray, promosArray, config) => {
  rsiArray = rsiArray.map(rsi => {

    /* promosArray looks like:
      [...,
        {
          id: 'rec5RPZiV2opeBFlR',        <---- matches an rsi's `promo`
          PromoNodeName: 'GOLDENGATE',
          SUB_24: [ 'recH3j8C9n7ne1HDE' ],
          SUB_12: [ 'recSvM75aJPPKQqWV' ],
          SUB_6: [ 'recWE8HSRTEeAy3Yh' ],
          SUB_3: [ 'recSXcOJXPyp97739' ],
          SUB_1: [ 'recAFQwNDFaj55BWz' ],
          SUB_18: [ 'recomEOORqRJsgtxG' ],
          SUB_27: [ 'recaWOSCLCVSA41SK' ],
          SUB_8: [ 'recQCaO8VVoYKTQOr' ],
          SUB_lifetime: [ 'recaWOSCLCVSA41SK' ],
          SUB_30: [ 'recaWOSCLCVSA41SK' ],
          SUB_15: [ 'recomEOORqRJsgtxG' ],
          SUB_36: [ 'recaWOSCLCVSA41SK' ],
          SUB_13: [ 'recomEOORqRJsgtxG' ]
        }
      ]

    rsi looks like:
    {
      id: 'winterdeal6adi',
      promo: [ 'rec0eeZTPnxkFNloj' ], <----- ID from the promosArray above
      mastheadimg:
        [{ id: 'att4962PF2VRE7Kau',
        url: 'https://dl.airtable.com/H7wyOe1Qcmv9v1rSrtVa_winter6-d.jpg',
        filename: 'winter6-d.jpg',
        size: 71266,
        type: 'image/jpeg',
        thumbnails: [Object] } ],
      mastheadmobile:
        [{ id: 'attMMRPhhoT2aPITp',
        url: 'https://dl.airtable.com/0FvpYx6ORqiYYuEgntMG_winter6.jpg',
        filename: 'winter6.jpg',
        size: 28684,
        type: 'image/jpeg',
        thumbnails: [Object] } ],
      expirationdate: 'December 31, 2018 23:59',
      campaign: undefined,
      bonusmonths: undefined,
      bogo: undefined,
      productfilter: undefined,
      js: undefined,
      css: undefined
    }
    */

    // Image should have been created already. No longer needed since
    // rsi.mastheadimg = `rsi name`. Both desktop and mobile images have
    // the rsi name as filename, but stored in different folders.
    delete rsi.mastheadmobile

    // Replace rsi.mastheadimg with rsi name, since the image file is the rsi name.
    rsi.mastheadimg = `${rsi.id}.jpg`


    // Replace rsi.promo with the name value (currently it's an id)
    let newPromo = "";
    if (rsi.promo && rsi.promo[0]) {
      let tmp = promosArray.filter(p => p.id === rsi.promo[0]);
      if (tmp[0] && tmp[0].PromoNodeName) {
        newPromo = tmp[0].PromoNodeName.trim();
      }
    }
    rsi.promo = newPromo;

    // Optional fields in Airtable, when left blank, defaults to undefined.
    // Here we convert them to null or whatever else we want

    rsi.campaign = rsi.Campaign === undefined ? '' : rsi.Campaign;

    rsi['bonusmonths'] = rsi['bonusmonths'] === undefined ? null : rsi['bonusmonths'].split(',');

    rsi['bogo'] = rsi['bogo'] === undefined ? null : rsi['bogo'].map(e => e);

    rsi['productfilter'] = rsi['productfilter'] === undefined ? null : rsi['productfilter'].map(e => e);

    rsi['ribbontext'] = rsi['ribbontext'] === undefined ? null : rsi['ribbontext']

    rsi['offertext'] = rsi['offertext'] === undefined ? null : rsi['offertext']

    rsi['xpay'] = rsi['xpay'] === undefined ? null : rsi['xpay']

    rsi['fullprice'] = rsi['fullprice'] === undefined ? Boolean(false) : (rsi['fullprice'] === 'true')

    rsi['productnames'] = rsi['productnames'] === undefined ? null : rsi['productnames']

    rsi['mastheadText'] = rsi['mastheadText'] === undefined ? null : rsi['mastheadText']
    

    // If ribbontext is set, let's format it into an object.
    // It's a longtext in Airtable, so we split at newline
    // We format them into an object so we have a js object on the landing page.
    // It should be set in airtable like this: month:locale:text. ie, 6:en:best value

    const ribbonText = rsi.ribbontext ? rsi.ribbontext.trim() : null;
    if (ribbonText) {
      let ribbonObj = {};
      let texts = ribbonText.split("\n");
      for (let obj of texts) {
        let [ month, locale, text, background, color, headerbackground, headercolor ] = obj.split(':');
        if (!month || !locale || !text) {
          console.error('------------------------------------------');
          console.error(`[ ERROR ] Formatting error on ribbon text of page \'${rsi.id}\'`);
          console.error('ribbontext:');
          console.error('-----------------------');
          console.error(ribbonText);
          console.error('-----------------------');
          console.error('month: ' + month + '\nlocale: ' + locale + '\ntext: ' + text + '\nbackground: ' + background
            + '\ncolor: ' + color + '\nheaderbackground: ' + headerbackground + '\nheadercolor: ' + headercolor  );
          console.error('------------------------------------------');
          process.exit(1);
        }
        locale = locale.trim();
        text = text.trim();
        month = month.toLowerCase().trim();
        background = background ? background.trim() : null;
        color = color ? color.trim() : null;
        headerbackground = headerbackground ? headerbackground.trim() : null;
        headercolor = headercolor ? headercolor.trim() : null;
        if (locale == config.locale) {
          ribbonObj[month] = {text, background, color, headerbackground, headercolor};
        }
      }
      rsi.ribbontext = ribbonObj;
    }

    // If offertext is set, let's format it into an object.
    // It's a longtext in Airtable, so we split at newline
    // We format them into an object so we have a js object on the landing page.
    // {6: 'foo!', 24: 'bar!'}
    // It should be set in airtable like this: month:locale:text. ie, 6:en:best value

    //if (Object.entries(rsi.offertext)) {
    if (rsi.offertext) {
      let offerObj = {}
      let texts = rsi.offertext.split("\n\r")
      for (let obj of texts) {
        let [ month, locale, text ] = obj.split(':')

        if (month == undefined || locale == undefined || text == undefined) {
          console.error('------------------------------------------')
          console.error(`[ ERROR ] Formatting error on offer text of page \'${rsi.id}\'`);
          console.error(rsi.offertext);
          console.error('------------------------------------------')
          process.exit(1);
        }
        if (locale.trim() == config.locale) {
          offerObj[month.toLowerCase()] = text.trim()
        }
      }
      rsi.offertext = offerObj
    }

    // If producctname is set...
    if (rsi.productnames) {
      let namesObj = {}
      let names = rsi.productnames.split("\n")
      for (let obj of names) {
        let [ product, locale, text ] = obj.split(':')
        if (product == undefined || locale == undefined || text == undefined) {
          console.error('------------------------------------------')
          console.error(`[ ERROR ] Formatting error on product name of page \'${rsi.id}\'`);
          console.error(rsi.productnames)
          console.error('------------------------------------------')
          process.exit(1);
        }
        if (locale.trim() == config.locale) {
          namesObj[product] = text.trim()
        }
      }
      rsi.productnames = namesObj
    }
    
    rsi.mastheadText = processMastheadText(rsi.mastheadText, config.locale);

    // Xpay is separated by a comma. ie, "24:3" (will show 3-pay on 24m)
    /*
    if (Object.entries(rsi.xpay).length) {
      let tmp = {}
      let xpays = rsi.xpay.split("\n")
      for (let xpay of xpays) {
        let [ month, divisor ] = xpay.split(':')
        tmp[month] = divisor
      }
      rsi.xpay = tmp
    }
    */

    // This probably shouldn't be here, but if an RSI has custom JS or CSS,
    // write it to a file (ie, custom-js/sitewide.js, custom-css/sitewide.css, etc)
    // And no need to keep the custom js and css in the RSI object, as the contents
    // are already written to a file, and it'll increase the size of the JS model later.
    // We replace the value with '1' to let our landing page know that there is a custom
    // css or js file associated with the page, and it will then insert it.
    // So basically instead of the RSI model having something like
    // RSI.js = 'some long js code'... it will just be RSI.js = 1
    // The landing page template will check for this, and if RSI.js is 1,
    // it'll create script tags and insert the js file, since it know it exists.
    if (rsi['js'] !== undefined)
    {
      let filepath = `${config.dstpath}/custom-js/${rsi.id}.js`
      createFile(filepath, rsi['js'])
      rsi['js'] = 1
    }
    else
    {
      rsi['js'] = 0
    }

    if (rsi['css'] !== undefined)
    {
      let filepath = `${config.dstpath}/custom-css/${rsi.id}.css`
      createFile(filepath, rsi['css'])
      rsi['css'] = 1
    }
    else
    {
      rsi['css'] = 0
    }

    return rsi

  });

  let dstPath = `${config.dstpath}/json/pages.json`
  createFile(dstPath, prettyjson(rsiArray));
};

export function processMastheadText(inputMastheadText, locale) {

  /**
   * Masthead text. In Airtable, it should be stored like this
   * `======
   * en
   * 1:: ffffff :: Binge Life
   * 2:: ffed038 :: Flip Between languages as often as you like
   * 3:: ffffff :: __price__
   * 4:: ffffff:: __msrp___ lifetime subscription
   * ======
   * es
   * 1:: ffffff :: Binge vida
   * 2:: ffed038 :: Flip Between languages as often as you like
   * 3:: ffffff :: __price__
   * 4:: ffffff:: __msrp___ lifetime subscription`;
   *
   * We then:
   * 1. split at =====
   * 2. Filter out empty elements
   * 3. Filter for the locale (element 0 should be the locale, per format shown above)
   *
   */

  let mastheadText = null;

  if (inputMastheadText) {
    // Split at ====== and filter out any empty elements.
    // After splits, element [0] is always empty string, so we filter a lot
    let content = inputMastheadText.split("======\n");

    let mode;
    if (content.length && ['left', 'right', 'center', 'xpay'].indexOf(content[0].trim()) >= 0) {
      mode = content[0].trim() + "-mode";
    } else {
      throw "--- first line of masthead text must be 'left, 'right', 'center', or 'xpay'";
    }
    
    content = content.filter(e => e.substr(0, e.indexOf("\n")).trim() === locale);

    // This happens if there is no masthead text for this locale. ie,
    // If we compile for pt but pages with mastheadTexts don't have something like
    // ======
    // pt
    // 1:: ffffff :: Preparado para mudar sua vida?
    // 2:: ffffff :: Tente idiomas ilimitados
    // 3:: ffffff :: <stackedsuper><stackedtop>USD</stackedtop>$</stackedsuper>199
    // 4:: ffffff :: ASSINATURA VITALÍCIA
    if (!content.length) {
      console.warn("------- ERROR -------: No masthead text for this locale")
      return
    }
    content = content[0].trim().split("\n").map(e => e.trim());
    
    // Remove the locale at position 0
    content.shift();

    // error checking
    if ((mode === 'left' || mode === "right" || mode === 'center') && content.length !== 4) {
      throw `--- masthead text for mode '${mode}' must have 4 lines of content for locale '${locale}' but instead has ${content.length}`;
    } else if (mode === "xpay" && content.length !== 6) {
      throw `--- masthead text for mode 'xpay' must have 6 lines of content for locale '${locale}' but instead has ${content.length}`;
    }
    
    let textContent = [];
    for (let line of content) {
      let [ , color, text] = line.split("::").map(e => e.trim());
      textContent.push({
        color: `#${color}`,
        text,
      });
    }

    if (mode === "left-mode" || mode === "right-mode" ) {
      if (textContent[1].text && mode === "left-mode") {
        mode = "left-2-line-title-mode";
      }
      else if (textContent[1].text && mode === "right-mode") {
        mode = "right-2-line-title-mode";
      }
      else if (!textContent[1].text && mode === "left-mode") {
        mode = "left-1-line-title-mode";
        textContent.splice(1, 1);
      }
      else {
        mode = "right-1-line-title-mode";
        textContent.splice(1, 1);
      }
    }

    mastheadText = {};
    mastheadText.mode = mode;
    mastheadText.content = textContent;
  }

  return mastheadText;
}


export default createPagesFile;