Coverage for jbank/management/commands/parse_xp.py: 0%

62 statements  

« prev     ^ index     » next       coverage.py v7.2.2, created at 2023-03-27 13:36 +0700

1import logging 

2import os 

3import traceback 

4from django.core.management.base import CommandParser 

5from jutil.admin import admin_log 

6from jutil.format import strip_media_root 

7from jbank.files import list_dir_files 

8from jbank.pain002 import process_pain002_file_content 

9from jbank.models import PayoutStatus 

10from jutil.command import SafeCommand 

11 

12 

13logger = logging.getLogger(__name__) 

14 

15 

16class Command(SafeCommand): 

17 help = "Parses pain.002 payment response .XP files and updates Payout status" 

18 

19 def add_arguments(self, parser: CommandParser): 

20 parser.add_argument("path", type=str) 

21 parser.add_argument("--test", action="store_true") 

22 parser.add_argument("--verbose", action="store_true") 

23 parser.add_argument("--suffix", type=str, default="XP") 

24 parser.add_argument("--set-default-paths", action="store_true") 

25 parser.add_argument("--ignore-errors", action="store_true") 

26 parser.add_argument("--ws", type=int) 

27 

28 def _set_default_paths(self, options: dict): 

29 default_path = os.path.abspath(options["path"]) 

30 qs = PayoutStatus.objects.all().filter(file_path="") 

31 if options["ws"]: 

32 qs = qs.filter(payout__connection_id=options["ws"]) 

33 objs = list(qs) 

34 print("Setting default path of {} status updates to {}".format(len(objs), strip_media_root(default_path))) 

35 for obj in objs: 

36 assert isinstance(obj, PayoutStatus) 

37 full_path = os.path.join(default_path, obj.file_name) 

38 if not os.path.isfile(full_path): 

39 msg = "Error while updating file path of PayoutStatus id={}: File {} not found".format(obj.id, full_path) 

40 if not options["ignore_errors"]: 

41 raise Exception(msg) 

42 logger.error(msg) 

43 continue 

44 file_path = strip_media_root(full_path) 

45 logger.info('PayoutStatus.objects.filter(id=%s).update(file_path="%s")', obj.id, file_path) 

46 if not options["test"]: 

47 PayoutStatus.objects.filter(id=obj.id).update(file_path=file_path) 

48 admin_log([obj], 'File path set as "{}" from terminal (parse_xp)'.format(full_path)) 

49 print("Done") 

50 

51 def do(self, *args, **options): 

52 if options["set_default_paths"]: 

53 self._set_default_paths(options) 

54 return 

55 

56 files = list_dir_files(options["path"], "." + options["suffix"]) 

57 for f in files: 

58 if PayoutStatus.objects.is_file_processed(f): 

59 if options["verbose"]: 

60 print("Skipping processed payment status file", f) 

61 continue 

62 if options["verbose"]: 

63 print("Importing payment status file", f) 

64 try: 

65 with open(f, "rb") as fp: 

66 process_pain002_file_content(fp.read(), f) 

67 except Exception: 

68 logger.error("Error while processing PayoutStatus id=%s: %s", f.id, traceback.format_exc()) # type: ignore 

69 if not options["ignore_errors"]: 

70 raise