#include "bs_util.h" #include "MySQLTransaction.h" using namespace std; int main() { Request req; Session se(req); Response res; json j; auto jsonfail=[&](int errcode,const std::string& dtl="") { jsonfail_func(j,errcode,dtl); }; do { if(!se.isReady()) { jsonfail(err_session); break; } if(se.getUser().empty()) { jsonfail(err_need_login); break; } if(req.requestMethod!="POST") { jsonfail(err_method_not_supported); break; } postval(bid); int bid_real=ParseInt(bid); if(bid_real<0) { jsonfail(err_parameter,"Failed to parse bid"); break; } startdb(); /// Start transaction Transaction ts(conn); if(!ts.isReady()) { jsonfail(err_sql_logic,"Failed to start transaction."); break; } /// Check if user can borrow... int cntval; if(conn.exec(make_str("select count(username) from bs_reader where username='", se.getUser(), "'"), SQLParseInt(cntval))<0) { jsonfail(err_sql,"Step 1"); break; } if(cntval!=1) { jsonfail(err_permission_denied,"You are not in reader list!"); break; } int borrow_limit,borrow_used,borrow_time_limit; if(conn.exec(make_str("select borrow_limit,borrow_used,borrow_time_limit from bs_reader where username='", se.getUser(), "'"), [&](MySQLResult& res) { res.stepRow([&](char** val,unsigned long* len) { borrow_limit=ParseInt(val[0]); borrow_used=ParseInt(val[1]); borrow_time_limit=ParseInt(val[2]); }); })<0) { jsonfail(err_sql,"Step 2"); break; } if(borrow_limit-borrow_used<=0) { jsonfail(err_general,"Reach Borrow Limit"); break; } /// Verify bid if(conn.exec(make_str("select count(book_id) from bs_bookstatus where book_id=", bid_real), SQLParseInt(cntval))<0) { jsonfail(err_sql,"Step 3"); break; } if(cntval!=1) { jsonfail(err_parameter,"Failed to verify bid"); break; } /// Check if bid is allowed to be borrowed. int book_status; if(conn.exec(make_str("select status from bs_bookstatus where book_id=",bid_real), SQLParseInt(book_status))<0) { jsonfail(err_sql,"Step 4"); break; } if(book_status!=2) { jsonfail(err_data,"Book is not allowed to borrow"); break; } /// DO UPDATE if(conn.exec(make_str("update bs_reader set borrow_used=borrow_used+1 where username='", se.getUser(), "'"),nullptr)<0) { jsonfail(err_sql,"Update 1"); break; } if(conn.exec(make_str("update bs_bookstatus set status=0 where book_id=",bid_real),nullptr)<0) { jsonfail(err_sql,"Update 2"); break; } if(conn.exec(make_str("insert into bs_borrow values ('", se.getUser(), "',", bid_real, ",curdate(),date_add(curdate(),interval ", borrow_time_limit, " day),null)"),nullptr)<0) { jsonfail(err_sql,"Update 3"); break; } /// Commit it ts.commit(); j["success"]=1; } while(0); se.writeToResponse(res); res.content.append(j.dump()); return 0; }