Backend for the Teso project written in 2022
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

210 lines
9.7 KiB

3 months ago
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Threading.Tasks;
using Teso_API.Models;
namespace Teso_API.Controllers
{
[AllowAnonymous, Route("search")]
[ApiController]
public class Search : ControllerBase
{
private readonly TESOContext _context;
public Search(TESOContext context)
{
_context = context;
}
[Authorize]
[Route("people"), HttpPost]
public async Task<IEnumerable<TesoUser>> TesoUsers([FromBody] string username)
{
var accessToken = Request.Headers[HeaderNames.Authorization];
string token = accessToken;
token = token.Substring(6).Trim();
var handler = new JwtSecurityTokenHandler();
var jwtToken = handler.ReadToken(token) as JwtSecurityToken;
string userID = jwtToken.Claims.First(claim => claim.Type == "userGUID").Value;
var persons = (from u in _context.TesoUserDetails.AsQueryable()
join e in _context.UserFinances on u.UserGUID equals e.UserGUID into finances
from fnc in finances.DefaultIfEmpty()
join b1 in _context.BlockedUsers on u.UserGUID equals b1.Initiator into intiated
from b1Init in intiated.DefaultIfEmpty()
join b2 in _context.BlockedUsers on u.UserGUID equals b2.Target into target
from bTarget in target.DefaultIfEmpty()
where u.UserGUID != userID && u.Username.Contains(username) && b1Init.Initiator != u.UserGUID && bTarget.Target != u.UserGUID
select new TesoUser()
{
username = u.Username,
address = u.Address,
country = u.Country,
thumbnail_dp = u.ThumbnailDp,
DateOfBirth = u.DateOfBirth,
description = u.Description,
email = u.Email,
firstname = u.Firstname,
friends = "0",
gender = u.Gender,
gold = fnc.UserGUID != null ? fnc.Gold.ToString() : "0",
silver = fnc.UserGUID != null ? fnc.Silver.ToString() : "0",
lastname = u.Surname,
phonenumber = u.Phonenumber.ToString(),
userGUID = u.UserGUID
}
).OrderBy(p => p.firstname).Take(20).ToListAsync();
return await persons;
}
[Authorize]
[Route("products"), HttpPost]
public async Task<IEnumerable<Product>> GetProducts([FromBody] string productName)
{
var param =
new SqlParameter()
{
ParameterName = "@product",
SqlDbType = System.Data.SqlDbType.VarChar,
Size = 100,
Direction = System.Data.ParameterDirection.Input,
Value = productName
};
List<Product> products = await _context.Products.FromSqlRaw("Select top (100) p.productID,p.pname,p.pdescription,c.catName as category, p.unitprice," +
"p.productimage,b.businessName as businessID From Products p Inner Join ProductCategories c on c.catcode = p.category Inner Join TesoBusinessDetail b on " +
"b.businessID = p.businessID where p.pname like '%'+@product+'%' order by p.pname asc", param).ToListAsync();
return products;
}
[Authorize]
[Route("business"), HttpPost]
public async Task<IEnumerable<TesoBusinessDetail>> GetBusiness([FromBody] string ShopName)
{
var param =
new SqlParameter()
{
ParameterName = "@shop",
SqlDbType = System.Data.SqlDbType.VarChar,
Size = 100,
Direction = System.Data.ParameterDirection.Input,
Value = ShopName
};
List<TesoBusinessDetail> businessDetails = await _context.TesoBusinessDetails.FromSqlRaw("Select top (100) b.businessID,b.handle,b.businessName,b.businessTin," +
"b.businessDescription,c.categoryname as businessCategory,b.businessaddress,b.businesscontact,b.businesslogo,b.dateofest,b.businessemail,b.businesslat,b.businesslng " +
"From TesoBusinessDetail b Inner Join BusinessCategory c on c.categoryCode = b.businesscategory Where b.businessName like '%'+@shop+'%'" +
" order by b.businessName asc", param).ToListAsync();
return businessDetails;
}
[Authorize]
[Route("category-products"), HttpPost]
public async Task<IEnumerable<Product>> GetCategoryProducts([FromBody] string category)
{
var param =
new SqlParameter()
{
ParameterName = "@category",
SqlDbType = System.Data.SqlDbType.VarChar,
Size = 100,
Direction = System.Data.ParameterDirection.Input,
Value = category
};
List<Product> products = await _context.Products.FromSqlRaw("Select top (100) p.productID,p.pname,p.pdescription,c.catName as category, p.unitprice," +
"p.productimage,b.businessName as businessID From Products p Inner Join ProductCategories c on c.catcode = p.category Inner Join TesoBusinessDetail b on " +
"b.businessID = p.businessID where p.category = @category order by p.pname asc", param).ToListAsync();
return products;
}
[Authorize]
[Route("artificial-intel-products"), HttpPost]
public async Task<IEnumerable<Product>> GetProducts([FromBody] List<string> imageKeys)
{
List<Product> products = new List<Product>();
foreach (string s in imageKeys)
{
//List<string> categories = await _context.ProductCategories.AsQueryable().Where(n => n.CatName.Contains(s)).Select(b => b.CatCode).ToListAsync();
List<Product> p = await _context.Products.AsQueryable().Where(p => p.Name.Contains(s) || p.Description.Contains(s))
.OrderBy(b => b.Name).Take(100).ToListAsync();
foreach (Product product in p)
{
if (!products.Contains(product))
{
product.BusinessId = await _context.TesoBusinessDetails.AsQueryable().Where(b => b.BusinessId == product.BusinessId).Select(b => b.BusinessName)
.FirstOrDefaultAsync();
product.Category = await _context.ProductCategories.AsQueryable().Where(c => c.CatCode == product.Category).Select(n => n.CatName).FirstOrDefaultAsync();
products.Add(product);
}
}
}
return products;
}
//[Authorize]
[Route("smart-search"), HttpPost]
public async Task<List<SmartSearch>> GetItems([FromBody] string searchKey)
{
string searchTerm = string.Format("%{0}%", searchKey);
List<SmartSearch> items = new List<SmartSearch>();
SqlConnection cn = new SqlConnection(ServerLocation.connection);
cn.Open();
SqlCommand cm = new SqlCommand("exec [dbo].[usp_smart_search_products] @searchKey = @search " +
"exec [dbo].usp_smart_search_businesses @searchKey = @search", cn);
cm.Parameters.AddWithValue("@search", searchTerm);
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
SmartSearch item = new SmartSearch
{
Name = dr["Name"].ToString(),
Type = "Products",
ProductBusinessIds = new()
{
new ProductBusinessId{
BusinessId = dr["BusinessId"].ToString(),
ProductId= dr["ProductId"].ToString(),
}
}
};
if (items.Any((e) => e.Name == item.Name))
{
items.Where((e) => e.Name == item.Name).First().ProductBusinessIds.ToList().AddRange(item.ProductBusinessIds);
}
else
{
items.Add(item);
}
}
dr.NextResult();
while (dr.Read())
{
SmartSearch item = new SmartSearch
{
Name = dr["businessName"].ToString(),
Type = "Business",
ProductBusinessIds = new(),
BusinessId = dr["BusinessId"].ToString(),
BusinessLat = dr["BusinessLat"].ToString(),
BusinessLng = dr["BusinessLng"].ToString(),
};
items.Add(item);
}
dr.Close();
cn.Close();
return items.OrderBy((a) => a.Name).ToList();
}
}
}