-
Notifications
You must be signed in to change notification settings - Fork 1
/
odoo2data_api.py
executable file
·699 lines (654 loc) · 27 KB
/
odoo2data_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
#! /usr/bin/env python3
__copyright__ = "(C) 2021-2024 Guido Draheim, licensed under the Apache License 2.0"""
__version__ = "0.7.3361"
import logging
from typing import List, Dict, Union, Optional, Tuple, Any, cast
import sys
import re
import os.path as path
import json
import requests
import datetime
import dotnetrc
from dotgitconfig import git_config_value
from fnmatch import fnmatchcase as fnmatch
import tabtotext
from tabtotext import JSONList, JSONDict
Cookies = Any
Day = datetime.date
Num = float
UserID = int
SessionID = str
ProjID = int
TaskID = int
ProjREF = Union[ProjID, str]
TaskREF = Union[TaskID, str]
EntryID = int
logg = logging.getLogger(__name__ == "__main__" and path.basename(sys.argv[0]) or __name__)
ODOO_URL = ""
ODOO_DB = ""
dotnetrc.NETRC_CLEARTEXT = True
class OdooException(Exception):
pass
def strDate(val: Union[str, Day]) -> str:
if isinstance(val, (datetime.date, datetime.datetime)):
return val.strftime("%Y-%m-%d")
return val
def odoo_url() -> str:
if ODOO_URL:
return ODOO_URL
value = git_config_value("odoo.url")
if value:
return value
value = git_config_value("zeit.url")
if value:
return value
return "https://example.odoo.com"
def odoo_db() -> str:
""" see https://o2sheet.com/docs/retrieve-odoo-database-name/ """
if ODOO_DB:
return ODOO_DB
value = git_config_value("odoo.db")
if value:
return value
value = git_config_value("zeit.db")
if value:
return value
return "prod-example"
# otter/odoo/rest.py#login
def odoo_login(url: str, db: str, username: str, password: str) -> Tuple[UserID, SessionID]:
request_json = {
"jsonrpc": "2.0",
"params": {
"db": db,
"login": username,
"password": password
}
}
response = requests.post(url + '/web/session/authenticate', json=request_json)
logg.debug("%s", response.json())
# before: and 'result' in response.json():
if response.status_code != 200 or 'error' in response.json():
if 'error' in response.json():
logg.error("Error during login:")
logg.error(" %s", response.json()['error']['data']['message'])
else:
logg.error("Error during login")
raise OdooException("error login")
uid = cast(UserID, response.json()['result']['uid'])
session = cast(SessionID, response.cookies['session_id']) # type: ignore[redundant-cast]
return uid, session
# otter/odoo/rest.py#get_databases_json
def odoo_get_databases(url: str) -> JSONList:
request_json = {
"jsonrpc": "2.0",
"context": {}
}
# endpoint only for Odoo version >= 10
response = requests.get(url + '/web/database/list', json=request_json)
if response.status_code != 200 or 'result' not in response.json():
logg.error("ERROR FETCHING DATABASES")
raise OdooException("error databases")
return response.json()['result'] # type: ignore
# otter/odoo/rest.py#get_projects_json
def odoo_get_projects(url: str, cookies: Cookies) -> JSONList:
request_json = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"model": "project.project",
"fields": [
"id",
"name",
"active"
],
"sort": "id ASC"
}
}
response = requests.post(f"{url}/web/dataset/search_read", json=request_json, cookies=cookies)
if response.status_code != 200 or 'result' not in response.json():
logg.error("ERROR GET PROJECTS")
if "error" in response.json():
logg.error(" %s", response.json()['error']['data']['message'])
return []
return response.json()['result']['records'] # type: ignore
# otter/odoo/rest.py#get_projects_tasks_json
def odoo_get_projects_tasks(url: str, cookies: Cookies) -> JSONList:
request_json = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"model": "project.task",
"domain": [
["project_id", "!=", False]
],
"fields": [
"id",
"name",
"active",
"project_id"
],
"sort": "id ASC"
}
}
response = requests.post(f"{url}/web/dataset/search_read", json=request_json, cookies=cookies)
if response.status_code != 200 or 'result' not in response.json():
logg.error("ERROR GET PROJECT TASKS")
if "error" in response.json():
logg.error(" %s", response.json()['error']['data']['message'])
return []
return response.json()['result']['records'] # type: ignore
def odoo_get_project_tasks(url: str, cookies: Cookies, proj_id: ProjREF) -> JSONList:
request_json = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"model": "project.task",
"domain": [
["project_id", "=", proj_id]
],
"fields": [
"id",
"name",
"active",
"project_id"
],
"sort": "id ASC"
}
}
response = requests.post(f"{url}/web/dataset/search_read", json=request_json, cookies=cookies)
if response.status_code != 200 or 'result' not in response.json():
logg.error("ERROR GET PROJECT TASKS")
logg.debug("%s", response.json())
if "error" in response.json():
logg.error(" %s", response.json()['error']['data']['message'])
return []
return response.json()['result']['records'] # type: ignore
# otter/odoo/rest.py#get_records_json
def odoo_get_timesheet_records(url: str, cookies: Cookies, uid: UserID, entry_date: Optional[Day] = None) -> JSONList:
dateref = datetime.date.today().strftime("%Y-%m-%d")
# logg.debug("date ref = %s", dateref)
if entry_date:
ondate = strDate(entry_date)
logg.debug("ondate %s", ondate)
searching = [
["project_id", "!=", False],
["task_id", "!=", False],
["user_id", "=", uid],
["date", "=", ondate], # <<<<
]
else:
searching = [
["project_id", "!=", False],
["task_id", "!=", False],
["user_id", "=", uid]
]
request_json = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"model": "account.analytic.line",
"domain": searching,
'date': dateref,
"sort": "id ASC"
}
}
response = requests.post(f"{url}/web/dataset/search_read", json=request_json, cookies=cookies)
if response.status_code != 200 or 'result' not in response.json():
logg.error("ERROR GET TIMESHEET")
logg.debug("%s", response.json())
if "error" in response.json():
logg.error(" %s", response.json()['error']['data']['message'])
return []
return response.json()['result']['records'] # type: ignore
def odoo_get_timesheet_record(url: str, cookies: Cookies, uid: UserID, proj_id: ProjREF, task_id: TaskREF, entry_date: Optional[Day] = None) -> JSONList:
dateref = datetime.date.today().strftime("%Y-%m-%d")
# logg.debug("date ref = %s", dateref)
if entry_date:
ondate = strDate(entry_date)
logg.debug("ondate %s", ondate)
searching = [
["project_id", "=", proj_id],
["task_id", "=", task_id],
["user_id", "=", uid],
["date", "=", ondate], # <<<<
]
else:
searching = [
["project_id", "=", proj_id],
["task_id", "=", task_id],
["user_id", "=", uid]
]
request_json = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"model": "account.analytic.line",
"domain": searching,
'date': dateref,
"sort": "id ASC"
}
}
# logg.debug("request %s", request_json)
response = requests.post(f"{url}/web/dataset/search_read", json=request_json, cookies=cookies)
if response.status_code != 200 or 'result' not in response.json():
logg.error("ERROR GET TIMESHEET")
logg.debug("%s", response.json())
if "error" in response.json():
logg.error(" %s", response.json()['error']['data']['message'])
return []
return response.json()['result']['records'] # type: ignore
# otter/odoo/rest.py#post_record
def odoo_add_timesheet_record(url: str, cookies: Cookies, uid: UserID, proj_id: ProjID, task_id: TaskID, entry_date: Day, entry_desc: str, entry_size: Num) -> bool:
request_json = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"args": [
{ # vals=
"date": strDate(entry_date),
"unit_amount": entry_size,
"name": entry_desc,
"project_id": proj_id,
"task_id": task_id
}
],
"model": "account.analytic.line",
"method": "create",
"kwargs": {
"context": {
"uid": uid,
}
}
}
}
response = requests.post(f"{url}/web/dataset/call_kw/account.analytic.line/create", json=request_json,
cookies=cookies)
if response.status_code != 200 or 'result' not in response.json():
logg.error("ERROR SET TIMESHEET")
logg.debug("%s", response.json())
if "error" in response.json():
logg.error(" %s", response.json()['error']['data']['message'])
return False
return response.json()['result'] # type: ignore
def odoo_set_timesheet_record(url: str, cookies: Cookies, uid: UserID, proj_id: ProjID, task_id: TaskID, entry_date: Day, entry_desc: str, entry_size: Num) -> bool:
existing = odoo_get_timesheet_record(url, cookies, uid, proj_id, task_id, entry_date)
if not existing:
return odoo_add_timesheet_record(url, cookies, uid, proj_id, task_id, entry_date, entry_desc, entry_size)
if len(existing) > 1:
logg.error("existing %sx\n%s", len(existing), existing[0])
raise OdooException("found multiple records for account&date")
logg.debug("existing %s", existing)
entry_id = cast(EntryID, existing[0]["id"])
logg.info("update existing record [%s]", entry_id)
return odoo_write_timesheet_record(url, cookies, uid, entry_id, proj_id, task_id, entry_date, entry_desc, entry_size)
def odoo_write_timesheet_record(url: str, cookies: Cookies, uid: UserID, entry_id: EntryID, proj_id: ProjID, task_id: TaskID, entry_date: Day, entry_desc: str, entry_size: Num) -> bool:
request_json = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"args": [[entry_id], # ids=
{ # vals=
"unit_amount": entry_size,
"name": entry_desc,
"date": strDate(entry_date),
"project_id": proj_id,
"task_id": task_id
}
],
"model": "account.analytic.line",
"method": "write",
"kwargs": {
"context": {
"uid": uid,
}
}
}
}
response = requests.post(f"{url}/web/dataset/call_kw/account.analytic.line/write", json=request_json,
cookies=cookies)
if response.status_code != 200 or 'result' not in response.json():
logg.error("ERROR SET TIMESHEET")
logg.debug("%s", response.json())
if "error" in response.json():
logg.error(" %s", response.json()['error']['data']['message'])
return False
return response.json()['result'] # type: ignore
def odoo_delete_timesheet_record(url: str, cookies: Cookies, uid: UserID, entry_id: EntryID) -> bool:
request_json = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"args": [[entry_id], # ids=
],
"model": "account.analytic.line",
"method": "unlink",
"kwargs": {
"context": {
"uid": uid,
}
}
}
}
response = requests.post(f"{url}/web/dataset/call_kw/account.analytic.line/unlink", json=request_json,
cookies=cookies)
if response.status_code != 200 or 'result' not in response.json():
logg.error("ERROR SET TIMESHEET")
logg.debug("%s", response.json())
if "error" in response.json():
logg.error(" %s", response.json()['error']['data']['message'])
return False
return response.json()['result'] # type: ignore
def odoo_get_users(url: str, cookies: Cookies) -> JSONList:
request_json = {
"jsonrpc": "2.0",
"method": "call",
"params": {
"model": "res.users",
"fields": [
"id",
"name",
"email",
"active",
],
"sort": "id ASC"
}
}
response = requests.post(f"{url}/web/dataset/search_read", json=request_json, cookies=cookies)
if response.status_code != 200 or 'result' not in response.json():
logg.error("ERROR GET USERS")
if "error" in response.json():
logg.error(" %s", response.json()['error']['data']['message'])
return []
return response.json()['result']['records'] # type: ignore
# https://www.odoo.com/documentation/10.0/api_integration.html
# search / search_read / search_count
# fields_get
# create / write / unlink (add, update, remote)
class OdooConfig:
url: str
db: str
user: Optional[str]
site: Optional[str]
def __init__(self, url: Optional[str] = None, db: Optional[str] = None, *, #
user: Optional[str] = None, site: Optional[str] = None):
self.url: str = url or odoo_url()
self.db: str = db or odoo_db()
self.site: Optional[str] = site
self.user: Optional[str] = user
def name(self) -> str:
if self.site:
return self.site
return self.db
def on_site(self, site: str) -> "OdooConfig":
self.site = site
return self
def for_user(self, user: str) -> "OdooConfig":
self.user = user
return self
class Odoo:
def __init__(self, config: Optional[OdooConfig] = None):
self.config: OdooConfig = config or OdooConfig()
self.uid: Optional[UserID] = None
self.sid: Optional[str] = None
self._projtasklist: Optional[JSONList] = None
logg.debug("URL %s DB %s", self.url, self.config.db)
self.user_name: Optional[str] = None
@property
def url(self) -> str:
return self.config.url
@property
def db(self) -> str:
return self.config.db
@property
def user(self) -> str:
if self.user_name:
return self.user_name
return self.config.user or ""
def login(self) -> UserID:
username, password = dotnetrc.get_username_password(self.config.url)
uid, sid = odoo_login(self.url, self.db, username, password)
self.uid = uid
self.sid = sid
if self.user:
self.uid = self.get_user_id(self.user)
return self.uid
def from_login(self) -> UserID:
if not self.uid:
return self.login()
return self.uid
def for_user(self, name: str) -> "Odoo":
if not self.uid:
self.uid = self.login()
if name:
self.uid = self.get_user_id(name)
self.user_name = name
return self
def get_user_id(self, name: str, default: Optional[UserID] = None) -> UserID:
uid = default or -1
users = self.users()
if name.endswith("@"):
emailname = name.lower().strip()[:-1]
for user in users:
if "user_email" not in user: continue
attr = cast(str, user["user_email"])
if attr.lower().strip().split("@", 1)[0] == emailname:
uid = cast(UserID, user["user_id"])
elif "@" in name:
email = name.lower().strip()
for user in users:
if "user_email" not in user: continue
attr = cast(str, user["user_email"])
if attr.lower().strip() == email:
uid = cast(UserID, user["user_id"])
elif "*" in name:
named = name.lower().strip().replace(" ", ".")
for user in users:
if "user_fullname" not in user: continue
attr = cast(str, user["user_fullname"])
if fnmatch(attr.lower().strip().replace(" ", "."), named):
uid = cast(UserID, user["user_id"])
else:
named = name.lower().strip().replace(" ", ".")
for user in users:
if "user_fullname" not in user: continue
attr = cast(str, user["user_fullname"])
if attr.lower().strip().replace(" ", ".") == named:
uid = cast(UserID, user["user_id"])
return uid
def databases(self) -> List[str]:
found = odoo_get_databases(self.url)
logg.info("%s", found)
return cast(List[str], found)
def cookies(self) -> Cookies:
uid = self.from_login()
return requests.utils.cookiejar_from_dict({"session_id": self.sid}) # type: ignore
def users(self) -> JSONList:
found = odoo_get_users(self.url, self.cookies())
return [{"user_id": item["id"], "user_fullname": item["name"], "user_email": item["email"]} for item in found if item["active"]]
def projects(self) -> JSONList:
found = odoo_get_projects(self.config.url, self.cookies())
return [{"proj_id": item["id"], "proj_name": item["name"]} for item in found if item["active"]]
def projects_tasks(self) -> JSONList:
found = odoo_get_projects_tasks(self.config.url, self.cookies())
return [{"task_id": item["id"], "task_name": item["name"],
"proj_id": item["project_id"][0], "proj_name": item["project_id"][1], # type: ignore
} for item in found if item["active"]]
def project_tasks(self, proj_id: ProjREF = 89) -> JSONList:
found = odoo_get_project_tasks(self.url, self.cookies(), proj_id)
return [{"task_id": item["id"], "task_name": item["name"],
"proj_id": item["project_id"][0], "proj_name": item["project_id"][1], # type: ignore
} for item in found if item["active"]]
def projtasklist(self) -> JSONList:
if self._projtasklist is None:
data = self.projects_tasks()
self._projtasklist = data
return data
return self._projtasklist
def proj_id(self, proj_id: ProjREF) -> int:
if isinstance(proj_id, int):
return proj_id
projtask = self.projtasklist()
for item in projtask:
if item["proj_name"] == proj_id:
return cast(int, item["proj_id"])
logg.warning("could not resolve proj_id '%s'", proj_id)
return proj_id # type: ignore
def task_id(self, proj_id: ProjREF, task_id: TaskREF) -> int:
if isinstance(task_id, int):
return task_id
projtask = self.projtasklist()
for item in projtask:
if str(proj_id) == item["proj_name"] or str(proj_id) == str(item["proj_id"]):
if item["task_name"] == task_id:
return cast(int, item["task_id"])
logg.warning("could not resolve task_id '%s' for proj_id '%s'", task_id, proj_id)
return task_id # type: ignore
def clean(self, rec: JSONDict) -> JSONDict:
for key in list(rec.keys()):
if key.startswith("display_"):
del rec[key]
for name in ["__last_update", "account_id", "create_date", "create_uid", "write_date", "write_uid",
"department_id", "general_account_id", "group_id", "holiday_id", "user_timer_id", "is_timer_running",
"is_so_line_edited", "l10n_de_document_title", "l10n_de_template_data", "move_id", "ref", "so_line",
"partner_id", "project_user_id", "tag_ids", "timer_pause", "timer_start", "timesheet_invoice_id"]:
if name in rec:
del rec[name]
return rec
def timesheet_records(self, date: Optional[datetime.date] = None) -> JSONList:
uid = self.from_login()
found = odoo_get_timesheet_records(self.url, self.cookies(), uid, date)
# logg.info("%s", found)
for rec in found:
self.clean(rec)
if found:
logg.debug("%s", found[0])
return [{"proj_id": item["project_id"][0], "proj_name": item["project_id"][1], # type: ignore
"task_id": item["task_id"][0], "task_name": item["task_id"][1], # type: ignore
"user_id": item["user_id"][0], "user_name": item["user_id"][1], # type: ignore
"entry_size": item["unit_amount"], "entry_desc": item["name"], # type: ignore
"entry_id": item["id"], "entry_date": item["date"],
} for item in found]
def timesheet_record(self, proj: str, task: str, date: Optional[datetime.date] = None) -> JSONList:
uid = self.from_login()
found = odoo_get_timesheet_record(self.url, self.cookies(), uid, proj, task, date)
# logg.info("%s", found)
for rec in found:
self.clean(rec)
if found:
logg.debug("%s", found[0])
return [{"proj_id": item["project_id"][0], "proj_name": item["project_id"][1], # type: ignore
"task_id": item["task_id"][0], "task_name": item["task_id"][1], # type: ignore
"user_id": item["user_id"][0], "user_name": item["user_id"][1], # type: ignore
"entry_size": item["unit_amount"], "entry_desc": item["name"], # type: ignore
"entry_id": item["id"], "entry_date": item["date"],
} for item in found]
def timesheet_delete(self, entry_id: EntryID) -> bool:
uid = self.from_login()
found = odoo_delete_timesheet_record(self.url, self.cookies(), uid, #
entry_id)
logg.info("deleted %s", found)
return found # bool
def timesheet_write(self, entry_id: EntryID, proj: ProjREF, task: TaskREF, date: Day, time: Num, desc: str) -> bool:
uid = self.from_login()
proj_id = self.proj_id(proj)
task_id = self.task_id(proj, task)
found = odoo_write_timesheet_record(self.url, self.cookies(), uid, #
entry_id, proj_id, task_id, #
entry_date=date, entry_size=time, entry_desc=desc)
logg.info("written %s", found)
return found # bool
def timesheet_create(self, proj: ProjREF, task: TaskREF, date: Day, time: Num, desc: str) -> bool:
uid = self.from_login()
proj_id = self.proj_id(proj)
task_id = self.task_id(proj, task)
found = odoo_add_timesheet_record(self.url, self.cookies(), uid, proj_id, task_id,
entry_date=date, entry_size=time, entry_desc=desc)
logg.info("created %s", found)
return found # bool
def timesheet_update(self, proj: ProjREF, task: TaskREF, date: Day, time: Num, desc: str) -> bool:
uid = self.from_login()
proj_id = self.proj_id(proj)
task_id = self.task_id(proj, task)
found = odoo_set_timesheet_record(self.url, self.cookies(), uid, proj_id, task_id,
entry_date=date, entry_size=time, entry_desc=desc)
logg.info("updated %s", found)
return found # bool
def timesheet(self, after: Day, before: Optional[Day] = None) -> JSONList:
if not before:
before = datetime.date.today()
if after > before:
logg.error("--after=DAY must be --before=DAY")
raise OdooException("bad timespan for timesheet()")
timespan = before - after
if timespan.days > 63:
logg.warning("--after=%s --before=%s is %s days", after.isoformat(), before.isoformat(), timespan.days + 1)
else:
logg.info("--after=%s --before=%s is %s days", after.isoformat(), before.isoformat(), timespan.days + 1)
ondate = after
records: JSONList = []
for attempt in range(366):
logg.debug("ondate %s (after %s before %s)", ondate.isoformat(), after.isoformat(), before.isoformat())
found = self.timesheet_records(ondate)
if found:
for record in found:
records.append(record)
if ondate == before:
break
ondate += datetime.timedelta(days=1)
return records
###########################################################################################
def run(arg: str) -> None:
if arg in ["help"]:
cmdline.print_help()
print("\nCommands:")
previous = ""
for line in open(__file__):
if previous.strip().replace("elif arg", "if arg").startswith("if arg in"):
if "#" in line:
print(previous.strip().split(" arg in")[1], line.strip().split("#")[1])
else:
print(previous.strip().split(" arg in")[1], line.strip())
previous = line
raise SystemExit()
if arg in ["dbs", "databases"]:
odoo = Odoo()
logg.info(" ODOO URL %s DB %s", odoo.url, odoo.db)
print(", ".join(odoo.databases()))
if arg in ["pjs", "projects"]:
odoo = Odoo()
logg.info(" ODOO URL %s DB %s", odoo.url, odoo.db)
data = odoo.projects()
text = tabtotext.tabtoGFM(data, ["proj_name:'%s'", "proj_id"])
print(text)
if arg in ["tks", "tasks"]:
odoo = Odoo()
logg.info(" ODOO URL %s DB %s", odoo.url, odoo.db)
data = odoo.projects_tasks()
text = tabtotext.tabtoGFM(data, ["proj_name:'%s'", "task_name:'%s'"])
print(text)
if arg in ["tks1", "tasks1"]:
odoo = Odoo()
logg.info(" ODOO URL %s DB %s", odoo.url, odoo.db)
data = odoo.project_tasks()
text = tabtotext.tabtoGFM(data, ["proj_name:'%s'", "task_name:'%s'"])
print(text)
def reset() -> None:
pass # only defined in the mockup
if __name__ == "__main__":
from optparse import OptionParser
cmdline = OptionParser("%prog [-options] [help|commands...]", version=__version__)
cmdline.add_option("-v", "--verbose", action="count", default=0, help="more verbose logging")
cmdline.add_option("-^", "--quiet", action="count", default=0, help="less verbose logging")
cmdline.add_option("-g", "--gitcredentials", metavar="FILE", default="~/.netrc")
cmdline.add_option("-d", "--db", metavar="name", default=ODOO_DB)
cmdline.add_option("-e", "--url", metavar="url", default=ODOO_URL)
opt, args = cmdline.parse_args()
logging.basicConfig(level=max(0, logging.WARNING - 10 * opt.verbose + 10 * opt.quiet))
dotnetrc.set_password_filename(opt.gitcredentials)
ODOO_URL = opt.url
ODOO_DB = opt.db
if not args:
args = ["projects"]
for arg in args:
run(arg)