<commit_before>/**
 * Testing application
 */

const { expect } = require("chai");
const helpers = require("./../helpers");

describe("Application", () => {
    it("should be able to launch if service workers are not available", async () => {
        let page = await browser.newPage();
        await page.goto(`${helpers.PAGE_URL_DEFAULT_NO_SSL}`);
        page = await helpers.waitForPageToLoad(page);
    });

    it("should take into account configuration options", async () => {
        // Non-empty "activateMainTab" option (module)
        let page = await browser.newPage();
        await page.setRequestInterception(true);
        page.on('request', request => {
            if (request.url().indexOf(`aleksandrshumilov/aleksandrshumilov.json`) !== -1) {
                request.respond({
                    content: 'application/json',
                    headers: {"Access-Control-Allow-Origin": "*"},
                    body: JSON.stringify({
                        "brandName": "Test 1",
                        "activateMainTab": "streetview"
                    })
                });
            } else {
                request.continue();
            }
        });

        await page.goto(`${helpers.PAGE_URL_DEFAULT_NO_SSL}`);
        page = await helpers.waitForPageToLoad(page);
        await helpers.sleep(1000);
        let text = await page.evaluate(`$('.navbar-brand').text()`);
        expect(text.indexOf(`Test 1`) > -1).to.be.true;
        expect(await page.evaluate(`$('#streetview-content').is(':visible')`)).to.be.true;
        await page.close();

        // Non-empty "activateMainTab" option (extension)
        page = await browser.newPage();
        await page.setRequestInterception(true);
        page.on('request', request => {
            if (request.url().indexOf(`aleksandrshumilov/aleksandrshumilov.json`) !== -1) {
                request.respond({
                    content: 'application/json',
                    headers: {"Access-Control-Allow-Origin": "*"},
                    body: JSON.stringify({
                        "brandName": "Test 2",
                        "activateMainTab": "draw"
                    })
                });
            } else {
                request.continue();
            }
        });

        await page.goto(`${helpers.PAGE_URL_DEFAULT_NO_SSL}`);
        page = await helpers.waitForPageToLoad(page);
        await helpers.sleep(1000);
        text = await page.evaluate(`$('.navbar-brand').text()`);
        expect(text.indexOf(`Test 2`) > -1).to.be.true;
        expect(await page.evaluate(`$('[href="#draw-collapse"]').is(':visible')`)).to.be.true;
        await page.close();

        // Empty "activateMainTab" option
        let newPage = await browser.newPage();
        await newPage.goto(`${helpers.PAGE_URL_DEFAULT_NO_SSL}`);
        newPage = await helpers.waitForPageToLoad(newPage);
        await helpers.sleep(1000);
        expect(await newPage.evaluate(`$('[href="#draw-collapse"]').is(':visible')`)).to.be.false;
        await newPage.close();
    });

    it("should have only one active module at a time", async () => {
        let page = await browser.newPage();
        await page.goto(`${helpers.PAGE_URL_BASE}app/aleksandrshumilov/public/#osm/18/39.279/-6.8352/public.test_poly`);
        page = await helpers.waitForPageToLoad(page);

        let numberOfSQLRequests = 0;
        await helpers.sleep(1000);
        await page.setRequestInterception(true);
        page.on('request', request => {
            if (request.url().indexOf(`api/sql/aleksandrshumilov`) !== -1) {
                numberOfSQLRequests++;
            }

            request.continue();
        });

        // Info click has to be disabled by default
        await page.click(`#map`);
        await helpers.sleep(1000);
        expect(numberOfSQLRequests).to.equal(0);

        await page.evaluate(`$('[class="floatRight cursorPointer fa fa-reorder"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#info-content"]').trigger('click');`);
        await helpers.sleep(1000);

        // Info click was enabled before, so it has to handle map clicks
        await page.click(`#map`);
        await helpers.sleep(1000);
        expect(numberOfSQLRequests).to.equal(1);
        expect(await page.evaluate(`$('#module-container').length`)).to.equal(1);
        expect(await page.evaluate(`$('#module-container').css('right')`)).to.equal(`0px`);

        // Enabling measurements module, so all other modules have to be hidden
        await page.evaluate(`$('.js-measurements-control').trigger('click')`);
        await helpers.sleep(2000);
        expect(await page.evaluate(`$('#module-container').css('right')`)).to.equal(`-400px`);
        expect(await page.evaluate(`$('.leaflet-draw-draw-polyline').is(':visible')`)).to.be.true;

        // Enabling draw module
        await page.evaluate(`$('[href="#draw-content"]').trigger('click');`);
        await helpers.sleep(1000);
        expect(await page.evaluate(`$('#module-container').css('right')`)).to.equal(`0px`);
    });

    it("should be able to reset the application", async () => {
        let page = await browser.newPage();
        await page.goto(`${helpers.PAGE_URL_DEFAULT}test.polygon,public.urbanspatial_dar_es_salaam_luse_2002,public.test_poly,v:public.test,v:public.test_line`);
        page = await helpers.waitForPageToLoad(page);

        // Accepting the dialog
        page.on('dialog', (dialog) => {
            dialog.accept();
        });

        expect(page.url().indexOf(`test.polygon`) > 0).to.be.true;
        expect(page.url().indexOf(`public.urbanspatial_dar_es_salaam_luse_2002`) > 0).to.be.true;
        expect(page.url().indexOf(`public.test_poly`) > 0).to.be.true;
        expect(page.url().indexOf(`v:public.test`) > 0).to.be.true;
        expect(page.url().indexOf(`v:public.test_line`) > 0).to.be.true;

        await page.evaluate(`$('[class="floatRight cursorPointer fa fa-reorder"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#layer-content"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#collapseUHVibGljIGdyb3Vw"]').trigger('click')`);
        await helpers.sleep(1000);

        expect(await page.evaluate(`$('input[data-gc2-id="test.polygon"]').is(':checked')`)).to.be.true;
        expect(await page.evaluate(`$('input[data-gc2-id="public.test"]').is(':checked')`)).to.be.true;

        // Check if the panel for different schema was drawn as well
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(0).text()`)).to.equal(`Test group`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(1).text()`)).to.equal(`Dar es Salaam Land Use and Informal Settlement Data Set`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(2).text()`)).to.equal(`Dynamic load test`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(3).text()`)).to.equal(`Snapping`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(4).text()`)).to.equal(`Public group`);

        // Change the base layer
        await page.evaluate(`$('[href="#baselayer-content"]').trigger('click');`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[name="baselayers"][value="osm"]').trigger('click');`);
        await helpers.sleep(1000);

        // Change the zoom level
        const button = await page.$('#map');
        await button.click({ clickCount: 2 });
        await helpers.sleep(1000);

        // Click the reset button
        await page.click(`#btn-reset`);
        await helpers.sleep(4000);
        await page.evaluate(`$('[href="#collapseUHVibGljIGdyb3Vw"]').trigger('click')`);
        await helpers.sleep(1000);

        expect(await page.evaluate(`$('input[data-gc2-id="public.test"]').is(':checked')`)).to.be.false;

        // Check if the panel for different schema was drawn as well
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(0).text()`)).to.equal(`Test group`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(1).text()`)).to.equal(`Dar es Salaam Land Use and Informal Settlement Data Set`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(2).text()`)).to.equal(`Dynamic load test`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(3).text()`)).to.equal(`Snapping`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(4).text()`)).to.equal(`Public group`);

        expect(page.url()).to.have.string(`/app/aleksandrshumilov/public/#stamenTonerLite/10/39.2358/-6.8057/`);
    });

    it("should ignore invalid layer in URL", async () => {
        let page = await browser.newPage();
        await page.goto(`${helpers.PAGE_URL_DEFAULT}test.polygon,public.test_poly_invalid_layer,v:public.test_line`);
        page = await helpers.waitForPageToLoad(page);

        // Accepting the dialog
        page.on('dialog', (dialog) => {
            dialog.accept();
        });

        await page.evaluate(`$('[class="floatRight cursorPointer fa fa-reorder"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#layer-content"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#collapseUHVibGljIGdyb3Vw"]').trigger('click')`);
        await helpers.sleep(1000);

        expect(await page.evaluate(`$('input[data-gc2-id="test.polygon"]').is(':checked')`)).to.be.true;
        expect(await page.evaluate(`$('input[data-gc2-id="public.test_line"]').is(':checked')`)).to.be.true;
    });

    it("should update coordinates upon map changes", async () => {
        let page = await browser.newPage();
        await page.goto(`${helpers.PAGE_URL_DEFAULT}`);
        page = await helpers.waitForPageToLoad(page);

        await page.evaluate(`$('[class="floatRight cursorPointer fa fa-reorder"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#coordinates-content"]').trigger('click')`);
        await helpers.sleep(1000);

        let initialCoordinates = await page.evaluate(`$('#coordinates').find('h3').eq(1).next().html()`);

        await helpers.sleep(1000);
        await page.mouse.move(50, 50);
        await page.mouse.down();
        await page.mouse.move(100, 100);
        await page.mouse.up();
        await helpers.sleep(1000);
        await page.mouse.move(200, 200);

        await helpers.sleep(1000);

        let updatedCoordinates = await page.evaluate(`$('#coordinates').find('h3').eq(1).next().html()`);

        expect(initialCoordinates === updatedCoordinates).to.be.false;
    });
});
<commit_msg>Minor adaptation in test<commit_after>/**
 * Testing application
 */

const { expect } = require("chai");
const helpers = require("./../helpers");

