# HG changeset patch
# User Rafa Alonso <rafael.alonso@openbravo.com>
# Date 1412948683 -7200
#      Fri Oct 10 15:44:43 2014 +0200
# Node ID 0cc9a2a7002727f4ae51d6c43dde4614a37d6694
# Parent  d742e2eed52cfc844be93dac4c1817aa3bdf446c
Fixes issue 27631: Document sequence is not reseted when you change the prefix

diff -r d742e2eed52c -r 0cc9a2a70027 src/org/openbravo/retail/posterminal/POSUtils.java
--- a/src/org/openbravo/retail/posterminal/POSUtils.java	Fri Oct 10 15:23:54 2014 +0200
+++ b/src/org/openbravo/retail/posterminal/POSUtils.java	Fri Oct 10 15:44:43 2014 +0200
@@ -371,6 +371,83 @@
     return maxDocNo;
   }

+  public static int getLastDocumentNumberQuotationForPOS(String searchKey,
+      List<String> documentTypeIds) {
+    OBCriteria<OBPOSApplications> termCrit = OBDal.getInstance().createCriteria(
+        OBPOSApplications.class);
+    termCrit.add(Restrictions.eq(OBPOSApplications.PROPERTY_SEARCHKEY, searchKey));
+    if (termCrit.count() != 1) {
+      throw new OBException("Error while loading the terminal " + searchKey);
+    }
+    OBPOSApplications terminal = (OBPOSApplications) termCrit.uniqueResult();
+
+    String curDbms = OBPropertiesProvider.getInstance().getOpenbravoProperties()
+        .getProperty("bbdd.rdbms");
+    String sqlToExecute;
+    String doctypeIds = "";
+    for (String doctypeId : documentTypeIds) {
+      if (!doctypeIds.equals("")) {
+        doctypeIds += ",";
+      }
+      doctypeIds += "'" + doctypeId + "'";
+    }
+
+    if (curDbms.equals("POSTGRE")) {
+      sqlToExecute = "select max(a.docno) from (select to_number(substring(documentno, '/([0-9]+)$')) docno from c_order where em_obpos_applications_id= (select obpos_applications_id from obpos_applications where value = ?) and c_doctype_id in ("
+          + doctypeIds
+          + ") and documentno like (select quotationdocno_prefix from obpos_applications where value = ?)||'%') a";
+    } else if (curDbms.equals("ORACLE")) {
+      sqlToExecute = "select max(a.docno) from (select to_number(substr(REGEXP_SUBSTR(documentno, '/([0-9]+)$'), 2)) docno from c_order where em_obpos_applications_id= (select obpos_applications_id from obpos_applications where value = ?) and c_doctype_id in ("
+          + doctypeIds
+          + ") and documentno like (select quotationdocno_prefix from obpos_applications where value = ?)||'%' ) a";
+    } else {
+      // unknow DBMS
+      // shouldn't happen
+      log.error("Error getting max documentNo because the DBMS is unknown.");
+      return 0;
+    }
+
+    SQLQuery query = OBDal.getInstance().getSession().createSQLQuery(sqlToExecute);
+    query.setString(0, searchKey);
+    query.setString(1, searchKey);
+    int maxDocNo;
+    Object result = query.uniqueResult();
+    if (result == null) {
+      maxDocNo = 0;
+    } else if (curDbms.equals("POSTGRE")) {
+      maxDocNo = ((BigDecimal) result).intValue();
+    } else if (curDbms.equals("ORACLE")) {
+      maxDocNo = ((Long) result).intValue();
+    } else {
+      maxDocNo = 0;
+    }
+
+    // This number will be compared against the maximum number of the failed orders
+    OBCriteria<OBPOSErrors> errorCrit = OBDal.getInstance().createCriteria(OBPOSErrors.class);
+    errorCrit.add(Restrictions.eq(OBPOSErrors.PROPERTY_OBPOSAPPLICATIONS, terminal));
+    errorCrit.add(Restrictions.eq(OBPOSErrors.PROPERTY_TYPEOFDATA, "order"));
+    List<OBPOSErrors> errors = errorCrit.list();
+    for (OBPOSErrors error : errors) {
+      try {
+        JSONObject jsonError = new JSONObject(error.getJsoninfo());
+        if (jsonError.has("documentNo")) {
+          String documentNo = jsonError.getString("documentNo");
+          if (documentNo.indexOf("/") != 0) {
+            String number = documentNo.substring(documentNo.indexOf("/") + 1);
+            int errorNumber = new Long(number).intValue();
+            if (errorNumber > maxDocNo) {
+              maxDocNo = errorNumber;
+            }
+          }
+        }
+      } catch (Exception e) {
+        e.printStackTrace();
+        // If not parseable, we continue
+      }
+    }
+    return maxDocNo;
+  }
+
   public static int getLastDocumentNumberForPOS(String searchKey, String documentTypeId) {
     ArrayList<String> doctypeId = new ArrayList<String>();
     doctypeId.add(documentTypeId);
@@ -378,6 +455,12 @@

   }

