# HG changeset patch
# User Silambarasan Sekar <silambarasan@qualiantech.com>
# Date 1469180183 -19800
#      Fri Jul 22 15:06:23 2016 +0530
# Node ID c5759ccfa5e39c437085df3befd6cacd00e69b16
# Parent  01921790ee465b4866401a9c7cc5129ce34e76fe
Cash Vat in sales order and sales invoice

diff -r 01921790ee46 -r c5759ccfa5e3 src/org/openbravo/retail/posterminal/OrderGroupingProcessor.java
--- a/src/org/openbravo/retail/posterminal/OrderGroupingProcessor.java	Thu Sep 01 14:00:14 2016 +0530
+++ b/src/org/openbravo/retail/posterminal/OrderGroupingProcessor.java	Fri Jul 22 15:06:23 2016 +0530
@@ -38,6 +38,7 @@
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.database.ConnectionProvider;
+import org.openbravo.erpCommon.utility.CashVATUtil;
 import org.openbravo.erpCommon.utility.SequenceIdData;
 import org.openbravo.erpCommon.utility.Utility;
 import org.openbravo.model.ad.access.InvoiceLineTax;
@@ -50,6 +51,7 @@
 import org.openbravo.model.common.order.Order;
 import org.openbravo.model.common.order.OrderLine;
 import org.openbravo.model.common.order.OrderLineOffer;
+import org.openbravo.model.financialmgmt.payment.FIN_PaymentDetail;
 import org.openbravo.model.financialmgmt.payment.FIN_PaymentSchedule;
 import org.openbravo.model.financialmgmt.payment.FIN_PaymentScheduleDetail;
 import org.openbravo.model.materialmgmt.transaction.ShipmentInOutLine;
@@ -221,6 +223,9 @@
           invoice.getDocumentType()));
       invoice.setDescription("Created by cash up " + cashUp.getIdentifier());
       finishInvoice(invoice, currentDate);
+      if (invoice.isCashVAT()) {
+        createCashVat(invoice);
+      }
       executeHooks(invoice, cashUpId);
     }
 
@@ -337,6 +342,18 @@
             : doctype.getId(), false, true);
   }
 
+  protected void createCashVat(Invoice invoiceObj) {
+    for (FIN_PaymentSchedule scheduleObj : invoiceObj.getFINPaymentScheduleList()) {
+      for (FIN_PaymentScheduleDetail schDetailObj : scheduleObj
+          .getFINPaymentScheduleDetailInvoicePaymentScheduleList()) {
+        FIN_PaymentDetail paymentDetail = schDetailObj.getPaymentDetails();
+        if (paymentDetail != null)
+          CashVATUtil.createInvoiceTaxCashVAT(paymentDetail, scheduleObj, paymentDetail.getAmount()
+              .add(paymentDetail.getWriteoffAmount()));
+      }
+    }
+  }
+
   private void finishInvoice(Invoice oriInvoice, Date currentDate) throws SQLException {
     if (oriInvoice == null) {
       return;
diff -r 01921790ee46 -r c5759ccfa5e3 src/org/openbravo/retail/posterminal/OrderGroupingProcessor_data.xsql
--- a/src/org/openbravo/retail/posterminal/OrderGroupingProcessor_data.xsql	Thu Sep 01 14:00:14 2016 +0530
+++ b/src/org/openbravo/retail/posterminal/OrderGroupingProcessor_data.xsql	Fri Jul 22 15:06:23 2016 +0530
@@ -30,13 +30,13 @@
         (c_invoice_id, ad_client_id, ad_org_id, isactive, created, createdby, updated, updatedby, issotrx,
          documentno, docstatus, docaction, processing, processed, posted, c_doctype_id, c_doctypetarget_id, c_order_id, description, dateordered,
          salesrep_id, dateinvoiced, dateacct, c_bpartner_id, c_bpartner_location_id,  c_currency_id, paymentrule, c_paymentterm_id, totallines,
-         grandtotal, m_pricelist_id, ispaid, totalpaid, outstandingamt, fin_paymentmethod_id, em_aprm_processinvoice)
+         grandtotal, m_pricelist_id, ispaid, totalpaid, outstandingamt, fin_paymentmethod_id, em_aprm_processinvoice, iscashvat)
         select get_uuid(), o.ad_client_id, o.ad_org_id, 'Y', now(), ?, now(), ?, 'Y', ?,
         'CO', 'RE', 'N', 'Y', 'N', dt.c_doctypeinvoice_id, dt.c_doctypeinvoice_id,
         null, null, null, max(o.salesrep_id), to_timestamp(to_char(?), to_char('DD-MM-YYYY HH24:MI:SS')),
         to_timestamp(to_char(?), to_char('DD-MM-YYYY HH24:MI:SS')), o.c_bpartner_id, coalesce(o.billto_id, o.c_bpartner_location_id),
         o.c_currency_id, bp.paymentrule, bp.c_paymentterm_id, sum(o.totallines), sum(o.grandtotal), max(o.m_pricelist_id),
-        'Y', sum(o.grandtotal),  0, bp.fin_paymentmethod_id, 'RE'
+        'Y', sum(o.grandtotal),  0, bp.fin_paymentmethod_id, 'RE', o.iscashvat
         from  c_order o, obpos_applications ap, obpos_terminaltype tt, c_doctype dt, c_bpartner bp
         where o.em_obpos_applications_id = ap.obpos_applications_id
         and ap.obpos_terminaltype_id = tt.obpos_terminaltype_id
@@ -48,7 +48,7 @@
         and o.em_obpos_notinvoiceoncashup = 'N'
         group by  o.ad_client_id, o.ad_org_id, dt.c_doctypeinvoice_id, dt.c_doctypeinvoice_id,
         o.c_bpartner_id, o.c_bpartner_location_id, o.billto_id, o.c_currency_id, bp.paymentrule,
-        bp.c_paymentterm_id, o.m_pricelist_id, bp.fin_paymentmethod_id
+        bp.c_paymentterm_id, o.m_pricelist_id, bp.fin_paymentmethod_id, o.iscashvat
     ]]>
     </Sql>
     <Parameter name="userId"/>
