# views.py import os from django.http import HttpResponse, JsonResponse, Http404 import subprocess, sys, os from django.views.decorators.csrf import csrf_exempt from django.conf import settings import re from datetime import datetime from openpyxl import load_workbook media_dir = os.path.join(os.path.dirname(__file__), 'media') @csrf_exempt def get_screenshot(request): if request.method == 'POST': import json data = json.loads(request.body or '{}') site = data.get('site') site_urls = { "walmart": "https://www.walmart.com/", "amazon": "https://www.amazon.com/", "target": "https://www.target.com/", "bestbuy": "https://www.bestbuy.com/" } print("site", site) if site not in site_urls: return JsonResponse({'error': 'Invalid site'}, status=400) url = site_urls[site] print("Url", url) base_dir = r"C:\Users\Abhyuday.Andugula\Work Space\CA\competitor_analysis\media" result = subprocess.run( [sys.executable, "-m", "CA_Analysis.capture", url], cwd=base_dir ) print("processed") print("result:", str(result)) full_img = os.path.join(settings.MEDIA_ROOT, site, 'fullpage.png') if os.path.exists(full_img): image_url = settings.MEDIA_URL + f'{site}/fullpage.png' best_seller_img1 = settings.MEDIA_URL + f'{site}/best_sellers_section_1.png' best_seller_img2 = settings.MEDIA_URL + f'{site}/best_sellers_section_2.png' carousel_img1 = settings.MEDIA_URL + f'{site}/carosal_img_1.jpg' carousel_img2 = settings.MEDIA_URL + f'{site}/carosal_img_2.jpg' carousel_img3 = settings.MEDIA_URL + f'{site}/carosal_img_3.jpg' if site == 'amazon': json_path = os.path.join(settings.MEDIA_ROOT, site, f'{site}_data.json') if os.path.exists(json_path): with open(json_path, 'r', encoding='utf-8') as f: json_data = json.load(f) best_seller_content_keys = list(json_data['Best Sellers'].keys()) best_seller_content1 = json.dumps(json_data['Best Sellers'][best_seller_content_keys[0]]) # ensure serializable best_seller_content2 = json.dumps(json_data['Best Sellers'][best_seller_content_keys[1]]) # ensure serializable carousel_name1 = json_data['Carosal Names'][1] carousel_name2 = json_data['Carosal Names'][2] carousel_name3 = json_data['Carosal Names'][3] carousel_link1 = json_data['carosal Links'][1] carousel_link2 = json_data['carosal Links'][2] carousel_link3 = json_data['carosal Links'][3] return JsonResponse({ 'image_url': image_url, 'best_seller_img1': best_seller_img1, 'best_seller_img2': best_seller_img2, 'best_seller_content1': best_seller_content1, 'best_seller_content2': best_seller_content2, 'carousel_img1': carousel_img1, 'carousel_img2': carousel_img2, 'carousel_img3': carousel_img3, 'carousel_name1': carousel_name1, 'carousel_name2': carousel_name2, 'carousel_name3': carousel_name3, 'carousel_link1': carousel_link1, 'carousel_link2': carousel_link2, 'carousel_link3': carousel_link3 }, status=200) elif site == 'bestbuy': best_seller_section = settings.MEDIA_URL + f'{site}/best_selling_section_3.png' best_seller_img2 = settings.MEDIA_URL + f'{site}/app_exclusive_section.png' json_path = os.path.join(settings.MEDIA_ROOT, site, f'{site}_data.json') first_section = settings.MEDIA_URL + f'{site}/first_section.png' if os.path.exists(json_path): with open(json_path, 'r', encoding='utf-8') as f: json_data = json.load(f) best_seller_content_keys = list(json_data['Best Sellers'].keys()) app_exclusive_keys = list(json_data['App Exclusive'].keys()) best_seller_content1 = json.dumps(json_data['Best Sellers'][best_seller_content_keys[0]]) # ensure serializable best_seller_content2 = json.dumps(json_data['App Exclusive'][app_exclusive_keys[0]]) # ensure serializable first_section_title = list(json_data['First Section'].keys())[0] first_section_url = json_data['First Section'][first_section_title] return JsonResponse({ 'image_url': image_url, 'first_section':first_section, 'first_section_url': first_section_url, 'first_section_title': first_section_title, 'first_section_url': first_section_url, 'best_seller_img1': best_seller_section, 'best_seller_img2': best_seller_img2, 'best_seller_content1': best_seller_content1, 'best_seller_content2': best_seller_content2 }, status=200) else: return JsonResponse({ 'image_url': image_url, }, status=200) return JsonResponse({'error': 'Screenshot not found'}, status=404) @csrf_exempt def run_script(request): ps_script = r"D:\open_outlook.ps1" # Run PowerShell silently and close after execution subprocess.Popen([ "powershell.exe", "-ExecutionPolicy", "Bypass", "-File", ps_script ], creationflags=subprocess.CREATE_NO_WINDOW) return JsonResponse({'message': '"✅ Outlook mail opened successfully!"'}, status=200) @csrf_exempt def download_excel(request): if request.method == 'GET': # Match filenames like csr_30-Oct-2025.xlsx pattern = re.compile(r'^csr_\d{2}-[A-Za-z]{3}-\d{4}\.xlsx$') folder_path = settings.MEDIA_ROOT for filename in os.listdir(folder_path): if pattern.match(filename): file_path = os.path.join(folder_path, filename) # ✅ Load the existing Excel workbook wb = load_workbook(file_path) ws = wb.active # or use wb[sheet_name] if specific sheet needed # ✅ Update cell L1 (column 12, row 1) ws["L1"] = datetime.now().strftime('%d %B %Y') # ✅ Save new file with updated name new_filename = f"csr_{datetime.now().strftime('%d-%b-%Y')}.xlsx" new_file_path = os.path.join(folder_path, new_filename) wb.save(new_file_path) # ✅ Return file for download with open(new_file_path, 'rb') as f: response = HttpResponse( f.read(), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ) response['Content-Disposition'] = f'attachment; filename="{new_filename}"' return response raise Http404("CSR Excel file not found.")