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