Coverage for api/proscai/client.py: 11%

134 statements  

« prev     ^ index     » next       coverage.py v6.4.4, created at 2024-08-08 09:23 -0600

1import requests 

2import jwt 

3import json 

4import base64 

5from time import sleep 

6from apps.local_models.models import JWTToken 

7from api.proscai.auth import BaseAPIClient 

8from django.conf import settings 

9from .errors import send_email, log_error 

10from .utils import get_next_clicod 

11from django.utils import timezone 

12from django.core.exceptions import ValidationError 

13from .contact import create_contact 

14 

15 

16PROSCAI_CONN = getattr(settings, "PROSCAI_CONN", None) 

17 

18 

19 

20 

21DATA_DICT = { 

22 "clicod": None, 

23 "nombre": None, 

24 "email": None, 

25 "fecha_nacimiento": None, 

26 "fecha_alta": timezone.now().date(), 

27 "genero": None, 

28 "direcciones": [ 

29 { 

30 "calle": "", 

31 "num_ext": "", 

32 "num_int": "", 

33 "cp": "", 

34 "delegacion": "", 

35 "colonia": "", 

36 "estado": "", 

37 "ciudad": "", 

38 "pais": "MEX", 

39 "telefono": "", 

40 "celular": "", 

41 "contacto": "" 

42 } 

43 ], 

44 "rfc": "XAXX010101000", 

45 "curp": "", 

46 "cuenta_contable": "1106002", 

47 "credito": { 

48 "limite": 0, 

49 "plazo": 0 

50 }, 

51 "clasificadores": [ 

52 "", 

53 "", 

54 "", 

55 "", 

56 "", 

57 "", 

58 "7C03", 

59 "", 

60 "" 

61 ], 

62 "varios": [ 

63 0.00, 

64 0.00, 

65 0.00, 

66 0.00, 

67 0.00, 

68 3.00, # 3.0 

69 0.00, 

70 0.00, 

71 0.00, 

72 0.00, 

73 0.00, 

74 0.00, 

75 0.00 

76 ], 

77 

78} 

79 

80 

81def map_kw_to_dict(kw): 

82 my_dict = DATA_DICT.copy() 

83 my_dict['clicod'] = kw.get('clicod').upper() if kw.get('clicod', None) else None 

84 my_dict['nombre'] = kw.get('clinom').upper() if kw.get('clinom', None) else None 

85 my_dict['email'] = kw.get('clitel3', None) 

86 my_dict['fecha_nacimiento'] = kw.get('clinacimiento', None) 

87 my_dict['fecha_alta'] = kw.get('clialta', None) 

88 my_dict['direcciones'][0]['calle'] = kw.get('clidir').upper() if kw.get('clidir', None) else None 

89 my_dict['direcciones'][0]['num_ext'] = kw.get('clinumext').upper() if kw.get('clinumext', None) else None 

90 my_dict['direcciones'][0]['num_int'] = kw.get('clinumint').upper() if kw.get('clinumint', None) else None 

91 my_dict['direcciones'][0]['cp'] = kw.get('clicp', None) 

92 my_dict['direcciones'][0]['delegacion'] = kw.get('clidelegacion').upper() if kw.get('clidelegacion', None) else None 

93 my_dict['direcciones'][0]['colonia'] = kw.get('clicolonia').upper() if kw.get('clicolonia', None) else None 

94 my_dict['direcciones'][0]['estado'] = kw.get('cliedo').upper() if kw.get('cliedo', None) else None 

95 my_dict['direcciones'][0]['ciudad'] = kw.get('clicd').upper() if kw.get('clicd', None) else None 

96 my_dict['direcciones'][0]['telefono'] = kw.get('clitel', None) 

97 my_dict['direcciones'][0]['celular'] = kw.get('clicelular', None) 

98 # my_dict['rfc'] = kw.get('clirfc').upper() if kw.get('clirfc', None) else my_dict['rfc'] 

99 my_dict['curp'] = kw.get('clicurp').upper() if kw.get('clicurp', None) else None 

100 my_dict['sucursal'] = kw.get('clisucursal', None) 

101 my_dict['credito']['limite'] = int(kw.get('clicredit', None)) 

102 my_dict['credito']['plazo'] = kw.get('cliplazo0', None) 

103 my_dict['varios'][6] = kw.get('clivarios7', 0.0) 

104 my_dict['varios'][12] = kw.get('clivarios13', 0.0) 

105 

106 new_dict = my_dict.copy() 

107 

108 new_dict_dirs = {k: v for k, v in my_dict['direcciones'][0].items() if v} 

109 new_dict_credito = {k: v for k, v in my_dict['credito'].items() if v} 

110 

111 new_dict['direcciones'][0] = new_dict_dirs 

