mirror of
https://github.com/HamzaSha1/zod-backend.git
synced 2025-08-25 05:42:27 +00:00
Compare commits
675 Commits
ecb058209d
...
ZBKBCK-52
Author | SHA1 | Date | |
---|---|---|---|
3afd7fecf3 | |||
d1a4b86b09 | |||
e157e98a17 | |||
a653518cfd | |||
eaf67b682f | |||
085607128b | |||
fbdef7c0c4 | |||
535e2e7f56 | |||
08f54f28a4 | |||
de710c8a7b | |||
af06dddbeb | |||
0a9dde2038 | |||
f11959d6bc | |||
7aee372606 | |||
1dec5ace3f | |||
2444b6f55e | |||
3ecbc1d303 | |||
ca0041caa6 | |||
c800853e9b | |||
373c1b70ab | |||
3a84b1ea75 | |||
bf1004696a | |||
d937c1bb92 | |||
0a877b410e | |||
9d4e7b05e4 | |||
b20e1cf516 | |||
6b0ea91742 | |||
859d26d073 | |||
154b9de32b | |||
4a554272a0 | |||
8533a27cb7 | |||
7db6502a89 | |||
a8e9a09d3f | |||
1e97d7bd6b | |||
b084b255dc | |||
441842df74 | |||
78fb5f5650 | |||
f3478c972e | |||
f63d9ddea0 | |||
bc18c67527 | |||
0471a3d588 | |||
ffb99f5099 | |||
8183edf319 | |||
8f214d11a7 | |||
b5a89df59a | |||
5524eeed64 | |||
aeaa7d7ab8 | |||
69be3bb2ac | |||
be9f600bcc | |||
65d0932893 | |||
9b14eedb18 | |||
6c96ea0820 | |||
a211baa10a | |||
a93dc83bd1 | |||
116fb00358 | |||
20fa6e43da | |||
2cffc4e128 | |||
ec585d35f3 | |||
d62efa2139 | |||
7b75a3233c | |||
e1ef289c69 | |||
4f79a690c1 | |||
0af2a35206 | |||
a262b03292 | |||
d24f075110 | |||
f7624bc1e7 | |||
dc12b35842 | |||
a80f9db557 | |||
3ad29e677d | |||
8b0a5d9a8e | |||
16d823f97d | |||
d4008d6cc2 | |||
3dae22a870 | |||
a8d291474a | |||
e6482167ae | |||
9a932d31b5 | |||
e2c84eb83d | |||
5bfc3966b3 | |||
37d191eef8 | |||
e9ee8ec8b2 | |||
cc5ecc0647 | |||
63dfd731fc | |||
e9d4d7091e | |||
219bae792e | |||
df3cab99a5 | |||
d2242d4c64 | |||
b7d5916f8e | |||
5e17edcf3f | |||
b6fe943bfc | |||
8e529b292d | |||
61ca2e7d2d | |||
966f94eb1e | |||
f424c99478 | |||
34359360e0 | |||
685a822e52 | |||
e57344e54f | |||
235fc9baac | |||
3dc8268b07 | |||
8be8d56036 | |||
c79a891c89 | |||
eb4e09964d | |||
cf9376663c | |||
9891060ee3 | |||
5b2ab2275e | |||
9b6a84c7d1 | |||
e9d4fbe373 | |||
21b92f8c74 | |||
c46b2ef52c | |||
c47f6222d9 | |||
b82902081f | |||
e9315beab9 | |||
3a938720dd | |||
464899f7d3 | |||
8a436bb79f | |||
2e0ceb8c92 | |||
1a2fd2d3a8 | |||
a65eb2f77d | |||
3d06139c4f | |||
f5a03e2fdf | |||
226ddfa7e6 | |||
1028822908 | |||
342f27fc62 | |||
e9aa2dfda9 | |||
624e7a4edb | |||
3072bd5cdb | |||
930b58cf05 | |||
339c49577e | |||
09f006eb13 | |||
cd3b385756 | |||
ab1a2be679 | |||
11605540d7 | |||
8cd4864748 | |||
ad0b5bfc75 | |||
f541608656 | |||
b1b7c42438 | |||
8f9450b743 | |||
bb3441e4ed | |||
5b9f7b1828 | |||
89dda61bff | |||
31f071a463 | |||
20644a6293 | |||
a8b01d4c3a | |||
56e1484b87 | |||
557a7d7a5c | |||
4e0c6a91f4 | |||
f931e20334 | |||
8d159ac3a4 | |||
95ce57ec7d | |||
7068551050 | |||
c23d65f67c | |||
73f05dc843 | |||
290089b9ef | |||
5f3a9c35fa | |||
b92115168d | |||
19acef10ef | |||
05fd76a50b | |||
60e6d96379 | |||
fad39d399f | |||
d573d56a35 | |||
08a08960ee | |||
f8e529600b | |||
9765c90b9b | |||
930c10b578 | |||
8ca74e4b03 | |||
95dad86b12 | |||
dfff643c71 | |||
214566ec8f | |||
210e1a39e9 | |||
e380f3f6ab | |||
99a59162a2 | |||
67a5f670f8 | |||
82189d3953 | |||
65ecd9a125 | |||
a7bce32993 | |||
4495d8999c | |||
61e94c9469 | |||
1c3d4731c1 | |||
46853011be | |||
2216411fd2 | |||
606c1fa6e6 | |||
092cbfad3e | |||
249a469d89 | |||
d202774df1 | |||
1adf0c2f70 | |||
b193166914 | |||
48b455e38a | |||
6d54a718b9 | |||
454f66b3a0 | |||
5045f5acda | |||
e84180a6c2 | |||
21e006ae2a | |||
92e5104e3f | |||
dfb73a7d36 | |||
3921f76f22 | |||
cdf1a7b74e | |||
b4026a4f11 | |||
71a3e36bf3 | |||
4bc91abebf | |||
5b236dfc81 | |||
150bb9250d | |||
51d3b77ff7 | |||
92c67dd455 | |||
9a5447bca2 | |||
392086760f | |||
ceaf584332 | |||
ef4c459229 | |||
dd2890bca6 | |||
b46109e487 | |||
3f6c9a2d99 | |||
f74302df04 | |||
9bdd324c4e | |||
04ed9c668c | |||
e1d092d663 | |||
4e8243c17e | |||
13ba311822 | |||
043c8c2f63 | |||
a5f239b9d9 | |||
36427b50c1 | |||
728d19da99 | |||
5da07002e0 | |||
3017b0ece0 | |||
e73113fcca | |||
ed1b5dd453 | |||
c278670c39 | |||
60af098e1e | |||
74328f37b2 | |||
d29a60558f | |||
451c3bdae7 | |||
d8f4467d98 | |||
7c809776b6 | |||
a9cc05c675 | |||
e46d649fdc | |||
adb827f5a0 | |||
a02dfd4e31 | |||
d3b0be953e | |||
11b9f00285 | |||
4bc16c56bd | |||
08dc9f8538 | |||
6373d1e02c | |||
83d7d119be | |||
a1d959299a | |||
070637bf1d | |||
19a6475097 | |||
fd9a4902ae | |||
082f93ff9d | |||
25eaee31a4 | |||
d5c30f2029 | |||
cae28e0b54 | |||
54200dba52 | |||
846a9d42d4 | |||
69c19cf097 | |||
18cb885410 | |||
4ca60af5da | |||
4d7209df19 | |||
94c76b7f2e | |||
af8ea39200 | |||
6e9304b2cc | |||
5eab8f4907 | |||
807526acfa | |||
f750487b88 | |||
8b0032f6d2 | |||
bb65f81200 | |||
04db40e100 | |||
1e162255d7 | |||
f4149379c2 | |||
a479f3cb62 | |||
fbd6f9ece5 | |||
11c84208b7 | |||
4f02cef0f9 | |||
b8f1acaed8 | |||
80dffb7942 | |||
0a8c2cf56d | |||
9e5dd5e3d5 | |||
03fb4f4176 | |||
22afe7e555 | |||
69723b362f | |||
9e612c7171 | |||
7a9be0326a | |||
aaa1c55227 | |||
656f0da89a | |||
b961044e4d | |||
28e71e132c | |||
b30643299f | |||
b6b70af13f | |||
22dd7fc10b | |||
2498394127 | |||
924bc20193 | |||
af7582b9e2 | |||
856d27d803 | |||
19f56280e4 | |||
2fc65d462d | |||
d3800dbc85 | |||
9373dc4697 | |||
32eaa6c3f2 | |||
11ff8fc700 | |||
9c75cb1615 | |||
3f8b0e2eb7 | |||
69ce6857e8 | |||
cdf656fdad | |||
3efa31efe4 | |||
275b09d2ea | |||
3cb0e3ed8b | |||
823c5ea4c4 | |||
c9ee482512 | |||
08750813ce | |||
75f4f66285 | |||
881bda739b | |||
d86f082e58 | |||
8eaf8751c2 | |||
b12c5071fe | |||
f75201b3dd | |||
6867920754 | |||
45ea7013f8 | |||
7d428f5eb5 | |||
22ba4288d9 | |||
9ff64e64ef | |||
4b23394569 | |||
81893c8841 | |||
10a1ea9b76 | |||
7ab16cb3de | |||
7fca493d0d | |||
85e4ae8761 | |||
6ebd5ae410 | |||
f57b111555 | |||
6596414675 | |||
ed7fd3c15d | |||
8cf7148114 | |||
b98443479f | |||
f917244265 | |||
ceb5bc13c3 | |||
ae0fc4fe8d | |||
0a1b9c7e70 | |||
f2cf1488e9 | |||
0426974539 | |||
b0e26f41b9 | |||
c20249730a | |||
b3b499e661 | |||
f377e283fd | |||
648a2ec4d5 | |||
83ec922584 | |||
88221ec77a | |||
e853346910 | |||
a088764b7b | |||
4a2f36cde8 | |||
401ee1ddf8 | |||
baacb1a18f | |||
5f1c645e3a | |||
07d150309b | |||
79648637aa | |||
756bea0471 | |||
465632f519 | |||
b9e2d9bc8a | |||
d82c8cd4ae | |||
dd0f2b027a | |||
3806d1f3a6 | |||
3801e6e027 | |||
f3e2ab9a34 | |||
685f627707 | |||
b2d172eae5 | |||
404825dc85 | |||
6e6f0a55d0 | |||
75d0b12008 | |||
2a4011ca5d | |||
ebb468166e | |||
e89fc513cb | |||
06176912ee | |||
ed8fc156ac | |||
e1af1c200d | |||
bff97f59b2 | |||
af121f5a53 | |||
4c3aa03e13 | |||
f3a8b52617 | |||
0c3a77cd11 | |||
d3564efbb9 | |||
329df77790 | |||
ee92c98f34 | |||
b238379a22 | |||
fbce04b97e | |||
afaed69eec | |||
3c0eaf676e | |||
6ffaa66a4d | |||
4b8e7189c1 | |||
d68f24543d | |||
3534561697 | |||
de774111c0 | |||
c081bc621d | |||
bab50e4492 | |||
151a177e76 | |||
73a62186a7 | |||
83c66ab3b6 | |||
94e53e1dcd | |||
68b77ef766 | |||
d2c8b18e3f | |||
a2000459d3 | |||
c079f3ceca | |||
671cdfc27b | |||
a83e27b12a | |||
87aa1af02b | |||
bdc0ba4fd5 | |||
5f3026f08f | |||
a323ad7df7 | |||
2b6e943d8c | |||
3af2584d6a | |||
bca0d8d49b | |||
b860d937f5 | |||
62cf2b14bf | |||
11b10bf751 | |||
d0ef4391cc | |||
5a1b419863 | |||
7bf0e62604 | |||
80843502a6 | |||
cbd3d139a5 | |||
3b31d08996 | |||
3cdd685ea8 | |||
c4152c0773 | |||
8a454c3f97 | |||
71405780f8 | |||
a8558b5e6e | |||
7c4f9b2506 | |||
cc3490b059 | |||
32476149bc | |||
c57224ad0e | |||
c8a8e1149b | |||
7c69dfd49f | |||
6dcf045131 | |||
6e84814117 | |||
c587ba322e | |||
2db0e47e3b | |||
52cdd4b0ba | |||
6be0682913 | |||
bfeeb5e41f | |||
bb56fc7a33 | |||
e6d45f3bf2 | |||
7cb792c6cf | |||
49b648e86b | |||
79e85fa968 | |||
5ea28bbd75 | |||
096961976d | |||
4d104bab1c | |||
ed28117a7f | |||
180104ece8 | |||
0a7c081f63 | |||
a2b4f3b758 | |||
d86f7d3436 | |||
a5a309cf5b | |||
0a5eaa233f | |||
b32d4def2d | |||
410282036e | |||
2a225ea79d | |||
65e012dd60 | |||
8013767d71 | |||
fdd0b88b11 | |||
bb1351c309 | |||
c15bd2339a | |||
5ee01af825 | |||
b8382e225c | |||
532b56c687 | |||
6fe29f0070 | |||
96d71d951e | |||
effad5cddc | |||
8c0da25814 | |||
b032300ab7 | |||
4b09ff41cb | |||
8762c00dba | |||
4410712b11 | |||
e2f737c5b4 | |||
0f5dfc2e9a | |||
b488b08f3f | |||
7102c44055 | |||
8e2d9c44b9 | |||
fa96364901 | |||
49abf12ce8 | |||
4002d1e561 | |||
9f9926da14 | |||
555d8231e7 | |||
3223a2b050 | |||
2e7d36485c | |||
2e3870dc53 | |||
86e2c75afc | |||
e238c85674 | |||
5429140a5c | |||
6e6ba881f6 | |||
74fc656bd1 | |||
e9b0e480e6 | |||
49fc8d9dca | |||
39271282e2 | |||
9b84d176af | |||
49336e2e18 | |||
0df748ccbf | |||
9d600a1ea8 | |||
06d841f444 | |||
e3a5d52a1d | |||
130dcd83e7 | |||
19a2a3d1db | |||
02f01b8a16 | |||
3d84c03163 | |||
5cc43aa2b8 | |||
4c0cac7cb0 | |||
6aa198d1ad | |||
ba4d5933de | |||
4d04f16cee | |||
032186bf43 | |||
04342133ef | |||
751af642b8 | |||
e90326fcb6 | |||
0cec3a5cf1 | |||
ae7250b34a | |||
8f1f49de45 | |||
de5d3b19d0 | |||
2b0fc56190 | |||
4779749b0c | |||
6d6d21137f | |||
cd944b10f5 | |||
1399b585e8 | |||
2d3100286d | |||
cfc36735d6 | |||
761e723cd3 | |||
32e52e17f4 | |||
71e7601d6b | |||
5bd865a685 | |||
45410fa0ca | |||
485dc83911 | |||
ac00543312 | |||
a0e1dc11fa | |||
c798357952 | |||
d163f43c85 | |||
b3f35d271b | |||
7b9b5a2c6f | |||
a4d9997580 | |||
c43db90219 | |||
5d528b885a | |||
d3b7b6cd07 | |||
1ea4720ab4 | |||
52a0f4b590 | |||
f7cfd53594 | |||
dae6ffbed1 | |||
a16fecb1c9 | |||
75bc387bec | |||
aadced6a13 | |||
1ac6c7c01d | |||
c3f7750349 | |||
ab06962b79 | |||
324a023d83 | |||
0c760a58f3 | |||
d0430d7aad | |||
701961234d | |||
1fc02d17e6 | |||
b156e62dc8 | |||
81e314878e | |||
b11137bfad | |||
a041028840 | |||
8720de4834 | |||
33101811ff | |||
18cb975d94 | |||
2e7ef5e69f | |||
7e7367e3a4 | |||
809f89bd42 | |||
68ce67d387 | |||
efa121640f | |||
23fb2a0695 | |||
7d6dfb15a2 | |||
8b4db3e2e9 | |||
fe8ddd02a5 | |||
c26e6140a7 | |||
41761f22e8 | |||
cd0f1c72a1 | |||
c0f20f732d | |||
628dbbf926 | |||
1ae81d4134 | |||
03fb774a7b | |||
4fb7a2fc6c | |||
0d4c9aae78 | |||
c8925aad8e | |||
51153a09cc | |||
026bfb6da7 | |||
3dc16ce79c | |||
65a00ef090 | |||
3098de36b8 | |||
15cc3eca51 | |||
1b60d4344e | |||
3723e46be1 | |||
b75756c43a | |||
8bf4ad8352 | |||
413434496c | |||
c7415c7760 | |||
9e8cde3516 | |||
af5f0cf200 | |||
ab435ef384 | |||
c01c2b4e23 | |||
3f0e73771c | |||
c6ffb1f039 | |||
2b783512a5 | |||
bea4cbe376 | |||
34034dcdb8 | |||
c7a5bf68a0 | |||
3b642fcc5f | |||
2edd8c4e00 | |||
cf966a5250 | |||
a80f603614 | |||
0d143a39ac | |||
5e5161a77e | |||
156dc496bd | |||
376bb89f20 | |||
1c7d6bac85 | |||
abbe09731c | |||
22f1d01b94 | |||
69c06691c7 | |||
a27c486c43 | |||
28cbdf9cfa | |||
ddfc4e946c | |||
014b5fe183 | |||
d2498f82ad | |||
f2533d9a08 | |||
36cedf8c69 | |||
4e22dd9871 | |||
66bbe06686 | |||
79ac140ddd | |||
4a34dab570 | |||
e5b88794ad | |||
245162b913 | |||
6cbe824d9e | |||
7376fc555b | |||
df438241ce | |||
ed2d7895ab | |||
c57968b7c0 | |||
bb06238623 | |||
e42d8af65b | |||
d254c5e5fa | |||
ada987413b | |||
118d73776b | |||
c2713b8214 | |||
4dd95e74fb | |||
70c136dde4 | |||
88a9e925ed | |||
3d3ccfb146 | |||
be6725c66d | |||
f3c41043e0 | |||
ea2bd635ca | |||
eb4cde397f | |||
4864d3b499 | |||
ef1f7ebeac | |||
c1ae88c32f | |||
9d7f265f40 | |||
323168b7d0 | |||
f0a2a4bd4b | |||
4a982f1baf | |||
d849153bec | |||
947119d4c2 | |||
a41e3a6f14 | |||
7b02b7dfbc | |||
3852e9bf03 | |||
d208e5252c | |||
7b6d34f334 | |||
0006208cf8 | |||
352de6d630 | |||
ad582d77d7 | |||
019d028cb6 | |||
e1e5b1838a | |||
8ff142ce2f | |||
4537f1f4fa | |||
2086dcb472 | |||
d4eaaada74 | |||
396b4a32c3 | |||
232f082c77 | |||
aaa1730636 | |||
44b25dde3e | |||
b52819c033 | |||
9bd31f9e86 | |||
6374ea0a90 | |||
9db620d818 | |||
89982f851f | |||
c115873972 | |||
8bc3a307c0 | |||
501deaac0b | |||
5d386322e4 |
23
.gitignore
vendored
Normal file
23
.gitignore
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
/static
|
||||
/media
|
||||
.idea/
|
||||
*.pyc
|
||||
media/
|
||||
*.name
|
||||
*.iml
|
||||
*.log
|
||||
*.pyo
|
||||
.DS_Store
|
||||
.idea
|
||||
venv/*
|
||||
static/*
|
||||
*.pem
|
||||
*.sqlite3
|
||||
/migrations/__pycache__/
|
||||
/__pycache__/
|
||||
/*.pyc
|
||||
*/__pycache__/*.pyc
|
||||
__pycache__/
|
||||
*.env
|
||||
ve/*
|
||||
celerybeat-schedule
|
11
Dockerfile
Normal file
11
Dockerfile
Normal file
@ -0,0 +1,11 @@
|
||||
FROM python:3.9
|
||||
ENV PYTHONUNBUFFERED 1
|
||||
RUN mkdir /usr/src/app
|
||||
WORKDIR /usr/src/app
|
||||
COPY . .
|
||||
RUN apt-get update
|
||||
RUN apt-get install wkhtmltopdf -y
|
||||
RUN apt install -y gdal-bin python3-gdal
|
||||
RUN pip install -r requirements.txt
|
||||
WORKDIR /usr/src/app
|
||||
|
0
account/__init__.py
Normal file
0
account/__init__.py
Normal file
62
account/admin.py
Normal file
62
account/admin.py
Normal file
@ -0,0 +1,62 @@
|
||||
"""Account admin"""
|
||||
from django.contrib import admin
|
||||
|
||||
"""Import django app"""
|
||||
from .models import UserEmailOtp, DefaultTaskImages, UserNotification, UserDelete, UserDeviceDetails, ForceUpdate
|
||||
# Register your models here.
|
||||
|
||||
@admin.register(UserDelete)
|
||||
class UserDeleteAdmin(admin.ModelAdmin):
|
||||
"""User profile admin"""
|
||||
list_display = ['user', 'old_email', 'd_email']
|
||||
|
||||
def __str__(self):
|
||||
"""Return delete user"""
|
||||
return self.user
|
||||
@admin.register(UserNotification)
|
||||
class UserNotificationAdmin(admin.ModelAdmin):
|
||||
"""User profile admin"""
|
||||
list_display = ['user', 'push_notification', 'email_notification', 'sms_notification']
|
||||
|
||||
def __str__(self):
|
||||
"""Return image url"""
|
||||
return self.image_url
|
||||
@admin.register(DefaultTaskImages)
|
||||
class DefaultTaskImagesAdmin(admin.ModelAdmin):
|
||||
"""User profile admin"""
|
||||
list_display = ['task_name', 'image_url']
|
||||
|
||||
def __str__(self):
|
||||
"""Return image url"""
|
||||
return self.image_url
|
||||
|
||||
@admin.register(UserEmailOtp)
|
||||
class UserEmailOtpAdmin(admin.ModelAdmin):
|
||||
"""User Email otp admin"""
|
||||
list_display = ['email']
|
||||
|
||||
def __str__(self):
|
||||
"""Return object in email and otp format"""
|
||||
return self.email + '-' + self.otp
|
||||
|
||||
@admin.register(ForceUpdate)
|
||||
class ForceUpdateAdmin(admin.ModelAdmin):
|
||||
"""Force update"""
|
||||
list_display = ['version', 'device_type']
|
||||
readonly_fields = ('device_type',)
|
||||
|
||||
def has_add_permission(self, request):
|
||||
count = ForceUpdate.objects.all().count()
|
||||
if count < 2:
|
||||
return True
|
||||
return False
|
||||
def has_delete_permission(self, request, obj=None):
|
||||
return False
|
||||
@admin.register(UserDeviceDetails)
|
||||
class UserDeviceDetailsAdmin(admin.ModelAdmin):
|
||||
"""User profile admin"""
|
||||
list_display = ['user', 'device_id']
|
||||
|
||||
def __str__(self):
|
||||
"""Return user email"""
|
||||
return self.user.email
|
9
account/apps.py
Normal file
9
account/apps.py
Normal file
@ -0,0 +1,9 @@
|
||||
"""Account app file"""
|
||||
"""Import Django"""
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class AccountConfig(AppConfig):
|
||||
"""default configurations"""
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'account'
|
73
account/custom_middleware.py
Normal file
73
account/custom_middleware.py
Normal file
@ -0,0 +1,73 @@
|
||||
"""middleware file"""
|
||||
"""Django import"""
|
||||
from rest_framework import status
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.renderers import JSONRenderer
|
||||
"""App django"""
|
||||
from account.utils import custom_error_response
|
||||
from account.models import UserDeviceDetails, ForceUpdate
|
||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
||||
from base.constants import NUMBER
|
||||
from junior.models import Junior
|
||||
from guardian.models import Guardian
|
||||
# Custom middleware
|
||||
# when user login with
|
||||
# multiple device simultaneously
|
||||
# It restricted login in
|
||||
# multiple devices only
|
||||
# user can login in single
|
||||
# device at a time"""
|
||||
# force update
|
||||
# use 308 status code for force update
|
||||
|
||||
def custom_response(custom_error, response_status = status.HTTP_404_NOT_FOUND):
|
||||
"""custom response"""
|
||||
response = Response(custom_error.data, status=response_status)
|
||||
# Set content type header to "application/json"
|
||||
response['Content-Type'] = 'application/json'
|
||||
# Render the response as JSON
|
||||
renderer = JSONRenderer()
|
||||
response.content = renderer.render(response.data)
|
||||
return response
|
||||
class CustomMiddleware(object):
|
||||
"""Custom middleware"""
|
||||
def __init__(self, get_response):
|
||||
"""response"""
|
||||
self.get_response = get_response
|
||||
|
||||
def __call__(self, request):
|
||||
# Code to be executed before the view is called
|
||||
response = self.get_response(request)
|
||||
# Code to be executed after the view is called
|
||||
device_id = request.META.get('HTTP_DEVICE_ID')
|
||||
user_type = request.META.get('HTTP_USER_TYPE')
|
||||
version = request.META.get('HTTP_VERSION')
|
||||
device_type = str(request.META.get('HTTP_TYPE'))
|
||||
|
||||
api_endpoint = request.path
|
||||
unrestricted_api = ('/api/v1/user/login/', '/api/v1/logout/', '/api/v1/generate-token/')
|
||||
if request.user.is_authenticated:
|
||||
# device details
|
||||
if device_id:
|
||||
device_details = UserDeviceDetails.objects.filter(user=request.user, device_id=device_id).last()
|
||||
if not device_details and api_endpoint not in unrestricted_api:
|
||||
custom_error = custom_error_response(ERROR_CODE['2037'], response_status=status.HTTP_404_NOT_FOUND)
|
||||
response = custom_response(custom_error)
|
||||
if user_type and str(user_type) == str(NUMBER['one']):
|
||||
junior = Junior.objects.filter(auth=request.user, is_active=False).last()
|
||||
if junior:
|
||||
custom_error = custom_error_response(ERROR_CODE['2075'], response_status=status.HTTP_404_NOT_FOUND)
|
||||
response = custom_response(custom_error)
|
||||
elif user_type and str(user_type) == str(NUMBER['two']):
|
||||
guardian = Guardian.objects.filter(user=request.user, is_active=False).last()
|
||||
if guardian:
|
||||
custom_error = custom_error_response(ERROR_CODE['2075'], response_status=status.HTTP_404_NOT_FOUND)
|
||||
response = custom_response(custom_error)
|
||||
|
||||
if version and device_type:
|
||||
force_update = ForceUpdate.objects.filter(version=version, device_type=device_type).last()
|
||||
if not force_update:
|
||||
custom_error = custom_error_response(ERROR_CODE['2079'],
|
||||
response_status=status.HTTP_308_PERMANENT_REDIRECT)
|
||||
response = custom_response(custom_error, status.HTTP_308_PERMANENT_REDIRECT)
|
||||
return response
|
65
account/migrations/0001_initial.py
Normal file
65
account/migrations/0001_initial.py
Normal file
@ -0,0 +1,65 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-23 12:05
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserEmailOtp',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('email', models.EmailField(max_length=254)),
|
||||
('otp', models.CharField(max_length=10)),
|
||||
('is_verified', models.BooleanField(default=False)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('expired_at', models.DateTimeField(blank=True, null=True)),
|
||||
('is_active', models.BooleanField(default=True)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'user_email_otp',
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='UserPhoneOtp',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('country_code', models.IntegerField()),
|
||||
('phone', models.CharField(max_length=17)),
|
||||
('otp', models.CharField(max_length=10)),
|
||||
('is_verified', models.BooleanField(default=False)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('expired_at', models.DateTimeField(blank=True, null=True)),
|
||||
('is_active', models.BooleanField(default=True)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'user_phone_otp',
|
||||
},
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='UserProfile',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('user_type', models.CharField(blank=True, choices=[('1', 'junior'), ('2', 'guardian'), ('3', 'superuser')], default=None, max_length=15, null=True)),
|
||||
('is_verified', models.BooleanField(default=False)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('is_active', models.BooleanField(default=False)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='user_profile', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'user_profile',
|
||||
},
|
||||
),
|
||||
]
|
18
account/migrations/0002_useremailotp_user_type.py
Normal file
18
account/migrations/0002_useremailotp_user_type.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-29 12:10
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('account', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='useremailotp',
|
||||
name='user_type',
|
||||
field=models.CharField(blank=True, choices=[('1', 'junior'), ('2', 'guardian'), ('3', 'superuser')], default=None, max_length=15, null=True),
|
||||
),
|
||||
]
|
26
account/migrations/0003_defaulttaskimages.py
Normal file
26
account/migrations/0003_defaulttaskimages.py
Normal file
@ -0,0 +1,26 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-07 10:23
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('account', '0002_useremailotp_user_type'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='DefaultTaskImages',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('task_name', models.CharField(max_length=15)),
|
||||
('image_url', models.URLField(blank=True, default=None, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'default_task_image',
|
||||
},
|
||||
),
|
||||
]
|
31
account/migrations/0004_userdelete.py
Normal file
31
account/migrations/0004_userdelete.py
Normal file
@ -0,0 +1,31 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-10 09:24
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
('account', '0003_defaulttaskimages'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserDelete',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('old_email', models.EmailField(blank=True, max_length=254, null=True, verbose_name='Original Email')),
|
||||
('d_email', models.EmailField(blank=True, max_length=254, null=True, verbose_name='Dummy Email')),
|
||||
('is_active', models.BooleanField(default=True)),
|
||||
('reason', models.TextField(blank=True, max_length=500, null=True, verbose_name='Reason for Leaving')),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='delete_information_set', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'user_delete_information',
|
||||
},
|
||||
),
|
||||
]
|
31
account/migrations/0005_usernotification.py
Normal file
31
account/migrations/0005_usernotification.py
Normal file
@ -0,0 +1,31 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-10 12:40
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
('account', '0004_userdelete'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserNotification',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('push_notification', models.BooleanField(default=True)),
|
||||
('email_notification', models.BooleanField(default=True)),
|
||||
('sms_notification', models.BooleanField(default=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='user_notification', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'db_table': 'user_notification',
|
||||
},
|
||||
),
|
||||
]
|
@ -0,0 +1,21 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-11 11:26
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('account', '0005_usernotification'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='useremailotp',
|
||||
options={'verbose_name': 'User Email OTP', 'verbose_name_plural': 'User Email OTP'},
|
||||
),
|
||||
migrations.AlterModelOptions(
|
||||
name='usernotification',
|
||||
options={'verbose_name': 'User Notification', 'verbose_name_plural': 'User Notification'},
|
||||
),
|
||||
]
|
@ -0,0 +1,21 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-14 09:34
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('account', '0006_alter_useremailotp_options_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='defaulttaskimages',
|
||||
options={'verbose_name': 'Default Task images', 'verbose_name_plural': 'Default Task images'},
|
||||
),
|
||||
migrations.AlterModelOptions(
|
||||
name='userdelete',
|
||||
options={'verbose_name': 'Deleted User', 'verbose_name_plural': 'Deleted User'},
|
||||
),
|
||||
]
|
31
account/migrations/0008_userdevicedetails.py
Normal file
31
account/migrations/0008_userdevicedetails.py
Normal file
@ -0,0 +1,31 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-14 11:08
|
||||
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
('account', '0007_alter_defaulttaskimages_options_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserDeviceDetails',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('device_id', models.CharField(max_length=500)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='user_device_details', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'User Device Details',
|
||||
'verbose_name_plural': 'User Device Details',
|
||||
'db_table': 'user_device_details',
|
||||
},
|
||||
),
|
||||
]
|
18
account/migrations/0009_alter_userdevicedetails_device_id.py
Normal file
18
account/migrations/0009_alter_userdevicedetails_device_id.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-20 11:38
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('account', '0008_userdevicedetails'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='userdevicedetails',
|
||||
name='device_id',
|
||||
field=models.CharField(blank=True, max_length=500, null=True),
|
||||
),
|
||||
]
|
28
account/migrations/0010_forceupdate.py
Normal file
28
account/migrations/0010_forceupdate.py
Normal file
@ -0,0 +1,28 @@
|
||||
# Generated by Django 4.2.2 on 2023-08-22 07:39
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('account', '0009_alter_userdevicedetails_device_id'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='ForceUpdate',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('version', models.CharField(blank=True, max_length=50, null=True)),
|
||||
('device_type', models.CharField(blank=True, choices=[('1', 'android'), ('2', 'ios')], default=None, max_length=15, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Force Update Version',
|
||||
'verbose_name_plural': 'Force Update Version',
|
||||
'db_table': 'force_update',
|
||||
},
|
||||
),
|
||||
]
|
0
account/migrations/__init__.py
Normal file
0
account/migrations/__init__.py
Normal file
190
account/models.py
Normal file
190
account/models.py
Normal file
@ -0,0 +1,190 @@
|
||||
"""Account module file"""
|
||||
"""Django import"""
|
||||
from django.db import models
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.exceptions import ValidationError
|
||||
"""App import"""
|
||||
from base.constants import USER_TYPE, DEVICE_TYPE
|
||||
# Create your models here.
|
||||
|
||||
class UserProfile(models.Model):
|
||||
"""
|
||||
User details
|
||||
"""
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_profile')
|
||||
user_type = models.CharField(max_length=15, choices=USER_TYPE, null=True, blank=True, default=None)
|
||||
is_verified = models.BooleanField(default=False)
|
||||
|
||||
# OTP validity
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
is_active = models.BooleanField(default=False)
|
||||
|
||||
class Meta(object):
|
||||
""" Meta information """
|
||||
db_table = 'user_profile'
|
||||
|
||||
def __str__(self):
|
||||
"""return phone as an object"""
|
||||
return f'{self.user}'
|
||||
|
||||
class UserPhoneOtp(models.Model):
|
||||
"""
|
||||
This class is used to verify user email and their contact no.
|
||||
"""
|
||||
"""user details"""
|
||||
country_code = models.IntegerField()
|
||||
phone = models.CharField(max_length=17)
|
||||
"""otp details"""
|
||||
otp = models.CharField(max_length=10)
|
||||
is_verified = models.BooleanField(default=False)
|
||||
|
||||
# OTP validity
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
expired_at = models.DateTimeField(blank=True, null=True)
|
||||
is_active = models.BooleanField(default=True)
|
||||
|
||||
class Meta(object):
|
||||
""" Meta information """
|
||||
db_table = 'user_phone_otp'
|
||||
|
||||
def __str__(self):
|
||||
"""return phone as an object"""
|
||||
return self.phone
|
||||
|
||||
class UserEmailOtp(models.Model):
|
||||
"""
|
||||
This class is used to verify user email and their contact no.
|
||||
"""
|
||||
"""user details"""
|
||||
email = models.EmailField()
|
||||
"""otp details"""
|
||||
otp = models.CharField(max_length=10)
|
||||
is_verified = models.BooleanField(default=False)
|
||||
user_type = models.CharField(max_length=15, choices=USER_TYPE, null=True, blank=True, default=None)
|
||||
|
||||
# OTP validity
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
expired_at = models.DateTimeField(blank=True, null=True)
|
||||
is_active = models.BooleanField(default=True)
|
||||
|
||||
class Meta(object):
|
||||
""" Meta information """
|
||||
db_table = 'user_email_otp'
|
||||
verbose_name = 'User Email OTP'
|
||||
verbose_name_plural = 'User Email OTP'
|
||||
|
||||
def __str__(self):
|
||||
"""return phone as an object"""
|
||||
return self.email
|
||||
|
||||
class DefaultTaskImages(models.Model):
|
||||
"""Default images upload in oss bucket"""
|
||||
|
||||
task_name = models.CharField(max_length=15)
|
||||
image_url = models.URLField(null=True, blank=True, default=None)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta(object):
|
||||
""" Meta information """
|
||||
db_table = 'default_task_image'
|
||||
verbose_name = 'Default Task images'
|
||||
verbose_name_plural = 'Default Task images'
|
||||
|
||||
def __str__(self):
|
||||
"""return phone as an object"""
|
||||
return self.task_name
|
||||
|
||||
class UserDelete(models.Model):
|
||||
"""
|
||||
User delete information
|
||||
"""
|
||||
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='delete_information_set')
|
||||
"""Old email"""
|
||||
old_email = models.EmailField(blank=True, null=True, verbose_name='Original Email')
|
||||
"""Dummy email"""
|
||||
d_email = models.EmailField(blank=True, null=True, verbose_name='Dummy Email')
|
||||
is_active = models.BooleanField(default=True)
|
||||
"""reason for leaving"""
|
||||
reason = models.TextField(max_length=500, blank=True, null=True, verbose_name='Reason for Leaving')
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
|
||||
class Meta(object):
|
||||
""" Meta information """
|
||||
db_table = 'user_delete_information'
|
||||
verbose_name = 'Deleted User'
|
||||
verbose_name_plural = 'Deleted User'
|
||||
|
||||
def __str__(self):
|
||||
return self.user.email
|
||||
|
||||
|
||||
class UserNotification(models.Model):
|
||||
"""
|
||||
User notification details
|
||||
"""
|
||||
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_notification')
|
||||
"""Push Notification"""
|
||||
push_notification = models.BooleanField(default=True)
|
||||
"""Email Notification"""
|
||||
email_notification = models.BooleanField(default=True)
|
||||
"""SMS Notification"""
|
||||
sms_notification = models.BooleanField(default=True)
|
||||
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta(object):
|
||||
""" Meta information """
|
||||
db_table = 'user_notification'
|
||||
verbose_name = 'User Notification'
|
||||
verbose_name_plural = 'User Notification'
|
||||
|
||||
def __str__(self):
|
||||
return self.user.email
|
||||
|
||||
|
||||
class UserDeviceDetails(models.Model):
|
||||
"""
|
||||
User notification details
|
||||
"""
|
||||
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_device_details')
|
||||
"""Device ID"""
|
||||
device_id = models.CharField(max_length=500, null=True, blank=True)
|
||||
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta(object):
|
||||
""" Meta information """
|
||||
db_table = 'user_device_details'
|
||||
verbose_name = 'User Device Details'
|
||||
verbose_name_plural = 'User Device Details'
|
||||
|
||||
def __str__(self):
|
||||
return self.user.email
|
||||
|
||||
|
||||
|
||||
|
||||
class ForceUpdate(models.Model):
|
||||
"""
|
||||
Force update
|
||||
"""
|
||||
"""Version ID"""
|
||||
version = models.CharField(max_length=50, null=True, blank=True)
|
||||
device_type = models.CharField(max_length=15, choices=DEVICE_TYPE, null=True, blank=True, default=None)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta(object):
|
||||
""" Meta information """
|
||||
db_table = 'force_update'
|
||||
verbose_name = 'Force Update Version'
|
||||
verbose_name_plural = 'Force Update Version'
|
||||
|
||||
def __str__(self):
|
||||
return self.version
|
401
account/serializers.py
Normal file
401
account/serializers.py
Normal file
@ -0,0 +1,401 @@
|
||||
"""Account serializer"""
|
||||
"""Django Import"""
|
||||
# Import Refresh token of jwt
|
||||
from rest_framework import serializers
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
import secrets
|
||||
"""App import"""
|
||||
# Import guardian's model,
|
||||
# Import junior's model,
|
||||
# Import account's model,
|
||||
# Import constant from
|
||||
# base package,
|
||||
# Import messages from
|
||||
# base package,
|
||||
# Import some functions
|
||||
# from utils file"""
|
||||
|
||||
from guardian.models import Guardian
|
||||
from junior.models import Junior
|
||||
from account.models import UserEmailOtp, DefaultTaskImages, UserDelete, UserNotification, UserPhoneOtp, ForceUpdate
|
||||
from base.constants import GUARDIAN, JUNIOR, SUPERUSER, NUMBER
|
||||
from base.messages import ERROR_CODE, SUCCESS_CODE, STATUS_CODE_ERROR
|
||||
from .utils import delete_user_account_condition_social, delete_user_account_condition
|
||||
|
||||
# In this serializer file
|
||||
# define google login serializer
|
||||
# update junior profile,
|
||||
# update guardian profile,
|
||||
# super admin serializer,
|
||||
# reset password,
|
||||
# forgot password,
|
||||
# change password,
|
||||
# basic junior serializer,
|
||||
# basic guardian serializer,
|
||||
# user delete account serializer,
|
||||
# user notification serializer,
|
||||
# update user notification serializer,
|
||||
# default task's images serializer,
|
||||
# upload default task's images serializer,
|
||||
# email verification serializer,
|
||||
# phone otp serializer
|
||||
|
||||
# create all serializer here
|
||||
class GoogleLoginSerializer(serializers.Serializer):
|
||||
"""google login serializer"""
|
||||
access_token = serializers.CharField(max_length=5000, required=True)
|
||||
|
||||
class Meta(object):
|
||||
"""meta class"""
|
||||
fields = ('access_token',)
|
||||
|
||||
|
||||
class UpdateJuniorProfileImageSerializer(serializers.ModelSerializer):
|
||||
"""update junior image"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = Junior
|
||||
fields = ['id', 'image']
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
"""update image """
|
||||
junior_image = validated_data.get('image', instance.image)
|
||||
instance.image = junior_image
|
||||
instance.save()
|
||||
return instance
|
||||
|
||||
|
||||
class UpdateGuardianImageSerializer(serializers.ModelSerializer):
|
||||
"""update guardian image"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = Guardian
|
||||
fields = ['id','image']
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
"""update image """
|
||||
instance.image = validated_data.get('image', instance.image)
|
||||
instance.save()
|
||||
return instance
|
||||
|
||||
|
||||
class ResetPasswordSerializer(serializers.Serializer):
|
||||
"""Reset Password after verification"""
|
||||
verification_code = serializers.CharField(max_length=10)
|
||||
password = serializers.CharField(required=True)
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = User
|
||||
|
||||
def create(self, validated_data):
|
||||
verification_code = validated_data.pop('verification_code')
|
||||
password = validated_data.pop('password')
|
||||
# fetch email otp object of the user
|
||||
user_opt_details = UserEmailOtp.objects.filter(otp=verification_code, is_verified=True).last()
|
||||
if user_opt_details:
|
||||
user_details = User.objects.filter(email=user_opt_details.email).last()
|
||||
if user_details:
|
||||
if user_details.check_password(password):
|
||||
raise serializers.ValidationError({"details":ERROR_CODE['2001'],"code":"400", "status":"failed"})
|
||||
user_details.set_password(password)
|
||||
user_details.save()
|
||||
return {'password':password}
|
||||
return user_opt_details
|
||||
return ''
|
||||
|
||||
|
||||
class ChangePasswordSerializer(serializers.Serializer):
|
||||
"""Update Password after verification"""
|
||||
current_password = serializers.CharField(max_length=100, required=True)
|
||||
new_password = serializers.CharField(required=True)
|
||||
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = User
|
||||
|
||||
def validate_current_password(self, value):
|
||||
user = self.context
|
||||
# check old password
|
||||
if self.context.password not in ('', None) and user.check_password(value):
|
||||
return value
|
||||
raise serializers.ValidationError(ERROR_CODE['2015'])
|
||||
|
||||
def create(self, validated_data):
|
||||
"""
|
||||
change password
|
||||
"""
|
||||
new_password = validated_data.pop('new_password')
|
||||
current_password = validated_data.pop('current_password')
|
||||
# Check new password is different from current password
|
||||
if new_password == current_password:
|
||||
raise serializers.ValidationError({"details": ERROR_CODE['2026']})
|
||||
|
||||
user_details = self.context
|
||||
user_details.set_password(new_password)
|
||||
user_details.save()
|
||||
return {'password':new_password}
|
||||
|
||||
|
||||
class ForgotPasswordSerializer(serializers.Serializer):
|
||||
"""Forget password serializer"""
|
||||
email = serializers.EmailField(required=True)
|
||||
|
||||
def validate_email(self, value):
|
||||
"""
|
||||
validate email exist ot not
|
||||
value: string
|
||||
return none
|
||||
"""
|
||||
if not User.objects.get(email=value):
|
||||
raise serializers.ValidationError({'details': ERROR_CODE['2004']})
|
||||
return value
|
||||
|
||||
class AdminLoginSerializer(serializers.ModelSerializer):
|
||||
"""admin login serializer"""
|
||||
email = serializers.EmailField(required=True)
|
||||
password = serializers.CharField(required=True)
|
||||
|
||||
class Meta:
|
||||
"""
|
||||
meta class
|
||||
"""
|
||||
model = User
|
||||
fields = ('email', 'password')
|
||||
|
||||
def validate(self, attrs):
|
||||
user = User.objects.filter(email__iexact=attrs['email'], is_superuser=True
|
||||
).only('id', 'first_name', 'last_name', 'email',
|
||||
'username', 'is_active', 'is_superuser').first()
|
||||
|
||||
if not user or not user.check_password(attrs['password']):
|
||||
raise serializers.ValidationError({'details': ERROR_CODE['2002']})
|
||||
|
||||
self.context.update({'user': user})
|
||||
return attrs
|
||||
|
||||
def create(self, validated_data):
|
||||
"""
|
||||
used to return the user object after validation
|
||||
"""
|
||||
return self.context['user']
|
||||
|
||||
|
||||
class SuperUserSerializer(serializers.ModelSerializer):
|
||||
"""Super admin serializer"""
|
||||
user_type = serializers.SerializerMethodField('get_user_type')
|
||||
auth_token = serializers.SerializerMethodField('get_auth_token')
|
||||
refresh_token = serializers.SerializerMethodField('get_refresh_token')
|
||||
|
||||
def get_auth_token(self, obj):
|
||||
refresh = RefreshToken.for_user(obj)
|
||||
access_token = str(refresh.access_token)
|
||||
return access_token
|
||||
|
||||
def get_refresh_token(self, obj):
|
||||
refresh = RefreshToken.for_user(obj)
|
||||
refresh_token = str(refresh)
|
||||
return refresh_token
|
||||
|
||||
def get_user_type(self, obj):
|
||||
"""user type"""
|
||||
return str(NUMBER['three'])
|
||||
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = User
|
||||
fields = ['id', 'auth_token', 'refresh_token', 'username', 'email', 'first_name',
|
||||
'last_name', 'is_active', 'user_type']
|
||||
|
||||
|
||||
class GuardianSerializer(serializers.ModelSerializer):
|
||||
"""guardian serializer"""
|
||||
user_type = serializers.SerializerMethodField('get_user_type')
|
||||
email = serializers.SerializerMethodField('get_auth')
|
||||
first_name = serializers.SerializerMethodField('get_first_name')
|
||||
last_name = serializers.SerializerMethodField('get_last_name')
|
||||
auth_token = serializers.SerializerMethodField('get_auth_token')
|
||||
refresh_token = serializers.SerializerMethodField('get_refresh_token')
|
||||
|
||||
def get_auth_token(self, obj):
|
||||
refresh = RefreshToken.for_user(obj.user)
|
||||
access_token = str(refresh.access_token)
|
||||
return access_token
|
||||
|
||||
def get_refresh_token(self, obj):
|
||||
refresh = RefreshToken.for_user(obj.user)
|
||||
refresh_token = str(refresh)
|
||||
return refresh_token
|
||||
|
||||
def get_user_type(self, obj):
|
||||
"""user type"""
|
||||
if self.context.get('user_type', ''):
|
||||
return self.context.get('user_type')
|
||||
# remove the below code once user_type can be passed
|
||||
# from everywhere from where this serializer is being called
|
||||
else:
|
||||
email_verified = UserEmailOtp.objects.filter(
|
||||
email=obj.user.username
|
||||
).last()
|
||||
if email_verified and email_verified.user_type is not None:
|
||||
return email_verified.user_type
|
||||
return str(NUMBER['two'])
|
||||
|
||||
def get_auth(self, obj):
|
||||
"""user email address"""
|
||||
return obj.user.username
|
||||
|
||||
def get_first_name(self, obj):
|
||||
"""user first name"""
|
||||
return obj.user.first_name
|
||||
|
||||
def get_last_name(self, obj):
|
||||
"""user last name"""
|
||||
return obj.user.last_name
|
||||
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = Guardian
|
||||
fields = ['id', 'auth_token', 'refresh_token', 'email', 'first_name', 'last_name', 'country_code',
|
||||
'phone', 'family_name', 'gender', 'dob', 'referral_code', 'is_active', 'is_deleted',
|
||||
'is_complete_profile', 'passcode', 'image', 'created_at', 'updated_at', 'user_type', 'country_name']
|
||||
|
||||
|
||||
class JuniorSerializer(serializers.ModelSerializer):
|
||||
"""junior serializer"""
|
||||
user_type = serializers.SerializerMethodField('get_user_type')
|
||||
email = serializers.SerializerMethodField('get_auth')
|
||||
first_name = serializers.SerializerMethodField('get_first_name')
|
||||
last_name = serializers.SerializerMethodField('get_last_name')
|
||||
auth_token = serializers.SerializerMethodField('get_auth_token')
|
||||
refresh_token = serializers.SerializerMethodField('get_refresh_token')
|
||||
|
||||
def get_auth_token(self, obj):
|
||||
refresh = RefreshToken.for_user(obj.auth)
|
||||
access_token = str(refresh.access_token)
|
||||
return access_token
|
||||
|
||||
def get_refresh_token(self, obj):
|
||||
refresh = RefreshToken.for_user(obj.auth)
|
||||
refresh_token = str(refresh)
|
||||
return refresh_token
|
||||
|
||||
def get_user_type(self, obj):
|
||||
email_verified = UserEmailOtp.objects.filter(email=obj.auth.username).last()
|
||||
if email_verified and email_verified.user_type is not None:
|
||||
return email_verified.user_type
|
||||
return str(NUMBER['one'])
|
||||
|
||||
def get_auth(self, obj):
|
||||
return obj.auth.username
|
||||
|
||||
def get_first_name(self, obj):
|
||||
return obj.auth.first_name
|
||||
|
||||
def get_last_name(self, obj):
|
||||
return obj.auth.last_name
|
||||
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = Junior
|
||||
fields = ['id', 'auth_token', 'refresh_token', 'email', 'first_name', 'last_name', 'country_code',
|
||||
'phone', 'gender', 'dob', 'guardian_code', 'referral_code','is_active', 'is_password_set',
|
||||
'is_complete_profile', 'created_at', 'image', 'updated_at', 'user_type', 'country_name','is_invited',
|
||||
'is_deleted']
|
||||
|
||||
class EmailVerificationSerializer(serializers.ModelSerializer):
|
||||
"""Email verification serializer"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = UserEmailOtp
|
||||
fields = ('email',)
|
||||
|
||||
|
||||
|
||||
class DefaultTaskImagesSerializer(serializers.ModelSerializer):
|
||||
"""Update Password after verification"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = DefaultTaskImages
|
||||
fields = ['id', 'task_name', 'image_url']
|
||||
def create(self, validated_data):
|
||||
# create default task object
|
||||
data = DefaultTaskImages.objects.create(**validated_data)
|
||||
return data
|
||||
|
||||
class DefaultTaskImagesDetailsSerializer(serializers.ModelSerializer):
|
||||
"""Update Password after verification"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = DefaultTaskImages
|
||||
fields = '__all__'
|
||||
|
||||
class UserDeleteSerializer(serializers.ModelSerializer):
|
||||
"""User Delete Serializer"""
|
||||
class Meta(object):
|
||||
"""Meta Information"""
|
||||
model = UserDelete
|
||||
fields = ['id','reason']
|
||||
def create(self, validated_data):
|
||||
user = self.context['user']
|
||||
user_type = str(self.context['user_type'])
|
||||
data = validated_data.get('reason')
|
||||
passwd = self.context['password']
|
||||
signup_method = self.context['signup_method']
|
||||
random_num = secrets.randbelow(10001)
|
||||
user_tb = User.objects.filter(id=user.id).last()
|
||||
user_type_datas = UserEmailOtp.objects.filter(email=user.email).last()
|
||||
# check password and sign up method
|
||||
if user_tb and user_tb.check_password(passwd) and signup_method == str(NUMBER['one']):
|
||||
user_type_data = user_type_datas.user_type
|
||||
instance = delete_user_account_condition(user, user_type_data, user_type, user_tb, data, random_num)
|
||||
return instance
|
||||
elif user_tb and passwd is None and signup_method in ['2','3']:
|
||||
inst = delete_user_account_condition_social(user, user_type, user_tb, data, random_num)
|
||||
return inst
|
||||
else:
|
||||
raise serializers.ValidationError({"details": ERROR_CODE['2031'], "code": "400", "status": "failed"})
|
||||
|
||||
|
||||
class UserNotificationSerializer(serializers.ModelSerializer):
|
||||
"""User Notification serializer"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = UserNotification
|
||||
fields = '__all__'
|
||||
|
||||
|
||||
class UpdateUserNotificationSerializer(serializers.ModelSerializer):
|
||||
"""Update User Notification serializer"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = UserNotification
|
||||
fields = ['push_notification', 'email_notification', 'sms_notification']
|
||||
|
||||
def create(self, validated_data):
|
||||
instance = UserNotification.objects.filter(user=self.context).last()
|
||||
if instance:
|
||||
# change notification status
|
||||
instance.push_notification = validated_data.get('push_notification',instance.push_notification)
|
||||
instance.email_notification = validated_data.get('email_notification', instance.email_notification)
|
||||
instance.sms_notification = validated_data.get('sms_notification', instance.sms_notification)
|
||||
instance.save()
|
||||
else:
|
||||
instance = UserNotification.objects.create(user=self.context)
|
||||
return instance
|
||||
|
||||
class UserPhoneOtpSerializer(serializers.ModelSerializer):
|
||||
"""User Phone serializers"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = UserPhoneOtp
|
||||
fields = '__all__'
|
||||
|
||||
class ForceUpdateSerializer(serializers.ModelSerializer):
|
||||
""" ForceUpdate Serializer
|
||||
"""
|
||||
|
||||
class Meta(object):
|
||||
""" meta info """
|
||||
model = ForceUpdate
|
||||
fields = ('id', 'version', 'device_type')
|
54
account/templates/templated_email/email_base.email
Normal file
54
account/templates/templated_email/email_base.email
Normal file
@ -0,0 +1,54 @@
|
||||
<!DOCTYPE HTML>
|
||||
{% block subject %}DinDin{% endblock %}
|
||||
{% load static %}
|
||||
|
||||
{% block html %}
|
||||
<html lang="en" style="height: 100%;">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type"
|
||||
content="text/html; charset=UTF-8">
|
||||
<meta name="viewport"
|
||||
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
|
||||
<title>Zod Bank | OTP</title>
|
||||
<style type="text/css">
|
||||
@media all and (max-width: 599px) {
|
||||
.block {
|
||||
display: block !important;
|
||||
width: 100%;
|
||||
}
|
||||
.top-space {
|
||||
padding: 15px 0 0 !important;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body style="margin: 0; padding: 0; background: #f7f8f9; height: 100%;">
|
||||
<!-- begin template body -->
|
||||
<table style="background:#f7f8f9; border: 0; border-collapse: separate; border-spacing: 0px; margin: auto; width: 100%; font-family: Arial, Helvetica, sans-serif; height: 100%;" aria-describedby="email-data-wrapper">
|
||||
<tr>
|
||||
<td style="padding: 0;">
|
||||
<table style="background-color: white; border-collapse: separate; border-spacing: 0px; border: 1px solid #e4e8eb; width: 100%; max-width: 600px; margin-right:auto; margin-left: auto;
|
||||
font-family: Arial, Helvetica, sans-serif;" aria-describedby="email-data-wrapper">
|
||||
<tr>
|
||||
<td style="padding: 41px 30px 40px; height: 39px; background: url({% static 'images/backgrounds/email_template.png' %}) left center no-repeat; background-size: cover;">
|
||||
</td>
|
||||
</tr>
|
||||
{% block plain %}
|
||||
{% endblock %}
|
||||
<tr>
|
||||
<td style="padding: 0 27px;">
|
||||
<p style="margin: 0; font-size: 14px; line-height: 20px; color: #505050; font-weight: 400;">-</p>
|
||||
<p style="margin: 0; font-size: 14px; line-height: 20px; color: #505050; font-weight: 400;">Cheers!</p>
|
||||
<p style="margin: 0 0 30px; font-size: 14px; line-height: 20px; color: #505050; font-weight: 700;">Zod Bank Team</p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<!-- end template body -->
|
||||
</body>
|
||||
</html>
|
||||
{% endblock %}
|
@ -0,0 +1,23 @@
|
||||
{% extends "templated_email/email_base.email" %}
|
||||
|
||||
{% block subject %}
|
||||
OTP Verification
|
||||
{% endblock %}
|
||||
|
||||
{% block plain %}
|
||||
<tr>
|
||||
<td style="padding: 0 27px 15px;">
|
||||
<p style="margin: 0; font-size: 16px; line-height: 20px; padding: 36px 0 0; font-weight: 500; color: #1f2532;">
|
||||
Hi User,
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 0 27px 22px;">
|
||||
<p style="margin: 0;font-size: 14px; font-weight: 400; line-height: 21px; color: #1f2532;">
|
||||
You are receiving this email for email verification. Please use <b>{{ otp }} </b>as the verification code for your email address & username.
|
||||
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
{% endblock %}
|
@ -0,0 +1,23 @@
|
||||
{% extends "templated_email/email_base.email" %}
|
||||
|
||||
{% block subject %}
|
||||
Password Reset Verification Code
|
||||
{% endblock %}
|
||||
|
||||
{% block plain %}
|
||||
<tr>
|
||||
<td style="padding: 0 27px 15px;">
|
||||
<p style="margin: 0; font-size: 16px; line-height: 20px; padding: 36px 0 0; font-weight: 500; color: #1f2532;">
|
||||
Hi User,
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 0 27px 22px;">
|
||||
<p style="margin: 0;font-size: 14px; font-weight: 400; line-height: 21px; color: #1f2532;">
|
||||
You are receiving this email for reset password verification. Please use <b>{{ verification_code }} </b>as the verification code.
|
||||
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
{% endblock %}
|
23
account/templates/templated_email/junior_approval_mail.email
Normal file
23
account/templates/templated_email/junior_approval_mail.email
Normal file
@ -0,0 +1,23 @@
|
||||
{% extends "templated_email/email_base.email" %}
|
||||
|
||||
{% block subject %}
|
||||
Approval Email
|
||||
{% endblock %}
|
||||
|
||||
{% block plain %}
|
||||
<tr>
|
||||
<td style="padding: 0 27px 15px;">
|
||||
<p style="margin: 0; font-size: 16px; line-height: 20px; padding: 36px 0 0; font-weight: 500; color: #1f2532;">
|
||||
Hello,
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 0 27px 22px;">
|
||||
<p style="margin: 0;font-size: 14px; font-weight: 400; line-height: 21px; color: #1f2532;">
|
||||
Please approve {{full_name}} for accessing the Zod bank platform as a junior.
|
||||
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
{% endblock %}
|
@ -0,0 +1,24 @@
|
||||
{% extends "templated_email/email_base.email" %}
|
||||
|
||||
{% block subject %}
|
||||
Invitation Email
|
||||
{% endblock %}
|
||||
|
||||
{% block plain %}
|
||||
<tr>
|
||||
<td style="padding: 0 27px 15px;">
|
||||
<p style="margin: 0; font-size: 16px; line-height: 20px; padding: 36px 0 0; font-weight: 500; color: #1f2532;">
|
||||
Hi {{full_name}},
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 0 27px 22px;">
|
||||
<p style="margin: 0;font-size: 14px; font-weight: 400; line-height: 21px; color: #1f2532;">
|
||||
You are receiving this email for joining the ZOD bank platform. Please use <b>{{ url }} </b> link to join the platform.
|
||||
<br> Your credentials are:- username = <b>{{email}}</b> and password <b>{{password}}</b><br> <br>Below are the steps to complete the account and how to use this platform.
|
||||
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
{% endblock %}
|
22
account/templates/templated_email/support_mail.email
Normal file
22
account/templates/templated_email/support_mail.email
Normal file
@ -0,0 +1,22 @@
|
||||
{% extends "templated_email/email_base.email" %}
|
||||
|
||||
{% block subject %}
|
||||
Support Mail
|
||||
{% endblock %}
|
||||
|
||||
{% block plain %}
|
||||
<tr>
|
||||
<td style="padding: 0 27px 15px;">
|
||||
<p style="margin: 0; font-size: 16px; line-height: 20px; padding: 36px 0 0; font-weight: 500; color: #1f2532;">
|
||||
Hi Support Team,
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 0 27px 22px;">
|
||||
<p style="margin: 0;font-size: 14px; font-weight: 400; line-height: 21px; color: #1f2532;">
|
||||
<b>{{name}}</b> have some queries and need some support. Please support them by using their email address <b> {{sender}}</b>. <br> <br> <b>Queries are:- </b> <br><li> {{ message }}</li>
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
{% endblock %}
|
22
account/templates/templated_email/user_deactivate.email
Normal file
22
account/templates/templated_email/user_deactivate.email
Normal file
@ -0,0 +1,22 @@
|
||||
{% extends "templated_email/email_base.email" %}
|
||||
|
||||
{% block subject %}
|
||||
Account Deactivated
|
||||
{% endblock %}
|
||||
|
||||
{% block plain %}
|
||||
<tr>
|
||||
<td style="padding: 0 27px 15px;">
|
||||
<p style="margin: 0; font-size: 16px; line-height: 20px; padding: 36px 0 0; font-weight: 500; color: #1f2532;">
|
||||
Hi User,
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 0 27px 22px;">
|
||||
<p style="margin: 0;font-size: 14px; font-weight: 400; line-height: 21px; color: #1f2532;">
|
||||
Your account has been deactivated by admin. Please reach out to the admin for assistance.
|
||||
</p>
|
||||
</td>
|
||||
</tr>
|
||||
{% endblock %}
|
60
account/tests.py
Normal file
60
account/tests.py
Normal file
@ -0,0 +1,60 @@
|
||||
"""
|
||||
test cases file of account
|
||||
"""
|
||||
# django imports
|
||||
from django.test import TestCase
|
||||
from rest_framework.test import APIClient
|
||||
from rest_framework import status
|
||||
from django.contrib.auth.models import User
|
||||
from django.urls import reverse
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
|
||||
|
||||
class UserLoginTestCase(TestCase):
|
||||
"""
|
||||
test cases for login
|
||||
"""
|
||||
def setUp(self):
|
||||
"""
|
||||
set up data
|
||||
:return:
|
||||
"""
|
||||
self.client = APIClient()
|
||||
self.user_email = 'user@example.com'
|
||||
self.user = User.objects.create_superuser(username=self.user_email, email=self.user_email)
|
||||
self.user.set_password('user@1234')
|
||||
self.user.save()
|
||||
|
||||
def test_admin_login_success(self):
|
||||
"""
|
||||
test admin login with valid credentials
|
||||
:return:
|
||||
"""
|
||||
url = reverse('account:admin-login')
|
||||
data = {
|
||||
'email': self.user_email,
|
||||
'password': 'user@1234',
|
||||
}
|
||||
response = self.client.post(url, data, format='json')
|
||||
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||
self.assertIn('auth_token', response.data['data'])
|
||||
self.assertIn('refresh_token', response.data['data'])
|
||||
self.assertEqual(response.data['data']['username'], data['email'])
|
||||
|
||||
def test_admin_login_invalid_credentials(self):
|
||||
"""
|
||||
test admin login with invalid credentials
|
||||
:return:
|
||||
"""
|
||||
url = reverse('account:admin-login')
|
||||
data = {
|
||||
'email': self.user_email,
|
||||
'password': 'user@1235',
|
||||
}
|
||||
response = self.client.post(url, data, format='json')
|
||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||
self.assertNotIn('auth_token', response.data)
|
||||
self.assertNotIn('refresh_token', response.data)
|
||||
|
||||
# Add more test cases as needed
|
||||
|
71
account/urls.py
Normal file
71
account/urls.py
Normal file
@ -0,0 +1,71 @@
|
||||
""" Urls files"""
|
||||
"""Django import"""
|
||||
from django.urls import path, include
|
||||
"""Third party import"""
|
||||
from rest_framework import routers
|
||||
# Import view functions
|
||||
# UserLogin views,
|
||||
# SendPhoneOtp views,
|
||||
# UserPhoneVerification views,
|
||||
# UserEmailVerification views,
|
||||
# ReSendEmailOtp views,
|
||||
# ForgotPasswordAPIView views,
|
||||
# ResetPasswordAPIView views,
|
||||
# ChangePasswordAPIView views,
|
||||
# UpdateProfileImage views,
|
||||
# GoogleLoginViewSet views,
|
||||
# SigninWithApple views,
|
||||
# ProfileAPIViewSet views,
|
||||
# UploadImageAPIViewSet views,
|
||||
# DefaultImageAPIViewSet views,
|
||||
# DeleteUserProfileAPIViewSet views,
|
||||
# UserNotificationAPIViewSet views,
|
||||
# UpdateUserNotificationAPIViewSet views,
|
||||
# SendSupportEmail views,
|
||||
# LogoutAPIView views,
|
||||
# AccessTokenAPIView views"""
|
||||
from .views import (UserLogin, SendPhoneOtp, UserPhoneVerification, UserEmailVerification, ReSendEmailOtp,
|
||||
ForgotPasswordAPIView, ResetPasswordAPIView, ChangePasswordAPIView, UpdateProfileImage,
|
||||
GoogleLoginViewSet, SigninWithApple, ProfileAPIViewSet, UploadImageAPIViewSet,
|
||||
DefaultImageAPIViewSet, DeleteUserProfileAPIViewSet, UserNotificationAPIViewSet,
|
||||
UpdateUserNotificationAPIViewSet, SendSupportEmail, LogoutAPIView, AccessTokenAPIView,
|
||||
AdminLoginViewSet, ForceUpdateViewSet)
|
||||
"""Router"""
|
||||
router = routers.SimpleRouter()
|
||||
|
||||
"""API End points with router"""
|
||||
router.register('user', UserLogin, basename='user')
|
||||
"""super admin login"""
|
||||
router.register('admin', AdminLoginViewSet, basename='admin')
|
||||
"""google login end point"""
|
||||
router.register('google-login', GoogleLoginViewSet, basename='admin')
|
||||
"""email verification end point"""
|
||||
router.register('user-email-verification', UserEmailVerification, basename='user-email-verification')
|
||||
"""Resend email otp end point"""
|
||||
router.register('resend-email-otp', ReSendEmailOtp, basename='resend-email-otp')
|
||||
"""Profile end point"""
|
||||
router.register('profile', ProfileAPIViewSet, basename='profile')
|
||||
"""Upload default task image end point"""
|
||||
router.register('upload-default-task-image', UploadImageAPIViewSet, basename='upload-default-task-image')
|
||||
"""Fetch default task image end point"""
|
||||
router.register('default-task-image', DefaultImageAPIViewSet, basename='default-task-image')
|
||||
"""Delete user account"""
|
||||
router.register('delete', DeleteUserProfileAPIViewSet, basename='delete')
|
||||
"""user account notification"""
|
||||
router.register('user-notification', UserNotificationAPIViewSet, basename='user-notification')
|
||||
"""update user account notification"""
|
||||
router.register('update-user-notification', UpdateUserNotificationAPIViewSet, basename='update-user-notification')
|
||||
# Force update entry API
|
||||
router.register('force-update', ForceUpdateViewSet, basename='force-update')
|
||||
"""Define url pattern"""
|
||||
urlpatterns = [
|
||||
path('api/v1/', include(router.urls)),
|
||||
path('api/v1/forgot-password/', ForgotPasswordAPIView.as_view()),
|
||||
path('api/v1/reset-password/', ResetPasswordAPIView.as_view()),
|
||||
path('api/v1/change-password/', ChangePasswordAPIView.as_view()),
|
||||
path('api/v1/update-profile-image/', UpdateProfileImage.as_view()),
|
||||
path('api/v1/apple-login/', SigninWithApple.as_view(), name='signup_with_apple'),
|
||||
path('api/v1/send-support-email/', SendSupportEmail.as_view(), name='send-support-email'),
|
||||
path('api/v1/logout/', LogoutAPIView.as_view(), name='logout'),
|
||||
path('api/v1/generate-token/', AccessTokenAPIView.as_view(), name='generate-token')
|
||||
]
|
326
account/utils.py
Normal file
326
account/utils.py
Normal file
@ -0,0 +1,326 @@
|
||||
"""Account utils"""
|
||||
from celery import shared_task
|
||||
import random
|
||||
"""Import django"""
|
||||
from django.conf import settings
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.response import Response
|
||||
"""Third party Django app"""
|
||||
from templated_email import send_templated_mail
|
||||
import jwt
|
||||
import string
|
||||
from datetime import datetime
|
||||
from calendar import timegm
|
||||
from uuid import uuid4
|
||||
# Import secrets module for generating random number
|
||||
import secrets
|
||||
from rest_framework import serializers
|
||||
# Django App Import
|
||||
# Import models from junior App,
|
||||
# Import models from guardian App,
|
||||
# Import models from account App,
|
||||
# Import messages from base package"""
|
||||
from junior.models import Junior
|
||||
from guardian.models import Guardian
|
||||
from account.models import UserDelete, UserDeviceDetails
|
||||
from base.messages import ERROR_CODE
|
||||
from django.utils import timezone
|
||||
from base.constants import NUMBER
|
||||
from junior.models import JuniorPoints
|
||||
# Define delete
|
||||
# user account condition,
|
||||
# Define delete
|
||||
# user account
|
||||
# condition for social
|
||||
# login account,
|
||||
# Update junior account,
|
||||
# Update guardian account,
|
||||
# Define custom email for otp verification,
|
||||
# Define support email for user's query,
|
||||
# Define custom success response,
|
||||
# Define custom error response,
|
||||
# Generate access token,
|
||||
# refresh token by using jwt,
|
||||
# Define function for generating
|
||||
# guardian code, junior code,
|
||||
# referral code,
|
||||
# Define function for generating
|
||||
# alphanumeric code
|
||||
# otp expiry
|
||||
def delete_user_account_condition(user, user_type_data, user_type, user_tb, data, random_num):
|
||||
"""delete user account"""
|
||||
if user_type == '1' and user_type_data == '1':
|
||||
junior_account_update(user_tb)
|
||||
elif user_type == '2' and user_type_data == '2':
|
||||
guardian_account_update(user_tb)
|
||||
else:
|
||||
raise serializers.ValidationError({"details": ERROR_CODE['2030'], "code": "400", "status": "failed"})
|
||||
user_tb.email = str(random_num) + str('@D_') + '{}'.format(user_tb.username).lower()
|
||||
user_tb.username = str(random_num) + str('@D_') + '{}'.format(user_tb.username).lower()
|
||||
d_email = user_tb.email
|
||||
o_mail = user.email
|
||||
# update user email with dummy email
|
||||
user_tb.save()
|
||||
"""create object in user delete model"""
|
||||
instance = UserDelete.objects.create(user=user_tb, d_email=d_email, old_email=o_mail,
|
||||
is_active=True, reason=data)
|
||||
|
||||
return instance
|
||||
|
||||
def delete_user_account_condition_social(user, user_type,user_tb, data, random_num):
|
||||
"""delete user account"""
|
||||
if user_type == '1':
|
||||
junior_account_update(user_tb)
|
||||
elif user_type == '2':
|
||||
guardian_account_update(user_tb)
|
||||
else:
|
||||
raise serializers.ValidationError({"details": ERROR_CODE['2030'], "code": "400", "status": "failed"})
|
||||
user_tb.email = str(random_num) + str('@D_') + '{}'.format(user_tb.username).lower()
|
||||
user_tb.username = str(random_num) + str('@D_') + '{}'.format(user_tb.username).lower()
|
||||
dummy_email = user_tb.email
|
||||
old_mail = user.email
|
||||
# update user email with dummy email
|
||||
user_tb.save()
|
||||
"""create object in user delete model"""
|
||||
instance_data = UserDelete.objects.create(user=user_tb, d_email=dummy_email, old_email=old_mail,
|
||||
is_active=True, reason=data)
|
||||
|
||||
return instance_data
|
||||
def junior_account_update(user_tb):
|
||||
"""junior account delete"""
|
||||
junior_data = Junior.objects.filter(auth__email=user_tb.email).first()
|
||||
if junior_data:
|
||||
# Update junior account
|
||||
junior_data.is_active = False
|
||||
junior_data.is_verified = False
|
||||
junior_data.guardian_code = None
|
||||
junior_data.guardian_code_status = None
|
||||
junior_data.is_deleted = True
|
||||
junior_data.save()
|
||||
JuniorPoints.objects.filter(junior=junior_data).delete()
|
||||
|
||||
def guardian_account_update(user_tb):
|
||||
"""update guardian account after delete the user account"""
|
||||
guardian_data = Guardian.objects.filter(user__email=user_tb.email).first()
|
||||
if guardian_data:
|
||||
# Update guardian account
|
||||
guardian_data.is_active = False
|
||||
guardian_data.is_verified = False
|
||||
guardian_data.is_deleted = True
|
||||
guardian_data.save()
|
||||
jun_data = Junior.objects.filter(guardian_code__icontains=str(guardian_data.guardian_code))
|
||||
"""Disassociate relation between guardian and junior"""
|
||||
for data in jun_data:
|
||||
data.guardian_code.remove(guardian_data.guardian_code)
|
||||
data.save()
|
||||
@shared_task()
|
||||
def send_otp_email(recipient_email, otp):
|
||||
"""Send otp on email with template"""
|
||||
from_email = settings.EMAIL_FROM_ADDRESS
|
||||
recipient_list = [recipient_email]
|
||||
"""Send otp on email"""
|
||||
send_templated_mail(
|
||||
template_name='email_otp_verification.email',
|
||||
from_email=from_email,
|
||||
recipient_list=recipient_list,
|
||||
context={
|
||||
'otp': otp
|
||||
}
|
||||
)
|
||||
return otp
|
||||
|
||||
|
||||
@shared_task()
|
||||
def send_all_email(template_name, email, otp):
|
||||
"""
|
||||
Send all type of email by passing template name
|
||||
template_name: string
|
||||
email: string
|
||||
otp: string
|
||||
"""
|
||||
from_email = settings.EMAIL_FROM_ADDRESS
|
||||
recipient_list = [email]
|
||||
send_templated_mail(
|
||||
template_name=template_name,
|
||||
from_email=from_email,
|
||||
recipient_list=recipient_list,
|
||||
context={
|
||||
'verification_code': otp
|
||||
}
|
||||
)
|
||||
|
||||
return otp
|
||||
|
||||
@shared_task
|
||||
def user_device_details(user, device_id):
|
||||
"""
|
||||
Used to store the device id of the user
|
||||
user: user object
|
||||
device_id: string
|
||||
return
|
||||
"""
|
||||
device_details, created = UserDeviceDetails.objects.get_or_create(user__id=user)
|
||||
if device_details:
|
||||
device_details.device_id = device_id
|
||||
device_details.save()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def send_support_email(name, sender, message):
|
||||
"""Send otp on email with template"""
|
||||
to_email = [settings.EMAIL_FROM_ADDRESS]
|
||||
from_email = settings.DEFAULT_ADDRESS
|
||||
"""Send support email to zod bank support team"""
|
||||
send_templated_mail(
|
||||
template_name='support_mail.email',
|
||||
from_email=from_email,
|
||||
recipient_list=to_email,
|
||||
context={
|
||||
'name': name.title(),
|
||||
'sender': sender,
|
||||
'message': message
|
||||
}
|
||||
)
|
||||
return name
|
||||
|
||||
|
||||
def custom_response(detail, data=None, response_status=status.HTTP_200_OK, count=None):
|
||||
"""Custom response code"""
|
||||
if not data:
|
||||
"""when data is none"""
|
||||
data = None
|
||||
return Response({"data": data, "message": detail, "status": "success",
|
||||
"code": response_status, "count": count})
|
||||
|
||||
|
||||
def custom_error_response(detail, response_status):
|
||||
"""
|
||||
function is used for getting same global error response for all
|
||||
:param detail: error message .
|
||||
:param response_status: http status.
|
||||
:return: Json response
|
||||
"""
|
||||
if not detail:
|
||||
"""when details is empty"""
|
||||
detail = {}
|
||||
if response_status == 406:
|
||||
return Response({"error": detail, "status": "failed", "code": response_status,},
|
||||
status=status.HTTP_308_PERMANENT_REDIRECT)
|
||||
else:
|
||||
return Response({"error": detail, "status": "failed", "code": response_status},
|
||||
status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
def get_user_data(attrs):
|
||||
"""
|
||||
used to decode token
|
||||
"""
|
||||
user_data = jwt.decode(jwt=attrs['token'], options={'verify_signature': False},
|
||||
algorithms=['RS256'])
|
||||
return user_data
|
||||
|
||||
|
||||
def generate_jwt_token(token_type: str, now_time: int, data: dict = dict):
|
||||
"""
|
||||
used to generate jwt token
|
||||
"""
|
||||
if type(data) == type:
|
||||
data = {}
|
||||
"""Update data dictionary"""
|
||||
data.update({
|
||||
'token_type': token_type,
|
||||
'iss': 'your_site_url',
|
||||
'iat': timegm(datetime.utcnow().utctimetuple()),
|
||||
'jti': uuid4().hex
|
||||
})
|
||||
"""Access and Refresh token"""
|
||||
TOKEN_TYPE = ["access", "refresh"]
|
||||
if token_type == TOKEN_TYPE[1]:
|
||||
"""Refresh token"""
|
||||
exp = now_time + settings.SIMPLE_JWT['REFRESH_TOKEN_LIFETIME']
|
||||
else:
|
||||
"""access token"""
|
||||
exp = now_time + settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME']
|
||||
|
||||
data.update({
|
||||
"exp": timegm(exp.utctimetuple())
|
||||
})
|
||||
|
||||
|
||||
signing_key = secrets.token_hex(32)
|
||||
|
||||
return jwt.encode(payload=data, key=signing_key,
|
||||
algorithm='HS256')
|
||||
|
||||
|
||||
def get_token(data: dict = dict):
|
||||
""" create access and refresh token """
|
||||
now_time = datetime.utcnow()
|
||||
"""generate access token"""
|
||||
access = generate_jwt_token('access', now_time, data)
|
||||
"""generate refresh token"""
|
||||
refresh = generate_jwt_token('refresh', now_time, data)
|
||||
|
||||
return {
|
||||
'access': access,
|
||||
'refresh': refresh
|
||||
}
|
||||
|
||||
|
||||
def generate_alphanumeric_code(length):
|
||||
"""Generate alphanumeric code"""
|
||||
alphabet = string.ascii_letters + string.digits
|
||||
code = ''.join(secrets.choice(alphabet) for _ in range(length))
|
||||
return code
|
||||
|
||||
|
||||
def generate_code(value, user_id):
|
||||
"""generate referral, junior and guardian code"""
|
||||
code = value + str(user_id).zfill(3)
|
||||
return code
|
||||
|
||||
|
||||
OTP_EXPIRY = timezone.now() + timezone.timedelta(days=1)
|
||||
|
||||
|
||||
def get_user_full_name(user_obj):
|
||||
"""
|
||||
to get user's full name
|
||||
"""
|
||||
return f"{user_obj.first_name} {user_obj.last_name}" if user_obj.first_name or user_obj.last_name else "User"
|
||||
|
||||
|
||||
def make_special_password(length=10):
|
||||
"""
|
||||
to make secured password
|
||||
:param length:
|
||||
:return:
|
||||
"""
|
||||
# Define character sets
|
||||
lowercase_letters = string.ascii_lowercase
|
||||
uppercase_letters = string.ascii_uppercase
|
||||
digits = string.digits
|
||||
special_characters = '@#$%&*?'
|
||||
|
||||
# Combine character sets
|
||||
alphabets = lowercase_letters + uppercase_letters
|
||||
|
||||
# Create a password with random characters
|
||||
password = [
|
||||
secrets.choice(uppercase_letters) +
|
||||
secrets.choice(lowercase_letters) +
|
||||
secrets.choice(digits) +
|
||||
secrets.choice(special_characters) +
|
||||
''.join(secrets.choice(alphabets) for _ in range(length - 4))
|
||||
]
|
||||
|
||||
return ''.join(password)
|
||||
|
||||
def task_status_fun(status_value):
|
||||
"""task status"""
|
||||
task_status_value = ['1']
|
||||
if str(status_value) == '2':
|
||||
task_status_value = ['2', '4']
|
||||
elif str(status_value) == '3':
|
||||
task_status_value = ['3', '5', '6']
|
||||
return task_status_value
|
752
account/views.py
Normal file
752
account/views.py
Normal file
@ -0,0 +1,752 @@
|
||||
"""Account view """
|
||||
import threading
|
||||
|
||||
from notifications.utils import remove_fcm_token
|
||||
|
||||
# django imports
|
||||
from rest_framework.viewsets import GenericViewSet, mixins
|
||||
from datetime import datetime, timedelta
|
||||
from rest_framework import viewsets, status, views
|
||||
from rest_framework.decorators import action
|
||||
import logging
|
||||
from django.utils import timezone
|
||||
import jwt
|
||||
from django.contrib.auth import logout
|
||||
from django.contrib.auth import authenticate, login
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from templated_email import send_templated_mail
|
||||
import google.oauth2.credentials
|
||||
import google.auth.transport.requests
|
||||
from rest_framework import status
|
||||
import requests
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import mixins
|
||||
from django.conf import settings
|
||||
|
||||
# local imports
|
||||
from guardian.models import Guardian
|
||||
from junior.models import Junior, JuniorPoints
|
||||
from guardian.utils import upload_image_to_alibaba
|
||||
from account.models import (UserDeviceDetails, UserPhoneOtp, UserEmailOtp, DefaultTaskImages, UserNotification,
|
||||
ForceUpdate)
|
||||
from django.contrib.auth.models import User
|
||||
from .serializers import (SuperUserSerializer, GuardianSerializer, JuniorSerializer, EmailVerificationSerializer,
|
||||
ForgotPasswordSerializer, ResetPasswordSerializer, ChangePasswordSerializer,
|
||||
GoogleLoginSerializer, UpdateGuardianImageSerializer, UpdateJuniorProfileImageSerializer,
|
||||
DefaultTaskImagesSerializer, DefaultTaskImagesDetailsSerializer, UserDeleteSerializer,
|
||||
UserNotificationSerializer, UpdateUserNotificationSerializer, UserPhoneOtpSerializer,
|
||||
AdminLoginSerializer, ForceUpdateSerializer)
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
||||
from base.constants import NUMBER, ZOD, JUN, GRD, USER_TYPE_FLAG
|
||||
from guardian.tasks import generate_otp
|
||||
from account.utils import (send_otp_email, send_support_email, custom_response, custom_error_response,
|
||||
generate_code, OTP_EXPIRY, user_device_details, send_all_email)
|
||||
from junior.serializers import JuniorProfileSerializer
|
||||
from guardian.serializers import GuardianProfileSerializer
|
||||
|
||||
class GoogleLoginMixin(object):
|
||||
"""google login mixin"""
|
||||
@staticmethod
|
||||
def google_login(request):
|
||||
"""google login function"""
|
||||
access_token = request.data.get('access_token')
|
||||
user_type = request.META.get('HTTP_USER_TYPE')
|
||||
device_id = request.META.get('HTTP_DEVICE_ID')
|
||||
if not access_token:
|
||||
return Response({'error': 'Access token is required.'}, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
try:
|
||||
# Validate the access token and obtain the user's email and name
|
||||
credentials = google.oauth2.credentials.Credentials.from_authorized_user_info(
|
||||
info={
|
||||
'access_token': access_token,
|
||||
'token_uri': 'https://oauth2.googleapis.com/token',
|
||||
'client_id': settings.GOOGLE_CLIENT_ID,
|
||||
'client_secret': settings.GOOGLE_CLIENT_SECRET,
|
||||
'refresh_token': None,
|
||||
}
|
||||
)
|
||||
user_info_endpoint = f'https://www.googleapis.com/oauth2/v3/userinfo?access_token={access_token}'
|
||||
headers = {'Authorization': f'Bearer {credentials.token}'}
|
||||
response = requests.get(user_info_endpoint, headers=headers)
|
||||
response.raise_for_status()
|
||||
user_info = response.json()
|
||||
email = user_info['email']
|
||||
first_name = user_info['given_name']
|
||||
last_name = user_info['family_name']
|
||||
profile_picture = user_info['picture']
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# Check if the user exists in your database or create a new user
|
||||
# ...
|
||||
user_data = User.objects.filter(email__iexact=email)
|
||||
if user_data.exists():
|
||||
if str(user_type) == '1':
|
||||
junior_query = Junior.objects.filter(auth=user_data.last()).last()
|
||||
if not junior_query:
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2071"],
|
||||
response_status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
serializer = JuniorSerializer(junior_query)
|
||||
elif str(user_type) == '2':
|
||||
guardian_query = Guardian.objects.filter(user=user_data.last()).last()
|
||||
if not guardian_query:
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2070"],
|
||||
response_status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
serializer = GuardianSerializer(guardian_query)
|
||||
else:
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2069"],
|
||||
response_status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
return custom_response(SUCCESS_CODE['3003'], serializer.data,
|
||||
response_status=status.HTTP_200_OK)
|
||||
|
||||
else:
|
||||
user_obj = User.objects.create(username=email, email=email, first_name=first_name, last_name=last_name)
|
||||
if str(user_type) == '1':
|
||||
junior_query = Junior.objects.create(auth=user_obj, is_verified=True, is_active=True,
|
||||
image=profile_picture, signup_method='2',
|
||||
junior_code=generate_code(JUN, user_obj.id),
|
||||
referral_code=generate_code(ZOD, user_obj.id)
|
||||
)
|
||||
serializer = JuniorSerializer(junior_query)
|
||||
position = Junior.objects.all().count()
|
||||
JuniorPoints.objects.create(junior=junior_query, position=position)
|
||||
elif str(user_type) == '2':
|
||||
guardian_query = Guardian.objects.create(user=user_obj, is_verified=True, is_active=True,
|
||||
image=profile_picture,signup_method='2',
|
||||
guardian_code=generate_code(GRD, user_obj.id),
|
||||
referral_code=generate_code(ZOD, user_obj.id)
|
||||
)
|
||||
serializer = GuardianSerializer(guardian_query)
|
||||
else:
|
||||
user_obj.delete()
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2069"],
|
||||
response_status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
device_detail, created = UserDeviceDetails.objects.get_or_create(user=user_obj)
|
||||
if device_detail:
|
||||
device_detail.device_id = device_id
|
||||
device_detail.save()
|
||||
# Return a JSON response with the user's email and name
|
||||
return custom_response(SUCCESS_CODE['3003'], serializer.data,
|
||||
response_status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class GoogleLoginViewSet(GoogleLoginMixin, viewsets.GenericViewSet):
|
||||
"""Google login viewset"""
|
||||
serializer_class = GoogleLoginSerializer
|
||||
|
||||
def create(self, request):
|
||||
"""Payload
|
||||
{
|
||||
"access_token",
|
||||
"user_type": "1"
|
||||
}"""
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
return self.google_login(request)
|
||||
|
||||
class SigninWithApple(views.APIView):
|
||||
"""This API is for sign in with Apple for app.
|
||||
Payload
|
||||
{
|
||||
"access_token",
|
||||
"user_type": "1"
|
||||
}"""
|
||||
def post(self, request):
|
||||
token = request.data.get("access_token")
|
||||
user_type = request.META.get('HTTP_USER_TYPE')
|
||||
device_id = request.META.get('HTTP_DEVICE_ID')
|
||||
try:
|
||||
decoded_data = jwt.decode(token, options={"verify_signature": False})
|
||||
user_data = {"email": decoded_data.get('email'), "username": decoded_data.get('email'), "is_active": True}
|
||||
if decoded_data.get("email"):
|
||||
try:
|
||||
user = User.objects.get(email=decoded_data.get("email"))
|
||||
if str(user_type) == '1':
|
||||
junior_data = Junior.objects.filter(auth=user).last()
|
||||
if not junior_data:
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2071"],
|
||||
response_status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
serializer = JuniorSerializer(junior_data)
|
||||
elif str(user_type) == '2':
|
||||
guardian_data = Guardian.objects.filter(user=user).last()
|
||||
if not guardian_data:
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2070"],
|
||||
response_status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
serializer = GuardianSerializer(guardian_data)
|
||||
else:
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2069"],
|
||||
response_status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
return custom_response(SUCCESS_CODE['3003'], serializer.data,
|
||||
response_status=status.HTTP_200_OK)
|
||||
|
||||
except User.DoesNotExist:
|
||||
user = User.objects.create(**user_data)
|
||||
if str(user_type) == '1':
|
||||
junior_query = Junior.objects.create(auth=user, is_verified=True, is_active=True,
|
||||
signup_method='3',
|
||||
junior_code=generate_code(JUN, user.id),
|
||||
referral_code=generate_code(ZOD, user.id))
|
||||
serializer = JuniorSerializer(junior_query)
|
||||
position = Junior.objects.all().count()
|
||||
JuniorPoints.objects.create(junior=junior_query, position=position)
|
||||
elif str(user_type) == '2':
|
||||
guardian_query = Guardian.objects.create(user=user, is_verified=True, is_active=True,
|
||||
signup_method='3',
|
||||
guardian_code=generate_code(GRD, user.id),
|
||||
referral_code=generate_code(ZOD, user.id))
|
||||
serializer = GuardianSerializer(guardian_query)
|
||||
else:
|
||||
user.delete()
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2069"],
|
||||
response_status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
device_detail, created = UserDeviceDetails.objects.get_or_create(user=user)
|
||||
if device_detail:
|
||||
device_detail.device_id = device_id
|
||||
device_detail.save()
|
||||
return custom_response(SUCCESS_CODE['3003'], serializer.data,
|
||||
response_status=status.HTTP_200_OK)
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class UpdateProfileImage(views.APIView):
|
||||
"""Update profile image"""
|
||||
permission_classes = [IsAuthenticated]
|
||||
def put(self, request, format=None):
|
||||
try:
|
||||
image = request.data['image']
|
||||
if image and image.size == NUMBER['zero']:
|
||||
return custom_error_response(ERROR_CODE['2035'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
filename = f"images/{image.name}"
|
||||
image_url = upload_image_to_alibaba(image, filename)
|
||||
image_data = image_url
|
||||
if str(request.data['user_type']) == '1':
|
||||
junior_query = Junior.objects.filter(auth=request.user).last()
|
||||
serializer = UpdateJuniorProfileImageSerializer(junior_query,
|
||||
data={'image':image_data}, partial=True)
|
||||
elif str(request.data['user_type']) == '2':
|
||||
guardian_query = Guardian.objects.filter(user=request.user).last()
|
||||
serializer = UpdateGuardianImageSerializer(guardian_query,
|
||||
data={'image':image_data}, partial=True)
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
return custom_response(SUCCESS_CODE['3017'], serializer.data, response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
return custom_error_response(ERROR_CODE['2036'],response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
class ChangePasswordAPIView(views.APIView):
|
||||
"""
|
||||
change password"
|
||||
"""
|
||||
serializer_class = ChangePasswordSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def post(self, request):
|
||||
"""
|
||||
POST request to change current login user password
|
||||
Payload
|
||||
{ "current_password":"Demo@123",
|
||||
"new_password":"Demo@123"
|
||||
}
|
||||
"""
|
||||
serializer = ChangePasswordSerializer(
|
||||
context=request.user,
|
||||
data=request.data
|
||||
)
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
return custom_response(
|
||||
SUCCESS_CODE['3007'],
|
||||
response_status=status.HTTP_200_OK
|
||||
)
|
||||
return custom_error_response(
|
||||
serializer.errors,
|
||||
response_status=status.HTTP_400_BAD_REQUEST
|
||||
)
|
||||
|
||||
class ResetPasswordAPIView(views.APIView):
|
||||
"""Reset password
|
||||
Payload
|
||||
{
|
||||
"verification_code":"373770",
|
||||
"password":"Demo@1323"
|
||||
}"""
|
||||
def post(self, request):
|
||||
serializer = ResetPasswordSerializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
return custom_response(SUCCESS_CODE['3006'], response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
class ForgotPasswordAPIView(views.APIView):
|
||||
"""
|
||||
Forgot password
|
||||
"""
|
||||
serializer_class = ForgotPasswordSerializer
|
||||
|
||||
def post(self, request):
|
||||
|
||||
"""
|
||||
Payload
|
||||
{
|
||||
"email": "abc@yopmail.com"
|
||||
}
|
||||
"""
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
email = serializer.validated_data['email']
|
||||
# generate otp
|
||||
verification_code = generate_otp()
|
||||
# Send the verification code to the user's email
|
||||
send_all_email.delay(
|
||||
'email_reset_verification.email', email, verification_code
|
||||
)
|
||||
expiry = timezone.now() + timezone.timedelta(days=1)
|
||||
user_data, created = UserEmailOtp.objects.get_or_create(
|
||||
email=email
|
||||
)
|
||||
if created:
|
||||
user_data.expired_at = expiry
|
||||
user_data.save()
|
||||
if user_data:
|
||||
user_data.otp = verification_code
|
||||
user_data.expired_at = expiry
|
||||
user_data.save()
|
||||
return custom_response(
|
||||
SUCCESS_CODE['3015'],
|
||||
response_status=status.HTTP_200_OK
|
||||
)
|
||||
|
||||
class SendPhoneOtp(viewsets.ModelViewSet):
|
||||
"""Send otp on phone"""
|
||||
serializer_class = UserPhoneOtpSerializer
|
||||
def create(self, request, *args, **kwargs):
|
||||
otp = generate_otp()
|
||||
phone_number = self.request.data['phone']
|
||||
if phone_number.isdigit() and len(phone_number) == 10:
|
||||
phone_otp, created = UserPhoneOtp.objects.get_or_create(country_code=self.request.data['country_code'],
|
||||
phone=self.request.data['phone'])
|
||||
if phone_otp:
|
||||
phone_otp.otp = otp
|
||||
phone_otp.save()
|
||||
return custom_response(None, {'phone_otp':otp}, response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(ERROR_CODE['2020'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class UserPhoneVerification(viewsets.ModelViewSet):
|
||||
"""Send otp on phone"""
|
||||
serializer_class = UserPhoneOtpSerializer
|
||||
def list(self, request, *args, **kwargs):
|
||||
try:
|
||||
phone_data = UserPhoneOtp.objects.filter(phone=self.request.GET.get('phone'),
|
||||
otp=self.request.GET.get('otp')).last()
|
||||
if phone_data:
|
||||
phone_data.is_verified = True
|
||||
phone_data.save()
|
||||
return custom_response(SUCCESS_CODE['3012'], response_status=status.HTTP_200_OK)
|
||||
else:
|
||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
except Exception:
|
||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class UserLogin(viewsets.ViewSet):
|
||||
"""User login"""
|
||||
@action(methods=['post'], detail=False)
|
||||
def login(self, request):
|
||||
username = request.data.get('username')
|
||||
password = request.data.get('password')
|
||||
user_type = request.META.get('HTTP_USER_TYPE')
|
||||
device_id = request.META.get('HTTP_DEVICE_ID')
|
||||
user = authenticate(request, username=username, password=password)
|
||||
|
||||
try:
|
||||
if user is not None:
|
||||
login(request, user)
|
||||
if str(user_type) == USER_TYPE_FLAG["TWO"]:
|
||||
guardian_data = Guardian.objects.filter(user__username=username).last()
|
||||
if guardian_data:
|
||||
if guardian_data.is_verified:
|
||||
serializer = GuardianSerializer(
|
||||
guardian_data, context={'user_type': user_type}
|
||||
).data
|
||||
else:
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2070"],
|
||||
response_status=status.HTTP_401_UNAUTHORIZED
|
||||
)
|
||||
elif str(user_type) == USER_TYPE_FLAG["FIRST"]:
|
||||
junior_data = Junior.objects.filter(auth__username=username).last()
|
||||
if junior_data:
|
||||
if junior_data.is_verified:
|
||||
serializer = JuniorSerializer(
|
||||
junior_data, context={'user_type': user_type}
|
||||
).data
|
||||
else:
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2071"],
|
||||
response_status=status.HTTP_401_UNAUTHORIZED
|
||||
)
|
||||
else:
|
||||
return custom_error_response(
|
||||
ERROR_CODE["2069"],
|
||||
response_status=status.HTTP_401_UNAUTHORIZED
|
||||
)
|
||||
# storing device id in using celery task so the time would be reduced
|
||||
# user_device_details.delay(user.id, device_id)
|
||||
device_details, created = UserDeviceDetails.objects.get_or_create(user=user)
|
||||
if device_details:
|
||||
device_details.device_id = device_id
|
||||
device_details.save()
|
||||
return custom_response(SUCCESS_CODE['3003'], serializer, response_status=status.HTTP_200_OK)
|
||||
else:
|
||||
return custom_error_response(ERROR_CODE["2002"], response_status=status.HTTP_401_UNAUTHORIZED)
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
email_verified = UserEmailOtp.objects.filter(email=username).last()
|
||||
refresh = RefreshToken.for_user(user)
|
||||
access_token = str(refresh.access_token)
|
||||
refresh_token = str(refresh)
|
||||
data = {
|
||||
"auth_token":access_token,
|
||||
"refresh_token":refresh_token,
|
||||
"is_profile_complete": False,
|
||||
"user_type": user_type,
|
||||
}
|
||||
is_verified = False
|
||||
if email_verified:
|
||||
is_verified = email_verified.is_verified
|
||||
if not is_verified:
|
||||
otp = generate_otp()
|
||||
email_verified.otp = otp
|
||||
email_verified.save()
|
||||
data.update({"email_otp":otp})
|
||||
send_otp_email.delay(username, otp)
|
||||
return custom_response(
|
||||
ERROR_CODE['2024'],
|
||||
{"email_otp": otp, "is_email_verified": is_verified},
|
||||
response_status=status.HTTP_200_OK
|
||||
)
|
||||
data.update({"is_email_verified": is_verified})
|
||||
return custom_response(
|
||||
SUCCESS_CODE['3003'],
|
||||
data,
|
||||
response_status=status.HTTP_200_OK
|
||||
)
|
||||
|
||||
@action(methods=['post'], detail=False)
|
||||
def admin_login(self, request):
|
||||
email = request.data.get('email')
|
||||
password = request.data.get('password')
|
||||
user = User.objects.filter(email__iexact=email, is_superuser=True
|
||||
).only('id', 'first_name', 'last_name', 'email',
|
||||
'username', 'is_active', 'is_superuser').first()
|
||||
|
||||
if not user or not user.check_password(password):
|
||||
return custom_error_response(ERROR_CODE["2002"], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
serializer = SuperUserSerializer(user)
|
||||
return custom_response(SUCCESS_CODE['3003'], serializer.data, response_status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class AdminLoginViewSet(viewsets.GenericViewSet):
|
||||
"""
|
||||
admin login api
|
||||
"""
|
||||
serializer_class = AdminLoginSerializer
|
||||
|
||||
@action(methods=['post'], url_name='login', url_path='login', detail=False)
|
||||
def admin_login(self, request, *args, **kwargs):
|
||||
"""
|
||||
:param request:
|
||||
:return:
|
||||
"""
|
||||
serializer = self.serializer_class(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
user = serializer.save()
|
||||
refresh = RefreshToken.for_user(user)
|
||||
access_token = str(refresh.access_token)
|
||||
refresh_token = str(refresh)
|
||||
data = {"auth_token": access_token, "refresh_token": refresh_token, "username": user.username,
|
||||
"email": user.email, "first_name": user.first_name, "last_name": user.last_name,
|
||||
"is_active": user.is_active, "user_type": '3', "is_superuser": user.is_superuser}
|
||||
return custom_response(None, data)
|
||||
|
||||
|
||||
class UserEmailVerification(viewsets.ModelViewSet):
|
||||
"""User Email verification
|
||||
Payload
|
||||
{
|
||||
"email":"ramu@yopmail.com",
|
||||
"otp":"361123"
|
||||
}"""
|
||||
serializer_class = EmailVerificationSerializer
|
||||
http_method_names = ('post',)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
try:
|
||||
user_obj = User.objects.filter(username=self.request.data.get('email')).last()
|
||||
email_data = UserEmailOtp.objects.filter(email=self.request.data.get('email'),
|
||||
otp=self.request.data.get('otp')).last()
|
||||
if email_data:
|
||||
input_datetime_str = str(email_data.expired_at)
|
||||
input_format = "%Y-%m-%d %H:%M:%S.%f%z"
|
||||
output_format = "%Y-%m-%d %H:%M:%S.%f"
|
||||
input_datetime = datetime.strptime(input_datetime_str, input_format)
|
||||
output_datetime_str = input_datetime.strftime(output_format)
|
||||
format_str = "%Y-%m-%d %H:%M:%S.%f"
|
||||
datetime_obj = datetime.strptime(output_datetime_str, format_str)
|
||||
if datetime.today() > datetime_obj:
|
||||
return custom_error_response(ERROR_CODE["2029"], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
email_data.is_verified = True
|
||||
email_data.save()
|
||||
if email_data.user_type == '1':
|
||||
junior_data = Junior.objects.filter(auth__email=self.request.data.get('email')).last()
|
||||
if junior_data:
|
||||
junior_data.is_verified = True
|
||||
junior_data.save()
|
||||
else:
|
||||
guardian_data = Guardian.objects.filter(user__email=self.request.data.get('email')).last()
|
||||
if guardian_data:
|
||||
guardian_data.is_verified = True
|
||||
guardian_data.save()
|
||||
refresh = RefreshToken.for_user(user_obj)
|
||||
access_token = str(refresh.access_token)
|
||||
refresh_token = str(refresh)
|
||||
return custom_response(SUCCESS_CODE['3011'], {"auth_token":access_token,
|
||||
"refresh_token":refresh_token},
|
||||
response_status=status.HTTP_200_OK)
|
||||
else:
|
||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
return custom_error_response(ERROR_CODE["2008"], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
class ReSendEmailOtp(viewsets.ModelViewSet):
|
||||
"""Send otp on phone"""
|
||||
serializer_class = EmailVerificationSerializer
|
||||
http_method_names = ('post',)
|
||||
def create(self, request, *args, **kwargs):
|
||||
"""Param
|
||||
{"email":"ashok@yopmail.com"}
|
||||
"""
|
||||
otp = generate_otp()
|
||||
if User.objects.filter(email=request.data['email']):
|
||||
expiry = timezone.now() + timezone.timedelta(days=1)
|
||||
email_data, created = UserEmailOtp.objects.get_or_create(email=request.data['email'])
|
||||
if created:
|
||||
email_data.expired_at = expiry
|
||||
email_data.save()
|
||||
if email_data:
|
||||
email_data.otp = otp
|
||||
email_data.expired_at = expiry
|
||||
email_data.save()
|
||||
send_otp_email.delay(request.data['email'], otp)
|
||||
return custom_response(SUCCESS_CODE['3016'], response_status=status.HTTP_200_OK)
|
||||
else:
|
||||
return custom_error_response(ERROR_CODE["2023"], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
class ProfileAPIViewSet(viewsets.ModelViewSet):
|
||||
"""Profile viewset"""
|
||||
serializer_class = JuniorProfileSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
http_method_names = ('get',)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""profile view
|
||||
Params
|
||||
user_type"""
|
||||
user_type = request.META.get('HTTP_USER_TYPE')
|
||||
if str(user_type) == '1':
|
||||
junior_data = Junior.objects.filter(auth=self.request.user).last()
|
||||
if junior_data:
|
||||
serializer = JuniorProfileSerializer(junior_data)
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
elif str(user_type) == '2':
|
||||
guardian_data = Guardian.objects.filter(user=self.request.user).last()
|
||||
if guardian_data:
|
||||
serializer = GuardianProfileSerializer(guardian_data)
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(None, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
class UploadImageAPIViewSet(viewsets.ModelViewSet):
|
||||
"""upload task image"""
|
||||
serializer_class = DefaultTaskImagesSerializer
|
||||
http_method_names = ('post',)
|
||||
def create(self, request, *args, **kwargs):
|
||||
"""upload images"""
|
||||
image_data = request.data['image_url']
|
||||
filename = f"default_task_images/{image_data.name}"
|
||||
if image_data.size == NUMBER['zero']:
|
||||
return custom_error_response(ERROR_CODE['2035'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
image = upload_image_to_alibaba(image_data, filename)
|
||||
image_data = image
|
||||
request.data['image_url'] = image_data
|
||||
serializer = DefaultTaskImagesSerializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(serializer.error, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
class DefaultImageAPIViewSet(viewsets.ModelViewSet):
|
||||
"""Profile viewset"""
|
||||
serializer_class = DefaultTaskImagesDetailsSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
http_method_names = ('get',)
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""profile view"""
|
||||
queryset = DefaultTaskImages.objects.all()
|
||||
serializer = DefaultTaskImagesSerializer(queryset, many=True)
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class DeleteUserProfileAPIViewSet(viewsets.GenericViewSet):
|
||||
""" Delete user API view set
|
||||
{"user_type":1,
|
||||
"signup_method":"1",
|
||||
"password":"Demo@123"}
|
||||
signup_method 1 for manual
|
||||
2 for google login
|
||||
3 for apple login"""
|
||||
|
||||
@action(detail=False, methods=['POST'], url_path='user-account',serializer_class=UserDeleteSerializer,
|
||||
permission_classes=[IsAuthenticated])
|
||||
def account(self, request):
|
||||
user_type = str(request.data['user_type'])
|
||||
password = request.data.get('password')
|
||||
signup_method = str(request.data.get('signup_method'))
|
||||
serializer = self.get_serializer(data=request.data, context={'request': request, 'user': request.user,
|
||||
'user_type': user_type,
|
||||
'password': password,
|
||||
'signup_method':signup_method})
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
return custom_response(SUCCESS_CODE['3005'], response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class UserNotificationAPIViewSet(viewsets.ModelViewSet):
|
||||
"""notification viewset"""
|
||||
serializer_class = UserNotificationSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
http_method_names = ('get',)
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""notification view"""
|
||||
queryset = UserNotification.objects.filter(user=request.user)
|
||||
serializer = UserNotificationSerializer(queryset, many=True)
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class UpdateUserNotificationAPIViewSet(viewsets.ModelViewSet):
|
||||
"""Update notification viewset"""
|
||||
serializer_class = UpdateUserNotificationSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
http_method_names = ('post',)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
"""Payload
|
||||
{"email_notification": false,
|
||||
"sms_notification": false,
|
||||
"push_notification": false}
|
||||
"""
|
||||
serializer = UpdateUserNotificationSerializer(data=request.data,
|
||||
context=request.user)
|
||||
if serializer.is_valid():
|
||||
serializer.save()
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(serializer.error, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class SendSupportEmail(views.APIView):
|
||||
"""support email api
|
||||
payload
|
||||
name
|
||||
email
|
||||
message
|
||||
"""
|
||||
permission_classes = (IsAuthenticated,)
|
||||
|
||||
def post(self, request):
|
||||
name = request.data.get('name')
|
||||
sender = request.data.get('email')
|
||||
message = request.data.get('message')
|
||||
if name and sender and message:
|
||||
try:
|
||||
send_support_email(name, sender, message)
|
||||
return custom_response(SUCCESS_CODE['3019'], response_status=status.HTTP_200_OK)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
else:
|
||||
return custom_error_response(ERROR_CODE['2033'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
class LogoutAPIView(views.APIView):
|
||||
"""Log out API"""
|
||||
permission_classes = (IsAuthenticated,)
|
||||
|
||||
def post(self, request):
|
||||
remove_fcm_token(
|
||||
request.auth.payload['user_id'],
|
||||
request.META['HTTP_AUTHORIZATION'].split(" ")[1],
|
||||
request.data.get('registration_id', ""))
|
||||
logout(request)
|
||||
request.session.flush()
|
||||
return custom_response(SUCCESS_CODE['3020'], response_status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class AccessTokenAPIView(views.APIView):
|
||||
"""generate access token API"""
|
||||
|
||||
def post(self, request):
|
||||
# Assuming you have a refresh_token string
|
||||
refresh_token = request.data['refresh_token']
|
||||
# Create a RefreshToken instance from the refresh token string
|
||||
refresh = RefreshToken(refresh_token)
|
||||
# Generate a new access token
|
||||
access_token = str(refresh.access_token)
|
||||
data = {"auth_token": access_token}
|
||||
return custom_response(None, data, response_status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class ForceUpdateViewSet(GenericViewSet, mixins.CreateModelMixin):
|
||||
"""FAQ view set"""
|
||||
|
||||
serializer_class = ForceUpdateSerializer
|
||||
http_method_names = ['post']
|
||||
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
"""
|
||||
faq create api method
|
||||
:param request:
|
||||
:param args: version, device type
|
||||
:param kwargs:
|
||||
:return: success message
|
||||
"""
|
||||
if ForceUpdate.objects.all().count() >= 2:
|
||||
return custom_error_response(ERROR_CODE['2080'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
obj_data = [ForceUpdate(**item) for item in request.data]
|
||||
try:
|
||||
ForceUpdate.objects.bulk_create(obj_data)
|
||||
return custom_response(SUCCESS_CODE["3046"], response_status=status.HTTP_200_OK)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
3
base/__init__.py
Normal file
3
base/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
"""
|
||||
This is init module of the Project Zod Bank
|
||||
"""
|
30
base/common_email.py
Normal file
30
base/common_email.py
Normal file
@ -0,0 +1,30 @@
|
||||
"""
|
||||
Common send_mail function
|
||||
"""
|
||||
import logging
|
||||
|
||||
from django.core.mail import EmailMultiAlternatives
|
||||
|
||||
|
||||
def send_mail(subject, message, from_email, recipient_list, html_message=None, cc=None,
|
||||
fail_silently=False):
|
||||
"""
|
||||
Send Email
|
||||
:param subject:
|
||||
:param message:
|
||||
:param from_email:
|
||||
:param recipient_list:
|
||||
:param html_message:
|
||||
:param cc:
|
||||
:param fail_silently:
|
||||
:return:
|
||||
"""
|
||||
try:
|
||||
mail = EmailMultiAlternatives(subject, message, from_email, recipient_list, cc)
|
||||
if html_message:
|
||||
mail.attach_alternative(html_message, 'text/html')
|
||||
|
||||
return mail.send(fail_silently)
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
return False
|
137
base/constants.py
Normal file
137
base/constants.py
Normal file
@ -0,0 +1,137 @@
|
||||
"""
|
||||
This module contains constants used throughout the project
|
||||
"""
|
||||
import os
|
||||
|
||||
# GOOGLE_URL used for interact with google server to verify user existence.
|
||||
#GOOGLE_URL = "https://www.googleapis.com/plus/v1/"
|
||||
|
||||
# Define Code prefix word
|
||||
# for guardian code,
|
||||
# junior code,
|
||||
# referral code"""
|
||||
ZOD = 'ZOD'
|
||||
JUN = 'JUN'
|
||||
GRD = 'GRD'
|
||||
# Define number variable
|
||||
# from zero to
|
||||
# twenty and
|
||||
# some standard
|
||||
# number"""
|
||||
NUMBER = {
|
||||
'point_zero': 0.0, 'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7,
|
||||
'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twelve': 12, 'thirteen': 13, 'fourteen': 14, 'fifteen': 15,
|
||||
'sixteen': 16, 'seventeen': 17, 'eighteen': 18, 'nineteen': 19, 'twenty': 20,
|
||||
'twenty_one': 21, 'twenty_two': 22,'twenty_three': 23, 'twenty_four': 24, 'twenty_five': 25,
|
||||
'thirty': 30, 'forty': 40, 'fifty': 50, 'sixty': 60, 'seventy': 70, 'eighty': 80, 'ninty': 90,
|
||||
'ninety_nine': 99, 'hundred': 100, 'thirty_six_hundred': 3600
|
||||
}
|
||||
|
||||
none = "none"
|
||||
|
||||
# Super Admin string constant for 'role'
|
||||
SUPER_ADMIN = "Super Admin"
|
||||
|
||||
# Define jwt_token_expiration time in minutes for now token will expire after 3 days
|
||||
JWT_TOKEN_EXPIRATION = 3 * 24 * 60
|
||||
|
||||
# Define common file extention
|
||||
FILE_EXTENSION = ("gif", "jpeg", "jpg", "png", "svg")
|
||||
|
||||
# Define file size in bytes(5MB = 5 * 1024 * 1024)
|
||||
FILE_SIZE = 5 * 1024 * 1024
|
||||
|
||||
# String constant for configurable date for allocation lock period
|
||||
ALLOCATION_LOCK_DATE = 1
|
||||
# guardian code status tuple
|
||||
guardian_code_tuple = ('1','3')
|
||||
"""user type"""
|
||||
USER_TYPE = (
|
||||
('1', 'junior'),
|
||||
('2', 'guardian'),
|
||||
('3', 'superuser')
|
||||
)
|
||||
DEVICE_TYPE = (
|
||||
('1', 'android'),
|
||||
('2', 'ios')
|
||||
)
|
||||
USER_TYPE_FLAG = {
|
||||
"FIRST" : "1",
|
||||
"TWO" : "2",
|
||||
"THREE": "3"
|
||||
}
|
||||
|
||||
"""gender"""
|
||||
GENDERS = (
|
||||
('1', 'Male'),
|
||||
('2', 'Female')
|
||||
)
|
||||
# Task status"""
|
||||
TASK_STATUS = (
|
||||
('1', 'pending'),
|
||||
('2', 'in-progress'),
|
||||
('3', 'rejected'),
|
||||
('4', 'requested'),
|
||||
('5', 'completed'),
|
||||
('6', 'expired')
|
||||
)
|
||||
# sign up method
|
||||
SIGNUP_METHODS = (
|
||||
('1', 'manual'),
|
||||
('2', 'google'),
|
||||
('3', 'apple')
|
||||
)
|
||||
# guardian code status
|
||||
GUARDIAN_CODE_STATUS = (
|
||||
('1', 'no guardian code'),
|
||||
('2', 'exist guardian code'),
|
||||
('3', 'request for guardian code')
|
||||
)
|
||||
# article status
|
||||
ARTICLE_STATUS = (
|
||||
('1', 'read'),
|
||||
('2', 'in_progress'),
|
||||
('3', 'completed')
|
||||
)
|
||||
# relationship
|
||||
RELATIONSHIP = (
|
||||
('1', 'parent'),
|
||||
('2', 'legal_guardian')
|
||||
)
|
||||
"""
|
||||
Define task status
|
||||
in a number"""
|
||||
PENDING = 1
|
||||
IN_PROGRESS = 2
|
||||
REJECTED = 3
|
||||
REQUESTED = 4
|
||||
COMPLETED = 5
|
||||
EXPIRED = 6
|
||||
TASK_POINTS = 5
|
||||
# duplicate name used defined in constant PROJECT_NAME
|
||||
PROJECT_NAME = 'Zod Bank'
|
||||
# define user type constant
|
||||
GUARDIAN = 'guardian'
|
||||
JUNIOR = 'junior'
|
||||
SUPERUSER = 'superuser'
|
||||
# numbers used as a constant
|
||||
|
||||
# Define the byte into kb
|
||||
BYTE_IMAGE_SIZE = 1024
|
||||
|
||||
# validate file size
|
||||
MAX_FILE_SIZE = 1024 * 1024 * 5
|
||||
|
||||
ARTICLE_SURVEY_POINTS = 5
|
||||
MAX_ARTICLE_CARD = 6
|
||||
|
||||
# min and max survey
|
||||
MIN_ARTICLE_SURVEY = 5
|
||||
MAX_ARTICLE_SURVEY = 10
|
||||
|
||||
# already register
|
||||
Already_register_user = "duplicate key value violates unique constraint"
|
||||
|
||||
ARTICLE_CARD_IMAGE_FOLDER = 'article-card-images'
|
||||
|
||||
DATE_FORMAT = '%Y-%m-%d'
|
16
base/image_constants.py
Normal file
16
base/image_constants.py
Normal file
@ -0,0 +1,16 @@
|
||||
"""
|
||||
This module contains constants used throughout the project
|
||||
"""
|
||||
from zod_bank.settings import BUCKET_NAME
|
||||
|
||||
# Define S3 folder url
|
||||
S3_FOLDER_DIR = {
|
||||
'user_image': 'user_image/',
|
||||
}
|
||||
|
||||
# S3 bucket url
|
||||
S3_URL = "https://"+BUCKET_NAME+".s3.amazonaws.com/"
|
||||
|
||||
S3_FOLDER_URL = {
|
||||
'user_image_file': S3_URL+S3_FOLDER_DIR['user_image'],
|
||||
}
|
202
base/messages.py
Normal file
202
base/messages.py
Normal file
@ -0,0 +1,202 @@
|
||||
"""
|
||||
This module contains all the messages used all across the project
|
||||
"""
|
||||
|
||||
ERROR_CODE_REQUIRED = {
|
||||
# Error code for email address
|
||||
"1000": ["Required email address not found."],
|
||||
# Error code for password
|
||||
"1001": ["Required password not found."],
|
||||
# Error code for Required Post parameters
|
||||
"1002": ["Required POST parameters not found."],
|
||||
# Error code for Required Get parameters
|
||||
"1003": ["Required GET parameters not found."],
|
||||
# Error code for Required Headers
|
||||
"1004": ["Required headers were not found."],
|
||||
# Error code for Required Put parameters
|
||||
"1005": ["Required PUT parameters not found."],
|
||||
# Error code for Required query parameters
|
||||
"1006": ["Required query parameters is not valid."],
|
||||
# Error code for Required Head parameters
|
||||
"1008": ["Required HEAD parameters not found."]
|
||||
}
|
||||
|
||||
# Error code
|
||||
ERROR_CODE = {
|
||||
"2000": "Invalid email address. Please enter a registered email.",
|
||||
"2001": "This is your existing password. Please choose other one",
|
||||
"2002": "Invalid username or password.",
|
||||
"2003": "An account already exists with this email address.",
|
||||
"2004": "User not found.",
|
||||
"2005": "Your account has been activated.",
|
||||
"2006": "Your account is not activated.",
|
||||
"2007": "Your account already activated.",
|
||||
"2008": "The OTP entered is not correct.",
|
||||
"2009": "The user provided cannot be found or the reset password token has become invalid/timed out.",
|
||||
"2010": "Invalid Link.",
|
||||
"2011": "Your profile has not been completed yet.",
|
||||
"2012": "Phone number already used",
|
||||
"2013": "Invalid token.",
|
||||
"2014": "Your old password doesn't match.",
|
||||
"2015": "Invalid old password.",
|
||||
"2016": "Invalid search.",
|
||||
"2017": "{model} object with {pk} does not exist",
|
||||
"2018": "Attached File not found",
|
||||
"2019": "Invalid Referral code",
|
||||
"2020": "Enter valid mobile number",
|
||||
"2021": "User registered",
|
||||
"2022": "Invalid Guardian code",
|
||||
"2023": "Invalid user",
|
||||
# email not verified
|
||||
"2024": "Email not verified",
|
||||
"2025": "Invalid input. Expected a list of strings.",
|
||||
# check old and new password
|
||||
"2026": "New password should not same as old password",
|
||||
"2027": "data should contain `identityToken`",
|
||||
"2028": "You are not authorized person to sign up on this platform",
|
||||
"2029": "Validity of otp verification has expired. Please request a new one.",
|
||||
"2030": "Use correct user type and token",
|
||||
# invalid password
|
||||
"2031": "Invalid password",
|
||||
"2032": "Failed to send email",
|
||||
"2033": "Missing required fields",
|
||||
"2034": "Junior is not associated",
|
||||
# image size
|
||||
"2035": "Image should not be 0 kb",
|
||||
"2036": "Choose valid user",
|
||||
# log in multiple device msg
|
||||
"2037": "You are already log in another device",
|
||||
"2038": "Choose valid action for task",
|
||||
# card length limit
|
||||
"2039": "Add at least one article card or maximum 6",
|
||||
"2040": "Add at least 5 article survey or maximum 10",
|
||||
# add article msg
|
||||
"2041": "Article with given id doesn't exist.",
|
||||
"2042": "Article Card with given id doesn't exist.",
|
||||
"2043": "Article Survey with given id doesn't exist.",
|
||||
"2044": "Task does not exist",
|
||||
"2045": "Invalid guardian",
|
||||
# past due date
|
||||
"2046": "Due date must be future date",
|
||||
# invalid junior id msg
|
||||
"2047": "Invalid Junior ID ",
|
||||
"2048": "Choose right file for image",
|
||||
# task request
|
||||
"2049": "This task is already requested ",
|
||||
"2059": "Already exist junior",
|
||||
# task status
|
||||
"2060": "Task does not exist or not in pending state",
|
||||
"2061": "Please insert image or check the image is valid or not.",
|
||||
# email not null
|
||||
"2062": "Please enter email address",
|
||||
"2063": "Unauthorized access.",
|
||||
"2064": "To change your password first request an OTP and get it verify then change your password.",
|
||||
"2065": "Passwords do not match. Please try again.",
|
||||
"2066": "Task does not exist or not in expired state",
|
||||
"2067": "Action not allowed. User type missing.",
|
||||
"2068": "No guardian associated with this junior",
|
||||
"2069": "Invalid user type",
|
||||
"2070": "You do not find as a guardian",
|
||||
"2071": "You do not find as a junior",
|
||||
"2072": "You can not approve or reject this task because junior does not exist in the system",
|
||||
"2073": "You can not approve or reject this junior because junior does not exist in the system",
|
||||
"2074": "You can not complete this task because you does not exist in the system",
|
||||
# deactivate account
|
||||
"2075": "Your account is deactivated. Please contact with admin",
|
||||
"2076": "This junior already associated with you",
|
||||
"2077": "You can not add guardian",
|
||||
"2078": "This junior is not associated with you",
|
||||
# force update
|
||||
"2079": "Please update your app version for enjoying uninterrupted services",
|
||||
"2080": "Can not add App version",
|
||||
"2081": "A junior can only be associated with a maximum of 3 guardian",
|
||||
# guardian code not exist
|
||||
"2082": "Guardian code does not exist",
|
||||
"2083": "You can not start this task because guardian is not associate with you",
|
||||
"2084": "You can not complete this task because guardian is not associate with you",
|
||||
"2085": "You can not take action on this task because junior is not associate with you"
|
||||
|
||||
}
|
||||
"""Success message code"""
|
||||
SUCCESS_CODE = {
|
||||
"3000": "ok",
|
||||
# Success code for password
|
||||
"3001": "Sign up successfully",
|
||||
# Success code for Thank you
|
||||
"3002": "Thank you for contacting us! Our Consumer Experience Team will reach out to you shortly.",
|
||||
# Success code for account activation
|
||||
"3003": "Log in successful.",
|
||||
# Success code for password reset
|
||||
"3004": "Password reset link has been sent to your email address.",
|
||||
# Success code for link verified
|
||||
"3005": "Your account has been deleted successfully.",
|
||||
# Success code for password reset
|
||||
"3006": "Password reset successful. You can now log in with your new password.",
|
||||
# Success code for password update
|
||||
"3007": "Your password has been changed successfully.",
|
||||
# Success code for valid link
|
||||
"3008": "You have a valid link.",
|
||||
# Success code for logged out
|
||||
"3009": "You have successfully logged out.",
|
||||
# Success code for check all fields
|
||||
"3010": "All fields are valid.",
|
||||
"3011": "Email OTP has been verified successfully.",
|
||||
"3012": "Phone OTP has been verified successfully.",
|
||||
"3013": "Valid Guardian code",
|
||||
"3014": "Password has been updated successfully.",
|
||||
"3015": "Verification code has been sent on your email.",
|
||||
"3016": "An OTP has been sent on your email.",
|
||||
"3017": "Profile image update successfully",
|
||||
"3018": "Task created successfully",
|
||||
"3019": "Support Email sent successfully",
|
||||
"3020": "Logged out successfully.",
|
||||
"3021": "Junior has been added successfully.",
|
||||
"3022": "Junior has been removed successfully.",
|
||||
"3023": "Junior has been approved successfully.",
|
||||
"3024": "Junior request is rejected successfully.",
|
||||
"3025": "Task is approved successfully.",
|
||||
"3026": "Task is rejected successfully.",
|
||||
"3027": "Article has been created successfully.",
|
||||
"3028": "Article has been updated successfully.",
|
||||
"3029": "Article has been deleted successfully.",
|
||||
"3030": "Article Card has been removed successfully.",
|
||||
"3031": "Article Survey has been removed successfully.",
|
||||
"3032": "Task request sent successfully.",
|
||||
"3033": "Valid Referral code.",
|
||||
"3034": "Invite guardian successfully.",
|
||||
"3035": "Task started successfully.",
|
||||
"3036": "Task reassign successfully.",
|
||||
"3037": "Profile has been updated successfully.",
|
||||
"3038": "Status has been changed successfully.",
|
||||
# notification read
|
||||
"3039": "Notification read successfully.",
|
||||
# start article
|
||||
"3040": "Start article successfully.",
|
||||
# complete article
|
||||
"3041": "Article completed successfully.",
|
||||
# submit assessment successfully
|
||||
"3042": "Assessment completed successfully.",
|
||||
# read article
|
||||
"3043": "Read article card successfully.",
|
||||
# remove guardian code request
|
||||
"3044": "Remove guardian code request successfully.",
|
||||
# create faq
|
||||
"3045": "Create FAQ data.",
|
||||
"3046": "Add App version successfully."
|
||||
|
||||
}
|
||||
"""status code error"""
|
||||
STATUS_CODE_ERROR = {
|
||||
# Status code for Invalid Input
|
||||
"4001": ["Invalid input."],
|
||||
# Status code for Authentication credentials
|
||||
"4002": ["Authentication credentials were not provided."],
|
||||
# Status code for Permission
|
||||
"4003": ["You do not have permission to perform this action."],
|
||||
# Status code for not found
|
||||
"4004": ["Not found."],
|
||||
# Status code for method not allowed
|
||||
"4005": ["Method not allowed."]
|
||||
}
|
||||
|
||||
|
34
base/pagination.py
Normal file
34
base/pagination.py
Normal file
@ -0,0 +1,34 @@
|
||||
"""
|
||||
web_admin pagination file
|
||||
"""
|
||||
# third party imports
|
||||
from collections import OrderedDict
|
||||
from rest_framework.pagination import PageNumberPagination
|
||||
|
||||
from account.utils import custom_response
|
||||
from base.constants import NUMBER
|
||||
|
||||
|
||||
class CustomPageNumberPagination(PageNumberPagination):
|
||||
"""
|
||||
custom paginator class
|
||||
"""
|
||||
# Set the desired page size
|
||||
page_size = NUMBER['ten']
|
||||
page_size_query_param = 'page_size'
|
||||
# Set a maximum page size if needed
|
||||
max_page_size = NUMBER['hundred']
|
||||
|
||||
def get_paginated_response(self, data):
|
||||
"""
|
||||
:param data: queryset to be paginated
|
||||
:return: return a OrderedDict
|
||||
"""
|
||||
return custom_response(None, OrderedDict([
|
||||
('count', self.page.paginator.count),
|
||||
('data', data),
|
||||
('current_page', self.page.number),
|
||||
('total_pages', self.page.paginator.num_pages),
|
||||
|
||||
|
||||
]))
|
17
base/routers.py
Normal file
17
base/routers.py
Normal file
@ -0,0 +1,17 @@
|
||||
"""
|
||||
Custom routers for job sourcing .
|
||||
"""
|
||||
# third party imports
|
||||
from rest_framework.routers import DefaultRouter
|
||||
|
||||
|
||||
class OptionalSlashRouter(DefaultRouter):
|
||||
"""
|
||||
optional slash router class
|
||||
"""
|
||||
def __init__(self):
|
||||
"""
|
||||
explicitly appending '/' in urls if '/' doesn't exists for making common url patterns .
|
||||
"""
|
||||
super(OptionalSlashRouter, self).__init__()
|
||||
self.trailing_slash = '/?'
|
88
base/tasks.py
Normal file
88
base/tasks.py
Normal file
@ -0,0 +1,88 @@
|
||||
"""
|
||||
web_admin tasks file
|
||||
"""
|
||||
import datetime
|
||||
|
||||
# third party imports
|
||||
from celery import shared_task
|
||||
from templated_email import send_templated_mail
|
||||
|
||||
# django imports
|
||||
from django.conf import settings
|
||||
from django.db.models import F, Window
|
||||
from django.db.models.functions.window import Rank
|
||||
|
||||
# local imports
|
||||
from base.constants import PENDING, IN_PROGRESS, JUNIOR
|
||||
from guardian.models import JuniorTask
|
||||
from junior.models import JuniorPoints
|
||||
from notifications.constants import PENDING_TASK_EXPIRING, IN_PROGRESS_TASK_EXPIRING, NOTIFICATION_DICT, TOP_JUNIOR
|
||||
from notifications.models import Notification
|
||||
from notifications.utils import send_notification, get_from_user_details, send_notification_multiple_user
|
||||
|
||||
|
||||
@shared_task
|
||||
def send_email(recipient_list, template, context: dict = None):
|
||||
"""
|
||||
used to send otp on email
|
||||
:param context:
|
||||
:param recipient_list: e-mail list
|
||||
:param template: email template
|
||||
"""
|
||||
if context is None:
|
||||
context = {}
|
||||
from_email = settings.EMAIL_FROM_ADDRESS
|
||||
send_templated_mail(
|
||||
template_name=template,
|
||||
from_email=from_email,
|
||||
recipient_list=recipient_list,
|
||||
context=context
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
@shared_task()
|
||||
def notify_task_expiry():
|
||||
"""
|
||||
task to send notification for those task which expiring soon
|
||||
:return:
|
||||
"""
|
||||
all_pending_tasks = JuniorTask.objects.filter(
|
||||
task_status__in=[PENDING, IN_PROGRESS],
|
||||
due_date__range=[datetime.datetime.now().date(),
|
||||
(datetime.datetime.now().date() + datetime.timedelta(days=1))])
|
||||
if pending_tasks := all_pending_tasks.filter(task_status=PENDING):
|
||||
for task in pending_tasks:
|
||||
send_notification(PENDING_TASK_EXPIRING, None, None, task.junior.auth_id,
|
||||
{'task_id': task.id})
|
||||
if in_progress_tasks := all_pending_tasks.filter(task_status=IN_PROGRESS):
|
||||
for task in in_progress_tasks:
|
||||
send_notification(IN_PROGRESS_TASK_EXPIRING, task.junior.auth_id, JUNIOR, task.guardian.user_id,
|
||||
{'task_id': task.id})
|
||||
return True
|
||||
|
||||
|
||||
@shared_task()
|
||||
def notify_top_junior():
|
||||
"""
|
||||
task to send notification for top leaderboard junior to all junior's
|
||||
:return:
|
||||
"""
|
||||
junior_points_qs = JuniorPoints.objects.filter(
|
||||
junior__is_verified=True
|
||||
).select_related(
|
||||
'junior', 'junior__auth'
|
||||
).annotate(rank=Window(
|
||||
expression=Rank(),
|
||||
order_by=[F('total_points').desc(), 'junior__created_at'])
|
||||
).order_by('-total_points', 'junior__created_at')
|
||||
|
||||
prev_top_position = junior_points_qs.filter(position=1).first()
|
||||
new_top_position = junior_points_qs.filter(rank=1).first()
|
||||
if prev_top_position != new_top_position:
|
||||
send_notification_multiple_user(TOP_JUNIOR, new_top_position.junior.auth_id, JUNIOR,
|
||||
{'points': new_top_position.total_points})
|
||||
for junior_point in junior_points_qs:
|
||||
junior_point.position = junior_point.rank
|
||||
junior_point.save()
|
||||
return True
|
177
base/upload_file.py
Normal file
177
base/upload_file.py
Normal file
@ -0,0 +1,177 @@
|
||||
"""
|
||||
This file used for file uploaded
|
||||
"""
|
||||
import datetime
|
||||
# python imports
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
|
||||
import boto3
|
||||
from django.core.files.storage import FileSystemStorage
|
||||
# django imports
|
||||
from django.utils.crypto import get_random_string
|
||||
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_200_OK
|
||||
|
||||
from base import constants
|
||||
from base.constants import NUMBER
|
||||
# local import
|
||||
from zod_bank.settings import base_settings as settings
|
||||
from zod_bank.settings.base_settings import BASE_DIR
|
||||
|
||||
|
||||
def image_upload(folder, file_name, data):
|
||||
"""
|
||||
Function to upload files
|
||||
:param folder:folder location string
|
||||
:param file_name:file_name without ext string
|
||||
:param data:data file obj
|
||||
:return:Dictionary
|
||||
"""
|
||||
status = HTTP_400_BAD_REQUEST
|
||||
img_name = None
|
||||
error = None
|
||||
try:
|
||||
s3_client = boto3.client('s3',
|
||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
||||
region_name=settings.AWS_DEFAULT_REGION
|
||||
)
|
||||
|
||||
bucket_name = settings.BUCKET_NAME
|
||||
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/tmp')
|
||||
fss = FileSystemStorage()
|
||||
file = fss.save('tmp/' + str(file_name), data)
|
||||
fss.url(file)
|
||||
tmp_file = os.path.join(MEDIA_ROOT, str(file_name))
|
||||
s3_client.upload_file(
|
||||
tmp_file, bucket_name, folder + str(file_name),
|
||||
ExtraArgs={'ACL': 'public-read', 'ContentType': data.content_type}
|
||||
)
|
||||
os.unlink(tmp_file)
|
||||
img_name = file_name
|
||||
status = HTTP_200_OK
|
||||
except Exception as e:
|
||||
error = e
|
||||
logging.error(e)
|
||||
return status, error, img_name
|
||||
|
||||
|
||||
def file_delete(folder, file_name):
|
||||
"""
|
||||
To delete common file
|
||||
:param folder: folder name str
|
||||
:param file_name: file_name string type
|
||||
"""
|
||||
status = HTTP_400_BAD_REQUEST
|
||||
error = None
|
||||
try:
|
||||
s3_client = boto3.client('s3',
|
||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
||||
region_name=settings.AWS_DEFAULT_REGION
|
||||
)
|
||||
|
||||
s3_client.delete_object(Bucket=settings.BUCKET_NAME, Key=str(folder) + str(file_name))
|
||||
status = HTTP_200_OK
|
||||
except Exception as e:
|
||||
error = e
|
||||
return status, error
|
||||
|
||||
|
||||
def get_aws_obj(folder, file_name):
|
||||
"""
|
||||
To get aws file obj
|
||||
:param folder: folder string type
|
||||
:param file_name: file_name string type
|
||||
"""
|
||||
status = HTTP_400_BAD_REQUEST
|
||||
obj = None
|
||||
try:
|
||||
s3_client = boto3.client('s3',
|
||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
||||
region_name=settings.AWS_DEFAULT_REGION
|
||||
)
|
||||
file_name = folder + file_name
|
||||
obj = s3_client.get_object(Bucket=settings.BUCKET_NAME, Key=file_name)
|
||||
status = HTTP_200_OK
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
return status, obj
|
||||
|
||||
|
||||
def upload_image(post_data, folder):
|
||||
"""
|
||||
:param post_data:
|
||||
:param folder: string type
|
||||
:return:
|
||||
"""
|
||||
upload_obj = None
|
||||
# Check Post data
|
||||
if post_data:
|
||||
date_now = datetime.datetime.now()
|
||||
file_extension = os.path.splitext(str(post_data.name))
|
||||
file_extension = file_extension[constants.NUMBER['one']].split(".")[constants.NUMBER['one']].lower()
|
||||
rand = get_random_string(NUMBER['twelve'])
|
||||
image_name = str(rand) + date_now.strftime("%s") + "." + file_extension
|
||||
upload_obj = image_upload(folder, image_name, post_data)
|
||||
return upload_obj
|
||||
|
||||
|
||||
def upload_voice_kit_image(post_data, folder, image_dir):
|
||||
"""
|
||||
:param post_data:
|
||||
:param folder: string type
|
||||
:param image_dir: image_dir
|
||||
:return:
|
||||
"""
|
||||
upload_obj = None
|
||||
# Check Post data
|
||||
if post_data:
|
||||
date_now = datetime.datetime.now()
|
||||
file_extension = os.path.splitext(str(post_data))
|
||||
file_extension = file_extension[constants.NUMBER['one']].split(".")[constants.NUMBER['one']].lower()
|
||||
rand = get_random_string(NUMBER['twelve'])
|
||||
image_name = str(rand) + date_now.strftime("%s") + "." + file_extension
|
||||
upload_obj = voice_kit_image_upload(folder, image_name, post_data, image_dir)
|
||||
return upload_obj
|
||||
|
||||
|
||||
def voice_kit_image_upload(folder, file_name, data, image_dir):
|
||||
"""
|
||||
Function to upload files
|
||||
:param folder:folder location string
|
||||
:param file_name:file_name without ext string
|
||||
:param data:data file obj
|
||||
:return:Dictionary
|
||||
"""
|
||||
status = HTTP_400_BAD_REQUEST
|
||||
img_name = None
|
||||
error = None
|
||||
try:
|
||||
s3_client = boto3.client('s3',
|
||||
aws_access_key_id=settings.AWS_ACCESS_KEY,
|
||||
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
|
||||
region_name=settings.AWS_DEFAULT_REGION
|
||||
)
|
||||
|
||||
bucket_name = settings.BUCKET_NAME
|
||||
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/tmp')
|
||||
fss = FileSystemStorage()
|
||||
with open(image_dir+data, 'rb') as f:
|
||||
file = fss.save('tmp/' + str(file_name), f)
|
||||
fss.url(file)
|
||||
tmp_file = os.path.join(MEDIA_ROOT, str(file_name))
|
||||
s3_client.upload_file(
|
||||
tmp_file, bucket_name, folder + str(file_name),
|
||||
ExtraArgs={'ACL': 'public-read', 'ContentType': mimetypes.guess_type(file_name)[0]}
|
||||
)
|
||||
os.unlink(tmp_file)
|
||||
img_name = file_name
|
||||
status = HTTP_200_OK
|
||||
except Exception as e:
|
||||
error = e
|
||||
logging.error(e)
|
||||
return status, error, img_name
|
||||
|
BIN
celerybeat-schedule
Normal file
BIN
celerybeat-schedule
Normal file
Binary file not shown.
5792
coverage-reports/coverage.xml
Normal file
5792
coverage-reports/coverage.xml
Normal file
File diff suppressed because it is too large
Load Diff
39
docker-compose-prod.yml
Normal file
39
docker-compose-prod.yml
Normal file
@ -0,0 +1,39 @@
|
||||
version: '3'
|
||||
services:
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
container_name: nginx
|
||||
restart: always
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
- ./nginx:/etc/nginx/conf.d
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- web
|
||||
web:
|
||||
build: .
|
||||
container_name: prod_django
|
||||
restart: always
|
||||
command: bash -c "pip install -r requirements.txt && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn zod_bank.wsgi -b 0.0.0.0:8000 -t 300 --log-level=info"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
|
||||
broker:
|
||||
image: rabbitmq:3.7
|
||||
container_name: prod_rabbitmq
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
ports:
|
||||
- 5673:5673
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: celery
|
||||
container_name: prod_celery
|
||||
restart: "always"
|
||||
command: bash -c " celery -A zod_bank.celery worker --concurrency=1 -B -l DEBUG -E"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- broker
|
39
docker-compose-qa.yml
Normal file
39
docker-compose-qa.yml
Normal file
@ -0,0 +1,39 @@
|
||||
version: '3'
|
||||
services:
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
container_name: nginx
|
||||
restart: always
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
- ./nginx:/etc/nginx/conf.d
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- web
|
||||
web:
|
||||
build: .
|
||||
container_name: qa_django
|
||||
restart: always
|
||||
command: bash -c "pip install -r requirements.txt && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn zod_bank.wsgi -b 0.0.0.0:8000 -t 300 --log-level=info"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
|
||||
broker:
|
||||
image: rabbitmq:3.7
|
||||
container_name: qa_rabbitmq
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
ports:
|
||||
- 5673:5673
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: celery
|
||||
container_name: qa_celery
|
||||
restart: "always"
|
||||
command: bash -c " celery -A zod_bank.celery worker --concurrency=1 -B -l DEBUG -E"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- broker
|
39
docker-compose-stage.yml
Normal file
39
docker-compose-stage.yml
Normal file
@ -0,0 +1,39 @@
|
||||
version: '3'
|
||||
services:
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
container_name: nginx
|
||||
restart: always
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
- ./nginx:/etc/nginx/conf.d
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- web
|
||||
web:
|
||||
build: .
|
||||
container_name: stage_django
|
||||
restart: always
|
||||
command: bash -c "pip install -r requirements.txt && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn zod_bank.wsgi -b 0.0.0.0:8000 -t 300 --log-level=info"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
|
||||
broker:
|
||||
image: rabbitmq:3.7
|
||||
container_name: stage_rabbitmq
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
ports:
|
||||
- 5673:5673
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: celery
|
||||
container_name: stage_celery
|
||||
restart: "always"
|
||||
command: bash -c " celery -A zod_bank.celery worker --concurrency=1 -B -l DEBUG -E"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- broker
|
39
docker-compose.yml
Normal file
39
docker-compose.yml
Normal file
@ -0,0 +1,39 @@
|
||||
version: '3'
|
||||
services:
|
||||
nginx:
|
||||
image: nginx:latest
|
||||
container_name: nginx
|
||||
restart: always
|
||||
ports:
|
||||
- "8000:8000"
|
||||
volumes:
|
||||
- ./nginx:/etc/nginx/conf.d
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- web
|
||||
web:
|
||||
build: .
|
||||
container_name: django
|
||||
restart: always
|
||||
command: bash -c "pip install -r requirements.txt && python manage.py collectstatic --noinput && python manage.py migrate && gunicorn zod_bank.wsgi -b 0.0.0.0:8000 -t 300 --log-level=info"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
|
||||
broker:
|
||||
image: rabbitmq:3.7
|
||||
container_name: rabbitmq
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
ports:
|
||||
- 5673:5673
|
||||
|
||||
worker:
|
||||
build: .
|
||||
image: celery
|
||||
container_name: dev_celery
|
||||
restart: "always"
|
||||
command: bash -c " celery -A zod_bank.celery worker --concurrency=1 -B -l DEBUG -E"
|
||||
volumes:
|
||||
- .:/usr/src/app
|
||||
depends_on:
|
||||
- broker
|
0
guardian/__init__.py
Normal file
0
guardian/__init__.py
Normal file
23
guardian/admin.py
Normal file
23
guardian/admin.py
Normal file
@ -0,0 +1,23 @@
|
||||
"""Guardian admin"""
|
||||
"""Third party Django app"""
|
||||
from django.contrib import admin
|
||||
"""Import Django app"""
|
||||
from .models import Guardian, JuniorTask
|
||||
# Register your models here.
|
||||
@admin.register(Guardian)
|
||||
class GuardianAdmin(admin.ModelAdmin):
|
||||
"""Junior Admin"""
|
||||
list_display = ['user', 'family_name']
|
||||
|
||||
def __str__(self):
|
||||
"""Return email id"""
|
||||
return self.user__email
|
||||
|
||||
@admin.register(JuniorTask)
|
||||
class TaskAdmin(admin.ModelAdmin):
|
||||
"""Junior Admin"""
|
||||
list_display = ['id', 'task_name', 'task_status', 'junior', 'due_date', 'points', 'created_at', 'updated_at']
|
||||
|
||||
def __str__(self):
|
||||
"""Return email id"""
|
||||
return str(self.task_name) + str(self.points)
|
9
guardian/apps.py
Normal file
9
guardian/apps.py
Normal file
@ -0,0 +1,9 @@
|
||||
"""Guardian app file"""
|
||||
"""Third party Django app"""
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class CustodianConfig(AppConfig):
|
||||
"""Guardian config"""
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'guardian'
|
43
guardian/migrations/0001_initial.py
Normal file
43
guardian/migrations/0001_initial.py
Normal file
@ -0,0 +1,43 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-23 12:05
|
||||
|
||||
from django.conf import settings
|
||||
import django.contrib.postgres.fields
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Guardian',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('country_code', models.IntegerField(blank=True, null=True)),
|
||||
('phone', models.CharField(blank=True, default=None, max_length=31, null=True)),
|
||||
('family_name', models.CharField(blank=True, default=None, max_length=50, null=True)),
|
||||
('gender', models.CharField(blank=True, choices=[('1', 'Male'), ('2', 'Female')], default=None, max_length=15, null=True)),
|
||||
('dob', models.DateField(blank=True, default=None, max_length=15, null=True)),
|
||||
('guardian_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
||||
('junior_code', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, default=None, max_length=10, null=True), null=True, size=None)),
|
||||
('referral_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
||||
('referral_code_used', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
||||
('is_active', models.BooleanField(default=True)),
|
||||
('is_complete_profile', models.BooleanField(default=False)),
|
||||
('passcode', models.IntegerField(blank=True, default=None, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='guardian_profile', to=settings.AUTH_USER_MODEL, verbose_name='Email')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Guardian',
|
||||
'db_table': 'guardians',
|
||||
},
|
||||
),
|
||||
]
|
17
guardian/migrations/0002_remove_guardian_junior_code.py
Normal file
17
guardian/migrations/0002_remove_guardian_junior_code.py
Normal file
@ -0,0 +1,17 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-27 06:15
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='guardian',
|
||||
name='junior_code',
|
||||
),
|
||||
]
|
18
guardian/migrations/0003_guardian_country_name.py
Normal file
18
guardian/migrations/0003_guardian_country_name.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-27 13:59
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0002_remove_guardian_junior_code'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='guardian',
|
||||
name='country_name',
|
||||
field=models.CharField(blank=True, default=None, max_length=30, null=True),
|
||||
),
|
||||
]
|
18
guardian/migrations/0004_guardian_image.py
Normal file
18
guardian/migrations/0004_guardian_image.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-28 06:52
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0003_guardian_country_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='guardian',
|
||||
name='image',
|
||||
field=models.ImageField(blank=True, default=None, null=True, upload_to='images/'),
|
||||
),
|
||||
]
|
18
guardian/migrations/0005_alter_guardian_image.py
Normal file
18
guardian/migrations/0005_alter_guardian_image.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-29 06:14
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0004_guardian_image'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='guardian',
|
||||
name='image',
|
||||
field=models.ImageField(blank=True, default=None, null=True, upload_to=''),
|
||||
),
|
||||
]
|
18
guardian/migrations/0006_guardian_is_verified.py
Normal file
18
guardian/migrations/0006_guardian_is_verified.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-29 12:10
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0005_alter_guardian_image'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='guardian',
|
||||
name='is_verified',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
18
guardian/migrations/0007_alter_guardian_country_name.py
Normal file
18
guardian/migrations/0007_alter_guardian_country_name.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-30 10:53
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0006_guardian_is_verified'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='guardian',
|
||||
name='country_name',
|
||||
field=models.CharField(blank=True, default=None, max_length=100, null=True),
|
||||
),
|
||||
]
|
36
guardian/migrations/0008_juniortask.py
Normal file
36
guardian/migrations/0008_juniortask.py
Normal file
@ -0,0 +1,36 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-04 09:24
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0006_alter_junior_country_name'),
|
||||
('guardian', '0007_alter_guardian_country_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='JuniorTask',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('task_name', models.CharField(max_length=100)),
|
||||
('task_description', models.CharField(max_length=500)),
|
||||
('points', models.IntegerField(default=5)),
|
||||
('due_date', models.DateField(blank=True, null=True)),
|
||||
('image', models.ImageField(blank=True, default=None, null=True, upload_to='')),
|
||||
('task_status', models.CharField(blank=True, choices=[('1', 'pending'), ('2', 'in-progress'), ('3', 'rejected'), ('4', 'requested'), ('5', 'completed')], default='pending', max_length=15, null=True)),
|
||||
('is_active', models.BooleanField(default=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('guardian', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='guardian', to='guardian.guardian', verbose_name='Guardian')),
|
||||
('junior', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='junior', to='junior.junior', verbose_name='Junior')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Junior Task',
|
||||
'db_table': 'junior_task',
|
||||
},
|
||||
),
|
||||
]
|
18
guardian/migrations/0009_alter_juniortask_image.py
Normal file
18
guardian/migrations/0009_alter_juniortask_image.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-04 12:56
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0008_juniortask'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='juniortask',
|
||||
name='image',
|
||||
field=models.URLField(blank=True, default=None, null=True),
|
||||
),
|
||||
]
|
18
guardian/migrations/0010_alter_juniortask_task_status.py
Normal file
18
guardian/migrations/0010_alter_juniortask_task_status.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-04 13:41
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0009_alter_juniortask_image'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='juniortask',
|
||||
name='task_status',
|
||||
field=models.CharField(choices=[('1', 'pending'), ('2', 'in-progress'), ('3', 'rejected'), ('4', 'requested'), ('5', 'completed')], default='pending', max_length=15),
|
||||
),
|
||||
]
|
@ -0,0 +1,28 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-05 11:17
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0010_alter_juniortask_task_status'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='juniortask',
|
||||
name='default_image',
|
||||
field=models.ImageField(blank=True, default=None, null=True, upload_to=''),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='juniortask',
|
||||
name='is_approved',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AlterField(
|
||||
model_name='juniortask',
|
||||
name='task_status',
|
||||
field=models.CharField(choices=[('1', 'pending'), ('2', 'in-progress'), ('3', 'rejected'), ('4', 'requested'), ('5', 'completed')], default=1, max_length=15),
|
||||
),
|
||||
]
|
18
guardian/migrations/0012_alter_juniortask_default_image.py
Normal file
18
guardian/migrations/0012_alter_juniortask_default_image.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-06 05:12
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0011_juniortask_default_image_juniortask_is_approved_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='juniortask',
|
||||
name='default_image',
|
||||
field=models.URLField(blank=True, default=None, null=True),
|
||||
),
|
||||
]
|
18
guardian/migrations/0013_alter_guardian_image.py
Normal file
18
guardian/migrations/0013_alter_guardian_image.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-06 06:40
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0012_alter_juniortask_default_image'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='guardian',
|
||||
name='image',
|
||||
field=models.URLField(blank=True, default=None, null=True),
|
||||
),
|
||||
]
|
18
guardian/migrations/0014_guardian_signup_method.py
Normal file
18
guardian/migrations/0014_guardian_signup_method.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-11 11:26
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0013_alter_guardian_image'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='guardian',
|
||||
name='signup_method',
|
||||
field=models.CharField(choices=[('1', 'manual'), ('2', 'google'), ('3', 'apple')], default='1', max_length=31),
|
||||
),
|
||||
]
|
@ -0,0 +1,21 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-14 09:34
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0014_guardian_signup_method'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='guardian',
|
||||
options={'verbose_name': 'Guardian', 'verbose_name_plural': 'Guardian'},
|
||||
),
|
||||
migrations.AlterModelOptions(
|
||||
name='juniortask',
|
||||
options={'verbose_name': 'Junior Task', 'verbose_name_plural': 'Junior Task'},
|
||||
),
|
||||
]
|
@ -0,0 +1,28 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-18 07:17
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0015_alter_guardian_options_alter_juniortask_options'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='juniortask',
|
||||
name='completed_on',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='juniortask',
|
||||
name='rejected_on',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='juniortask',
|
||||
name='requested_on',
|
||||
field=models.DateTimeField(blank=True, null=True),
|
||||
),
|
||||
]
|
@ -0,0 +1,23 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-24 13:21
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0016_juniortask_completed_on_juniortask_rejected_on_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='juniortask',
|
||||
name='is_invited',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='juniortask',
|
||||
name='is_password_set',
|
||||
field=models.BooleanField(default=True),
|
||||
),
|
||||
]
|
@ -0,0 +1,21 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-24 13:23
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0017_juniortask_is_invited_juniortask_is_password_set'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='juniortask',
|
||||
name='is_invited',
|
||||
),
|
||||
migrations.RemoveField(
|
||||
model_name='juniortask',
|
||||
name='is_password_set',
|
||||
),
|
||||
]
|
@ -0,0 +1,23 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-24 13:23
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0018_remove_juniortask_is_invited_and_more'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='guardian',
|
||||
name='is_invited',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='guardian',
|
||||
name='is_password_set',
|
||||
field=models.BooleanField(default=True),
|
||||
),
|
||||
]
|
18
guardian/migrations/0020_alter_juniortask_task_status.py
Normal file
18
guardian/migrations/0020_alter_juniortask_task_status.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-25 07:44
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0019_guardian_is_invited_guardian_is_password_set'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='juniortask',
|
||||
name='task_status',
|
||||
field=models.CharField(choices=[('1', 'pending'), ('2', 'in-progress'), ('3', 'rejected'), ('4', 'requested'), ('5', 'completed'), ('6', 'expired')], default=1, max_length=15),
|
||||
),
|
||||
]
|
18
guardian/migrations/0021_guardian_is_deleted.py
Normal file
18
guardian/migrations/0021_guardian_is_deleted.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-08-17 12:45
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0020_alter_juniortask_task_status'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='guardian',
|
||||
name='is_deleted',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-09-08 10:41
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0021_guardian_is_deleted'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='juniortask',
|
||||
name='task_description',
|
||||
field=models.CharField(blank=True, max_length=500, null=True),
|
||||
),
|
||||
]
|
0
guardian/migrations/__init__.py
Normal file
0
guardian/migrations/__init__.py
Normal file
138
guardian/models.py
Normal file
138
guardian/models.py
Normal file
@ -0,0 +1,138 @@
|
||||
"""Guardian model file"""
|
||||
"""Third party Django app"""
|
||||
from django.db import models
|
||||
from django.contrib.auth import get_user_model
|
||||
"""Import Django app"""
|
||||
from base.constants import GENDERS, TASK_STATUS, PENDING, TASK_POINTS, SIGNUP_METHODS
|
||||
"""import Junior model"""
|
||||
import junior.models
|
||||
"""Add user model"""
|
||||
User = get_user_model()
|
||||
|
||||
# Create your models here.
|
||||
# Define junior model with
|
||||
# various fields like
|
||||
# phone, country code,
|
||||
# country name,
|
||||
# gender,
|
||||
# date of birth,
|
||||
# profile image,
|
||||
# signup method,
|
||||
# guardian code,
|
||||
# referral code,
|
||||
# referral code that used by the guardian
|
||||
# is invited guardian
|
||||
# profile is active or not
|
||||
# profile is complete or not
|
||||
# passcode
|
||||
# guardian is verified or not
|
||||
"""Define junior task model"""
|
||||
# define name of the Task
|
||||
# task description
|
||||
# points of the task
|
||||
# default image of the task
|
||||
# image uploaded by junior
|
||||
# task status
|
||||
# task approved or not
|
||||
|
||||
# Create your models here.
|
||||
|
||||
class Guardian(models.Model):
|
||||
"""Guardian model"""
|
||||
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='guardian_profile', verbose_name='Email')
|
||||
"""Contact details"""
|
||||
country_code = models.IntegerField(blank=True, null=True)
|
||||
phone = models.CharField(max_length=31, null=True, blank=True, default=None)
|
||||
"""country name of the guardian"""
|
||||
country_name = models.CharField(max_length=100, null=True, blank=True, default=None)
|
||||
"""Image info"""
|
||||
image = models.URLField(null=True, blank=True, default=None)
|
||||
"""Personal info"""
|
||||
family_name = models.CharField(max_length=50, null=True, blank=True, default=None)
|
||||
"""gender of the guardian"""
|
||||
gender = models.CharField(choices=GENDERS, max_length=15, null=True, blank=True, default=None)
|
||||
"""date of birth of the guardian"""
|
||||
dob = models.DateField(max_length=15, null=True, blank=True, default=None)
|
||||
# invited junior"""
|
||||
is_invited = models.BooleanField(default=False)
|
||||
# Profile activity"""
|
||||
is_password_set = models.BooleanField(default=True)
|
||||
# guardian profile deleted or not"""
|
||||
is_deleted = models.BooleanField(default=False)
|
||||
"""Profile activity"""
|
||||
is_active = models.BooleanField(default=True)
|
||||
"""guardian is verified or not"""
|
||||
is_verified = models.BooleanField(default=False)
|
||||
"""guardian profile is complete or not"""
|
||||
is_complete_profile = models.BooleanField(default=False)
|
||||
"""passcode of the guardian profile"""
|
||||
passcode = models.IntegerField(null=True, blank=True, default=None)
|
||||
"""Sign up method"""
|
||||
signup_method = models.CharField(max_length=31, choices=SIGNUP_METHODS, default='1')
|
||||
"""Guardian Codes"""
|
||||
guardian_code = models.CharField(max_length=10, null=True, blank=True, default=None)
|
||||
"""Referral code"""
|
||||
referral_code = models.CharField(max_length=10, null=True, blank=True, default=None)
|
||||
"""Referral code that is used by guardian while signup"""
|
||||
referral_code_used = models.CharField(max_length=10, null=True, blank=True, default=None)
|
||||
"""Profile created and updated time"""
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta(object):
|
||||
""" Meta class """
|
||||
db_table = 'guardians'
|
||||
"""verbose name of the model"""
|
||||
verbose_name = 'Guardian'
|
||||
"""change another name"""
|
||||
verbose_name_plural = 'Guardian'
|
||||
|
||||
def __str__(self):
|
||||
"""Return email id"""
|
||||
return f'{self.user}'
|
||||
|
||||
class JuniorTask(models.Model):
|
||||
"""Junior Task details model"""
|
||||
guardian = models.ForeignKey(Guardian, on_delete=models.CASCADE, related_name='guardian', verbose_name='Guardian')
|
||||
"""task details"""
|
||||
task_name = models.CharField(max_length=100)
|
||||
"""task description"""
|
||||
task_description = models.CharField(max_length=500, null=True, blank=True)
|
||||
"""points of the task"""
|
||||
points = models.IntegerField(default=TASK_POINTS)
|
||||
"""last date of the task"""
|
||||
due_date = models.DateField(auto_now_add=False, null=True, blank=True)
|
||||
"""Images of task that is upload by guardian"""
|
||||
default_image = models.URLField(null=True, blank=True, default=None)
|
||||
"""image that is uploaded by junior"""
|
||||
image = models.URLField(null=True, blank=True, default=None)
|
||||
"""associated junior with the task"""
|
||||
junior = models.ForeignKey('junior.Junior', on_delete=models.CASCADE, related_name='junior', verbose_name='Junior')
|
||||
"""task status"""
|
||||
task_status = models.CharField(choices=TASK_STATUS, max_length=15, default=PENDING)
|
||||
"""task is active or not"""
|
||||
is_active = models.BooleanField(default=True)
|
||||
"""Task is approved or not"""
|
||||
is_approved = models.BooleanField(default=False)
|
||||
"""request task on particular date"""
|
||||
requested_on = models.DateTimeField(auto_now_add=False, null=True, blank=True)
|
||||
"""reject task on particular date"""
|
||||
rejected_on = models.DateTimeField(auto_now_add=False, null=True, blank=True)
|
||||
"""complete task on particular date"""
|
||||
completed_on = models.DateTimeField(auto_now_add=False, null=True, blank=True)
|
||||
"""Profile created and updated time"""
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
updated_at = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta(object):
|
||||
""" Meta class """
|
||||
db_table = 'junior_task'
|
||||
"""verbose name of the model"""
|
||||
verbose_name = 'Junior Task'
|
||||
verbose_name_plural = 'Junior Task'
|
||||
|
||||
def __str__(self):
|
||||
"""Return email id"""
|
||||
return f'{self.task_name}'
|
||||
|
||||
|
529
guardian/serializers.py
Normal file
529
guardian/serializers.py
Normal file
@ -0,0 +1,529 @@
|
||||
"""Serializer of Guardian"""
|
||||
# third party imports
|
||||
import logging
|
||||
from django.contrib.auth import password_validation
|
||||
from rest_framework import serializers
|
||||
# Import Refresh token of jwt
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
from django.db import transaction
|
||||
from django.contrib.auth.models import User
|
||||
from datetime import datetime, time
|
||||
import pytz
|
||||
from django.utils import timezone
|
||||
# Import guardian's model,
|
||||
# Import junior's model,
|
||||
# Import account's model,
|
||||
# Import constant from
|
||||
# base package,
|
||||
# Import messages from
|
||||
# base package,
|
||||
# Import some functions
|
||||
# local imports
|
||||
from .models import Guardian, JuniorTask
|
||||
from account.models import UserProfile, UserEmailOtp, UserNotification
|
||||
from account.utils import generate_code
|
||||
from junior.serializers import JuniorDetailSerializer
|
||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
||||
from base.constants import NUMBER, JUN, ZOD, GRD, Already_register_user, GUARDIAN
|
||||
from junior.models import Junior, JuniorPoints, JuniorGuardianRelationship
|
||||
from .utils import real_time, convert_timedelta_into_datetime, update_referral_points
|
||||
# notification's constant
|
||||
from notifications.constants import TASK_APPROVED, TASK_REJECTED, TASK_ASSIGNED
|
||||
# send notification function
|
||||
from notifications.utils import send_notification
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.utils.translation import gettext as _
|
||||
|
||||
# In this serializer file
|
||||
# define user serializer,
|
||||
# define password validation
|
||||
# create guardian serializer,
|
||||
# task serializer,
|
||||
# guardian serializer,
|
||||
# task details serializer,
|
||||
# top junior serializer,
|
||||
# guardian profile serializer,
|
||||
# approve junior serializer,
|
||||
# approve task serializer,
|
||||
from rest_framework import serializers
|
||||
|
||||
class PasswordValidator:
|
||||
"""Password validation"""
|
||||
def __init__(self, min_length=8, max_length=None, require_uppercase=True, require_numbers=True):
|
||||
self.min_length = min_length
|
||||
self.max_length = max_length
|
||||
self.require_uppercase = require_uppercase
|
||||
self.require_numbers = require_numbers
|
||||
|
||||
def __call__(self, value):
|
||||
self.enforce_password_policy(value)
|
||||
|
||||
def enforce_password_policy(self, password):
|
||||
# add validation for password
|
||||
special_characters = "!@#$%^&*()_-+=<>?/[]{}|"
|
||||
if len(password) < self.min_length:
|
||||
raise serializers.ValidationError(
|
||||
_("Password must be at least %(min_length)d characters long.") % {'min_length': self.min_length}
|
||||
)
|
||||
|
||||
if self.max_length is not None and len(password) > self.max_length:
|
||||
# must be 8 character
|
||||
raise serializers.ValidationError(
|
||||
_("Password must be at most %(max_length)d characters long.") % {'max_length': self.max_length}
|
||||
)
|
||||
|
||||
if self.require_uppercase and not any(char.isupper() for char in password):
|
||||
# must contain upper case letter
|
||||
raise serializers.ValidationError(_("Password must contain at least one uppercase letter."))
|
||||
|
||||
if self.require_numbers and not any(char.isdigit() for char in password):
|
||||
# must contain digit
|
||||
raise serializers.ValidationError(_("Password must contain at least one digit."))
|
||||
if self.require_numbers and not any(char in special_characters for char in password):
|
||||
# must contain special character
|
||||
raise serializers.ValidationError(_("Password must contain at least one special character."))
|
||||
|
||||
|
||||
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
"""User serializer"""
|
||||
auth_token = serializers.SerializerMethodField('get_auth_token')
|
||||
password = serializers.CharField(write_only=True, validators=[PasswordValidator()])
|
||||
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = User
|
||||
fields = ['id', 'email', 'password', 'auth_token']
|
||||
|
||||
def get_auth_token(self, obj):
|
||||
"""generate auth token"""
|
||||
refresh = RefreshToken.for_user(obj)
|
||||
access_token = str(refresh.access_token)
|
||||
return access_token
|
||||
def create(self, validated_data):
|
||||
"""fetch data"""
|
||||
email = validated_data.get('email')
|
||||
user_type = self.context
|
||||
password = validated_data.get('password')
|
||||
try:
|
||||
"""Create user profile"""
|
||||
user = User.objects.create_user(username=email, email=email, password=password)
|
||||
UserNotification.objects.get_or_create(user=user)
|
||||
if user_type == str(NUMBER['one']):
|
||||
# create junior profile
|
||||
junior = Junior.objects.create(auth=user, junior_code=generate_code(JUN, user.id),
|
||||
referral_code=generate_code(ZOD, user.id))
|
||||
position = Junior.objects.all().count()
|
||||
JuniorPoints.objects.create(junior=junior, position=position)
|
||||
if user_type == str(NUMBER['two']):
|
||||
# create guardian profile
|
||||
Guardian.objects.create(user=user, guardian_code=generate_code(GRD, user.id),
|
||||
referral_code=generate_code(ZOD, user.id))
|
||||
return user
|
||||
except Exception as e:
|
||||
"""Error handling"""
|
||||
logging.error(e)
|
||||
otp = UserEmailOtp.objects.filter(email=email).last()
|
||||
otp_verified = False
|
||||
if otp and otp.is_verified:
|
||||
otp_verified = True
|
||||
raise serializers.ValidationError({"details": ERROR_CODE['2021'], "otp_verified":bool(otp_verified),
|
||||
"code": 400, "status":"failed",
|
||||
})
|
||||
|
||||
# update guardian profile
|
||||
class CreateGuardianSerializer(serializers.ModelSerializer):
|
||||
"""Create guardian serializer"""
|
||||
"""Basic info"""
|
||||
first_name = serializers.SerializerMethodField('get_first_name')
|
||||
last_name = serializers.SerializerMethodField('get_last_name')
|
||||
email = serializers.SerializerMethodField('get_email')
|
||||
"""Contact details"""
|
||||
phone = serializers.CharField(max_length=20, required=False)
|
||||
country_code = serializers.IntegerField(required=False)
|
||||
# basic info
|
||||
family_name = serializers.CharField(max_length=100, required=False)
|
||||
dob = serializers.DateField(required=False)
|
||||
# code info
|
||||
referral_code = serializers.CharField(max_length=100, required=False)
|
||||
# image info
|
||||
image = serializers.URLField(required=False)
|
||||
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = Guardian
|
||||
fields = ['id', 'first_name', 'last_name', 'email', 'phone', 'family_name', 'gender', 'country_code',
|
||||
'dob', 'referral_code', 'passcode', 'is_complete_profile', 'referral_code_used',
|
||||
'country_name', 'image']
|
||||
|
||||
def get_first_name(self,obj):
|
||||
"""first name of guardian"""
|
||||
return obj.user.first_name
|
||||
|
||||
def get_last_name(self,obj):
|
||||
"""last name of guardian"""
|
||||
return obj.user.last_name
|
||||
|
||||
def get_email(self,obj):
|
||||
"""emailof guardian"""
|
||||
return obj.user.email
|
||||
|
||||
def create(self, validated_data):
|
||||
"""Create guardian profile"""
|
||||
user = User.objects.filter(username=self.context['user']).last()
|
||||
if user:
|
||||
"""Save first and last name of guardian"""
|
||||
if self.context.get('first_name') != '' and self.context.get('first_name') is not None:
|
||||
user.first_name = self.context.get('first_name')
|
||||
if self.context.get('last_name') != '' and self.context.get('last_name') is not None:
|
||||
user.last_name = self.context.get('last_name')
|
||||
user.save()
|
||||
"""Create guardian data"""
|
||||
guardian = Guardian.objects.filter(user=self.context['user']).last()
|
||||
if guardian:
|
||||
"""update details according to the data get from request"""
|
||||
guardian.gender = validated_data.get('gender',guardian.gender)
|
||||
guardian.family_name = validated_data.get('family_name', guardian.family_name)
|
||||
guardian.dob = validated_data.get('dob',guardian.dob)
|
||||
"""Update country code and phone number"""
|
||||
guardian.phone = validated_data.get('phone', guardian.phone)
|
||||
guardian.country_code = validated_data.get('country_code', guardian.country_code)
|
||||
guardian.passcode = validated_data.get('passcode', guardian.passcode)
|
||||
guardian.country_name = validated_data.get('country_name', guardian.country_name)
|
||||
guardian.image = validated_data.get('image', guardian.image)
|
||||
"""Complete profile of the junior if below all data are filled"""
|
||||
complete_profile_field = all([guardian.gender, guardian.country_name,
|
||||
guardian.dob, user.first_name,
|
||||
guardian.image])
|
||||
guardian.is_complete_profile = False
|
||||
if complete_profile_field:
|
||||
guardian.is_complete_profile = True
|
||||
referral_code_used = validated_data.get('referral_code_used')
|
||||
update_referral_points(guardian.referral_code, referral_code_used)
|
||||
guardian.referral_code_used = validated_data.get('referral_code_used', guardian.referral_code_used)
|
||||
guardian.save()
|
||||
return guardian
|
||||
|
||||
def save(self, **kwargs):
|
||||
"""Save the data into junior table"""
|
||||
with transaction.atomic():
|
||||
instance = super().save(**kwargs)
|
||||
return instance
|
||||
|
||||
|
||||
|
||||
class TaskSerializer(serializers.ModelSerializer):
|
||||
"""Task serializer"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = JuniorTask
|
||||
fields = ['id', 'task_name','task_description','points', 'due_date','default_image']
|
||||
|
||||
def validate_due_date(self, value):
|
||||
"""validation on due date"""
|
||||
if value < datetime.today().date():
|
||||
raise serializers.ValidationError({"details": ERROR_CODE['2046'],
|
||||
"code": 400, "status": "failed",
|
||||
})
|
||||
return value
|
||||
def create(self, validated_data):
|
||||
"""create default task image data"""
|
||||
guardian = self.context['guardian']
|
||||
# update image of the task
|
||||
images = self.context['image']
|
||||
junior_data = self.context['junior_data']
|
||||
tasks_created = []
|
||||
|
||||
for junior in junior_data:
|
||||
# create task
|
||||
task_data = validated_data.copy()
|
||||
task_data['guardian'] = guardian
|
||||
task_data['default_image'] = images
|
||||
task_data['junior'] = junior
|
||||
instance = JuniorTask.objects.create(**task_data)
|
||||
tasks_created.append(instance)
|
||||
send_notification.delay(TASK_ASSIGNED, guardian.user_id, GUARDIAN,
|
||||
junior.auth_id, {'task_id': instance.id})
|
||||
return instance
|
||||
|
||||
class GuardianDetailSerializer(serializers.ModelSerializer):
|
||||
"""junior serializer"""
|
||||
|
||||
email = serializers.SerializerMethodField('get_auth')
|
||||
first_name = serializers.SerializerMethodField('get_first_name')
|
||||
last_name = serializers.SerializerMethodField('get_last_name')
|
||||
|
||||
def get_auth(self, obj):
|
||||
"""user email address"""
|
||||
return obj.user.username
|
||||
|
||||
def get_first_name(self, obj):
|
||||
"""user first name"""
|
||||
return obj.user.first_name
|
||||
|
||||
def get_last_name(self, obj):
|
||||
"""user last name"""
|
||||
return obj.user.last_name
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = Guardian
|
||||
fields = ['id', 'email', 'first_name', 'last_name', 'country_code', 'phone', 'gender', 'dob',
|
||||
'guardian_code','is_active', 'is_complete_profile', 'created_at', 'image', 'is_deleted',
|
||||
'updated_at']
|
||||
class TaskDetailsSerializer(serializers.ModelSerializer):
|
||||
"""Task detail serializer"""
|
||||
|
||||
junior = JuniorDetailSerializer()
|
||||
remaining_time = serializers.SerializerMethodField('get_remaining_time')
|
||||
is_expired = serializers.SerializerMethodField('get_is_expired')
|
||||
|
||||
def get_remaining_time(self, obj):
|
||||
""" remaining time to complete task"""
|
||||
due_date_datetime = datetime.combine(obj.due_date, datetime.max.time())
|
||||
# fetch real time
|
||||
# current_datetime = real_time()
|
||||
# new code
|
||||
due_date_datetime = due_date_datetime.astimezone(pytz.utc)
|
||||
current_datetime = timezone.now().astimezone(pytz.utc)
|
||||
# Perform the subtraction
|
||||
if due_date_datetime > current_datetime:
|
||||
time_difference = due_date_datetime - current_datetime
|
||||
time_only = convert_timedelta_into_datetime(time_difference)
|
||||
return str(time_difference.days) + ' days ' + str(time_only)
|
||||
return str(NUMBER['zero']) + ' days ' + '00:00:00:00000'
|
||||
|
||||
def get_is_expired(self, obj):
|
||||
""" task expired or not"""
|
||||
if obj.due_date < datetime.today().date():
|
||||
return True
|
||||
return False
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = JuniorTask
|
||||
fields = ['id', 'guardian', 'task_name', 'task_description', 'points', 'due_date','default_image', 'image',
|
||||
'requested_on', 'rejected_on', 'completed_on', 'is_expired',
|
||||
'junior', 'task_status', 'is_active', 'remaining_time', 'created_at','updated_at']
|
||||
|
||||
class TaskDetailsjuniorSerializer(serializers.ModelSerializer):
|
||||
"""Task detail serializer"""
|
||||
|
||||
guardian = GuardianDetailSerializer()
|
||||
remaining_time = serializers.SerializerMethodField('get_remaining_time')
|
||||
|
||||
def get_remaining_time(self, obj):
|
||||
""" remaining time to complete task"""
|
||||
due_date_datetime = datetime.combine(obj.due_date, datetime.max.time())
|
||||
# fetch real time
|
||||
# current_datetime = real_time()
|
||||
# new code
|
||||
due_date_datetime = due_date_datetime.astimezone(pytz.utc)
|
||||
current_datetime = timezone.now().astimezone(pytz.utc)
|
||||
# Perform the subtraction
|
||||
if due_date_datetime > current_datetime:
|
||||
time_difference = due_date_datetime - current_datetime
|
||||
time_only = convert_timedelta_into_datetime(time_difference)
|
||||
return str(time_difference.days) + ' days ' + str(time_only)
|
||||
return str(NUMBER['zero']) + ' days ' + '00:00:00:00000'
|
||||
|
||||
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = JuniorTask
|
||||
fields = ['id', 'guardian', 'task_name', 'task_description', 'points', 'due_date','default_image', 'image',
|
||||
'requested_on', 'rejected_on', 'completed_on',
|
||||
'junior', 'task_status', 'is_active', 'remaining_time', 'created_at','updated_at']
|
||||
|
||||
|
||||
class TopJuniorSerializer(serializers.ModelSerializer):
|
||||
"""Top junior serializer"""
|
||||
junior = JuniorDetailSerializer()
|
||||
position = serializers.SerializerMethodField()
|
||||
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = JuniorPoints
|
||||
fields = ['id', 'junior', 'total_points', 'position', 'created_at', 'updated_at']
|
||||
|
||||
def to_representation(self, instance):
|
||||
"""Convert instance to representation"""
|
||||
representation = super().to_representation(instance)
|
||||
return representation
|
||||
|
||||
@staticmethod
|
||||
def get_position(obj):
|
||||
""" get position/rank """
|
||||
return obj.rank
|
||||
|
||||
|
||||
class GuardianProfileSerializer(serializers.ModelSerializer):
|
||||
"""junior serializer"""
|
||||
|
||||
email = serializers.SerializerMethodField('get_auth')
|
||||
first_name = serializers.SerializerMethodField('get_first_name')
|
||||
last_name = serializers.SerializerMethodField('get_last_name')
|
||||
total_count = serializers.SerializerMethodField('get_total_count')
|
||||
complete_field_count = serializers.SerializerMethodField('get_complete_field_count')
|
||||
notification_count = serializers.SerializerMethodField('get_notification_count')
|
||||
|
||||
def get_auth(self, obj):
|
||||
"""user email address"""
|
||||
return obj.user.username
|
||||
|
||||
def get_first_name(self, obj):
|
||||
"""user first name"""
|
||||
return obj.user.first_name
|
||||
|
||||
def get_last_name(self, obj):
|
||||
"""user last name"""
|
||||
return obj.user.last_name
|
||||
|
||||
def get_total_count(self, obj):
|
||||
"""total fields count"""
|
||||
return NUMBER['five']
|
||||
|
||||
def get_complete_field_count(self, obj):
|
||||
"""total filled fields count"""
|
||||
total_field_list = [obj.user.first_name, obj.country_name,
|
||||
obj.gender, obj.dob, obj.image]
|
||||
# count total complete field
|
||||
total_complete_field = [data for data in total_field_list if data != '' and data is not None]
|
||||
return len(total_complete_field)
|
||||
|
||||
def get_notification_count(self, obj):
|
||||
"""total notification count"""
|
||||
return 0
|
||||
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = Guardian
|
||||
fields = ['id', 'email', 'first_name', 'last_name', 'country_name','country_code', 'phone', 'gender', 'dob',
|
||||
'guardian_code', 'notification_count', 'total_count', 'complete_field_count', 'referral_code',
|
||||
'is_active', 'is_complete_profile', 'created_at', 'image', 'signup_method',
|
||||
'updated_at', 'passcode','is_deleted']
|
||||
|
||||
|
||||
class ApproveJuniorSerializer(serializers.ModelSerializer):
|
||||
"""approve junior serializer"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = Junior
|
||||
fields = ['id', 'guardian_code']
|
||||
|
||||
def create(self, validated_data):
|
||||
"""update guardian code"""
|
||||
instance = self.context['junior']
|
||||
guardian_code = self.context['guardian_code']
|
||||
index = instance.guardian_code.index(guardian_code)
|
||||
instance.guardian_code_status[index] = str(NUMBER['two'])
|
||||
instance.save()
|
||||
return instance
|
||||
|
||||
|
||||
class ApproveTaskSerializer(serializers.ModelSerializer):
|
||||
"""approve task serializer"""
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = JuniorTask
|
||||
fields = ['id', 'task_status', 'is_approved']
|
||||
|
||||
def create(self, validated_data):
|
||||
"""update task status """
|
||||
with transaction.atomic():
|
||||
instance = self.context['task_instance']
|
||||
junior = self.context['junior']
|
||||
junior_details = Junior.objects.filter(id=junior).last()
|
||||
junior_data, created = JuniorPoints.objects.get_or_create(junior=junior_details)
|
||||
if self.context['action'] == str(NUMBER['one']):
|
||||
# approve the task
|
||||
instance.task_status = str(NUMBER['five'])
|
||||
instance.is_approved = True
|
||||
# update total task point
|
||||
junior_data.total_points = junior_data.total_points + instance.points
|
||||
# update complete time of task
|
||||
# instance.completed_on = real_time()
|
||||
instance.completed_on = timezone.now().astimezone(pytz.utc)
|
||||
send_notification.delay(TASK_APPROVED, instance.guardian.user_id, GUARDIAN,
|
||||
junior_details.auth_id, {'task_id': instance.id})
|
||||
else:
|
||||
# reject the task
|
||||
instance.task_status = str(NUMBER['three'])
|
||||
instance.is_approved = False
|
||||
# update reject time of task
|
||||
# instance.rejected_on = real_time()
|
||||
instance.rejected_on = timezone.now().astimezone(pytz.utc)
|
||||
send_notification.delay(TASK_REJECTED, instance.guardian.user_id, GUARDIAN,
|
||||
junior_details.auth_id, {'task_id': instance.id})
|
||||
instance.save()
|
||||
junior_data.save()
|
||||
return junior_details
|
||||
|
||||
class GuardianDetailListSerializer(serializers.ModelSerializer):
|
||||
"""Guardian serializer"""
|
||||
|
||||
first_name = serializers.SerializerMethodField('get_first_name')
|
||||
last_name = serializers.SerializerMethodField('get_last_name')
|
||||
email = serializers.SerializerMethodField('get_email')
|
||||
image = serializers.SerializerMethodField('get_image')
|
||||
guardian_id = serializers.SerializerMethodField('get_guardian_id')
|
||||
guardian_code = serializers.SerializerMethodField('get_guardian_code')
|
||||
gender = serializers.SerializerMethodField('get_gender')
|
||||
phone = serializers.SerializerMethodField('get_phone')
|
||||
country_name = serializers.SerializerMethodField('get_country_name')
|
||||
dob = serializers.SerializerMethodField('get_dob')
|
||||
guardian_code_status = serializers.SerializerMethodField('get_guardian_code_status')
|
||||
# code info
|
||||
|
||||
|
||||
class Meta(object):
|
||||
"""Meta info"""
|
||||
model = JuniorGuardianRelationship
|
||||
fields = ['guardian_id', 'first_name', 'last_name', 'email', 'relationship', 'image', 'dob',
|
||||
'guardian_code', 'gender', 'phone', 'country_name', 'created_at', 'guardian_code_status',
|
||||
'updated_at']
|
||||
|
||||
def get_guardian_id(self,obj):
|
||||
"""first name of guardian"""
|
||||
return obj.guardian.id
|
||||
def get_first_name(self,obj):
|
||||
"""first name of guardian"""
|
||||
return obj.guardian.user.first_name
|
||||
|
||||
def get_last_name(self,obj):
|
||||
"""last name of guardian"""
|
||||
return obj.guardian.user.last_name
|
||||
|
||||
def get_email(self,obj):
|
||||
"""email of guardian"""
|
||||
return obj.guardian.user.email
|
||||
|
||||
def get_image(self,obj):
|
||||
"""guardian image"""
|
||||
return obj.guardian.image
|
||||
|
||||
def get_guardian_code(self,obj):
|
||||
""" guardian code"""
|
||||
return obj.guardian.guardian_code
|
||||
|
||||
def get_gender(self,obj):
|
||||
""" guardian gender"""
|
||||
return obj.guardian.gender
|
||||
|
||||
def get_phone(self,obj):
|
||||
"""guardian phone"""
|
||||
return obj.guardian.phone
|
||||
|
||||
def get_country_name(self,obj):
|
||||
""" guardian country name """
|
||||
return obj.guardian.country_name
|
||||
|
||||
def get_dob(self,obj):
|
||||
"""guardian dob """
|
||||
return obj.guardian.dob
|
||||
|
||||
def get_guardian_code_status(self,obj):
|
||||
"""guardian code status"""
|
||||
if obj.guardian.guardian_code in obj.junior.guardian_code:
|
||||
index = obj.junior.guardian_code.index(obj.guardian.guardian_code)
|
||||
data = obj.junior.guardian_code_status[index]
|
||||
return data
|
12
guardian/tasks.py
Normal file
12
guardian/tasks.py
Normal file
@ -0,0 +1,12 @@
|
||||
"""task files"""
|
||||
|
||||
# Django import
|
||||
import secrets
|
||||
|
||||
|
||||
def generate_otp():
|
||||
"""
|
||||
generate random otp
|
||||
"""
|
||||
digits = "0123456789"
|
||||
return "".join(secrets.choice(digits) for _ in range(6))
|
5
guardian/tests.py
Normal file
5
guardian/tests.py
Normal file
@ -0,0 +1,5 @@
|
||||
"""Test file of Guardian"""
|
||||
"""Third party Django app"""
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
43
guardian/urls.py
Normal file
43
guardian/urls.py
Normal file
@ -0,0 +1,43 @@
|
||||
""" Urls files"""
|
||||
"""Django import"""
|
||||
from django.urls import path, include
|
||||
from .views import (SignupViewset, UpdateGuardianProfile, CreateTaskAPIView, TaskListAPIView,
|
||||
SearchTaskListAPIView, TopJuniorListAPIView, ApproveJuniorAPIView, ApproveTaskAPIView,
|
||||
GuardianListAPIView)
|
||||
"""Third party import"""
|
||||
from rest_framework import routers
|
||||
|
||||
"""Define Router"""
|
||||
router = routers.SimpleRouter()
|
||||
|
||||
# API End points with router
|
||||
# in this file
|
||||
# we define various api end point
|
||||
# that is covered in this guardian
|
||||
# section API:- like
|
||||
# sign-up, create guardian profile,
|
||||
# create-task,
|
||||
# all task list, top junior,
|
||||
# filter-task"""
|
||||
"""Sign up API"""
|
||||
router.register('sign-up', SignupViewset, basename='sign-up')
|
||||
# Create guardian profile API"""
|
||||
router.register('create-guardian-profile', UpdateGuardianProfile, basename='update-guardian-profile')
|
||||
# Create Task API"""
|
||||
router.register('create-task', CreateTaskAPIView, basename='create-task')
|
||||
# Task list bases on the status API"""
|
||||
router.register('task-list', TaskListAPIView, basename='task-list')
|
||||
# Leaderboard API"""
|
||||
router.register('top-junior', TopJuniorListAPIView, basename='top-junior')
|
||||
# Search Task list on the bases of status, due date, and task title API"""
|
||||
router.register('filter-task', SearchTaskListAPIView, basename='filter-task')
|
||||
# Approve junior API"""
|
||||
router.register('approve-junior', ApproveJuniorAPIView, basename='approve-junior')
|
||||
# Approve junior API"""
|
||||
router.register('approve-task', ApproveTaskAPIView, basename='approve-task')
|
||||
# guardian list API"""
|
||||
router.register('guardian-list', GuardianListAPIView, basename='guardian-list')
|
||||
# Define Url pattern"""
|
||||
urlpatterns = [
|
||||
path('api/v1/', include(router.urls)),
|
||||
]
|
134
guardian/utils.py
Normal file
134
guardian/utils.py
Normal file
@ -0,0 +1,134 @@
|
||||
"""Utiles file of guardian"""
|
||||
"""Django import"""
|
||||
import oss2
|
||||
"""Import setting"""
|
||||
from django.conf import settings
|
||||
import logging
|
||||
import requests
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
"""Import tempfile"""
|
||||
import tempfile
|
||||
# Import date time module's function
|
||||
from datetime import datetime, time
|
||||
# import Number constant
|
||||
from base.constants import NUMBER
|
||||
# Import Junior's model
|
||||
from junior.models import Junior, JuniorPoints
|
||||
# Import guardian's model
|
||||
from .models import JuniorTask
|
||||
# Import app from celery
|
||||
from zod_bank.celery import app
|
||||
# notification's constant
|
||||
from notifications.constants import REFERRAL_POINTS
|
||||
# send notification function
|
||||
from notifications.utils import send_notification
|
||||
|
||||
|
||||
# Define upload image on
|
||||
# ali baba cloud
|
||||
# firstly save image
|
||||
# in temporary file
|
||||
# then check bucket name
|
||||
# then upload on ali baba
|
||||
# bucket and reform the image url"""
|
||||
# fetch real time data without depend on system time
|
||||
# convert time delta into date time object
|
||||
# update junior total points
|
||||
# update referral points
|
||||
# if any one use referral code of the junior
|
||||
# junior earn 5 points
|
||||
|
||||
def upload_image_to_alibaba(image, filename):
|
||||
"""upload image on oss alibaba bucket"""
|
||||
# Save the image object to a temporary file
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
"""write image in temporary file"""
|
||||
temp_file.write(image.read())
|
||||
return upload_file_to_alibaba(temp_file, filename)
|
||||
|
||||
|
||||
def upload_base64_image_to_alibaba(image, filename):
|
||||
"""
|
||||
upload image on oss alibaba bucket
|
||||
"""
|
||||
# Save the image object to a temporary file
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
# write image in temporary file
|
||||
temp_file.write(image)
|
||||
return upload_file_to_alibaba(temp_file, filename)
|
||||
|
||||
|
||||
def upload_excel_file_to_alibaba(response, filename):
|
||||
"""
|
||||
upload excel file on oss alibaba bucket
|
||||
"""
|
||||
# Save the image object to a temporary file
|
||||
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
||||
# write image in temporary file
|
||||
temp_file.write(response.content)
|
||||
return upload_file_to_alibaba(temp_file, filename)
|
||||
|
||||
|
||||
def upload_file_to_alibaba(temp_file, filename):
|
||||
"""auth of bucket"""
|
||||
auth = oss2.Auth(settings.ALIYUN_OSS_ACCESS_KEY_ID, settings.ALIYUN_OSS_ACCESS_KEY_SECRET)
|
||||
"""fetch bucket details"""
|
||||
bucket = oss2.Bucket(auth, settings.ALIYUN_OSS_ENDPOINT, settings.ALIYUN_OSS_BUCKET_NAME)
|
||||
# Upload the temporary file to Alibaba OSS
|
||||
bucket.put_object_from_file(filename, temp_file.name)
|
||||
"""create perfect url for image"""
|
||||
new_filename = filename.replace(' ', '%20')
|
||||
return f"https://{settings.ALIYUN_OSS_BUCKET_NAME}.{settings.ALIYUN_OSS_ENDPOINT}/{new_filename}"
|
||||
|
||||
|
||||
def real_time():
|
||||
"""fetch real time from world time api"""
|
||||
url = time_url
|
||||
response = requests.get(url)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
time_str = data['datetime']
|
||||
realtime = datetime.fromisoformat(time_str.replace('Z', '+00:00')).replace(tzinfo=None)
|
||||
return realtime
|
||||
else:
|
||||
logging.error("Could not fetch error")
|
||||
return None
|
||||
|
||||
|
||||
def convert_timedelta_into_datetime(time_difference):
|
||||
"""convert date time"""
|
||||
# convert timedelta into datetime format
|
||||
hours = time_difference.seconds // NUMBER['thirty_six_hundred']
|
||||
minutes = (time_difference.seconds // NUMBER['sixty']) % NUMBER['sixty']
|
||||
seconds = time_difference.seconds % NUMBER['sixty']
|
||||
microseconds = time_difference.microseconds
|
||||
# Create a new time object with the extracted time components
|
||||
time_only = time(hours, minutes, seconds, microseconds)
|
||||
return time_only
|
||||
|
||||
def update_referral_points(referral_code, referral_code_used):
|
||||
"""Update benefit of referral points"""
|
||||
junior_queryset = Junior.objects.filter(referral_code=referral_code_used).last()
|
||||
if junior_queryset and junior_queryset.referral_code != referral_code:
|
||||
# create data if junior points is not exist
|
||||
junior_query, created = JuniorPoints.objects.get_or_create(junior=junior_queryset)
|
||||
if junior_query:
|
||||
# update junior total points and referral points
|
||||
junior_query.total_points = junior_query.total_points + NUMBER['five']
|
||||
junior_query.referral_points = junior_query.referral_points + NUMBER['five']
|
||||
junior_query.save()
|
||||
send_notification.delay(REFERRAL_POINTS, None, None, junior_queryset.auth_id, {})
|
||||
|
||||
|
||||
|
||||
@app.task
|
||||
def update_expired_task_status(data=None):
|
||||
"""
|
||||
Update task of the status if due date is in past
|
||||
"""
|
||||
try:
|
||||
task_status = [str(NUMBER['one']), str(NUMBER['two'])]
|
||||
JuniorTask.objects.filter(due_date__lt=datetime.today().date(),
|
||||
task_status__in=task_status).update(task_status=str(NUMBER['six']))
|
||||
except ObjectDoesNotExist as e:
|
||||
logging.error(str(e))
|
410
guardian/views.py
Normal file
410
guardian/views.py
Normal file
@ -0,0 +1,410 @@
|
||||
"""Views of Guardian"""
|
||||
import math
|
||||
|
||||
# django imports
|
||||
# Import IsAuthenticated
|
||||
# Import viewsets and status
|
||||
# Import PageNumberPagination
|
||||
# Import User
|
||||
# Import timezone
|
||||
from django.db.models import F, Window
|
||||
from django.db.models.functions.window import Rank
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework import viewsets, status
|
||||
from rest_framework.pagination import PageNumberPagination
|
||||
from django.contrib.auth.models import User
|
||||
from base.constants import guardian_code_tuple
|
||||
from rest_framework.filters import SearchFilter
|
||||
from django.utils import timezone
|
||||
|
||||
from base.pagination import CustomPageNumberPagination
|
||||
# Import guardian's model,
|
||||
# Import junior's model,
|
||||
# Import account's model,
|
||||
# Import constant from
|
||||
# base package,
|
||||
# Import messages from
|
||||
# base package,
|
||||
# Import some functions
|
||||
# from utils file
|
||||
# Import account's serializer
|
||||
# Import account's task
|
||||
# Import notification constant
|
||||
# Import send_notification function
|
||||
from .serializers import (UserSerializer, CreateGuardianSerializer, TaskSerializer, TaskDetailsSerializer,
|
||||
TopJuniorSerializer, ApproveJuniorSerializer, ApproveTaskSerializer,
|
||||
GuardianDetailListSerializer)
|
||||
from .models import Guardian, JuniorTask
|
||||
from junior.models import Junior, JuniorPoints, JuniorGuardianRelationship
|
||||
from account.models import UserEmailOtp, UserNotification, UserDeviceDetails
|
||||
from .tasks import generate_otp
|
||||
from account.utils import custom_response, custom_error_response, send_otp_email, task_status_fun
|
||||
from base.messages import ERROR_CODE, SUCCESS_CODE
|
||||
from base.constants import NUMBER, GUARDIAN_CODE_STATUS, GUARDIAN
|
||||
from .utils import upload_image_to_alibaba
|
||||
from notifications.constants import REGISTRATION, TASK_ASSIGNED, ASSOCIATE_APPROVED, ASSOCIATE_REJECTED
|
||||
from notifications.utils import send_notification
|
||||
|
||||
""" Define APIs """
|
||||
# Define Signup API,
|
||||
# update guardian profile,
|
||||
# list of all task
|
||||
# list of task according to the status of the task
|
||||
# create task API
|
||||
# search task by name of the task API
|
||||
# top junior API,
|
||||
# approve junior API
|
||||
# approve task API
|
||||
# Create your views here.
|
||||
# create approve task API
|
||||
class SignupViewset(viewsets.ModelViewSet):
|
||||
"""Signup view set"""
|
||||
queryset = User.objects.all()
|
||||
serializer_class = UserSerializer
|
||||
http_method_names = ('post',)
|
||||
def create(self, request, *args, **kwargs):
|
||||
"""Create user profile"""
|
||||
device_id = request.META.get('HTTP_DEVICE_ID')
|
||||
if request.data['user_type'] in [str(NUMBER['one']), str(NUMBER['two'])]:
|
||||
serializer = UserSerializer(context=request.data['user_type'], data=request.data)
|
||||
if serializer.is_valid():
|
||||
user = serializer.save()
|
||||
"""Generate otp"""
|
||||
otp = generate_otp()
|
||||
# expire otp after 1 day
|
||||
expiry = timezone.now() + timezone.timedelta(days=1)
|
||||
# create user email otp object
|
||||
UserEmailOtp.objects.create(email=request.data['email'], otp=otp,
|
||||
user_type=str(request.data['user_type']), expired_at=expiry)
|
||||
"""Send email to the register user"""
|
||||
send_otp_email.delay(request.data['email'], otp)
|
||||
UserDeviceDetails.objects.create(user=user, device_id=device_id)
|
||||
return custom_response(SUCCESS_CODE['3001'],
|
||||
response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
else:
|
||||
return custom_error_response(ERROR_CODE['2028'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class UpdateGuardianProfile(viewsets.ModelViewSet):
|
||||
"""Update guardian profile"""
|
||||
serializer_class = CreateGuardianSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
http_method_names = ('post',)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
"""Create guardian profile"""
|
||||
try:
|
||||
data = request.data
|
||||
image = request.data.get('image')
|
||||
image_url = ''
|
||||
if image:
|
||||
if image and image.size == NUMBER['zero']:
|
||||
return custom_error_response(ERROR_CODE['2035'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
filename = f"images/{image.name}"
|
||||
# upload image on ali baba
|
||||
image_url = upload_image_to_alibaba(image, filename)
|
||||
data = {"image":image_url}
|
||||
serializer = CreateGuardianSerializer(context={"user":request.user,
|
||||
"first_name":request.data.get('first_name'),
|
||||
"last_name": request.data.get('last_name'),
|
||||
"image":image_url},
|
||||
data=data)
|
||||
if serializer.is_valid():
|
||||
"""save serializer"""
|
||||
serializer.save()
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class AllTaskListAPIView(viewsets.ModelViewSet):
|
||||
"""Update guardian profile"""
|
||||
serializer_class = TaskDetailsSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""Create guardian profile"""
|
||||
queryset = JuniorTask.objects.filter(guardian__user=request.user)
|
||||
# use TaskDetailsSerializer serializer
|
||||
serializer = TaskDetailsSerializer(queryset, many=True)
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
|
||||
|
||||
class TaskListAPIView(viewsets.ModelViewSet):
|
||||
"""Task list
|
||||
Params
|
||||
status
|
||||
search
|
||||
page
|
||||
junior"""
|
||||
serializer_class = TaskDetailsSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
filter_backends = (SearchFilter,)
|
||||
search_fields = ['task_name', ]
|
||||
pagination_class = PageNumberPagination
|
||||
http_method_names = ('get',)
|
||||
|
||||
def get_queryset(self):
|
||||
queryset = JuniorTask.objects.filter(guardian__user=self.request.user
|
||||
).select_related('junior', 'junior__auth'
|
||||
).order_by('-created_at')
|
||||
|
||||
queryset = self.filter_queryset(queryset)
|
||||
return queryset
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""Create guardian profile"""
|
||||
status_value = self.request.GET.get('status')
|
||||
junior = self.request.GET.get('junior')
|
||||
queryset = self.get_queryset()
|
||||
task_status = task_status_fun(status_value)
|
||||
if status_value:
|
||||
queryset = queryset.filter(task_status__in=task_status)
|
||||
if junior:
|
||||
queryset = queryset.filter(junior=int(junior))
|
||||
paginator = CustomPageNumberPagination()
|
||||
# use Pagination
|
||||
paginated_queryset = paginator.paginate_queryset(queryset, request)
|
||||
# use TaskDetailsSerializer serializer
|
||||
serializer = self.serializer_class(paginated_queryset, many=True)
|
||||
return paginator.get_paginated_response(serializer.data)
|
||||
|
||||
|
||||
class CreateTaskAPIView(viewsets.ModelViewSet):
|
||||
"""create task for junior"""
|
||||
serializer_class = TaskSerializer
|
||||
queryset = JuniorTask.objects.all()
|
||||
http_method_names = ('post', )
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
"""
|
||||
image should be in form data
|
||||
"""
|
||||
try:
|
||||
image = request.data['default_image']
|
||||
junior_ids = request.data['junior'].split(',')
|
||||
|
||||
invalid_junior_ids = [junior_id for junior_id in junior_ids if not junior_id.isnumeric()]
|
||||
if invalid_junior_ids:
|
||||
# At least one junior value is not an integer
|
||||
return custom_error_response(ERROR_CODE['2047'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
allowed_extensions = ['.jpg', '.jpeg', '.png']
|
||||
if not any(extension in str(image) for extension in allowed_extensions):
|
||||
return custom_error_response(ERROR_CODE['2048'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
if 'https' in str(image):
|
||||
image_data = image
|
||||
else:
|
||||
filename = f"images/{image}"
|
||||
if image and image.size == NUMBER['zero']:
|
||||
return custom_error_response(ERROR_CODE['2035'],
|
||||
response_status=status.HTTP_400_BAD_REQUEST)
|
||||
image_data = upload_image_to_alibaba(image, filename)
|
||||
request.data.pop('default_image')
|
||||
|
||||
guardian = Guardian.objects.filter(user=request.user).select_related('user').last()
|
||||
junior_data = Junior.objects.filter(id__in=junior_ids,
|
||||
guardian_code__contains=[guardian.guardian_code]
|
||||
).select_related('auth')
|
||||
if not junior_data:
|
||||
return custom_error_response(ERROR_CODE['2047'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
for junior in junior_data:
|
||||
index = junior.guardian_code.index(guardian.guardian_code)
|
||||
status_index = junior.guardian_code_status[index]
|
||||
if status_index == str(NUMBER['three']):
|
||||
return custom_error_response(ERROR_CODE['2078'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# use TaskSerializer serializer
|
||||
serializer = TaskSerializer(context={"guardian": guardian, "image": image_data,
|
||||
"junior_data": junior_data}, data=request.data)
|
||||
if serializer.is_valid():
|
||||
# save serializer
|
||||
serializer.save()
|
||||
# removed send notification method and used in serializer
|
||||
return custom_response(SUCCESS_CODE['3018'], response_status=status.HTTP_200_OK)
|
||||
return custom_error_response(serializer.errors, response_status=status.HTTP_400_BAD_REQUEST)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class SearchTaskListAPIView(viewsets.ModelViewSet):
|
||||
"""Filter task"""
|
||||
serializer_class = TaskDetailsSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
pagination_class = PageNumberPagination
|
||||
http_method_names = ('get',)
|
||||
|
||||
def get_queryset(self):
|
||||
"""Get the queryset for the view"""
|
||||
title = self.request.GET.get('title')
|
||||
# fetch junior query
|
||||
junior_queryset = JuniorTask.objects.filter(guardian__user=self.request.user, task_name__icontains=title)\
|
||||
.order_by('due_date', 'created_at')
|
||||
return junior_queryset
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""Filter task"""
|
||||
try:
|
||||
queryset = self.get_queryset()
|
||||
paginator = self.pagination_class()
|
||||
# use pagination
|
||||
paginated_queryset = paginator.paginate_queryset(queryset, request)
|
||||
# use TaskSerializer serializer
|
||||
serializer = TaskDetailsSerializer(paginated_queryset, many=True)
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class TopJuniorListAPIView(viewsets.ModelViewSet):
|
||||
"""Top juniors list
|
||||
No Params"""
|
||||
serializer_class = TopJuniorSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
http_method_names = ('get',)
|
||||
|
||||
def get_serializer_context(self):
|
||||
# context list
|
||||
context = super().get_serializer_context()
|
||||
context.update({'view': self})
|
||||
return context
|
||||
|
||||
def get_queryset(self):
|
||||
queryset = JuniorPoints.objects.filter(
|
||||
junior__is_verified=True
|
||||
).select_related(
|
||||
'junior', 'junior__auth'
|
||||
).annotate(rank=Window(
|
||||
expression=Rank(),
|
||||
order_by=[F('total_points').desc(), 'junior__created_at'])
|
||||
).order_by('-total_points', 'junior__created_at')
|
||||
return queryset
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
"""Fetch junior list of those who complete their tasks"""
|
||||
try:
|
||||
junior_total_points = self.get_queryset()[:15]
|
||||
serializer = self.get_serializer(junior_total_points, many=True)
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class ApproveJuniorAPIView(viewsets.ModelViewSet):
|
||||
"""approve junior by guardian"""
|
||||
serializer_class = ApproveJuniorSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
http_method_names = ('post',)
|
||||
|
||||
def create(self, request, *args, **kwargs):
|
||||
""" Use below param
|
||||
{"junior_id":"75",
|
||||
"action":"1"}
|
||||
"""
|
||||
try:
|
||||
relation_obj = JuniorGuardianRelationship.objects.filter(
|
||||
guardian__user__email=self.request.user,
|
||||
junior__id=self.request.data.get('junior_id')
|
||||
).select_related('guardian', 'junior').first()
|
||||
guardian = relation_obj.guardian
|
||||
# fetch junior query
|
||||
junior_queryset = relation_obj.junior
|
||||
if junior_queryset and (junior_queryset.is_deleted or not junior_queryset.is_active):
|
||||
return custom_error_response(ERROR_CODE['2073'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
# action 1 is use for approve and 2 for reject
|
||||
if request.data['action'] == '1':
|
||||
# use ApproveJuniorSerializer serializer
|
||||
serializer = ApproveJuniorSerializer(context={"guardian_code": guardian.guardian_code,
|
||||
"junior": junior_queryset,
|
||||
"action": request.data['action']},
|
||||
data=request.data)
|
||||
if serializer.is_valid():
|
||||
# save serializer
|
||||
serializer.save()
|
||||
send_notification.delay(ASSOCIATE_APPROVED, guardian.user_id, GUARDIAN,
|
||||
junior_queryset.auth_id, {})
|
||||
return custom_response(SUCCESS_CODE['3023'], serializer.data, response_status=status.HTTP_200_OK)
|
||||
else:
|
||||
if junior_queryset.guardian_code and ('-' in junior_queryset.guardian_code):
|
||||
junior_queryset.guardian_code.remove('-')
|
||||
if junior_queryset.guardian_code_status and ('-' in junior_queryset.guardian_code_status):
|
||||
junior_queryset.guardian_code_status.remove('-')
|
||||
index = junior_queryset.guardian_code.index(guardian.guardian_code)
|
||||
junior_queryset.guardian_code.remove(guardian.guardian_code)
|
||||
junior_queryset.guardian_code_status.pop(index)
|
||||
junior_queryset.save()
|
||||
send_notification.delay(ASSOCIATE_REJECTED, guardian.user_id, GUARDIAN, junior_queryset.auth_id, {})
|
||||
relation_obj.delete()
|
||||
return custom_response(SUCCESS_CODE['3024'], response_status=status.HTTP_200_OK)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
|
||||
class ApproveTaskAPIView(viewsets.ModelViewSet):
|
||||
"""approve junior by guardian"""
|
||||
serializer_class = ApproveTaskSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
http_method_names = ('post',)
|
||||
def create(self, request, *args, **kwargs):
|
||||
""" Params
|
||||
{"junior_id":"82",
|
||||
"task_id":"43",
|
||||
"action":"1"}
|
||||
action 1 for approve
|
||||
2 for reject
|
||||
"""
|
||||
# action 1 is use for approve and 2 for reject
|
||||
try:
|
||||
guardian = Guardian.objects.filter(user__email=self.request.user).last()
|
||||
# task query
|
||||
task_queryset = JuniorTask.objects.filter(id=self.request.data.get('task_id'),
|
||||
guardian=guardian,
|
||||
junior=self.request.data.get('junior_id')).last()
|
||||
if task_queryset and guardian.guardian_code not in task_queryset.junior.guardian_code:
|
||||
return custom_error_response(ERROR_CODE['2084'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
if task_queryset and (task_queryset.junior.is_deleted or not task_queryset.junior.is_active):
|
||||
return custom_error_response(ERROR_CODE['2072'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
# use ApproveJuniorSerializer serializer
|
||||
serializer = ApproveTaskSerializer(context={"guardian_code": guardian.guardian_code,
|
||||
"task_instance": task_queryset,
|
||||
"action": str(request.data['action']),
|
||||
"junior": self.request.data['junior_id']},
|
||||
data=request.data)
|
||||
unexpected_task_status = [str(NUMBER['five']), str(NUMBER['six'])]
|
||||
if (str(request.data['action']) == str(NUMBER['one']) and serializer.is_valid()
|
||||
and task_queryset and task_queryset.task_status not in unexpected_task_status):
|
||||
# save serializer
|
||||
serializer.save()
|
||||
return custom_response(SUCCESS_CODE['3025'], response_status=status.HTTP_200_OK)
|
||||
elif (str(request.data['action']) == str(NUMBER['two']) and serializer.is_valid()
|
||||
and task_queryset and task_queryset.task_status not in unexpected_task_status):
|
||||
# save serializer
|
||||
serializer.save()
|
||||
return custom_response(SUCCESS_CODE['3026'], response_status=status.HTTP_200_OK)
|
||||
else:
|
||||
return custom_error_response(ERROR_CODE['2038'], response_status=status.HTTP_400_BAD_REQUEST)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
||||
#
|
||||
class GuardianListAPIView(viewsets.ModelViewSet):
|
||||
"""Guardian list of assosicated junior"""
|
||||
|
||||
serializer_class = GuardianDetailListSerializer
|
||||
permission_classes = [IsAuthenticated]
|
||||
http_method_names = ('get',)
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
""" Guardian list of assosicated junior
|
||||
No Params"""
|
||||
try:
|
||||
guardian_data = JuniorGuardianRelationship.objects.filter(junior__auth__email=self.request.user)
|
||||
# fetch junior object
|
||||
if guardian_data:
|
||||
# use GuardianDetailListSerializer serializer
|
||||
serializer = GuardianDetailListSerializer(guardian_data, many=True)
|
||||
return custom_response(None, serializer.data, response_status=status.HTTP_200_OK)
|
||||
return custom_response({"status": GUARDIAN_CODE_STATUS[1][0]}, response_status=status.HTTP_200_OK)
|
||||
except Exception as e:
|
||||
return custom_error_response(str(e), response_status=status.HTTP_400_BAD_REQUEST)
|
0
junior/__init__.py
Normal file
0
junior/__init__.py
Normal file
52
junior/admin.py
Normal file
52
junior/admin.py
Normal file
@ -0,0 +1,52 @@
|
||||
"""Junior admin"""
|
||||
"""Third party Django app"""
|
||||
from django.contrib import admin
|
||||
"""Import Django app"""
|
||||
from .models import (Junior, JuniorPoints, JuniorGuardianRelationship, JuniorArticlePoints, JuniorArticle,
|
||||
JuniorArticleCard, FAQ)
|
||||
# Register your models here.
|
||||
admin.site.register(FAQ)
|
||||
@admin.register(JuniorArticle)
|
||||
class JuniorArticleAdmin(admin.ModelAdmin):
|
||||
"""Junior Admin"""
|
||||
list_display = ['junior', 'article', 'status', 'is_completed']
|
||||
|
||||
def __str__(self):
|
||||
"""Return email id"""
|
||||
return self.junior__auth__email
|
||||
|
||||
@admin.register(JuniorArticleCard)
|
||||
class JuniorArticleCardAdmin(admin.ModelAdmin):
|
||||
"""Junior Admin"""
|
||||
list_display = ['junior', 'article', 'article_card', 'is_read']
|
||||
|
||||
def __str__(self):
|
||||
"""Return email id"""
|
||||
return self.junior__auth__email
|
||||
@admin.register(Junior)
|
||||
class JuniorAdmin(admin.ModelAdmin):
|
||||
"""Junior Admin"""
|
||||
list_display = ['auth', 'guardian_code']
|
||||
|
||||
def __str__(self):
|
||||
"""Return email id"""
|
||||
return self.auth__email
|
||||
|
||||
@admin.register(JuniorPoints)
|
||||
class JuniorPointsAdmin(admin.ModelAdmin):
|
||||
"""Junior Points Admin"""
|
||||
list_display = ['junior', 'total_points', 'position']
|
||||
|
||||
def __str__(self):
|
||||
"""Return email id"""
|
||||
return self.junior.auth.email
|
||||
|
||||
@admin.register(JuniorGuardianRelationship)
|
||||
class JuniorGuardianRelationshipAdmin(admin.ModelAdmin):
|
||||
"""Junior Admin"""
|
||||
list_display = ['guardian', 'junior', 'relationship']
|
||||
|
||||
@admin.register(JuniorArticlePoints)
|
||||
class JuniorArticlePointsAdmin(admin.ModelAdmin):
|
||||
"""Junior Admin"""
|
||||
list_display = ['junior', 'article', 'question', 'submitted_answer', 'is_answer_correct']
|
8
junior/apps.py
Normal file
8
junior/apps.py
Normal file
@ -0,0 +1,8 @@
|
||||
"""App file"""
|
||||
"""Import AppConfig"""
|
||||
from django.apps import AppConfig
|
||||
|
||||
class JuniorConfig(AppConfig):
|
||||
"""Junior config"""
|
||||
default_auto_field = 'django.db.models.BigAutoField'
|
||||
name = 'junior'
|
42
junior/migrations/0001_initial.py
Normal file
42
junior/migrations/0001_initial.py
Normal file
@ -0,0 +1,42 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-23 12:05
|
||||
|
||||
from django.conf import settings
|
||||
import django.contrib.postgres.fields
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Junior',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('phone', models.CharField(blank=True, default=None, max_length=31, null=True)),
|
||||
('country_code', models.IntegerField(blank=True, null=True)),
|
||||
('gender', models.CharField(blank=True, choices=[('1', 'Male'), ('2', 'Female')], default=None, max_length=10, null=True)),
|
||||
('dob', models.DateField(blank=True, default=None, max_length=15, null=True)),
|
||||
('junior_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
||||
('guardian_code', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, default=None, max_length=10, null=True), null=True, size=None)),
|
||||
('referral_code', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
||||
('referral_code_used', models.CharField(blank=True, default=None, max_length=10, null=True)),
|
||||
('is_active', models.BooleanField(default=True)),
|
||||
('is_complete_profile', models.BooleanField(default=False)),
|
||||
('passcode', models.IntegerField(blank=True, default=None, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('auth', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='junior_profile', to=settings.AUTH_USER_MODEL, verbose_name='Email')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Junior',
|
||||
'db_table': 'junior',
|
||||
},
|
||||
),
|
||||
]
|
18
junior/migrations/0002_junior_country_name.py
Normal file
18
junior/migrations/0002_junior_country_name.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-27 13:59
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='junior',
|
||||
name='country_name',
|
||||
field=models.CharField(blank=True, default=None, max_length=30, null=True),
|
||||
),
|
||||
]
|
18
junior/migrations/0003_junior_image.py
Normal file
18
junior/migrations/0003_junior_image.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-28 10:16
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0002_junior_country_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='junior',
|
||||
name='image',
|
||||
field=models.ImageField(blank=True, default=None, null=True, upload_to='images/'),
|
||||
),
|
||||
]
|
18
junior/migrations/0004_alter_junior_image.py
Normal file
18
junior/migrations/0004_alter_junior_image.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-29 06:14
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0003_junior_image'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='junior',
|
||||
name='image',
|
||||
field=models.ImageField(blank=True, default=None, null=True, upload_to=''),
|
||||
),
|
||||
]
|
18
junior/migrations/0005_junior_is_verified.py
Normal file
18
junior/migrations/0005_junior_is_verified.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-29 12:10
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0004_alter_junior_image'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='junior',
|
||||
name='is_verified',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
18
junior/migrations/0006_alter_junior_country_name.py
Normal file
18
junior/migrations/0006_alter_junior_country_name.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-06-30 10:53
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0005_junior_is_verified'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='junior',
|
||||
name='country_name',
|
||||
field=models.CharField(blank=True, default=None, max_length=100, null=True),
|
||||
),
|
||||
]
|
18
junior/migrations/0007_alter_junior_image.py
Normal file
18
junior/migrations/0007_alter_junior_image.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-06 12:18
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0006_alter_junior_country_name'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterField(
|
||||
model_name='junior',
|
||||
name='image',
|
||||
field=models.URLField(blank=True, default=None, null=True),
|
||||
),
|
||||
]
|
28
junior/migrations/0008_juniorpoints.py
Normal file
28
junior/migrations/0008_juniorpoints.py
Normal file
@ -0,0 +1,28 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-09 12:40
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0007_alter_junior_image'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='JuniorPoints',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('total_task_points', models.IntegerField(blank=True, default=0, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('junior', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='junior_points', to='junior.junior')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Junior Task Points',
|
||||
'db_table': 'junior_task_points',
|
||||
},
|
||||
),
|
||||
]
|
18
junior/migrations/0009_juniorpoints_position.py
Normal file
18
junior/migrations/0009_juniorpoints_position.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-10 07:36
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0008_juniorpoints'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='juniorpoints',
|
||||
name='position',
|
||||
field=models.IntegerField(blank=True, default=99999, null=True),
|
||||
),
|
||||
]
|
18
junior/migrations/0010_junior_signup_method.py
Normal file
18
junior/migrations/0010_junior_signup_method.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-11 11:26
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0009_juniorpoints_position'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='junior',
|
||||
name='signup_method',
|
||||
field=models.CharField(choices=[('1', 'manual'), ('2', 'google'), ('3', 'apple')], default='1', max_length=31),
|
||||
),
|
||||
]
|
18
junior/migrations/0011_junior_relationship.py
Normal file
18
junior/migrations/0011_junior_relationship.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-12 06:52
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0010_junior_signup_method'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='junior',
|
||||
name='relationship',
|
||||
field=models.CharField(blank=True, choices=[('1', 'parent'), ('2', 'legal_guardian')], default='1', max_length=31, null=True),
|
||||
),
|
||||
]
|
18
junior/migrations/0012_junior_is_invited.py
Normal file
18
junior/migrations/0012_junior_is_invited.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-12 10:51
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0011_junior_relationship'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='junior',
|
||||
name='is_invited',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
@ -0,0 +1,21 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-14 09:34
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0012_junior_is_invited'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='junior',
|
||||
options={'verbose_name': 'Junior', 'verbose_name_plural': 'Junior'},
|
||||
),
|
||||
migrations.AlterModelOptions(
|
||||
name='juniorpoints',
|
||||
options={'verbose_name': 'Junior Task Points', 'verbose_name_plural': 'Junior Task Points'},
|
||||
),
|
||||
]
|
18
junior/migrations/0014_junior_is_password_set.py
Normal file
18
junior/migrations/0014_junior_is_password_set.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-18 09:28
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0013_alter_junior_options_alter_juniorpoints_options'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='junior',
|
||||
name='is_password_set',
|
||||
field=models.BooleanField(default=True),
|
||||
),
|
||||
]
|
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-19 09:40
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0014_junior_is_password_set'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RenameField(
|
||||
model_name='juniorpoints',
|
||||
old_name='total_task_points',
|
||||
new_name='total_points',
|
||||
),
|
||||
]
|
18
junior/migrations/0016_juniorpoints_referral_points.py
Normal file
18
junior/migrations/0016_juniorpoints_referral_points.py
Normal file
@ -0,0 +1,18 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-19 11:00
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0015_rename_total_task_points_juniorpoints_total_points'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name='juniorpoints',
|
||||
name='referral_points',
|
||||
field=models.IntegerField(blank=True, default=0, null=True),
|
||||
),
|
||||
]
|
31
junior/migrations/0017_juniorguardianrelationship.py
Normal file
31
junior/migrations/0017_juniorguardianrelationship.py
Normal file
@ -0,0 +1,31 @@
|
||||
# Generated by Django 4.2.2 on 2023-07-25 07:44
|
||||
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('guardian', '0020_alter_juniortask_task_status'),
|
||||
('junior', '0016_juniorpoints_referral_points'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='JuniorGuardianRelationship',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('relationship', models.CharField(blank=True, choices=[('1', 'parent'), ('2', 'legal_guardian')], default='1', max_length=31, null=True)),
|
||||
('created_at', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_at', models.DateTimeField(auto_now=True)),
|
||||
('guardian', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='guardian_relation', to='guardian.guardian', verbose_name='Guardian')),
|
||||
('junior', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='junior_relation', to='junior.junior', verbose_name='Junior')),
|
||||
],
|
||||
options={
|
||||
'verbose_name': 'Junior Guardian Relation',
|
||||
'verbose_name_plural': 'Junior Guardian Relation',
|
||||
'db_table': 'junior_guardian_relation',
|
||||
},
|
||||
),
|
||||
]
|
@ -0,0 +1,22 @@
|
||||
# Generated by Django 4.2.2 on 2023-08-02 11:27
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('junior', '0017_juniorguardianrelationship'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RemoveField(
|
||||
model_name='junior',
|
||||
name='relationship',
|
||||
),
|
||||
migrations.AddField(
|
||||
model_name='junior',
|
||||
name='guardian_code_approved',
|
||||
field=models.BooleanField(default=False),
|
||||
),
|
||||
]
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user