UNPKG

@speakr/speakr-module-services

Version:
119 lines (103 loc) 3.63 kB
"use strict"; const db = require('../../db'); module.exports = { newRecord }; function newRecord(options) { let campaign = options.req.body; let agencies = options.agencies; let brands = options.brands; let where = { id_hash: options.req.body.network_id_hash }; return db.networks.findOne({ where }) .then(networks => { // TODO: We can remove alot of this if we just passed the agency & brand ids // Find the agency where = { id_hash: agencies.id_hash }; return db.agencies.findOne({where}) .then((agencies) => { // If an agency exists if (!!agencies) { // Find the brand where = { id: brands.id }; return db.brands.findOne({ where }) .then((brands) => { if (!!brands) { let values = { "title": campaign.title, "network_id": networks.id, "agency_id": agencies.id, "brandname_id": brands.id, "budget": campaign.budget, "start_date": campaign.start_date, "end_date": campaign.end_date }; return db.campaigns.create(values) .then(campaigns => { // create a campaign profile for the new campaign return db.campaign_profiles.create({ campaign_id: campaigns.id, project_name: campaigns.title }) }) .then(campaign_profile => { return db.campaigns.findOne({ where: { id: campaign_profile.campaign_id }, include: [ { model: db.initiatives, required: false, include: [ db.platforms, db.statuses ] }, { model: db.contacts }, { model: db.brands, required: true }, { model: db.agencies, required: true }, { model: db.networks, required: false } ] }).then((campaigns) => { options.campaigns = campaigns; return Promise.resolve(options); }); }).catch((err) => { return Promise.reject(err); }) } else { return Promise.reject( { error: { code:500, message: "Brand does not exist" } } ); } }); } else { return Promise.reject( { error: { code:500, message: "Agency does not exist" } } ); } }); }) }