@@ -67,14 +67,14 @@
         (c_invoice_id, ad_client_id, ad_org_id, isactive, created, createdby, updated, updatedby, issotrx,
          documentno, docstatus, docaction, processing, processed, posted, c_doctype_id, c_doctypetarget_id, c_order_id, description, dateordered,
          salesrep_id, dateinvoiced, dateacct, c_bpartner_id, c_bpartner_location_id,  c_currency_id, paymentrule, c_paymentterm_id, totallines,
-         grandtotal, m_pricelist_id, ispaid, totalpaid, outstandingamt, fin_paymentmethod_id, em_aprm_processinvoice)
+         grandtotal, m_pricelist_id, ispaid, totalpaid, outstandingamt, fin_paymentmethod_id, em_aprm_processinvoice, iscashvat)
         select get_uuid(), o.ad_client_id, o.ad_org_id, 'Y', now(), ?, now(), ?, 'Y', ?, 'CO', 'RE', 'N', 'Y', 'N',
         dt.c_doctypeinvoice_id, dt.c_doctypeinvoice_id,
         o.c_order_id, max(ad_message_get2('OrderDocumentno', ?)) || ' ' || o.documentno, o.dateordered,
         max(o.salesrep_id), to_timestamp(to_char(?), to_char('DD-MM-YYYY HH24:MI:SS')),
         to_timestamp(to_char(?), to_char('DD-MM-YYYY HH24:MI:SS')),
         o.c_bpartner_id, coalesce(o.billto_id, o.c_bpartner_location_id), o.c_currency_id, bp.paymentrule,
-        bp.c_paymentterm_id, sum(o.totallines), sum(o.grandtotal), max(o.m_pricelist_id), 'Y', sum(o.grandtotal),  0, bp.fin_paymentmethod_id, 'RE'
+        bp.c_paymentterm_id, sum(o.totallines), sum(o.grandtotal), max(o.m_pricelist_id), 'Y', sum(o.grandtotal),  0, bp.fin_paymentmethod_id, 'RE', o.iscashvat
         from  c_order o, obpos_applications ap, obpos_terminaltype tt, c_doctype dt, c_bpartner bp
         where o.em_obpos_applications_id = ap.obpos_applications_id
         and ap.obpos_terminaltype_id = tt.obpos_terminaltype_id
@@ -87,7 +87,7 @@
         group by  o.ad_client_id, o.ad_org_id, dt.c_doctypeinvoice_id, dt.c_doctypeinvoice_id,
         o.c_bpartner_id, o.c_bpartner_location_id, o.billto_id, o.c_currency_id, bp.paymentrule,
         bp.c_paymentterm_id, o.m_pricelist_id, bp.fin_paymentmethod_id,
-        o.c_order_id, o.dateOrdered, o.documentno
+        o.c_order_id, o.dateOrdered, o.documentno, o.iscashvat
         order by o.dateOrdered, o.documentno
       ]]>
     </Sql>
@@ -131,6 +131,7 @@
         and o.c_doctype_id in (tt.c_doctype_id, tt.c_doctyperet_id)
         and not exists (select 1 from c_orderline ol2 where ol2.qtyinvoiced <> 0 and ol2.c_order_id = o.c_order_id)
         and o.em_obpos_notinvoiceoncashup = 'N'
+        and o.iscashvat = i.iscashvat
         and i.documentno = ?
         and i.c_bpartner_id = o.c_bpartner_id and i.c_bpartner_location_id = o.billto_id
         group by i.ad_client_id, i.ad_org_id, i.createdby, i.updatedby,
@@ -179,6 +180,7 @@
         and o.c_doctype_id in (tt.c_doctype_id, tt.c_doctyperet_id)
         and not exists (select 1 from c_orderline ol2 where ol2.qtyinvoiced <> 0 and ol2.c_order_id = o.c_order_id)
         and o.em_obpos_notinvoiceoncashup = 'N'
+        and o.iscashvat = i.iscashvat
         and i.documentno = ?
         and i.c_order_id = o.c_order_id
         group by i.ad_client_id, i.ad_org_id, i.createdby, i.updatedby,
@@ -409,4 +411,4 @@
     ]]></Sql>
     <Parameter name="executionId"/>
   </SqlMethod>
-</SqlClass>
+</SqlClass>
\ No newline at end of file
diff -r 01921790ee46 -r c5759ccfa5e3 src/org/openbravo/retail/posterminal/OrderLoader.java
--- a/src/org/openbravo/retail/posterminal/OrderLoader.java	Thu Sep 01 14:00:14 2016 +0530
+++ b/src/org/openbravo/retail/posterminal/OrderLoader.java	Fri Jul 22 15:06:23 2016 +0530
@@ -1419,6 +1419,9 @@
       order.setId(jsonorder.getString("id"));
       order.setNewOBObject(true);
     }
+    if (jsonorder.has("cashVAT")) {
+      order.setCashVAT(jsonorder.getBoolean("cashVAT"));
+    }
     int pricePrecision = order.getCurrency().getObposPosprecision() == null ? order.getCurrency()
         .getPricePrecision().intValue() : order.getCurrency().getObposPosprecision().intValue();
     BusinessPartner bp = order.getBusinessPartner();
diff -r 01921790ee46 -r c5759ccfa5e3 src/org/openbravo/retail/posterminal/term/Terminal.java
--- a/src/org/openbravo/retail/posterminal/term/Terminal.java	Thu Sep 01 14:00:14 2016 +0530
+++ b/src/org/openbravo/retail/posterminal/term/Terminal.java	Fri Jul 22 15:06:23 2016 +0530
@@ -40,6 +40,7 @@
 import org.openbravo.mobile.core.process.SimpleQueryBuilder;
 import org.openbravo.model.ad.domain.ModelImplementation;
 import org.openbravo.model.ad.domain.ModelImplementationParameter;
+import org.openbravo.model.common.enterprise.Organization;
 import org.openbravo.model.common.enterprise.OrganizationInformation;
 import org.openbravo.retail.posterminal.InitialValidations;
 import org.openbravo.retail.posterminal.JSONProcessSimple;
@@ -100,13 +101,17 @@
 
       HQLPropertyList regularTerminalHQLProperties = ModelExtensionUtils
           .getPropertyExtensions(extensions);
+      String strOrgId = pOSTerminal.getOrganization().getId();
 
       final OrganizationInformation myOrgInfo = pOSTerminal.getOrganization()
           .getOrganizationInformationList().get(0);
+      final Organization org = OBDal.getInstance().get(Organization.class, strOrgId);
+      final Organization legalEntity = OBContext.getOBContext()
+          .getOrganizationStructureProvider(org.getClient().getId()).getLegalEntity(org);
 
       String storeAddress = "";
       String regionId = "";
