[IMP] rephrase some error and warning messages in base_action_rule, base_calendar...
[odoo/odoo.git] / addons / base_report_designer / plugin / openerp_report_designer / bin / script / SendToServer.py
1 ##########################################################################
2 #
3 # Portions of this file are under the following copyright and license:
4 #
5 #
6 #   Copyright (c) 2003-2004 Danny Brewer
7 #   d29583@groovegarden.com
8 #
9 #   This library is free software; you can redistribute it and/or
10 #   modify it under the terms of the GNU Lesser General Public
11 #   License as published by the Free Software Foundation; either
12 #   version 2.1 of the License, or (at your option) any later version.
13 #
14 #   This library is distributed in the hope that it will be useful,
15 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
16 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 #   Lesser General Public License for more details.
18 #
19 #   You should have received a copy of the GNU Lesser General Public
20 #   License along with this library; if not, write to the Free Software
21 #   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
22 #
23 #   See:  http://www.gnu.org/licenses/lgpl.html
24 #
25 #
26 # and other portions are under the following copyright and license:
27 #
28 #
29 #    OpenERP, Open Source Management Solution>..
30 #    Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>).
31 #
32 #    This program is free software: you can redistribute it and/or modify
33 #    it under the terms of the GNU Affero General Public License as published by
34 #    the Free Software Foundation, either version 3 of the License, or
35 #    (at your option) any later version.
36 #
37 #    This program is distributed in the hope that it will be useful,
38 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
39 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
40 #    GNU Affero General Public License for more details.
41 #
42 #    You should have received a copy of the GNU Affero General Public License
43 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
44 #
45 #
46 ##############################################################################
47
48 import uno
49 import string
50 import unohelper
51 import random
52 import xmlrpclib
53 import base64, tempfile
54 from com.sun.star.task import XJobExecutor
55 import os
56 import sys
57 if __name__<>'package':
58     from lib.gui import *
59     from lib.error import *
60     from lib.functions import *
61     from lib.logreport import *
62     from lib.tools import *
63     from LoginTest import *
64     from lib.rpc import *
65     database="report"
66     uid = 3
67
68 class SendtoServer(unohelper.Base, XJobExecutor):
69     Kind = {
70         'PDF' : 'pdf',
71         'OpenOffice': 'sxw',
72         'HTML' : 'html'
73     }
74
75     def __init__(self,ctx):
76         self.ctx     = ctx
77         self.module  = "openerp_report"
78         self.version = "0.1"
79         LoginTest()
80         self.logobj=Logger()
81         if not loginstatus and __name__=="package":
82             exit(1)
83
84         global passwd
85         self.password = passwd
86         global url
87         self.sock=RPCSession(url)
88         desktop=getDesktop()
89         oDoc2 = desktop.getCurrentComponent()
90         docinfo=oDoc2.getDocumentInfo()
91
92         self.ids = self.sock.execute(database, uid, self.password, 'ir.module.module', 'search', [('name','=','base_report_designer'),('state', '=', 'installed')])
93         if not len(self.ids):
94             ErrorDialog("Please install base_report_designer module.", "", "Module Uninstalled Error !")
95             exit(1)
96
97         report_name = ""
98         name=""
99         if docinfo.getUserFieldValue(2)<>"" :
100             try:
101                 fields=['name','report_name']
102                 self.res_other = self.sock.execute(database, uid, self.password, 'ir.actions.report.xml', 'read', [int(docinfo.getUserFieldValue(2))],fields)
103                 name = self.res_other[0]['name']
104                 report_name = self.res_other[0]['report_name']
105             except:
106                 import traceback,sys
107                 info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
108                 self.logob.log_write('ServerParameter', LOG_ERROR, info)
109         elif docinfo.getUserFieldValue(3) <> "":
110             name = ""
111             result =  "rnd"
112             for i in range(5):
113                 result =result + random.choice('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890')
114
115             report_name = docinfo.getUserFieldValue(3) + "." + result
116         else:
117             ErrorDialog("Please select appropriate module...","Note: use OpenERP Report -> Open a new Report", "Module selection ERROR");
118             exit(1)
119
120         self.win = DBModalDialog(60, 50, 180, 100, "Send To Server")
121         self.win.addFixedText("lblName",10 , 9, 40, 15, "Report Name :")
122         self.win.addEdit("txtName", -5, 5, 123, 15,name)
123         self.win.addFixedText("lblReportName", 2, 30, 50, 15, "Technical Name :")
124         self.win.addEdit("txtReportName", -5, 25, 123, 15,report_name)
125         self.win.addCheckBox("chkHeader", 51, 45, 70 ,15, "Corporate Header")
126         self.win.addFixedText("lblResourceType", 2 , 60, 50, 15, "Select Rpt. Type :")
127         self.win.addComboListBox("lstResourceType", -5, 58, 123, 15,True,itemListenerProc=self.lstbox_selected)
128         self.lstResourceType = self.win.getControl( "lstResourceType" )
129         self.txtReportName=self.win.getControl( "txtReportName" )
130         self.txtReportName.Enable=False
131         for kind in self.Kind.keys():
132             self.lstResourceType.addItem( kind, self.lstResourceType.getItemCount() )
133
134         self.win.addButton( "btnSend", -5, -5, 80, 15, "Send Report to Server", actionListenerProc = self.btnOk_clicked)
135         self.win.addButton( "btnCancel", -5 - 80 -5, -5, 40, 15, "Cancel", actionListenerProc = self.btnCancel_clicked)
136
137         self.win.doModalDialog("lstResourceType", self.Kind.keys()[0])
138
139     def lstbox_selected(self,oItemEvent):
140         pass
141
142     def btnCancel_clicked( self, oActionEvent ):
143         self.win.endExecute()
144
145     def btnOk_clicked(self, oActionEvent):
146         if self.win.getEditText("txtName") <> "" and self.win.getEditText("txtReportName") <> "":
147             desktop=getDesktop()
148             oDoc2 = desktop.getCurrentComponent()
149             docinfo=oDoc2.getDocumentInfo()
150             self.getInverseFieldsRecord(1)
151             fp_name = tempfile.mktemp('.'+"sxw")
152             if not oDoc2.hasLocation():
153                 oDoc2.storeAsURL("file://"+fp_name,Array(makePropertyValue("MediaType","application/vnd.sun.xml.writer"),))
154
155             if docinfo.getUserFieldValue(2)=="":
156                 name=self.win.getEditText("txtName"),
157                 name_id={}
158                 try:
159                     name_id = self.sock.execute(database, uid, self.password, 'ir.actions.report.xml' , 'search',[('name','=',name)])
160                     if not name_id:
161                         id=self.getID()
162                         docinfo.setUserFieldValue(2,id)
163                         rec = {
164                                 'name': self.win.getEditText("txtReportName"),
165                                 'key': 'action',
166                                 'model': docinfo.getUserFieldValue(3),
167                                 'value': 'ir.actions.report.xml,'+str(id),
168                                 'key2': 'client_print_multi',
169                                 'object': True
170                             }
171                         res = self.sock.execute(database, uid, self.password, 'ir.values' , 'create',rec )
172                     else :
173                         ErrorDialog("This name is already used for another report.\nPlease try with another name.", "", "Report Name !")
174                         self.logobj.log_write('SendToServer',LOG_WARNING, ': report name already used DB %s' % (database))
175                         self.win.endExecute()
176                 except Exception,e:
177                     import traceback,sys
178                     info = reduce(lambda x, y: x+y, traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback))
179                     self.logobj.log_write('ServerParameter', LOG_ERROR, info)
180             else:
181
182                 id = docinfo.getUserFieldValue(2)
183                 vId = self.sock.execute(database, uid, self.password, 'ir.values' ,  'search', [('value','=','ir.actions.report.xml,'+str(id))])
184                 rec = { 'name': self.win.getEditText("txtReportName") }
185                 res = self.sock.execute(database, uid, self.password, 'ir.values' , 'write',vId,rec)
186             oDoc2.store()
187             data = read_data_from_file( get_absolute_file_path( oDoc2.getURL()[7:] ) )
188             self.getInverseFieldsRecord(0)
189             #sock = xmlrpclib.ServerProxy(docinfo.getUserFieldValue(0) +'/xmlrpc/object')
190
191             file_type = oDoc2.getURL()[7:].split(".")[-1]
192             res = self.sock.execute(database, uid, self.password, 'ir.actions.report.xml', 'upload_report', int(docinfo.getUserFieldValue(2)),base64.encodestring(data),file_type,{})
193             params = {
194                 'name': self.win.getEditText("txtName"),
195                 'model': docinfo.getUserFieldValue(3),
196                 'report_name': self.win.getEditText("txtReportName"),
197                 'header': (self.win.getCheckBoxState("chkHeader") <> 0),
198                 'report_type': self.Kind[self.win.getListBoxSelectedItem("lstResourceType")],
199             }
200             if self.win.getListBoxSelectedItem("lstResourceType")=='OpenOffice':
201                 params['report_type']=file_type
202             res = self.sock.execute(database, uid, self.password, 'ir.actions.report.xml', 'write', int(docinfo.getUserFieldValue(2)), params)
203             self.logobj.log_write('SendToServer',LOG_INFO, ':Report %s successfully send using %s'%(params['name'],database))
204             self.win.endExecute()
205         else:
206             ErrorDialog("Either report name or technical name is blank.\nPlease specify an appropriate name.","","Blank Field Error !")
207             self.logobj.log_write('SendToServer',LOG_WARNING, ': either report name or technical name is blank.')
208             self.win.endExecute()
209
210     def getID(self):
211         desktop=getDesktop()
212         doc = desktop.getCurrentComponent()
213         docinfo=doc.getDocumentInfo()
214         params = {
215             'name': self.win.getEditText("txtName"),
216             'model': docinfo.getUserFieldValue(3),
217             'report_name': self.win.getEditText('txtReportName')
218         }
219
220
221         id=self.sock.execute(database, uid, self.password, 'ir.actions.report.xml' ,'create', params)
222         return id
223
224     def getInverseFieldsRecord(self,nVal):
225         desktop=getDesktop()
226         doc = desktop.getCurrentComponent()
227         count=0
228         oParEnum = doc.getTextFields().createEnumeration()
229         while oParEnum.hasMoreElements():
230             oPar = oParEnum.nextElement()
231             if oPar.supportsService("com.sun.star.text.TextField.DropDown"):
232                 oPar.SelectedItem = oPar.Items[nVal]
233                 if nVal==0:
234                     oPar.update()
235
236 if __name__<>"package" and __name__=="__main__":
237     SendtoServer(None)
238 elif __name__=="package":
239     g_ImplementationHelper.addImplementation( SendtoServer, "org.openoffice.openerp.report.sendtoserver", ("com.sun.star.task.Job",),)
240
241 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: