+clear unused characters in phone numbers
[lhc/oe_alcatel_export.git] / alcatel_export.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 import psycopg2
4 from lxml import etree
5
6 # variables
7 db_name = "heureuxcyclage"
8 db_user = "bikecoop"
9 db_host = "localhost"
10 limit = 0
11
12 # functions
13 def keep_numbers_only(sentence):
14 """Return a string with only number characters"""
15 set = '0123456789'
16 return ''.join(c for c in sentence if c in set)
17
18 # sql connect
19 conn = psycopg2.connect("dbname=%s user=%s host=%s" % (db_name, db_user, db_host))
20 cur = conn.cursor()
21
22 # import datas in dicos
23 query = "SELECT name, phone, mobile, is_company from res_partner where name != '/' and name is not null and (phone is not null or mobile is not null) and active = True and usual_contact = True"
24 cur.execute(query)
25
26 root = etree.Element('directory')
27 group = etree.SubElement(root, 'DIR_GROUP')
28
29 line = 0
30 for row in cur:
31 line += 1
32 fields = {
33 'LINE_NUMBER': '0',
34 'BLOCK': '0',
35 'RINGER': '0',
36 }
37 if row[1]:
38 fields['NUMBER_WORK'] = keep_numbers_only(unicode(str(row[1]), 'utf-8'))
39 if row[2]:
40 fields['NUMBER_MOBILE'] = keep_numbers_only(unicode(str(row[2]), 'utf-8'))
41 if row[3]:
42 fields['NAME_LAST'] = unicode(row[0], 'utf-8')
43 else:
44 name = unicode(row[0], 'utf-8')
45 try:
46 pspace = name.index(' ')
47 fields['NAME_FIRST'] = name[:pspace]
48 fields['NAME_LAST'] = name[pspace+1:]
49 except ValueError:
50 fields['NAME_FIRST'] = name
51
52 entry = etree.SubElement(group, 'DIR_ENTRY')
53
54 for field in fields:
55 entry_field = etree.SubElement(entry, 'DIR_ENTRY_%s' % field.upper())
56 entry_field.text = fields[field]
57
58 if limit:
59 if line == limit:
60 break
61
62 # sql disconnect
63 cur.close()
64 conn.close()
65
66 content = '<?xml version="1.0"?>\n%s' % etree.tostring(root, pretty_print=True)
67 print(content)