-      String countryId = "";
+      String countryId = "", orgInfoId = "";
 
       if (myOrgInfo.getLocationAddress() != null
           && myOrgInfo.getLocationAddress().getIdentifier().length() > 0) {
@@ -120,6 +125,12 @@
       if (myOrgInfo.getLocationAddress().getCountry() != null) {
         countryId = myOrgInfo.getLocationAddress().getCountry().getId();
       }
+
+      if (legalEntity != null && legalEntity.getOrganizationInformationList() != null
+          && !legalEntity.getOrganizationInformationList().isEmpty()) {
+        orgInfoId = legalEntity.getId();
+      }
+
       String selectOrgImage = "";
       String fromOrgImage = "";
       String whereOrgImage = "";
@@ -179,7 +190,7 @@
           + "'"
           + countryId
           + "'"
-          + " as organizationCountryId, '"
+          + " as organizationCountryId,  orginfo.cashVAT as cashVat,'"
           + ProcessHQLQuery.escape(storeAddress)
           + "' as organizationAddressIdentifier, "
           + sessionTimeout
@@ -187,7 +198,11 @@
           + selectOrgImage
           + regularTerminalHQLProperties.getHqlSelect()
           + " from OBPOS_Applications AS pos inner join pos.obposTerminaltype as postype "
+          + ", Organization org "
           + fromOrgImage
+          + " inner join org.organizationInformationList as orginfo with orginfo.id='"
+          + orgInfoId
+          + "'"
           + " where pos.$readableSimpleCriteria and pos.$activeCriteria  and pos.searchKey = :searchKey "
           + whereOrgImage;
 
diff -r 01921790ee46 -r c5759ccfa5e3 web/org.openbravo.retail.posterminal/js/data/dataordertaxes.js
--- a/web/org.openbravo.retail.posterminal/js/data/dataordertaxes.js	Thu Sep 01 14:00:14 2016 +0530
+++ b/web/org.openbravo.retail.posterminal/js/data/dataordertaxes.js	Fri Jul 22 15:06:23 2016 +0530
@@ -112,7 +112,8 @@
             bplCountryId = receipt.get('bp').get('locationModel') ? receipt.get('bp').get('locationModel').get('countryId') : null,
             bplRegionId = receipt.get('bp').get('locationModel') ? receipt.get('bp').get('locationModel').get('regionId') : null,
             bpName = receipt.get('bp').get('name') || OB.I18N.getLabel('OBPOS_LblEmptyAddress'),
-            bpLocName = receipt.get('bp').get('locName') || OB.I18N.getLabel('OBPOS_LblEmptyAddress');
+            bpLocName = receipt.get('bp').get('locName') || OB.I18N.getLabel('OBPOS_LblEmptyAddress'),
+            isCashVat = OB.MobileApp.model.get('terminal').cashVat;
         // SQL build
         // the query is ordered by countryId desc and regionId desc
         // (so, the first record will be the tax with the same country or
@@ -143,6 +144,9 @@
           sql = sql + " and (c_tax.to_country_id = '" + bplCountryId + "'   or tz.to_country_id = '" + bplCountryId + "'   or (c_tax.to_country_id is null       and (not exists (select 1 from c_tax_zone z where z.c_tax_id = c_tax.c_tax_id)           or exists (select 1 from c_tax_zone z where z.c_tax_id = c_tax.c_tax_id and z.to_country_id = '" + bplCountryId + "')           or exists (select 1 from c_tax_zone z where z.c_tax_id = c_tax.c_tax_id and z.to_country_id is null))))";
           sql = sql + " and (c_tax.to_region_id = '" + bplRegionId + "'   or tz.to_region_id = '" + bplRegionId + "'  or (c_tax.to_region_id is null       and (not exists (select 1 from c_tax_zone z where z.c_tax_id = c_tax.c_tax_id)           or exists (select 1 from c_tax_zone z where z.c_tax_id = c_tax.c_tax_id and z.to_region_id = '" + bplRegionId + "')           or exists (select 1 from c_tax_zone z where z.c_tax_id = c_tax.c_tax_id and z.to_region_id is null))))";
         }
+        if (isCashVat) {
+          sql = sql + " and (c_tax.isCashVAT ='" + isCashVat + "' OR (c_tax.isCashVAT = 'false' and (c_tax.isWithholdingTax = 'true' or c_tax.rate=0))) ";
+        }
         sql = sql + " order by orderRegionTo, orderRegionFrom, orderCountryTo, orderCountryFrom, c_tax.validFrom desc, c_tax.isdefault desc";
 
         OB.UTIL.HookManager.executeHooks('OBPOS_FindTaxRate', {
diff -r 01921790ee46 -r c5759ccfa5e3 web/org.openbravo.retail.posterminal/js/model/order.js
--- a/web/org.openbravo.retail.posterminal/js/model/order.js	Thu Sep 01 14:00:14 2016 +0530
+++ b/web/org.openbravo.retail.posterminal/js/model/order.js	Fri Jul 22 15:06:23 2016 +0530
@@ -3536,6 +3536,7 @@
       order.set('isQuotation', false);
       order.set('oldId', null);
       order.set('session', OB.MobileApp.model.get('session'));
+      order.set('cashVAT', OB.MobileApp.model.get('terminal').cashVat);
       order.set('bp', bp);
       if (OB.MobileApp.model.hasPermission('EnableMultiPriceList', true)) {
         // Set price list for order