describe("Application", () => {
    it("should be able to launch if service workers are not available", async () => {
        let page = await browser.newPage();
        await page.goto(`${helpers.PAGE_URL_DEFAULT_NO_SSL}`);
        page = await helpers.waitForPageToLoad(page);
    });

    it("should take into account configuration options", async () => {
        // Non-empty "activateMainTab" option (module)
        let page = await browser.newPage();
        await page.setRequestInterception(true);
        page.on('request', request => {
            if (request.url().indexOf(`aleksandrshumilov/aleksandrshumilov.json`) !== -1) {
                request.respond({
                    content: 'application/json',
                    headers: {"Access-Control-Allow-Origin": "*"},
                    body: JSON.stringify({
                        "brandName": "Test 1",
                        "activateMainTab": "streetView"
                    })
                });
            } else {
                request.continue();
            }
        });

        await page.goto(`${helpers.PAGE_URL_DEFAULT_NO_SSL}`);
        page = await helpers.waitForPageToLoad(page);
        await helpers.sleep(1000);
        let text = await page.evaluate(`$('.navbar-brand').text()`);
        expect(text.indexOf(`Test 1`) > -1).to.be.true;
        expect(await page.evaluate(`$('#streetView-content').is(':visible')`)).to.be.true;
        await page.close();

        // Non-empty "activateMainTab" option (extension)
        page = await browser.newPage();
        await page.setRequestInterception(true);
        page.on('request', request => {
            if (request.url().indexOf(`aleksandrshumilov/aleksandrshumilov.json`) !== -1) {
                request.respond({
                    content: 'application/json',
                    headers: {"Access-Control-Allow-Origin": "*"},
                    body: JSON.stringify({
                        "brandName": "Test 2",
                        "activateMainTab": "draw"
                    })
                });
            } else {
                request.continue();
            }
        });

        await page.goto(`${helpers.PAGE_URL_DEFAULT_NO_SSL}`);
        page = await helpers.waitForPageToLoad(page);
        await helpers.sleep(1000);
        text = await page.evaluate(`$('.navbar-brand').text()`);
        expect(text.indexOf(`Test 2`) > -1).to.be.true;
        expect(await page.evaluate(`$('[href="#draw-collapse"]').is(':visible')`)).to.be.true;
        await page.close();

        // Empty "activateMainTab" option
        let newPage = await browser.newPage();
        await newPage.goto(`${helpers.PAGE_URL_DEFAULT_NO_SSL}`);
        newPage = await helpers.waitForPageToLoad(newPage);
        await helpers.sleep(1000);
        expect(await newPage.evaluate(`$('[href="#draw-collapse"]').is(':visible')`)).to.be.false;
        await newPage.close();
    });

    it("should have only one active module at a time", async () => {
        let page = await browser.newPage();
        await page.goto(`${helpers.PAGE_URL_BASE}app/aleksandrshumilov/public/#osm/18/39.279/-6.8352/public.test_poly`);
        page = await helpers.waitForPageToLoad(page);

        let numberOfSQLRequests = 0;
        await helpers.sleep(1000);
        await page.setRequestInterception(true);
        page.on('request', request => {
            if (request.url().indexOf(`api/sql/aleksandrshumilov`) !== -1) {
                numberOfSQLRequests++;
            }

            request.continue();
        });

        // Info click has to be disabled by default
        await page.click(`#map`);
        await helpers.sleep(1000);
        expect(numberOfSQLRequests).to.equal(0);

        await page.evaluate(`$('[class="floatRight cursorPointer fa fa-reorder"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#info-content"]').trigger('click');`);
        await helpers.sleep(1000);

        // Info click was enabled before, so it has to handle map clicks
        await page.click(`#map`);
        await helpers.sleep(1000);
        expect(numberOfSQLRequests).to.equal(1);
        expect(await page.evaluate(`$('#module-container').length`)).to.equal(1);
        expect(await page.evaluate(`$('#module-container').css('right')`)).to.equal(`0px`);

        // Enabling measurements module, so all other modules have to be hidden
        await page.evaluate(`$('.js-measurements-control').trigger('click')`);
        await helpers.sleep(2000);
        expect(await page.evaluate(`$('#module-container').css('right')`)).to.equal(`-400px`);
        expect(await page.evaluate(`$('.leaflet-draw-draw-polyline').is(':visible')`)).to.be.true;

        // Enabling draw module
        await page.evaluate(`$('[href="#draw-content"]').trigger('click');`);
        await helpers.sleep(1000);
        expect(await page.evaluate(`$('#module-container').css('right')`)).to.equal(`0px`);
    });

    it("should be able to reset the application", async () => {
        let page = await browser.newPage();
        await page.goto(`${helpers.PAGE_URL_DEFAULT}test.polygon,public.urbanspatial_dar_es_salaam_luse_2002,public.test_poly,v:public.test,v:public.test_line`);
        page = await helpers.waitForPageToLoad(page);

        // Accepting the dialog
        page.on('dialog', (dialog) => {
            dialog.accept();
        });

        expect(page.url().indexOf(`test.polygon`) > 0).to.be.true;
        expect(page.url().indexOf(`public.urbanspatial_dar_es_salaam_luse_2002`) > 0).to.be.true;
        expect(page.url().indexOf(`public.test_poly`) > 0).to.be.true;
        expect(page.url().indexOf(`v:public.test`) > 0).to.be.true;
        expect(page.url().indexOf(`v:public.test_line`) > 0).to.be.true;

        await page.evaluate(`$('[class="floatRight cursorPointer fa fa-reorder"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#layer-content"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#collapseUHVibGljIGdyb3Vw"]').trigger('click')`);
        await helpers.sleep(1000);

        expect(await page.evaluate(`$('input[data-gc2-id="test.polygon"]').is(':checked')`)).to.be.true;
        expect(await page.evaluate(`$('input[data-gc2-id="public.test"]').is(':checked')`)).to.be.true;

        // Check if the panel for different schema was drawn as well
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(0).text()`)).to.equal(`Test group`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(1).text()`)).to.equal(`Dar es Salaam Land Use and Informal Settlement Data Set`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(2).text()`)).to.equal(`Dynamic load test`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(3).text()`)).to.equal(`Snapping`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(4).text()`)).to.equal(`Public group`);

        // Change the base layer
        await page.evaluate(`$('[href="#baselayer-content"]').trigger('click');`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[name="baselayers"][value="osm"]').trigger('click');`);
        await helpers.sleep(1000);

        // Change the zoom level
        const button = await page.$('#map');
        await button.click({ clickCount: 2 });
        await helpers.sleep(1000);

        // Click the reset button
        await page.click(`#btn-reset`);
        await helpers.sleep(4000);
        await page.evaluate(`$('[href="#collapseUHVibGljIGdyb3Vw"]').trigger('click')`);
        await helpers.sleep(1000);

        expect(await page.evaluate(`$('input[data-gc2-id="public.test"]').is(':checked')`)).to.be.false;

        // Check if the panel for different schema was drawn as well
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(0).text()`)).to.equal(`Test group`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(1).text()`)).to.equal(`Dar es Salaam Land Use and Informal Settlement Data Set`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(2).text()`)).to.equal(`Dynamic load test`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(3).text()`)).to.equal(`Snapping`);
        expect(await page.evaluate(`$('#layers_list').find('.accordion-toggle').eq(4).text()`)).to.equal(`Public group`);

        expect(page.url()).to.have.string(`/app/aleksandrshumilov/public/#stamenTonerLite/10/39.2358/-6.8057/`);
    });

    it("should ignore invalid layer in URL", async () => {
        let page = await browser.newPage();
        await page.goto(`${helpers.PAGE_URL_DEFAULT}test.polygon,public.test_poly_invalid_layer,v:public.test_line`);
        page = await helpers.waitForPageToLoad(page);

        // Accepting the dialog
        page.on('dialog', (dialog) => {
            dialog.accept();
        });

        await page.evaluate(`$('[class="floatRight cursorPointer fa fa-reorder"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#layer-content"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#collapseUHVibGljIGdyb3Vw"]').trigger('click')`);
        await helpers.sleep(1000);

        expect(await page.evaluate(`$('input[data-gc2-id="test.polygon"]').is(':checked')`)).to.be.true;
        expect(await page.evaluate(`$('input[data-gc2-id="public.test_line"]').is(':checked')`)).to.be.true;
    });

    it("should update coordinates upon map changes", async () => {
        let page = await browser.newPage();
        await page.goto(`${helpers.PAGE_URL_DEFAULT}`);
        page = await helpers.waitForPageToLoad(page);

        await page.evaluate(`$('[class="floatRight cursorPointer fa fa-reorder"]').trigger('click')`);
        await helpers.sleep(1000);
        await page.evaluate(`$('[href="#coordinates-content"]').trigger('click')`);
        await helpers.sleep(1000);

        let initialCoordinates = await page.evaluate(`$('#coordinates').find('h3').eq(1).next().html()`);

        await helpers.sleep(1000);
        await page.mouse.move(50, 50);
        await page.mouse.down();
        await page.mouse.move(100, 100);
        await page.mouse.up();
        await helpers.sleep(1000);
        await page.mouse.move(200, 200);

        await helpers.sleep(1000);

        let updatedCoordinates = await page.evaluate(`$('#coordinates').find('h3').eq(1).next().html()`);

        expect(initialCoordinates === updatedCoordinates).to.be.false;
    });
});
<|endoftext|>


<commit_before>require("should");
var DataUtil = require("../../data-util/sales/production-order-data-util");
var helper = require("../../helper");
var validate = require("dl-models").validator.sales.productionOrder;
var codeGenerator = require('../../../src/utils/code-generator');
var ProductionOrderManager = require("../../../src/managers/sales/production-order-manager");
var instanceManager;

