"use strict";

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Invoice = function () {
  function Invoice(data) {
    _classCallCheck(this, Invoice);

    this.update(data);
  }

  _createClass(Invoice, [{
    key: "update",
    value: function update(data) {

      if (typeof data.history === "undefined") {
        data.history = [];
      }
      if (typeof data.items === "undefined") {
        data.items = [];
      }
      if (typeof data.payments === "undefined") {
        data.payments = [];
      }

      //items
      for (var i = 0; i < data.items.length; i++) {
        data.items[i].prefix = "";
        data.items[i].selected = false;
        data.items[i].isNew = false;
      }

      //payments
      for (var i = 0; i < data.payments.length; i++) {
        data.payments[i].prefix = "";
        data.payments[i].payment_status = parseInt(data.payments[i].payment_status);
        data.payments[i].selected = false;
        data.payments[i].isNew = false;

        data.payments[i].payment_link = im_base + im_extrabase + '/index.php?option=com_invoices&view=payment&id=' + data.payments[i].id;

        if (moment(data.payments[i].payment_datetime).isValid()) data.payments[i].payment_datetime = moment(data.payments[i].payment_datetime).format('YYYY-MM-DD');else data.payments[i].payment_datetime = "";

        if (moment(data.payments[i].payment_duedate).isValid()) data.payments[i].payment_duedate = moment(data.payments[i].payment_duedate).format('YYYY-MM-DD');else data.payments[i].payment_duedate = "";
      }

      //taxes
      for (var property in data.taxes) {
        if (data.taxes.hasOwnProperty(property)) {

          if (data.id == 0) {
            data.taxes[property].active = data.taxes[property].checked;
          }
          data.taxes[property].active = parseInt(data.taxes[property].active);
          data.taxes[property].checked = parseInt(data.taxes[property].checked);
        }
      }

      data.publish = parseInt(data.publish);
      data.rec_email = parseInt(data.rec_email);
      data.is_recurrent = parseInt(data.is_recurrent);
      data.user_id = parseInt(data.user_id);
      data.template_id = parseInt(data.template_id);
      //data.currency_id = parseInt(data.currency_id);
      data.computed_total = parseFloat(data.computed_total);
      data.computed_subtotal = parseFloat(data.computed_subtotal);

      if (data.user_id != 0) data.vincular_cliente_checkbox = 1;else data.vincular_cliente_checkbox = 2;

      data.numItemsSelected = 0;
      data.payment_class = "";

      if (moment(data.invoice_date).isValid()) data.invoice_date = moment(data.invoice_date).format('YYYY-MM-DD');else data.invoice_date = "";

      if (moment(data.invoice_duedate).isValid()) data.invoice_duedate = moment(data.invoice_duedate).format('YYYY-MM-DD');else data.invoice_duedate = "";

      if (moment(data.start_publish).isValid()) data.start_publish = moment(data.start_publish).format('YYYY-MM-DD');else data.start_publish = "";

      if (moment(data.end_publish).isValid()) data.end_publish = moment(data.end_publish).format('YYYY-MM-DD');else data.end_publish = "";

      if (moment(data.rec_nextdate).isValid()) data.rec_nextdate = moment(data.rec_nextdate).format('YYYY-MM-DD');else data.rec_nextdate = "";

      for (var field in data) {
        this[field] = data[field];
      }

      this.needsSaving = false;
    }
  }, {
    key: "edit",
    value: function edit() {
      edit_invoice(this);
    }
  }, {
    key: "new",
    value: function _new() {
      new_invoice(this.user_id);
    }
  }, {
    key: "email",
    value: function email() {
      email_invoice(this.id, false, this);
    }
  }, {
    key: "preview",
    value: function preview() {
      preview_invoice(this.id, this);
    }
  }, {
    key: "publish_invoice",
    value: function (_publish_invoice) {
      function publish_invoice() {
        return _publish_invoice.apply(this, arguments);
      }

      publish_invoice.toString = function () {
        return _publish_invoice.toString();
      };

      return publish_invoice;
    }(function () {
      publish_invoice(this.id);
    })
  }, {
    key: "unpublish_invoice",
    value: function (_unpublish_invoice) {
      function unpublish_invoice() {
        return _unpublish_invoice.apply(this, arguments);
      }

      unpublish_invoice.toString = function () {
        return _unpublish_invoice.toString();
      };

      return unpublish_invoice;
    }(function () {
      unpublish_invoice(this.id);
    })
  }, {
    key: "change_status",
    value: function change_status(status) {
      changestatus_invoice(this.id, status, false, this);
    }
  }, {
    key: "display_tax",
    value: function (_display_tax) {
      function display_tax(_x) {
        return _display_tax.apply(this, arguments);
      }

      display_tax.toString = function () {
        return _display_tax.toString();
      };

      return display_tax;
    }(function (tax_id) {
      return display_tax(tax_id);
    })
  }, {
    key: "subtotal",
    value: function subtotal() {
      var total = 0;
      for (var i = 0; i < this.items.length; i++) {
        total += this.totalItem(i);
      }
      return total - this.discount;
    }
  }, {
    key: "thetotal",
    value: function thetotal() {
      var total = this.subtotal() + this.totalGlobalTaxes();
      this.total = total;
      return total;
    }
  }, {
    key: "totalItem",
    value: function totalItem(i) {

      return this.totalItemNoTax(i) + this.taxItem(i);
    }
  }, {
    key: "subtotalItemNoDiscount",
    value: function subtotalItemNoDiscount(i) {

      var value = 0;
      var amount = 0;
      if (this.items[i].value !== undefined && this.items[i].value != "") value = this.items[i].value;
      if (this.items[i].amount !== undefined && this.items[i].amount != "") amount = this.items[i].amount;

      var total = parseFloat(value * amount);

      return total;
    }
  }, {
    key: "subtotalItem",
    value: function subtotalItem(i) {

      var discount = 0;
      if (this.items[i].discount !== undefined && this.items[i].discount != "") discount = this.items[i].discount;

      return this.subtotalItemNoDiscount(i) - discount;
    }
  }, {
    key: "itemWithTax",
    value: function itemWithTax(i) {

      var value = 0;
      var tax = 0;
      if (this.items[i].value !== undefined && this.items[i].value != "") value = this.items[i].value;
      if (this.items[i].tax !== undefined && this.items[i].tax != "") tax = this.items[i].tax;

      var total = parseFloat(value * (1 + tax / 100));

      return total;
    }
  }, {
    key: "taxItem",
    value: function taxItem(i) {

      var value = 0;
      var amount = 0;
      var discount = 0;
      var tax = 0;
      if (this.items[i].value !== undefined && this.items[i].value != "") value = this.items[i].value;
      if (this.items[i].amount !== undefined && this.items[i].amount != "") amount = this.items[i].amount;
      if (this.items[i].discount !== undefined && this.items[i].discount != "") discount = this.items[i].discount;
      if (this.items[i].tax !== undefined && this.items[i].tax != "") tax = this.items[i].tax;

      var total = parseFloat((value * amount - discount) * (tax / 100));

      return total;
    }
  }, {
    key: "totalItemNoTax",
    value: function totalItemNoTax(i) {

      var value = 0;
      var amount = 0;
      var discount = 0;

      if (this.items[i].value !== undefined && this.items[i].value != "") value = this.items[i].value;
      if (this.items[i].amount !== undefined && this.items[i].amount != "") amount = this.items[i].amount;
      if (this.items[i].discount !== undefined && this.items[i].discount != "") discount = this.items[i].discount;

      var total = parseFloat(value * amount - discount);

      return total;
    }
  }, {
    key: "subtotal_items",
    value: function subtotal_items() {
      var total = 0;
      for (var i = 0; i < this.items.length; i++) {
        total += this.totalItemNoTax(i);
      }
      return total - this.discount;
    }

    //returns the value of the GLOBAL tax only for a given tax

  }, {
    key: "globaltax",
    value: function globaltax(tax_id) {
      if (this.taxes[tax_id].active) {
        if (this.taxes[tax_id].type == "percent") {
          if (this.taxes[tax_id].ordering == "1") {
            if (this.taxes[tax_id].calculate_on == "1") {
              return this.subtotal_items() * this.taxes[tax_id].tax_value / 100;
            } else return this.subtotal() * this.taxes[tax_id].tax_value / 100;
          } else if (this.taxes[tax_id].ordering == "2") {
            if (this.taxes[tax_id].calculate_on == "1") {
              return (this.subtotal_items() + this.globaltaxesFirstLevel()) * this.taxes[tax_id].tax_value / 100;
            } else return (this.subtotal() + this.globaltaxesFirstLevel()) * this.taxes[tax_id].tax_value / 100;
          }
        } else return parseFloat(this.taxes[tax_id].tax_value);
      }

      return 0;
    }

    //returns the total amount of global taxes of level 1

  }, {
    key: "globaltaxesFirstLevel",
    value: function globaltaxesFirstLevel() {
      var level1taxes = [];
      var total = 0;
      for (var property in this.taxes) {
        if (this.taxes.hasOwnProperty(property)) {

          if (this.taxes[property].ordering == 1) total += this.globaltax(property);
        }
      }

      return total;
    }

    //returns the total amount of a given tax (global + items)

  }, {
    key: "tax",
    value: function tax(tax_id) {
      var total = 0;
      for (var i = 0; i < this.items.length; i++) {
        if (this.items[i].tax_id == tax_id) total += this.taxItem(i);
      }
      return total + this.globaltax(tax_id);
    }

    //returns tax percentage in case there is ONLY global tax for that tax_id

  }, {
    key: "tax_percentage",
    value: function tax_percentage(tax_id) {
      var individualtaxexists = false;
      if (this.taxes[tax_id].active) {
        if (this.taxes[tax_id].type == "percent") {
          for (var i = 0; i < this.items.length; i++) {
            if (this.items[i].tax_id == tax_id) individualtaxexists = true;
          }
          if (!individualtaxexists) {
            if (this.taxes[tax_id].tax_value !== undefined && this.taxes[tax_id].tax_value != "") return this.taxes[tax_id].tax_value;else return 0;
          }
        }
      }

      return null;
    }
  }, {
    key: "totalTaxes",
    value: function totalTaxes() {
      var total = 0;

      for (var key in this.taxes) {
        if (this.taxes.hasOwnProperty(key)) {
          total += this.tax(key);
        }
      }

      return total;
    }

    //invoiceform and preview
    // totalTaxes: function(){
    //   var total = 0;
    //
    //   for (var key in this.taxes) {
    //     if (this.taxes.hasOwnProperty(key)) {
    //       total += this.globaltax(key);
    //     }
    //   }
    //
    //   return total;
    // },

  }, {
    key: "totalGlobalTaxes",
    value: function totalGlobalTaxes() {
      var total = 0;

      for (var key in this.taxes) {
        if (this.taxes.hasOwnProperty(key)) {
          total += this.globaltax(key);
        }
      }

      return total;
    }
  }, {
    key: "totalPayments",
    value: function totalPayments() {
      var total = 0;
      for (var i = 0; i < this.payments.length; i++) {
        if (this.payments[i].payment_amount !== undefined && this.payments[i].payment_amount != "") {
          total += parseFloat(this.payments[i].payment_amount);
        }
      }
      return total;
    }
  }, {
    key: "totalPaid",
    value: function totalPaid() {
      //actually computes all payments, not only paid.
      var paid_payments = 0;
      var total_paid = 0;
      var unpaid_payments = 0;
      var total_unpaid = 0;
      var total_unpaid_ontime = 0;
      var unpaid_payments_ontime = 0;
      var unpaid_payments_notontime = 0;

      for (var i = 0; i < this.payments.length; i++) {
        if (parseInt(this.payments[i].payment_status) == 1) {
          paid_payments++;
          total_paid += parseFloat(this.payments[i].payment_amount);
        }
        if (parseInt(this.payments[i].payment_status) == 0) {
          unpaid_payments++;
          total_unpaid += parseFloat(this.payments[i].payment_amount);

          if (moment(this.payments[i].payment_duedate).isAfter(moment()) || this.payments[i].payment_duedate == "0000-00-00 00:00:00" || this.payments[i].payment_duedate == "") {
            unpaid_payments_ontime++;
            total_unpaid_ontime += parseFloat(this.payments[i].payment_amount);
          }
        }
      }
      this.total_paid = total_paid;
      this.paid_payments = paid_payments;
      this.unpaid_payments = unpaid_payments;
      this.total_unpaid = total_unpaid;
      this.unpaid_payments_ontime = unpaid_payments_ontime;
      this.total_unpaid_ontime = total_unpaid_ontime;
      this.unpaid_payments_notontime = unpaid_payments - unpaid_payments_ontime;

      var invoice_total = this.thetotal();

      if (parseFloat(total_paid.toFixed(vm.format.decimals)) < parseFloat(invoice_total.toFixed(vm.format.decimals))) {
        this.payment_class = "notontime";
      } else {
        this.payment_class = "ontime";
      }

      return total_paid;
    }
  }, {
    key: "individualTaxes",
    value: function individualTaxes() {
      var total = 0;
      var individual_taxes = {};
      var individual_taxes_totals = {};

      for (var i = 0; i < this.items.length; i++) {

        var item_subtotal = this.totalItemNoTax(i);

        var item_tax = parseFloat(item_subtotal * (this.items[i].tax / 100));

        if (item_tax != 0 || parseInt(this.items[i].tax_id)) {

          if (typeof individual_taxes[this.items[i].tax_id] === "undefined") {
            individual_taxes[this.items[i].tax_id] = [];
          }

          //totals
          if (typeof individual_taxes_totals[this.items[i].tax_id] === "undefined" && parseInt(this.items[i].tax_id)) {
            individual_taxes_totals[this.items[i].tax_id] = { value: 0,
              calculated_on_amount: 0,
              name: ""
            };
            if (parseInt(this.items[i].tax_id)) {
              individual_taxes_totals[this.items[i].tax_id].name = vm.alltaxes[this.items[i].tax_id].name;
            }
          }

          if (typeof individual_taxes[this.items[i].tax_id][this.items[i].tax] !== "undefined") {
            individual_taxes[this.items[i].tax_id][this.items[i].tax].value += item_tax;
            individual_taxes[this.items[i].tax_id][this.items[i].tax].calculated_on_amount += item_subtotal;
          } else {
            individual_taxes[this.items[i].tax_id][this.items[i].tax] = { value: 0,
              calculated_on_amount: 0,
              name: "",
              percent_value: 0,
              tax_id: 0 };

            if (parseInt(this.items[i].tax_id)) {
              individual_taxes[this.items[i].tax_id][this.items[i].tax].name = vm.alltaxes[this.items[i].tax_id].name;
            } else individual_taxes[this.items[i].tax_id][this.items[i].tax].name = "GROUPED_TAX";

            individual_taxes[this.items[i].tax_id][this.items[i].tax].value = item_tax;
            individual_taxes[this.items[i].tax_id][this.items[i].tax].percent_value = this.items[i].tax;
            individual_taxes[this.items[i].tax_id][this.items[i].tax].calculated_on_amount = item_subtotal;
            individual_taxes[this.items[i].tax_id][this.items[i].tax].tax_id = this.items[i].tax_id;
          }

          //totals
          if (parseInt(this.items[i].tax_id)) {
            individual_taxes_totals[this.items[i].tax_id].value += item_tax;
            individual_taxes_totals[this.items[i].tax_id].calculated_on_amount += item_subtotal;
          }
        }
      }

      this.individual_taxes = individual_taxes;
      this.individual_taxes_totals = individual_taxes_totals;

      //we reorder for easy using
      var return_individual_taxes = [];

      for (var property in individual_taxes) {
        if (individual_taxes.hasOwnProperty(property)) {

          for (var property2 in individual_taxes[property]) {
            if (individual_taxes[property].hasOwnProperty(property2)) {

              return_individual_taxes.push(individual_taxes[property][property2]);
            }
          }
        }
      }

      this.return_individual_taxes = return_individual_taxes;

      return return_individual_taxes;
    }
  }, {
    key: "getStatus",
    value: function getStatus() {
      var status = this.status;
      if (status == "" && this.type == 1) {
        status = this.getComputedStatus();
      }
      return status;
    }
  }, {
    key: "getComputedStatus",
    value: function getComputedStatus() {
      var status = "";
      var total_payments = parseFloat(this.totalPaid().toFixed(vm.format.decimals));
      var total = parseFloat(this.thetotal().toFixed(vm.format.decimals));

      if (this.total_unpaid == 0 && total_payments >= total) {
        status = "paid";
      } else if (this.invoice_duedate != "0000-00-00" && this.invoice_duedate != "0000-00-00 00:00:00" && this.invoice_duedate != "") {
        if (moment(this.invoice_duedate).isBefore(moment())) {
          status = "pastdue";
        } else {
          if (this.total_unpaid > 0 && total_payments > 0) {
            status = "partial_paid";
          } else status = "pending";
        }
      } else if (this.invoice_duedate == "0000-00-00" || this.invoice_duedate == "0000-00-00 00:00:00" || this.invoice_duedate == "") {
        if (this.total_unpaid > 0 && total_payments > 0) {
          status = "partial_paid";
        } else if (total_payments > 0) {
          status = "partial_paid";
        } else status = "pending";
      }

      return status;
    }
  }, {
    key: "getPaymentStatus",
    value: function getPaymentStatus(payment) {

      var thestatus = 0;

      if (payment.payment_status) {
        thestatus = 1;
      } else if (payment.payment_duedate != "0000-00-00 00:00:00" && !payment.payment_status) {
        if (moment(payment.payment_duedate).isBefore(moment())) {

          thestatus = 0;
        } else {

          thestatus = 2;
        }
      } else if (payment.payment_duedate == "0000-00-00 00:00:00") {
        thestatus = 2;
      }

      if (payment.payment_status == 2) {
        thestatus = 3;
      }

      return thestatus;
    }
  }, {
    key: "getPaymentStatusClass",
    value: function getPaymentStatusClass(payment) {

      var status = this.getPaymentStatus(payment);

      switch (status) {
        case 0:
          status = "danger";
          break;
        case 1:
          status = "success";
          break;
        case 2:
          status = "warning";
          break;
        case 3:
          status = "default";
          break;
      }

      return status;
    }
  }, {
    key: "getPaymentStatusName",
    value: function getPaymentStatusName(payment) {

      var status = this.getPaymentStatus(payment);

      switch (status) {
        case 0:
          status = "UNPAID";
          break;
        case 1:
          status = "PAID";
          break;
        case 2:
          status = "UNPAID_ONTIME";
          break;
        case 3:
          status = "PENDING_VALIDATION";
          break;
      }

      return status;
    }
  }]);

  return Invoice;
}(); // end Invoice class

//export default Invoice;