-
Notifications
You must be signed in to change notification settings - Fork 2
/
myspace_api.py
3021 lines (2360 loc) · 143 KB
/
myspace_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# MANIFEST MY SPACE (PROPERTY MANAGEMENT) BACKEND PYTHON FILE
# https://l0h6a9zi1e.execute-api.us-west-1.amazonaws.com/dev/<enter_endpoint_details>
# To run program: python3 myspace_api.py
# README: if conn error make sure password is set properly in RDS PASSWORD section
# README: Debug Mode may need to be set to False when deploying live (although it seems to be working through Zappa)
# README: if there are errors, make sure you have all requirements are loaded
# pip3 install -r requirements.txt
# SECTION 1: IMPORT FILES AND FUNCTIONS
from dashboard import Dashboard
from appliances import Appliances #, RemoveAppliance
from rents import Rents, RentDetails, RentTest
from payments import NewPayments, PaymentMethod
from properties import Properties
# from cashflow import CashflowByOwner
# from cashflow import Cashflow, CashflowSimplified, HappinessMatrix, CashflowSummary, CashflowRevised,
from cashflow import PaymentVerification, CashflowTransactions
from employees import Employee, EmployeeVerification
from profiles import Profile, BusinessProfile #, BusinessProfileList
# from documents import OwnerDocuments, TenantDocuments
from documents import Documents
from leases import LeaseDetails, LeaseApplication, LeaseReferal
from purchases import Bills, AddExpense, AddRevenue, AddPurchase # , RentPurchase
from maintenance import MaintenanceStatus, MaintenanceRequests, MaintenanceQuotes, MaintenanceQuotesByUid
# from cron import PeriodicPurchases_CLASS # , ExtendLease, MonthlyRentPurchase_CLASS, MonthlyRentPurchase_CRON, LateFees_CLASS, LateFees_CRON
# from cron import MonthlyRent_CLASS
from contacts import Contacts
from contracts import Contracts
from settings import Account
from lists import List
from listings import Listings
from managers import SearchManager
from status_update import StatusUpdate
from utilities import Utilities
from users import UserInfo
from password import Password
from data_pm import connect, uploadImage, s3
from queries import NextDueDate, UnpaidRents, ApprovedContracts
# from jwtToken import JwtToken
from functools import wraps
import jwt
from test_api import endPointTest_CLASS
from extract_api import Extract_API, CleanUpDatabase
# from flask import Request
import os
import boto3
import json
import pytz
# import time
# import sys
# import pymysql
# import requests
# import stripe
# import urllib.request
# import base64
# import math
# import string
# import random
# import hashlib
# import binascii
# import csv
# import re # regex
import calendar
from dotenv import load_dotenv
# from datetime import datetime as dt
# from datetime import timezone as dtz
# from datetime import datetime, date, timedelta
from datetime import datetime, date, timedelta, timezone
from flask import Flask, request, render_template, url_for, redirect, jsonify, abort
from flask_restful import Resource, Api
from flask_cors import CORS
from flask_mail import Mail, Message # used for email
from flask_jwt_extended import JWTManager, verify_jwt_in_request, get_jwt_identity, jwt_required, create_access_token
from pytz import timezone as ptz # Not sure what the difference is
from decimal import Decimal
from hashlib import sha512
from twilio.rest import Client
from oauth2client import GOOGLE_REVOKE_URI, GOOGLE_TOKEN_URI, client
# from google_auth_oauthlib.flow import InstalledAppFlow
from urllib.parse import urlparse
from io import BytesIO
from dateutil.relativedelta import relativedelta
from dateutil.relativedelta import *
from math import ceil
from werkzeug.exceptions import BadRequest, NotFound
from werkzeug.datastructures import FileStorage # For file handling
from werkzeug.datastructures import ImmutableMultiDict
# used for serializer email and error handling
from itsdangerous import URLSafeTimedSerializer, SignatureExpired, BadTimeSignature
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives.padding import PKCS7
from cryptography.hazmat.backends import default_backend
import json
import base64
# == Using Cryptography library for AES encryption ==
# AES_KEY = b'IO95120secretkey' # 16 bytes
# BLOCK_SIZE = 16 # AES block size
# load_dotenv()
AES_SECRET_KEY = os.getenv('AES_SECRET_KEY')
# print("AES Secret Key: ", AES_SECRET_KEY)
AES_KEY = AES_SECRET_KEY.encode('utf-8')
BLOCK_SIZE = int(os.getenv('BLOCK_SIZE'))
# print("Block Size: ", BLOCK_SIZE)
POSTMAN_SECRET = os.getenv('POSTMAN_SECRET')
# print("POSTMAN_SECRET: ", POSTMAN_SECRET)
# Encrypt dictionary
def encrypt_dict(data_dict):
try:
print("In encrypt_dict: ", data_dict)
# Convert dictionary to JSON string
json_data = json.dumps(data_dict).encode()
# Pad the JSON data
padder = PKCS7(BLOCK_SIZE * 8).padder()
padded_data = padder.update(json_data) + padder.finalize()
# Generate a random initialization vector (IV)
iv = os.urandom(BLOCK_SIZE)
# Create a new AES cipher
cipher = Cipher(algorithms.AES(AES_KEY), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
# Encrypt the padded data
encrypted_data = encryptor.update(padded_data) + encryptor.finalize()
# Combine IV and encrypted data, then Base64 encode
encrypted_blob = base64.b64encode(iv + encrypted_data).decode()
return encrypted_blob
except Exception as e:
print(f"Encryption error: {e}")
return None
# Decrypt dictionary
def decrypt_dict(encrypted_blob):
print("Actual decryption started")
try:
# Base64 decode the encrypted blob
encrypted_data = base64.b64decode(encrypted_blob)
# Extract the IV (first BLOCK_SIZE bytes) and the encrypted content
iv = encrypted_data[:BLOCK_SIZE]
encrypted_content = encrypted_data[BLOCK_SIZE:]
# Create a new AES cipher
cipher = Cipher(algorithms.AES(AES_KEY), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
# Decrypt the encrypted content
decrypted_padded_data = decryptor.update(encrypted_content) + decryptor.finalize()
# Unpad the decrypted content
unpadder = PKCS7(BLOCK_SIZE * 8).unpadder()
decrypted_data = unpadder.update(decrypted_padded_data) + unpadder.finalize()
# Convert the JSON string back to a dictionary
return json.loads(decrypted_data.decode())
except Exception as e:
print(f"Decryption error: {e}")
return None
# NEED to figure out where the NotFound or InternalServerError is displayed
# from werkzeug.exceptions import BadRequest, InternalServerError
# NEED TO SOLVE THIS
# from NotificationHub import Notification
# from NotificationHub import NotificationHub
# BING API KEY
# Import Bing API key into bing_api_key.py
# NEED TO SOLVE THIS
# from env_keys import BING_API_KEY, RDS_PW
# from env_file import RDS_PW, S3_BUCKET, S3_KEY, S3_SECRET_ACCESS_KEY
s3 = boto3.client('s3')
app = Flask(__name__)
api = Api(app)
# load_dotenv()
CORS(app)
# CORS(app, resources={r'/api/*': {'origins': '*'}})
# Set this to false when deploying to live application
app.config['DEBUG'] = True
# Setup the Flask-JWT-Extended extension
app.config["JWT_SECRET_KEY"] = os.getenv('JWT_SECRET_KEY')
app.config['JWT_TOKEN_LOCATION'] = ['headers']
app.config['JWT_HEADER_NAME'] = 'Authorization'
app.config['JWT_HEADER_TYPE'] = 'Bearer'
jwtManager = JWTManager(app)
# SECTION 2: UTILITIES AND SUPPORT FUNCTIONS
ENDPOINT = "https://l0h6a9zi1e.execute-api.us-west-1.amazonaws.com/dev"
# --------------- Google Scopes and Credentials------------------
# SCOPES = "https://www.googleapis.com/auth/calendar"
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
# CLIENT_SECRET_FILE = "credentials.json"
# APPLICATION_NAME = "nitya-ayurveda"
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg'])
s = URLSafeTimedSerializer('thisisaverysecretkey')
# --------------- Stripe Variables ------------------
# STRIPE KEYS
stripe_public_test_key = os.getenv("stripe_public_test_key")
stripe_secret_test_key = os.getenv("stripe_secret_test_key")
stripe_public_live_key = os.getenv("stripe_public_live_key")
stripe_secret_live_key = os.getenv("stripe_secret_live_key")
# --------------- Twilio Setting ------------------
# Twilio's settings
# from twilio.rest import Client
TWILIO_ACCOUNT_SID = os.getenv('TWILIO_ACCOUNT_SID')
TWILIO_AUTH_TOKEN = os.getenv('TWILIO_AUTH_TOKEN')
# --------------- Mail Variables ------------------
# Mail username and password loaded in .env file
app.config['MAIL_USERNAME'] = os.getenv('SUPPORT_EMAIL')
app.config['MAIL_PASSWORD'] = os.getenv('SUPPORT_PASSWORD')
app.config['MAIL_DEFAULT_SENDER'] = os.getenv('MAIL_DEFAULT_SENDER')
# print("Sender: ", app.config['MAIL_DEFAULT_SENDER'])
# Setting for mydomain.com
app.config["MAIL_SERVER"] = "smtp.mydomain.com"
app.config["MAIL_PORT"] = 465
# Setting for gmail
# app.config['MAIL_SERVER'] = 'smtp.gmail.com'
# app.config['MAIL_PORT'] = 465
app.config["MAIL_USE_TLS"] = False
app.config["MAIL_USE_SSL"] = True
# Set this to false when deploying to live application
app.config["DEBUG"] = True
# app.config["DEBUG"] = False
# MAIL -- This statement has to be below the Mail Variables
mail = Mail(app)
# --------------- Time Variables ------------------
# convert to UTC time zone when testing in local time zone
utc = pytz.utc
# # These statment return Day and Time in GMT
# def getToday(): return datetime.strftime(datetime.now(utc), "%Y-%m-%d")
# def getNow(): return datetime.strftime(datetime.now(utc), "%Y-%m-%d %H:%M:%S")
# # These statment return Day and Time in Local Time - Not sure about PST vs PDT
def getToday():
return datetime.strftime(datetime.now(), "%Y-%m-%d")
def getNow():
return datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
# NOTIFICATIONS - NEED TO INCLUDE NOTIFICATION HUB FILE IN SAME DIRECTORY
# from NotificationHub import AzureNotification
# from NotificationHub import AzureNotificationHub
# from NotificationHub import Notification
# from NotificationHub import NotificationHub
# For Push notification
# isDebug = False
# NOTIFICATION_HUB_KEY = os.environ.get('NOTIFICATION_HUB_KEY')
# NOTIFICATION_HUB_NAME = os.environ.get('NOTIFICATION_HUB_NAME')
# NOTIFICATION_HUB_NAME = os.environ.get('NOTIFICATION_HUB_NAME'
# -- Send Email Endpoints start here -------------------------------------------------------------------------------
def sendEmail(recipient, subject, body):
with app.app_context():
# print("In sendEmail: ", recipient, subject, body)
sender="[email protected]"
# print("sender: ", sender)
msg = Message(
sender=sender,
recipients=[recipient],
subject=subject,
body=body
)
# print("sender: ", sender)
# print("Email message: ", msg)
mail.send(msg)
# print("email sent")
# app.sendEmail = sendEmail
class SendEmail(Resource):
def post(self):
payload = request.get_json()
print(payload)
# Check if each field in the payload is not null
if all(field is not None for field in payload.values()):
sendEmail(payload["receiver"], payload["email_subject"], payload["email_body"])
return "Email Sent"
else:
return "Some fields are missing in the payload", 400
class SendEmail_CLASS(Resource):
def get(self):
print("In Send EMail CRON get")
try:
conn = connect()
recipient = "[email protected]"
subject = "MySpace CRON Jobs Completed"
body = "The Following CRON Jobs Ran:"
# mail.send(msg)
sendEmail(recipient, subject, body)
return "Email Sent", 200
except:
raise BadRequest("Request failed, please try again later.")
finally:
print("exit SendEmail")
def SendEmail_CRON(self):
print("In Send EMail CRON get")
try:
conn = connect()
recipient = "[email protected]"
subject = "MySpace CRON Jobs Completed"
body = "The Following CRON Jobs Ran:"
# mail.send(msg)
sendEmail(recipient, subject, body)
return "Email Sent", 200
except:
raise BadRequest("Request failed, please try again later.")
finally:
print("exit SendEmail")
def Send_Twilio_SMS(message, phone_number):
# print("In Twilio: ", message, phone_number)
items = {}
numbers = phone_number
message = message
numbers = list(set(numbers.split(',')))
# print("TWILIO_ACCOUNT_SID: ", TWILIO_ACCOUNT_SID)
# print("TWILIO_AUTH_TOKEN: ", TWILIO_AUTH_TOKEN)
client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
# print("Client Info: ", client)
for destination in numbers:
message = client.messages.create(
body=message,
from_='+19254815757',
to="+1" + destination
)
items['code'] = 200
items['Message'] = 'SMS sent successfully to the recipient'
return items
class Announcements(Resource):
def get(self, user_id):
print("In Announcements GET")
response = {}
with connect() as db:
# if user_id.startswith("600-"):
sentQuery = db.execute("""
SELECT
a.*,
COALESCE(b.business_name, c.owner_first_name, d.tenant_first_name) AS receiver_first_name,
COALESCE(c.owner_last_name, d.tenant_last_name) AS receiver_last_name,
COALESCE(b.business_phone_number, c.owner_phone_number, d.tenant_phone_number) AS receiver_phone_number,
COALESCE(b.business_photo_url, c.owner_photo_url, d.tenant_photo_url) AS receiver_photo_url
, CASE
WHEN a.announcement_receiver LIKE '600%' THEN 'Business'
WHEN a.announcement_receiver LIKE '350%' THEN 'Tenant'
WHEN a.announcement_receiver LIKE '110%' THEN 'Owner'
ELSE 'Unknown'
END AS receiver_role
FROM space.announcements a
LEFT JOIN space.businessProfileInfo b ON a.announcement_receiver LIKE '600%' AND b.business_uid = a.announcement_receiver
LEFT JOIN space.ownerProfileInfo c ON a.announcement_receiver LIKE '110%' AND c.owner_uid = a.announcement_receiver
LEFT JOIN space.tenantProfileInfo d ON a.announcement_receiver LIKE '350%' AND d.tenant_uid = a.announcement_receiver
WHERE announcement_sender = \'""" + user_id + """\';
""")
response["sent"] = sentQuery
receivedQuery = db.execute("""
SELECT
a.*,
COALESCE(b.business_name, c.owner_first_name, d.tenant_first_name) AS sender_first_name,
COALESCE(c.owner_last_name, d.tenant_last_name) AS sender_last_name,
COALESCE(b.business_phone_number, c.owner_phone_number, d.tenant_phone_number) AS sender_phone_number,
COALESCE(b.business_photo_url, c.owner_photo_url, d.tenant_photo_url) AS sender_photo_url
, CASE
WHEN a.announcement_sender LIKE '600%' THEN 'Business'
WHEN a.announcement_sender LIKE '350%' THEN 'Tenant'
WHEN a.announcement_sender LIKE '110%' THEN 'Owner'
ELSE 'Unknown'
END AS sender_role
FROM
space.announcements a
LEFT JOIN
space.businessProfileInfo b ON a.announcement_sender LIKE '600%' AND b.business_uid = a.announcement_sender
LEFT JOIN
space.ownerProfileInfo c ON a.announcement_sender LIKE '110%' AND c.owner_uid = a.announcement_sender
LEFT JOIN
space.tenantProfileInfo d ON a.announcement_sender LIKE '350%' AND d.tenant_uid = a.announcement_sender
WHERE
announcement_receiver = \'""" + user_id + """\';
""")
response["received"] = receivedQuery
# else:
# response = db.execute("""
# -- Find the user details
# SELECT *
# FROM space.announcements AS a
# WHERE a.announcement_receiver = \'""" + user_id + """\'
# AND a.App = '1'
# ORDER BY a.announcement_date DESC;
# """)
return response
def post(self, user_id):
print("In Announcements POST ", user_id)
response = {}
payload = request.get_json()
print("Post Announcement Payload: ", payload)
manager_id = user_id
# print("Manager ID: ", manager_id)
if isinstance(payload["announcement_receiver"], list):
receivers = payload["announcement_receiver"]
else:
receivers = [payload["announcement_receiver"]]
# print("Receivers: ", receivers)
if isinstance(payload["announcement_properties"], list):
properties = payload["announcement_properties"]
else:
properties = [payload["announcement_properties"]]
# print("Properties: ", properties)
receiverPropertiesMap = {}
for propertyString in properties:
propertyObj = json.loads(propertyString)
# print("Property: ", propertyObj)
for key, value in propertyObj.items():
receiverPropertiesMap[key] = value
with connect() as db:
for i in range(len(receivers)):
newRequest = {}
newRequest['announcement_title'] = payload["announcement_title"]
newRequest['announcement_msg'] = payload["announcement_msg"]
newRequest['announcement_sender'] = manager_id
newRequest['announcement_mode'] = payload["announcement_mode"]
newRequest['announcement_properties'] = json.dumps(receiverPropertiesMap.get(receivers[i], []))
newRequest['announcement_receiver'] = receivers[i]
# Get the current date and time
current_datetime = datetime.now().strftime("%m-%d-%Y %H:%M:%S")
# Insert or update the "announcement_read" key with the current date and time
newRequest['announcement_date'] = current_datetime
# print("Announcement Date: ", newRequest['announcement_date'])
# Get Receiver email
user_query = None
if(receivers[i][:3] == '350'):
user_query = db.execute("""
-- Find the user details
SELECT tenant_email as email, tenant_phone_number as phone_number, notifications
FROM space.tenantProfileInfo AS t
LEFT JOIN space.users ON tenant_user_id = user_uid
-- WHERE t.tenant_uid = '350-000005';
WHERE t.tenant_uid = \'""" + receivers[i] + """\';
""")
elif(receivers[i][:3] == '110'):
user_query = db.execute("""
-- Find the user details
SELECT owner_email as email, owner_phone_number as phone_number, notifications
FROM space.ownerProfileInfo AS o
LEFT JOIN space.users ON owner_user_id = user_uid
-- WHERE o.owner_uid = '110-000005';
WHERE o.owner_uid = \'""" + receivers[i] + """\';
""")
elif(receivers[i][:3] == '600'):
user_query = db.execute("""
-- Find the user details
SELECT business_email as email, business_phone_number as phone_number, notifications
FROM space.businessProfileInfo AS b
LEFT JOIN space.users ON business_user_id = user_uid
-- WHERE b.business_uid = '600-000005';
WHERE b.business_uid = \'""" + receivers[i] + """\';
""")
# print("Notifications allowed: ", user_query['result'][0]['notifications'], type( user_query['result'][0]['notifications']))
for j in range(len(payload["announcement_type"])):
# print("Announcement Type: ", payload["announcement_type"][j])
if payload["announcement_type"][j] == "Email":
newRequest['Email'] = "1"
user_email = user_query['result'][0]['email']
sendEmail(user_email, payload["announcement_title"], payload["announcement_msg"])
response["email"] = "email sent"
print("Before Text: ", payload["announcement_type"][j], user_query['result'][0]['notifications'])
if payload["announcement_type"][j] == "Text":
if user_query['result'][0]['notifications'] == 'true':
print("sending Text")
# continue
newRequest['Text'] = "1"
user_phone = user_query['result'][0]['phone_number']
msg = payload["announcement_title"]+"\n" + payload["announcement_msg"]
# print("Before Twilio Call: ", msg, user_phone)
try:
Send_Twilio_SMS(msg, user_phone)
response["text"] = "Text Sent"
except:
print("Phone Number may not be valid")
response["text"] = "Phone Number may not be valid"
else:
response["text"] = "text notifications turned off"
# if payload["announcement_type"][j] == "App":
# newRequest['App'] = "1"
newRequest['App'] = "1"
response["App"] = db.insert('announcements', newRequest)
return response
def put(self):
print("In Announcements PUT")
response = {}
payload = request.get_json()
print("Announcement Payload: ", payload, type(payload))
if 'announcement_uid' in payload and payload['announcement_uid']:
# payload.get('announcement_uid')
# Get the current date and time
current_datetime = datetime.now().strftime("%m-%d-%Y %H:%M:%S")
# Insert or update the "announcement_read" key with the current date and time
payload['announcement_read'] = current_datetime
i = 0
for each in payload['announcement_uid']:
if each in {None, '', 'null'}:
print("No announcement_uid")
# raise BadRequest("Request failed, no UID in payload.")
response["bad data"] = "TRUE"
else:
print("current uid: ", each)
key = {'announcement_uid': each}
print("Annoucement Key: ", key)
with connect() as db:
response = db.update('announcements', key, payload)
i = i + 1
response["rows affected"] = i
else:
response['msg'] = 'No UID in payload'
return response
class LeaseExpiringNotify(Resource):
def get(self):
with connect() as db:
response = db.execute("""
SELECT *
FROM space.leases l
LEFT JOIN space.t_details t ON t.lt_lease_id = l.lease_uid
LEFT JOIN space.b_details b ON b.contract_property_id = l.lease_property_id
LEFT JOIN space.properties p ON p.property_uid = l.lease_property_id
WHERE l.lease_end = DATE_FORMAT(DATE_ADD(NOW(), INTERVAL 2 MONTH), "%Y-%m-%d")
AND l.lease_status='ACTIVE'
AND b.contract_status='ACTIVE'; """)
print(response)
if len(response['result']) > 0:
for i in range(len(response['result'])):
name = response['result'][i]['tenant_first_name'] + \
' ' + response['result'][i]['tenant_last_name']
address = response['result'][i]["tenant_address"] + \
' ' + response['result'][i]["tenant_unit"] + ", " + response['result'][i]["tenant_city"] + \
', ' + response['result'][i]["tenant_state"] + \
' ' + response['result'][i]["tenant_zip"]
start_date = response['result'][i]['lease_start']
end_date = response['result'][i]['lease_end']
business_name = response['result'][i]['business_name']
phone = response['result'][i]['business_phone_number']
email = response['result'][i]['business_email']
recipient = response['result'][i]['tenant_email']
subject = "Lease ending soon..."
body = (
"Hello " + str(name) + "," + "\n"
"\n"
"Property: " + str(address) + "\n"
"This is your 2 month reminder, that your lease is ending. \n"
"Here are your lease details: \n"
"Start Date: " +
str(start_date) + "\n"
"End Date: " +
str(end_date) + "\n"
"Please contact your Property Manager if you wish to renew or end your lease before the time of expiry. \n"
"\n"
"Name: " + str(business_name) + "\n"
"Phone: " + str(phone) + "\n"
"Email: " + str(email) + "\n"
"\n"
"Thank you - Team Property Management\n\n"
)
sendEmail(recipient, subject, body)
print('sending')
return response
# -- Stored Procedures start here -------------------------------------------------------------------------------
# RUN STORED PROCEDURES
# def get_new_billUID(conn):
# newBillQuery = execute("CALL space.new_bill_uid;", "get", conn)
# if newBillQuery["code"] == 280:
# return newBillQuery["result"][0]["new_id"]
# return "Could not generate new bill UID", 500
# def get_new_purchaseUID(conn):
# newPurchaseQuery = execute("CALL space.new_purchase_uid;", "get", conn)
# if newPurchaseQuery["code"] == 280:
# return newPurchaseQuery["result"][0]["new_id"]
# return "Could not generate new bill UID", 500
# def get_new_propertyUID(conn):
# newPropertyQuery = execute("CALL space.new_property_uid;", "get", conn)
# if newPropertyQuery["code"] == 280:
# return newPropertyQuery["result"][0]["new_id"]
# return "Could not generate new property UID", 500
# -- SPACE Queries start here -------------------------------------------------------------------------------
class stripe_key(Resource):
def get(self, desc):
print(desc)
if desc == "PMTEST":
return {"publicKey": stripe_public_test_key}
else:
return {"publicKey": stripe_public_live_key}
# -- SPACE CRON ENDPOINTS start here -------------------------------------------------------------------------------
# -- CURRENT CRON JOB
class Lease_CLASS(Resource):
def get(self):
print("In Lease CRON JOB")
# Establish current day, month and year
dt = date.today()
leasesMadeInactive = 0
leasesMadeActive = 0
leasesM2M = 0
leasesExpired = 0
CronPostings = ["Lease Affected:"]
response = {}
try:
# Run query to find all APPROVED Contracts
with connect() as db:
lease_query = db.execute("""
SELECT *
FROM space.leases
WHERE lease_status = "APPROVED"
AND STR_TO_DATE(lease_start, '%m-%d-%Y') <= CURDATE();
""")
approved_leases = lease_query['result']
# print("\nApproved Contracts: ", approved_leases)
for lease in approved_leases:
# print("Lease: ", lease)
# print("Lease Property ID: ", lease['lease_property_id'])
# See if there is a matching ACTIVE contract for the same property and make that contract INACTIVE
active_lease = ("""
UPDATE space.leases
SET lease_status = 'INACTIVE'
WHERE lease_property_id = \'""" + lease['lease_property_id'] + """\'
AND lease_status = 'ACTIVE';
""")
# print("active_lease Query: ", active_lease)
response['old_lease'] = db.execute(active_lease, cmd='post')
# print(response['old_lease']['change'])
leasesMadeInactive = leasesMadeInactive + 1
# print("Leases Made Inactive: ", leasesMadeInactive)
# Make the Approved contract Active
new_lease = ("""
UPDATE space.leases
SET lease_status = 'ACTIVE'
WHERE lease_property_id = \'""" + lease['lease_property_id'] + """\'
AND lease_status = 'APPROVED';
""")
# print("new_lease Query: ", new_lease)
response['new_lease'] = db.execute(new_lease, cmd='post')
# print(response['new_lease']['change'])
leasesMadeActive = leasesMadeActive + 1
# print("Leases Made Active: ", leasesMadeActive)
CronPostings.append(f"{lease['lease_property_id']} ")
# print("Lease Cron Query Complete")
response['Leases_Made_Inactive'] = leasesMadeInactive
response['Leases_Made_Aactive'] = leasesMadeActive
# print("This is the Function response: ", response)
# Run query to find all EXPIRED Contracts
lease_query = db.execute("""
SELECT *
FROM space.leases
WHERE STR_TO_DATE(lease_end, '%m-%d-%Y') <= CURDATE()
AND lease_status = "ACTIVE" ;
""")
expired_leases = lease_query['result']
# print("\nExpired Leases: ", expired_leases)
for lease in expired_leases:
if lease["lease_m2m"] == "1":
m2m_lease = ("""
UPDATE space.leases
SET lease_status = 'ACTIVE M2M'
WHERE lease_uid = \'""" + lease['lease_uid'] + """\'
""")
# print("new_lease Query: ", new_lease)
response['new_lease'] = db.execute(m2m_lease, cmd='post')
leasesM2M = leasesM2M + 1
else:
expired_lease = ("""
UPDATE space.leases
SET lease_status = 'EXPIRED'
WHERE lease_uid = \'""" + lease['lease_uid'] + """\'
""")
# print("new_lease Query: ", new_lease)
response['expired'] = db.execute(expired_lease, cmd='post')
leasesExpired = leasesExpired + 1
response['Leases_Made_M2M'] = leasesM2M
response['Leases_Expired'] = leasesExpired
# APPEND TO CRON OUTPUT
CronPostings.append(
f"""
response['Leases_Made_Inactive'] = {leasesMadeInactive}
response['Leases_Made_Active'] = {leasesMadeActive}
response['Leases_Made_M2M'] = {leasesM2M}
response['Leases_Expired'] = {leasesExpired}
"""
)
try:
# print(CronPostings)
recipient = "[email protected]"
subject = f"MySpace LEASE CRON JOB for {dt} Completed "
body = f"LEASE CRON JOB has been executed.\n\n" + "\n".join(CronPostings)
# mail.send(msg)
sendEmail(recipient, subject, body)
response["email"] = {'message': f'LEASE CRON Job Email for {dt} sent!' ,
'code': 200}
except:
response["email fail"] = {'message': f'LEASE CRON Job Email for {dt} could not be sent' ,
'code': 500}
except:
response["cron fail"] = {'message': f'LEASE CRON Job failed for {dt}' ,
'code': 500}
try:
recipient = "[email protected]"
subject = "MySpace LEASE CRON JOB Failed!"
body = "LEASE CRON JOB Failed"
# mail.send(msg)
sendEmail(recipient, subject, body)
response["email"] = {'message': f'LEASE CRON Job Fail Email for {dt} sent!' ,
'code': 201}
except:
response["email fail"] = {'message': f'LEASE CRON Job Fail Email for {dt} could not be sent' ,
'code': 500}
return response
def Lease_CRON(Resource):
print("In Lease CRON JOB")
# Establish current day, month and year
dt = date.today()
leasesMadeInactive = 0
leasesMadeActive = 0
leasesM2M = 0
leasesExpired = 0
CronPostings = ["Lease Affected:"]
response = {}
try:
# Run query to find all APPROVED Contracts
with connect() as db:
lease_query = db.execute("""
SELECT *
FROM space.leases
WHERE lease_status = "APPROVED"
AND STR_TO_DATE(lease_start, '%m-%d-%Y') <= CURDATE();
""")
approved_leases = lease_query['result']
# print("\nApproved Contracts: ", approved_leases)
for lease in approved_leases:
# print("Lease: ", lease)
# print("Lease Property ID: ", lease['lease_property_id'])
# See if there is a matching ACTIVE contract for the same property and make that contract INACTIVE
active_lease = ("""
UPDATE space.leases
SET lease_status = 'INACTIVE'
WHERE lease_property_id = \'""" + lease['lease_property_id'] + """\'
AND lease_status = 'ACTIVE';
""")
# print("active_lease Query: ", active_lease)
response['old_lease'] = db.execute(active_lease, cmd='post')
# print(response['old_lease']['change'])
leasesMadeInactive = leasesMadeInactive + 1
# print("Leases Made Inactive: ", leasesMadeInactive)
# Make the Approved contract Active
new_lease = ("""
UPDATE space.leases
SET lease_status = 'ACTIVE'
WHERE lease_property_id = \'""" + lease['lease_property_id'] + """\'
AND lease_status = 'APPROVED';
""")
# print("new_lease Query: ", new_lease)
response['new_lease'] = db.execute(new_lease, cmd='post')
# print(response['new_lease']['change'])
leasesMadeActive = leasesMadeActive + 1
# print("Leases Made Active: ", leasesMadeActive)
CronPostings.append(f"{lease['lease_property_id']} ")
# print("Lease Cron Query Complete")
response['Leases_Made_Inactive'] = leasesMadeInactive
response['Leases_Made_Aactive'] = leasesMadeActive
# print("This is the Function response: ", response)
# Run query to find all EXPIRED Contracts
lease_query = db.execute("""
SELECT *
FROM space.leases
WHERE STR_TO_DATE(lease_end, '%m-%d-%Y') <= CURDATE()
AND lease_status = "ACTIVE" ;
""")
expired_leases = lease_query['result']
# print("\nExpired Leases: ", expired_leases)
for lease in expired_leases:
if lease["lease_m2m"] == "1":
m2m_lease = ("""
UPDATE space.leases
SET lease_status = 'ACTIVE M2M'
WHERE lease_uid = \'""" + lease['lease_uid'] + """\'
""")
# print("new_lease Query: ", new_lease)
response['new_lease'] = db.execute(m2m_lease, cmd='post')
leasesM2M = leasesM2M + 1
else:
expired_lease = ("""
UPDATE space.leases
SET lease_status = 'EXPIRED'
WHERE lease_uid = \'""" + lease['lease_uid'] + """\'
""")
# print("new_lease Query: ", new_lease)
response['expired'] = db.execute(expired_lease, cmd='post')
leasesExpired = leasesExpired + 1
response['Leases_Made_M2M'] = leasesM2M
response['Leases_Expired'] = leasesExpired
# APPEND TO CRON OUTPUT
CronPostings.append(
f"""
response['Leases_Made_Inactive'] = {leasesMadeInactive}
response['Leases_Made_Active'] = {leasesMadeActive}
response['Leases_Made_M2M'] = {leasesM2M}
response['Leases_Expired'] = {leasesExpired}
"""
)
try:
# print(CronPostings)
recipient = "[email protected]"
subject = f"MySpace LEASE CRON JOB for {dt} Completed "
body = f"LEASE CRON JOB has been executed.\n\n" + "\n".join(CronPostings)
# mail.send(msg)
sendEmail(recipient, subject, body)
response["email"] = {'message': f'LEASE CRON Job Email for {dt} sent!' ,
'code': 200}
except:
response["email fail"] = {'message': f'LEASE CRON Job Email for {dt} could not be sent' ,
'code': 500}
except:
response["cron fail"] = {'message': f'LEASE CRON Job failed for {dt}' ,
'code': 500}
try:
recipient = "[email protected]"
subject = "MySpace LEASE CRON JOB Failed!"
body = "LEASE CRON JOB Failed"