before('#00. connect db', function (done) {
    helper.getDb()
        .then((db) => {
            instanceManager = new ProductionOrderManager(db, {
                username: 'dev'
            });
            done();
        })
        .catch(e => {
            done(e);
        });
});

var createdId;
it("#01. should success when create new data", function (done) {
    DataUtil.getNewData()

        .then((data) => instanceManager.create(data))
        .then((id) => {
            id.should.be.Object();
            createdId = id;
            done();
        })
        .catch((e) => {
            done(e);
        });
});

var createdData;
it(`#02. should success when get created data with id`, function (done) {
    instanceManager.getSingleById(createdId)
        .then((data) => {
            data.should.instanceof(Object);
            validate(data);
            createdData = data;
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it('#04. should success when create pdf', function (done) {
    var query = {};

    instanceManager.pdf(createdData._id, 7)
        .then((pdfData) => {
            done();
        }).catch((e) => {
            done(e);
        });
});

it("#05. should success update isRequested create context", function (done) {
    var data = {
        ids: [createdData._id],
        context: "CREATE"
    }
    instanceManager.updateIsRequested(data)
        .then((result) => {
            done();
        })
        .catch((e) => {
            done(e)
        })
});

it("#06. should success update isRequested delete context", function (done) {
    var data = {
        ids: [createdData._id],
        context: "DELETE"
    }
    instanceManager.updateIsRequested(data)
        .then((result) => {
            done();
        })
        .catch((e) => {
            done(e)
        })
});

it("#07. should success update isCompleted with context", function (done) {
    var data = {
        contextAndIds: [{
            id: createdData._id,
            context: "COMPLETE"
        },
        {
            id: createdData._id,
            context: "INCOMPLETE"
        }]
    }
    instanceManager.updateIsCompleted(data)
        .then((result) => {
            done();
        })
        .catch((e) => {
            done(e)
        })
});

it("#08. should success update distributed quantity with context", function (done) {
    var params = {
        contextQuantityAndIds: [{
            id: createdData._id,
            receivedQuantity: 10,
            context: "CREATE"
        },
        {
            id: createdData._id,
            receivedQuantity: 10,
            context: "DELETE"
        }]
    }

    instanceManager.updateDistributedQuantity(params)
        .then((result) => {
            done();
        })
        .catch((e) => {
            done(e)
        })
});

it("#09. should success when destroy all unit test data", function (done) {
    instanceManager.destroy(createdData._id)
        .then((result) => {
            result.should.be.Boolean();
            result.should.equal(true);
            done();
        })
        .catch((e) => {
            done(e);
        });
});
<commit_msg>update production order<commit_after>require("should");
var DataUtil = require("../../data-util/sales/production-order-data-util");
var helper = require("../../helper");
var validate = require("dl-models").validator.sales.productionOrder;
var codeGenerator = require('../../../src/utils/code-generator');
var ProductionOrderManager = require("../../../src/managers/sales/production-order-manager");
var instanceManager;

before('#00. connect db', function (done) {
    helper.getDb()
        .then((db) => {
            instanceManager = new ProductionOrderManager(db, {
                username: 'dev'
            });
            done();
        })
        .catch(e => {
            done(e);
        });
});

var createdId;
it("#01. should success when create new data", function (done) {
    DataUtil.getNewData()

        .then((data) => instanceManager.create(data))
        .then((id) => {
            id.should.be.Object();
            createdId = id;
            done();
        })
        .catch((e) => {
            done(e);
        });
});

var createdData;
it(`#02. should success when get created data with id`, function (done) {
    instanceManager.getSingleById(createdId)
        .then((data) => {
            data.should.instanceof(Object);
            validate(data);
            createdData = data;
            done();
        })
        .catch((e) => {
            done(e);
        });
});

it('#04. should success when create pdf', function (done) {
    var query = {};

    instanceManager.pdf(createdData._id, 7)
        .then((pdfData) => {
            done();
        }).catch((e) => {
            done(e);
        });
});

it("#05. should success update isRequested create context", function (done) {
    var data = {
        ids: [createdData._id],
        context: "CREATE"
    }
    instanceManager.updateIsRequested(data)
        .then((result) => {
            done();
        })
        .catch((e) => {
            done(e)
        })
});

it("#06. should success update isRequested delete context", function (done) {
    var data = {
        ids: [createdData._id],
        context: "DELETE"
    }
    instanceManager.updateIsRequested(data)
        .then((result) => {
            done();
        })
        .catch((e) => {
            done(e)
        })
});

it("#07. should success update isCompleted with context", function (done) {
    var data = {
        contextAndIds: [{
            id: createdData._id,
            context: "COMPLETE"
        },
        {
            id: createdData._id,
            context: "INCOMPLETE"
        }]
    }
    instanceManager.updateIsCompleted(data)
        .then((result) => {
            done();
        })
        .catch((e) => {
            done(e)
        })
});

it("#08. should success update distributed quantity with context", function (done) {
    var params = {
        contextQuantityAndIds: [{
            id: createdData._id,
            distributedQuantity: 10,
            context: "CREATE"
        },
        {
            id: createdData._id,
            distributedQuantity: 10,
            context: "DELETE"
        }]
    }

    instanceManager.updateDistributedQuantity(params)
        .then((result) => {
            done();
        })
        .catch((e) => {
            done(e)
        })
});

it("#09. should success when destroy all unit test data", function (done) {
    instanceManager.destroy(createdData._id)
        .then((result) => {
            result.should.be.Boolean();
            result.should.equal(true);
            done();
        })
        .catch((e) => {
            done(e);
        });
});
<|endoftext|>


<commit_before>/*
EB_Template version: 1.41
https://github.com/Amarok24/EB-template
EB_Template is released under The Unlicense,
see LICENSE.md or http://unlicense.org/ for more information.
*/

var EB_Template = (function() {

  "use strict";

  const _onePageLayout = false; // set this to either "true" or "false"
  const _desktopBreakpoint = 481; // set this to define minimal screen width for desktop layout

  var _monsterTemplateType = {
    jv30_general: false, // true in both cases: fullpage + combined view
    jv30_combined: false  // true only in combinded view
  };
  var _timeoutIDwindowResize = null;
  var _isMobileScreen = false;
  var _winScrollBy = null; // used by scrollToObject
  var _JobViewHeader = null; // used in jv30_combined
  var _iframeParent = null; // used in jv30

/*
  function idGetCss(s_elementId, s_styleProp) {
    var element = document.getElementById(s_elementId);
    return window.getComputedStyle(element, null).getPropertyValue(s_styleProp);
  }
  function idSetCss(s_elementId, s_styleName, s_styleProp) {
    // styleNames are CSS2Properties:  backgroundColor, fontSize ...
    document.getElementById(s_elementId).style[s_styleName] = s_styleProp;
  }
  function addClassAll(myQuery, className) {
    var nodeList = document.querySelectorAll(myQuery);
    // classList in IE 10+, nodeList as result from querySelectorAll etc.
    for (var i = 0; i < nodeList.length; i++) {
      nodeList[i].classList.add(className);
    }
  }
  function toggleClassAll(myQuery, className) {
    var nodeList = document.querySelectorAll(myQuery);
    for (var i = 0; i < nodeList.length; i++) {
      nodeList[i].classList.toggle(className);
    }
  }
*/

  function removeClassAll(myQuery, className) {
    var nodeList = document.querySelectorAll(myQuery);
    for (var i = 0; i < nodeList.length; i++) {
      nodeList[i].classList.remove(className);
    }
  }

  function iframeParentResize() {
    // this function handles iframe height in JV30
    var container = document.querySelector(".containerIA");

    // the following could not be tested yet, *TODO* test in live environment
    var MUXmethod = window.parent.window.MUX;
    if ((MUXmethod != null) && (MUXmethod.callResize != null)) {
      try {
        MUXmethod.callResize();
        console.info("_iframeParent resized, MUX method");
      } catch (er) {
        console.error("EB_template: callResize error", er);
      }
    } else {
      _iframeParent.style.height = container.offsetHeight + 10 + "px";
      console.info("_iframeParent resized, own method");
    }
  }

  function scrollToObject(elementObject, yCorrection) {
    try {
      elementObject.scrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'});
      if ( (yCorrection != null) && (yCorrection != 0) ) {
        window.setTimeout( function() {_winScrollBy(0, yCorrection);}, 800); // dirty hack because scrollIntoView is asynchronous, *TODO*
      }
    } catch (er) {
      console.error("scrollToObject error", er);
    }
  }

  function navButtonClick(buttonIndex, ev /* default true (MouseEvent click) */ ) {
    var i;
    var tabContent = document.querySelectorAll(".containerIA .tabContent");
    var clickOrigin = ev ? ev.target.parentElement.id : null;

    if (!_onePageLayout) {
      for (i = 0; i < tabContent.length; i++) {
        tabContent[i].style.display = "none";
      }
      tabContent[buttonIndex].style.display = "block";
      removeClassAll("#navigation button", "active");
      document.querySelectorAll("#navigation button")[buttonIndex].classList.add("active");
    }

    // first we need to resize iframe and THEN we can scroll, else wrong behaviour can be expected
    if (_monsterTemplateType.jv30_general) {
      window.setTimeout(iframeParentResize, 80); // wait a little bit for content to settle
    }

    if (_onePageLayout || _isMobileScreen || (clickOrigin == "sitemap")) {
      window.setTimeout( function() {scrollToObject(tabContent[buttonIndex]);}, 120);
    }
  }

  function onWindowResize() {
    function windowResizeAction() {
      var mainContainer = document.getElementsByClassName("containerIA")[0];
      var availWidth = document.body.clientWidth;

      mainContainer.classList.remove("mobile");
      if (availWidth < _desktopBreakpoint) {
        _isMobileScreen = true;
        mainContainer.classList.add("mobile");
      } else {
        _isMobileScreen = false;
      }
      console.log("EB_Template _isMobileScreen:", _isMobileScreen);
      if (_monsterTemplateType.jv30_general) {
        iframeParentResize();
      }
    }

    if (_timeoutIDwindowResize) {
      window.clearTimeout(_timeoutIDwindowResize);
    }
    _timeoutIDwindowResize = window.setTimeout(windowResizeAction, 50);
  }

  function onParentContentScroll() {
    if (_JobViewHeader.classList.contains("is-reduced")) {
      _iframeParent.style.marginTop = "72px";
    } else {
      _iframeParent.style.marginTop = "0";
    }
  }

  function initStartingTab() {
    // switches to some tab directly if URL parameter "tab" found, or just switches to 1st tab
    var params = {}, // pairs of  key - value (name - value)
        locationSearch = "",
        i;

    if (_monsterTemplateType.jv30_general) {
      try {
        locationSearch = window.parent.location.search;
      }
      catch(er) {
        console.error("EB_Template initStartingTab: locationSearch error, details following");
        console.log(er);
      }
    } else {
      locationSearch = window.location.search;
    }

    if (locationSearch) {
      var a_parts = locationSearch.substring(1).split('&');
      // "a_parts" will be eg. ["tab=2", "bla=text", "val="]
      for (i = 0; i < a_parts.length; i++) {
        var nv = a_parts[i].split('=');
        console.log("EB_Template initStartingTab:", nv);
        if (!nv[0]) {
          continue;
        } // skip cases like "=25" with no 'key'
        params[nv[0]] = nv[1] || true; // 'true' if no value was provided
      }
    }

    if (params.tab) {
      try {
        navButtonClick(params.tab);
        //document.querySelectorAll("#navigation button")[params.tab].click();
      } catch (er) {
        console.error("EB_Template initStartingTab: navigation click error, details following");
        console.log(er);
        navButtonClick(0);
      }
    } else {
      navButtonClick(0);
    }
  } // end initStartingTab

  function addEvents() {
    var i;
    var navItems = document.querySelectorAll("#navigation button");
    var navSitemapItems = document.querySelectorAll("#sitemap button");

    for (i = 0; i < navItems.length; i++) {
      navItems[i].addEventListener("click", navButtonClick.bind(null, i));
      navSitemapItems[i].addEventListener("click", navButtonClick.bind(null, i));
    }
    window.addEventListener("resize", onWindowResize);
    if (_monsterTemplateType.jv30_combined) {
      window.parent.document.getElementById("ContentScrollable").addEventListener("scroll", onParentContentScroll);
    }
  }

  function detectMonsterTemplateType() {
    var jobId = document.getElementsByTagName("body")[0].getAttribute("data-job-id");

    function insideOfIframe() { // test if this html document is in iframe
      try { return window.self !== window.top }
      catch (e) { return true; } // fallback for bad browsers, assumes true
    }

    _monsterTemplateType.jv30_general = insideOfIframe();
    _monsterTemplateType.jv30_combined = window.parent.document.getElementById("ContentScrollable") ? true : false;

    console.group("EB_Template detectMonsterTemplateType");
    console.log("_monsterTemplateType:", _monsterTemplateType);
    if (jobId) { console.log("jobId = ", jobId); }
    console.groupEnd();
  }

  function initAllTabs() {
    var i;
    var tabContents = document.querySelectorAll(".containerIA .tabContent");

    if (_monsterTemplateType.jv30_general) {
      _winScrollBy = window.parent.scrollBy;
      // *TODO* window.parent.scrollBy has no effect for combined view (DIV scrolls)
      _iframeParent = window.parent.document.getElementById("JobPreviewSandbox");
    } else {
      _winScrollBy =  window.scrollBy;
    }

    if (_monsterTemplateType.jv30_combined) {
      _iframeParent.style.transition = "margin-top 1s";
      _JobViewHeader = window.parent.document.getElementById("JobViewHeader");
    }

    if (!_onePageLayout) {
      for (i = 0; i < tabContents.length; i++) {
        tabContents[i].style.display = "none";
      }
      initStartingTab();
    }
  }

  function startTemplate() {
    detectMonsterTemplateType();
    onWindowResize(); // decides if mobile view should be used
    addEvents();
    initAllTabs();
  }

  document.addEventListener("DOMContentLoaded", startTemplate);

  return {
    /*publicProperty: "test",
    publicMethod: function() {},*/
    navButtonClick: navButtonClick,
    _monsterTemplateType: _monsterTemplateType // info: public properties won't get updated during runtime
  };

})(); // end EB_Template
<commit_msg>Add files via upload<commit_after>/*
EB_Template version: 1.42
https://github.com/Amarok24/EB-template
EB_Template is released under The Unlicense,
see LICENSE.md or http://unlicense.org/ for more information.
*/

var EB_Template = (function() {

  "use strict";

  const _onePageLayout = false; // set this to either "true" or "false"
  const _desktopBreakpoint = 481; // set this to define minimal screen width for desktop layout

  var _monsterTemplateType = {
    jv30_general: false, // true in both cases: fullpage + combined view
    jv30_combined: false  // true only in combinded view
  };
  var _timeoutIDwindowResize = null;
  var _isMobileScreen = false;
  var _winScrollBy = null; // used by scrollToObject
  var _iframeParent = null; // used in jv30

/*
  function idGetCss(s_elementId, s_styleProp) {
    var element = document.getElementById(s_elementId);
    return window.getComputedStyle(element, null).getPropertyValue(s_styleProp);
  }
  function idSetCss(s_elementId, s_styleName, s_styleProp) {
    // styleNames are CSS2Properties:  backgroundColor, fontSize ...
    document.getElementById(s_elementId).style[s_styleName] = s_styleProp;
  }
  function addClassAll(myQuery, className) {
    var nodeList = document.querySelectorAll(myQuery);
    // classList in IE 10+, nodeList as result from querySelectorAll etc.
    for (var i = 0; i < nodeList.length; i++) {
      nodeList[i].classList.add(className);
    }
  }
  function toggleClassAll(myQuery, className) {
    var nodeList = document.querySelectorAll(myQuery);
    for (var i = 0; i < nodeList.length; i++) {
      nodeList[i].classList.toggle(className);
    }
  }
*/

  function removeClassAll(myQuery, className) {
    var nodeList = document.querySelectorAll(myQuery);
    for (var i = 0; i < nodeList.length; i++) {
      nodeList[i].classList.remove(className);
    }
  }

  function iframeParentResize() {
    // this function handles iframe height in JV30
    var container = document.querySelector(".containerIA");

    // the following could not be tested yet, *TODO* test in live environment
    /*
    var MUXmethod = window.parent.window.MUX;
    if ((MUXmethod != null) && (MUXmethod.callResize != null)) {
      try {
        MUXmethod.callResize();
        console.info("_iframeParent resized, MUX method");
      } catch (er) {
        console.error("EB_template: callResize error", er);
      }
    } else {
      _iframeParent.style.height = container.offsetHeight + 10 + "px";
      console.info("_iframeParent resized, own method");
    }
    */
    _iframeParent.style.height = container.offsetHeight + 10 + "px";
    console.info("_iframeParent resized, own method");
  }

  function scrollToObject(elementObject, yCorrection) {
    try {
      elementObject.scrollIntoView({behavior: 'instant', block: 'start', inline: 'nearest'});
      if ( (yCorrection != null) && (yCorrection != 0) ) {
        window.setTimeout( function() {_winScrollBy(0, yCorrection);}, 50); // dirty hack because scrollIntoView is asynchronous, *TODO*
      }
    } catch (er) {
      console.error("scrollToObject error", er);
    }
  }

  function navButtonClick(buttonIndex, ev /* default true (MouseEvent click) */ ) {
    var i;
    var tabContent = document.querySelectorAll(".containerIA .tabContent");
    var clickOrigin = ev ? ev.target.parentElement.id : null;
    var scrollCorrection = _monsterTemplateType.jv30_combined ? -78 : 0; // JobViewHeader height is 72px

    if (!_onePageLayout) {
      for (i = 0; i < tabContent.length; i++) {
        tabContent[i].style.display = "none";
      }
      tabContent[buttonIndex].style.display = "block";
      removeClassAll("#navigation button", "active");
      document.querySelectorAll("#navigation button")[buttonIndex].classList.add("active");
    }

    // first we need to resize iframe and THEN we can scroll, else wrong behaviour can be expected
    if (_monsterTemplateType.jv30_general) {
      window.setTimeout(iframeParentResize, 80); // wait a little bit for content to settle
    }

    if (_onePageLayout || _isMobileScreen || (clickOrigin == "sitemap")) {
      window.setTimeout( function() {scrollToObject(tabContent[buttonIndex], scrollCorrection);}, 120);
    }
  }

  function onWindowResize() {
    function windowResizeAction() {
      var mainContainer = document.getElementsByClassName("containerIA")[0];
      var availWidth = document.body.clientWidth;

      mainContainer.classList.remove("mobile");
      if (availWidth < _desktopBreakpoint) {
        _isMobileScreen = true;
        mainContainer.classList.add("mobile");
      } else {
        _isMobileScreen = false;
      }
      console.log("EB_Template _isMobileScreen:", _isMobileScreen);
      if (_monsterTemplateType.jv30_general) {
        iframeParentResize();
      }
    }

    if (_timeoutIDwindowResize) {
      window.clearTimeout(_timeoutIDwindowResize);
    }
    _timeoutIDwindowResize = window.setTimeout(windowResizeAction, 50);
  }

/*
  function onParentContentScroll() {
    // combined view feature to detect reduced banner
    if (_JobViewHeader.classList.contains("is-reduced")) {
      _iframeParent.style.marginTop = "72px";
    } else {
      _iframeParent.style.marginTop = "0";
    }
  }
*/

  function initStartingTab() {
    // switches to some tab directly if URL parameter "tab" found, or just switches to 1st tab
    var params = {}, // pairs of  key - value (name - value)
        locationSearch = "",
        i;

    if (_monsterTemplateType.jv30_general) {
      try {
        locationSearch = window.parent.location.search;
      }
      catch(er) {
        console.error("EB_Template initStartingTab: locationSearch error, details following");
        console.log(er);
      }
    } else {
      locationSearch = window.location.search;
    }

    if (locationSearch) {
      var a_parts = locationSearch.substring(1).split('&');
      // "a_parts" will be eg. ["tab=2", "bla=text", "val="]
      for (i = 0; i < a_parts.length; i++) {
        var nv = a_parts[i].split('=');
        console.log("EB_Template initStartingTab:", nv);
        if (!nv[0]) {
          continue;
        } // skip cases like "=25" with no 'key'
        params[nv[0]] = nv[1] || true; // 'true' if no value was provided
      }
    }

    if (params.tab) {
      try {
        navButtonClick(params.tab);
        //document.querySelectorAll("#navigation button")[params.tab].click();
      } catch (er) {
        console.error("EB_Template initStartingTab: navigation click error, details following");
        console.log(er);
        navButtonClick(0);
      }
    } else {
      navButtonClick(0);
    }
  } // end initStartingTab

  function addEvents() {
    var i;
    var navItems = document.querySelectorAll("#navigation button");
    var navSitemapItems = document.querySelectorAll("#sitemap button");

    for (i = 0; i < navItems.length; i++) {
      navItems[i].addEventListener("click", navButtonClick.bind(null, i));
      navSitemapItems[i].addEventListener("click", navButtonClick.bind(null, i));
    }
    window.addEventListener("resize", onWindowResize);
    /*
    if (_monsterTemplateType.jv30_combined) {
      window.parent.document.getElementById("ContentScrollable").addEventListener("scroll", onParentContentScroll);
    }
    */
  }

  function detectMonsterTemplateType() {
    var jobId = document.getElementsByTagName("body")[0].getAttribute("data-job-id");

    function insideOfIframe() { // test if this html document is in iframe
      try { return window.self !== window.top }
      catch (e) { return true; } // fallback for bad browsers, assumes true
    }

    _monsterTemplateType.jv30_general = insideOfIframe();
    _monsterTemplateType.jv30_combined = window.parent.document.getElementById("ContentScrollable") ? true : false;

    console.group("EB_Template detectMonsterTemplateType");
    console.log("_monsterTemplateType:", _monsterTemplateType);
    if (jobId) { console.log("jobId = ", jobId); }
    console.groupEnd();
  }

  function initAllTabs() {
    var i;
    var tabContents = document.querySelectorAll(".containerIA .tabContent");

    if (_monsterTemplateType.jv30_combined) {
      _winScrollBy =  window.parent.document.getElementById("ContentScrollable").scrollBy;
      _iframeParent = window.parent.document.getElementById("JobPreviewSandbox");
      //_JobViewHeader = window.parent.document.getElementById("JobViewHeader");
    } else if (_monsterTemplateType.jv30_general) {
      _winScrollBy = window.parent.scrollBy;
      _iframeParent = window.parent.document.getElementById("JobPreviewSandbox");
    } else {
      _winScrollBy =  window.scrollBy;
    }

    if (!_onePageLayout) {
      for (i = 0; i < tabContents.length; i++) {
        tabContents[i].style.display = "none";
      }
      initStartingTab();
    }
  }

  function startTemplate() {
    detectMonsterTemplateType();
    onWindowResize(); // decides if mobile view should be used
    addEvents();
    initAllTabs();
  }

  document.addEventListener("DOMContentLoaded", startTemplate);

  return {
    /*publicProperty: "test",
    publicMethod: function() {},*/
    navButtonClick: navButtonClick,
    _monsterTemplateType: _monsterTemplateType // info: public properties won't get updated during runtime
  };

})(); // end EB_Template
<|endoftext|>


<commit_before>/*
 * Copyright 2011 eBay Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
function removeDashes(str) {
    return str.replace(/-([a-z])/g, function (match, lower) {
        return lower.toUpperCase();
    });
}
var extend = require('raptor-util').extend;

var WriteNode = require('./WriteNode');
var ForNode = require('./ForNode');
var IfNode = require('./IfNode');
var ElseIfNode = require('./ElseIfNode');
var ElseNode = require('./ElseNode');
var WithNode = require('./WithNode');
var WhenNode = require('./WhenNode');
var OtherwiseNode = require('./OtherwiseNode');
var TagHandlerNode = require('./TagHandlerNode');
var IncludeNode = require('./IncludeNode');

var resolver = require('raptor-modules/resolver');

function handleAttr(node, compiler, template) {
    var parentNode = node.parentNode;
    if (!parentNode.isElementNode()) {
        node.addError(node.toString() + ' tag is not nested within an element tag.');
        return;
    }
    var hasValue = node.hasAttribute('value');
    var attrName = node.getAttribute('name');
    var attrValue = node.getAttribute('value');
    var attrUri = node.getAttribute('namespace') || '';
    var attrPrefix = node.getAttribute('prefix') || '';
    if (parentNode.hasAttributeNS(attrUri, attrName)) {
        node.addError(node.toString() + ' tag adds duplicate attribute with name "' + attrName + '"' + (attrUri ? ' and URI "' + attrUri + '"' : ''));
        return;
    }
    node.removeAttribute('name');
    node.removeAttribute('value');
    node.removeAttribute('namespace');
    node.removeAttribute('prefix');
    if (node.hasAttributesAnyNS()) {
        var invalidAttrs = node.getAllAttributes().map(function (attr) {
                return attr.qName;
            });
        node.addError('Invalid attributes for tag ' + node.toString() + ': ' + invalidAttrs.join(', '));
        return;
    }
    //Cleanup whitespace between <c-attr> tags
    if (node.previousSibling && node.previousSibling.isTextNode() && node.previousSibling.getText().trim() === '') {
        node.previousSibling.detach();
    }
    if (node.nextSibling && node.nextSibling.isTextNode() && node.nextSibling.getText().trim() === '') {
        node.nextSibling.detach();
    }
    if (node.nextSibling && node.nextSibling.isTextNode()) {
        node.nextSibling.setText(node.nextSibling.getText().replace(/^\n\s*/, ''));
    }
    node.detach();
    //Remove the node out of the tree
    compiler.transformTree(node, template);
    if (hasValue) {
        parentNode.setAttributeNS(attrUri, attrName, attrValue, attrPrefix);
    } else {
        node.setEscapeXmlContext('ATTRIBUTE');
        //Escape body text and expressions as attributes
        parentNode.setAttributeNS(attrUri, attrName, node.getBodyContentExpression(template), attrPrefix, false);
    }
}

