Example #1
0
    that.performCheck = function(result) {
      var data = result.data;
      
      // console.log('performCheck:\n' + util.inspect(result));

      if (data.status === App.Status.InMarket) {
        if (result.deltaLast !== 0) {
          if (existy(result.previousLast)) {
            if (result.positionDeltaPercent <= data.lossThreshold) {
              console.log('LOSS THRESHOLD -------------------------------------------------- (' 
                + accounting.formatNumber(result.positionDeltaPercent, 4) + ')');
              result.data.status = App.Status.Waiting;
              sell(result);
            }
            else if (result.positionDeltaPercent >= data.gainThreshold) {
              console.log('GAIN THRESHOLD ++++++++++++++++++++++++++++++++++++++++++++++++++ (' 
                + accounting.formatNumber(result.positionDeltaPercent, 4) + ')');
              result.data.status = App.Status.Waiting;
              sell(result);
            }
          }
        }
      }
      else if (data.status === App.Status.Waiting) {
        if ((result.positionDeltaPercent <= data.enterAfterWaitingThreshold)
         || (result.deltaPercent <= data.enterAfterWaitingThreshold)) {
          console.log('RE-ENTERING MARKET $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$');
          result.data.status = App.Status.EnteringMarket;
        }
      }
    }
							.exec(function(err, bank) {
								if (err){console.log('ERR: Find Bank');return res.send(500,err);} else {
									// If no bank was found....
									if ( bank === null ) {
										// Return a 400 validation error
										invalids.push('bank');
										return checkValidationAgain();
									}
									else {
										// It found the bank!
										transaction.meta.bankAmounts = [{
											amount: transaction.meta.amount,
											bank: bank._id
										}];
										// Now update the bank balance
										if ( date.obj.isAfter(today) ) {
											// Expected Income
											bank.meta.expectedIncome = bank.meta.expectedIncome + transaction.meta.amount;
											bank.expectedIncome = accounting.formatNumber(bank.meta.expectedIncome, 2);
										}
										else {
											// Balance
											bank.meta.balance = bank.meta.balance + transaction.meta.amount;
											bank.balance = accounting.formatNumber(bank.meta.balance, 2);
										}										
										bank.meta.last_modified = today;
										bank.save(function(err) {
											if (err) {console.log('ERR: Save Bank 3');return res.send(500,err)}
										});

										// Now check the validation one more time...
										return checkValidationAgain();
									}
								}
							});
Example #3
0
    function sell(result) {
      result.data.cash = result.position;
      result.data.originalPrice = result.market.ask;
      result.data.btc = result.data.cash / result.data.originalPrice;

      // console.log('sold:\n' + util.inspect(result.data));
      var message = 'sold:\n  '; 
         message += accounting.formatNumber(result.data.btc, 4) + '\n  ';
         message += accounting.formatNumber(result.data.cash, 4) + '\n  ';
         message += accounting.formatNumber(result.data.originalPrice, 4);
      console.log(message);

      PubSub.global.publish(App.Events.UpdateConfig, result.data);
    }
Example #4
0
	formatNumber: function (input, p, l) {
		var accounting = require("accounting");
		p = parseInt(p,10) || 2;
		l = l || ",";

		return accounting.formatNumber(input,p,l);
	},
