From 7efacecb083441e8c4ddbb3f4c3c4c727177aa69 Mon Sep 17 00:00:00 2001
From: simnandez <jmenent@2byte.es>
Date: Fri, 26 Jul 2013 12:46:34 +0200
Subject: [PATCH] New:  [ task #1005 ] Adapting to Spanish legislation bill
 numbering

---
 ChangeLog                                     |   7 +-
 .../core/modules/facture/mod_facture_mars.php | 207 ++++++++++++++++++
 htdocs/langs/ca_ES/bills.lang                 |   1 +
 htdocs/langs/en_US/bills.lang                 |   2 +
 htdocs/langs/es_ES/bills.lang                 |   1 +
 htdocs/langs/fr_FR/bills.lang                 |   1 +
 6 files changed, 216 insertions(+), 3 deletions(-)
 create mode 100644 htdocs/core/modules/facture/mod_facture_mars.php

diff --git a/ChangeLog b/ChangeLog
index 7d3297cad89..1529a25943d 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -32,12 +32,13 @@ For users:
 - New: Can add an event automatically when a projet is create. 
 - New: Add option MAIN_GENERATE_DOCUMENT_WITH_PICTURE.
 - New: Add option excludethirdparties and onlythirdparties into merge pdf scripts.
-- New : [ task #925 ] Add ODT document generation for Tasks in project module.
-- New : [ task #924 ] Add numbering rule on task.
-- New : [ task #165 ] Add import/export of multiprices.
+- New: [ task #925 ] Add ODT document generation for Tasks in project module.
+- New: [ task #924 ] Add numbering rule on task.
+- New: [ task #165 ] Add import/export of multiprices.
 - New: Add Maghreb regions and departments.
 - New: A more responsive desgin for statistic box of home page.
 - Qual: Implement same rule for return value of all command line scripts (0 when success, <>0 if error).
+- New:  [ task #1005 ] Adapting to Spanish legislation bill numbering
 
 
 For translators:
diff --git a/htdocs/core/modules/facture/mod_facture_mars.php b/htdocs/core/modules/facture/mod_facture_mars.php
new file mode 100644
index 00000000000..28a32868d39
--- /dev/null
+++ b/htdocs/core/modules/facture/mod_facture_mars.php
@@ -0,0 +1,207 @@
+<?php
+/* Copyright (C) 2005-2008 Laurent Destailleur  <eldy@users.sourceforge.net>
+ * Copyright (C) 2005-2009 Regis Houssin        <regis.houssin@capnetworks.com>
+ * Copyright (C) 2013		Juanjo Menent		<jmenent@2byte.es>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * or see http://www.gnu.org/
+ */
+
+/**
+ *	\file       htdocs/core/modules/facture/mod_facture_mars.php
+ *	\ingroup    facture
+ *	\brief      File containing class for numbering module Mars
+ */
+require_once DOL_DOCUMENT_ROOT .'/core/modules/facture/modules_facture.php';
+
+/**	    \class      mod_facture_mars
+ *		\brief      Classe du modele de numerotation de reference de facture Mars
+ */
+class mod_facture_mars extends ModeleNumRefFactures
+{
+	var $version='dolibarr';		// 'development', 'experimental', 'dolibarr'
+	var $prefixinvoice='FA';
+	var $prefixreplacement='FR';
+	var $prefixproforma='FP';
+	var $prefixcreditnote='AV';
+	var $error='';
+
+	/**
+	 *  Renvoi la description du modele de numerotation
+	 *
+	 *  @return     string      Texte descripif
+	 */
+	function info()
+	{
+		global $langs;
+		$langs->load("bills");
+		return $langs->trans('MarsNumRefModelDesc1',$this->prefixinvoice,$this->prefixreplacement,$this->prefixproforma,$this->prefixcreditnote);
+	}
+
+	/**
+	 *  Renvoi un exemple de numerotation
+	 *
+	 *  @return     string      Example
+	 */
+	function getExample()
+	{
+		return $this->prefixinvoice."0501-0001";
+	}
+
+	/**
+	 *  Test si les numeros deja en vigueur dans la base ne provoquent pas de
+	 *  de conflits qui empechera cette numerotation de fonctionner.
+	 *
+	 *  @return     boolean     false si conflit, true si ok
+	 */
+	function canBeActivated()
+	{
+		global $langs,$conf;
+
+		$langs->load("bills");
+
+		// Check invoice num
+		$fayymm=''; $max='';
+
+		$posindice=8;
+		$sql = "SELECT MAX(SUBSTRING(facnumber FROM ".$posindice.")) as max";	// This is standard SQL
+		$sql.= " FROM ".MAIN_DB_PREFIX."facture";
+		$sql.= " WHERE facnumber LIKE '".$this->prefixinvoice."____-%'";
+		$sql.= " AND entity = ".$conf->entity;
+
+		$resql=$db->query($sql);
+		if ($resql)
+		{
+			$row = $db->fetch_row($resql);
+			if ($row) { $fayymm = substr($row[0],0,6); $max=$row[0]; }
+		}
+		if ($fayymm && ! preg_match('/'.$this->prefixinvoice.'[0-9][0-9][0-9][0-9]/i',$fayymm))
+		{
+			$langs->load("errors");
+			$this->error=$langs->trans('ErrorNumRefModel',$max);
+			return false;
+		}
+
+		// Check credit note num
+		$fayymm='';
+
+		$posindice=8;
+		$sql = "SELECT MAX(SUBSTRING(facnumber FROM ".$posindice.")) as max";	// This is standard SQL
+		$sql.= " FROM ".MAIN_DB_PREFIX."facture";
+		$sql.= " WHERE facnumber LIKE '".$this->prefixcreditnote."____-%'";
+		$sql.= " AND entity = ".$conf->entity;
+
+		$resql=$db->query($sql);
+		if ($resql)
+		{
+			$row = $db->fetch_row($resql);
+			if ($row) { $fayymm = substr($row[0],0,6); $max=$row[0]; }
+		}
+		if ($fayymm && ! preg_match('/'.$this->prefixcreditnote.'[0-9][0-9][0-9][0-9]/i',$fayymm))
+		{
+			$this->error=$langs->trans('ErrorNumRefModel',$max);
+			return false;
+		}
+
+		return true;
+	}
+
+	/**
+	 * Return next value not used or last value used
+	 *
+	 * @param	Societe		$objsoc		Object third party
+	 * @param   Facture		$facture	Object invoice
+     * @param   string		$mode       'next' for next value or 'last' for last value
+	 * @return  string       			Value
+	 */
+	function getNextValue($objsoc,$facture,$mode='next')
+	{
+		global $db,$conf;
+
+		$prefix=$this->prefixinvoice;
+		
+		if ($facture->type == 1) $prefix=$this->prefixreplacement;
+		elseif ($facture->type == 2) $prefix=$this->prefixcreditnote;
+		elseif ($facture->type == 4) $prefix=$this->prefixproforma; 
+
+		// D'abord on recupere la valeur max
+		$posindice=8;
+		$sql = "SELECT MAX(SUBSTRING(facnumber FROM ".$posindice.")) as max";	// This is standard SQL
+		$sql.= " FROM ".MAIN_DB_PREFIX."facture";
+		$sql.= " WHERE facnumber LIKE '".$prefix."____-%'";
+		$sql.= " AND entity = ".$conf->entity;
+
+		$resql=$db->query($sql);
+		dol_syslog(get_class($this)."::getNextValue sql=".$sql);
+		if ($resql)
+		{
+			$obj = $db->fetch_object($resql);
+			if ($obj) $max = intval($obj->max);
+			else $max=0;
+		}
+		else
+		{
+			dol_syslog(get_class($this)."::getNextValue sql=".$sql, LOG_ERR);
+			return -1;
+		}
+
+		if ($mode == 'last')
+		{
+            $num = sprintf("%04s",$max);
+
+            $ref='';
+            $sql = "SELECT facnumber as ref";
+            $sql.= " FROM ".MAIN_DB_PREFIX."facture";
+            $sql.= " WHERE facnumber LIKE '".$prefix."____-".$num."'";
+            $sql.= " AND entity = ".$conf->entity;
+
+            dol_syslog(get_class($this)."::getNextValue sql=".$sql);
+            $resql=$db->query($sql);
+            if ($resql)
+            {
+                $obj = $db->fetch_object($resql);
+                if ($obj) $ref = $obj->ref;
+            }
+            else dol_print_error($db);
+
+            return $ref;
+		}
+		else if ($mode == 'next')
+		{
+    		$date=$facture->date;	// This is invoice date (not creation date)
+    		$yymm = strftime("%y%m",$date);
+    		$num = sprintf("%04s",$max+1);
+
+    		dol_syslog(get_class($this)."::getNextValue return ".$prefix.$yymm."-".$num);
+    		return $prefix.$yymm."-".$num;
+		}
+		else dol_print_error('','Bad parameter for getNextValue');
+	}
+
+	/**
+	 * Return next free value
+	 *
+     * @param	Societe		$objsoc     	Object third party
+     * @param	string		$objforref		Object for number to search
+     * @param   string		$mode       	'next' for next value or 'last' for last value
+     * @return  string      				Next free value
+	 */
+	function getNumRef($objsoc,$objforref,$mode='next')
+	{
+		return $this->getNextValue($objsoc,$objforref,$mode);
+	}
+
+}
+
+?>
diff --git a/htdocs/langs/ca_ES/bills.lang b/htdocs/langs/ca_ES/bills.lang
index 478da4f90c8..67f88938ca0 100644
--- a/htdocs/langs/ca_ES/bills.lang
+++ b/htdocs/langs/ca_ES/bills.lang
@@ -403,3 +403,4 @@ PDFCrabeDescription=Model de factura complet (model recomanat per defecte)
 PDFOursinDescription=Model de factura complet (model alternatiu)
 # NumRef Modules
 TerreNumRefModelDesc1=Retorna el nombre sota el format %syymm-nnnn per a les factures i %syymm-nnnn per als abonaments on yy és l'any, mm. el mes i nnnn un comptador seqüencial sense ruptura i sense permanència a 0
+MarsNumRefModelDesc1=Retorna el nombre sota el format %syymm-nnnn per a les factures, %syymm-nnnn per a les factures rectificatives, %syymm-nnnn per a les factures proforma i %syymm-nnnn per als abonaments on yy és l'any, mm. el mes i nnnn un comptador seqüencial sense ruptura i sense permanència a 0
\ No newline at end of file
diff --git a/htdocs/langs/en_US/bills.lang b/htdocs/langs/en_US/bills.lang
index 82abde453c1..ceab52445e2 100644
--- a/htdocs/langs/en_US/bills.lang
+++ b/htdocs/langs/en_US/bills.lang
@@ -412,4 +412,6 @@ PDFCrabeDescription=Invoice PDF template Crabe. A complete invoice template (Tem
 PDFOursinDescription=Invoice PDF template Oursin. A complete invoice template (Template alternative)
 # NumRef Modules
 TerreNumRefModelDesc1=Return numero with format %syymm-nnnn for standard invoices and %syymm-nnnn for credit notes where yy is year, mm is month and nnnn is a sequence with no break and no return to 0
+MarsNumRefModelDesc1=Return numero with format %syymm-nnnn for standard invoices, %syymm-nnnn for replacement invoices, %syymm-nnnn for proforma invoices and %syymm-nnnn for credit notes where yy is year, mm is month and nnnn is a sequence with no break and no return to 0
+
 TerreNumRefModelError=A bill starting with $syymm already exists and is not compatible with this model of sequence. Remove it or rename it to activate this module.
diff --git a/htdocs/langs/es_ES/bills.lang b/htdocs/langs/es_ES/bills.lang
index f8093cfe158..0cf2fd83894 100644
--- a/htdocs/langs/es_ES/bills.lang
+++ b/htdocs/langs/es_ES/bills.lang
@@ -406,3 +406,4 @@ PDFCrabeDescription=Modelo de factura completo (modelo recomendado por defecto)
 PDFOursinDescription=Modelo de factura completo (modelo alternativo)
 # NumRef Modules
 TerreNumRefModelDesc1=Devuelve el número bajo el formato %syymm-nnnn para las facturas y %syymm-nnnn para los abonos donde yy es el año, mm. el mes y nnnn un contador secuencial sin ruptura y sin permanencia a 0
+MarsNumRefModelDesc1=Devuelve el número bajo el formato %syymm-nnnn para las facturas, %syymm-nnnn para las facturas rectificativas, %syymm-nnnn para las facturas proforma y %syymm-nnnn para los abonos donde yy es el año, mm. el mes y nnnn un contador secuencial sin ruptura y sin permanencia a 0
\ No newline at end of file
diff --git a/htdocs/langs/fr_FR/bills.lang b/htdocs/langs/fr_FR/bills.lang
index c27aeb340c4..d50dc794c5c 100644
--- a/htdocs/langs/fr_FR/bills.lang
+++ b/htdocs/langs/fr_FR/bills.lang
@@ -409,3 +409,4 @@ PDFCrabeDescription=Modèle de facture PDF complet (modèle recommandé par déf
 PDFOursinDescription=Modèle de facture PDF complet (modèle alternatif)
 # NumRef Modules
 TerreNumRefModelDesc1=Renvoie le numéro sous la forme %syymm-nnnn pour les factures et %syymm-nnnn pour les avoirs où yy est l'année, mm le mois et nnnn un compteur séquentiel sans rupture et sans remise à 0
+MarsNumRefModelDesc1=Renvoie le numéro sous la forme %syymm-nnnn pour les factures, %syymm-nnnn pour les factures de remplacement, %syymm-nnnn pour les factures proforma et %syymm-nnnn pour les avoirs où yy est l'année, mm le mois et nnnn un compteur séquentiel sans rupture et sans remise à 0
\ No newline at end of file
-- 
GitLab