Fix #7123 - getting abra ready to test
[Pman.Xtuple] / Import / Customers.php
1 <?php
2
3 require_once 'Pman/Roo.php';
4
5 class Pman_Xtuple_Import_Customers extends Pman_Roo
6 {
7     function getAuth()
8     {
9         if (HTML_FlexyFramework::get()->cli) {
10             return true;
11         }
12         return parent::getAuth();
13     }
14     
15     function post()
16     {
17         $this->transObj = DB_DataObject::Factory('vendinfo');
18         
19         $this->transObj->query('BEGIN');
20         
21         PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
22         
23         $img = DB_DataObject::Factory('images');
24         $img->setFrom(array(
25             'onid' => 0,
26             'ontable' => 'ipshead'
27         ));
28         $img->onUpload(false);
29         
30         require_once 'File/Convert.php';
31         $fc = new File_Convert($img->getStoreName(), $img->mimetype );
32         $csv = $fc->convert('text/csv');
33         $this->importCsv($csv);
34     }
35     
36     function importCsv($csv)
37     {
38         ini_set("auto_detect_line_endings", true);
39         
40         $fh = fopen($csv, 'r');
41         if (!$fh) {
42             $this->jerr("invalid file");
43         }
44         
45         $req = array(
46             'ACTIVE STATUS', 'CUSTOMER', 'BALANCE', 'BALANCE TOTAL', 'COMPANY', 'MR, MRS',
47             'FIRST NAME', 'M.I.', 'LAST NAME', 'CONTACT', 'PHONE', 'FAX', 'ALT. PHONE', 'ALT. CONTACT', 'EMAIL', 'BILL TO 1',
48             'BILL TO 2', 'BILL TO 3', 'BILL TO 4', 'BILL TO 5', 'SHIP TO 1', 'SHIP TO 2', 'SHIP TO 3', 'SHIP TO 4', 'SHIP TO 5',
49             'CUSTOMER TYPE', 'TERMS', 'REP', 'TAX CODE', 'RESALE NUM', 'ACCOUNT NO.', 'CREDIT LIMIT', 'JOB STATUS', 'JOB TYPE',
50             'JOB DESCRIPTION', 'START DATE', 'PROJECTED END', 'END DATE', 'NOTE'
51         );
52         
53         $cols = false;
54         $rows = array();
55         
56         while(false !== ($n = fgetcsv($fh,10000, ',', '"'))) {
57             if (!$cols) {
58                 
59                 $cols = array();
60                 foreach($n as $k) {
61                     $cols[] = strtoupper(trim($k));
62                 }
63                 
64                 if (empty($cols)) {
65                     continue;
66                 }
67                 foreach($req as $r) {
68                     if (!in_array($r,$cols)) {
69                         $cols = false;
70                         break;
71                     }
72                 }
73                 continue;
74             }
75             foreach($cols as $i=>$k) {
76                 $row[$k] = $n[$i];
77             }
78             $rows[] = $row;
79         }
80         
81         if (empty($cols)) {
82             $this->jerr("could not find a row with " . implode(' / ', $req));
83         }
84         
85         fclose($fh);
86         
87         $tz = DB_DataObject::Factory('taxzone');
88         $tz->whereAdd("taxzone_code != 'NO TAX'");
89         if (!$tz->find(true)) {
90             $this->jerr("could not find tax zone for taxable");
91         }
92         
93         
94         foreach ($rows as $row){
95             $custinfo = DB_DataObject::factory('custinfo');
96             if(empty($row['COMPANY'])){
97                 continue;
98             }
99             $checkTerms = true;
100             if(!$custinfo->get('cust_name', $row['COMPANY'])){ // customer not exist
101                 $custinfo->setFrom(array(
102                     'cust_active'       => $row['ACTIVE STATUS'] == 'Active' ? TRUE : FALSE,
103                     'cust_salesrep_id'  => $this->salesrep($row['REP']),
104                     'cust_name'         => $row['COMPANY'],
105                     'cust_number'       => str_replace(' ', '', strtoupper($row['COMPANY'])),
106                     'cust_creditlmt'    => empty($row['CREDIT LIMIT']) ? 0 : $row['CREDIT LIMIT'],
107                     'cust_terms_id'     => $this->terms($row['TERMS']),
108                     'cust_taxzone_id'   => $tz->pid()
109                 ));
110                 
111                 
112                 foreach($custinfo->defaults() as $k=>$v) {
113                     if (!isset($custinfo->$k)) {
114                         $custinfo->$k = $v;
115                     }
116                 }
117
118                 $custinfo->insert();
119                 
120                 $checkTerms = false;
121             }
122             
123             if(!$custinfo->pid()){
124                 $this->jerr("error occur on insert customer " . $row['COMPANY']);
125             }
126             
127             // check the terms
128             if($checkTerms){
129                 $terms_id = $this->terms($row['TERMS']);
130                 if($custinfo->cust_terms_id  != $terms_id){
131                     $oldcust = clone($custinfo);
132                     $custinfo->cust_terms_id = $terms_id;
133                     $custinfo->update($oldcust);
134                 }
135             }
136             
137             // check cntct and update cust_cntct_id
138             $cntct = DB_DataObject::factory('cntct');
139             if(empty($row['FIRST NAME']) && empty($row['LAST NAME'])){
140                 $row['FIRST NAME'] = $row['CONTACT'];
141                 
142                 if(empty($row['CONTACT'])){
143                     $row['FIRST NAME'] = $row['CUSTOMER'];
144                 }
145                 
146             }
147            
148             $c = array(
149                 'cntct_first_name'  => empty($row['MR, MRS']) ? $row['FIRST NAME'] : $row['MR, MRS'] . ' ' . $row['FIRST NAME'],
150                 'cntct_last_name'   => $row['LAST NAME'],
151                 'cntct_active'      => 1,
152                 'cntct_phone'       => $row['PHONE'],
153                 'cntct_fax'         => $row['FAX'],
154                 'cntct_email'       => $row['EMAIL'],
155                 'cntct_notes'       => $row['NOTE'],
156                 'cntct_crmacct_id'  => $cntct->sqlValue("(SELECT crmacct_id FROM crmacct WHERE crmacct_cust_id = {$custinfo->pid()})")
157             );
158             $c['cntct_name'] = empty($c['cntct_last_name']) ? $c['cntct_first_name'] : $c['cntct_first_name'] . ' ' . $c['cntct_last_name'];
159             if(!$cntct->get('cntct_name', $c['cntct_name'])){
160                 $cntct = $cntct->createFromArray($c);
161             }
162             if(!$cntct->pid()){
163                 $this->jerr("error occur on insert cntct " . $row['CUSTOMER']);
164             }
165             
166             
167             if(!$cntct->cntct_addr_id){
168                 $addrs = $this->addrValue($row);
169                 $addr = DB_DataObject::Factory('addr');
170                 $addr->createFromArray($addrs);
171                 
172                 if(!$addr->pid()){
173                     $this->jerr("error occur on insert address " . $row['CUSTOMER']);
174                 }
175
176                 $oldcn = clone($cntct);
177                 $cntct->cntct_addr_id = $addr->pid();
178                 $cntct->update($oldcn);
179             }
180             
181             if(!$custinfo->cust_cntct_id){
182                 $oldcust = clone($custinfo);
183                 $custinfo->cust_cntct_id = $cntct->pid();
184                 $custinfo->update($oldcust);
185             }
186             
187             // fetch all cntct id to update the shipment list
188             $cn = DB_DataObject::factory('cntct');
189             $cn->whereAdd("
190                 cntct_crmacct_id = (SELECT crmacct_id FROM crmacct WHERE crmacct_cust_id = {$custinfo->pid()})
191             ");
192             $list = $cn->fetchAll('cntct_id');
193             
194             $custinfo->updateShipList($list);
195             
196         }
197         
198         $this->jok("DONE");
199         
200         exit;
201     }
202     
203     /*
204      * use default salesrep accounts if the code does not exist
205      */
206     function salesrep($salesrep_name)
207     {
208         $salesrep = DB_DataObject::factory('salesrep');
209         if(!$salesrep->get('salesrep_name', $salesrep_name)){
210             $salesrep->get('salesrep_name', 'accounts');
211         }
212         return $salesrep->pid();
213         
214     }
215     
216     /*
217      * use default terms C.O.D. if the code does not exist
218      */
219     function terms($t)
220     {
221         $terms = DB_DataObject::factory('terms');
222         $terms->whereAdd("
223             terms_code ILIKE '%{$terms->escape($t)}%'
224             OR
225             terms_descrip ILIKE '%{$terms->escape($t)}%'
226         ");
227         if($terms->find(true)){
228             return $terms->pid();
229         }
230         
231         $terms->setFrom(array(
232             'terms_code' => strtoupper($t),
233             'terms_descrip' => $t,
234             'terms_type' => 'D',
235             'terms_duedays' => 0,
236             'terms_discprcnt' => 0,
237             'terms_cutoffday' => 0,
238             'terms_ap' => TRUE,
239             'terms_ar' => TRUE 
240         ));
241         $terms->insert();
242         
243         if(!$terms->pid()){
244             $this->jerr("error occur on insert a terms " . $t);
245         }
246         
247         return $terms->pid();
248     }
249     
250     function addrValue($row)
251     {
252         $australiaStates = array(
253             'ACT'   => 'Australian Capital Territory',
254             'JBT'   => 'Jervis Bay Territory',
255             'NSW'   => 'New South Wales',
256             'NT'    => 'Northern Territory',
257             'QLD'   => 'Queensland',
258             'SA'    => 'South Australia',
259             'TAS'   => 'Tasmania',
260             'VIC'   => 'Victoria',
261             'WA'    => 'Western Australia'
262         );
263         $address = array(
264             'SHIP TO 5' => '',
265             'SHIP TO 4' => '',
266             'SHIP TO 3' => 'addr_line3', 
267             'SHIP TO 2' => 'addr_line2',
268             'SHIP TO 1' => 'addr_line1'
269         );
270         
271         $city = '';
272         $state = '';
273         $postalcode = '';
274
275         foreach (array_keys($address) as $a){
276             if(empty($row[$a])){
277                 unset($address[$a]);
278                 continue;
279             }
280             foreach ($australiaStates as $k => $v){
281                 if(!preg_match("/{$k}\s{0,}[0-9]{0,}$/", $row[$a])){
282                     continue;
283                 }
284                 $city = trim(preg_replace("/{$k}\s{0,}[0-9]{0,}$/", '', $row[$a]));
285                 
286                 $postalcode = trim(preg_replace("/{$city}/", '', $row[$a]));
287                 
288                 $state = $v;
289             }
290             unset($address[$a]);
291             break;
292         }
293
294         foreach ($address as $k => $v){
295             if(empty($v)){
296                 $row['SHIP TO 3'] = implode(' ', array($row['SHIP TO 3'], $row['SHIP TO 4']));
297             }
298         }
299         $addrs = array(
300             'addr_active'       => 1,
301             'addr_line1'        => isset($address['SHIP TO 1']) ? $row['SHIP TO 1'] : '',
302             'addr_line2'        => isset($address['SHIP TO 2']) ? $row['SHIP TO 2'] : '',
303             'addr_line3'        => isset($address['SHIP TO 3']) ? $row['SHIP TO 3'] : '',
304             'addr_city'         => $city,
305             'addr_state'        => $state,
306             'addr_postalcode'   => $postalcode
307         );
308         
309         return $addrs;
310     }
311 }