How to count thousands of daily visits - visitor-statistic

I have a classifieds site with thousands of daily visits.
I would like some advice: how can I count the visits of each ad and show the final data to the user who entered the ad?
Now I'm saving the visits to the database, but when I add them it takes a long time.
Can you recommend a quicker solution to save the total visits of each individual ad?
My code that updates visits:
$nomehost = "";
$nomeuser = "";
$password = "";
$nomedb = "";
$connect = new MySQLi($nomehost,$nomeuser,$password,$nomedb);
$sql="SELECT * FROM immobili_d";
$result=mysqli_query($connect,$sql);
while ($row=mysqli_fetch_array($result)) {
$sqlvisite="SELECT COUNT(id) FROM pageview WHERE idAnnuncio ='".$row['id']."'";
$resultvisite=mysqli_query($connect,$sqlvisite);
$visite = mysqli_fetch_array($resultvisite);
$queryUpdate = $connect->prepare("UPDATE immobili SET visite_tot=? WHERE id = ? ");
$queryUpdate->bind_param('ii', $visite['COUNT(id)'], $row['id']);
$resultUpdate = $queryUpdate->execute();
$sqlcontatti="SELECT COUNT(id) FROM sendrequest WHERE immobile_id ='".$row['id']."'";
$resultcontatti=mysqli_query($connect,$sqlcontatti);
$contatti = mysqli_fetch_array($resultcontatti);
$queryConUpdate = $connect->prepare("UPDATE immobili SET contatti_tot=? WHERE id = ? ");
$queryConUpdate->bind_param('ii', $contatti['COUNT(id)'], $row['id']);
$resultConUpdate = $queryConUpdate->execute();
}

Related

Dynamic NAV 2018 Web Service: Creating Sales Order Lines gets error "Standard Code Text does not exist...."

In Dynamic NAV 2018, I exposed page Sales Order (id 36) as web service, I'm following some guides to create Sales Order Header and Sales Order Lines, the Header can be created successfully, but the Sales Lines always get error "Standard Code Text does not exist..."
SOWS.Sales_Order_VS_Service testcreateSO = new SOWS.Sales_Order_VS_Service();
testcreateSO.UseDefaultCredentials = true;
SOWS.Sales_Order_VS SOEntity = new SOWS.Sales_Order_VS();
testcreateSO.Create(ref SOEntity);
SOEntity.Sell_to_Customer_No = "44094";
SOEntity.Store_No = "S9003";
SOEntity.Location_Code = "S9003";
testcreateSO.Update(ref SOEntity);
SOEntity.SalesLines = new SOWS.Sales_Order_Line[1];
SOEntity.SalesLines[0] = new SOWS.Sales_Order_Line();
testcreateSO.Update(ref SOEntity);
SOEntity.SalesLines[0].Type = SOWS.Type.Item;
SOEntity.SalesLines[0].TypeSpecified = true;
SOEntity.SalesLines[0].No = "208122";
SOEntity.SalesLines[0].Quantity = 1;
testcreateSO.Update(ref SOEntity);
System.Web.Services.Protocols.SoapException: 'The Standard Text does not exist. Identification fields and values: Code='208122''
Checking in table Sales Lines, a record of new order has been created but Type = 0 (means blank)
Document No_ Line No_ Sell-to Customer No_ Type No_ Location Code Document Type
SO210600017 10000 0 1
Please help
Solution
Instead of using only singe page Sales Order as web service, can expose page Sales Order Line as another web service, so full code as below:
SOWS.Sales_Order_VS_Service testcreateSO = new SOWS.Sales_Order_VS_Service();
testcreateSO.UseDefaultCredentials = true;
SOWS.Sales_Order_VS SOEntity = new SOWS.Sales_Order_VS();
testcreateSO.Create(ref SOEntity);
SOEntity.Sell_to_Customer_No = "44094";
SOEntity.Store_No = "S9003";
SOEntity.Location_Code = "S9003";
testcreateSO.Update(ref SOEntity);
//Using Sales Order Line page as web service from here
SOLinesWS.salesDocumentLines_Service saleslinesSV = new SOLinesWS.salesDocumentLines_Service
{
UseDefaultCredentials = true
};
SOLinesWS.salesDocumentLines saleslines = new SOLinesWS.salesDocumentLines();
saleslines.documentType = SOLinesWS.documentType.Order;
saleslines.documentTypeSpecified = true;
saleslines.documentNumber = SOEntity.No;
saleslines.type = SOLinesWS.type.Item;
saleslines.typeSpecified = true;
saleslines.number = "208122";
saleslines.quantity = 1;
saleslines.quantitySpecified = true;
saleslinesSV.Create(ref saleslines);

Accessing values inside an object