Example #5
0
  formatNumber: function (input, p, l) {
    var accounting = require("accounting");
    p = parseInt(p,10) || 2;
    l = (l === "" || l === false) ? "" : (l || ",");

    return accounting.formatNumber(input,p,l);
  },
        that.screenshots.forEach(function(screenshot, index) {
            var included = (!differentOnly) || (differentOnly && screenshot.get('misMatchPercentage') > 0)
            if (included) {
                var oldImg = that.find(that.toId('old-img-' + index)),
                    newImg = that.find(that.toId('new-img-' + index)),
                    diffImg = that.find(that.toId('diff-img-' + index)),
                    folder = root.folder(S.pad(index + '', 4, '0') + '-' + S.slugify(screenshot.get('caption')));


                if (screenshot.get('misMatchPercentage') > 0) {
                    folder.file("result.txt", 'The new image is ' + accounting.formatNumber(screenshot.get('misMatchPercentage'), 2) + '% different compared to the old.' + "\n");
                }
                else {
                    folder.file("result.txt", 'New image and old image are identical.' + "\n");
                }

                folder.file("old.png", that.getBase64ImageData(oldImg), {
                    base64: true
                });
                folder.file("new.png", that.getBase64ImageData(newImg), {
                    base64: true
                });
                folder.file("diff.png", diffImg.attr('src').replace(/^data:image\/(png|jpg);base64,/, ""), {
                    base64: true
                });
            }
        });
            .then(function(screenshots) {
                that.screenshots.reset(screenshots);

                if (that.screenshots.length > 0) {
                    that.controls.result.removeClass('hidden');
                    that.controls.subtitle.text(accounting.formatNumber(that.screenshots.reduce(function(memo, s){
                        return memo + (s.get('oldScreenshot') ? 1 : 0) + (s.get('newScreenshot') ? 1 : 0);
                    }, 0)) + ' screenshots have been taken.');
                }
                else {
                    that.controls.result.addClass('hidden');
                }


                that.screenshots.forEach(function(u, index) {
                    var row = that.find(that.toId('head-row-' + index));
                    if (row.size() === 0) {
                        row = ROW({
                            id: that.id,
                            index: index,
                            device: that.device.toJSON(),
                            data: u.toJSON()
                        });
                        that.controls.screenshots.append(row);
                    }

                    var oldImg = that.find(that.toId('old-img-' + index)),
                        newImg = that.find(that.toId('new-img-' + index));

                    if (u.get('oldScreenshot')) {
                        if (!oldImg.data('loaded')) {
                            oldImg.bind('load', function() {
                                oldImg.data('loaded', true);
                                oldImg.unbind('load');
                                // //console.log('old ' + index + ' is loaded');
                                _.defer(function() {
                                    that.compare(index);
                                });

                            });
                            oldImg.attr('src', u.get('oldScreenshot'));
                        }
                    }

                    if (u.get('newScreenshot')) {
                        if (!newImg.data('loaded')) {
                            newImg.bind('load', function() {
                                newImg.data('loaded', true);
                                newImg.unbind('load');
                                // //console.log('new ' + index + ' is loaded');
                                _.defer(function() {
                                    that.compare(index);
                                });
                            });
                            newImg.attr('src', u.get('newScreenshot'));
                        }
                    }
                });
            });
Example #8
0
 .map(result => {
   const price = accounting.formatNumber(result.price, 0, ' ', '');
   return `
     <a class="result">
       <div class="content">
         <div class="price">${price}</div>
         <div class="title">${result.title}</div>
       </div>
     </a>`;
 }).join('');
Example #9
0
			formatarResposta: function(resultado) {
				var accounting = require('accounting');
				var resposta   = {
					resultado: 0.0
				};
				
				resultado = accounting.formatNumber(resultado, 2, ".", ",");
				resposta.resultado = resultado;
				
				return resposta;
			},
Example #10
0
			function setBalExp(futureBalances, pastBalances) {
				for (var i = banks.length - 1; i >= 0; i--) {
					var thisBank = banks[i];

					// Reset all values
					thisBank.balance = '0.00';
					thisBank.meta.balance = 0;
					thisBank.expectedIncome = '0.00';
					thisBank.meta.expectedIncome = 0;

					// Set the expectedIncome
					for (var e = futureBalances.length - 1; e >= 0; e--) {
						if ( thisBank._id.equals(futureBalances[e]._id) ) {
							thisBank.expectedIncome = accounting.formatNumber(futureBalances[e].amount, 2);
							thisBank.meta.expectedIncome = futureBalances[e].amount;
							break;
						}
					};
					
					// Set the balance
					for (var e = pastBalances.length - 1; e >= 0; e--) {
						if ( thisBank._id.equals(pastBalances[e]._id) ) {
							thisBank.balance = accounting.formatNumber(pastBalances[e].amount, 2);
							thisBank.meta.balance = pastBalances[e].amount;
							break;
						}
					};
					
					// Update the last_modified date
					thisBank.meta.last_modified = today;

					// Save the bank
					thisBank.save(function(err) {
						if (err) return res.send(500,err);
					});
				};

				// Finally, return the banks to the callback
				callback(banks);
			}
