PageRenderTime 53ms CodeModel.GetById 4ms app.highlight 35ms RepoModel.GetById 2ms app.codeStats 0ms

/htdocs/fourn/facture/fiche.php

https://bitbucket.org/speedealing/speedealing
PHP | 2050 lines | 1511 code | 265 blank | 274 comment | 411 complexity | 115b42541377c57293f0d9e88edc0235 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/* Copyright (C) 2002-2005	Rodolphe Quiedeville	<rodolphe@quiedeville.org>
   3 * Copyright (C) 2004-2012	Laurent Destailleur 	<eldy@users.sourceforge.net>
   4 * Copyright (C) 2004		Christophe Combelles	<ccomb@free.fr>
   5 * Copyright (C) 2005		Marc Barilley			<marc@ocebo.fr>
   6 * Copyright (C) 2005-2012	Regis Houssin			<regis.houssin@capnetworks.com>
   7 * Copyright (C) 2010-2012	Juanjo Menent			<jmenent@2byte.es>
   8 *
   9 * This program is free software; you can redistribute it and/or modify
  10 * it under the terms of the GNU General Public License as published by
  11 * the Free Software Foundation; either version 3 of the License, or
  12 * (at your option) any later version.
  13 *
  14 * This program is distributed in the hope that it will be useful,
  15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17 * GNU General Public License for more details.
  18 *
  19 * You should have received a copy of the GNU General Public License
  20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
  21 */
  22
  23/**
  24 *	\file       htdocs/fourn/facture/fiche.php
  25 *	\ingroup    facture, fournisseur
  26 *	\brief      Page for supplier invoice card (view, edit, validate)
  27 */
  28
  29require '../../main.inc.php';
  30require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  31require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
  32require_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_invoice/modules_facturefournisseur.php';
  33require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  34require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
  35require_once DOL_DOCUMENT_ROOT.'/core/lib/fourn.lib.php';
  36require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  37if (! empty($conf->projet->enabled)) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  38
  39
  40$langs->load('bills');
  41$langs->load('suppliers');
  42$langs->load('companies');
  43
  44$mesg='';
  45$errors=array();
  46$id			= (GETPOST('facid','int') ? GETPOST('facid','int') : GETPOST('id','int'));
  47$action		= GETPOST("action");
  48$confirm	= GETPOST("confirm");
  49
  50//PDF
  51$hidedetails = (GETPOST('hidedetails','int') ? GETPOST('hidedetails','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0));
  52$hidedesc 	 = (GETPOST('hidedesc','int') ? GETPOST('hidedesc','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ?  1 : 0));
  53$hideref 	 = (GETPOST('hideref','int') ? GETPOST('hideref','int') : (! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0));
  54
  55// Security check
  56$socid='';
  57if (! empty($user->societe_id)) $socid=$user->societe_id;
  58$result = restrictedArea($user, 'fournisseur', $id, 'facture_fourn', 'facture');
  59
  60// Initialize technical object to manage hooks of thirdparties. Note that conf->hooks_modules contains array array
  61$hookmanager->initHooks(array('invoicesuppliercard'));
  62
  63$object=new FactureFournisseur($db);
  64
  65
  66
  67/*
  68 * Actions
  69*/
  70
  71// Action clone object
  72if ($action == 'confirm_clone' && $confirm == 'yes')
  73{
  74    if (1==0 && empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"]))
  75    {
  76        $mesg='<div class="error">'.$langs->trans("NoCloneOptionsSpecified").'</div>';
  77    }
  78    else
  79    {
  80        $result=$object->createFromClone($id);
  81        if ($result > 0)
  82        {
  83            header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
  84            exit;
  85        }
  86        else
  87        {
  88            $langs->load("errors");
  89            $mesg='<div class="error">'.$langs->trans($object->error).'</div>';
  90            $action='';
  91        }
  92    }
  93}
  94
  95elseif ($action == 'confirm_valid' && $confirm == 'yes' && $user->rights->fournisseur->facture->valider)
  96{
  97    $idwarehouse=GETPOST('idwarehouse');
  98
  99    $object->fetch($id);
 100    $object->fetch_thirdparty();
 101
 102    // Check parameters
 103    if (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $object->hasProductsOrServices(1))
 104    {
 105        $langs->load("stocks");
 106        if (! $idwarehouse || $idwarehouse == -1)
 107        {
 108            $error++;
 109            $errors[]=$langs->trans('ErrorFieldRequired',$langs->transnoentitiesnoconv("Warehouse"));
 110            $action='';
 111        }
 112    }
 113
 114    if (! $error)
 115    {
 116        $result = $object->validate($user,'',$idwarehouse);
 117        if ($result < 0)
 118        {
 119            $mesg='<div class="error">'.$object->error.'</div>';
 120        }
 121    }
 122}
 123
 124elseif ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer)
 125{
 126    $object->fetch($id);
 127    $object->fetch_thirdparty();
 128    $result=$object->delete($id);
 129    if ($result > 0)
 130    {
 131        header('Location: index.php');
 132        exit;
 133    }
 134    else
 135    {
 136        $mesg='<div class="error">'.$object->error.'</div>';
 137    }
 138}
 139
 140elseif ($action == 'confirm_deleteline' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer)
 141{
 142	$object->fetch($id);
 143	$ret = $object->deleteline(GETPOST('lineid'));
 144	if ($ret > 0)
 145	{
 146		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id);
 147		exit;
 148	}
 149	else
 150	{
 151		$mesg='<div class="error">'.$object->error.'</div>';
 152	}
 153}
 154
 155elseif ($action == 'confirm_paid' && $confirm == 'yes' && $user->rights->fournisseur->facture->creer)
 156{
 157    $object->fetch($id);
 158    $result=$object->set_paid($user);
 159}
 160
 161// Set supplier ref
 162elseif ($action == 'setfacnumber' && $user->rights->fournisseur->facture->creer)
 163{
 164    $object->fetch($id);
 165    $result=$object->set_ref_supplier($user, GETPOST('facnumber'));
 166}
 167
 168// Set label
 169elseif ($action == 'setlabel' && $user->rights->fournisseur->facture->creer)
 170{
 171    $object->fetch($id);
 172    $object->label=$_POST['label'];
 173    $result=$object->update($user);
 174    if ($result < 0) dol_print_error($db);
 175}
 176
 177elseif ($action == 'setdatef' && $user->rights->fournisseur->facture->creer)
 178{
 179    $object->fetch($id);
 180    $object->date=dol_mktime(12,0,0,$_POST['datefmonth'],$_POST['datefday'],$_POST['datefyear']);
 181    if ($object->date_echeance < $object->date) $object->date_echeance=$object->date;
 182    $result=$object->update($user);
 183    if ($result < 0) dol_print_error($db,$object->error);
 184}
 185elseif ($action == 'setdate_lim_reglement' && $user->rights->fournisseur->facture->creer)
 186{
 187    $object->fetch($id);
 188    $object->date_echeance=dol_mktime(12,0,0,$_POST['date_lim_reglementmonth'],$_POST['date_lim_reglementday'],$_POST['date_lim_reglementyear']);
 189    if ($object->date_echeance < $object->date) $object->date_echeance=$object->date;
 190    $result=$object->update($user);
 191    if ($result < 0) dol_print_error($db,$object->error);
 192}
 193elseif ($action == 'setnote_public' && $user->rights->fournisseur->facture->creer)
 194{
 195	$object->fetch($id);
 196	$result=$object->update_note_public(dol_html_entity_decode(GETPOST('note_public'), ENT_QUOTES));
 197	if ($result < 0) dol_print_error($db,$object->error);
 198}
 199elseif ($action == 'setnote' && $user->rights->fournisseur->facture->creer)
 200{
 201	$object->fetch($id);
 202	$result=$object->update_note(dol_html_entity_decode(GETPOST('note'), ENT_QUOTES));
 203	if ($result < 0) dol_print_error($db,$object->error);
 204}
 205
 206// Delete payment
 207elseif ($action == 'deletepaiement')
 208{
 209    $object->fetch($id);
 210    if ($object->statut == 1 && $object->paye == 0 && $user->societe_id == 0)
 211    {
 212        $paiementfourn = new PaiementFourn($db);
 213        $paiementfourn->fetch(GETPOST('paiement_id'));
 214        $result=$paiementfourn->delete();
 215        if ($result < 0) $mesg='<div class="error">'.$paiementfourn->error.'</div>';
 216    }
 217}
 218
 219// Create
 220elseif ($action == 'add' && $user->rights->fournisseur->facture->creer)
 221{
 222    $error=0;
 223
 224    $datefacture=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
 225    $datedue=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']);
 226
 227    if ($datefacture == '')
 228    {
 229        $mesg='<div class="error">'.$langs->trans('ErrorFieldRequired',$langs->transnoentities('DateInvoice')).'</div>';
 230        $action='create';
 231        $_GET['socid']=$_POST['socid'];
 232        $error++;
 233    }
 234    if (! GETPOST('facnumber'))
 235    {
 236        $mesg='<div class="error">'.$langs->trans('ErrorFieldRequired',$langs->transnoentities('RefSupplier')).'</div>';
 237        $action='create';
 238        $_GET['socid']=$_POST['socid'];
 239        $error++;
 240    }
 241
 242    if (! $error)
 243    {
 244        $db->begin();
 245
 246        // Creation facture
 247        $object->ref           = $_POST['facnumber'];
 248        $object->socid         = $_POST['socid'];
 249        $object->libelle       = $_POST['libelle'];
 250        $object->date          = $datefacture;
 251        $object->date_echeance = $datedue;
 252        $object->note_public   = $_POST['note'];
 253
 254        // If creation from another object of another module
 255        if ($_POST['origin'] && $_POST['originid'])
 256        {
 257            // Parse element/subelement (ex: project_task)
 258            $element = $subelement = $_POST['origin'];
 259            /*if (preg_match('/^([^_]+)_([^_]+)/i',$_POST['origin'],$regs))
 260             {
 261            $element = $regs[1];
 262            $subelement = $regs[2];
 263            }*/
 264
 265            // For compatibility
 266            if ($element == 'order')    {
 267                $element = $subelement = 'commande';
 268            }
 269            if ($element == 'propal')   {
 270                $element = 'comm/propal'; $subelement = 'propal';
 271            }
 272            if ($element == 'contract') {
 273                $element = $subelement = 'contrat';
 274            }
 275            if ($element == 'order_supplier') {
 276                $element = 'fourn'; $subelement = 'fournisseur.commande';
 277            }
 278
 279            $object->origin    = $_POST['origin'];
 280            $object->origin_id = $_POST['originid'];
 281
 282            $id = $object->create($user);
 283
 284            // Add lines
 285            if ($id > 0)
 286            {
 287                require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
 288                $classname = ucfirst($subelement);
 289                if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur';
 290                $srcobject = new $classname($db);
 291
 292                $result=$srcobject->fetch($_POST['originid']);
 293                if ($result > 0)
 294                {
 295                    $lines = $srcobject->lines;
 296                    if (empty($lines) && method_exists($srcobject,'fetch_lines'))  $lines = $srcobject->fetch_lines();
 297
 298                    $num=count($lines);
 299                    for ($i = 0; $i < $num; $i++)
 300                    {
 301                        $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
 302                        $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
 303
 304                        // Dates
 305                        // TODO mutualiser
 306                        $date_start=$lines[$i]->date_debut_prevue;
 307                        if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
 308                        if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
 309                        $date_end=$lines[$i]->date_fin_prevue;
 310                        if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
 311                        if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
 312
 313                        $result = $object->addline(
 314                            $desc,
 315                            $lines[$i]->subprice,
 316                            $lines[$i]->tva_tx,
 317                            $lines[$i]->localtax1_tx,
 318                            $lines[$i]->localtax2_tx,
 319                            $lines[$i]->qty,
 320                            $lines[$i]->fk_product,
 321                            $lines[$i]->remise_percent,
 322                            $date_start,
 323                            $date_end,
 324                            0,
 325                            $lines[$i]->info_bits,
 326                            'HT',
 327                            $product_type
 328                        );
 329
 330                        if ($result < 0)
 331                        {
 332                            $error++;
 333                            break;
 334                        }
 335                    }
 336                }
 337                else
 338                {
 339                    $error++;
 340                }
 341            }
 342            else
 343            {
 344                $error++;
 345            }
 346        }
 347        // If some invoice's lines already known
 348        else
 349        {
 350            $id = $object->create($user);
 351            if ($id < 0)
 352            {
 353                $error++;
 354            }
 355
 356            if (! $error)
 357            {
 358                for ($i = 1 ; $i < 9 ; $i++)
 359                {
 360                    $label = $_POST['label'.$i];
 361                    $amountht  = price2num($_POST['amount'.$i]);
 362                    $amountttc = price2num($_POST['amountttc'.$i]);
 363                    $tauxtva   = price2num($_POST['tauxtva'.$i]);
 364                    $qty = $_POST['qty'.$i];
 365                    $fk_product = $_POST['fk_product'.$i];
 366                    if ($label)
 367                    {
 368                        if ($amountht)
 369                        {
 370                            $price_base='HT'; $amount=$amountht;
 371                        }
 372                        else
 373                        {
 374                            $price_base='TTC'; $amount=$amountttc;
 375                        }
 376                        $atleastoneline=1;
 377
 378                        $product=new Product($db);
 379                        $product->fetch($_POST['idprod'.$i]);
 380
 381                        $ret=$object->addline($label, $amount, $tauxtva, $product->localtax1_tx, $product->localtax2_tx, $qty, $fk_product, $remise_percent, '', '', '', 0, $price_base);
 382                        if ($ret < 0) $error++;
 383                    }
 384                }
 385            }
 386        }
 387
 388        if ($error)
 389        {
 390            $langs->load("errors");
 391            $db->rollback();
 392            $mesg='<div class="error">'.$langs->trans($object->error).'</div>';
 393            $action='create';
 394            $_GET['socid']=$_POST['socid'];
 395        }
 396        else
 397        {
 398            $db->commit();
 399            header("Location: ".$_SERVER['PHP_SELF']."?id=".$id);
 400            exit;
 401        }
 402    }
 403}
 404
 405// Modification d'une ligne
 406elseif ($action == 'update_line')
 407{
 408    if (GETPOST('etat') == '1' && ! GETPOST('cancel')) // si on valide la modification
 409    {
 410        $object->fetch($id);
 411        $object->fetch_thirdparty();
 412
 413        if ($_POST['puht'])
 414        {
 415            $pu=$_POST['puht'];
 416            $price_base_type='HT';
 417        }
 418        if ($_POST['puttc'])
 419        {
 420            $pu=$_POST['puttc'];
 421            $price_base_type='TTC';
 422        }
 423
 424        if (GETPOST('idprod'))
 425        {
 426            $prod = new Product($db);
 427            $prod->fetch($_POST['idprod']);
 428            $label = $prod->description;
 429            if (trim($_POST['desc']) != trim($label)) $label=$_POST['desc'];
 430
 431            $type = $prod->type;
 432        }
 433        else
 434        {
 435
 436            $label = $_POST['desc'];
 437            $type = $_POST["type"]?$_POST["type"]:0;
 438
 439        }
 440
 441        $localtax1tx= get_localtax($_POST['tauxtva'], 1, $object->thirdparty);
 442        $localtax2tx= get_localtax($_POST['tauxtva'], 2, $object->thirdparty);
 443        $remise_percent=GETPOST('remise_percent');
 444
 445        $result=$object->updateline(GETPOST('lineid'), $label, $pu, GETPOST('tauxtva'), $localtax1tx, $localtax2tx, GETPOST('qty'), GETPOST('idprod'), $price_base_type, 0, $type, $remise_percent);
 446        if ($result >= 0)
 447        {
 448            unset($_POST['label']);
 449        }
 450    }
 451}
 452
 453elseif ($action == 'addline')
 454{
 455    $ret=$object->fetch($id);
 456    if ($ret < 0)
 457    {
 458        dol_print_error($db,$object->error);
 459        exit;
 460    }
 461    $ret=$object->fetch_thirdparty();
 462
 463    if ($_POST['idprodfournprice'])	// > 0 or -1
 464    {
 465        $product=new Product($db);
 466        $idprod=$product->get_buyprice($_POST['idprodfournprice'], $_POST['qty']);    // Just to see if a price exists for the quantity. Not used to found vat
 467
 468        if ($idprod > 0)
 469        {
 470            $result=$product->fetch($idprod);
 471
 472            // cas special pour lequel on a les meme reference que le fournisseur
 473            // $label = '['.$product->ref.'] - '. $product->libelle;
 474            $label = $product->description;
 475            $label.= $product->description && $_POST['np_desc'] ? "\n" : "";
 476            $label.= $_POST['np_desc'];
 477
 478            $tvatx=get_default_tva($object->thirdparty, $mysoc, $product->id, $_POST['idprodfournprice']);
 479
 480            $localtax1tx= get_localtax($tvatx, 1, $object->thirdparty);
 481            $localtax2tx= get_localtax($tvatx, 2, $object->thirdparty);
 482            $remise_percent=GETPOST('remise_percent');
 483            $type = $product->type;
 484
 485            $result=$object->addline($label, $product->fourn_pu, $tvatx, $localtax1tx, $localtax2tx, $_POST['qty'], $idprod, $remise_percent);
 486
 487        }
 488        if ($idprod == -1)
 489        {
 490            // Quantity too low
 491            $langs->load("errors");
 492            $mesg='<div class="error">'.$langs->trans("ErrorQtyTooLowForThisSupplier").'</div>';
 493        }
 494    }
 495    else
 496    {
 497        $tauxtva = price2num($_POST['tauxtva']);
 498        $localtax1tx= get_localtax($tauxtva, 1, $object->thirdparty);
 499        $localtax2tx= get_localtax($tauxtva, 2, $object->thirdparty);
 500        $remise_percent=GETPOST('remise_percent');
 501
 502        if (! $_POST['dp_desc'])
 503        {
 504            $mesg='<div class="error">'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("Description")).'</div>';
 505        }
 506        else
 507        {
 508            $type = $_POST["type"];
 509            if (! empty($_POST['amount']))
 510            {
 511                $ht = price2num($_POST['amount']);
 512                $price_base_type = 'HT';
 513
 514                //$desc, $pu, $txtva, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0)
 515                $result=$object->addline($_POST['dp_desc'], $ht, $tauxtva, $localtax1tx, $localtax2tx, $_POST['qty'], 0, $remise_percent, $datestart, $dateend, 0, 0, $price_base_type, $type);
 516            }
 517            else
 518            {
 519                $ttc = price2num($_POST['amountttc']);
 520                $ht = $ttc / (1 + ($tauxtva / 100));
 521                $price_base_type = 'HT';
 522                $result=$object->addline($_POST['dp_desc'], $ht, $tauxtva,$localtax1tx, $localtax2tx, $_POST['qty'], 0, $remise_percent, $datestart, $dateend, 0, 0, $price_base_type, $type);
 523            }
 524        }
 525    }
 526
 527    //print "xx".$tva_tx; exit;
 528    if ($result > 0)
 529    {
 530    	// Define output language
 531    	$outputlangs = $langs;
 532        $newlang=GETPOST('lang_id','alpha');
 533        if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$object->client->default_lang;
 534    	if (! empty($newlang))
 535    	{
 536    		$outputlangs = new Translate();
 537    		$outputlangs->setDefaultLang($newlang);
 538    	}
 539        //if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) supplier_invoice_pdf_create($db, $object->id, $object->modelpdf, $outputlangs);
 540
 541        unset($_POST['qty']);
 542        unset($_POST['type']);
 543        unset($_POST['idprodfournprice']);
 544        unset($_POST['remise_percent']);
 545        unset($_POST['dp_desc']);
 546        unset($_POST['np_desc']);
 547        unset($_POST['pu']);
 548        unset($_POST['tva_tx']);
 549        unset($_POST['label']);
 550        unset($localtax1_tx);
 551        unset($localtax2_tx);
 552    }
 553    else if (empty($mesg))
 554    {
 555        $mesg='<div class="error">'.$object->error.'</div>';
 556    }
 557
 558    $action = '';
 559}
 560
 561elseif ($action == 'classin')
 562{
 563    $object->fetch($id);
 564    $result=$object->setProject($_POST['projectid']);
 565}
 566
 567
 568// Set invoice to draft status
 569elseif ($action == 'edit' && $user->rights->fournisseur->facture->creer)
 570{
 571    $object->fetch($id);
 572
 573    $totalpaye = $object->getSommePaiement();
 574    $resteapayer = $object->total_ttc - $totalpaye;
 575
 576    // On verifie si les lignes de factures ont ete exportees en compta et/ou ventilees
 577    //$ventilExportCompta = $object->getVentilExportCompta();
 578
 579    // On verifie si aucun paiement n'a ete effectue
 580    if ($resteapayer == $object->total_ttc	&& $object->paye == 0 && $ventilExportCompta == 0)
 581    {
 582        $object->set_draft($user);
 583
 584        $outputlangs = $langs;
 585        if (! empty($_REQUEST['lang_id']))
 586        {
 587            $outputlangs = new Translate();
 588            $outputlangs->setDefaultLang($_REQUEST['lang_id']);
 589        }
 590        //if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) supplier_invoice_pdf_create($db, $object->id, $object->modelpdf, $outputlangs);
 591    }
 592}
 593
 594// Set invoice to validated/unpaid status
 595elseif ($action == 'reopen' && $user->rights->fournisseur->facture->creer)
 596{
 597    $result = $object->fetch($id);
 598    if ($object->statut == 2
 599    || ($object->statut == 3 && $object->close_code != 'replaced'))
 600    {
 601        $result = $object->set_unpaid($user);
 602        if ($result > 0)
 603        {
 604            header('Location: '.$_SERVER["PHP_SELF"].'?id='.$id);
 605            exit;
 606        }
 607        else
 608        {
 609            $mesg='<div class="error">'.$object->error.'</div>';
 610        }
 611    }
 612}
 613
 614// Add file in email form
 615if (GETPOST('addfile'))
 616{
 617    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 618
 619    // Set tmp user directory TODO Use a dedicated directory for temp mails files
 620    $vardir=$conf->user->dir_output."/".$user->id;
 621    $upload_dir_tmp = $vardir.'/temp';
 622
 623    dol_add_file_process($upload_dir_tmp,0,0);
 624    $action='presend';
 625}
 626
 627// Remove file in email form
 628if (! empty($_POST['removedfile']))
 629{
 630    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 631
 632    // Set tmp user directory
 633    $vardir=$conf->user->dir_output."/".$user->id;
 634    $upload_dir_tmp = $vardir.'/temp';
 635
 636	// TODO Delete only files that was uploaded from email form
 637    dol_remove_file_process($_POST['removedfile'],0);
 638    $action='presend';
 639}
 640
 641// Send mail
 642if ($action == 'send' && ! $_POST['addfile'] && ! $_POST['removedfile'] && ! $_POST['cancel'])
 643{
 644    $langs->load('mails');
 645
 646    $object->fetch($id);
 647    $result=$object->fetch_thirdparty();
 648    if ($result > 0)
 649    {
 650//        $ref = dol_sanitizeFileName($object->ref);
 651//        $file = $conf->fournisseur->facture->dir_output.'/'.get_exdir($object->id,2).$ref.'/'.$ref.'.pdf';
 652
 653//        if (is_readable($file))
 654//        {
 655            if ($_POST['sendto'])
 656            {
 657                // Le destinataire a ete fourni via le champ libre
 658                $sendto = $_POST['sendto'];
 659                $sendtoid = 0;
 660            }
 661            elseif ($_POST['receiver'] != '-1')
 662            {
 663                // Recipient was provided from combo list
 664                if ($_POST['receiver'] == 'thirdparty') // Id of third party
 665                {
 666                    $sendto = $object->client->email;
 667                    $sendtoid = 0;
 668                }
 669                else	// Id du contact
 670                {
 671                    $sendto = $object->client->contact_get_property($_POST['receiver'],'email');
 672                    $sendtoid = $_POST['receiver'];
 673                }
 674            }
 675
 676            if (dol_strlen($sendto))
 677            {
 678                $langs->load("commercial");
 679
 680                $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
 681                $replyto = $_POST['replytoname']. ' <' . $_POST['replytomail'].'>';
 682                $message = $_POST['message'];
 683                $sendtocc = $_POST['sendtocc'];
 684                $deliveryreceipt = $_POST['deliveryreceipt'];
 685
 686                if ($action == 'send')
 687                {
 688                    if (dol_strlen($_POST['subject'])) $subject=$_POST['subject'];
 689                    else $subject = $langs->transnoentities('CustomerOrder').' '.$object->ref;
 690                    $actiontypecode='AC_SUP_ORD';
 691                    $actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto.".\n";
 692                    if ($message)
 693                    {
 694                        $actionmsg.=$langs->transnoentities('MailTopic').": ".$subject."\n";
 695                        $actionmsg.=$langs->transnoentities('TextUsedInTheMessageBody').":\n";
 696                        $actionmsg.=$message;
 697                    }
 698                    $actionmsg2=$langs->transnoentities('Action'.$actiontypecode);
 699                }
 700
 701                // Create form object
 702                include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
 703                $formmail = new FormMail($db);
 704
 705                $attachedfiles=$formmail->get_attached_files();
 706                $filepath = $attachedfiles['paths'];
 707                $filename = $attachedfiles['names'];
 708                $mimetype = $attachedfiles['mimes'];
 709
 710                // Send mail
 711                require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
 712                $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,'',$deliveryreceipt);
 713                if ($mailfile->error)
 714                {
 715                    $mesg='<div class="error">'.$mailfile->error.'</div>';
 716                }
 717                else
 718                {
 719                    $result=$mailfile->sendfile();
 720                    if ($result)
 721                    {
 722                        $mesg=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2));		// Must not contain "
 723
 724                        $error=0;
 725
 726                        // Initialisation donnees
 727                        $object->sendtoid		= $sendtoid;
 728                        $object->actiontypecode	= $actiontypecode;
 729                        $object->actionmsg		= $actionmsg;
 730                        $object->actionmsg2		= $actionmsg2;
 731                        $object->fk_element		= $object->id;
 732                        $object->elementtype	= $object->element;
 733
 734                        // Appel des triggers
 735                        include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
 736                        $interface=new Interfaces($db);
 737                        $result=$interface->run_triggers('BILL_SUPPLIER_SENTBYMAIL',$object,$user,$langs,$conf);
 738                        if ($result < 0) {
 739                            $error++; $this->errors=$interface->errors;
 740                        }
 741                        // Fin appel triggers
 742
 743                        if ($error)
 744                        {
 745                            dol_print_error($db);
 746                        }
 747                        else
 748                        {
 749                            // Redirect here
 750                            // This avoid sending mail twice if going out and then back to page
 751                            header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'&mesg='.urlencode($mesg));
 752                            exit;
 753                        }
 754                    }
 755                    else
 756                    {
 757                        $langs->load("other");
 758                        $mesg='<div class="error">';
 759                        if ($mailfile->error)
 760                        {
 761                            $mesg.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
 762                            $mesg.='<br>'.$mailfile->error;
 763                        }
 764                        else
 765                        {
 766                            $mesg.='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
 767                        }
 768                        $mesg.='</div>';
 769                    }
 770                }
 771            }
 772
 773            else
 774            {
 775                $langs->load("other");
 776                $mesg='<div class="error">'.$langs->trans('ErrorMailRecipientIsEmpty').'</div>';
 777                dol_syslog('Recipient email is empty');
 778            }
 779/*        }
 780        else
 781        {
 782            $langs->load("errors");
 783            $mesg='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div>';
 784            dol_syslog('Failed to read file: '.$file);
 785        }*/
 786    }
 787    else
 788    {
 789        $langs->load("other");
 790        $mesg='<div class="error">'.$langs->trans('ErrorFailedToReadEntity',$langs->trans("Invoice")).'</div>';
 791        dol_syslog('Unable to read data from the invoice. The invoice file has perhaps not been generated.');
 792    }
 793
 794    //$action = 'presend';
 795}
 796
 797// Build document
 798elseif ($action	== 'builddoc')
 799{
 800    // Save modele used
 801    $object->fetch($id);
 802    $object->fetch_thirdparty();
 803    if ($_REQUEST['model'])
 804    {
 805        $object->setDocModel($user, $_REQUEST['model']);
 806    }
 807
 808    $outputlangs = $langs;
 809    if (! empty($_REQUEST['lang_id']))
 810    {
 811        $outputlangs = new Translate();
 812        $outputlangs->setDefaultLang($_REQUEST['lang_id']);
 813    }
 814    $result=supplier_invoice_pdf_create($db,$object,$object->modelpdf,$outputlangs);
 815    if ($result	<= 0)
 816    {
 817        dol_print_error($db,$result);
 818        exit;
 819    }
 820    else
 821    {
 822        header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(empty($conf->global->MAIN_JUMP_TAG)?'':'#builddoc'));
 823        exit;
 824    }
 825}
 826
 827// Delete file in doc form
 828elseif ($action == 'remove_file')
 829{
 830    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 831
 832    if ($object->fetch($id))
 833    {
 834    	$object->fetch_thirdparty();
 835        $upload_dir =	$conf->fournisseur->facture->dir_output . "/";
 836        $file =	$upload_dir	. '/' .	GETPOST('file');
 837        $ret=dol_delete_file($file,0,0,0,$object);
 838        if ($ret) setEventMessage($langs->trans("FileWasRemoved", GETPOST('urlfile')));
 839        else setEventMessage($langs->trans("ErrorFailToDeleteFile", GETPOST('urlfile')), 'errors');
 840    }
 841}
 842
 843if (! empty($conf->global->MAIN_DISABLE_CONTACTS_TAB) && $user->rights->fournisseur->facture->creer)
 844{
 845	if ($action == 'addcontact')
 846	{
 847		$result = $object->fetch($id);
 848
 849		if ($result > 0 && $id > 0)
 850		{
 851			$contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid'));
 852			$result = $result = $object->add_contact($contactid, $_POST["type"], $_POST["source"]);
 853		}
 854
 855		if ($result >= 0)
 856		{
 857			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 858			exit;
 859		}
 860		else
 861		{
 862			if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS')
 863			{
 864				$langs->load("errors");
 865				$mesg = '<div class="error">'.$langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType").'</div>';
 866			}
 867			else
 868			{
 869				$mesg = '<div class="error">'.$object->error.'</div>';
 870			}
 871		}
 872	}
 873
 874	// bascule du statut d'un contact
 875	else if ($action == 'swapstatut')
 876	{
 877		if ($object->fetch($id))
 878		{
 879			$result=$object->swapContactStatus(GETPOST('ligne'));
 880		}
 881		else
 882		{
 883			dol_print_error($db);
 884		}
 885	}
 886
 887	// Efface un contact
 888	else if ($action == 'deletecontact')
 889	{
 890		$object->fetch($id);
 891		$result = $object->delete_contact($_GET["lineid"]);
 892
 893		if ($result >= 0)
 894		{
 895			header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
 896			exit;
 897		}
 898		else {
 899			dol_print_error($db);
 900		}
 901	}
 902}
 903
 904
 905/*
 906 *	View
 907 */
 908
 909$form = new Form($db);
 910$formfile = new FormFile($db);
 911$bankaccountstatic=new Account($db);
 912
 913llxHeader('','','');
 914
 915// Mode creation
 916if ($action == 'create')
 917{
 918    print_fiche_titre($langs->trans('NewBill'));
 919
 920    dol_htmloutput_mesg($mesg);
 921
 922    $societe='';
 923    if ($_GET['socid'])
 924    {
 925        $societe=new Societe($db);
 926        $societe->fetch($_GET['socid']);
 927    }
 928
 929    if (GETPOST('origin') && GETPOST('originid'))
 930    {
 931        // Parse element/subelement (ex: project_task)
 932        $element = $subelement = GETPOST('origin');
 933
 934        if ($element == 'project')
 935        {
 936            $projectid=GETPOST('originid');
 937        }
 938        else if (in_array($element,array('order_supplier')))
 939        {
 940            // For compatibility
 941            if ($element == 'order')    {
 942                $element = $subelement = 'commande';
 943            }
 944            if ($element == 'propal')   {
 945                dol_htmloutput_errors('',$errors);
 946                $element = 'comm/propal'; $subelement = 'propal';
 947            }
 948            if ($element == 'contract') {
 949                $element = $subelement = 'contrat';
 950            }
 951            if ($element == 'order_supplier') {
 952                $element = 'fourn'; $subelement = 'fournisseur.commande';
 953            }
 954
 955            require_once DOL_DOCUMENT_ROOT.'/'.$element.'/class/'.$subelement.'.class.php';
 956            $classname = ucfirst($subelement);
 957            if ($classname == 'Fournisseur.commande') $classname='CommandeFournisseur';
 958            $objectsrc = new $classname($db);
 959            $objectsrc->fetch(GETPOST('originid'));
 960            $objectsrc->fetch_thirdparty();
 961
 962            $projectid			= (!empty($objectsrc->fk_project)?$object->fk_project:'');
 963            //$ref_client			= (!empty($objectsrc->ref_client)?$object->ref_client:'');
 964
 965            $soc = $objectsrc->client;
 966            $cond_reglement_id 	= (!empty($objectsrc->cond_reglement_id)?$objectsrc->cond_reglement_id:(!empty($soc->cond_reglement_id)?$soc->cond_reglement_id:1));
 967            $mode_reglement_id 	= (!empty($objectsrc->mode_reglement_id)?$objectsrc->mode_reglement_id:(!empty($soc->mode_reglement_id)?$soc->mode_reglement_id:0));
 968            $remise_percent 	= (!empty($objectsrc->remise_percent)?$objectsrc->remise_percent:(!empty($soc->remise_percent)?$soc->remise_percent:0));
 969            $remise_absolue 	= (!empty($objectsrc->remise_absolue)?$objectsrc->remise_absolue:(!empty($soc->remise_absolue)?$soc->remise_absolue:0));
 970            $dateinvoice		= empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0;
 971
 972            $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
 973            $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0):$datetmp);
 974            $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']);
 975            $datedue=($datetmp==''?-1:$datetmp);
 976        }
 977    }
 978    else
 979    {
 980        $datetmp=dol_mktime(12,0,0,$_POST['remonth'],$_POST['reday'],$_POST['reyear']);
 981        $dateinvoice=($datetmp==''?(empty($conf->global->MAIN_AUTOFILL_DATE)?-1:0):$datetmp);
 982        $datetmp=dol_mktime(12,0,0,$_POST['echmonth'],$_POST['echday'],$_POST['echyear']);
 983        $datedue=($datetmp==''?-1:$datetmp);
 984    }
 985
 986    print '<form name="add" action="'.$_SERVER["PHP_SELF"].'" method="post">';
 987    print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 988    print '<input type="hidden" name="action" value="add">';
 989    print '<input type="hidden" name="origin" value="'.GETPOST('origin').'">';
 990    print '<input type="hidden" name="originid" value="'.GETPOST('originid').'">';
 991    print '<table class="border" width="100%">';
 992
 993    // Ref
 994    print '<tr><td>'.$langs->trans('Ref').'</td><td>'.$langs->trans('Draft').'</td></tr>';
 995
 996    // Third party
 997    print '<tr><td class="fieldrequired">'.$langs->trans('Supplier').'</td>';
 998    print '<td>';
 999
1000    if ($_REQUEST['socid'] > 0)
1001    {
1002        print $societe->getNomUrl(1);
1003        print '<input type="hidden" name="socid" value="'.$_GET['socid'].'">';
1004    }
1005    else
1006    {
1007        print $form->select_company((empty($_GET['socid'])?'':$_GET['socid']),'socid','s.fournisseur = 1',1);
1008    }
1009    print '</td>';
1010
1011    // Ref supplier
1012    print '<tr><td class="fieldrequired">'.$langs->trans('RefSupplier').'</td><td><input name="facnumber" value="'.(isset($_POST['facnumber'])?$_POST['facnumber']:$fac_ori->ref).'" type="text"></td>';
1013    print '</tr>';
1014
1015    print '<tr><td valign="top" class="fieldrequired">'.$langs->trans('Type').'</td><td colspan="2">';
1016    print '<table class="nobordernopadding">'."\n";
1017
1018    // Standard invoice
1019    print '<tr height="18"><td width="16px" valign="middle">';
1020    print '<input type="radio" name="type" value="0"'.($_POST['type']==0?' checked="checked"':'').'>';
1021    print '</td><td valign="middle">';
1022    $desc=$form->textwithpicto($langs->trans("InvoiceStandardAsk"),$langs->transnoentities("InvoiceStandardDesc"),1);
1023    print $desc;
1024    print '</td></tr>'."\n";
1025
1026    /*
1027     // Deposit
1028    print '<tr height="18"><td width="16px" valign="middle">';
1029    print '<input type="radio" name="type" value="3"'.($_POST['type']==3?' checked="checked"':'').'>';
1030    print '</td><td valign="middle">';
1031    $desc=$form->textwithpicto($langs->trans("InvoiceDeposit"),$langs->transnoentities("InvoiceDepositDesc"),1);
1032    print $desc;
1033    print '</td></tr>'."\n";
1034
1035    // Proforma
1036    if (! empty($conf->global->FACTURE_USE_PROFORMAT))
1037    {
1038    print '<tr height="18"><td width="16px" valign="middle">';
1039    print '<input type="radio" name="type" value="4"'.($_POST['type']==4?' checked="checked"':'').'>';
1040    print '</td><td valign="middle">';
1041    $desc=$form->textwithpicto($langs->trans("InvoiceProForma"),$langs->transnoentities("InvoiceProFormaDesc"),1);
1042    print $desc;
1043    print '</td></tr>'."\n";
1044    }
1045
1046    // Replacement
1047    print '<tr height="18"><td valign="middle">';
1048    print '<input type="radio" name="type" value="1"'.($_POST['type']==1?' checked="checked"':'');
1049    if (! $options) print ' disabled="disabled"';
1050    print '>';
1051    print '</td><td valign="middle">';
1052    $text=$langs->trans("InvoiceReplacementAsk").' ';
1053    $text.='<select class="flat" name="fac_replacement"';
1054    if (! $options) $text.=' disabled="disabled"';
1055    $text.='>';
1056    if ($options)
1057    {
1058    $text.='<option value="-1">&nbsp;</option>';
1059    $text.=$options;
1060    }
1061    else
1062    {
1063    $text.='<option value="-1">'.$langs->trans("NoReplacableInvoice").'</option>';
1064    }
1065    $text.='</select>';
1066    $desc=$form->textwithpicto($text,$langs->transnoentities("InvoiceReplacementDesc"),1);
1067    print $desc;
1068    print '</td></tr>';
1069
1070    // Credit note
1071    print '<tr height="18"><td valign="middle">';
1072    print '<input type="radio" name="type" value="2"'.($_POST['type']==2?' checked=true':'');
1073    if (! $optionsav) print ' disabled="disabled"';
1074    print '>';
1075    print '</td><td valign="middle">';
1076    $text=$langs->transnoentities("InvoiceAvoirAsk").' ';
1077    //	$text.='<input type="text" value="">';
1078    $text.='<select class="flat" name="fac_avoir"';
1079    if (! $optionsav) $text.=' disabled="disabled"';
1080    $text.='>';
1081    if ($optionsav)
1082    {
1083    $text.='<option value="-1">&nbsp;</option>';
1084    $text.=$optionsav;
1085    }
1086    else
1087    {
1088    $text.='<option value="-1">'.$langs->trans("NoInvoiceToCorrect").'</option>';
1089    }
1090    $text.='</select>';
1091    $desc=$form->textwithpicto($text,$langs->transnoentities("InvoiceAvoirDesc"),1);
1092    print $desc;
1093    print '</td></tr>'."\n";
1094    */
1095    print '</table>';
1096    print '</td></tr>';
1097
1098    // Label
1099    print '<tr><td>'.$langs->trans('Label').'</td><td><input size="30" name="libelle" value="'.(isset($_POST['libelle'])?$_POST['libelle']:$fac_ori->libelle).'" type="text"></td></tr>';
1100
1101    // Date invoice
1102    print '<tr><td class="fieldrequired">'.$langs->trans('DateInvoice').'</td><td>';
1103    $form->select_date($dateinvoice,'','','','',"add",1,1);
1104    print '</td></tr>';
1105
1106    // Due date
1107    print '<tr><td>'.$langs->trans('DateMaxPayment').'</td><td>';
1108    $form->select_date($datedue,'ech','','','',"add",1,1);
1109    print '</td></tr>';
1110
1111    print '<tr><td>'.$langs->trans('NotePublic').'</td>';
1112    print '<td><textarea name="note" wrap="soft" cols="60" rows="'.ROWS_5.'"></textarea></td>';
1113    print '</tr>';
1114
1115    if (is_object($objectsrc))
1116    {
1117        print "\n<!-- ".$classname." info -->";
1118        print "\n";
1119        print '<input type="hidden" name="amount"         value="'.$objectsrc->total_ht.'">'."\n";
1120        print '<input type="hidden" name="total"          value="'.$objectsrc->total_ttc.'">'."\n";
1121        print '<input type="hidden" name="tva"            value="'.$objectsrc->total_tva.'">'."\n";
1122        print '<input type="hidden" name="origin"         value="'.$objectsrc->element.'">';
1123        print '<input type="hidden" name="originid"       value="'.$objectsrc->id.'">';
1124
1125        $txt=$langs->trans($classname);
1126        if ($classname=='CommandeFournisseur') $txt=$langs->trans("SupplierOrder");
1127        print '<tr><td>'.$txt.'</td><td colspan="2">'.$objectsrc->getNomUrl(1).'</td></tr>';
1128        print '<tr><td>'.$langs->trans('TotalHT').'</td><td colspan="2">'.price($objectsrc->total_ht).'</td></tr>';
1129        print '<tr><td>'.$langs->trans('TotalVAT').'</td><td colspan="2">'.price($objectsrc->total_tva)."</td></tr>";
1130        if ($mysoc->country_code=='ES')
1131        {
1132            if ($mysoc->localtax1_assuj=="1") //Localtax1 RE
1133            {
1134                print '<tr><td>'.$langs->transcountry("AmountLT1",$mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax1)."</td></tr>";
1135            }
1136
1137            if ($mysoc->localtax2_assuj=="1") //Localtax2 IRPF
1138            {
1139                print '<tr><td>'.$langs->transcountry("AmountLT2",$mysoc->country_code).'</td><td colspan="2">'.price($objectsrc->total_localtax2)."</td></tr>";
1140            }
1141        }
1142        print '<tr><td>'.$langs->trans('TotalTTC').'</td><td colspan="2">'.price($objectsrc->total_ttc)."</td></tr>";
1143    }
1144    else
1145    {
1146    	// TODO more bugs
1147        if (1==2 && ! empty($conf->global->PRODUCT_SHOW_WHEN_CREATE))
1148        {
1149            print '<tr class="liste_titre">';
1150            print '<td>&nbsp;</td><td>'.$langs->trans('Label').'</td>';
1151            print '<td align="right">'.$langs->trans('PriceUHT').'</td>';
1152            print '<td align="right">'.$langs->trans('VAT').'</td>';
1153            print '<td align="right">'.$langs->trans('Qty').'</td>';
1154            print '<td align="right">'.$langs->trans('PriceUTTC').'</td>';
1155            print '</tr>';
1156
1157            for ($i = 1 ; $i < 9 ; $i++)
1158            {
1159                $value_qty = '1';
1160                $value_tauxtva = '';
1161                print '<tr><td>'.$i.'</td>';
1162                print '<td><input size="50" name="label'.$i.'" value="'.$value_label.'" type="text"></td>';
1163                print '<td align="right"><input type="text" size="8" name="amount'.$i.'" value="'.$value_pu.'"></td>';
1164                print '<td align="right">';
1165                print $form->load_tva('tauxtva'.$i,$value_tauxtva,$societe,$mysoc);
1166                print '</td>';
1167                print '<td align="right"><input type="text" size="3" name="qty'.$i.'" value="'.$value_qty.'"></td>';
1168                print '<td align="right"><input type="text" size="8" name="amountttc'.$i.'" value=""></td></tr>';
1169            }
1170        }
1171    }
1172
1173    // Other options
1174    $parameters=array();
1175    $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
1176
1177    // Bouton "Create Draft"
1178    print "</table>\n";
1179
1180    print '<br><center><input type="submit" class="button" name="bouton" value="'.$langs->trans('CreateDraft').'"></center>';
1181
1182    print "</form>\n";
1183
1184
1185    // Show origin lines
1186    if (is_object($objectsrc))
1187    {
1188        print '<br>';
1189
1190        $title=$langs->trans('ProductsAndServices');
1191        print_titre($title);
1192
1193        print '<table class="noborder" width="100%">';
1194
1195        $objectsrc->printOriginLinesList();
1196
1197        print '</table>';
1198    }
1199}
1200else
1201{
1202    if ($id > 0)
1203    {
1204        /* *************************************************************************** */
1205        /*                                                                             */
1206        /* Fiche en mode visu ou edition                                               */
1207        /*                                                                             */
1208        /* *************************************************************************** */
1209
1210        $now=dol_now();
1211
1212        $productstatic = new Product($db);
1213
1214        $object->fetch($id);
1215
1216        $societe = new Fournisseur($db);
1217        $societe->fetch($object->socid);
1218
1219        /*
1220         *	View card
1221        */
1222        $head = facturefourn_prepare_head($object);
1223        $titre=$langs->trans('SupplierInvoice');
1224        dol_fiche_head($head, 'card', $titre, 0, 'bill');
1225
1226        dol_htmloutput_mesg($mesg);
1227        dol_htmloutput_errors('',$errors);
1228
1229        // Confirmation de la suppression d'une ligne produit
1230        if ($action == 'confirm_delete_line')
1231        {
1232            $ret=$form->form_confirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$_GET["lineid"], $langs->trans('DeleteProductLine'), $langs->trans('ConfirmDeleteProductLine'), 'confirm_deleteline', '', 1, 1);
1233            if ($ret == 'html') print '<br>';
1234        }
1235
1236        // Clone confirmation
1237        if ($action == 'clone')
1238        {
1239            // Create an array for form
1240            $formquestion=array(
1241            //'text' => $langs->trans("ConfirmClone"),
1242            //array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1)
1243            );
1244            // Paiement incomplet. On demande si motif = escompte ou autre
1245            $ret=$form->form_confirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneInvoice'),$langs->trans('ConfirmCloneInvoice',$object->ref),'confirm_clone',$formquestion,'yes', 1);
1246            if ($ret == 'html') print '<br>';
1247        }
1248
1249        // Confirmation de la validation
1250        if ($action == 'valid')
1251        {
1252            $formquestion=array();
1253            if (! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) && $object->hasProductsOrServices(1))
1254            {
1255                $langs->load("stocks");
1256                require_once DOL_DOCUMENT_ROOT.'/product/class/html.formproduct.class.php';
1257                $formproduct=new FormProduct($db);
1258                $formquestion=array(
1259                //'text' => $langs->trans("ConfirmClone"),
1260                //array('type' => 'checkbox', 'name' => 'clone_content',   'label' => $langs->trans("CloneMainAttributes"),   'value' => 1),
1261                //array('type' => 'checkbox', 'name' => 'update_prices',   'label' => $langs->trans("PuttingPricesUpToDate"),   'value' => 1),
1262                array('type' => 'other', 'name' => 'idwarehouse',   'label' => $langs->trans("SelectWarehouseForStockDecrease"),   'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse'),'idwarehouse','',1)));
1263            }
1264
1265            $ret=$form->form_confirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ValidateBill'), $langs->trans('ConfirmValidateBill', $object->ref), 'confirm_valid', $formquestion, 1, 1, 240);
1266            if ($ret == 'html') print '<br>';
1267        }
1268
1269        // Confirmation set paid
1270        if ($action == 'paid')
1271        {
1272            $ret=$form->form_confirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ClassifyPaid'), $langs->trans('ConfirmClassifyPaidBill', $object->ref), 'confirm_paid', '', 0, 1);
1273            if ($ret == 'html') print '<br>';
1274        }
1275
1276        // Confirmation de la suppression de la facture fournisseur
1277        if ($action == 'delete')
1278        {
1279            $ret=$form->form_confirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteBill'), $langs->trans('ConfirmDeleteBill'), 'confirm_delete', '', 0, 1);
1280            if ($ret == 'html') print '<br>';
1281        }
1282
1283
1284        /**
1285         * 	Invoice
1286         */
1287        print '<table class="border" width="100%">';
1288
1289        $linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/index.php'.(! empty($socid)?'?socid='.$socid:'').'">'.$langs->trans("BackToList").'</a>';
1290
1291        // Ref
1292        print '<tr><td nowrap="nowrap" width="20%">'.$langs->trans("Ref").'</td><td colspan="4">';
1293        print $form->showrefnav($object, 'id', $linkback, 1, 'rowid', 'ref');
1294        print '</td>';
1295        print "</tr>\n";
1296
1297        // Ref supplier
1298        print '<tr><td>'.$form->editfieldkey("RefSupplier",'facnumber',$object->ref_supplier,$object,($object->statut<2 && $user->rights->fournisseur->facture->creer)).'</td><td colspan="4">';
1299        print $form->editfieldval("RefSupplier",'facnumber',$object->ref_supplier,$object,($object->statut<2 && $user->rights->fournisseur->facture->creer));
1300        print '</td></tr>';
1301
1302        // Third party
1303        print '<tr><td>'.$langs->trans('Supplier').'</td><td colspan="4">'.$societe->getNomUrl(1);
1304        print ' &nbsp; (<a href="'.DOL_URL_ROOT.'/fourn/facture/index.php?socid='.$object->socid.'">'.$langs->trans('OtherBills').'</a>)</td>';
1305        print '</tr>';
1306
1307        // Type
1308        print '<tr><td>'.$langs->trans('Type').'</td><td colspan="4">';
1309        print $object->getLibType();
1310        if ($object->type == 1)
1311        {
1312            $facreplaced=new FactureFournisseur($db);
1313            $facreplaced->fetch($object->fk_facture_source);
1314            print ' ('.$langs->transnoentities("ReplaceInvoice",$facreplaced->getNomUrl(1)).')';
1315        }
1316        if ($object->type == 2)
1317        {
1318            $facusing=new FactureFournisseur($db);
1319            $facusing->fetch($object->fk_facture_source);
1320            print ' ('.$langs->transnoentities("CorrectInvoice",$facusing->getNomUrl(1)).')';
1321        }
1322
1323        $facidavoir=$object->getListIdAvoirFromInvoice();
1324        if (count($facidavoir) > 0)
1325        {
1326            print ' ('.$langs->transnoentities("InvoiceHasAvoir");
1327            $i=0;
1328            foreach($facidavoir as $id)
1329            {
1330                if ($i==0) print ' ';
1331                else print ',';
1332                $facavoir=new FactureFournisseur($db);
1333                $facavoir->fetch($id);
1334                print $facavoir->getNomUrl(1);
1335            }
1336            print ')';
1337        }
1338        if (isset($facidnext) && $facidnext > 0)
1339        {
1340            $facthatreplace=new FactureFournisseur($db);
1341            $facthatreplace->fetch($facidnext);
1342            print ' ('.$langs->transnoentities("ReplacedByInvoice",$facthatreplace->getNomUrl(1)).')';
1343        }
1344        print '</td></tr>';
1345
1346        // Label
1347        print '<tr><td>'.$form->editfieldkey("Label",'label',$object->label,$object,($object->statut<2 && $user->rights->fournisseur->facture->creer)).'</td>';
1348        print '<td colspan="3">'.$form->editfieldval("Label",'label',$object->label,$object,($object->statut<2 && $user->rights->fournisseur->facture->creer)).'</td>';
1349
1350        /*
1351         * Li…

Large files files are truncated, but you can click here to view the full file