When the user of the application selects a card, I want to be able to retrieve the user's 'stripeID', however whenever I print paymentContext.selectedPaymentOption I am able to see the data that I need, but cannot access it.
Language used: swift.
I am using stripe for the payment system in Swift, and I am also using the stripe UI to allow users to add their credit card information to the app.
your comments will be very helpful
The message I am receiving is:
STPPaymentMethod: 0x28105c080; stripeId = pm_1GuuilCs27VSYM8G5UUd3q2S;
auBECSDebit = (null); bacsDebit = (null); billingDetails =
<STPPaymentMethodBillingDetails: 0x282b4d3c0; name = (null); phone =
(null); email = (null); address = <STPPaymentMethodAddress:
0x281d2e3f0; line1 = (null); line2 = (null); city = (null); state =
(null); postalCode = 6643; country = (null)>>; card =
<STPPaymentMethodCard: 0x281affea0; brand = Mastercard; checks =
<STPPaymentMethodCardChecks: 0x2831c9cb0; addressLine1Check: (null);
addressPostalCodeCheck: pass; cvcCheck: pass>; country = US; expMonth
= 2; expYear = 2054; funding = credit; last4 = 4444; fingerprint = TBj8N5wToO3eEbfK; threeDSecureUsage =
<STPPaymentMethodThreeDSecureUsage: 0x283f38840; supported: YES>;
wallet = (null)>; cardPresent = (null); created = 2020-06-17 06:26:04
+0000; customerId = cus_HTrYPeMU1l0pcB; ideal = (null); fpx = (null); sepaDebit = (null); liveMode = NO; metadata = { }; type = card
Any comments or assistance you can provide on this issue would be a great help.
Normally, this option should be performed in the backend,so you can list them or target the exact one.
Here how you retrieve an account: https://stripe.com/docs/api/accounts/retrieve?lang=node

E-mail notification based on cell value. Unable to apply script function for all rows

I am using Google sheets and the Google script editor to create a script to automatically send myself an e-mail every time a product quantity goes below the minimum inventory level. Since I have multiple products with different minimum inventory levels I expect to get a series of e-mails, one for each row.
I use one sheet for the actual Inventory data and another sheet that contains information for the script to refer to, such as my email and what message to include in the e-mail.
I succeeded having an e-mail sent collecting data from the first row of the Inventory sheet but I am not being able to apply that for all the following rows.
I tried changing the .getRange("F2") to .getRange("F2:F"), then whenever one of the products goes under the minimum inventory level I get one single e-mail containing the information about all products, regardless of whether their quantity is under the minimum level or not.
The ideal solution would be ONE single e-mail containing all the information about all products that are under the minimum quantity .
Here is a link to my spreadsheet: https://docs.google.com/spreadsheets/d/1ZHmBvi8ZeaDRYq6Qigaw08NUiOwZumPrLnvnka_mgmA/edit?usp=sharing
Current script:
function CheckInventory() {
// Fetch inventory quantity
var InventoryRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory").getRange("F2");
var Inventory = InventoryRange.getValue();
// Fetch minimum quantity
var MinimumQuantityRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Inventory").getRange("D2");
var MinimumQuantity = MinimumQuantityRange.getValue();
// Check Inventory
if (Inventory < MinimumQuantity){
// Fetch email address
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Notification Rules").getRange("E2");
var emailAddress = emailRange.getValues();
// Fetch email message details.
var detailsRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Notification Rules").getRange("G2");
var details = detailsRange.getValues();
var subjectdetailsRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Notification Rules").getRange("H2");
var subjectdetails = subjectdetailsRange.getValues();
// Send Alert Email.
var message = details;
var subject = subjectdetails;
MailApp.sendEmail(emailAddress, subject, message);
}
}
Update:
As you said in a comment, you want the email to be sent when you edit an inventory cell, and only if this edited inventory quantity is below the corresponding minimum. So here I update my answer accordingly.
First, I guess you have done this already, but because the function uses sendEmail, you will have to grant authorization for it to work. I created a trigger for that. Run this once:
function createEditTrigger() {
var ss = SpreadsheetApp.getActive();
ScriptApp.newTrigger("CheckInventory")
.forSpreadsheet(ss)
.onEdit()
.create();
}
Then, this is the function that will run every time the spreadsheet is edited. To avoid the email to be sent every time the file is edited, we need a condition that checks whether the edited cell is an inventory and that this inventory is below the minimum:
function CheckInventory(e) {
var ss = e.source;
var inventorySheet = ss.getSheetByName("Inventory");
var rowIndex = e.range.getRow();
var columnIndex = e.range.getColumn();
var numCols = 6;
var row = inventorySheet.getRange(rowIndex, 1, 1, numCols).getValues()[0];
var editedInventory = row[5];
var editedMinimum = row[3];
var sheetName = ss.getActiveSheet().getName();
// Checking that: (1) edited cell is an inventory quantity, and (2) Inventory is below minimum
if(editedInventory <= editedMinimum && sheetName == "Inventory" && columnIndex == 6 && rowIndex > 1) {
var inventoryValues = inventorySheet.getDataRange().getValues();
var emailBody = "";
for(var i = 1; i < inventoryValues.length; i++) {
var inventory = inventoryValues[i][5];
var minimum = inventoryValues[i][3];
if(inventory <= minimum) {
var productName = inventoryValues[i][0] + " " + inventoryValues[i][1];
var productUnits = minimum + " " + inventoryValues[i][4];
var messagePart1 = "Inventory for " + productName + " has gone under " + productUnits + ". ";
var messagePart2 = "Organise purchase order. Inventory as of today is: " + inventory + " " + inventoryValues[i][4];
var message = messagePart1.concat(messagePart2);
var newItem = "<p>".concat(message, "</p>");
emailBody += newItem;
}
}
var emailSubject = "Low inventory alert";
var emailAddress = "your-email#your-domain.com";
// Send Alert Email
if(emailBody != "") {
MailApp.sendEmail({
to: emailAddress,
subject: emailSubject,
htmlBody: emailBody
});
}
}
}
As I said in a comment, if you just want to send an email, it doesn't make sense to have many email subjects, so I hardcoded the subject.
Regarding the emails, I assumed you just want an email address to receive the email, so I hardcoded it too. If you want all the different email addresses found in Notifications tab to receive emails regarding all products, a small fix would be needed to this code. Tell me if that's needed for you.
Also, I didn't use your notifications tab at all, I created the message directly using the script. I'm not sure it is that useful to have the sheet "Notification Rules". Much of its info is the same as the one in inventory, and the rest of data (email address, basically) could be easily included there. But whatever suits you.
I hope this is of any help.

