-
Notifications
You must be signed in to change notification settings - Fork 0
/
mmu_api.py
1866 lines (1494 loc) · 98.9 KB
/
mmu_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
# MEET ME UP BACKEND PYTHON FILE
# https://41c664jpz1.execute-api.us-west-1.amazonaws.com/dev/<enter_endpoint_details>
# To run program: python3 mmu_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
# import eventlet
# eventlet.monkey_patch()
# SECTION 1: IMPORT FILES AND FUNCTIONS
# from users import UserInfo
from lists import List
from user import UserInfo
from matches import Match
from meet import Meet
from likes import Likes
from messages import Messages, get_conversation_id
from data import connect, disconnect
from announcements import Announcements
from s3 import uploadImage, s3
import os
import boto3
# import json
# import time
# import sys
import pymysql
# import requests
import pytz
# import stripe
# import urllib.request
# import base64
# import math
# import string
# import random
# import hashlib
# import binascii
# import csv
# import re # regex
from dotenv import load_dotenv
# from datetime import datetime as dt
# from datetime import timezone as dtz
from datetime import datetime, date, timedelta
from flask import Flask, request, render_template, url_for, redirect
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
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 flask_socketio import SocketIO, emit, join_room, leave_room
# used for serializer email and error handling
from itsdangerous import URLSafeTimedSerializer, SignatureExpired, BadTimeSignature
# 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__)
# socketio = SocketIO(app, cors_allowed_origins="*")
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
# SECTION 2: UTILITIES AND SUPPORT FUNCTIONS
# --------------- 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):
items = {}
numbers = phone_number
message = message
numbers = list(set(numbers.split(',')))
client = Client(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN)
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")
# payload = request.get_json()
# # print("Post Announcement Payload: ", payload)
# manager_id = user_id
# if isinstance(payload["announcement_receiver"], list):
# receivers = payload["announcement_receiver"]
# else:
# receivers = [payload["announcement_receiver"]]
# if isinstance(payload["announcement_properties"], list):
# properties = payload["announcement_properties"]
# else:
# properties = [payload["announcement_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'])
# 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
# FROM space.tenantProfileInfo AS t
# 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
# FROM space.ownerProfileInfo AS o
# 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
# FROM space.businessProfileInfo AS b
# WHERE b.business_uid = \'""" + receivers[i] + """\';
# """)
# for j in range(len(payload["announcement_type"])):
# 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"])
# if payload["announcement_type"][j] == "Text":
# continue
# newRequest['Text'] = "1"
# user_phone = user_query['result'][0]['phone_number']
# msg = payload["announcement_title"]+"\n" + payload["announcement_msg"]
# Send_Twilio_SMS(msg, user_phone)
# # if payload["announcement_type"][j] == "App":
# # newRequest['App'] = "1"
# newRequest['App'] = "1"
# response = db.insert('announcements', newRequest)
# return response
# def put(self):
# print("In Announcements PUT")
# response = {}
# payload = request.get_json()
# if payload.get('announcement_uid') in {None, '', 'null'}:
# print("No announcement_uid")
# raise BadRequest("Request failed, no UID in payload.")
# # print("Announcement Payload: ", payload)
# # 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']:
# # 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
# 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
# -- MMU 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 -------------------------------------------------------------------------------
# class MonthlyRentPurchase_CLASS(Resource):
# def get(self):
# print("In Monthly Rent CRON JOB")
# numCronPurchases = 0
# # Establish current month and year
# dt = datetime.today()
# try:
# # Run query to find rents of ACTIVE leases
# with connect() as db:
# response = db.execute("""
# -- CALCULATE RECURRING FEES
# SELECT leaseFees.*
# , lease_tenant.*
# , property_owner_id, po_owner_percent
# , contract_uid, contract_business_id, contract_status, contract_fees
# , lease_property_id, lease_start, lease_end, lease_status, lease_early_end_date, lease_renew_status
# -- , lease_assigned_contacts, lease_documents, lease_early_end_date, lease_renew_status, lease_move_in_date, move_out_date, lease_adults, lease_children, lease_pets, lease_vehicles, lease_referred, lease_effective_date, lease_docuSign, lease_consent, lease_actual_rent, lease_end_notice_period, lease_end_reason
# FROM space.leaseFees
# LEFT JOIN space.leases ON fees_lease_id = lease_uid
# LEFT JOIN space.lease_tenant ON fees_lease_id = lt_lease_id
# LEFT JOIN space.property_owner ON lease_property_id = property_id
# LEFT JOIN space.contracts ON lease_property_id = contract_property_id
# WHERE frequency != 'One-time' AND !ISNULL(frequency) AND frequency != ""
# AND lease_status IN ('ACTIVE', 'ACTIVE MTM', 'APPROVED')
# AND contract_status = 'ACTIVE'
# ORDER BY leaseFees_uid -- frequency;
# """)
# for i in range(len(response['result'])):
# # print("\n",i, response['result'][i]['leaseFees_uid'], response['result'][i]['fees_lease_id'], response['result'][i]['lease_property_id'], response['result'][i]['contract_uid'], response['result'][i]['contract_business_id'])
# # Check Frequecy of Rent Payment. Currently query only returns MONTHLY leases
# # rentFrequency = response['result'][i]['frequency']
# # print(response['result'][i]['frequency'])
# # if rentFrequency == "Weekly":
# # print("Weekly Rent Fee")
# # elif rentFrequency == "Anually":
# # print("Annual Rent Fee")
# # elif rentFrequency == "Monthly" or rentFrequency is None:
# # print("Monthly Rent Fee")
# # else: print("Investigate")
# # Check if available_topay is NONE
# if response['result'][i]['available_topay'] is None:
# # print("available_topay Is NULL!!")
# payable = 10
# else:
# payable = response['result'][i]['available_topay']
# # print("available_topay: ", payable)
# # Check if due_by is NONE
# # print(response['result'][i]['due_by'])
# if response['result'][i]['due_by'] is None or response['result'][i]['due_by'] == 0:
# # print("due_by Is NULL!!")
# due_by = 1
# else:
# due_by = response['result'][i]['due_by']
# # print("due_by: ", due_by, type(due_by)) # Day rent is due ie 2
# # print("dt.day: ", dt.day, type(dt.day)) # Todays Day ie 8/3/2024 would return 3
# # Calculate Actual Rent due date
# # due_by < dt.day means that due_by date has already pasted so look towards next month.
# # example: 2 < 3 means rent was already due on the second. Look to rent due next month on the 2nd
# if due_by < dt.day: # Due date has already passed. Look to next month
# # print(due_by, " < ", dt.day)
# due_date = datetime(dt.year, dt.month, due_by) + relativedelta(months=1)
# else:
# due_date = datetime(dt.year, dt.month, due_by) # Current month Due date has NOT passed. Calculate this months rent
# # print("due date: ", due_date, type(due_date)) # Prints Date of Next Rent Due: 2024-09-02
# pm_due_date = due_date + relativedelta(days=10)
# # print("PM due date: ", pm_due_date, type(pm_due_date)) # Prints Date of Next PM to Owner Payment : 2024-09-12
# # Calculate number of days until rent is due
# if response['result'][i]['frequency'] == 'Monthly':
# # print(due_date, dt)
# days_for_rent = (due_date.date() - dt.date()).days
# # print("Rent due in : ", days_for_rent, " days", type(days_for_rent))
# # print("Rent Posts in: ", days_for_rent - payable , " days", type(payable))
# elif response['result'][i]['frequency'] == 'Weekly':
# # print("Weekly")
# days_for_rent = 500
# elif response['result'][i]['frequency'] == 'Bi-Weekly':
# # print("Bi-Weekly")
# days_for_rent = 500
# elif response['result'][i]['frequency'] == 'Annually':
# # print("Annually ", response['result'][i]['due_by_date'], type(response['result'][i]['due_by_date']) )
# days_for_rent = 500
# # CHECK IF RENT IS AVAILABLE TO PAY ==> IF IT IS, ADD PURCHASES FOR TENANT TO PM AND PM TO OWNER
# print(i, response['result'][i]['leaseFees_uid'], response['result'][i]['fees_lease_id'], response['result'][i]['lease_property_id'], "Rent Due: ", due_date.date(), "Rent Posts: ", due_date.date() - timedelta(days=payable), " days_for_rent: ", days_for_rent, " payable: ", payable, " Rent posts in: ", days_for_rent - payable)
# if days_for_rent == payable + (0): # Remove/Change number to get query to run and return data
# # IF Changing the dates manually
# # if days_for_rent >= 0: # Remove/Change number to get query to run and return data
# # due_date = datetime(2024, 1, due_by) # Comment this out since due_date is set above
# # pm_due_date = due_date + relativedelta(days=10) # Comment this out since due_date is set above
# print("Rent posted. Please Pay")
# numCronPurchases = numCronPurchases + 1
# # print(i, response['result'][i])
# # Perform Remainder Checks to ensure no blank fields
# # Check if late_fee is NONE
# # print(response['result'][i]['fee_name'], response['result'][i]['late_fee'], type(response['result'][i]['late_fee']))
# if response['result'][i]['late_fee'] is None or response['result'][i]['late_fee'] == 0 or response['result'][i]['late_fee'] == "":
# # print("Is NULL!!")
# late_fee = 0
# else:
# late_fee = response['result'][i]['late_fee']
# # print("late_fee: ", late_fee, type(late_fee))
# # Check if perDay_late_fee is NONE
# # print(response['result'][i]['perDay_late_fee'])
# if response['result'][i]['perDay_late_fee'] is None or response['result'][i]['perDay_late_fee'] == 0:
# # print("Is NULL!!")
# perDay_late_fee = 0
# else:
# perDay_late_fee = response['result'][i]['perDay_late_fee']
# # print("perDay_late_fee: ", perDay_late_fee, type(perDay_late_fee))
# # Check if late_by is NONE
# # print(response['result'][i]['late_by'])
# if response['result'][i]['late_by'] is None or response['result'][i]['late_by'] == 0:
# # print("Is NULL!!")
# late_by = 1
# else:
# late_by = response['result'][i]['late_by']
# # print("late_by: ", late_by, type(late_by))
# # Check if tenant responsiblity is NONE
# # print("What is in the db: ", response['result'][i]['lt_responsibility'])
# if response['result'][i]['lt_responsibility'] is None:
# # print("Is NULL!!")
# responsible_percent = 1.0
# else:
# responsible_percent = response['result'][i]['lt_responsibility']
# # print("What we set programmatically: ", responsible_percent, type(responsible_percent))
# charge = response['result'][i]['charge']
# # print("Charge: ", charge, type(charge))
# amt_due = float(charge) * responsible_percent
# # print("Amount due: ", amt_due)
# # Establish payer, initiator and receiver
# contract_uid = response['result'][i]['contract_uid']
# property = response['result'][i]['lease_property_id']
# tenant = response['result'][i]['lt_tenant_id']
# owner = response['result'][i]['property_owner_id']
# manager = response['result'][i]['contract_business_id']
# fee_name = response['result'][i]['fee_name']
# # print("Purchase Parameters: ", i, contract_uid, tenant, owner, manager)
# # Common JSON Object Attributes
# newRequest = {}
# newRequest['pur_timestamp'] = datetime.today().date().strftime("%m-%d-%Y")
# newRequest['pur_property_id'] = property
# newRequest['purchase_type'] = "Rent"
# newRequest['pur_cf_type'] = "revenue"
# newRequest['pur_amount_due'] = amt_due
# newRequest['purchase_status'] = "UNPAID"
# newRequest['pur_status_value'] = "0"
# newRequest['pur_notes'] = fee_name
# newRequest['pur_due_by'] = due_by
# newRequest['pur_late_by'] = late_by
# newRequest['pur_late_fee'] = late_fee
# newRequest['pur_perDay_late_fee'] = perDay_late_fee
# newRequest['purchase_date'] = datetime.today().date().strftime("%m-%d-%Y")
# newRequest['pur_description'] = f"Rent for {due_date.strftime('%B')} {due_date.year} CRON"
# # Create JSON Object for Rent Purchase for Tenant-PM Payment
# newRequestID = db.call('new_purchase_uid')['result'][0]['new_id']
# grouping = newRequestID
# newRequest['purchase_uid'] = newRequestID
# newRequest['pur_group'] = grouping
# # print(newRequestID)
# newRequest['pur_receiver'] = manager
# newRequest['pur_payer'] = tenant
# newRequest['pur_initiator'] = manager
# newRequest['pur_due_date'] = due_date.date().strftime("%m-%d-%Y")
# # print(newRequest)
# # print("Purchase Parameters: ", i, newRequestID, property, contract_uid, tenant, owner, manager)
# db.insert('purchases', newRequest)
# # Create JSON Object for Rent Purchase for PM-Owner Payment
# newRequestID = db.call('new_purchase_uid')['result'][0]['new_id']
# newRequest['purchase_uid'] = newRequestID
# # print(newRequestID)
# newRequest['pur_receiver'] = owner
# newRequest['pur_payer'] = manager
# newRequest['pur_initiator'] = manager
# newRequest['pur_due_date'] = pm_due_date.date().strftime("%m-%d-%Y")
# newRequest['pur_group'] = grouping
# # print(newRequest)
# # print("Purchase Parameters: ", i, newRequestID, property, contract_uid, tenant, owner, manager)
# db.insert('purchases', newRequest)
# # For each entry posted to the purchases table, post any contract fees based on Rent
# # Find contract fees based rent
# manager_fees = db.execute("""
# SELECT -- *
# contract_uid, contract_property_id, contract_business_id
# -- , contract_start_date, contract_end_date
# , contract_fees
# -- , contract_assigned_contacts, contract_documents, contract_name, contract_status, contract_early_end_date
# , jt.*
# FROM
# space.contracts,
# JSON_TABLE(
# contract_fees,
# "$[*]" COLUMNS (
# of_column VARCHAR(50) PATH "$.of",
# charge_column VARCHAR(50) PATH "$.charge",
# fee_name_column VARCHAR(50) PATH "$.fee_name",
# fee_type_column VARCHAR(10) PATH "$.fee_type",
# frequency_column VARCHAR(20) PATH "$.frequency"
# )
# ) AS jt
# -- WHERE contract_uid = '010-000003' AND of_column LIKE '%rent%';
# WHERE contract_uid = \'""" + contract_uid + """\' AND of_column LIKE '%rent%';
# """)
# # print(manager_fees)
# for j in range(len(manager_fees['result'])):
# # Check if fees is monthly
# if manager_fees['result'][j]['frequency_column'] == 'Monthly' or manager_fees['result'][j]['frequency_column'] == 'monthly':
# # Check if charge is a % or Fixed $ Amount
# if manager_fees['result'][j]['fee_type_column'] == '%' or manager_fees['result'][j]['fee_type_column'] == 'PERCENT':
# charge_amt = Decimal(manager_fees['result'][j]['charge_column']) * Decimal(amt_due) / 100
# else:
# charge_amt = Decimal(manager_fees['result'][j]['charge_column'])
# # print("Charge Amount: ", charge_amt, property, contract_uid, manager_fees['result'][j]['charge_column'], response['result'][i]['charge'] )
# # Create JSON Object for Fee Purchase
# newPMRequest = {}
# newPMRequestID = db.call('new_purchase_uid')['result'][0]['new_id']
# # print(newPMRequestID)
# newPMRequest['purchase_uid'] = newPMRequestID
# newPMRequest['pur_timestamp'] = datetime.today().date().strftime("%m-%d-%Y")
# newPMRequest['pur_property_id'] = property
# newPMRequest['purchase_type'] = "Management"
# newPMRequest['pur_cf_type'] = "expense"
# newPMRequest['pur_amount_due'] = charge_amt
# newPMRequest['purchase_status'] = "UNPAID"
# newPMRequest['pur_status_value'] = "0"
# newPMRequest['pur_notes'] = manager_fees['result'][j]['fee_name_column']
# newPMRequest['pur_description'] = f"{manager_fees['result'][j]['fee_name_column']} for {due_date.strftime('%B')} {due_date.year} "
# # newPMRequest['pur_description'] = newRequestID # Original Rent Purchase ID
# # newPMRequest['pur_description'] = f"Fees for MARCH {nextMonth.year} CRON"
# newPMRequest['pur_receiver'] = manager
# newPMRequest['pur_payer'] = owner
# newPMRequest['pur_initiator'] = manager
# newPMRequest['purchase_date'] = datetime.today().date().strftime("%m-%d-%Y")
# newPMRequest['pur_group'] = grouping
# # *********
# newPMRequest['pur_due_date'] = due_date.date().strftime("%m-%d-%Y")
# # newPMRequest['pur_due_date'] = datetime(nextMonth.year, nextMonth.month, due_by).date().strftime("%m-%d-%Y")
# # newPMRequest['pur_due_date'] = datetime(nextMonth.year, 1, due_by).date().strftime("%m-%d-%Y")
# # print(newPMRequest)
# print("Number of CRON Purchases: ", numCronPurchases, dt)
# db.insert('purchases', newPMRequest)
# # For each fee, post to purchases table
# response["cron_job"] = {'message': f'Successfully completed CRON Job for {dt}' ,
# 'rows affected': f'{numCronPurchases}',
# 'code': 200}
# try:
# recipient = "[email protected]"
# subject = "MySpace Monthly Rent CRON JOB Completed "
# body = "Monthly Rent CRON JOB"
# # mail.send(msg)
# sendEmail(recipient, subject, body)
# response["email"] = {'message': f'CRON Job Email for {dt} sent!' ,
# 'code': 500}
# except:
# response["email fail"] = {'message': f'CRON Job Email for {dt} could not be sent' ,
# 'code': 500}
# except:
# response["cron fail"] = {'message': f'CRON Job failed for {dt}' ,
# 'code': 500}
# try:
# recipient = "[email protected]"
# subject = "MySpace Monthly Rent CRON JOB Failed!"
# body = "Monthly Rent CRON JOB Failed"
# # mail.send(msg)
# sendEmail(recipient, subject, body)
# response["email"] = {'message': f'CRON Job Fail Email for {dt} sent!' ,
# 'code': 500}
# except:
# response["email fail"] = {'message': f'CRON Job Fail Email for {dt} could not be sent' ,
# 'code': 500}
# return response
# def MonthlyRentPurchase_CRON(self):
# print("In Monthly Rent CRON JOB")
# numCronPurchases = 0
# # Establish current month and year
# dt = datetime.today()
# try:
# # Run query to find rents of ACTIVE leases
# with connect() as db:
# response = db.execute("""
# -- CALCULATE RECURRING FEES
# SELECT leaseFees.*
# , lease_tenant.*
# , property_owner_id, po_owner_percent
# , contract_uid, contract_business_id, contract_status, contract_fees
# , lease_property_id, lease_start, lease_end, lease_status, lease_early_end_date, lease_renew_status
# -- , lease_assigned_contacts, lease_documents, lease_early_end_date, lease_renew_status, lease_move_in_date, move_out_date, lease_adults, lease_children, lease_pets, lease_vehicles, lease_referred, lease_effective_date, lease_docuSign, lease_consent, lease_actual_rent, lease_end_notice_period, lease_end_reason
# FROM space.leaseFees
# LEFT JOIN space.leases ON fees_lease_id = lease_uid
# LEFT JOIN space.lease_tenant ON fees_lease_id = lt_lease_id
# LEFT JOIN space.property_owner ON lease_property_id = property_id
# LEFT JOIN space.contracts ON lease_property_id = contract_property_id
# WHERE frequency != 'One-time' AND !ISNULL(frequency) AND frequency != ""
# AND lease_status IN ('ACTIVE', 'ACTIVE MTM', 'APPROVED')
# AND contract_status = 'ACTIVE'
# ORDER BY leaseFees_uid -- frequency;
# """)
# for i in range(len(response['result'])):
# # print("\n",i, response['result'][i]['leaseFees_uid'], response['result'][i]['fees_lease_id'], response['result'][i]['lease_property_id'], response['result'][i]['contract_uid'], response['result'][i]['contract_business_id'])
# # Check Frequecy of Rent Payment. Currently query only returns MONTHLY leases
# # rentFrequency = response['result'][i]['frequency']
# # print(response['result'][i]['frequency'])
# # if rentFrequency == "Weekly":
# # print("Weekly Rent Fee")
# # elif rentFrequency == "Anually":
# # print("Annual Rent Fee")
# # elif rentFrequency == "Monthly" or rentFrequency is None:
# # print("Monthly Rent Fee")
# # else: print("Investigate")
# # Check if available_topay is NONE
# if response['result'][i]['available_topay'] is None:
# # print("available_topay Is NULL!!")
# payable = 10
# else:
# payable = response['result'][i]['available_topay']
# # print("available_topay: ", payable)
# # Check if due_by is NONE
# # print(response['result'][i]['due_by'])
# if response['result'][i]['due_by'] is None or response['result'][i]['due_by'] == 0:
# # print("due_by Is NULL!!")
# due_by = 1
# else:
# due_by = response['result'][i]['due_by']
# # print("due_by: ", due_by, type(due_by)) # Day rent is due ie 2
# # print("dt.day: ", dt.day, type(dt.day)) # Todays Day ie 8/3/2024 would return 3
# # Calculate Actual Rent due date
# # due_by < dt.day means that due_by date has already pasted so look towards next month.
# # example: 2 < 3 means rent was already due on the second. Look to rent due next month on the 2nd
# if due_by < dt.day: # Due date has already passed. Look to next month
# # print(due_by, " < ", dt.day)
# due_date = datetime(dt.year, dt.month, due_by) + relativedelta(months=1)
# else:
# due_date = datetime(dt.year, dt.month, due_by) # Current month Due date has NOT passed. Calculate this months rent
# # print("due date: ", due_date, type(due_date)) # Prints Date of Next Rent Due: 2024-09-02
# pm_due_date = due_date + relativedelta(days=10)
# # print("PM due date: ", pm_due_date, type(pm_due_date)) # Prints Date of Next PM to Owner Payment : 2024-09-12
# # Calculate number of days until rent is due
# if response['result'][i]['frequency'] == 'Monthly':
# # print(due_date, dt)
# days_for_rent = (due_date.date() - dt.date()).days
# # print("Rent due in : ", days_for_rent, " days", type(days_for_rent))
# # print("Rent Posts in: ", days_for_rent - payable , " days", type(payable))
# elif response['result'][i]['frequency'] == 'Weekly':
# # print("Weekly")
# days_for_rent = 500
# elif response['result'][i]['frequency'] == 'Bi-Weekly':
# # print("Bi-Weekly")
# days_for_rent = 500
# elif response['result'][i]['frequency'] == 'Annually':
# # print("Annually ", response['result'][i]['due_by_date'], type(response['result'][i]['due_by_date']) )
# days_for_rent = 500
# # CHECK IF RENT IS AVAILABLE TO PAY ==> IF IT IS, ADD PURCHASES FOR TENANT TO PM AND PM TO OWNER
# print(i, response['result'][i]['leaseFees_uid'], response['result'][i]['fees_lease_id'], response['result'][i]['lease_property_id'], "Rent Due: ", due_date.date(), "Rent Posts: ", due_date.date() - timedelta(days=payable), " days_for_rent: ", days_for_rent, " payable: ", payable, " Rent posts in: ", days_for_rent - payable)
# if days_for_rent == payable + (0): # Remove/Change number to get query to run and return data
# # IF Changing the dates manually
# # if days_for_rent >= 0: # Remove/Change number to get query to run and return data
# # due_date = datetime(2024, 1, due_by) # Comment this out since due_date is set above
# # pm_due_date = due_date + relativedelta(days=10) # Comment this out since due_date is set above