hbs.registerHelper('number', function(num, options){
  var defaultPrecision = accounting.settings.number.precision,
      precision = options.hash.precision || defaultPrecision;

  if( precision === 'auto' ) {
    precision = Utils.decimalPlaces(num);
  }

  if(options.hash.negative) {
    num = num * -1;
  }

  return accounting.formatNumber(num, precision);
});
Example #12
0
            stat.map((item, i) => {
              if(item.value) return (
                <div key={i}>
                  <CellsTitle>
                    <a href="#">
                      {item._id}年
                    </a>
                  </CellsTitle>
                  <CellsTitle>
                    {formatMoney(item.value.amount, '¥')}元 | {formatNumber(item.value.count)}人次
                  </CellsTitle>
                  <Progress value={(item.value.amount/totalAmount)*100} />

                </div>
              )
              else return null;
            })
					// It continues here one way or another...
					function continueSetBank(budget) {
						var currentBank = 0;
						while ( amountLeft > 0 ) {
							// If amountLeft is a bigger or equal number than this bank...
							if ( amountLeft >= budget.banks[currentBank].meta.balance ) {
								// Get amountLeft closer to 0 by the bank balance amount
								amountLeft -= budget.banks[currentBank].meta.balance;
								// Set that bank amount to 0 and save
								budget.banks[currentBank].meta.balance = 0;
								budget.banks[currentBank].balance = '0.00';
								budget.banks[currentBank].last_modified = today;
								budget.banks[currentBank].save(function(err) {
									if (err){console.log('ERR: Save Bank 1');return res.send(500,err);}
								});
								// Store the info
								transaction.meta.bankAmounts.push({
									amount: budget.banks[currentBank].meta.balance,
									bank: budget.banks[currentBank]._id
								});
								// Next bank...
								currentBank++;
							}
							// amountLeft is a smaller number than the current bank balance
							else {
								// Set the values
								transaction.meta.bankAmounts.push({
									amount: amountLeft,
									bank: budget.banks[currentBank]._id
								});
								// Set the bank
								budget.banks[currentBank].meta.balance -= amountLeft;
								budget.banks[currentBank].balance = accounting.formatNumber(budget.banks[currentBank].meta.balance,2);
								budget.banks[currentBank].last_modified = today;
								budget.banks[currentBank].save(function(err) {
									if (err){console.log('ERR: Save Bank 2');return res.send(500,err);}
								});
								// Zero out the amountLeft
								amountLeft = 0;
							}
						}

						checkValidationAgain(budget);
					}