112 if new_dict_credito == {}: 

113 new_dict['credito'] = None 

114 else: 

115 new_dict['credito'] = new_dict_credito 

116 clean_dict = {k: v for k, v in new_dict.items() if v} 

117 json_dict = clean_dict 

118 return json_dict 

119 

120 

121 

122 

123 

124def create_client(*args, **kwargs): 

125 next_clicod = get_next_clicod() 

126 kwargs.update({'clicod': next_clicod}) 

127 mapped_data = map_kw_to_dict(kwargs) 

128 

129 auth_client = BaseAPIClient() 

130 token = JWTToken.objects.last() 

131 url = 'https://pas.proscai.com/v1/clientes/' 

132 data = json.dumps(mapped_data, default=str, indent=4) 

133 json_data = str(data) 

134 headers = { 

135 "Authorization": "Bearer {}".format(token.token), 

136 "Content-Type": "application/json", 

137 "ConexionAuth": PROSCAI_CONN, 

138 } 

139 

140 # ver si con CURP jala 

141 if mapped_data.get('curp', None): 

142 curp = mapped_data.get('curp') 

143 try: 

144 curp = curp.strip() 

145 except: 

146 pass 

147 url_curp = 'https://pas.proscai.com/v1/clientes/curp/{}/'.format(curp) 

148 r_curp = requests.get( url_curp, headers=headers) 

149 if r_curp.ok: 

150 clicod = r_curp.json().get('clicod') 

151 return clicod 

152 else: 

153 pass 

154 

155 

156 timmer = 0.5 #minutes 

157 counter = 1 # times 

158 limit = 1 

159 while counter <= limit: 

160 r = requests.post(url, data=json_data, headers=headers) 

161 r_contents = r.json() 

162 if r.ok: 

163 clicod = r.json().get('clicod') 

164 # crearemos contactos 

165 try: 

166 reference_dict_1 = { 

167 'clicod': clicod, 

168 'nombre': kwargs.get('reference_name_1', ''), 

169 'puesto': kwargs.get('reference_relationship_1', ''), 

170 'telefono1': kwargs.get('reference_phone_1', ''), 

171 } 

172 contact_1 = create_contact(reference_dict_1) 

173 except Exception as e: 

174 print(e) 

175 pass 

176 try: 

177 reference_dict_2 = { 

178 'clicod': clicod, 

179 'nombre': kwargs.get('reference_name_2', ''), 

180 'puesto': kwargs.get('reference_relationship_2', ''), 

181 'telefono1': kwargs.get('reference_phone_2', ''), 

182 } 

183 contact_2 = create_contact(reference_dict_2) 

184 except Exception as e: 

185 print(e) 

186 pass 

187 return clicod 

188 elif r.status_code == 409: 

189 if r_contents['mensaje'].startswith('El cliente con el email'): 

190 try: 

191 del kwargs['clitel3'] 

192 except: 

193 pass 

194 mapped_data = map_kw_to_dict(kwargs) 

195 data = json.dumps(mapped_data, default=str, indent=4) 

196 json_data = str(data) 

197 elif r_contents['mensaje'].startswith('El cliente con el CURP'): 

198 try: 

199 del kwargs['clicurp'] 

200 except: 

201 pass 

202 mapped_data = map_kw_to_dict(kwargs) 

203 data = json.dumps(mapped_data, default=str, indent=4) 

204 json_data = str(data) 

205 else: 

206 raise ValidationError(r_contents['mensaje']) 

207 ++counter 

208 

209 

210 

211 else: 

212 log_error(r) 

213 send_email(r) 

214 sleep(timmer * 60) 

215 timmer = min(timmer * 2, 10) 

216 ++counter 

217 

218 

219 

220 

221def update_client(*args, **kwargs): 

222 auth_client = BaseAPIClient() 

223 token = JWTToken.objects.first() 

224 url = 'https://pas.proscai.com/v1/clientes/{}'.format(kwargs.get('clicod')) 

225 data = kwargs 

226 json_data = json.dumps(data, default=str) 

227 headers = { 

228 "Authorization": "Bearer {}".format(token.token), 

229 "Content-Type": "application/json", 

230 "ConexionAuth": PROSCAI_CONN 

231 } 

232 

233 

234 timmer = 0.5 #minutes 

235 counter = 1 # times 

236 limit = 20 

237 while counter <= limit: 

238 r = requests.post(url, data=json_data, headers=headers) 

239 if r.ok: 

240 clicod = r.json().get('clicod') 

241 return Client.objects.get(clicod=clicod) 

242 else: 

243 log_error(r) 

244 send_email(r) 

245 sleep(timmer * 60) 

246 timmer = min(timmer * 2, 10) 

247 ++counter