# HG changeset patch
# User Miguel de Juana <miguel.dejuana@openbravo.com>
# Date 1411471688 -7200
#      Tue Sep 23 13:28:08 2014 +0200
# Node ID 66c542692433ba7b535fb750d5b20e071cecb76b
# Parent  cfe16f6aae3ebd800bc3c05886a8169b1c92437b
Fixed issue 0027631: Document sequence is not reseted when you change the prefix

diff -r cfe16f6aae3e -r 66c542692433 src/org/openbravo/retail/posterminal/POSUtils.java
--- a/src/org/openbravo/retail/posterminal/POSUtils.java	Sat Sep 06 19:18:34 2014 +0200
+++ b/src/org/openbravo/retail/posterminal/POSUtils.java	Tue Sep 23 13:28:08 2014 +0200
@@ -324,13 +324,90 @@
     query.setString(0, searchKey);
     query.setString(1, searchKey);
     int maxDocNo;
-    List result = query.list();
-    if (result.size() == 0 || result.get(0) == null) {
+    Object result = query.uniqueResult();
+    if (result == null) {
       maxDocNo = 0;
     } else if (curDbms.equals("POSTGRE")) {
-      maxDocNo = ((BigDecimal) result.get(0)).intValue();
+      maxDocNo = ((BigDecimal) result).intValue();
     } else if (curDbms.equals("ORACLE")) {
-      maxDocNo = ((Long) result.get(0)).intValue();
+      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 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;
     }
@@ -368,6 +445,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 cfe16f6aae3e -r 66c542692433 src/org/openbravo/retail/posterminal/term/Terminal.java
--- a/src/org/openbravo/retail/posterminal/term/Terminal.java	Sat Sep 06 19:18:34 2014 +0200
+++ b/src/org/openbravo/retail/posterminal/term/Terminal.java	Tue Sep 23 13:28:08 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 cfe16f6aae3e -r 66c542692433 web/org.openbravo.retail.posterminal/js/login/model/login-model.js
--- a/web/org.openbravo.retail.posterminal/js/login/model/login-model.js	Sat Sep 06 19:18:34 2014 +0200
+++ b/web/org.openbravo.retail.posterminal/js/login/model/login-model.js	Tue Sep 23 13:28:08 2014 +0200
@@ -466,6 +466,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)
@@ -478,7 +485,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();
               }
             }
@@ -486,10 +493,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;
       }
 
@@ -502,11 +509,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 {
@@ -520,12 +527,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;
       });
     },
 
@@ -547,7 +556,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--;
@@ -565,7 +574,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 cfe16f6aae3e -r 66c542692433 web/org.openbravo.retail.posterminal/js/model/order.js
--- a/web/org.openbravo.retail.posterminal/js/model/order.js	Sat Sep 06 19:18:34 2014 +0200
+++ b/web/org.openbravo.retail.posterminal/js/model/order.js	Tue Sep 23 13:28:08 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);
@@ -584,6 +586,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', '');
@@ -1377,9 +1381,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) {
@@ -1684,9 +1690,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);
@@ -1887,7 +1895,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();