How to do this query using Django orm?

I have a Profile model and Complain model both are connected to the inbuilt User model.I have to do a query using both in which Profile model have residence. I want to have a count, that how many complains are made from a particular residence. I can do it using SQL but I didn't know how to do it using Django.
SELECT users_profile.residence,count(user_id)from users_profile INNER JOIN chp_complain on(users_profile.user_id = chp_complain.complain_user_id)GROUP BY(user_id)
Complain Model:-
class Complain(models.Model):
complain_user = models.ForeignKey(User, on_delete=models.CASCADE)
complain_department=models.CharField(max_length=100)
complain_subject = models.CharField(max_length = 100,help_text = "Enter the complain subject")
department_head=models.CharField(max_length=100)
recepient=models.CharField(max_length=100)
complain_description=models.TextField(max_length=2000)
date_posted = models.DateTimeField(default = timezone.now)
NOT_VISITED = 'NV'
VISITED = 'V'
INPROCESS = 'IP'
COMPLETED = 'C'
status = (
(NOT_VISITED, 'NV'),
(VISITED, 'V'),
(INPROCESS, 'IP'),
(COMPLETED, 'C'),)
status=models.CharField(max_length=2,choices=status,)
Profile Model:-
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
UID =models.CharField(max_length=30,default = "000",help_text = "'Staff's fill their STAFF ID and student's fill their ROLL NO " )
MALE = 'M'
FEMALE = 'F'
Gender=((MALE, 'Male'),(FEMALE, 'Female'),)
Gender=models.CharField(max_length=6,choices=Gender,default=MALE,)
FIRST = '1st'
SECOND = '2nd'
THIRD = '3rd'
FOURTH = '4th'
NGH = 'NGH'
NON_HOSTELER = 'Non_hosteler'
TEACHER_QUARTER = 'Teacher_quarter'
residence = ((FIRST, 'First'),(SECOND, 'Second'),(THIRD, 'Third'),(FOURTH, 'Fourth'),(NGH,'NGH'),(NON_HOSTELER, 'Non_hosteler'),(TEACHER_QUARTER,'Teacher_quarter'))
residence = models.CharField(max_length=20,choices=residence,default=FIRST,)
room_no=models.CharField(max_length=10,default = "000")
I want to have a count, that how many complains are made from a particular residence you can write:
Complain.objects.values('complain_user__profile__residence').annotate(complains_count=Count('id'))
In your SQL query:
SELECT users_profile.residence,count(user_id)from users_profile INNER JOIN chp_complain on(users_profile.user_id = chp_complain.complain_user_id)GROUP BY(user_id)
You calculate how many users filed complaints from a particular residence. It can be calculated as follows:
User.objects.values('profile__residence').annotate(Count('id'))

How do I test a trigger with an approval process?