function findNestedAttrs(node, compiler, template) {
    node.forEachChild(function (child) {
        if (child.qName === 'c-attr') {
            handleAttr(child, compiler, template);
        }
    });
}

module.exports = function transform(node, compiler, template) {

    //Find and handle nested <c-attrs> elements
    findNestedAttrs(node, compiler, template);

    var inputAttr;
    var forEachNode;
    var tag;

    function forEachProp(callback, thisObj) {
        var foundProps = {};

        node.forEachAttributeAnyNS(function (attr) {
            var attrDef = compiler.taglibs.getAttribute(node, attr);
            var type = attrDef ? attrDef.type || 'string' : 'string';

            var value;

            if (!attrDef) {
                // var isAttrForTaglib = compiler.taglibs.isTaglib(attrUri);
                //Tag doesn't allow dynamic attributes
                node.addError('The tag "' + tag.name + '" in taglib "' + tag.taglibId + '" does not support attribute "' + attr + '"');
                return;
            }

            if (compiler.isExpression(attr.value)) {
                value = attr.value;
            } else {
                try {
                    value = compiler.convertType(attr.value, type, attrDef ? attrDef.allowExpressions !== false : true);
                } catch (e) {
                    node.addError('Invalid attribute value of "' + attr.value + '" for attribute "' + attr.name + '": ' + e.message);
                    value = attr.value;
                }

            }
            var propName;
            if (attrDef.dynamicAttribute) {
                propName = attr.qName;
            } else {
                if (attrDef.targetProperty) {
                    propName = attrDef.targetProperty;
                } else if (attrDef.preserveName) {
                    propName = attr.localName;
                } else {
                    propName = removeDashes(attr.localName);
                }
            }

            foundProps[propName] = true;
            callback.call(thisObj, propName, value, attrDef);
        });

        tag.forEachAttribute(function (attr) {
            if (attr.hasOwnProperty('defaultValue') && !foundProps[attr.name]) {
                callback.call(thisObj, attr.name, template.makeExpression(JSON.stringify(attr.defaultValue)), '', attr);
            }
        });
    }

    tag = node.tag || compiler.taglibs.getTag(node);

    var coreAttrHandlers = {
        'c-space': function(attr) {
            this['c-whitespace'](attr);
        },
        'c-whitespace': function(attr) {
            if (attr.value === 'preserve') {
                node.setPreserveWhitespace(true);
            }
        },
        'c-escape-xml': function(attr) {
            node.setEscapeXmlBodyText(attr.value !== 'false');
        },
        'c-parse-body-text': function(attr) {
            node.parseBodyText = attr.value !== 'false';
        },
        'c-when': function(attr) {
            var whenNode = compiler.createNode(WhenNode, {
                    test: template.makeExpression(attr.value),
                    pos: node.getPosition()
                });
            node.parentNode.replaceChild(whenNode, node);
            whenNode.appendChild(node);
        },
        'c-otherwise': function(attr) {
            var otherwiseNode = compiler.createNode(OtherwiseNode, { pos: node.getPosition() });
            node.parentNode.replaceChild(otherwiseNode, node);
            otherwiseNode.appendChild(node);
        },
        'c-attrs': function(attr) {
            node.dynamicAttributesExpression = attr.value;
        },
        'c-for-each': function(attr) {
            this['for'](attr);
        },
        'c-for': function(attr) {
            var forEachProps = compiler.parseAttribute(attr.value, {
                    each: { type: 'custom' },
                    separator: { type: 'expression' },
                    'iterator': { type: 'expression' },
                    'status-var': { type: 'identifier' },
                    'for-loop': {
                        type: 'boolean',
                        allowExpressions: false
                    }
                }, {
                    removeDashes: true,
                    defaultName: 'each',
                    errorHandler: function (message) {
                        node.addError('Invalid c-for attribute of "' + attr.value + '". Error: ' + message);
                    }
                });
            forEachProps.pos = node.getPosition();
            //Copy the position property
            forEachNode = compiler.createNode(ForNode, forEachProps);
            //Surround the existing node with an "forEach" node by replacing the current
            //node with the new "forEach" node and then adding the current node as a child
            node.parentNode.replaceChild(forEachNode, node);
            forEachNode.appendChild(node);
        },
        'c-if': function(attr) {
            var ifNode = compiler.createNode(IfNode, {
                    test: template.makeExpression(attr.value),
                    pos: node.getPosition()
                });
            //Surround the existing node with an "if" node by replacing the current
            //node with the new "if" node and then adding the current node as a child
            node.parentNode.replaceChild(ifNode, node);
            ifNode.appendChild(node);
        },
        'c-else-if': function(attr) {
            var elseIfNode = compiler.createNode(ElseIfNode, {
                    test: template.makeExpression(attr.value),
                    pos: node.getPosition()
                });
            //Surround the existing node with an "if" node by replacing the current
            //node with the new "if" node and then adding the current node as a child
            node.parentNode.replaceChild(elseIfNode, node);
            elseIfNode.appendChild(node);
        },
        'c-else': function(attr) {
            var elseNode = compiler.createNode(ElseNode, { pos: node.getPosition() });
            //Surround the existing node with an "if" node by replacing the current
            //node with the new "if" node and then adding the current node as a child
            node.parentNode.replaceChild(elseNode, node);
            elseNode.appendChild(node);
        },
        'c-with': function(attr) {
            var withNode = compiler.createNode(WithNode, {
                    vars: attr.value,
                    pos: node.getPosition()
                });
            node.parentNode.replaceChild(withNode, node);
            withNode.appendChild(node);
        },
        'c-body-content': function(attr) {
            this.content(attr);
        },
        'c-content': function(attr) {
            var newChild = compiler.createNode(WriteNode, {
                    expression: attr.value,
                    pos: node.getPosition()
                });
            node.removeChildren();
            node.appendChild(newChild);
        },
        'c-trim-body-indent': function(attr) {
            if (attr.value === 'true') {
                node.trimBodyIndent = true;
            }
        },
        'c-strip': function(attr) {
            if (!node.setStripExpression) {
                node.addError('The c-strip directive is not allowed for target node');
            }
            node.setStripExpression(attr.value);
        },
        'c-replace': function(attr) {
            var replaceWriteNode = compiler.createNode(WriteNode, {
                    expression: attr.value,
                    pos: node.getPosition()
                });
            //Replace the existing node with an node that only has children
            node.parentNode.replaceChild(replaceWriteNode, node);
            node = replaceWriteNode;
        },
        'c-input': function(attr) {
            inputAttr = attr.value;
        }
    };

    node.forEachAttributeNS('', function(attr) {

        var handler = coreAttrHandlers[attr.qName];
        if (handler) {
            node.removeAttribute(attr.localName);
            coreAttrHandlers[attr.localName](attr);
        }
    });

    if (tag) {
        if (tag.preserveWhitespace) {
            node.setPreserveWhitespace(true);
        }
        if (tag.renderer || tag.template) {
            if (tag.renderer) {
                //Instead of compiling as a static XML element, we'll
                //make the node render as a tag handler node so that
                //writes code that invokes the handler
                TagHandlerNode.convertNode(node, tag);
                if (inputAttr) {
                    node.setInputExpression(template.makeExpression(inputAttr));
                }
            } else {
                var templatePath = resolver.deresolve(tag.template, compiler.dirname);
                // The tag is mapped to a template that will be used to perform
                // the rendering so convert the node into a "IncludeNode" that can
                // be used to include the output of rendering a template
                IncludeNode.convertNode(node, templatePath);
            }

            forEachProp(function (name, value, attrDef) {
                if (attrDef.dynamicAttribute && attrDef.targetProperty) {
                    if (attrDef.removeDashes === true) {
                        name = removeDashes(name);
                    }
                    node.addDynamicAttribute(name, value);
                    node.setDynamicAttributesProperty(attrDef.targetProperty);
                } else {
                    node.setProperty(name, value);
                }
            });

        } else if (tag.nodeClass) {
            var NodeCompilerClass = require(tag.nodeClass);
            compiler.inheritNode(NodeCompilerClass);
            extend(node, NodeCompilerClass.prototype);
            NodeCompilerClass.call(node);
            node.setNodeClass(NodeCompilerClass);
            forEachProp(function (name, value) {
                node.setProperty(name, value);
            });
        }
    }
};<commit_msg>Allow c-data as synonym for c-input<commit_after>/*
 * Copyright 2011 eBay Software Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
function removeDashes(str) {
    return str.replace(/-([a-z])/g, function (match, lower) {
        return lower.toUpperCase();
    });
}
var extend = require('raptor-util').extend;

var WriteNode = require('./WriteNode');
var ForNode = require('./ForNode');
var IfNode = require('./IfNode');
var ElseIfNode = require('./ElseIfNode');
var ElseNode = require('./ElseNode');
var WithNode = require('./WithNode');
var WhenNode = require('./WhenNode');
var OtherwiseNode = require('./OtherwiseNode');
var TagHandlerNode = require('./TagHandlerNode');
var IncludeNode = require('./IncludeNode');

var resolver = require('raptor-modules/resolver');

function handleAttr(node, compiler, template) {
    var parentNode = node.parentNode;
    if (!parentNode.isElementNode()) {
        node.addError(node.toString() + ' tag is not nested within an element tag.');
        return;
    }
    var hasValue = node.hasAttribute('value');
    var attrName = node.getAttribute('name');
    var attrValue = node.getAttribute('value');
    var attrUri = node.getAttribute('namespace') || '';
    var attrPrefix = node.getAttribute('prefix') || '';
    if (parentNode.hasAttributeNS(attrUri, attrName)) {
        node.addError(node.toString() + ' tag adds duplicate attribute with name "' + attrName + '"' + (attrUri ? ' and URI "' + attrUri + '"' : ''));
        return;
    }
    node.removeAttribute('name');
    node.removeAttribute('value');
    node.removeAttribute('namespace');
    node.removeAttribute('prefix');
    if (node.hasAttributesAnyNS()) {
        var invalidAttrs = node.getAllAttributes().map(function (attr) {
                return attr.qName;
            });
        node.addError('Invalid attributes for tag ' + node.toString() + ': ' + invalidAttrs.join(', '));
        return;
    }
    //Cleanup whitespace between <c-attr> tags
    if (node.previousSibling && node.previousSibling.isTextNode() && node.previousSibling.getText().trim() === '') {
        node.previousSibling.detach();
    }
    if (node.nextSibling && node.nextSibling.isTextNode() && node.nextSibling.getText().trim() === '') {
        node.nextSibling.detach();
    }
    if (node.nextSibling && node.nextSibling.isTextNode()) {
        node.nextSibling.setText(node.nextSibling.getText().replace(/^\n\s*/, ''));
    }
    node.detach();
    //Remove the node out of the tree
    compiler.transformTree(node, template);
    if (hasValue) {
        parentNode.setAttributeNS(attrUri, attrName, attrValue, attrPrefix);
    } else {
        node.setEscapeXmlContext('ATTRIBUTE');
        //Escape body text and expressions as attributes
        parentNode.setAttributeNS(attrUri, attrName, node.getBodyContentExpression(template), attrPrefix, false);
    }
}