+  public static int getLastDocumentNumberQuotationForPOS(String searchKey, String documentTypeId) {
+    ArrayList<String> doctypeId = new ArrayList<String>();
+    doctypeId.add(documentTypeId);
+    return getLastDocumentNumberQuotationForPOS(searchKey, doctypeId);
+  }
+
   public static void getRetailDependantModules(Module module, List<Module> moduleList,
       List<ModuleDependency> list) {
     for (ModuleDependency depModule : list) {
diff -r d742e2eed52c -r 0cc9a2a70027 src/org/openbravo/retail/posterminal/term/Terminal.java
--- a/src/org/openbravo/retail/posterminal/term/Terminal.java	Fri Oct 10 15:23:54 2014 +0200
+++ b/src/org/openbravo/retail/posterminal/term/Terminal.java	Fri Oct 10 15:44:43 2014 +0200
@@ -62,7 +62,7 @@
         doctypeIds);
     int lastQuotationDocumentNumber = 0;
     if (quotationsDocTypeId != null) {
-      lastQuotationDocumentNumber = POSUtils.getLastDocumentNumberForPOS(
+      lastQuotationDocumentNumber = POSUtils.getLastDocumentNumberQuotationForPOS(
           pOSTerminal.getSearchKey(), quotationsDocTypeId);
     }
     String warehouseId = POSUtils.getWarehouseForTerminal(pOSTerminal).getId();
diff -r d742e2eed52c -r 0cc9a2a70027 web/org.openbravo.retail.posterminal/js/login/model/login-model.js
--- a/web/org.openbravo.retail.posterminal/js/login/model/login-model.js	Fri Oct 10 15:23:54 2014 +0200
+++ b/web/org.openbravo.retail.posterminal/js/login/model/login-model.js	Fri Oct 10 15:44:43 2014 +0200
@@ -610,6 +610,13 @@
      */
     saveDocumentSequence: function (documentnoSuffix, quotationnoSuffix) {
       var me = this;
+      if (me.restartingDocNo === true) {
+        return;
+      }
+      //If documentnoSuffix === 0 || quotationnoSuffix === 0, it means that we have restarted documentNo prefix, so we block this method while we save the new documentNo in localStorage
+      if (documentnoSuffix === 0 || quotationnoSuffix === 0) {
+        me.restartingDocNo = true;
+      }

       /**
        * If for whatever reason the maxSuffix is not the current order suffix (most likely, the server returning a higher docno value)
@@ -622,7 +629,7 @@
           var orderlist = OB.MobileApp.model.orderList;
           if (orderlist && orderlist.models.length > 0 && orderlist.current) {
             if (orderlist.current.get('lines') && orderlist.current.get('lines').length === 0) {
-              if (orderlist.current.get('documentnoSuffix') <= me.documentnoThreshold) {
+              if (orderlist.current.get('documentnoSuffix') <= me.documentnoThreshold || me.documentnoThreshold === 0) {
                 orderlist.deleteCurrent();
               }
             }
@@ -630,10 +637,10 @@
           };

       // verify that the values are higher than the local variables
-      if (documentnoSuffix > this.documentnoThreshold) {
+      if (documentnoSuffix > this.documentnoThreshold || documentnoSuffix === 0) {
         this.documentnoThreshold = documentnoSuffix;
       }
-      if (quotationnoSuffix > this.quotationnoThreshold) {
+      if (quotationnoSuffix > this.quotationnoThreshold || quotationnoSuffix === 0) {
         this.quotationnoThreshold = quotationnoSuffix;
       }

@@ -646,11 +653,11 @@
         if (documentSequenceList && documentSequenceList.length > 0) {
           // There can only be one documentSequence model in the list (posSearchKey is unique)
           docSeq = documentSequenceList.models[0];
-          // verify if the new values are higher
-          if (docSeq.get('documentSequence') > me.documentnoThreshold) {
+          // verify if the new values are higher and if it is not undefined or 0
+          if (docSeq.get('documentSequence') > me.documentnoThreshold && documentnoSuffix !== 0) {
             me.documentnoThreshold = docSeq.get('documentSequence');
           }
-          if (docSeq.get('quotationDocumentSequence') > me.quotationnoThreshold) {
+          if (docSeq.get('quotationDocumentSequence') > me.quotationnoThreshold && quotationnoSuffix !== 0) {
             me.quotationnoThreshold = docSeq.get('quotationDocumentSequence');
           }
         } else {
@@ -664,12 +671,14 @@
         docSeq.set('quotationDocumentSequence', me.quotationnoThreshold);
         OB.Dal.save(docSeq, function () {
           synchronizeCurrentOrder();
+          me.restartingDocNo = false;
         }, function () {
           // nothing to do
+          me.restartingDocNo = false;
         });

       }, function () {
-        OB.debug("The 'c_document_sequence' table is locked");
+        me.restartingDocNo = false;
       });
     },

@@ -691,7 +700,7 @@
         var i = OB.MobileApp.model.orderList.models.length - 1;
         while (lastSuffix === null && i >= 0) {
           var order = OB.MobileApp.model.orderList.models[i];
-          if (!order.get('isPaid') && !order.get('isQuotation')) {
+          if (!order.get('isPaid') && !order.get('isQuotation') && order.get('docNoPrefix') === OB.MobileApp.model.get('terminal').docNoPrefix) {
             lastSuffix = order.get('documentnoSuffix');
           }
           i--;
@@ -709,7 +718,7 @@
         var i = OB.MobileApp.model.orderList.models.length - 1;
         while (lastSuffix === null && i >= 0) {
           var order = OB.MobileApp.model.orderList.models[i];
-          if (order.get('isQuotation')) {
+          if (order.get('isQuotation') && order.get('quotationDocNoPrefix') === OB.MobileApp.model.get('terminal').quotationDocNoPrefix) {
             lastSuffix = order.get('quotationnoSuffix');
           }
           i--;
diff -r d742e2eed52c -r 0cc9a2a70027 web/org.openbravo.retail.posterminal/js/model/order.js
--- a/web/org.openbravo.retail.posterminal/js/model/order.js	Fri Oct 10 15:23:54 2014 +0200
+++ b/web/org.openbravo.retail.posterminal/js/model/order.js	Fri Oct 10 15:44:43 2014 +0200
@@ -267,6 +267,8 @@
         this.set('posTerminal', attributes.posTerminal);
         this.set('posTerminal' + OB.Constants.FIELDSEPARATOR + OB.Constants.IDENTIFIER, attributes['posTerminal' + OB.Constants.FIELDSEPARATOR + OB.Constants.IDENTIFIER]);
         this.set('orderDate', new Date(attributes.orderDate));
+        this.set('quotationDocNoPrefix', attributes.quotationDocNoPrefix);
+        this.set('docNoPrefix', attributes.docNoPrefix);
         this.set('documentnoSuffix', attributes.documentnoSuffix);
         this.set('quotationnoSuffix', attributes.quotationnoSuffix);
         this.set('documentNo', attributes.documentNo);
@@ -580,6 +582,8 @@
       this.set('posTerminal', null);
       this.set('posTerminal' + OB.Constants.FIELDSEPARATOR + OB.Constants.IDENTIFIER, null);
       this.set('orderDate', new Date());
+      this.set('quotationDocNoPrefix', -1);
+      this.set('docNoPrefix', -1);
       this.set('documentnoSuffix', -1);
       this.set('quotationnoSuffix', -1);
       this.set('documentNo', '');
@@ -1380,9 +1384,11 @@
       this.set('isPaid', false);
       this.set('isEditable', true);
       this.set('orderDate', new Date());
+      this.set('quotationDocNoPrefix', OB.MobileApp.model.get('terminal').quotationDocNoPrefix);
+      this.set('docNoPrefix', OB.MobileApp.model.get('terminal').docNoPrefix);
       var nextDocumentno = OB.MobileApp.model.getNextDocumentno();
       this.set('documentnoSuffix', nextDocumentno.documentnoSuffix);
-      this.set('documentNo',  nextDocumentno.documentNo);
+      this.set('documentNo', nextDocumentno.documentNo);
       this.set('posTerminal', OB.POS.modelterminal.get('terminal').id);
       this.save();
       if (updatePrices) {
@@ -2078,9 +2084,11 @@
       order.set('isLayaway', false);
       order.set('taxes', null);

+      order.set('quotationDocNoPrefix', OB.MobileApp.model.get('terminal').quotationDocNoPrefix);
+      order.set('docNoPrefix', OB.MobileApp.model.get('terminal').docNoPrefix);
       var nextDocumentno = OB.MobileApp.model.getNextDocumentno();
       order.set('documentnoSuffix', nextDocumentno.documentnoSuffix);
-      order.set('documentNo',  nextDocumentno.documentNo);
+      order.set('documentNo', nextDocumentno.documentNo);

       order.set('bp', OB.POS.modelterminal.get('businessPartner'));
       order.set('print', true);
@@ -2281,7 +2289,7 @@
       this.current.set('documentType', OB.POS.modelterminal.get('terminal').terminalType.documentTypeForQuotations);
       var nextQuotationno = OB.MobileApp.model.getNextQuotationno();
       this.current.set('quotationnoSuffix', nextQuotationno.quotationnoSuffix);
-      this.current.set('documentNo',  nextQuotationno.documentNo);
+      this.current.set('documentNo', nextQuotationno.documentNo);

       this.add(this.current);
       this.loadCurrent();