I have a trigger which initiates an approval process when certain criteria are met:
trigger AddendumAfterIHMS on Addendum__c (after update) {
for (integer i = 0; i<Trigger.new.size(); i++){
if(Trigger.new[i].RecordTypeId != '012V0000000CkQA'){
if(Trigger.new[i].From_IHMS__c != null && Trigger.old[i].From_IHMS__c == null){
ID addendumId = Trigger.new[i].Id;
// Start next approval process
Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest();
request.setObjectId(addendumId);
Approval.ProcessResult requestResult = Approval.process(request);
}
}
}
}
It works perfectly, but now i need to create a test class for it. I have created a class which brings the code up to 75% coverage, which is the minimum, but I'm picky and like to have 100% coverage on my code. The test class I have now gets stuck on the line request.setObjectId(addendumId); and doesn't move past it. The error I receive is:
System.DmlException: Update failed. First exception on row 0 with id a0CV0000000B8cgMAC; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AddendumAfterIHMS: execution of AfterUpdate
Here is the test class that I have written so far, most of the class actually tests some other triggers, but the important line which is throwing the error is the very last line update addendumTierFeature;
#isTest
private class AddendumTest {
static testMethod void myUnitTest() {
// Query Testing Account, will need ID changed before testing to place into production
Account existingAccount = [SELECT Id FROM Account LIMIT 1];
Model__c existingModel = [SELECT Id FROM Model__c WHERE Active__c = TRUE LIMIT 1];
Pricebook2 existingPricebook = [SELECT Id,Name FROM Pricebook2 WHERE IsActive = TRUE LIMIT 1];
List<Contact> existingContacts = [SELECT Id,Name FROM Contact LIMIT 2];
Contact existingContactPrimary = existingContacts[0];
Contact existingContactSecondary = existingContacts[1];
Opportunity newOpportunity = new Opportunity(
Name = 'New Opportunity',
Account = existingAccount,
CloseDate = Date.today(),
Order_Proposed__c = Date.today(),
StageName = 'Branch Visit - Not Responding',
Opportunity_Follow_Up__c = 'Every 120 Days',
LeadSource = 'Farm Lists',
Source_Detail__c = 'FSBO',
Model_Name__c = existingModel.Id,
Processing_Fee__c = 100.50,
Site_State__c = 'OR',
base_Build_Zone__c = 'OR',
Pricebook_from_Lead__c = existingPricebook.Name
);
insert newOpportunity;
//system.assert(newOpportunity.Id != null);
ID newOppId = newOpportunity.Id;
OpportunityContactRole contactPrimary = new OpportunityContactRole(
Role = 'Primary',
IsPrimary = true,
OpportunityId = newOppId,
ContactId = existingContactPrimary.Id
);
OpportunityContactRole contactSecondary = new OpportunityContactRole(
Role = 'Primary',
IsPrimary = false,
OpportunityId = newOppId,
ContactId = existingContactPrimary.Id
);
insert contactPrimary;
insert contactSecondary;
newOpportunity.Name = 'Different - Updating';
newOpportunity.Order_Accepted__c = Datetime.now();
update newOpportunity;
Addendum__c addendumCustomOption = new Addendum__c(
RecordTypeId = '012V0000000CkQA', //Pre Priced Custom Option
Opportunity__c = newOppId,
Item_Pre_Priced_Description__c = 'a1eV00000004DNu',
Reason__c = 'This is a reason',
Item__c = 'This is an Item',
Quantity__c = 1
);
Addendum__c addendumTierFeature = new Addendum__c(
RecordTypeId = '012V0000000Cjks', //Tier Feature
Opportunity__c = newOppId,
Category__c = 'Countertops',
Reason__c = 'This is a reason',
Item__c = 'This is an Item',
Quantity__c = 1
);
insert addendumCustomOption;
insert addendumTierFeature;
addendumCustomOption.Quantity__c = 2;
addendumTierFeature.Quantity__c = 2;
update addendumCustomOption;
update addendumTierFeature;
update newOpportunity;
addendumTierFeature.To_IHMS__c = system.now();
update addendumTierFeature;
addendumTierFeature.From_IHMS__c = system.now();
update addendumTierFeature;
}
}
Any help on this matter would be greatly appreciated. I believe the problem is in the way I am testing the approval process start. Is there by chance a special testing function for this?
After fiddling around for a little while I discovered that the error was actually tied into my approval process. I kept digging into the error logs until I got to the error: caused by: System.DmlException: Process failed. First exception on row 0; first error: MANAGER_NOT_DEFINED, Manager undefined.: []. This phrase indicates that there is no one defined for the next step in my approval process.
When I created the opportunity, I did not set the owner and somehow this created an opportunity which had an owner without a manager. The addendum was also created without an owner/manager. So when I tried to launch the next approval process, there was no manager to send the approval to and an error was thrown.