function findNestedAttrs(node, compiler, template) {
    node.forEachChild(function (child) {
        if (child.qName === 'c-attr') {
            handleAttr(child, compiler, template);
        }
    });
}

module.exports = function transform(node, compiler, template) {

    //Find and handle nested <c-attrs> elements
    findNestedAttrs(node, compiler, template);

    var inputAttr;
    var forEachNode;
    var tag;

    function forEachProp(callback, thisObj) {
        var foundProps = {};

        node.forEachAttributeAnyNS(function (attr) {
            var attrDef = compiler.taglibs.getAttribute(node, attr);
            var type = attrDef ? attrDef.type || 'string' : 'string';

            var value;

            if (!attrDef) {
                // var isAttrForTaglib = compiler.taglibs.isTaglib(attrUri);
                //Tag doesn't allow dynamic attributes
                node.addError('The tag "' + tag.name + '" in taglib "' + tag.taglibId + '" does not support attribute "' + attr + '"');
                return;
            }

            if (compiler.isExpression(attr.value)) {
                value = attr.value;
            } else {
                try {
                    value = compiler.convertType(attr.value, type, attrDef ? attrDef.allowExpressions !== false : true);
                } catch (e) {
                    node.addError('Invalid attribute value of "' + attr.value + '" for attribute "' + attr.name + '": ' + e.message);
                    value = attr.value;
                }

            }
            var propName;
            if (attrDef.dynamicAttribute) {
                propName = attr.qName;
            } else {
                if (attrDef.targetProperty) {
                    propName = attrDef.targetProperty;
                } else if (attrDef.preserveName) {
                    propName = attr.localName;
                } else {
                    propName = removeDashes(attr.localName);
                }
            }

            foundProps[propName] = true;
            callback.call(thisObj, propName, value, attrDef);
        });

        tag.forEachAttribute(function (attr) {
            if (attr.hasOwnProperty('defaultValue') && !foundProps[attr.name]) {
                callback.call(thisObj, attr.name, template.makeExpression(JSON.stringify(attr.defaultValue)), '', attr);
            }
        });
    }

    tag = node.tag || compiler.taglibs.getTag(node);

    var coreAttrHandlers = {
        'c-space': function(attr) {
            this['c-whitespace'](attr);
        },
        'c-whitespace': function(attr) {
            if (attr.value === 'preserve') {
                node.setPreserveWhitespace(true);
            }
        },
        'c-escape-xml': function(attr) {
            node.setEscapeXmlBodyText(attr.value !== 'false');
        },
        'c-parse-body-text': function(attr) {
            node.parseBodyText = attr.value !== 'false';
        },
        'c-when': function(attr) {
            var whenNode = compiler.createNode(WhenNode, {
                    test: template.makeExpression(attr.value),
                    pos: node.getPosition()
                });
            node.parentNode.replaceChild(whenNode, node);
            whenNode.appendChild(node);
        },
        'c-otherwise': function(attr) {
            var otherwiseNode = compiler.createNode(OtherwiseNode, { pos: node.getPosition() });
            node.parentNode.replaceChild(otherwiseNode, node);
            otherwiseNode.appendChild(node);
        },
        'c-attrs': function(attr) {
            node.dynamicAttributesExpression = attr.value;
        },
        'c-for-each': function(attr) {
            this['for'](attr);
        },
        'c-for': function(attr) {
            var forEachProps = compiler.parseAttribute(attr.value, {
                    each: { type: 'custom' },
                    separator: { type: 'expression' },
                    'iterator': { type: 'expression' },
                    'status-var': { type: 'identifier' },
                    'for-loop': {
                        type: 'boolean',
                        allowExpressions: false
                    }
                }, {
                    removeDashes: true,
                    defaultName: 'each',
                    errorHandler: function (message) {
                        node.addError('Invalid c-for attribute of "' + attr.value + '". Error: ' + message);
                    }
                });
            forEachProps.pos = node.getPosition();
            //Copy the position property
            forEachNode = compiler.createNode(ForNode, forEachProps);
            //Surround the existing node with an "forEach" node by replacing the current
            //node with the new "forEach" node and then adding the current node as a child
            node.parentNode.replaceChild(forEachNode, node);
            forEachNode.appendChild(node);
        },
        'c-if': function(attr) {
            var ifNode = compiler.createNode(IfNode, {
                    test: template.makeExpression(attr.value),
                    pos: node.getPosition()
                });
            //Surround the existing node with an "if" node by replacing the current
            //node with the new "if" node and then adding the current node as a child
            node.parentNode.replaceChild(ifNode, node);
            ifNode.appendChild(node);
        },
        'c-else-if': function(attr) {
            var elseIfNode = compiler.createNode(ElseIfNode, {
                    test: template.makeExpression(attr.value),
                    pos: node.getPosition()
                });
            //Surround the existing node with an "if" node by replacing the current
            //node with the new "if" node and then adding the current node as a child
            node.parentNode.replaceChild(elseIfNode, node);
            elseIfNode.appendChild(node);
        },
        'c-else': function(attr) {
            var elseNode = compiler.createNode(ElseNode, { pos: node.getPosition() });
            //Surround the existing node with an "if" node by replacing the current
            //node with the new "if" node and then adding the current node as a child
            node.parentNode.replaceChild(elseNode, node);
            elseNode.appendChild(node);
        },
        'c-with': function(attr) {
            var withNode = compiler.createNode(WithNode, {
                    vars: attr.value,
                    pos: node.getPosition()
                });
            node.parentNode.replaceChild(withNode, node);
            withNode.appendChild(node);
        },
        'c-body-content': function(attr) {
            this.content(attr);
        },
        'c-content': function(attr) {
            var newChild = compiler.createNode(WriteNode, {
                    expression: attr.value,
                    pos: node.getPosition()
                });
            node.removeChildren();
            node.appendChild(newChild);
        },
        'c-trim-body-indent': function(attr) {
            if (attr.value === 'true') {
                node.trimBodyIndent = true;
            }
        },
        'c-strip': function(attr) {
            if (!node.setStripExpression) {
                node.addError('The c-strip directive is not allowed for target node');
            }
            node.setStripExpression(attr.value);
        },
        'c-replace': function(attr) {
            var replaceWriteNode = compiler.createNode(WriteNode, {
                    expression: attr.value,
                    pos: node.getPosition()
                });
            //Replace the existing node with an node that only has children
            node.parentNode.replaceChild(replaceWriteNode, node);
            node = replaceWriteNode;
        },
        'c-input': function(attr) {
            inputAttr = attr.value;
        },
        'c-data': function(attr) {
            inputAttr = attr.value;
        }
    };

    node.forEachAttributeNS('', function(attr) {

        var handler = coreAttrHandlers[attr.qName];
        if (handler) {
            node.removeAttribute(attr.localName);
            coreAttrHandlers[attr.localName](attr);
        }
    });

    if (tag) {
        if (tag.preserveWhitespace) {
            node.setPreserveWhitespace(true);
        }
        if (tag.renderer || tag.template) {
            if (tag.renderer) {
                //Instead of compiling as a static XML element, we'll
                //make the node render as a tag handler node so that
                //writes code that invokes the handler
                TagHandlerNode.convertNode(node, tag);
                if (inputAttr) {
                    node.setInputExpression(template.makeExpression(inputAttr));
                }
            } else {
                var templatePath = resolver.deresolve(tag.template, compiler.dirname);
                // The tag is mapped to a template that will be used to perform
                // the rendering so convert the node into a "IncludeNode" that can
                // be used to include the output of rendering a template
                IncludeNode.convertNode(node, templatePath);
            }

            forEachProp(function (name, value, attrDef) {
                if (attrDef.dynamicAttribute && attrDef.targetProperty) {
                    if (attrDef.removeDashes === true) {
                        name = removeDashes(name);
                    }
                    node.addDynamicAttribute(name, value);
                    node.setDynamicAttributesProperty(attrDef.targetProperty);
                } else {
                    node.setProperty(name, value);
                }
            });

        } else if (tag.nodeClass) {
            var NodeCompilerClass = require(tag.nodeClass);
            compiler.inheritNode(NodeCompilerClass);
            extend(node, NodeCompilerClass.prototype);
            NodeCompilerClass.call(node);
            node.setNodeClass(NodeCompilerClass);
            forEachProp(function (name, value) {
                node.setProperty(name, value);
            });
        }
    }
};<|endoftext|>


