root/trunk/core/promogest/Environment.py @ 843

Revision 843, 13.9 KB (checked in by vete, 7 months ago)

iaggiunta di definizione punto cassa e magazzino e utente in vendita dettaglio Gestione negozio

Line 
1# -*- coding: utf-8 -*-
2
3"""
4 Promogest - promoCMS
5 Copyright (C) 2007-2008 by Promotux Informatica - http://www.promotux.it/
6 license: GPL see LICENSE file
7"""
8import locale
9from config import Config
10import gtk
11import os
12import shutil
13import glob
14import getopt, sys
15from sqlalchemy import *
16from sqlalchemy.orm import *
17from sqlalchemy.interfaces import PoolListener
18import logging
19import logging.handlers
20
21
22PRODOTTO = "PromoTux - Virtual Company"
23VERSIONE = "PromoGest2"
24debugFilter = False
25debugDao = False
26debugSQL = False
27reportTemplatesDir = None
28imagesDir = None
29labelTemplatesDir = None
30templatesDir = None
31documentsDir = None
32conf = None
33promogestDir = None
34exceptionHandler = None
35connection = None
36feed = None
37emailcompose = None
38loc = None
39subject= None
40body = None
41rivenditoreUrl = None
42smtpServer = None
43emailmittente = None
44cliente_predefinito = None
45tipo_documento_predefinito = None
46multilinelimit = None
47mltext = None
48sistemaColonnaFrontaline = None
49sistemaRigaFrontaline = None
50bordoDestro = None
51bordoSinistro = None
52feedCache = ""
53feedAll = ""
54scontisave = {}
55tagliacoloretempdata = (False,None)
56lastCode = None
57righeDocumentoDict = {}
58totaliDict = {}
59percentualeIvaRiga = None
60aliquotaIvaRiga = None
61modulesList = []
62listinoFissato = None
63new_print_enjine=False
64shop = False
65rev_locale = None
66rev_remota = None
67magazzino_pos = None
68
69gtkrc = """# Auto-written by gtk2_prefs. Do not edit.
70
71gtk-theme-name = "Nodoka"
72style "user-font"
73{
74    font_name="Tahoma 8"
75}
76widget_class "*" style "user-font"
77"""
78
79
80if os.name =="nt" and not os.path.exists(os.path.expanduser('~')+os.sep+".gtkrc-2.0"):
81    f = open(os.path.expanduser('~')+os.sep+".gtkrc-2.0","w")
82    f.write(gtkrc)
83    f.close
84
85def getConfigureDir(company='__default__'):
86    """ Tests if another configuration folder was indicated """
87    default='promogest2'
88    if company != '__default__' and company is not None:
89        default = os.path.join('promogest2',company)
90
91    try:
92        opts, args = getopt.getopt(sys.argv[1:], "c:", ["config-dir="])
93        for opt, arg in opts:
94            if opt in ("-c", "--config-dir"):
95                return arg
96        else:
97            return default
98    except getopt.GetoptError:
99        return default
100
101
102
103def startdir():
104    startDir = getConfigureDir()
105    promogestStartDir = os.path.expanduser('~') + os.sep + startDir + os.sep
106    return promogestStartDir
107
108
109try:
110
111    promogestStartDir = startdir()
112    if not (os.path.exists(promogestStartDir)):
113        os.mkdir(promogestStartDir)
114    configFile = promogestStartDir + 'configure'
115    conf = Config(configFile)
116    conf.guiDir = '.' + os.sep + 'gui' + os.sep
117
118except IOError:
119    c = open('configure.dist','r')
120    content = c.readlines()
121    fileConfig = open(configFile,'w')
122    for row in content[0:13]:
123        fileConfig.write(row)
124    c.close()
125    fileConfig.close()
126    conf = Config(configFile)
127    conf.guiDir = '.' + os.sep + 'gui' + os.sep
128
129
130""" Sets configuration value """
131def set_configuration(company=None, year = None):
132    global conf,connection, exceptionHandler, promogestDir, feed,  emailcompose,\
133                emailmittente, smtpServer, cliente_predefinito, tipo_documento_predefinito,\
134                multilinelimit, mltext, sistemaColonnaFrontaline, sistemaRigaFrontaline,\
135                imagesDir, labelTemplatesDir, templatesDir, documentsDir, reportTemplatesDir,\
136                bordoDestro, bordoSinistro, magazzini, listini
137
138    try:
139        dire = getConfigureDir(company)
140        promogestDir = os.path.expanduser('~') + os.sep + dire + os.sep
141        if not (os.path.exists(promogestDir)):
142            os.mkdir(promogestDir)
143        try:
144            documentsDir = promogestDir + 'documenti' + os.sep
145            if not (os.path.exists(documentsDir)):
146                os.mkdir(documentsDir)
147
148            tempDir = promogestDir + 'temp' + os.sep
149            if not (os.path.exists(tempDir)):
150                os.mkdir(tempDir)
151
152            templatesDir = promogestDir + 'templates' + os.sep
153            if not (os.path.exists(templatesDir)):
154                os.mkdir(templatesDir)
155                slas = glob.glob(os.path.join('.', 'templates', '*.sla'))
156                for s in slas:
157                    shutil.copy(s, templatesDir)
158
159            #dataDir = promogestDir + 'data' + os.sep
160            #if not (os.path.exists(dataDir)):
161                #os.mkdir(dataDir)
162                #slas = glob.glob(os.path.join('.', 'data', '*.*'))
163                #for s in slas:
164                    #shutil.copy(s, dataDir)
165
166            reportTemplatesDir = promogestDir + 'report-templates' + os.sep
167            if not (os.path.exists(reportTemplatesDir)):
168                os.mkdir(reportTemplatesDir)
169                slas = glob.glob(os.path.join('.', 'report-templates', '*.sla'))
170                for s in slas:
171                    shutil.copy(s, reportTemplatesDir)
172
173            labelTemplatesDir = promogestDir + 'label-templates' + os.sep
174            if not (os.path.exists(labelTemplatesDir)):
175                os.mkdir(labelTemplatesDir)
176                slas = glob.glob(os.path.join('.', 'label-templates', '*.sla'))
177                for s in slas:
178                    shutil.copy(s, labelTemplatesDir)
179
180            imagesDir = promogestDir + 'images' + os.sep
181            if not (os.path.exists(imagesDir)):
182                os.mkdir(imagesDir)
183        except:
184            print "Qualcosa e' fallito nell'env"
185            raise
186
187        configFile = promogestDir + 'configure'
188        conf = Config(configFile)
189    except IOError:
190        msg = ('Il file configure non e\' stato trovato !\n\n' +
191               'Il file verra creato in questo momento con valori di default\n' +
192               'e una connessione al database demo di Promotux.\n\n' +
193               'Ti invitiamo a riconfigurare il setup secondo le tue esigenze.')
194        overDialog = gtk.MessageDialog(None,
195                                       gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
196                                       gtk.MESSAGE_INFO,
197                                       gtk.BUTTONS_OK, msg)
198        response = overDialog.run()
199        if response == gtk.RESPONSE_OK:
200            b= open(promogestStartDir+'configure')
201            db_cont = b.readlines()
202
203            c = open('configure.dist','r')
204            cont = c.readlines()
205            fileConfig = open(configFile,'w')
206            for row in db_cont[0:10]:
207                fileConfig.write(str(cont))
208            for row in cont[11:]:
209                fileConfig.write(str(row))
210            b.close()
211            c.close()
212            fileConfig.close()
213            conf = Config(configFile)
214        overDialog.destroy()
215
216    # Impostazioni di default
217        conf.Documenti.cartella_predefinita = documentsDir
218        conf.Documenti.ricerca_per = 'descrizione'
219        conf.save()
220
221
222    # Imposto variabili di formattazione numeri
223    conf.number_format = '%-14.' + str(getattr(conf.Numbers, 'decimals', 4)) + 'f'
224    conf.decimals = str(getattr(conf.Numbers, 'decimals', 4))
225    conf.batch_size = int(getattr(conf.Numbers, "batch_size",15))
226
227
228    # Parametri localizzazione formati
229    loc = locale.setlocale(locale.LC_ALL, '')
230    conf.windowsrc = promogestDir + 'windowsrc.xml'
231    conf.guiDir = '.' + os.sep + 'gui' + os.sep
232
233    #Anno di lavoro
234    conf.workingYear = None
235    workingYear = None
236    # stampa il debug del Dao
237
238
239    #[Feed]
240    try:
241        feed = str(getattr(conf.Feed, 'feed'))
242    except:
243        feed = True
244
245    #[Composer]
246    if hasattr(conf,'Composer'):
247        conf.emailcompose = str(getattr(conf.Composer, 'emailcompose'))
248        try:
249            conf.subject = conf.Composer.subject
250        except:
251            conf.subject = "[ Invio Doc: %s ]"
252        try:
253            conf.signature = conf.Composer.signature
254        except:
255            conf.signature = """Invio elettronico di  %s   effettuato tramite software gestionale PromoGest """
256        try :
257            conf.bodytemplate = conf.Composer.bodytemplate
258        except:
259            conf.bodytemplate = ""
260        conf.body = ",body="+ conf.bodytemplate + conf.signature
261    else:
262        emailcompose = None
263
264    #[Rivenditore]
265    if hasattr(conf,'Rivenditore'):
266        rivenditoreUrl = str(getattr(conf.Composer, 'rivenditoreurl'))
267    else:
268        rivenditoreUrl = "http://promogest.promotux.it/contatti.php"
269
270    if hasattr(conf,'Numbers'):
271        conf.combo_columns = int(getattr(conf.Numbers,'combo_column',5))
272    else:
273        print "ATTENZIONE: OPZIONE combo_column = 5  MANCANTE NEL CONFIGURE SEZIONE [Numbers]"
274        conf.combo_columns = 3
275    #[SMTP]
276    smtpServer = str(getattr(conf.SMTP, 'smtpserver'))
277    emailmittente = str(getattr(conf.SMTP, 'emailmittente'))
278
279    #[Documenti]
280    cliente_predefinito = str(getattr(conf.Documenti, 'cliente_predefinito'))
281    tipo_documento_predefinito = str(getattr(conf.Documenti, 'tipo_documento_predefinito'))
282
283
284    #[Multilinea]
285    try :
286        multilinelimit = int(getattr(conf.Multilinea, 'multilinealimite'))
287    except:
288        multilinelimit = 60
289    mltext = ""
290
291    #[Pagamenti]
292    if hasattr(conf, 'Pagamenti'):
293        mod_enable = getattr(
294                conf.Pagamenti,'mod_enable','no')
295        if mod_enable == 'yes':
296            conf.hasPagamenti = True
297        else:
298            conf.hasPagamenti = False
299    else:
300        conf.hasPagamenti = False
301
302    #[Magazzini]
303    magazzini = False
304    if hasattr(conf, 'Magazzini'):
305        mod_enable = getattr( conf.Magazzini,'mod_enable','no')
306        if mod_enable == 'yes':
307            magazzini = True
308
309
310    #[Listini]
311    listini = False
312    if hasattr(conf, 'Listini'):
313        mod_enable = getattr( conf.Listini,'mod_enable','no')
314        if mod_enable == 'yes':
315            listini = True
316
317
318    #[Label]
319    if hasattr(conf,'Label'):
320        mod_enable = getattr(conf.Label,'mod_enable')
321        if mod_enable:
322            conf.hasLabel = True
323            sistemaColonnaFrontaline = float(getattr(conf.Label, 'sistemacolonnafrontaline'))
324            sistemaRigaFrontaline = float(getattr(conf.Label, 'sistemarigafrontaline'))
325            #bordoDestro = float(getattr(conf.Label, 'bordodestro'))
326            #bordoSinistro = float(getattr(conf.Label, 'bordosinistro'))
327        else:
328            conf.hasLabel = False
329            sistemaColonnaFrontaline = 0
330            sistemaRigaFrontaline = 0
331            bordoDestro = None
332            bordoSinistro = None
333    else:
334        conf.hasLabel = False
335
336    importDebug = True
337
338
339#mainSchema = "promogest2"
340#mainSchema = None
341#try :
342azienda=conf.Database.azienda
343#azienda = None
344#except:
345    #azienda = "azienda_prova"
346#print sys.path
347
348try:
349    tipodb = conf.Database.tipodb
350except:
351    tipodb = "postgresql"
352try:
353    pw = conf.Database.pw
354except:
355    pw = "No"
356if tipodb == "sqlite" and not (os.path.exists(startdir()+"db")):
357    if os.path.exists("data/db"):
358        shutil.copy("data/db",startdir()+"db")
359        os.remove("data/db")
360    elif os.path.exists("data/db_pw.dist")\
361                        and pw.upper()=="YES":
362        shutil.copy("data/db_pw.dist",startdir()+"db" )
363    elif os.path.exists("data/db.dist"):
364        shutil.copy("data/db.dist",startdir()+"db" )
365    else:
366        print("ERRORE NON RIESCO A CREARE IL DB")
367
368database = conf.Database.database
369port = conf.Database.port
370user = conf.Database.user
371password = conf.Database.password
372host = conf.Database.host
373userdata = ["","","",user]
374
375
376class SetTextFactory(PoolListener):
377     def connect(self, dbapi_con, con_record):
378         dbapi_con.text_factory = str
379
380
381if tipodb == "sqlite":
382    azienda = None
383    mainSchema = None
384    print "startdir()", startdir()
385    engine =create_engine("sqlite:///"+startdir()+"db",listeners=[SetTextFactory()])
386else:
387    mainSchema = "promogest2"
388    #azienda=conf.Database.azienda
389    engine = create_engine('postgres:'+'//'
390                    +user+':'
391                    + password+ '@'
392                    + host + ':'
393                    + port + '/'
394                    + database,
395                    encoding='utf-8',
396                    convert_unicode=True )
397tipo_eng = engine.name
398engine.echo = False
399meta = MetaData(engine)
400    #Session = sessionmaker(bind=engine)
401Session = scoped_session(sessionmaker(bind=engine, autoflush=True))
402
403#meta = None
404#Session = scoped_session(sessionmaker(bind=engine))
405session = Session()
406params = {'engine': engine ,
407        'mainSchema': mainSchema,
408        'schema': azienda,
409        'metadata': meta,
410        'session' : session,
411        'rowsFamily' : [],
412        'defaultLimit': 5,
413        'widthThumbnail' : 64,
414        'heightThumbnail' : 64,
415        'widthdetail' : 110,
416        'heightdetail': 110 ,
417        'usernameLoggedList':userdata}
418
419
420 # Parametri localizzazione formati
421loc = locale.setlocale(locale.LC_ALL, '')
422conf.windowsrc = os.path.expanduser('~') + os.sep + 'promogest2/windowsrc.xml'
423conf.guiDir = '.' + os.sep + 'gui' + os.sep
424#conf.windowsrc = promogestDir + 'windowsrc.xml'
425#conf.guiDir = '.' + os.sep + 'gui' + os.sep
426
427LOG_FILENAME = startdir()+'pg2.log'
428
429# Set up a specific logger with our desired output level
430pg2log = logging.getLogger('PromoGest2')
431pg2log.setLevel(logging.DEBUG)
432
433# Add the log message handler to the logger
434handler = logging.handlers.RotatingFileHandler(
435              LOG_FILENAME, maxBytes=400000, backupCount=3)
436
437formatter = logging.Formatter(
438    "%(asctime)s - %(name)s - %(levelname)s - %(message)s - %(pathname)s - %(funcName)s - %(lineno)d")
439# add formatter to ch
440handler.setFormatter(formatter)
441pg2log.addHandler(handler)
442pg2log.debug("\n\n<<<<<<<<<<<  AVVIO PROMOGEST >>>>>>>>>>")
443
444
445def hook(et, ev, eb):
446    import traceback
447    pg2log.debug("\n  ".join (["Error occurred: traceback follows"]+list(traceback.format_exception(et, ev, eb))))
448    print "UN ERRORE È STATO INTERCETTATO E LOGGATO, SI CONSIGLIA DI RIAVVIARE E DI CONTATTARE L'ASSISTENZA \n\nPREMERE CTRL+C PER CHIUDERE"
449sys.excepthook = hook
450
451#import warnings
452
453#def fxn():
454#warnings.warn("deprecated", DeprecationWarning)
455#warnings.showwarning()
456#print "GFGFGFG", warnings.filterwarnings('default')
457#with warnings.catch_warnings():
458    ##print "GFGFGFGFG", warnings.catch_warnings()
459    #print warnings.simplefilter("always")
460    #fxn()
Note: See TracBrowser for help on using the browser.