Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update user accounts and new ifxbilling #319

Merged
merged 3 commits into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,21 @@
function () { productUsagesTable.ajax.reload() }
)
})
$("#updateUserAccounts").click((ev) => {
ev.preventDefault()
$.ajax({
url: '/ifx/api/update-user-accounts/',
method: 'POST',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: '',
dataType: "json",
error: function (jqXHR, status, error) {
alert(status + ' ' + error)
},
}).success(
alert('Update started. You will receive an email when the update is complete.')
)
})
})
})(jQuery)

Expand All @@ -130,6 +145,12 @@
<input id="productUsageReload" type="submit" value="Reload Data"></input>
</div>
<div style="position: relative; float: right;">
<div style="position: relative; float: left">
<form method="post">
{% csrf_token %}
<input id="updateUserAccounts" style="color: white; background-color: red;" type="submit" value="Update User Accounts"></input>
</form>
</div>
<div style="position: relative; float: left">
<label for="recalculate">Recalculate</label>
<input type="checkbox" id="recalculate" name="recalculate" value="false"/>
Expand Down
3 changes: 2 additions & 1 deletion coldfront/plugins/ifx/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from ifxbilling.views import unauthorized as unauthorized_api
from ifxuser.views import get_org_names
from coldfront.plugins.ifx.viewsets import ColdfrontBillingRecordViewSet, ColdfrontReportRunViewSet, ColdfrontProductUsageViewSet
from coldfront.plugins.ifx.views import get_billing_record_list, unauthorized, report_runs, run_report, calculate_billing_month, billing_month, get_product_usages, billing_records, send_billing_record_review_notification
from coldfront.plugins.ifx.views import update_user_accounts_view, get_billing_record_list, unauthorized, report_runs, run_report, calculate_billing_month, billing_month, get_product_usages, billing_records, send_billing_record_review_notification

router = routers.DefaultRouter()
router.register(r'billing-records', ColdfrontBillingRecordViewSet, 'billing-record')
Expand All @@ -18,6 +18,7 @@
path('api/get-org-names/', get_org_names, name='get-org-names'),
path('api/get-product-usages/', get_product_usages, name='get-product-usages'),
path('api/send-billing-record-review-notification/<int:year>/<int:month>/', send_billing_record_review_notification, name='send-billing-record-review-notification'),
path('api/update-user-accounts/', update_user_accounts_view, name='update-user-accounts'),
path('api/', include(router.urls)),
path('unauthorized/', unauthorized, name='unauthorized'),
path('report-runs/', report_runs, name='report-runs'),
Expand Down
77 changes: 74 additions & 3 deletions coldfront/plugins/ifx/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,22 @@
import json
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth import get_user_model
from django.utils import timezone
from django.db import connection
from django.conf import settings
from django.core.exceptions import PermissionDenied
from rest_framework.decorators import api_view, permission_classes
from django_q.tasks import async_task
from rest_framework.decorators import api_view, permission_classes, authentication_classes
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import SessionAuthentication, BasicAuthentication, TokenAuthentication
from ifxreport.views import run_report as ifxreport_run_report
from ifxbilling import models as ifxbilling_models
from ifxbilling.calculator import getClassFromName
from ifxbilling.views import get_billing_record_list as ifxbilling_get_billing_record_list
from ifxbilling.fiine import update_user_accounts
from ifxmail.client import send
from ifxuser import models as ifxuser_models
from coldfront.plugins.ifx.calculator import NewColdfrontBillingCalculator
from coldfront.plugins.ifx.permissions import AdminPermissions
Expand Down Expand Up @@ -76,14 +81,15 @@ def billing_records(request):
raise PermissionDenied
return render(request, 'plugins/ifx/billing_records.html')

@login_required
@api_view(['GET',])
@authentication_classes([TokenAuthentication, SessionAuthentication, BasicAuthentication])
def get_billing_record_list(request):
'''
Get billing record list
'''
if not request.user.is_superuser:
raise PermissionDenied
return ifxbilling_get_billing_record_list(request)
return ifxbilling_get_billing_record_list(request._request)

@login_required
@api_view(['POST',])
Expand Down Expand Up @@ -252,3 +258,68 @@ def send_billing_record_review_notification(request, year, month):
except Exception as e:
logger.exception(e)
return Response(data={ 'error': f'Billing record summary failed {str(e)}' }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

def update_user_accounts_and_notify(user_queryset, email):
'''
Update user accounts and notify the user by sending an email with ifxmail.client send()
'''
successes = 0
errors = []

for user in user_queryset:
try:
update_user_accounts(user)
successes += 1
except Exception as e:
logger.exception(e)
errors.append(f'Error updating {user}: {e}')


fromstr = 'rchelp@rc.fas.harvard.edu'
tostr = email
message = f'{successes} user accounts updated successfully.'
if errors:
errorstr = '\n'.join(errors)
message += f'Errors: {errorstr}'
subject = "Update of user accounts"

try:
send(
to=tostr,
fromaddr=fromstr,
message=message,
subject=subject
)
except Exception as e:
logger.exception(e)
raise Exception(f'Error sending email to {tostr} from {fromstr} with message {message} and subject {subject}: {e}.') from e
print('User accounts updated and email sent to %s', tostr)


@api_view(('POST',))
def update_user_accounts_view(request):
'''
Take a list of ifxids and update data from fiine. Body should be of the form:
{
'ifxids': [
'IFXID0001',
'IFXID0002',
]
}
If no data is specified, all accounts will be updated
'''
logger.error('Updating user accounts in view')
data = request.data

if not data.keys():
queryset = get_user_model().objects.filter(ifxid__isnull=False)
else:
queryset = get_user_model().objects.filter(ifxid__in=data['ifxids'])

async_task(
'coldfront.plugins.ifx.views.update_user_accounts_and_notify',
queryset,
request.user.email
)

return Response('OK')
2 changes: 1 addition & 1 deletion fiine.client
2 changes: 1 addition & 1 deletion ifxbilling
2 changes: 1 addition & 1 deletion ifxec
Submodule ifxec updated from 3d472b to 677e37
Loading