forked from NaN-tic/tryton-tasks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gal.py
2116 lines (1814 loc) · 63.2 KB
/
gal.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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: utf-8
#!/usr/bin/env python
import os
import sys
import time
import subprocess
import hgapi
import random
import json
import datetime
from . import iban
import traceback
try:
from functools32 import lru_cache
except:
from functools import lru_cache
from dateutil.relativedelta import relativedelta
from datetime import timedelta
from decimal import Decimal
from invoke import task, Collection
from .utils import t
global restore_step
global commit_msg
restore_step = True
directory = os.path.abspath(os.path.normpath(os.path.join(os.getcwd(),
'trytond')))
proteus_directory = os.path.abspath(os.path.normpath(os.path.join(os.getcwd(),
'proteus')))
if os.path.isdir(directory):
sys.path.insert(0, directory)
if os.path.isdir(proteus_directory):
sys.path.insert(0, proteus_directory)
try:
from proteus import config as pconfig, Model, Wizard
except:
pass
TODAY = datetime.date.today()
commits_enabled = True
def random_datetime(start, end):
"""
This function will return a random datetime between two datetime
objects.
"""
delta = end - start
int_delta = (delta.days * 24 * 60 * 60) + delta.seconds
random_second = random.randrange(int_delta)
return start + timedelta(seconds=random_second)
def check_output(*args):
print(t.bold(' '.join(args)))
process = subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
data = stdout + stderr
if process.returncode:
if stdout and stderr:
print(stdout, t.red(stderr))
elif stdout:
print(stdout)
elif stderr:
print(t.red(stderr))
else:
print(t.green('Ok'))
return data
# Execute method that shows the exception and line number of the 'exec' call.
# Snippet taken from:
# https://stackoverflow.com/questions/28836078/how-to-get-the-line-number-of-an-error-from-exec-or-execfile-in-python
class InterpreterError(Exception): pass
def execute(cmd, globals=None, locals=None, description='source string'):
try:
exec(cmd, globals, locals)
except SyntaxError as err:
error_class = err.__class__.__name__
detail = err.args[0]
line_number = err.lineno
except Exception as err:
error_class = err.__class__.__name__
detail = err.args[0]
cl, exc, tb = sys.exc_info()
line_number = traceback.extract_tb(tb)[-1][1]
else:
return
raise InterpreterError("%s at line %d of %s: %s" % (error_class, line_number, description, detail))
def connect_database(database=None, password='admin',
database_type='postgresql', language=None):
if database is None:
database = 'gal'
global config
global version
os.environ['TRYTOND_DATABASE_URI'] = '%s:///' % database_type
os.environ['DB_NAME'] = database
# Tries to use sqlite without these two lines:
from trytond.config import config
config.set('database', 'uri', '%s://' % database_type)
from trytond.tests.test_tryton import db_exist
if not db_exist():
try:
from trytond.protocols.dispatcher import create as tcreate
if language is None:
language = 'en_US'
tcreate(None, database, None, language, password)
except:
from trytond.tests.test_tryton import create_db as tcreate
if language is None:
language = 'en'
tcreate(database, language)
config = pconfig.set_trytond(database, config_file='trytond.conf')
config.pool.test = False
def database_name():
import uuid
return uuid.uuid4()
def dump(dbname=None):
if dbname is None:
dbname = 'gal'
from trytond import backend
Database = backend.get('Database')
Database(dbname).close()
Database('template1').close()
# Sleep to let connections close
time.sleep(1)
dump_file = 'gal.sql'
# Ensure gal repository exists before dump
gal_repo()
check_output('pg_dump', '-f', gal_path(dump_file), dbname)
gal_repo().hg_add(dump_file)
def dropdb(dbname=None):
if dbname is None:
dbname = 'gal'
check_output('dropdb', dbname)
def restore(dbname=None):
global restore_step
if not restore_step:
return
if dbname is None:
dbname = 'gal'
dump_file = 'gal.sql'
dropdb(dbname)
check_output('createdb', dbname)
check_output('psql', '-f', gal_path(dump_file), dbname)
def gal_path(path=None):
res = 'gal'
if path:
res = os.path.join(res, path)
return res
def gal_repo():
path = gal_path()
if os.path.exists(path) and not os.path.isdir(path):
print(t.red('Error: gal file exists'), file=sys.stderr)
sys.exit(1)
if os.path.isdir(path) and not os.path.isdir(os.path.join(path, '.hg')):
print(t.red('Invalid gal repository'), file=sys.stderr)
sys.exit(1)
repo = hgapi.Repo(path)
if not os.path.exists(path):
os.mkdir(path)
repo.hg_init()
return repo
def gal_action(action, **kwargs):
global commit_msg
commit_msg = json.dumps((action, kwargs))
def gal_commit(do_dump=True):
if not commits_enabled:
return
if do_dump:
dump()
gal_repo().hg_commit(commit_msg)
@lru_cache()
def module_activated(module):
Module = Model.get('ir.module')
return bool(Module.find([
('name', '=', module),
('state', '=', 'active'),
]))
@task()
def create(ctx, language=None, password=None):
"""
Creates a new tryton database and stores it in the gal repository.
"""
gal_repo()
gal_action('create', language=language, password=password)
dropdb()
connect_database(language=language)
gal_commit()
@task()
def replay(ctx, name):
"""
Executes all steps needed to create a database like the one in the gal
repository.
"""
repo = gal_repo()
print('Actions to replay:')
has_set = False
for revision in repo.revisions(slice(0, 'tip')):
description = revision.desc
action, parameters = json.loads(description)
if action == 'set':
has_set = True
print(t.bold('%s(%s)' % (action, parameters)))
print()
if has_set:
print(t.red('It is not possible to replay tip '
'version because there is a set() operation in the list of '
'commands to execute'), file=sys.stderr)
sys.exit(1)
# Disable commits before replaying
commits_enabled = False
# Just add this line to avoid pyflakes warnings
commits_enabled
print('Replaying actions:')
for revision in repo.revisions(slice(0, 'tip')):
description = revision.desc
action, parameters = json.loads(description)
print(t.bold('%s(%s)' % (action, parameters)))
# TODO: This is not safe. Run with care.
eval('%s(%s)' % (action, parameters))
@task()
def get(ctx, name):
"""
Restores current gal database with the given database name
"""
restore(name)
@task()
def set(ctx, name):
"""
Saves the given database as current gal database
"""
gal_action('set')
dump(name)
gal_commit(do_dump=False)
@task()
def build(ctx, filename=None, no_restore=False):
"""
Creates a database with the commands found in the specified filename.
If no filename is given it will search for a file named 'Galfile'
"""
if filename is None:
filename = 'Galfile'
print("Building %s..." % filename)
global restore_step
restore_step = True
if no_restore:
restore_step = False
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
print(t.bold(str(line)))
splitted = line.split('(')
line = splitted[0] + '(ctx, ' + splitted[1]
eval(line)
@task()
def galfile(ctx):
"""
Prints the Galfile to be used to reproduce current gal database.
The result can be used by gal.build operation.
"""
repo = gal_repo()
has_set = False
for revision in repo.revisions(slice(0, 'tip')):
description = revision.desc
action, parameters = json.loads(description)
if action == 'set':
has_set = True
if has_set:
print(t.red('It will not be possible to build the '
'generated Galfile because it contains at least one set command.'), file=sys.stderr)
# Disable commits before replaying
for revision in repo.revisions(slice(0, 'tip')):
description = revision.desc
action, parameters = json.loads(description)
print('%s(**%s)' % (action, parameters))
@task()
def execute_script(ctx, script):
gal_action('execute_script', script=script)
restore()
connect_database()
if script.endswith('.rst'):
import unittest
import doctest
import trytond.tests.test_tryton
suite = trytond.tests.test_tryton.suite()
suite.addTests(doctest.DocFileSuite(script, module_relative=False,
encoding='utf-8'))
result = unittest.TestResult()
suite.run(result)
if result.errors or result.failures:
if result.errors:
print("Errors:")
for error in result.errors:
print(error[0])
print(error[1])
print()
print()
if result.failures:
print("Failures:")
for failure in result.failures:
print(failure[0])
print(failure[1])
print()
# Ensure we do not commit
return
elif script.endswith('.py'):
with open(script, 'r') as f:
code = f.read()
execute(code)
else:
print(t.red("Don't know how to execute %s" % script), file=sys.stderr)
sys.exit(1)
gal_commit()
#
# Extension commands
#
@task()
def update_all(ctx):
"""
Update all modules. Equivalent to execute trytond with "-u all" parameter
"""
gal_action('update_all')
restore()
connect_database()
upgraded_modules = upgrade_modules(all=True)
gal_commit()
return upgraded_modules
def upgrade_modules(modules=None, all=False):
'''
Function get from tryton_demo.py in tryton-tools repo:
http://hg.tryton.org/tryton-tools
'''
assert all or modules
Module = Model.get('ir.module')
if all:
modules = Module.find([
('state', '=', 'activated'),
])
else:
modules = Module.find([
('name', 'in', modules),
('state', '=', 'activated'),
])
Module.upgrade([x.id for x in modules], config.context)
Wizard('ir.module.activate_upgrade').execute('upgrade')
ConfigWizardItem = Model.get('ir.module.config_wizard.item')
for item in ConfigWizardItem.find([('state', '!=', 'done')]):
item.state = 'done'
item.save()
upgraded_modules = [x.name for x in Module.find([
('state', '=', 'to_upgrade'),
])]
return upgraded_modules
@task()
def set_active_languages(ctx, lang_codes=None):
"""
Sets the given languages (for example 'ca_ES,es_ES') as active languages
in the database.
If no languages are given 'ca_ES,es_ES' are used by default.
"""
gal_action('set_active_languages', lang_codes=lang_codes)
restore()
connect_database()
if lang_codes:
lang_codes = lang_codes.split(',')
Lang = Model.get('ir.lang')
User = Model.get('res.user')
if not lang_codes:
lang_codes = ['ca_ES', 'es_ES']
langs = Lang.find([
('code', 'in', lang_codes),
])
assert len(langs) > 0
Lang.write([l.id for l in langs], {
'translatable': True,
}, config.context)
default_langs = [l for l in langs if l.code == lang_codes[0]]
if not default_langs:
default_langs = langs
users = User.find([])
if users:
User.write([u.id for u in users], {
'language': default_langs[0].id,
}, config.context)
# Reload context
User = Model.get('res.user')
config._context = User.get_preferences(True, config.context)
if not all(l.translatable for l in langs):
# langs is fetched before wet all translatable
print("Upgrading all because new translatable languages has been added")
upgrade_modules(config, all=True)
gal_commit()
@task()
def activate_modules(ctx, modules):
'''
Installs the given modules (for example, 'party,product') to current gal
database.
Function taken from tryton_demo.py in tryton-tools repo:
http://hg.tryton.org/tryton-tools
'''
gal_action('activate_modules', modules=modules)
restore()
connect_database()
# Clear cache
module_activated.cache_clear()
modules = modules.split(',')
Module = Model.get('ir.module')
modules = Module.find([
('name', 'in', modules),
#('state', '!=', 'activated'),
])
Module.activate([x.id for x in modules], config.context)
modules = [x.name for x in Module.find([
('state', 'in', ('to activate', 'to upgrade')),
])]
Wizard('ir.module.activate_upgrade').execute('upgrade')
ConfigWizardItem = Model.get('ir.module.config_wizard.item')
for item in ConfigWizardItem.find([('state', '!=', 'done')]):
item.state = 'done'
item.save()
activated_modules = [m.name
for m in Module.find([('state', '=', 'activated')])]
gal_commit()
return modules, activated_modules
@task()
def load_countries(ctx):
gal_action('load_countries')
restore()
check_output(
'./trytond/trytond/modules/country/scripts/import_countries.py',
'-d', 'gal')
gal_commit()
@task()
def load_zips(ctx, country):
gal_action('load_zips')
restore()
check_output(
'./trytond/trytond/modules/country/scripts/import_zip.py',
'-d', 'gal', country)
gal_commit()
@task()
def load_currencies(ctx):
gal_action('load_currencies')
restore()
check_output(
'./trytond/trytond/modules/currency/scripts/import_currencies.py',
'-d', 'gal')
gal_commit()
@task()
def load_spanish_banks(ctx):
'''
Execute Load Spanish Banks wizard. Requires bank_es module
'''
gal_action('load_spanish_banks')
restore()
connect_database()
Wizard('load.banks').execute('accept')
gal_commit()
@lru_cache()
def get_payment_terms():
Term = Model.get('account.invoice.payment_term')
return Term.find([])
@lru_cache()
def get_payment_types(kind):
Type = Model.get('account.payment.type')
return Type.find([('kind', '=', kind)])
@lru_cache()
def get_languages():
Lang = Model.get('ir.lang')
return Lang.find([
('code', 'in', ['ca', 'es', 'en']),
])
@lru_cache()
def get_price_lists():
PriceList = Model.get('product.price_list')
return PriceList.find([])
@lru_cache()
def get_banks():
if not module_activated('bank'):
return
Bank = Model.get('bank')
return Bank.find([])
@lru_cache()
def get_company():
Company = Model.get('company.company')
companies = Company.find([])
if companies:
return companies[0]
@lru_cache()
def get_model_id(module, fs_id):
ModelData = Model.get('ir.model.data')
data, = ModelData.find([
('module', '=', 'account_es'),
('fs_id', '=', fs_id),
])
return data.model, data.db_id
def get_object(module, fs_id):
model, id = get_model_id(module, fs_id)
Class = Model.get(model)
return Class(id)
def create_party(name, street=None, zip=None, city=None,
subdivision_code=None, country_code='ES', phone=None, website=None,
email=None, address_name=None, account_payable=None,
account_receivable=None):
Address = Model.get('party.address')
ContactMechanism = Model.get('party.contact_mechanism')
Country = Model.get('country.country')
Party = Model.get('party.party')
Subdivision = Model.get('country.subdivision')
parties = Party.find([('name', '=', name)])
if parties:
return parties[0]
country, = Country.find([('code', '=', country_code)])
if subdivision_code:
subdivision, = Subdivision.find([('code', '=', subdivision_code)])
else:
subdivision = None
if zip is None:
# Create a ZIP from Barcelona if none was provided
zip = '08' + str(random.randrange(1000)).zfill(3)
party = Party(name=name)
party.addresses.pop()
party.addresses.append(
Address(
name=address_name,
street=street,
zip=zip,
city=city,
country=country,
subdivision=subdivision))
if phone:
party.contact_mechanisms.append(
ContactMechanism(type='phone',
value=phone))
if website:
party.contact_mechanisms.append(
ContactMechanism(type='website',
value=website))
if email:
party.contact_mechanisms.append(
ContactMechanism(type='email',
value=email))
party.lang = random.choice(get_languages())
if account_payable:
party.account_payable = account_payable
if account_receivable:
party.account_receivable = account_receivable
if hasattr(party, 'customer_payment_term'):
terms = get_payment_terms()
if terms:
term = random.choice(terms)
party.customer_payment_term = term
party.supplier_payment_term = term
if hasattr(party, 'customer_payment_type'):
types = get_payment_types('receivable')
if types:
party.customer_payment_type = random.choice(types)
if hasattr(party, 'customer_payment_type'):
types = get_payment_types('payable')
if types:
party.supplier_payment_type = random.choice(types)
if hasattr(party, 'sale_price_list'):
price_lists = get_price_lists()
if price_lists:
party.sale_price_list = random.choice(price_lists)
if hasattr(party, 'include_347'):
party.include_347 = True
party.save()
return party
@task()
def create_random_parties(ctx, count=4000):
"""
Create 'count' parties taking random information from the following files:
- companies.txt
- streets.txt
- names.txt
- surnames.txt
"""
gal_action('create_random_parties', count=count)
restore()
connect_database()
with open('tasks/gal_files/companies.txt', 'r') as f:
companies = f.read().split('\n')
companies = [x.strip() for x in companies if x.strip()]
with open('tasks/gal_files/streets.txt', 'r') as f:
streets = f.read().split('\n')
streets = [x.strip() for x in streets if x.strip()]
with open('tasks/gal_files/names.txt', 'r') as f:
names = f.read().split('\n')
names = [x.strip() for x in names if x.strip()]
with open('tasks/gal_files/surnames.txt', 'r') as f:
surnames = f.read().split('\n')
surnames = [x.strip() for x in surnames if x.strip()]
phones = ['93', '972', '973', '977', '6', '900']
for x in range(count):
company = random.choice(companies)
name = random.choice(names)
surname1 = random.choice(surnames)
surname2 = random.choice(surnames)
street = random.choice(streets)
name = '%s %s, %s' % (surname1, surname2, name)
street = '%s, %d' % (street, random.randrange(1, 100))
phone = random.choice(phones)
while len(phone) < 9:
phone += str(random.randrange(9))
create_party(company, street=street, zip=None, city=None,
subdivision_code=None, country_code='ES', phone=phone,
website=None, address_name=name)
gal_commit()
@task()
def create_parties(ctx, count=1000):
"""
Create 'count' parties taking random information from the following files:
- companies.txt
- streets.txt
- names.txt
- surnames.txt
"""
gal_action('create_parties', count=count)
restore()
connect_database()
with open('tasks/gal_files/companies.txt', 'r') as f:
companies = f.read().split('\n')
companies = [x.strip() for x in companies if x.strip()]
companies = random.sample(companies, min(len(companies), count))
with open('tasks/gal_files/streets.txt', 'r') as f:
streets = f.read().split('\n')
streets = [x.strip() for x in streets if x.strip()]
with open('tasks/gal_files/names.txt', 'r') as f:
names = f.read().split('\n')
names = [x.strip() for x in names if x.strip()]
with open('tasks/gal_files/surnames.txt', 'r') as f:
surnames = f.read().split('\n')
surnames = [x.strip() for x in surnames if x.strip()]
phones = ['93', '972', '973', '977', '6', '900']
for company in companies:
name = random.choice(names)
surname1 = random.choice(surnames)
surname2 = random.choice(surnames)
street = random.choice(streets)
name = '%s %s, %s' % (surname1, surname2, name)
street = '%s, %d' % (street, random.randrange(1, 100))
phone = random.choice(phones)
while len(phone) < 9:
phone += str(random.randrange(9))
create_party(company, street=street, zip=None, city=None,
subdivision_code=None, country_code='ES', phone=phone,
website=None, address_name=name)
gal_commit()
@task()
def create_bank_accounts(ctx):
gal_action('create_bank_accounts')
restore()
connect_database()
Party = Model.get('party.party')
Invoice = Model.get('account.invoice')
banks = get_banks()
if not module_activated('account_bank'):
print(t.red('account_bank module must be activated before creating '
'bank accounts.'))
good_number = None
for party in Party.find([]):
BankAccount = Model.get('bank.account')
AccountNumber = Model.get('bank.account.number')
bank = random.choice(banks)
account = BankAccount()
party.bank_accounts.append(account)
account.bank = bank
number = AccountNumber()
account.numbers.append(number)
country = 'ES'
number.type = 'iban'
if not good_number:
while True:
account_code = bank.bank_code
account_code += ''.join([str(x) for x in random.sample(list(range(10)) *
4, 4)])
account_number = ''.join([str(x) for x in random.sample(list(range(10)) *
12, 12)])
number.number = iban.create_iban(country, account_code,
account_number)
print('Looping...', number.number)
#x = iban.check_iban(number.number)
try:
good_number = number.number
account.save()
print('Ok!')
break
except Exception as e:
print('Exception: ', str(e))
pass
else:
number.number = good_number
account.save()
if module_activated('account_bank'):
if hasattr(party, 'payable_bank_account'):
party.payable_bank_account = account
if hasattr(party, 'receivable_bank_account'):
party.receivable_bank_account = account
if hasattr(party, 'payable_company_bank_account'):
company = get_company()
if company:
accounts = company.party.bank_accounts
if accounts:
party.receivable_company_bank_account = accounts[0]
if hasattr(party, 'receivable_company_bank_account'):
company = get_company()
if company:
accounts = company.party.bank_accounts
if accounts:
party.payable_company_bank_account = accounts[0]
for invoice in Invoice.find([('party', '=', party.id)]):
if (invoice.payment_type
and invoice.payment_type.account_bank == 'party'):
invoice.bank_account = account
invoice.save()
party.save()
gal_commit()
@task()
def create_product_category(ctx, name):
"""
Creates product category with the supplied name.
"""
gal_action('create_product_category', name=name)
restore()
connect_database()
Category = Model.get('product.category')
category = Category(name=name)
category.save()
gal_commit()
@task()
def create_product_categories(ctx, count=20):
"""
Creates 'count' (20 by default) product categories.
"""
gal_action('create_product_categories', count=count)
restore()
connect_database()
Category = Model.get('product.category')
for name in ('A', 'B', 'C', 'D', 'E'):
category = Category(name=name)
category.save()
gal_commit()
def create_product(name, code="", template=None, cost_price=None,
list_price=None, type='goods', unit=None, consumable=False):
ProductUom = Model.get('product.uom')
Product = Model.get('product.product')
ProductTemplate = Model.get('product.template')
Tax = Model.get('account.tax')
Category = Model.get('product.category')
categories = Category.find([])
category = None
if categories:
category = random.choice(categories)
product = Product.find([('name', '=', name), ('code', '=', code)])
if product:
return product[0]
if not cost_price:
cost_price = Decimal(random.randrange(1, 100))
if not list_price:
list_price = cost_price * (1 + Decimal(random.randrange(1, 100)) / 100)
if unit is None:
unit = ProductUom(1)
if template is None:
template = ProductTemplate()
template.name = name
template.default_uom = unit
template.type = type
template.consumable = consumable
template.list_price = list_price
template.cost_price = cost_price
template.category = category
if hasattr(template, 'salable'):
template.salable = True
if hasattr(template, 'purchasable'):
template.purchasable = True
if hasattr(template, 'producible'):
template.producible = True
if (hasattr(template, 'account_expense')
or hasattr(template, 'account_revenue')):
Company = Model.get('company.company')
company = Company(1)
if hasattr(template, 'account_expense'):
Account = Model.get('account.account')
expense = Account.find([
('type.expense', '=', True),
('company', '=', company.id),
])
if expense:
template.account_expense = expense[0]
if hasattr(template, 'account_revenue'):
Account = Model.get('account.account')
revenue = Account.find([
('type.revenue', '=', True),
('company', '=', company.id),
])
if revenue:
template.account_revenue = revenue[0]
if module_activated('account_es'):
if hasattr(template, 'customer_taxes'):
tax, = Tax.find([
('template', '=',
get_object('account_es', 'iva_rep_21').id)
])
template.customer_taxes.append(tax)
if hasattr(template, 'supplier_taxes'):
tax, = Tax.find([
('template', '=',
get_object('account_es', 'iva_sop_21').id)
])
template.supplier_taxes.append(tax)
template.products[0].code = code
template.save()
product = template.products[0]
else:
product = Product()
product.template = template
product.code = code
product.save()
return product
@task()
def create_products(ctx, count=400):
"""
Creates the 'count' first products from the icecat database in catalog.xml.
"""
gal_action('create_products', count=count)
restore()
connect_database()
import xmltodict
with open('tasks/gal_files/catalog.xml', 'r') as f:
xml = xmltodict.parse(f.read())
i = 0
for item in xml.get('ICECAT-interface').get('files.index').get('file'):
name = item.get('@Model_Name')
create_product(name)
i += 1
if i >= count:
break
gal_commit()
@task()
def create_company(ctx, name, street=None, zip=None, city=None,
subdivision_code=None, country_code='ES', currency_code='EUR',
phone=None, website=None, email=None):
'''
Creates a company in current gal database.
Based on tryton_demo.py in tryton-tools repo:
http://hg.tryton.org/tryton-tools
'''
gal_action('create_company', name=name, street=street,
zip=zip, city=city, subdivision_code=subdivision_code,
country_code=country_code, currency_code=currency_code, phone=phone,
website=website, email=email)
restore()
connect_database()
Company = Model.get('company.company')
Currency = Model.get('currency.currency')
party = create_party(name, street=street, zip=zip,
city=city, subdivision_code=subdivision_code, country_code=country_code,
phone=phone, website=website, email=email)
companies = Company.find([('party', '=', party.id)])
if companies:
return companies[0]
currency, = Currency.find([('code', '=', currency_code)])
company_config = Wizard('company.company.config')
company_config.execute('company')
company = company_config.form
company.party = party
company.currency = currency