Patch aus Bug 1343: csv in ../users speichern
[kivitendo-erp.git] / lxo-import / parts_import.php
1 <?
2 //Henry Margies <h.margies@maxina.de>
3 //Holger Lindemann <hli@lx-system.de>
4
5 /**
6  * Returns ID of a partgroup (or adds a new partgroup entry)
7  * \db is the database
8  * \value is the partgroup name
9  * \add if true and partgroup does not exist yet, we will add it automatically
10  * \returns partgroup id or "" in case of an error
11  */
12 function getPartsgroupId($db, $value, $add) {
13     $sql="select id from partsgroup where partsgroup = '$value'";
14     $rs=$db->getAll($sql);
15     if (empty($rs[0]["id"]) && $add) {
16         $sql="insert into partsgroup (partsgroup) values ('$value')";
17         $rc=$db->query($sql);
18         if (!$rc)
19             return "";
20         return getPartsgroupId($db, $value, 0);
21     }
22     return $rs[0]["id"];
23 }
24 function insertParts($db,$insert,$show,$data) {
25     if ($show) {
26         show('<tr>',false);
27         show($data["partnumber"]);        show($data["lastcost"]);          show($data["sellprice"]);
28         show($data["description"]);       show(substr($data["notes"],0,25));show($data["ean"]);
29         show($data["weight"]);            show($data["image"]);             show($data["partsgroup_id"]);
30         show($data["buchungsgruppen_id"]);show($data["income_accno"]);      show($data["expense_accno"]);
31         show($data["inventory_accno"]);   show($data["microfiche"]);        show($data["drawing"]);
32         show($data["rop"]);               show($data["assembly"]);          show($data["makemodel"]);
33         show($data["shop"]);
34     }
35     /*foreach ($data as $key=>$val) {
36         echo $key.":".gettype($val).":".gettype($data[$key]).":".$val."<br>";
37     }*/
38     if ($insert) {
39         $sqlIa  = 'INSERT INTO parts (';
40         $sqlIa .= 'partnumber,description,notes,ean,unit,';
41         $sqlIa .= 'weight,image,sellprice,lastcost,partsgroup_id,';
42         $sqlIa .= 'buchungsgruppen_id,income_accno_id,expense_accno_id,inventory_accno_id,';
43         $sqlIa .= 'microfiche,drawing,rop,assembly,shop,makemodel,import) ';
44         $sqlIa .= 'VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)';
45         $data["import"]=time();
46         $rc=$db->execute($sqlIa,$data);
47     } else {
48         $rc = true;
49     }
50     if ($show) {
51         if ($rc) 
52             show('<b>ok</b>');
53         else
54             show('<font color="red">error</font>');
55         show('</tr>'."\n",false);
56     }
57     return $rc;
58 }
59 function updPrice($db,$insert,$show,$partnumber,$lastcost,$sellprice,$shop) {
60     if ($show) {
61         show('<tr>',false);
62         show($partnumber); show($lastcost); show($sellprice);
63     }
64     if ($insert) {
65         $sqlPr  = 'UPDATE PARTS SET ';
66         $sqlPr .= 'sellprice = ?, lastcost = ?, shop = ? ';
67         $sqlPr .= 'WHERE  partnumber = ?';
68         $rc=$db->execute($sqlPr,array("sellprice"=>$sellprice,"lastcost"=>$lastcost,"shop"=>$shop,"partnumber"=>$partnumber));
69     } else {
70         $rc = true;
71     }
72     if ($show) {
73         if ($rc) 
74             show('<b>ok</b>');
75         else
76             show('<font color="red">error</font>');
77         show('</tr>'."\n",false);
78     }
79     return $rc;
80 }
81 function updParts($db,$insert,$show,$partnumber,$lastcost,$sellprice,
82                     $description,$notes,$ean,$weight,$image,
83                     $partsgroup_id, $shop) {
84     if ($show) {
85         show('<tr>',false);
86         show($partnumber);      show($lastcost);          show($sellprice);
87         show($description);     show(substr($notes,0,25));show($ean);
88         show($weight);          show($image);             show($partsgroup_id);
89     }
90     if ($insert) {
91         $sqlUa  = 'UPDATE PARTS SET ';
92         $sqlUa .= 'description = ?, notes = ?, ean = ?, weight = ?, image = ?, ';
93         $sqlUa .= 'sellprice = ?, lastcost = ?, partsgroup_id = ?, shop = ? ';
94         $sqlUa .= 'WHERE  partnumber = ?';
95         $rc=$db->execute($sqlUa,array($description,$notes,$ean,$weight,$image,
96                                 $sellprice,$lastcost,$partsgroup_id,$shop,$partnumber));
97     } else {
98         $rc = true;
99     }
100     if ($show) {
101         if ($rc) 
102             show('<b>ok</b>');
103         else
104             show('<font color="red">error</font>');
105         show('</tr>'."\n",false);
106     }
107     return $rc;
108 }
109
110 function getMakemodel($db,$check,$hersteller,$model,$partsid,$add=true) {
111     $sql="select * from makemodel where make = $hersteller and model = '$model' and parts_id = $partsid";
112     $rs=$db->getAll($sql);
113     if (empty($rs[0]["id"]) && $add) {
114         $sql="insert into makemodel (parts_id,make,model) values ($partsid,'$hersteller','$model')";    
115         $rc=$db->query($sql);
116     }
117 }
118
119 function getAccnoId($db, $accno) {
120     $sql = "select id from chart where accno='$accno'";
121     $rs=$db->getAll($sql);
122     return $rs[0]["id"];
123 }
124
125 function getPartsid($db,$number) {
126     $sql = "select id from parts where partnumber = '$number'";
127     $rs=$db->getAll($sql);
128     if ($rs[0]["id"]>0) {
129         return $rs[0]["id"];
130     } else { 
131         return false;
132     }
133 }
134
135 function newPartNumber($db,$check) {
136     if ($check) return "check";
137     $rc=$db->query("BEGIN");
138     $sql = "select  articlenumber from defaults";
139     $rs=$db->getAll($sql);
140     if ($rs[0]["articlenumber"]) {
141         preg_match("/([^0-9]+)?([0-9]+)([^0-9]+)?/", $rs[0]["articlenumber"] , $regs);
142         print_r($regs);
143         $number=$regs[1].($regs[2]+1).$regs[3];
144     }
145     $sql = "update defaults set articlenumber = '$number'";
146     $rc=$db->query($sql);
147     $rc=$db->query("COMMIT");
148     //Prüfen ob die Nummer nicht doch schon vergeben ist.
149     $sql = "select * from parts where partnumber = '$number'";
150     $rs=$db->getAll($sql);
151     if ($rs[0]["id"]>0) return "";
152     return $number;
153 }
154
155 function getBuchungsgruppe($db, $income, $expense) {
156     $income_id = getAccnoId($db, $income);
157     $expense_id = getAccnoId($db, $expense);
158     $sql  = "select id from buchungsgruppen where ";
159     $sql .= "income_accno_id_0 = $income and ";
160     $sql .= "expense_accno_id_0 = $expense ";
161     $sql .= "order by sortkey";
162     $rs=$db->getAll($sql);
163     return $rs[0]["id"];
164 }
165
166 function getFromBG($db, $bg_id, $name) {
167     $sql  = "select $name from buchungsgruppen where id='$bg_id'";
168     $rs=$db->getAll($sql);
169     return 1*$rs[0][$name];
170 }
171
172 function existUnit($db, $value) {
173     $sql="select name from units where name = '$value'";
174     $rs=$db->getAll($sql);
175     if (empty($rs[0]["name"]))
176         return FALSE;
177     return TRUE;
178 }
179
180 function show($things,$td=true) {
181         if ($td) 
182             echo '<td>'.$things.'</td>';
183         else
184             echo $things;
185 }
186
187 function getStdUnit($db,$type) {
188     $sql="select * from units where type='$type' order by sortkey limit 1";
189     $rs=$db->getAll($sql);
190     return $rs[0]["name"];
191 }
192
193 function import_parts($db, $file, $trenner, $trennzeichen, $fields, $check, $insert, $show ,$maske) {
194     $precision=$maske["precision"];
195     $quotation=$maske["quotation"];
196     $quottype=$maske["quottype"];
197     $shop=$maske["shop"];
198     $wgtrenner=$maske["wgtrenner"];
199     $Update=($maske["update"]=="U")?true:false;
200     $UpdText=($maske["TextUpd"]=="1")?true:false;
201
202     $stdunitW=getStdUnit($db,"dimension");
203     $stdunitD=getStdUnit($db,"service");
204     if ($quottype=="P") $quotation=($quotation+100)/100;
205
206     if ($show && !$insert) show("<b>Testimport</b>",false);
207     if ($show) show("<table border='1'>\n",false);
208
209     /* field description */
210     $parts_fld = array_keys($fields);
211
212     /* open csv file */
213     $f=fopen("$file","r");
214     
215     /*
216      * read first line with table descriptions
217      */
218     if ($show) {
219         show('<tr>',false);
220         show("partnumber"); show("lastcost");   show("sellprice");
221         show("description");show("notes");      show("ean");
222         show("weight");     show("image");      show("partsgroup_id");
223         show("bg");         show("income_accno"); show("expense_accno");
224         show("inventory_accno"); show("microfiche");show("drawing");show("rop");
225         show("assembly");show("makemodel");show("shop");  show("");
226         show("</tr>\n",false);
227     }
228
229     if ($trenner=="other") $trenner=trim($trennzeichen);
230     if (substr($trenner,0,1)=="#") if (strlen($trenner)>1) $trenner=chr(substr($trenner,1));
231    
232     // Erst einmal die erste Zeile mit den Feldbezeichnungen einlesen. 
233     $infld=fgetcsv($f,1200,$trenner);
234     $p=0;
235     foreach ($infld as $fld) {
236         $fld = strtolower(trim(strtr($fld,array("\""=>"","'"=>""))));
237         if (in_array($fld,$parts_fld)) {
238             $fldpos[$fld]=$p;
239         }
240         $p++;
241     }
242     $i=0;
243     $u=0;
244     $m=0;        /* line */
245     $errors=0;    /* number of errors detected */
246     $income_accno = "";
247     $expense_accno = "";
248     $assembly = 'f';
249
250     while ( ($zeile=fgetcsv($f,120000,$trenner)) != FALSE) {
251         $m++;    /* increase line */
252         $unit=false;
253    
254         unset($pgroup); 
255         unset($notes); 
256         unset($rop);
257         unset($weight);
258         unset($inventory_accno);
259         unset($income_accno);
260         unset($expense_accno);
261         unset($model);
262         unset($makemodel);
263         unset($hersteller);
264
265         /* VK-Preis bilden */
266         $sellprice = str_replace(",", ".", $zeile[$fldpos["sellprice"]]);
267         $lastcost = str_replace(",", ".", $zeile[$fldpos["lastcost"]]);
268         if ($quotation<>0) {
269             if ($quottype=="A") { $sellprice += $quotation; }
270             else { $sellprice = $sellprice * $quotation; }
271         };
272         if ($lastcost=="") unset($lastcost);
273         if ($sellprice=="") unset($sellprice);
274
275         /* Langtext zusammenbauen */
276         if ($zeile[$fldpos["notes"]]) {
277             $notes = preg_replace('/""[^ ]/','"',$zeile[$fldpos["notes"]]);
278             $notes = addslashes($notes);
279         }
280         if ($zeile[$fldpos["notes1"]]) {
281             $notes1 = preg_replace('/""[^ ]/','"',$zeile[$fldpos["notes1"]]);
282             if ($notes) {
283                 $notes = "\n".addslashes($notes1);
284             } else {
285                 $notes = addslashes($notes1);
286             }
287         }
288
289         /* Warengruppe bilden */
290         if ($fldpos["partsgroup"]>0  and $zeile[$fldpos["partsgroup"]])  $pgroup[]=$zeile[$fldpos["partsgroup"]];
291         if ($fldpos["partsgroup1"]>0 and $zeile[$fldpos["partsgroup1"]]) $pgroup[]=$zeile[$fldpos["partsgroup1"]];
292         if ($fldpos["partsgroup2"]>0 and $zeile[$fldpos["partsgroup2"]]) $pgroup[]=$zeile[$fldpos["partsgroup2"]];
293         if ($fldpos["partsgroup3"]>0 and $zeile[$fldpos["partsgroup3"]]) $pgroup[]=$zeile[$fldpos["partsgroup3"]];
294         if ($fldpos["partsgroup4"]>0 and $zeile[$fldpos["partsgroup4"]]) $pgroup[]=$zeile[$fldpos["partsgroup4"]];
295         if (count($pgroup)>0) {
296                 $pgname = implode($wgtrenner,$pgroup);
297                 $partsgroup_id = getPartsgroupId($db, $pgname, $insert);
298         }
299
300         /* sind Hersteller und Modelnummer hinterlegt 
301             wenn ja, erfolgt er insert später */
302         if (!empty($zeile[$fldpos["makemodel"]]) and !$artikel) { 
303             $hersteller=suchFirma("vendor",$zeile[$fldpos["makemodel"]]);
304             $hersteller=$hersteller["cp_cv_id"];
305             if (!empty($zeile[$fldpos["model"]])) {
306                 $model = $zeile[$fldpos["model"]];
307                 $makemodel = 't';
308             } else { 
309                 unset($hersteller);
310                 $makemodel = 'f';
311             }
312         }
313
314         /* Ware oder Dienstleistung */
315         if (($maske["ware"]=="G" and strtoupper($zeile[$fldpos["art"]])=="D") or $maske["ware"]=="D") { 
316             $artikel = false; 
317         } else if (($maske["ware"]=="G" and strtoupper($zeile[$fldpos["art"]])=="W") or $maske["ware"]=="W") { 
318             $artikel = true;
319         }
320
321         /* Einheit ermitteln */
322         if ($zeile[$fldpos["unit"]]=="") {
323             //Keine Einheit mitgegeben
324             if ($maske["ware"]=="G") { 
325                 if ($artikel) {
326                     $unit = $stdunitD;
327                 } else {
328                     $unit = $stdunitW; 
329                 }
330             } else if ($maske["ware"]=="D") { $unit = $stdunitD; }
331             else { $unit = $stdunitW; };
332         } else {
333             if (existUnit($db,$zeile[$fldpos["unit"]])) {
334                 $unit = $zeile[$fldpos["unit"]];
335             } else {
336                 $unit = ($artikel)?$stdunitD:$stdunitW;
337             }
338         }
339
340         /* Buchungsgruppe ermitteln */
341         if ($maske["bugrufix"]==1) {
342             $bg = $maske["bugru"];
343         } else {
344             if ($zeile[$fldpos["income_accno"]]<>"" and $zeile[$fldpos["expense_accno"]]<>"") {
345                 /* search for buchungsgruppe */
346                 $bg = getBuchungsgruppe($db, $zeile[$fldpos["income_accno"]],$zeile[$fldpos["expense_accno"]]);
347                 if ($bg == "" and $maske["bugrufix"]==2 and $maske["bugru"]<>"") {
348                     $bg = $maske["bugru"];
349                 }
350             } else if ($maske["bugru"]<>"" and $maske["bugrufix"]==2) {
351                 $bg = $maske["bugru"];
352             } else {
353                 /* nothing found? user must create one */
354                 echo "Error in line $m: ";
355                 echo "Keine Buchungsgruppe gefunden f&uuml;r <br>";
356                 echo "Erl&ouml;se Inland: ".$zeile[$fldpos["income_accno"]]."<br>";
357                 echo "Aufwand Inland: ".$zeile[$fldpos["expense_accno"]]."<br>";
358                 echo "Bitte legen Sie eine an oder geben Sie eine vor.<br>";
359                 echo "<br>";
360                 $errors++;
361             }
362         }
363         if ($bg > 0) {
364             /* found one, add income_accno_id etc from buchungsgr. */
365             /* XXX nur bei artikel!!! */
366             if ($artikel) {
367                 $inventory_accno = getFromBG($db, $bg, "inventory_accno_id");
368             };
369             $income_accno = getFromBG($db, $bg, "income_accno_id_0");
370             $expense_accno = getFromBG($db, $bg, "expense_accno_id_0");
371             $bg = $bg * 1;
372         } else {
373             echo "Error in line $m: ";
374             echo "Keine Buchungsgruppe angegeben/gefunden<br>";
375             $errors++;
376             continue;
377         }
378
379         $description = preg_replace('/""[^ ]/','"',$zeile[$fldpos["description"]]);
380         $description = addslashes($description);
381
382         // rop und weight müssen null oder Zahl sein
383         if ($zeile[$fldpos["rop"]]) $rop = 1 * str_replace(",", ".",$zeile[$fldpos["rop"]]);
384         if ($zeile[$fldpos["weight"]]) $weight = 1 * str_replace(",", ".", $zeile[$fldpos["weight"]]);
385
386         // Shop-Artikel
387         if ($zeile[$fldpos["shop"]]) {
388                 $shop = ($zeile[$fldpos["shop"]] > 0)?'t':'f';
389         } else {
390                 $shop = $maske["shop"];
391         }
392
393         // Artikel updaten
394         if (getPartsid($db,trim($zeile[$fldpos["partnumber"]]))) {
395             /* es gibt die Artikelnummer */
396             if ($Update) {
397                 /* Updates durchführen */
398                 if ($UpdText=='1') {
399                     $u += updParts($db,$insert,$show,$zeile[$fldpos["partnumber"]],$lastcost,$sellprice,
400                     $description,$notes,$zeile[$fldpos["ean"]],$weight,
401                     $zeile[$fldpos["image"]],$partsgroup_id, $shop);
402                 } else {
403                     $u += updPrice($db,$insert,$show,$zeile[$fldpos["partnumber"]],$lastcost,$sellprice,$shop);
404                 }
405                 continue;
406                 // nächste Zeile
407             } 
408         }
409
410         // Neuen Artikel einfügen
411
412         if ($zeile[$fldpos["partnumber"]] == "") {
413             $zeile[$fldpos["partnumber"]] = newPartNumber($db,$check);
414             //Keine Artikelnummer bekommen
415             if ($zeile[$fldpos["partnumber"]] == "") {
416                 continue;
417             }
418         }
419         $i += insertParts($db,$insert,$show,array(
420                     "partnumber"=>$zeile[$fldpos["partnumber"]],
421                     "description"=>$description,"notes"=>$notes,
422                     "ean"=>$zeile[$fldpos["ean"]],"unit"=>$unit,
423                     "weight"=>$weight,"image"=>$zeile[$fldpos["image"]],
424                     "sellprice"=>$sellprice,"lastcost"=>$lastcost,
425                     "partsgroup_id"=>$partsgroup_id,
426                     "buchungsgruppen_id"=>$bg,"income_accno"=>$income_accno,
427                     "expense_accno"=>$expense_accno,"inventory_accno"=>$inventory_accno,
428                     "microfiche"=>$zeile[$fldpos["microfiche"]],"drawing"=>$zeile[$fldpos["drawing"]],
429                     "rop"=>$rop,"assembly"=>$assembly,
430                     "shop"=>$shop,"makemodel"=>$makemodel)
431                 );
432         if ($hersteller>0 && $model) {
433             $partsid=getPartsid($db,$zeile[$fldpos["partnumber"]]);
434             if ($partsid) {
435                 getMakemodel($db,$check,$hersteller,$model,$partsid,true);
436             }
437         }
438         unset($zeile);
439     }
440
441     if ($show) show("</table>",false);
442     fclose($f);
443     echo "$m Zeilen bearbeitet. Importiert: $i Update: $u (".($m-$u-$i+$errors)." : Fehler) ";
444 }
445 ?>