Example #14
0
  render () {
    let {stat, totalAmount, totalCount, lastUpdated} = this.props;
    let year = (new Date(lastUpdated)).getYear() + 1900;
    let month = (new Date(lastUpdated)).getMonth();
    return (
      <div className="progress">
        <div className="hd">
          <h1 className="page_title">年度统计</h1>
        </div>
        <div className="bd spacing">

          {
            stat.map((item, i) => {
              if(item.value) return (
                <div key={i}>
                  <CellsTitle>
                    <a href="#">
                      {item._id}年
                    </a>
                  </CellsTitle>
                  <CellsTitle>
                    {formatMoney(item.value.amount, '¥')}元 | {formatNumber(item.value.count)}人次
                  </CellsTitle>
                  <Progress value={(item.value.amount/totalAmount)*100} />

                </div>
              )
              else return null;
            })
          }
        </div>
        <MediaBox>
          <MediaBoxDescription>
            <b>截止至{year}年{month}月,一共捐赠{formatMoney(totalAmount, '¥')}元,共计{formatNumber(totalCount)}人次</b>
          </MediaBoxDescription>
        </MediaBox>
      </div>
    )
  }
    View.prototype.downloadButtonClickHandler = function(event) {
        var that = this;
        var e = $(event.currentTarget),
            index = e.data("index"),
            oldImg = that.find(that.toId('old-img-' + index)),
            newImg = that.find(that.toId('new-img-' + index)),
            diffImg = that.find(that.toId('diff-img-' + index));

        var screenshot = that.screenshots.at(e.data('index'));
        var fileName = S.slugify(_.now() + '-' + S.prune(screenshot.get('caption'), 200, ''));


        var zip = new JSZip(),
            root = zip.folder(fileName);
        if (screenshot.get('misMatchPercentage') > 0) {
            root.file("result.txt", 'The new image is ' + accounting.formatNumber(screenshot.get('misMatchPercentage'), 2) + '% different compared to the old.' + "\n");
        }
        else {
            root.file("result.txt", 'New image and old image are identical.' + "\n");
        }

        root.file("old.png", that.getBase64ImageData(oldImg), {
            base64: true
        });
        root.file("new.png", that.getBase64ImageData(newImg), {
            base64: true
        });
        root.file("diff.png", diffImg.attr('src').replace(/^data:image\/(png|jpg);base64,/, ""), {
            base64: true
        });

        var content = zip.generate({
            type: "blob"
        });

        saveAs(content, fileName + '.zip');
    };
Example #16
0
				bank.meta.openingTransaction.populate('meta.contact', function(err, transaction) {
					if (err) return res.send(404,err); else {
						// Save the returned and populated transaction in the bank meta
						bank.meta.openingTransaction = transaction;

						// ------- NOW PROCEED WITH THE UPDATES ---------- //

						// Setup some basic values ------------------------
						var name = validator.trim(req.body.name);
						var openingBalance = {
							num: parseFloat(accounting.unformat(req.body.openingBalance).toFixed(2)),
							str: accounting.formatNumber(req.body.openingBalance,2)
						};
						var dateOpened = {
							obj: Date.parse(req.body.dateOpened),
							str: Date.parse(req.body.dateOpened).toString('MMMM d, yyyy')
						};

						var newBal = bank.meta.balance - bank.meta.openingTransaction.meta.amount + openingBalance.num;
						var balance = {
							num: newBal,
							str: accounting.formatNumber(newBal, 2)
						};

						// UPDATES -----------------------------------------
						
						// Update name
						bank.name = name;
						bank.meta.openingTransaction.contactName = name;
						bank.meta.openingTransaction.meta.contact.name = name;
						// Update priority
						bank.priority = req.body.priority;
						// Update dateOpened
						bank.dateOpened = dateOpened.str;
						bank.meta.openingTransaction.date = dateOpened.str;
						bank.meta.openingTransaction.meta.date = dateOpened.obj;
						// Update openingBalance
						bank.openingBalance = openingBalance.str;
						bank.meta.openingTransaction.amount = openingBalance.str;
						bank.meta.openingTransaction.meta.amount = openingBalance.num;
						bank.meta.openingTransaction.meta.bankAmounts[0].amount = openingBalance.num;
						// Update the bank balance
						bank.balance = balance.str;
						bank.meta.balance = balance.num;
						// Update last_modified
						bank.meta.last_modified = Date.now();
						bank.meta.openingTransaction.meta.last_modified = Date.now();
						bank.meta.openingTransaction.meta.contact.last_modified = Date.now();

						// SAVE!!! ------------------------------
						
						// Save the contact
						bank.meta.openingTransaction.meta.contact.save(function(err) { if (err) return res.send(500,err); });
						// Save the transaction
						bank.meta.openingTransaction.save(function(err) { if (err) return res.send(500,err); });

						// Save the bank
						bank.save(function(err) {
							if (err) return res.send(500,err); else {

								// Return only what we need to return...
								return res.send({
									_id: bank._id,
									name: bank.name,
									priority: bank.priority,
									dateOpened: bank.dateOpened,
									openingBalance: bank.openingBalance,
									balance: bank.balance,
									meta: {
										openingTransaction: bank.meta.openingTransaction._id
									}
								});

							}
						});

					}
				});
                global.services.settings.getAll().then(function (settings) {
                    let noti = new QueueableNotification()
                        .title('Channel Hosted!')
                        .message(username + ' has hosted the channel for ' + accounting.formatNumber(viewers) + ' viewer' + (viewers === 1 ? '' : 's') + '!')
                        .timeout(_.result(_.findWhere(settings, {group: 'notifications', name: 'channelHostedNotificationTime'}), 'value') * 1000)
                        .socketIO('channel-hosted', {username, viewers})
                        .sound(_.result(_.findWhere(settings, {group: 'sounds', name: 'channelHosted'}), 'value'), _.result(_.findWhere(settings, {
                            group: 'sounds',
                            name: 'channelHostedVolume'
                        }), 'value'));

                    global.services.notificationQueue.add(noti);

                    return resolve();
                }).catch(reject);