<commit_before>import {MapProvider} from '../maps/create-map.js';
import {UsersManager} from '../kinvey/users.js';
import {WeatherProvider} from '../weather/get-weather.js';

import {ProfileScreen} from '../profile/profileScreen.js';
import {TemplatesProvider} from '../kinvey/templates.js';

import {geolocation} from '../maps/get-geolocation.js';

const WeatherApp = (() => {
    let users,
        weather,
        maps,
        templates,
        profileScreen;

    class WeatherApp {
        constructor(contentContainerId) {
            maps = new MapProvider();
            users = new UsersManager();
            weather = new WeatherProvider();
            templates = new TemplatesProvider();
            profileScreen = new ProfileScreen();

            this._contentContainer = $(contentContainerId);
            this.__app__ = this.__initializeSammyApp__();
        }

        start() {
            const isUserLoggedIn = users.isUserLogged();
            if (isUserLoggedIn) {
                $(document.body).addClass("logged-in");
            }

            this.__app__.run('#/');
        }

        __initializeSammyApp__() {
            const that = this;

            var sammyApp = Sammy("#content", function () {
                var $content = $("#content"),
                    $weatherInfo = $("#weather");

                this.get("#/", function () {
                    $content.html("
Route: #/

Content: TBD
");
                });

                this.get("#/login", function (context) {
                    if (users.isUserLogged()) {
                        context.redirect('#/');
                        toastr.success("", "You logged in already!", { "positionClass": "toast-bottom-left", });
                        return;
                    }

                    templates.get("login")
                        .then(function (template) {
                            $content.html(template());

                            $("#btn-login").on("click", function () {
                                var logUser = {
                                    username: $('#username').val(),
                                    password: $('#password').val()
                                };

                                users.login(logUser)
                                    .then(function (response) {
                                        $(document.body).addClass("logged-in");

                                        context.redirect('#/profile');
                                    });
                            });
                        });
                });

                this.get("#/register", function (context) {
                    if (users.isUserLogged()) {
                        context.redirect('#/');
                        return;
                    }

                    templates.get("register")
                        .then(function (template) {
                            $content.html(template());

                            $("#btn-register").on("click", function () {
                                var newUser = {
                                    username: $('#new-username').val(),
                                    password: $('#new-username').val()
                                };

                                users.register(newUser)
                                    .then(function (response) {
                                        context.redirect('#/');
                                    });

                                toastr.success("Congrats on your registration!");
                            });
                        });
                });

                this.get('#/profile', function () {
                    startProfileScreen();
                });

                this.get('#/profile/:location/:duration', function (route) {
                    // Display weather location
                    // for params.location
                    // with params.duration
                    const profileScreen = $('#profile-screen');
                    if (profileScreen.length === 0) {
                        startProfileScreen();
                    }

                    let templateName;
                    let duration = Number(route.params.duration);
                    if (isNaN(duration)) {
                        duration = 14;
                    }

                    switch (duration) {
                        case 1:
                            templateName = 'current-weather';

                            break;
                        case 5:
                            templateName = 'five-day';
                            break;
                        case 14:
                            templateName = 'fourteen-day';
                            break;
                        default:
                            return;
                    }

                    Promise.all([
                        weather.getForecast(route.params.location, duration),
                        templates.get(templateName),

                    ])
                        .then(([data, template]) => {
                            const generatedHtml = template(data);
                            $("#weather-tiles").html(generatedHtml);
                            return data;
                        })
                        .then(data => {
                            const idSelector = document.getElementById('map-container');
                            idSelector.style.height = (window.innerHeight - 75) + 'px';
                            idSelector.style.width = '100%';

                            maps.initializeMap(
                                data.city.coord.lat,
                                data.city.coord.lon,
                                idSelector
                            );
                        })
                        .then(() => {
                            const windowLocation = String(window.location);
                            const cityName = extractCityNameFromCurrentWindowLocation();

                            const container = $(that._contentContainer);
                            container
                                .find('#one-day-forecast')
                                .attr('href', `#/profile/${cityName}/1`);

                            container
                                .find('#five-day-forecast')
                                .attr('href', `#/profile/${cityName}/5`);

                            container
                                .find('#fourteen-day-forecast')
                                .attr('href', `#/profile/${cityName}/14`);

                            container
                                .find('#twttr-share')
                                .attr('href', 'https://twitter.com/intent/tweet?text=' + `Team Watchmen Weather forecast for ${cityName} ` + windowLocation);
                        })
                        .catch(console.log);

                    function extractCityNameFromCurrentWindowLocation() {
                        const windowLocation = String(window.location);
                        const locationElements = windowLocation.split('/');
                        const numberOfElements = locationElements.length;
                        const cityName = locationElements[numberOfElements - 2];

                        return cityName;
                    }
                });

                this.get('#/profile/add', function (route) {
                    const newLocation = $('#input-location').val();
                    if (!newLocation) {
                        return;
                    }

                    users.setUserLocations(newLocation);
                    startProfileScreen();
                    window.location = `#/profile/${newLocation}/1`;
                });

                function startProfileScreen() {
                    profileScreen.start('#content');
                    profileScreen.displayLocationsListForUser('#location-list');
                }
            });

            //logout
            $("#nav-btn-logout").on("click", function () {
                if (users.isUserLogged()) {
                    users.logout()
                        .then(function () {
                            $(document.body).remove("logged-in");

                            context.redirect('#/');
                        });
                    toastr.info("", "You just logged out!", { "positionClass": "toast-bottom-left", });
                } else {
                    toastr.info("So, no need to log out :)", "You are not logged in!", { "positionClass": "toast-bottom-left", });
                }
            });

            return sammyApp;
        }
    }

    return WeatherApp;
})();

export {WeatherApp};<commit_msg>remove class log in if no user is logged in<commit_after>import {MapProvider} from '../maps/create-map.js';
import {UsersManager} from '../kinvey/users.js';
import {WeatherProvider} from '../weather/get-weather.js';

import {ProfileScreen} from '../profile/profileScreen.js';
import {TemplatesProvider} from '../kinvey/templates.js';

import {geolocation} from '../maps/get-geolocation.js';

const WeatherApp = (() => {
    let users,
        weather,
        maps,
        templates,
        profileScreen;

    class WeatherApp {
        constructor(contentContainerId) {
            maps = new MapProvider();
            users = new UsersManager();
            weather = new WeatherProvider();
            templates = new TemplatesProvider();
            profileScreen = new ProfileScreen();

            this._contentContainer = $(contentContainerId);
            this.__app__ = this.__initializeSammyApp__();
        }

        start() {
            const isUserLoggedIn = users.isUserLogged();
            if (isUserLoggedIn) {
                $(document.body).addClass("logged-in");
            } else {
                $(document.body).removeClass("logged-in");
            }

            this.__app__.run('#/');
        }

        __initializeSammyApp__() {
            const that = this;

            var sammyApp = Sammy("#content", function () {
                var $content = $("#content"),
                    $weatherInfo = $("#weather");

                this.get("#/", function () {
                    $content.html("
Route: #/

Content: TBD
");
                });

                this.get("#/login", function (context) {
                    if (users.isUserLogged()) {
                        context.redirect('#/');
                        toastr.success("", "You logged in already!", { "positionClass": "toast-bottom-left", });
                        return;
                    }

                    templates.get("login")
                        .then(function (template) {
                            $content.html(template());

                            $("#btn-login").on("click", function () {
                                var logUser = {
                                    username: $('#username').val(),
                                    password: $('#password').val()
                                };

                                users.login(logUser)
                                    .then(function (response) {
                                        $(document.body).addClass("logged-in");

                                        context.redirect('#/profile');
                                    });
                            });
                        });
                });

                this.get("#/register", function (context) {
                    if (users.isUserLogged()) {
                        context.redirect('#/');
                        return;
                    }

                    templates.get("register")
                        .then(function (template) {
                            $content.html(template());

                            $("#btn-register").on("click", function () {
                                var newUser = {
                                    username: $('#new-username').val(),
                                    password: $('#new-username').val()
                                };

                                users.register(newUser)
                                    .then(function (response) {
                                        context.redirect('#/');
                                    });

                                toastr.success("Congrats on your registration!");
                            });
                        });
                });

                this.get('#/profile', function () {
                    startProfileScreen();
                });

                this.get('#/profile/:location/:duration', function (route) {
                    // Display weather location
                    // for params.location
                    // with params.duration
                    const profileScreen = $('#profile-screen');
                    if (profileScreen.length === 0) {
                        startProfileScreen();
                    }

                    let templateName;
                    let duration = Number(route.params.duration);
                    if (isNaN(duration)) {
                        duration = 14;
                    }

                    switch (duration) {
                        case 1:
                            templateName = 'current-weather';

                            break;
                        case 5:
                            templateName = 'five-day';
                            break;
                        case 14:
                            templateName = 'fourteen-day';
                            break;
                        default:
                            return;
                    }

                    Promise.all([
                        weather.getForecast(route.params.location, duration),
                        templates.get(templateName),

                    ])
                        .then(([data, template]) => {
                            const generatedHtml = template(data);
                            $("#weather-tiles").html(generatedHtml);
                            return data;
                        })
                        .then(data => {
                            const idSelector = document.getElementById('map-container');
                            idSelector.style.height = (window.innerHeight - 75) + 'px';
                            idSelector.style.width = '100%';

                            maps.initializeMap(
                                data.city.coord.lat,
                                data.city.coord.lon,
                                idSelector
                            );
                        })
                        .then(() => {
                            const windowLocation = String(window.location);
                            const cityName = extractCityNameFromCurrentWindowLocation();

                            const container = $(that._contentContainer);
                            container
                                .find('#one-day-forecast')
                                .attr('href', `#/profile/${cityName}/1`);

                            container
                                .find('#five-day-forecast')
                                .attr('href', `#/profile/${cityName}/5`);

                            container
                                .find('#fourteen-day-forecast')
                                .attr('href', `#/profile/${cityName}/14`);

                            container
                                .find('#twttr-share')
                                .attr('href', 'https://twitter.com/intent/tweet?text=' + `Team Watchmen Weather forecast for ${cityName} ` + windowLocation);
                        })
                        .catch(console.log);

                    function extractCityNameFromCurrentWindowLocation() {
                        const windowLocation = String(window.location);
                        const locationElements = windowLocation.split('/');
                        const numberOfElements = locationElements.length;
                        const cityName = locationElements[numberOfElements - 2];

                        return cityName;
                    }
                });

                this.get('#/profile/add', function (route) {
                    const newLocation = $('#input-location').val();
                    if (!newLocation) {
                        return;
                    }

                    users.setUserLocations(newLocation);
                    startProfileScreen();
                    window.location = `#/profile/${newLocation}/1`;
                });

                function startProfileScreen() {
                    profileScreen.start('#content');
                    profileScreen.displayLocationsListForUser('#location-list');
                }
            });

            //logout
            $("#nav-btn-logout").on("click", function () {
                if (users.isUserLogged()) {
                    users.logout()
                        .then(function () {
                            $(document.body).remove("logged-in");

                            context.redirect('#/');
                        });
                    toastr.info("", "You just logged out!", { "positionClass": "toast-bottom-left", });
                } else {
                    toastr.info("So, no need to log out :)", "You are not logged in!", { "positionClass": "toast-bottom-left", });
                }
            });

            return sammyApp;
        }
    }

    return WeatherApp;
})();

export {WeatherApp};<|endoftext|>