Example #18
0
 formatLocal: function(localAmount){
   return accounting.formatNumber(localAmount, [precision = 2], [thousand = ","], [decimal = "."]);
 }
Example #19
0
 formatBtc: function(btcAmount){
   return accounting.formatNumber(btcAmount, [precision = 8], [thousand = ","], [decimal = "."]);
 },
Example #20
0
 getOwnership: function(btcAmount){
   //returns the ownership points based on the BTC amount
   var newValue = btcAmount / 0.075;
   newValue = accounting.formatNumber(newValue, [precision = 4], [thousand = ","], [decimal = "."]);
   return newValue;
 },
Example #21
0
const Backbone = require('backbone');
var accounting = require('accounting');

module.exports = Backbone.Collection.extend({
  url() {
    const urlRoot = 'https://spreadsheets.google.com/feeds/list/';
    return `${urlRoot}${this.spreadsheetId}/1/public/full?alt=json`
  },
  parse(response, options) {
    return response.feed.entry.map(e => {
      return {
        code: e.gsx$code.$t.trim(),
        title: e.gsx$text.$t,
        price: e.gsx$pris.$t
      }
    });
  },
  getSum() {
    return this.reduce(function(memo, value) {
      return memo + Number(value.get('sum'))
    }, 0);
  },
  getSumFormatted() {
    return accounting.formatNumber(this.getSum(), 0, ' ', '') + ' kr';
  }
});
exports.create = function(req, res) {
	models.banks(req);
	models.budgets(req);
	models.contacts(req);

	// VALIDATE FIRST ----------------------------------------
	var invalids = [];
	if ( !validator.isMoney(req.body.amount) ) invalids.push('amount');
	if ( validator.trim(req.body.contact) === '' ) invalids.push('contact');
	if ( typeof req.body.bank !== 'undefined' && validator.trim(req.body.bank) === '' ) invalids.push('bank');
	if ( typeof req.body.budget === 'undefined' && !validator.isValidIncomeDate(req.body.date) ) invalids.push('date');
	if ( typeof req.body.budget !== 'undefined' && !validator.isValidExpenseDate(req.body.date) ) invalids.push('date');

	// Validation done - what are the results?
	if ( invalids.length > 0 ) return res.send(400,invalids); else {
		// VALIDATION PASSED - PROCEED ---------------------------------
		
		// Create the values
		var amount = {
			num: parseFloat(accounting.unformat(req.body.amount).toFixed(2)),
			str: accounting.formatNumber(req.body.amount,2)
		};
		var desc = req.body.desc;
		var date = {
			obj: Date.parse(req.body.date),
			str: Date.parse(req.body.date).toString('MMMM d, yyyy')			
		};

		// Set up the initial transaction
		var transaction = new models.transactions(req)({
			amount: amount.str,
			desc: desc,
			date: date.str,
			meta: {
				date: date.obj,
				amount: amount.num
			}
		});

		// Set the rest of the stuff, starting with budget...
		setBudget();

		function setBudget() {
			if ( typeof req.body.budget === 'undefined' ) return setBank(); else {

				// Find the budget in question
				models.budgets(req).findOne({ name: req.body.budget })
							.populate('banks')
							.exec(function(err, budget) {
								if (err){console.log('ERR: Find Budget');return res.send(500,err);} else {

									// If the budget wasn't found, then return validation error
									if ( budget === null ) {
										invalids.push('budget');
										return setBank();
									}
									else {
										// A budget was found, so set the transaction values
										transaction.budgetName = budget.name;
										transaction.meta.budget = budget._id;
										return setBank(budget);
									}
								}
							});
			}
		}

		function setBank(budget) {
			transaction.meta.bankAmounts = [];

			// Figure out those crazy banks...
			if ( typeof budget !== 'undefined' ) {
				// Calculate / input bank expenses
				
				// Remember - this is a NEGATIVE NUMBER
				var amountLeft = amount.num;				

				// First make sure the amount left is not a larger number than the budget amount
				if ( amountLeft > budget.meta.balance ) {
					invalids.push('amount');
					checkValidationAgain(budget);
				}
				else {

					// Update budget balance
					budget.meta.balance -= amount.num;
					budget.balance = accounting.formatNumber(budget.meta.balance, 2);
					budget.meta.last_modified = today;
					budget.save(function(err) {
						if (err){console.log('ERR: Save Budget',err);return res.send(500,err);}
					});

					// We need to make sure that there are banks here...
					if ( budget.banks.length === 0 ) {
						// If there are no banks, then we need to use all of them - in the default order
						models.banks(req).find().sort('priority').exec(function(err,banks) {
							if (err) return res.send(500,err); else {
								// Set the banks...
								budget.banks = banks;
								// Continue...
								continueSetBank(budget);
							}
						});
					}
					else {
						// Just continue...
						continueSetBank(budget);
					}

					// It continues here one way or another...
					function continueSetBank(budget) {
						var currentBank = 0;
						while ( amountLeft > 0 ) {
							// If amountLeft is a bigger or equal number than this bank...
							if ( amountLeft >= budget.banks[currentBank].meta.balance ) {
								// Get amountLeft closer to 0 by the bank balance amount
								amountLeft -= budget.banks[currentBank].meta.balance;
								// Set that bank amount to 0 and save
								budget.banks[currentBank].meta.balance = 0;
								budget.banks[currentBank].balance = '0.00';
								budget.banks[currentBank].last_modified = today;
								budget.banks[currentBank].save(function(err) {
									if (err){console.log('ERR: Save Bank 1');return res.send(500,err);}
								});
								// Store the info
								transaction.meta.bankAmounts.push({
									amount: budget.banks[currentBank].meta.balance,
									bank: budget.banks[currentBank]._id
								});
								// Next bank...
								currentBank++;
							}
							// amountLeft is a smaller number than the current bank balance
							else {
								// Set the values
								transaction.meta.bankAmounts.push({
									amount: amountLeft,
									bank: budget.banks[currentBank]._id
								});
								// Set the bank
								budget.banks[currentBank].meta.balance -= amountLeft;
								budget.banks[currentBank].balance = accounting.formatNumber(budget.banks[currentBank].meta.balance,2);
								budget.banks[currentBank].last_modified = today;
								budget.banks[currentBank].save(function(err) {
									if (err){console.log('ERR: Save Bank 2');return res.send(500,err);}
								});
								// Zero out the amountLeft
								amountLeft = 0;
							}
						}

						checkValidationAgain(budget);
					}
				}
			}
			else {
				// It's income! Easy - just grab the bank and set the values
				models.banks(req).findOne({ name: req.body.bank })
							.exec(function(err, bank) {
								if (err){console.log('ERR: Find Bank');return res.send(500,err);} else {
									// If no bank was found....
									if ( bank === null ) {
										// Return a 400 validation error
										invalids.push('bank');
										return checkValidationAgain();
									}
									else {
										// It found the bank!
										transaction.meta.bankAmounts = [{
											amount: transaction.meta.amount,
											bank: bank._id
										}];
										// Now update the bank balance
										if ( date.obj.isAfter(today) ) {
											// Expected Income
											bank.meta.expectedIncome = bank.meta.expectedIncome + transaction.meta.amount;
											bank.expectedIncome = accounting.formatNumber(bank.meta.expectedIncome, 2);
										}
										else {
											// Balance
											bank.meta.balance = bank.meta.balance + transaction.meta.amount;
											bank.balance = accounting.formatNumber(bank.meta.balance, 2);
										}										
										bank.meta.last_modified = today;
										bank.save(function(err) {
											if (err) {console.log('ERR: Save Bank 3');return res.send(500,err)}
										});

										// Now check the validation one more time...
										return checkValidationAgain();
									}
								}
							});
			}
		}

		function checkValidationAgain(budget) {
			if ( invalids.length > 0 ) {
				return res.send(400,invalids);
			}
			else {
				return setContact(budget);
			}
		}

		function setContact(budget) {
			models.contacts(req).findOne({ name: req.body.contact })
						.select('_id name')
						.lean(true)
						.exec(function(err,contact) {
							if (err){console.log('ERR: Find Contact');return res.send(500,err);} else {
								// If no contact was found...
								if ( contact === null ) {
									// Create a new contact
									var contact = models.contacts(req)({
										name: req.body.contact
									});
									contact.save(function(err) {
										if (err){console.log('ERR: Save Contact');return res.send(500,err);} else {
											// Set values
											transaction.contactName = contact.name;
											transaction.meta.contact = contact._id;

											// Save and return!
											return saveAndReturn(budget);
										}
									});									
								}
								// Found the contact!
								else
									// Set values
									transaction.contactName = contact.name;
									transaction.meta.contact = contact._id;
									
									// Save and return!
									return saveAndReturn(budget);
							}
						});
		}

		function saveAndReturn(budget) {
			// Save the transaction
			transaction.save(function(err) {
				if (err){console.log('ERR: Save Transaction');return res.send(500,err);} else {

					if ( typeof budget !== 'undefined' ) {
						// Return the transaction!
						return res.send(201, {
							_id: transaction._id,
							contactName: transaction.contactName,
							budgetName: transaction.budgetName,
							amount: transaction.amount,
							desc: transaction.desc,
							date: transaction.date,
							budgetBalance: budget.balance,
							budgetId: budget._id
						});
					}
					else {
						// Return the transaction!
						return res.send(201, {
							_id: transaction._id,
							contactName: transaction.contactName,
							budgetName: transaction.budgetName,
							amount: transaction.amount,
							desc: transaction.desc,
							date: transaction.date
						});
					}					
				}
			});
		}
	}
};
Example #23
0
                }).join('');
          }
        },
        onSelect: this.onProductSelect.bind(this)
      });

    return this;
  },

  updateSum() {
    this.$('#sum').text(this.collection.getSumFormatted());
  },

  onProductSelect(result) {
    delete result.id;
    this.collection.add(_.extend(result, {qty: 1, sum: result.price, sumFormatted: accounting.formatNumber(result.price, 0, ' ', '') + ' kr'}));
    this.render();
    this.$('#search-doc-input').focus();
  },

  onRemove(evt) {
    const buttonEl = this.$(evt.target).closest('button');
    const code = buttonEl.attr('id').replace(/remove-button-/, '');
    const model = this.collection.findWhere({code});
    this.collection.remove(model);
    this.render();
  },

  onQuantityChange(evt) {
    const code = evt.target.id.replace(/qty-input-/, '');
    const qty = evt.target.value;
 function fNumber (val) {
   return accounting.formatNumber(val)
 }
                row.data('resemble', resemble(oldImg.attr('src')).compareTo(newImg.attr('src')).onComplete(function(data) {
                    //enable download button
                    downloadBtn.removeAttr('disabled');


                    diffImg.data('loaded', true);
                    screenshot.set('misMatchPercentage', data.misMatchPercentage);
                    screenshot.set('compared', true);

                    if (data.misMatchPercentage > 0) {
                        diffCaption.html('<i class="fa fa-exclamation-circle"></i> The new image is ' + accounting.formatNumber(data.misMatchPercentage, 2) + '% different compared to the old.').removeClass('hidden').addClass('text-warning').removeClass('text-success');
                    }
                    else {
                        diffCaption.html('<i class="fa fa-check-circle"></i> New image and old image are identical.').removeClass('hidden').addClass('text-success').removeClass('text-warning');
                    }
                    diffImg.attr('src', data.getImageDataUrl());


                    if (that.screenshots.every(function(s) {
                            return s.get('compared');
                        })) {
                        resultToolbar.removeClass('hidden');
                    }

                }));
exports.formatNumber = function (value, precision) {
    return accounting.formatNumber(value, precision);
};
Example #27
0
 player.Towns = player.Towns.map(o => {
   o.points = accounting.formatNumber(o.points);
   o.ocean = util.format("%d%d", Math.round(o.x/100), Math.round(o.y/100));
   return o;
 });
Example #28
0
 centsToDollars: function(value) {
   return accounting.formatNumber(accounting.toFixed(value / 100, 2), 2);
 },
Example #29
0
exports.create = function(req, res) {	
	// VALIDATE FIRST
	var invalids = [];
	if ( typeof req.body.name === 'undefined' || validator.trim(req.body.name) === '' ) invalids.push('name');
	if ( typeof req.body.dateOpened === 'undefined' || !validator.isValidBankDate(req.body.dateOpened) ) invalids.push('dateOpened');
	if ( typeof req.body.openingBalance === 'undefined' || !validator.isMoney(req.body.openingBalance) ) invalids.push('openingBalance');
	if ( typeof req.body.priority === 'undefined' || !validator.isNumeric(req.body.priority) ) invalids.push('priority');
	// Validation is done... what are the results?
	if ( invalids.length > 0 ) return res.send(400,invalids); else {
		// Validation checks out! Now continue!
		
		// Create the values
		var name = validator.trim(req.body.name);
		var openingBalance = {
			num: parseFloat(accounting.unformat(req.body.openingBalance).toFixed(2)),
			str: accounting.formatNumber(req.body.openingBalance,2)
		};
		var dateOpened = {
			obj: Date.parse(req.body.dateOpened),
			str: Date.parse(req.body.dateOpened).toString('MMMM d, yyyy')
		};

		// Create the bank and set values
		var bank = new models.banks(req)({
			name: name,
			priority: req.body.priority,
			openingBalance: openingBalance.str,
			dateOpened: dateOpened.str,
			balance: openingBalance.str,
			meta: {
				balance: openingBalance.num
			}
		});

		// Save the bank
		bank.save(function(err) {
			if (err) return req.send(500,err); else {

				// Now create a contact that will go into the transaction
				var contact = new models.contacts(req)({ name: name });
				// Save the contact
				contact.save(function(err) {
					if (err) return req.send(500,err); else {

						// Now create the transaction
						var transaction = new models.transactions(req)({
							contactName: name,
							amount: openingBalance.str,
							desc: 'Opening Balance',
							date: dateOpened.str,

							meta: {
								date: dateOpened.obj,
								amount: openingBalance.num,
								contact: contact._id,
								bankAmounts: [{
									amount: openingBalance.num,
									bank: bank._id
								}]
							}
						});
						// Save the transaction
						transaction.save(function(err) {
							if (err) return res.send(500,err); else {

								// Now add the transaction id to the bank
								bank.meta.openingTransaction = transaction._id;
								// Now save the bank again
								bank.save(function(err) {
									if (err) return res.send(500,err);
								});

								// Now return what needs to be returned
								// No need to wait for the save to complete
								return res.send(201, bank);

							}
						});

					}
				});

			}
		});
	}
};
Example #30
0
Template.registerHelper('formatNumberZ', function(amount, decimals) {
    decimals = decimals || 0;
    return accounting.formatNumber(amount, decimals);
});