text stringlengths 1 1.05M |
|---|
#!/bin/bash
# fix /etc/hosts
if ! grep -q "localhost" /etc/hosts; then
touch /etc/hosts
chmod 644 /etc/hosts
echo $HOSTNAME localhost >> /etc/hosts
echo "127.0.0.1 localhost" >> /etc/hosts
fi
# check pub key
if [ -z ${pub_key+x} ]; then
echo pub_key does not set in env variables
else
[[ -d /root/.ssh ]] || mkdir -p /root/.ssh
if ! grep -q "$pub_key" /root/.ssh/authorized_keys; then
echo $pub_key >> /root/.ssh/authorized_keys
fi
fi
chmod +x /opt/bin/*
echo "runing mariadb"
/bin/bash /opt/bin/mariadb_entry.sh
# prepare mysql server
chown -R mysql:mysql /var/lib/mysql /var/run/mysqld /var/log/mysql
chmod 777 /var/run/mysqld
echo "mariaserver running"
echo "running faveo server"
chown -R www-data:www-data /var/run/php
# prepare for ssh service
chmod 400 -R /etc/ssh/
mkdir -p /run/sshd
[ -d /root/.ssh/ ] || mkdir /root/.ssh
# prepare for supervisor service
[ -d /var/log/php-fpm ] || mkdir -p /var/log/php-fpm
chown -R www-data:www-data /var/log/supervisor
chgrp -R www-data /usr/share/nginx/storage /usr/share/nginx/bootstrap/cache
chmod -R ug+rwx . /usr/share/nginx/storage /usr/share/nginx/bootstrap/cache
chmod -R 0777 /usr/share/nginx/storage
chmod 0644 /etc/cron.d/faveo-cron
# use supervisord to start ssh, mysql and nginx and php-fpm
supervisord -c /etc/supervisor/supervisord.conf
exec "$@"
|
<filename>command/cmd_list.go
package command
import (
"context"
"fmt"
"github.com/hashicorp/go-multierror"
"github.com/urfave/cli/v2"
errorpkg "github.com/peak/s5cmd/error"
"github.com/peak/s5cmd/log"
"github.com/peak/s5cmd/storage"
"github.com/peak/s5cmd/storage/url"
"github.com/peak/s5cmd/strutil"
)
var ListCommand = &cli.Command{
Name: "ls",
HelpName: "ls",
Usage: "list buckets and objects",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "etag",
Aliases: []string{"e"},
Usage: "show entity tag (ETag) in the output",
},
&cli.BoolFlag{
Name: "humanize",
Aliases: []string{"H"},
Usage: "human-readable output for object sizes",
},
},
Before: func(c *cli.Context) error {
if c.Args().Len() > 1 {
return fmt.Errorf("expected only 1 argument")
}
return nil
},
Action: func(c *cli.Context) error {
if !c.Args().Present() {
return ListBuckets(c.Context)
}
showEtag := c.Bool("etag")
humanize := c.Bool("humanize")
return List(
c.Context,
c.Args().First(),
showEtag,
humanize,
)
},
}
func ListBuckets(ctx context.Context) error {
// set as remote storage
url := &url.URL{Type: 0}
client, err := storage.NewClient(url)
if err != nil {
return err
}
buckets, err := client.ListBuckets(ctx, "")
if err != nil {
return err
}
for _, bucket := range buckets {
log.Info(bucket)
}
return nil
}
func List(
ctx context.Context,
src string,
// flags
showEtag bool,
humanize bool,
) error {
srcurl, err := url.New(src)
if err != nil {
return err
}
client, err := storage.NewClient(srcurl)
if err != nil {
return err
}
var merror error
for object := range client.List(ctx, srcurl, true) {
if errorpkg.IsCancelation(object.Err) {
continue
}
if err := object.Err; err != nil {
merror = multierror.Append(merror, err)
continue
}
msg := ListMessage{
Object: object,
showEtag: showEtag,
showHumanized: humanize,
}
log.Info(msg)
}
return merror
}
// ListMessage is a structure for logging ls results.
type ListMessage struct {
Object *storage.Object `json:"object"`
showEtag bool
showHumanized bool
}
// humanize is a helper function to humanize bytes.
func (l ListMessage) humanize() string {
var size string
if l.showHumanized {
size = strutil.HumanizeBytes(l.Object.Size)
} else {
size = fmt.Sprintf("%d", l.Object.Size)
}
return size
}
const (
listFormat = "%19s %1s %-6s %12s %s"
dateFormat = "2006/01/02 15:04:05"
)
// String returns the string representation of ListMessage.
func (l ListMessage) String() string {
if l.Object.Type.IsDir() {
s := fmt.Sprintf(
listFormat,
"",
"",
"",
"DIR",
l.Object.URL.Relative(),
)
return s
}
var etag string
if l.showEtag {
etag = l.Object.Etag
}
s := fmt.Sprintf(
listFormat,
l.Object.ModTime.Format(dateFormat),
l.Object.StorageClass.ShortCode(),
etag,
l.humanize(),
l.Object.URL.Relative(),
)
return s
}
// JSON returns the JSON representation of ListMessage.
func (l ListMessage) JSON() string {
return strutil.JSON(l.Object)
}
|
#include <iostream>
using namespace std;
int search(int arr[], int n, int element)
{
for (int i = 0; i < n; i++) {
if (arr[i] == element)
return i;
}
return -1;
}
int main()
{
int arr[] = { 4, 7, 5, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int element = 8;
int index = search(arr, n, element);
if (index == -1)
cout << element << " is not present in the array";
else
cout << element << " is present at index " << index;
return 0;
} |
<reponame>Financial-Times/kquery
const expect = require('chai').expect;
const KeenQuery = require('../lib/keen-query');
describe('toString', function () {
describe('aggregator', function () {
it('should preserve shared filters', function () {
const query = KeenQuery.build(`
@pct(
page:view ->count(user.uuid) ->filter(user.myft.optedIntoDailyEmail=true),
page:view->count(user.uuid)
)
->filter(user.subscriptions.isStaff!=true)`);
expect(query.toString()).to.equal('@pct(page:view->count(user.uuid)->filter(user.myft.optedIntoDailyEmail=true),page:view->count(user.uuid))->filter(user.subscriptions.isStaff!=true)');
});
});
});
|
<filename>src/vuejsclient/ts/components/dashboard_builder/viewer/DashboardViewerComponent.ts
import Component from 'vue-class-component';
import { Prop, Watch } from 'vue-property-decorator';
import ModuleAccessPolicy from '../../../../../shared/modules/AccessPolicy/ModuleAccessPolicy';
import ModuleDAO from '../../../../../shared/modules/DAO/ModuleDAO';
import ModuleDashboardBuilder from '../../../../../shared/modules/DashboardBuilder/ModuleDashboardBuilder';
import DashboardPageVO from '../../../../../shared/modules/DashboardBuilder/vos/DashboardPageVO';
import DashboardPageWidgetVO from '../../../../../shared/modules/DashboardBuilder/vos/DashboardPageWidgetVO';
import DashboardVO from '../../../../../shared/modules/DashboardBuilder/vos/DashboardVO';
import WeightHandler from '../../../../../shared/tools/WeightHandler';
import InlineTranslatableText from '../../InlineTranslatableText/InlineTranslatableText';
import VueComponentBase from '../../VueComponentBase';
import DashboardBuilderBoardComponent from '../board/DashboardBuilderBoardComponent';
import { ModuleDashboardPageAction, ModuleDashboardPageGetter } from '../page/DashboardPageStore';
import './DashboardViewerComponent.scss';
@Component({
template: require('./DashboardViewerComponent.pug'),
components: {
Inlinetranslatabletext: InlineTranslatableText,
Dashboardbuilderboardcomponent: DashboardBuilderBoardComponent,
}
})
export default class DashboardViewerComponent extends VueComponentBase {
@ModuleDashboardPageGetter
private get_page_history: DashboardPageVO[];
@ModuleDashboardPageAction
private add_page_history: (page_history: DashboardPageVO) => void;
@ModuleDashboardPageAction
private set_page_history: (page_history: DashboardPageVO[]) => void;
@ModuleDashboardPageAction
private pop_page_history: (fk) => void;
@ModuleDashboardPageAction
private clear_active_field_filters: () => void;
@Prop({ default: null })
private dashboard_id: number;
private dashboard: DashboardVO = null;
private loading: boolean = true;
private pages: DashboardPageVO[] = [];
private page: DashboardPageVO = null;
private selected_widget: DashboardPageWidgetVO = null;
private can_edit: boolean = false;
private select_widget(page_widget) {
this.selected_widget = page_widget;
}
get has_navigation_history(): boolean {
return this.get_page_history && (this.get_page_history.length > 0);
}
private select_previous_page() {
this.page = this.get_page_history[this.get_page_history.length - 1];
this.pop_page_history(null);
}
private select_page_clear_navigation(page: DashboardPageVO) {
this.set_page_history([]);
this.page = page;
}
get visible_pages(): DashboardPageVO[] {
if (!this.pages) {
return null;
}
let res: DashboardPageVO[] = [];
for (let i in this.pages) {
let page = this.pages[i];
if (!page.hide_navigation) {
res.push(page);
}
}
return res;
}
/**
* Quand on change de dahsboard, on supprime les filtres contextuels existants (en tout cas par défaut)
* on pourrait vouloir garder les filtres communs aussi => non implémenté (il faut un switch et supprimer les filtres non applicables aux widgets du dashboard)
* et on pourrait vouloir garder tous les filtres => non implémenté (il faut un switch et simplement ne pas supprimer les filtres)
*/
@Watch("dashboard_id", { immediate: true })
private async onchange_dashboard_id() {
this.loading = true;
if (!this.dashboard_id) {
this.can_edit = false;
this.loading = false;
return;
}
this.dashboard = await ModuleDAO.getInstance().getVoById<DashboardVO>(DashboardVO.API_TYPE_ID, this.dashboard_id);
if (!this.dashboard) {
this.can_edit = false;
this.loading = false;
return;
}
this.clear_active_field_filters();
this.pages = await ModuleDAO.getInstance().getVosByRefFieldIds<DashboardPageVO>(DashboardPageVO.API_TYPE_ID, 'dashboard_id', [this.dashboard.id]);
if (!this.pages) {
this.isLoading = false;
this.can_edit = false;
return;
}
WeightHandler.getInstance().sortByWeight(this.pages);
this.page = this.pages[0];
this.can_edit = await ModuleAccessPolicy.getInstance().testAccess(ModuleDashboardBuilder.POLICY_BO_ACCESS);
this.loading = false;
}
private select_page(page: DashboardPageVO) {
this.add_page_history(this.page);
this.select_widget(null);
this.page = page;
}
get dashboard_name_code_text(): string {
if (!this.dashboard) {
return null;
}
return this.dashboard.translatable_name_code_text ? this.dashboard.translatable_name_code_text : null;
}
get pages_name_code_text(): string[] {
let res: string[] = [];
if (!this.pages) {
return res;
}
for (let i in this.pages) {
let page = this.pages[i];
res.push(page.translatable_name_code_text ? page.translatable_name_code_text : null);
}
return res;
}
// private mounted() {
// let body = document.getElementById('page-top');
// body.classList.add("sidenav-toggled");
// }
// private beforeDestroy() {
// let body = document.getElementById('page-top');
// body.classList.remove("sidenav-toggled");
// }
} |
<gh_stars>0
/*=========================================================================
Program: BatchMake
Module: bmScriptErrorGUI.h
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2005 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __ScriptErrorGUI_h_
#define __ScriptErrorGUI_h_
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include <bmScriptError.h>
#include <iostream>
#include "BMString.h"
#include <FL/Fl_Text_Display.H>
namespace bm {
class ScriptErrorGUI : public ScriptError
{
public:
ScriptErrorGUI();
~ScriptErrorGUI();
void SetTextDisplay(Fl_Text_Display* textdisplay);
void SetError(const BMString& error,int line=-1);
void SetWarning(const BMString& warning,int line=-1);
void SetStatus(const BMString& status);
void DisplaySummary();
protected:
Fl_Text_Display* m_TextDisplay;
};
} // end namespace bm
#endif
|
string AddCommas(string input)
{
StringBuilder output = new StringBuilder();
foreach(char c in input)
{
output.Append(c).Append(",");
}
output.Remove(output.Length - 1, 1);
return output.ToString();
} |
<filename>velocloud/vcoclient/model_edge_certificate.go
package vcoclient
import (
"time"
)
type EdgeCertificate struct {
Id int32 `json:"id,omitempty"`
Created time.Time `json:"created,omitempty"`
CsrId int32 `json:"csrId,omitempty"`
EdgeId int32 `json:"edgeId,omitempty"`
EnterpriseId int32 `json:"enterpriseId,omitempty"`
Certificate string `json:"certificate,omitempty"`
SerialNumber string `json:"serialNumber,omitempty"`
SubjectKeyId string `json:"subjectKeyId,omitempty"`
FingerPrint string `json:"fingerPrint,omitempty"`
FingerPrint256 string `json:"fingerPrint256,omitempty"`
ValidFrom time.Time `json:"validFrom,omitempty"`
ValidTo time.Time `json:"validTo,omitempty"`
}
|
package edu.uwp.appfactory.racinezoo.Util;
/**
* Created by hanh on 2/11/17.
*/
public class Config {
public static char[] ALPHABET = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
public static final String BEACON_LAYOUT = "m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24";
public static final int ANIMAL = 0;
public static final int EVENT = 1;
public static final int LOCATION =2;
public static final String CATEGORY_BIRD ="Birds";
public static final String CATEGORY_MAMMAL ="Mammals";
public static final String CATEGORY_REPTILE ="Reptile";
public static final String CATEGORY_AMPHIBIAN ="Amphibian";
public static final int DETAIL_TYPE_GENERAL = 0;
public static final int DETAIL_TYPE_FACT = 1;
public static final int DETAIL_TYPE_LOCATION = 2;
public static final int DETAIL_TYPE_INFO = 3;
public static final int DETAIL_TYPE_CLICKABLE_ANIMAL = 4;
public static final int INFO_TYPE_HOUR = 1;
public static final int INFO_TYPE_DIRECT = 2;
public static final int INFO_TYPE_SHOW = 3;
public static final int INFO_TYPE_ABOUT = 4;
public static final int INFO_TYPE_PRIVACY = 5;
public static final int INFO_TYPE_ADMIN = 6;
public static final int INFO_TYPE_FOOD = 7;
public static final int INFO_TYPE_CONTACT = 8;
public static final String PREF_EXPLORE_MODE = "EXPLORE_MODE";
//1h
//public static final long BEACON_WAIT_INTERVAL = 1000*60*60;
//1 min
public static final long BEACON_WAIT_INTERVAL = 1000*60;
}
|
#!/bin/bash
echo "Install SafeKit from `ls ./*.bin`"
chmod +x ./safekit*.bin
./safekit*.bin
yum -y localinstall ./safekit*.rpm
#rm ./safekit*.bin ./safekit*.rpm
echo "Install powershell"
# Register the Microsoft RedHat repository
curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo
yum update powershell
# Install PowerShell
yum install -y powershell
mkdir /replicated
echo "This is a replicated file" >/replicated/repfile.txt
if [ -f "installAzureRM.ps1" ]; then
pwsh ./installAzureRM.ps1 -linux
fi
echo "starting CA helper service"
cd /opt/safekit/web/bin
./startcaserv "$2" |
# /bin/bash
curl -X POST -H "Content-Type: application/json" -d '{"name": "Test user", "number": 100}' http://127.0.0.1:8080
|
ffmpeg -r 1 -i %d.png -vcodec mpeg4 -y out_final.mp4
|
def max(x, y):
if x > y:
return x
else:
return y |
One approach to detecting a triangle in a given set of points is to use the triangle inequality theorem. This theorem states that the sum of two sides of any given triangle must be greater than the length of the remaining sides. So, if we iterate through every combination of three points, we can check the lengths of the sides and determine if they form a triangle or not. |
net processNetworkRequests() {
// Simulate network requests
bool errorOccurred = false;
bool timeoutOccurred = false;
// Assume network requests are made here and set errorOccurred or timeoutOccurred accordingly
// For demonstration purposes, let's assume an error occurred
// errorOccurred = true;
if (errorOccurred) {
return net::ERROR;
} else if (timeoutOccurred) {
return net::TIMEOUT;
} else {
return net::OK;
}
} |
<gh_stars>0
const complete = JSON.parse(localStorage.getItem("OK")) || [];
const color = "rgb(19 88 150)";
const dayColor = "black";
function App() {
return (
<div className="App">
<Calendar />
</div>
);
}
export default App;
const Calendar = () => {
let monthNumber = [];
for (let x = 0; x < 12; x++) {
monthNumber.push(x);
}
const year = 2022;
return (
<div className="calendar">
<h1>{year}</h1>
{monthNumber.map((m) => (
<Months key={m} year={year} month={m} />
))}
</div>
);
};
const Months = (props) => {
const monthNames = [
"Janeiro",
"Fevereiro",
"Março",
"Abril",
"Maio",
"Junho",
"Julho",
"Agosto",
"Setembro",
"Outubro",
"Novembro",
"Dezembro",
];
const month = monthNames[props.month];
const year = props.year;
const weekDays = ["D", "S", "T", "Q", "Q", "S", "S"];
const daysPerMonth = new Date(year, props.month + 1, 0).getDate();
let days = [];
for (let x = 1; x <= daysPerMonth; x++) {
days.push(x);
}
const prevDaysWeekPerMonth = new Date(year, props.month, 0).getDay();
const prevDaysPerMonth = new Date(year, props.month, 0).getDate();
const prevDays = [];
for (
let x = prevDaysPerMonth - prevDaysWeekPerMonth;
x <= prevDaysPerMonth;
x++
) {
prevDays.push(x);
}
const nextDays = [];
const nextDaysMonth = new Date(year, props.month + 1, 0).getDay();
for (let x = 1; x <= 6 - nextDaysMonth; x++) {
nextDays.push(x);
}
const save = (dados) => {
localStorage.setItem("OK", JSON.stringify(dados));
};
const handleClick = (e) => {
e.preventDefault();
const span = e.target;
const okDay = span.getAttribute("id");
const exist = complete.indexOf(okDay);
if (exist === -1) {
span.style.backgroundColor = color;
complete.push(okDay);
console.log("add azul");
} else {
complete.splice(exist, 1);
span.style.backgroundColor = dayColor;
console.log("r azul");
}
save(complete);
};
return (
<div className="month">
<h1>{month}</h1>
<div className="week">
{weekDays.map((d, i) => (
<h2 key={d + i}>{d}</h2>
))}
</div>
<div className="days">
{prevDays.map((d) => (
<span
className="days prev"
id={month + d + "Prev" + year}
key={month + d + "Prev"}
onClick={(e) => handleClick(e)}
>
{d}
</span>
))}
{days.map((d) => (
<span
className="days"
id={month + d + year}
key={month + d}
onClick={(e) => handleClick(e)}
>
{d}
</span>
))}
{nextDays.map((d) => (
<span
className="days prev"
id={month + d + "Next" + year}
key={month + d + "Next"}
onClick={(e) => handleClick(e)}
>
{d}
</span>
))}
</div>
</div>
);
};
window.onload = () => {
for (let x = 0; x < complete.length; x++) {
const elem = document.querySelector("#" + complete[x]);
if (elem) {
elem.style.backgroundColor = color;
}
}
};
|
<filename>preload.js
// Make Pluggable Electron's facade available to hte renderer on window.plugins
const { contextBridge } = require('electron')
const facade = require("pluggable-electron/facade")
contextBridge.exposeInMainWorld("plugins", facade)
|
package com.kalpvaig.mvpfromscratch.models;
import android.content.ContentValues;
import com.tinmegali.tutsmvp_sample.data.DBSchema;
/**
* ---------------------------------------------------
* Created by <NAME> on 18/03/16.
* Project: tuts+mvp_sample
* ---------------------------------------------------
* <a href="http://www.tinmegali.com">tinmegali.com</a>
* <a href="http://www.github.com/tinmegali>github</a>
* ---------------------------------------------------
*/
public class Note {
private int id = -1;
private String mText;
private String mDate;
public Note() {
}
public Note(int id, String mText, String mDate) {
this.id = id;
this.mText = mText;
this.mDate = mDate;
}
public Note(String mText, String mDate) {
this.mText = mText;
this.mDate = mDate;
}
public ContentValues getValues(){
ContentValues cv = new ContentValues();
if ( id!=-1) cv.put(DBSchema.TB_NOTES.ID, id);
cv.put(DBSchema.TB_NOTES.NOTE, mText);
cv.put(DBSchema.TB_NOTES.DATE, mDate);
return cv;
}
public void setId(int id) {
this.id = id;
}
public void setDate(String mDate) {
this.mDate = mDate;
}
public void setText(String mText) {
this.mText = mText;
}
public int getId() {
return id;
}
public String getDate() {
return mDate;
}
public String getText() {
return mText;
}
}
|
#!/bin/bash -e
################################################################################
## File: swift.sh
## Desc: Installs Swift
################################################################################
# Source the helpers for use with the script
source $HELPER_SCRIPTS/install.sh
# Install
image_label="$(lsb_release -rs)"
swift_version=$(curl -s "https://api.github.com/repos/apple/swift/releases/latest" | jq -r '.tag_name | match("[0-9.]+").string')
swift_tar_name="swift-$swift_version-RELEASE-ubuntu$image_label.tar.gz"
swift_tar_url="https://swift.org/builds/swift-$swift_version-release/ubuntu${image_label//./}/swift-$swift_version-RELEASE/$swift_tar_name"
download_with_retries $swift_tar_url "/tmp" "$swift_tar_name"
tar xzf /tmp/$swift_tar_name
mv swift-$swift_version-RELEASE-ubuntu$image_label /usr/share/swift
SWIFT_PATH="/usr/share/swift/usr/bin"
SWIFT_BIN="$SWIFT_PATH/swift"
SWIFTC_BIN="$SWIFT_PATH/swiftc"
ln -s "$SWIFT_BIN" /usr/local/bin/swift
ln -s "$SWIFTC_BIN" /usr/local/bin/swiftc
echo "SWIFT_PATH=$SWIFT_PATH" | tee -a /etc/environment
invoke_tests "Common" "Swift"
|
N, P = map(int, input().split())
M = N
order = dict()
while True:
M = M * N % P
if M in order:
print(f'M: {M}')
print(order)
print(order[M])
print(len(order)-order[M])
break
else:
cnt = len(order)
order[M] = cnt
|
<filename>v15.4/app/modules/Animation/components/Todos.js
import RaisedButton from 'material-ui/RaisedButton';
export default class Animation extends React.Component {
constructor(props) {
super(props);
this.state = {
items: ['hello', 'world', 'click', 'me'],
enableTransitionLeave: true
};
this.handleAdd = this.handleAdd.bind(this);
}
handleAdd() {
const newItems = this.state.items.concat([
prompt('Enter some text')
]);
this.setState({items: newItems});
}
handleRemove(i) {
let newItems = this.state.items.slice();
newItems.splice(i, 1);
this.setState({items: newItems});
}
toggleTransitionLeave() {
this.setState({enableTransitionLeave: !this.state.enableTransitionLeave});
}
render() {
const {enableTransitionLeave} = this.state;
const items = this.state.items.map((item, i) => (
<div key={item} onClick={() => this.handleRemove(i) }>
{item}
</div>
));
return (
<div>
<RaisedButton label='Add Item' onClick={this.handleAdd}/>
<RaisedButton label='toggleTransitionLeave' onClick={::this.toggleTransitionLeave}/>
<p>transitionLeave开启状态:{enableTransitionLeave ? '开启' : '关闭'}</p>
{/*默认的, 如果不设置transitionEnter和transitionLeave属性,这两个属性的默认值是true */}
<ReactCSSTransitionGroup
transitionName="example"
transitionLeave={enableTransitionLeave}
transitionEnterTimeout={500}
transitionLeaveTimeout={300}>
{items}
</ReactCSSTransitionGroup>
</div>
);
}
}
|
#!/bin/bash -l
#SBATCH -n 400 # Number of cores
#SBATCH -t 1-00:00:00 # Runtime in D-HH:MM:SS
#SBATCH -J Box1ReeSciama
#SBATCH -o ./logs/jobid_%j.out # File to which STDOUT will be written
#SBATCH -e ./logs/jobid_%j.err # File to which STDERR will be written
#SBATCH -p cosma7 # Partition to submit to
#SBATCH -A dp004
#SBATCH --exclusive
#SBATCH --mail-user=christoph.becker@durham.ac.uk
#SBATCH --mail-type=BEGIN
#SBATCH --mail-type=END
#SBATCH --mail-type=FAIL
# perpare
module purge
module load intel_comp/2018-update2 intel_mpi/2018
# module load hdfview
unset I_MPI_HYDRA_BOOTSTRAP
#rm ./logs/*
# compile
#make clean && make
# run
mpirun -np $SLURM_NTASKS ./bin/ramses3d ./namelist/cosmo_box1.nml
# report
echo ""
sacct -j $SLURM_JOBID --format=JobID,JobName,Partition,AllocCPUS,Elapsed,ExitCode
exit
|
package net.cp.jlibical;
import java.lang.String;
public class testjni
{
static final String content = "BEGIN:VCALENDAR\nVERSION:2.1\nBEGIN:VEVENT\nUID:abcd12345\nDTSTART:20020307T180000Z\nDTEND:20020307T190000Z\nSUMMARY:Important Meeting\nEND:VEVENT\nEND:VCALENDAR";
public static void main(String[] args)
{
// VAGENDA test case
ICalProperty calidProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_RELCALID_PROPERTY);
ICalProperty ownerProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_OWNER_PROPERTY);
calidProp.set_relcalid("1212");
ownerProp.set_owner("<NAME>");
VAgenda vAgenda = new VAgenda();
vAgenda.add_property(calidProp);
vAgenda.add_property(ownerProp);
System.out.println("VAgenda:\n" + vAgenda.as_ical_string());
// VEVENT test case
ICalProperty summProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_SUMMARY_PROPERTY);
ICalProperty startProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_DTSTART_PROPERTY);
ICalProperty endProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_DTEND_PROPERTY);
ICalProperty locationProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_LOCATION_PROPERTY);
ICalProperty descProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_DESCRIPTION_PROPERTY);
ICalTimeType starttime = new ICalTimeType();
starttime.setYear(2001);
starttime.setMonth(12);
starttime.setDay(21);
starttime.setHour(18);
starttime.setMinute(0);
starttime.setSecond(0);
starttime.setIs_utc(true);
System.out.println("done creating starttime");
ICalTimeType endtime = new ICalTimeType();
endtime.setYear(2002);
endtime.setMonth(1);
endtime.setDay(1);
endtime.setHour(8);
endtime.setMinute(0);
endtime.setSecond(0);
endtime.setIs_utc(true);
System.out.println("done creating endtime");
// START - get, set_exdate
ICalProperty property_tma = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_EXDATE_PROPERTY);
property_tma.set_exdate(starttime);
ICalTimeType starttime_return = property_tma.get_exdate();
System.out.println("****** property - exdate ******");
System.out.println("setYear=" + starttime_return.getYear());
System.out.println("setMonth=" + starttime_return.getMonth());
System.out.println("setDay=" + starttime_return.getDay());
System.out.println("setHour=" + starttime_return.getHour());
System.out.println("setMinute=" + starttime_return.getMinute());
System.out.println("setSecond=" + starttime_return.getSecond());
System.out.println("******* property - exdate *****");
// END - get, set exdate
// START - get, set exrule
ICalProperty property_exrule_tma = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_EXRULE_PROPERTY);
ICalRecurrenceType exrule_tma = new ICalRecurrenceType();
exrule_tma.setUntil(starttime);
exrule_tma.setFreq(ICalRecurrenceType.ICalRecurrenceTypeFrequency.ICAL_MINUTELY_RECURRENCE);
exrule_tma.setWeek_start(ICalRecurrenceType.ICalRecurrenceTypeWeekday.ICAL_SUNDAY_WEEKDAY);
short test_tma[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61};
exrule_tma.setBy_second(test_tma);
exrule_tma.setBy_minute(test_tma);
property_exrule_tma.set_exrule(exrule_tma);
ICalRecurrenceType recurence_tma_return = property_exrule_tma.get_exrule();
System.out.println("****** property - exrule ******");
System.out.println("setFreq=" + recurence_tma_return.getFreq());
System.out.println("setWeek_start=" + recurence_tma_return.getWeek_start());
System.out.println("setBy_second[30]=" + recurence_tma_return.getBy_secondIndexed(30));
System.out.println("setBy_minute[28]=" + recurence_tma_return.getBy_minuteIndexed(28));
System.out.println("****** property - exrule ******");
// END - get, set exrule
// START - get, set recurrenceid
ICalProperty property_recurrenceid_tma = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_RECURRENCEID_PROPERTY);
property_recurrenceid_tma.set_recurrenceid(starttime);
ICalTimeType recurrenceid_return = property_recurrenceid_tma.get_recurrenceid();
System.out.println("****** property - recurrenceid ******");
System.out.println("setYear=" + recurrenceid_return.getYear());
System.out.println("setMonth=" + recurrenceid_return.getMonth());
System.out.println("setDay=" + recurrenceid_return.getDay());
System.out.println("setHour=" + recurrenceid_return.getHour());
System.out.println("setMinute=" + recurrenceid_return.getMinute());
System.out.println("setSecond=" + recurrenceid_return.getSecond());
System.out.println("******* property - recurrenceid *****");
// END - get, set recurrenceid
// START - get, set rrule
ICalProperty property_rrule_tma = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_RRULE_PROPERTY);
ICalRecurrenceType rrule_tma = new ICalRecurrenceType();
rrule_tma.setUntil(starttime);
rrule_tma.setFreq(ICalRecurrenceType.ICalRecurrenceTypeFrequency.ICAL_MINUTELY_RECURRENCE);
rrule_tma.setWeek_start(ICalRecurrenceType.ICalRecurrenceTypeWeekday.ICAL_SUNDAY_WEEKDAY);
short test_hour_tma[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25};
rrule_tma.setBy_hour(test_hour_tma);
property_rrule_tma.set_rrule(rrule_tma);
ICalRecurrenceType rrule_tma_return = property_rrule_tma.get_rrule();
System.out.println("****** property - rrule ******");
System.out.println("setFreq=" + rrule_tma_return.getFreq());
System.out.println("setWeek_start=" + rrule_tma_return.getWeek_start());
System.out.println("setBy_hour[11]=" + rrule_tma_return.getBy_hourIndexed(11));
System.out.println("****** property - rrule ******");
// END - get, set rrule
// START - get, set freebusy
ICalProperty property_freebusy_tma = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_FREEBUSY_PROPERTY);
ICalPeriodType period_tma = new ICalPeriodType();
ICalDurationType duration_tma = new ICalDurationType();
duration_tma.setDays((long) 0);
duration_tma.setHours((long) 10);
duration_tma.setMinutes((long) 15);
period_tma.setStart(starttime);
period_tma.setEnd(endtime);
period_tma.setDuration(duration_tma);
property_freebusy_tma.set_freebusy(period_tma);
ICalPeriodType period_tma_return = property_freebusy_tma.get_freebusy();
ICalTimeType start_tma_return = period_tma_return.getStart();
ICalTimeType end_tma_return = period_tma_return.getEnd();
ICalDurationType duration_tma_return = period_tma_return.getDuration();
System.out.println("****** property - freebusy - start ******");
System.out.println("setYear=" + start_tma_return.getYear());
System.out.println("setMonth=" + start_tma_return.getMonth());
System.out.println("setDay=" + start_tma_return.getDay());
System.out.println("setHour=" + start_tma_return.getHour());
System.out.println("setMinute=" + start_tma_return.getMinute());
System.out.println("setSecond=" + start_tma_return.getSecond());
System.out.println("******* property - freebusy - start *****");
System.out.println("****** property - freebusy - end ******");
System.out.println("setYear=" + end_tma_return.getYear());
System.out.println("setMonth=" + end_tma_return.getMonth());
System.out.println("setDay=" + end_tma_return.getDay());
System.out.println("setHour=" + end_tma_return.getHour());
System.out.println("setMinute=" + end_tma_return.getMinute());
System.out.println("setSecond=" + end_tma_return.getSecond());
System.out.println("******* property - freebusy - end *****");
System.out.println("****** property - freebusy - duration ******");
System.out.println("setYear=" + duration_tma_return.getDays());
System.out.println("setMonth=" + duration_tma_return.getHours());
System.out.println("setDay=" + duration_tma_return.getMinutes());
System.out.println("******* property - freebusy - duration *****");
// END - get, set freebusy
// START - get, set dtstamp
ICalProperty property_dtstamp_tma = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_DTSTAMP_PROPERTY);
property_dtstamp_tma.set_dtstamp(starttime);
ICalTimeType dtstamp_tma_return = property_dtstamp_tma.get_dtstamp();
System.out.println("****** property - dtstamp ******");
System.out.println("setYear=" + dtstamp_tma_return.getYear());
System.out.println("setMonth=" + dtstamp_tma_return.getMonth());
System.out.println("setDay=" + dtstamp_tma_return.getDay());
System.out.println("setHour=" + dtstamp_tma_return.getHour());
System.out.println("setMinute=" + dtstamp_tma_return.getMinute());
System.out.println("setSecond=" + dtstamp_tma_return.getSecond());
System.out.println("******* property - dtstamp *****");
// END - get, set dtstamp
// START - get, set attendee
ICalProperty property_attendee_tma = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_ATTENDEE_PROPERTY);
property_attendee_tma.set_attendee("John");
String attendee_tma_return = property_attendee_tma.get_attendee();
System.out.println("****** property - attendee ******");
System.out.println("setAttendee=" + attendee_tma_return);
System.out.println("****** property - attendee ******");
// END - get, set attendee
// START - get, set comment
ICalProperty property_comment_tma = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_COMMENT_PROPERTY);
property_comment_tma.set_comment("John");
String comment_tma_return = property_comment_tma.get_comment();
System.out.println("****** property - comment ******");
System.out.println("setComment=" + comment_tma_return);
System.out.println("****** property - comment ******");
// END - get, set comment
// START - get, set organizer
ICalProperty property_organizer_tma = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_ORGANIZER_PROPERTY);
property_organizer_tma.set_organizer("John");
String organizer_tma_return = property_organizer_tma.get_organizer();
System.out.println("****** property - organizer ******");
System.out.println("setOrganizer=" + organizer_tma_return);
System.out.println("****** property - organizer ******");
// END - get, set organizer
summProp.set_summary("New Year's Eve Party, and more");
System.out.println("done setting summProp");
startProp.set_dtstart(starttime);
System.out.println("done setting startProp");
endProp.set_dtend(endtime);
System.out.println("done setting endProp");
locationProp.set_location("Bothin, Marin County, CA, USA");
System.out.println("done setting locationProp\n");
descProp.set_description("Drive carefully; come to have fun!");
System.out.println("done setting descProp\n");
VEvent vEvent = new VEvent();
vEvent.add_property(summProp);
vEvent.add_property(startProp);
vEvent.add_property(endProp);
vEvent.add_property(locationProp);
vEvent.add_property(descProp);
ICalTimeType sTime = vEvent.get_dtstart();
ICalTimeType eTime = vEvent.get_dtend();
//System.out.println("VEvent:\n" + vEvent.as_ical_string());
System.out.println("Summary: \n" + vEvent.get_summary());
System.out.println("DTSTART: \n" + sTime.getYear() + sTime.getMonth() + sTime.getDay() +
sTime.getHour() + sTime.getMinute() + sTime.getSecond());
System.out.println("DTEND: \n" + eTime.getYear() + eTime.getMonth() + eTime.getDay() +
eTime.getHour() + eTime.getMinute() + eTime.getSecond());
System.out.println("Location: \n" + vEvent.get_location());
System.out.println("Description: \n" +vEvent.get_description());
VComponent ic = new VComponent(content);
if (ic == null)
System.err.println("Failed to parse component");
System.out.println("VComponent:\n" + ic.as_ical_string());
// component is wrapped within BEGIN:VCALENDAR END:VCALENDAR
// we need to unwrap it.
VEvent sub_ic = (VEvent)ic.get_first_component(VComponent.ICalComponentKind.ICAL_VEVENT_COMPONENT);
if (sub_ic == null)
System.out.println("Failed to get subcomponent");
while (sub_ic != null)
{
System.out.println("subcomponent:\n" + sub_ic.as_ical_string());
sub_ic = (VEvent)ic.get_next_component(VComponent.ICalComponentKind.ICAL_VEVENT_COMPONENT);
}
// START - get, set recurrenceid
ICalTimeType time_tma = new ICalTimeType();
time_tma.setYear(2002);
time_tma.setMonth(2);
time_tma.setDay(2);
time_tma.setHour(2);
time_tma.setMinute(2);
time_tma.setSecond(2);
time_tma.setIs_utc(true);
ic.set_recurrenceid(time_tma);
ICalTimeType time_tma_return = new ICalTimeType();
time_tma_return = ic.get_recurrenceid();
System.out.println("****** vcomponent - recurrenceid ******");
System.out.println("setYear=" + time_tma_return.getYear());
System.out.println("setMonth=" + time_tma_return.getMonth());
System.out.println("setDay=" + time_tma_return.getDay());
System.out.println("setHour=" + time_tma_return.getHour());
System.out.println("setMinute=" + time_tma_return.getMinute());
System.out.println("setSecond=" + time_tma_return.getSecond());
System.out.println("****** vcomponent - recurrenceid ******");
// END - get, set recurrenceid
// START - get, set dtstamp
ic.set_dtstamp(time_tma);
ICalTimeType vcomponent_dtstamp_tma_return = ic.get_dtstamp();
System.out.println("****** vcomponent - dtstamp ******");
System.out.println("setYear=" + vcomponent_dtstamp_tma_return.getYear());
System.out.println("setMonth=" + vcomponent_dtstamp_tma_return.getMonth());
System.out.println("setDay=" + vcomponent_dtstamp_tma_return.getDay());
System.out.println("setHour=" + vcomponent_dtstamp_tma_return.getHour());
System.out.println("setMinute=" + vcomponent_dtstamp_tma_return.getMinute());
System.out.println("setSecond=" + vcomponent_dtstamp_tma_return.getSecond());
System.out.println("****** vcomponent - dtstamp ******");
// END - get, set dtstamp
// VTODO test cases
ICalProperty statusProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_STATUS_PROPERTY);
ICalProperty dueProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_DUE_PROPERTY);
ICalTimeType duetime = new ICalTimeType();
duetime.setYear(2002);
duetime.setMonth(12);
duetime.setDay(21);
duetime.setHour(18);
duetime.setMinute(0);
duetime.setSecond(0);
duetime.setIs_utc(true);
System.out.println("done creating duetime");
statusProp.set_status(ICalProperty.ICalPropertyStatus.ICAL_STATUS_COMPLETED);
dueProp.set_due(duetime);
VToDo vtodo = new VToDo();
vtodo.add_property(statusProp);
vtodo.add_property(dueProp);
System.out.println("VToDo:\n" + vtodo.as_ical_string());
// VALARM test cases
VAlarm valarm = new VAlarm();
System.out.println("created valarm");
// 1. Create a ICAL_DURATION_PROPERTY using the TimePeriod.
ICalDurationType duration = new ICalDurationType();
duration.setDays((long) 0);
duration.setHours((long) 0);
duration.setMinutes((long) 15);
System.out.println("created duration object");
// Since we want to trigger before the event or task,
// we always want to set this to 1. If we say this is not
// a negative duration, that means the alarm will trigger
// AFTER the event or task start or due date, which is useless.
duration.setIs_neg(1);
// 2. Create a ICalTriggerType oject and set the duration on it.
ICalTriggerType trigger = new ICalTriggerType();
trigger.setDuration(duration);
System.out.println("set trigger to duration object");
// 3. Create a trigger ICalProperty and set the trigger on it.
ICalProperty triggerProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_TRIGGER_PROPERTY);
System.out.println("created trigger property");
triggerProp.set_trigger(trigger);
System.out.println("set trigger property");
trigger = triggerProp.get_trigger();
System.out.println("get trigger property");
// 4. set the trigger property on the Valarm object.
valarm.add_property(triggerProp);
System.out.println("VAlarm:\n" + valarm.as_ical_string());
// 5. create attendee property
String userEmail = "userid@domain";
ICalProperty attendeeProp = new ICalProperty(ICalProperty.ICalPropertyKind.ICAL_ATTENDEE_PROPERTY);
attendeeProp.set_attendee("MAILTO:" + userEmail);
System.out.println("set attendee property");
userEmail = attendeeProp.get_attendee();
System.out.println("get attendee property");
valarm.add_property(attendeeProp);
System.out.println("VAlarm:\n" + valarm.as_ical_string());
// START - get, set_role
ICalParameter parameter_role_tma = new ICalParameter(ICalParameter.ICalParameterKind.ICAL_ROLE_PARAMETER);
parameter_role_tma.set_role(ICalParameter.ICalParameterRole.ICAL_ROLE_REQPARTICIPANT);
int role_tma_return = parameter_role_tma.get_role();
System.out.println("******* parameter - role *****");
System.out.println("setRole=" + role_tma_return);
System.out.println("******* parameter - role *****");
// END - get, set_role
// START - get, set_partstat
ICalParameter parameter_partstat_tma = new ICalParameter(ICalParameter.ICalParameterKind.ICAL_PARTSTAT_PARAMETER);
parameter_partstat_tma.set_partstat(ICalParameter.ICalParameterPartStat.ICAL_PARTSTAT_DECLINED);
int partstat_tma_return = parameter_partstat_tma.get_partstat();
System.out.println("******* parameter - partstat *****");
System.out.println("setPartstat=" + partstat_tma_return);
System.out.println("******* parameter - partstat *****");
// END - get, set_partstat
}
}
|
#!/bin/bash
CUDA_VISIBLE_DEVICES=0 python scripts/train.py \
--dataset_type=ffhq_encode \
--exp_dir=./exp_dir/train-ffhq \
--start_from_latent_avg \
--use_w_pool \
--w_discriminator_lambda 0.1 \
--progressive_start 20000 \
--id_lambda 0.5 \
--val_interval 10000 \
--max_steps 200000 \
--stylegan_size 512 \
--workers 8 \
--batch_size 8 \
--test_batch_size 4 \
--test_workers 4
|
def maxsum(arr):
if len(arr) == 0:
return 0
incl = arr[0]
excl = 0
for i in arr[1:]:
new_excl = max(incl, excl)
incl = excl + i
excl = new_excl
# return max of incl and excl
return max(incl, excl) |
#!/bin/bash -xe
apt-get update
apt-get install -y apache2 libapache2-mod-php
cat > /var/www/html/index.php <<'EOF'
<?php
function metadata_value($value) {
$opts = [
"http" => [
"method" => "GET",
"header" => "Metadata-Flavor: Google"
]
];
$context = stream_context_create($opts);
$content = file_get_contents("http://metadata/computeMetadata/v1/$value", false, $context);
return $content;
}
?>
<!doctype html>
<html>
<head>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.0/js/materialize.min.js"></script>
<title>Frontend Web Server</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col s2"> </div>
<div class="col s8">
<div class="card blue">
<div class="card-content white-text">
<div class="card-title">Backend that serviced this request</div>
</div>
<div class="card-content white">
<table class="bordered">
<tbody>
<tr>
<td>Name</td>
<td><?php printf(metadata_value("instance/name")) ?></td>
</tr>
<tr>
<td>ID</td>
<td><?php printf(metadata_value("instance/id")) ?></td>
</tr>
<tr>
<td>Hostname</td>
<td><?php printf(metadata_value("instance/hostname")) ?></td>
</tr>
<tr>
<td>Zone</td>
<td><?php printf(metadata_value("instance/zone")) ?></td>
</tr>
<tr>
<td>Machine Type</td>
<td><?php printf(metadata_value("instance/machine-type")) ?></td>
</tr>
<tr>
<td>Project</td>
<td><?php printf(metadata_value("project/project-id")) ?></td>
</tr>
<tr>
<td>Internal IP</td>
<td><?php printf(metadata_value("instance/network-interfaces/0/ip")) ?></td>
</tr>
<tr>
<td>External IP</td>
<td><?php printf(metadata_value("instance/network-interfaces/0/access-configs/0/external-ip")) ?></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="card blue">
<div class="card-content white-text">
<div class="card-title">Proxy that handled this request</div>
</div>
<div class="card-content white">
<table class="bordered">
<tbody>
<tr>
<td>Address</td>
<td><?php printf($_SERVER["HTTP_HOST"]); ?></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col s2"> </div>
</div>
</div>
</html>
EOF
sudo mv /var/www/html/index.html /var/www/html/index.html.old
systemctl enable apache2
systemctl restart apache2
|
<reponame>Jimmt/HologramClock
package com.jimmt.HologramClock;
import com.badlogic.gdx.graphics.g2d.ParticleEffect;
import com.badlogic.gdx.graphics.g2d.ParticleEmitter;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
public class Tile extends Group {
Image background;
DisplayEffect effect;
int index;
public Tile(DisplayEffect effect, int index) {
this.effect = effect;
this.index = index;
ParticleEffectActor actor = new ParticleEffectActor(effect.getPaths()[index], "effects");
ParticleEffect particleEffect = actor.effect;
background = new Image(Assets.getTex("tile.png"));
float scale = 1 / 4f;
for (int i = 0; i < particleEffect.getEmitters().size; i++) {
particleEffect.getEmitters().get(i).getScale().setHigh(particleEffect.getEmitters().get(i).getScale().getHighMax() * scale);
particleEffect.getEmitters().get(i).getVelocity().setHigh(particleEffect.getEmitters().get(i).getVelocity().getHighMax() * scale);
if(particleEffect.getEmitters().get(i).getXOffsetValue().getLowMin() != 0){
particleEffect.getEmitters().get(i).getXOffsetValue().setLow(-getWidth() / 3, getWidth() / 3);
}
}
// ParticleEmitter firstEmitter = particleEffect.getEmitters().get(0);
// float verticalDistance = firstEmitter.getVelocity().getHighMax() * (firstEmitter.getLife().getHighMax() - firstEmitter.getLife().getHighMin()) / 200f;
// System.out.println(firstEmitter.getVelocity().getHighMax() + " " + (firstEmitter.getLife().getHighMax() - firstEmitter.getLife().getHighMin()) / 2);
actor.setPosition(getWidth() / 2, getHeight() / 3);
addActor(background);
addActor(actor);
}
public int getIndex(){
return index;
}
@Override
public void setWidth(float width){
super.setWidth(width);
background.setWidth(width);
}
@Override
public void setHeight(float height){
super.setHeight(height);
background.setHeight(height);
}
@Override
public float getWidth(){
return background.getWidth();
}
@Override
public float getHeight(){
return background.getHeight();
}
}
|
<filename>ram.go<gh_stars>1-10
package main
type RAM struct {
Memory [2048]uint8
}
|
package com.biniam.designpatterns.bridge.foobarmotorco;
/**
* @author <NAME>
*/
public abstract class AbstractEngine implements Engine {
private int size;
private boolean turbo;
private boolean running;
private int power;
public AbstractEngine(int size, boolean turbo) {
this.size = size;
this.turbo = turbo;
this.running = false;
this.power = 0;
}
@Override
public int getSize() {
return size;
}
@Override
public boolean isTurbo() {
return turbo;
}
@Override
public void start() {
running = true;
System.out.println("Engine started");
}
@Override
public void stop() {
running = false;
power = 0;
System.out.println("Engine stopped");
}
@Override
public void increasePower() {
if (running && power < 10) {
power++;
System.out.println("Engine power increased to " + power);
}
}
@Override
public void decreasePower() {
if (running && power > 0) {
power--;
System.out.println("Engine power decreased to " + power);
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "(size=" + size + ", turbo=" + turbo + ')';
}
}
|
import { Component } from '@angular/core';
@Component({
selector: 'config',
templateUrl: './app/modules/config/components/tpl/config.component.html'
})
export class ConfigComponent {
}
|
# encoding: UTF-8
class Treet::Gitfarm < Treet::Farm
attr_reader :author
def initialize(opts)
raise ArgumentError, "No git farm without an author for commits" unless opts[:author]
super
@repotype = Treet::Gitrepo
@author = opts[:author]
end
def self.plant(opts)
super(opts.merge(:repotype => Treet::Gitrepo))
end
def repos
super(:author => author)
end
def repo(id, opts = {})
super(id, opts.merge(:author => author))
end
def add(hash, opts = {})
repo = super(hash, opts.merge(:author => author))
if opts[:tag]
repo.tag(opts[:tag])
end
repo
end
end
|
import Client from "../struct/Client"
import GuildMember from "../struct/discord/GuildMember"
import Roles from "../util/roles"
export default async function guildMemberUpdate(
this: Client,
oldMember: GuildMember,
newMember: GuildMember
): Promise<void> {
if (newMember.guild.id === this.config.guilds.youtube) {
const main = this.guilds.cache.get(this.config.guilds.main)
const mainMember: GuildMember = await main.members
.fetch({ user: newMember.user, cache: true })
.catch(() => null)
if (!mainMember) return
const mainRole = main.roles.cache.find(
role => role.name === Roles.PIPPEN_YOUTUBE_GROUP
)
const was = oldMember.hasStaffPermission(Roles.YOUTUBE)
const is = newMember.hasStaffPermission(Roles.YOUTUBE)
if (was && !is) mainMember.roles.remove(mainRole).catch(() => null)
else if (is && !was) mainMember.roles.add(mainRole).catch(() => null)
}
}
|
# Copyright (c) 2016 Intel Corporation
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Author: Irene Liew <irene dot liew at intel dot com>
#This script launches pktgen. The parameters allow DPDK to run on CPUs 2-6, allocate 512M of memory per socket, and specify that the hugepage memory for this process should have prefix of 'pg' to distinguish it from other applications that might be using the hugepages. The pktgen parameters specify that it should run in promiscuous mode and that
# core 2 should handle port 0 rx
# core 4 should handle port 0 tx
# core 3 should handle port 1 rx
# core 5 should handle port 1 tx
export PKTGEN_DIR=/root/pktgen-3.0.14
cd $PKTGEN_DIR
./app/app/x86_64-native-linuxapp-gcc/app/pktgen -c 0x3E -n 4 --proc-type auto --socket-mem 512 --file-prefix pg -- -T -p 0x3 -P -m "[2:4].0,[3:5].1"
|
#!/usr/bin/env bash
set -e
if [ "$#" -lt 3 ]; then
(2> echo "Usage:\n$0 arch template_fname output_fname")
exit 1
fi
ARCH="$1"
FNAME="$2"
DEST="$3"
golang_dl_url=""
from_image=""
# the default Docker instruction for architectures supported by it
node_install="RUN curl -sL https://deb.nodesource.com/setup_4.x | bash - \&\& apt-get install -y nodejs"
case "$ARCH" in
('armhf')
from_image="arm32v7/ubuntu:16.04"
node_install="RUN apt-get install -y nodejs npm"
golang_arch="armv6l"
;;
('arm64')
from_image="arm64v8/ubuntu:16.04"
golang_arch="arm64"
;;
*amd64)
from_image="ubuntu:16.04"
golang_arch="amd64"
;;
('ppc64el')
from_image="ppc64le/ubuntu:16.04"
node_install="RUN apt-get install -y nodejs npm"
golang_arch="ppc64le"
;;
(*)
(>&2 echo "Unknown or unsupported architecture: $1")
exit 1
;;
esac
golang_dl_url="https://storage.googleapis.com/golang/go1.14.linux-${golang_arch}.tar.gz"
sed "s,##from_image##,$from_image," "$FNAME" > "$DEST"
sed -i.bak "s,##arch##,$ARCH," "$DEST" && rm -f "$DEST".bak
sed -i.bak "s,##node_install##,$node_install," "$DEST" && rm -f "$DEST".bak
sed -i.bak "s,##golang_dl_url##,$golang_dl_url," "$DEST" && rm -f "$DEST".bak
|
SELECT * FROM Customer WHERE Age > 30 AND City = 'Toronto'; |
public class calculate {
public static void main(String[] args){
float x = Float.parseFloat(args[1]);
float y = Float.parseFloat(args[2]);
if (args[0].equals("somar")) {
sum(x, y);
} else if (args[0].equals("subtrair")) {
minus(x, y);
}
else if (args[0].equals("multiplicar")) {
multiply(x, y);
} else{
division(x, y);
}
}
static float sum(float x, float y){
System.out.println(x + y);
float sum = x + y;
return sum;
}
static float minus(float x, float y){
System.out.println(x - y);
float minus = x - y;
return minus;
}
static float multiply(float x, float y){
System.out.println(x * y);
float multiply = x * y;
return multiply;
}
static float division(float x, float y){
System.out.println(x / y);
float division = x / y;
return division;
}
}
|
#! /bin/sh
export PATH=$PATH:/opt/local/bin:/opt/local/sbin:/opt/local/share/man:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin
DIR=$(cd "$(dirname "$0")"; pwd)
DIR=$(dirname "$DIR")
DIR=$(dirname "$DIR")
DIR=$(dirname "$DIR")
MDIR=$(dirname "$DIR")
VERSION=$1
LIBNAME=curl
echo "load $LIBNAME start"
NON_ZTS_FILENAME=`ls $DIR/php/php$VERSION/lib/php/extensions | grep no-debug-non-zts`
extFile=$DIR/php/php$VERSION/lib/php/extensions/${NON_ZTS_FILENAME}/${LIBNAME}.so
if [ ! -f $extFile ]; then
echo "load $LIBNAME fail"
exit 1
fi
echo "" >> $DIR/php/php$VERSION/etc/php.ini
echo "[${LIBNAME}]" >> $DIR/php/php$VERSION/etc/php.ini
echo "extension=${LIBNAME}.so" >> $DIR/php/php$VERSION/etc/php.ini
$MDIR/bin/reinstall/reload.sh $VERSION
echo "load $LIBNAME end"
|
FIRST_RUN=1
DATA_ROOT="data/"
NER_DATASET=$DATA_ROOT/ner_dataset.pk
CHECKPOINT_ROOT="checkpoint/"
NER_CHECKPOINT=$CHECKPOINT_ROOT/ner.th
CHECKPOINT_NAME="p_ner0"
green=`tput setaf 2`
reset=`tput sgr0`
if [ $FIRST_RUN == 1 ] && [ ! -e $NER_DATASET ]; then
echo ${green}=== Downloading Dataset ===${reset}
mkdir -p DATA_ROOT
curl http://dmserv4.cs.illinois.edu/ner_dataset.pk -o $NER_DATASET
fi
if [ $FIRST_RUN == 1 ] && [ ! -e $NER_CHECKPOINT ]; then
echo ${green}=== Downloading Checkpoint ===${reset}
mkdir -p CHECKPOINT_ROOT
curl http://dmserv4.cs.illinois.edu/ner.th -o $NER_CHECKPOINT
fi
echo ${green}=== Pruning NER Model ===${reset}
python prune_sparse_seq.py --cp_root $CHECKPOINT_ROOT --checkpoint_name $CHECKPOINT_NAME --corpus $NER_DATASET --load_seq $NER_CHECKPOINT --seq_lambda0 0.05 --seq_lambda1 2
|
<reponame>tdrv90/freeCodeCamp
// Modify the function increment by adding default parameters so that
// it will add 1 to number if value is not specified.
// The result of increment(5, 2) should be 7.
// The result of increment(5) should be 6.
// A default parameter value of 1 should be used for value.
const increment = (number, value = 1) => number + value;
console.log(increment(5, 2)); // returns 7
console.log(increment(5)); // returns 6 |
#!/bin/bash
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
set -e
SOURCE_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <version> <rc-num>"
exit
fi
version=$1
rc=$2
if [ -d tmp/ ]; then
echo "Cannot run: tmp/ exists"
exit
fi
tag=apache-arrow-${version}
tagrc=${tag}-rc${rc}
echo "Preparing source for tag ${tag}"
release_hash=`git rev-list $tag 2> /dev/null | head -n 1 `
if [ -z "$release_hash" ]; then
echo "Cannot continue: unknown git tag: $tag"
exit
fi
echo "Using commit $release_hash"
tarball=${tag}.tar.gz
extract_dir=tmp-apache-arrow
rm -rf ${extract_dir}
# be conservative and use the release hash, even though git produces the same
# archive (identical hashes) using the scm tag
git archive ${release_hash} --prefix ${extract_dir}/ | tar xf -
# build Apache Arrow C++ before building Apache Arrow GLib because
# Apache Arrow GLib requires Apache Arrow C++.
mkdir -p ${extract_dir}/cpp/build
cpp_install_dir=${PWD}/${extract_dir}/cpp/install
cd ${extract_dir}/cpp/build
cmake .. \
-DCMAKE_INSTALL_PREFIX=${cpp_install_dir} \
-DARROW_BUILD_TESTS=no
make -j8
make install
cd -
# build source archive for Apache Arrow GLib by "make dist".
cd ${extract_dir}/c_glib
./autogen.sh
./configure \
PKG_CONFIG_PATH=$cpp_install_dir/lib/pkgconfig \
--enable-gtk-doc
LD_LIBRARY_PATH=$cpp_install_dir/lib:$LD_LIBRARY_PATH make -j8
make dist
tar xzf *.tar.gz
rm *.tar.gz
cd -
rm -rf tmp-c_glib/
mv ${extract_dir}/c_glib/apache-arrow-glib-* tmp-c_glib/
rm -rf ${extract_dir}
# replace c_glib/ by tar.gz generated by "make dist"
rm -rf ${tag}
git archive $release_hash --prefix ${tag}/ | tar xf -
rm -rf ${tag}/c_glib
mv tmp-c_glib ${tag}/c_glib
# Create new tarball from modified source directory
tar czf ${tarball} ${tag}
rm -rf ${tag}
${SOURCE_DIR}/run-rat.sh ${tarball}
# sign the archive
gpg --armor --output ${tarball}.asc --detach-sig ${tarball}
gpg --print-md MD5 ${tarball} > ${tarball}.md5
sha1sum $tarball > ${tarball}.sha1
sha256sum $tarball > ${tarball}.sha256
sha512sum $tarball > ${tarball}.sha512
# check out the arrow RC folder
svn co --depth=empty https://dist.apache.org/repos/dist/dev/arrow tmp
# add the release candidate for the tag
mkdir -p tmp/${tagrc}
cp ${tarball}* tmp/${tagrc}
svn add tmp/${tagrc}
svn ci -m 'Apache Arrow ${version} RC${rc}' tmp/${tagrc}
# clean up
rm -rf tmp
echo "Success! The release candidate is available here:"
echo " https://dist.apache.org/repos/dist/dev/arrow/${tagrc}"
echo ""
echo "Commit SHA1: ${release_hash}"
|
#!/bin/bash
set -e
current_folder=$(pwd)
cd standalone
terraform init
terraform apply \
-var-file ../configuration.tfvars \
-var-file ../nsg.tfvars\
-var-file ../public-ip-addresses.tfvars \
-var-file ../routes.tfvars \
-var tags='{testing_job_id='"${1}"'}' \
-var var_folder_path=${current_folder} \
-input=false \
-auto-approve
terraform destroy \
-var-file ../configuration.tfvars \
-var-file ../nsg.tfvars\
-var-file ../public-ip-addresses.tfvars \
-var-file ../routes.tfvars \
-var tags='{testing_job_id='"${1}"'}' \
-var var_folder_path=${current_folder} \
-input=false \
-auto-approve
|
#!/usr/bin/env bash
set -euo pipefail
pushd "$HOME/.dotfiles"
# install brew and the brewfile
if ! command -v brew &>/dev/null; then
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew bundle install --file=Brewfile
fi
# create deeplinks to the home folder
STOW_FOLDERS=(
"alacritty"
"nvim"
"codespell"
"private"
"tmux"
"qmk"
"zsh"
)
for folder in "${STOW_FOLDERS[@]}"; do
stow -D "$folder"
stow "$folder"
done
# clone tmux plugin manager
if [ ! -d ~/.tmux/plugins ]; then
mkdir -p ~/.tmux
git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm
fi
# clone qmk firmware
if [ ! -d ~/qmk_firmware ]; then
git clone https://github.com/qmk/qmk_firmware ~/qmk_firmware
qmk setup -y
qmk config user.keyboard=splitkb/kyria/rev1
qmk config user.keymap=pgherveou
qmk generate-compilation-database
ln -s ~/qmk_firmware/compile_commands.json "$PWD"
fi
# install global npm packages
IFS=' ' read -r -a NPM_PKGS_LIST <<<"$NPM_PKGS"
npm install -g "${NPM_PKGS_LIST[@]}"
# install global lua packages
IFS=' ' read -r -a LUA_PKGS_LIST <<<"$LUA_PKGS"
luarocks install "${LUA_PKGS_LIST[@]}"
# install vimplug
vimplug="$HOME/.local/share/nvim/site/autoload/plug.vim"
if [ ! -f vimplug ]; then
curl -fLo "$vimplug" --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
fi
# setup spectacle
cp -r spectacles/Shortcuts.json "$HOME/Library/Application Support/Spectacle/Shortcuts.json" 2>/dev/null
popd
|
def process_parameters(service, params):
if service not in ["base", "pubmed"]:
return None
if service == "pubmed":
params.pop("article_types", None) # Remove "article_types" if present
params["limit"] = 100
if service == "base":
params["limit"] = 120
doctypes = params.get("article_types")
if doctypes:
try:
doctypes_list = eval(doctypes) # Safely evaluate the string as a list
if isinstance(doctypes_list, list):
params["document_types"] = doctypes_list
except (SyntaxError, NameError, TypeError):
pass # Ignore if "article_types" is not a valid list
return params |
<gh_stars>1-10
# encoding: UTF-8
require 'rspec'
require 'net/http'
require 'webmock/rspec'
require_relative '../../lib/mockserver-client'
RSpec.configure do |config|
include WebMock::API
include MockServer
include MockServer::UtilityMethods
include MockServer::Model::DSL
# Only accept expect syntax do not allow old should syntax
config.expect_with :rspec do |c|
c.syntax = :expect
end
end
describe MockServer::MockServerClient do
let(:client) { MockServer::MockServerClient.new('localhost', 8098) }
before do
# To suppress logging output to standard output, write to a temporary file
client.logger = LoggingFactory::DEFAULT_FACTORY.log('test', output: 'tmp.log', truncate: true)
end
def create_agent
uri = URI('http://api.nsa.gov:1337/agent')
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.path, 'Content-Type' => 'application/json')
req.body = { name: '<NAME>', role: 'agent' }.to_json
res = http.request(req)
puts "response #{res.body}"
rescue => e
puts "failed #{e}"
end
it 'setup complex expectation' do
WebMock.allow_net_connect!
# given
mock_expectation = expectation do |expectation|
expectation.request do |request|
request.method = 'POST'
request.path = '/somePath'
request.query_string_parameters << parameter('param', 'someQueryStringValue')
request.headers << header('Header', 'someHeaderValue')
request.cookies << cookie('cookie', 'someCookieValue')
request.body = exact('someBody')
end
expectation.response do |response|
response.status_code = 201
response.headers << header('header', 'someHeaderValue')
response.body = body('someBody')
response.delay = delay_by(:SECONDS, 1)
end
expectation.times = exactly(1)
end
# and
expect(client.register(mock_expectation).code).to eq(201)
# when
uri = URI('http://localhost:8098/somePath')
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new('/somePath?param=someQueryStringValue')
req['Header'] = 'someHeaderValue'
req['Cookie'] = 'cookie=someCookieValue'
req.body = 'someBody'
res = http.request(req)
# then
expect(res.code).to eq('201')
expect(res.body).to eq('someBody')
WebMock.disable_net_connect!
end
end
|
<filename>_tests_/Manager.test.js
const Manager = require('../lib/Manager');
test('properties of manager object', () => {
const manager = new Manager('Jen', '0001', '<EMAIL>', '1');
expect(manager.name).toEqual('Jen');
expect(manager.id).toEqual('0001');
expect(manager.email).toEqual('<EMAIL>');
expect(manager.office).toEqual('1');
})
test("get manager's info", () => {
const manager = new Manager('Jen', '0001', '<EMAIL>', '1')
expect(manager.getName()).toBe('Jen');
expect(manager.getId()).toEqual('0001');
expect(manager.getEmail()).toEqual('<EMAIL>');
expect(manager.getOffice()).toEqual('1');
}) |
#!/bin/sh
# Any subsequent(*) commands which fail will cause the shell script to exit immediately
set -e
./bin/build.sh
./bin/install.sh |
#!/bin/bash
#DEPLOYING TO ECS USING CLOUDFORMATION SERVICE SCRIPT
echo "DEPLOYING PRODUCT MANAGER SERVICE VIA CFN CLI"
aws cloudformation create-stack --stack-name ProductManagerService --template-body file://../../../templates/product-manager-v1.template --parameters ParameterKey=BaselineStackName,ParameterValue=${BASELINE_STACK} --capabilities CAPABILITY_IAM
aws cloudformation wait stack-create-complete --stack-name ProductManagerService
echo "STACK CREATE COMPLETE" |
<gh_stars>1-10
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QDropEvent>
#include <QImage>
#include <QMimeData>
#include <QPainter>
#include <QTime>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
setAcceptDrops(true);
QWidget * displayWidget = new QWidget(this);
setCentralWidget(displayWidget);
displayWidget->installEventFilter(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::dragEnterEvent(QDragEnterEvent* event)
{
if (event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void MainWindow::dropEvent(QDropEvent* event)
{
QTime timer;
timer.start();
_colorsData = std::vector<ColorData>(0xFFFFFFU + 1U, {{0.0, 0.0, 0.0}, 0U, 0ULL});
qDebug() << "Clearing _colorsData took" << timer.elapsed() << "ms";
timer.restart();
if (event->mimeData()->hasUrls())
{
QImage img(event->mimeData()->urls().front().toLocalFile());
for (int h = 0; h < img.height(); ++h)
{
for (int w = 0; w < img.width(); ++w)
{
QRgb color = img.pixel(w, h);
++_colorsData[color & RGB_MASK].count;
_colorsData[color & RGB_MASK].colorRgb = color;
}
}
}
qDebug() << "Scanning the image took" << timer.elapsed() << "ms";
timer.restart();
_colorsData.erase(std::remove_if(_colorsData.begin(), _colorsData.end(), [](const ColorData& colorData){
return colorData.count == 0;
}), _colorsData.end());
qDebug() << "Erasing non-existing colors took" << timer.elapsed() << "ms";
timer.restart();
std::sort(_colorsData.begin(), _colorsData.end(), [](const ColorData& l, const ColorData& r){
return l.count > r.count;
});
qDebug() << "Sorting colors took" << timer.elapsed() << "ms";
for (ColorData& color: _colorsData)
color.colorLab = rgb2lab(color.colorRgb);
centralWidget()->update();
}
bool MainWindow::eventFilter(QObject * object, QEvent * event)
{
if (event->type() == QEvent::Paint && _colorsData.size() >= 3)
{
QPainter p((QWidget*)object);
auto color = _colorsData.begin();
p.fillRect(0, 0, width()/3, height(), QColor::fromRgb(((color->colorRgb) >> 16) & 0xFFU, ((color->colorRgb) >> 8) & 0xFFU, (color->colorRgb) & 0xFFU));
color = color + 1000;
p.fillRect(width()/3, 0, width()/3, height(), QColor::fromRgb(((color->colorRgb) >> 16) & 0xFFU, ((color->colorRgb) >> 8) & 0xFFU, (color->colorRgb) & 0xFFU));
color += 1000;
p.fillRect(2 * width() / 3, 0, width() / 3, height(), QColor::fromRgb(((color->colorRgb) >> 16) & 0xFFU, ((color->colorRgb) >> 8) & 0xFFU, (color->colorRgb) & 0xFFU));
return false;
}
return QMainWindow::eventFilter(object, event);
}
|
<reponame>xblia/Upgrade-service-for-java-application<filename>VersionMonitorPro/src/com/cats/version/httpserver/msg/MessageHandlerGetOnlineUser.java
/*
* Copyright 2015 lixiaobo
*
* VersionUpgrade project licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.cats.version.httpserver.msg;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.cats.version.msg.IMessageDef;
import com.cats.version.msg.IMessageGetOnlineUserReq;
import com.cats.version.msg.IMessageGetOnlineUserRsp;
import com.cats.version.ui.UserInfo;
import com.cats.version.ui.UserTableModel;
import io.netty.channel.ChannelHandlerContext;
/**
* @author xblia2
* Jul 22, 2015
*/
public class MessageHandlerGetOnlineUser extends IMsgHandler
{
@Override
public boolean handleMessage(String strReq, ChannelHandlerContext ctx)
{
IMessageGetOnlineUserReq getOnlineReq = JSON.parseObject(strReq, IMessageGetOnlineUserReq.class);
if(null != getOnlineReq)
{
String checkRsp = fireRequestGenRsp(getOnlineReq);
sendMessageToClient(checkRsp, ctx);
return true;
}
return false;
}
private String fireRequestGenRsp(IMessageGetOnlineUserReq request)
{
List<UserInfo> userTable = UserTableModel.getInstance().getAllusers();
IMessageGetOnlineUserRsp getUserRsp = new IMessageGetOnlineUserRsp();
getUserRsp.setMsgIdentified(IMessageDef.MSGIDENTIFIED_VERSIONSERVICE);
getUserRsp.setMsgid(IMessageDef.genMsgId());
getUserRsp.setMsgType(IMessageDef.MSGTYPE_GET_ONLINELIST_RSP);
getUserRsp.setSoftName(request.getSoftName());
getUserRsp.setMsgResult(IMessageDef.FAIL);
if(!userTable.isEmpty())
{
getUserRsp.setMsgResult(IMessageDef.SUCC);
Map<String, String> onLineIpToUser = new HashMap<String, String>();
for (UserInfo userInfo : userTable)
{
if(userInfo.getSoftName().equals(request.getSoftName()))
{
onLineIpToUser.put(userInfo.getIp(), userInfo.getClientName());
}
}
getUserRsp.setOnlineIPToUser(onLineIpToUser);
}
return JSON.toJSONString(getUserRsp);
}
@Override
public int getType()
{
return IMessageDef.MSGTYPE_GET_ONLINELIST_REQ;
}
}
|
# %%
from wikidata2df import wikidata2df
import pandas as pd
# %%
with open("query_template.rq", "r") as q:
query_template = q.read()
with_dash_query = query_template.replace("TITLE_FILTER", "sars-cov-2")
no_dash_query = query_template.replace("TITLE_FILTER", "sars-cov2")
# %%
no_subj_papers = pd.concat([wikidata2df(with_dash_query), wikidata2df(no_dash_query)])
# %%
with open("update_cov2_papers.rq", "w") as qs:
for _, row in no_subj_papers.iterrows():
row_qs = f"{row['item']}|P921|Q82069695\n"
qs.write(row_qs)
|
<gh_stars>0
from client import ChatClient
import threading
import socket
import sys
PORT = 9000
class ChatServer(threading.Thread):
def __init__(self, port, host='localhost'):
super().__init__(daemon=True)
self.port = port
self.host = host
self.server = socket.socket(
socket.AF_INET,
socket.SOCK_STREAM,
socket.IPPROTO_TCP
)
self.client_pool = []
try:
self.server.bind((self.host, self.port))
except socket.error:
print('Bind failed {}'.format(socket.error))
sys.exit()
self.server.listen(10)
def parser(self, id, nick, conn, message):
if message.decode().startswith('@'):
data = message.decode().split(maxsplit=1)
if data[0] == '@quit':
conn.sendall(b'You have left the chat.')
reply = nick.encode() + b'has left the channel.\n'
[c.conn.sendall(reply) for c in self.client_pool if len(self.client_pool)]
self.client_pool = [c for c in self.client_pool if c.id != id]
conn.close()
elif data[0] == '@list':
reply = ''
if len(self.client_pool) > 1:
for c in self.client_pool:
reply += f'{c.nick}\n'
conn.sendall(reply.encode())
else:
conn.sendall(b'You are the only one dude.\n')
elif data[0] == '@nickname':
for c in self.client_pool:
if c.id == id:
c.update_nick(data[1].strip())
for idx in range(len(self.client_pool)):
if self.client_pool[idx].id == id:
self.client_pool[idx].nick = data[1].strip()
else:
conn.sendall(b'Invalid command. Please try again.\n')
else:
reply = nick.encode() + b': ' + message
[c.conn.sendall(reply) for c in self.client_pool if len(self.client_pool)]
def run_thread(self, id, nick, conn, addr):
print('{} connected with {}:{}'.format(nick, addr[0], str(addr[1])))
try:
while True:
data = conn.recv(4096)
self.parser(id, nick, conn, data)
except (ConnectionResetError, BrokenPipeError, OSError):
conn.close()
def run(self):
print('Server running on {}'.format(PORT))
while True:
conn, addr = self.server.accept()
client = ChatClient(conn, addr)
self.client_pool.append(client)
threading.Thread(
target=self.run_thread,
args=(client.id, client.nick, client.conn, client.addr),
daemon=True
).start()
def exit(self):
self.server.close()
if __name__ == '__main__':
server = ChatServer(PORT)
try:
server.run()
except KeyboardInterrupt:
[c.conn.sendall(b'You have been blocked') for c in server.client_pool]
[c.conn.close() for c in server.client_pool if len(server.client_pool)]
|
<reponame>erikjchan/ballroom
// Database queries
const query = require('./query')
const query2 = require('./query2')
const log_debug = require('./log')
/************************ TEST PATHS *************************/
module.exports = app => {
app.get('/test/competitors', (req, res) => {
query2.get_all_competitors().then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/competitors/competition/:id', (req, res) => {
const id = parseInt(req.params.id)
query2.get_competitors_by_competition(id).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/competitors/id/:id', (req, res) => {
const id = parseInt(req.params.id)
query2.get_competitor_by_id(id).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/competitors/email/:email', (req, res) => {
const email = req.params.email
query2.get_competitor_by_email(email).then(function (value) {
log_debug(2)(value)
query2.check_competitor_email_exist(email).then(function (value2) {
console.log(value2);
res.send({query_result: value, check_if_exists: value2});
});
});
})
app.get('/test/competitors/insert/:email/:firstname/:lastname/:mailingaddress/:affiliationid/:password', (req, res) => {
const affiliationid = null
const lastname = req.params.lastname
const firstname = req.params.firstname
const email = req.params.email
const mailingaddress = req.params.mailingaddress
const password = <PASSWORD>
query2.create_competitor(firstname, lastname, email, mailingaddress, affiliationid, password).then(function (value) {
log_debug(2)(value)
res.send(value);
},
function (err){
res.send(err);
});
})
app.get('/test/competitors/update/email/:email/:firstname/:lastname/:mailingaddress/:affiliationid/:password/:hasregistered', (req, res) => {
const affiliationid = null
const lastname = req.params.lastname
const firstname = req.params.firstname
const email = req.params.email
const mailingaddress = req.params.mailingaddress
const password = <PASSWORD>
const hasregistered = parseInt(req.params.hasregistered)
query2.update_competitor_by_email(email, firstname, lastname, mailingaddress, affiliationid, password, hasregistered)
.then(function (value) {
log_debug(2)(value)
res.send(value);
},
function (err){
res.send(err);
});
})
app.get('/test/competitors/update/id/:id/:firstname/:lastname/:mailingaddress/:affiliationid/:password/:hasregistered', (req, res) => {
const affiliationid = null
const lastname = req.params.lastname
const firstname = req.params.firstname
const id = parseInt(req.params.id)
const mailingaddress = req.params.mailingaddress
const password = <PASSWORD>
const hasregistered = parseInt(req.params.hasregistered)
query2.update_competitor_by_id(id, firstname, lastname, mailingaddress, affiliationid, password, hasregistered)
.then(function (value) {
log_debug(2)(value)
res.send(value);
},
function (err){
res.send(err);
});
})
app.get('/test/payment_records', (req, res) => {
query2.get_all_paymentrecords().then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/payment_records/competition/:id', (req, res) => {
const id = parseInt(req.params.id)
query2.get_paymentrecords_by_competition(id).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/payment_records/competitor/:id', (req, res) => {
const id = parseInt(req.params.id)
query2.get_paymentrecords_by_competitor(id).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/payment_records/:competitionid/:competitorid', (req, res) => {
const competitionid = parseInt(req.params.competitionid)
const competitorid = parseInt(req.params.competitorid)
query2.get_paymentrecord_by_competition_competitor(competitionid, competitorid).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/payment_records/insert/:competitionid/:competitorid/:amount/:online/:paidwithaffiliation', (req, res) => {
const competitionid = parseInt(req.params.competitionid)
const competitorid = parseInt(req.params.competitorid)
const amount = parseFloat(req.params.amount)
const online = (req.params.online)
const paidwithaffiliation = (req.params.paidwithaffiliation)
query2.create_paymentrecord(competitionid, competitorid, amount, online, paidwithaffiliation).then(function (value) {
log_debug(2)(value)
res.send(value);
},
function (err){
res.send(err);
});
})
app.get('/test/payment_records/update/:competitionid/:competitorid/:amount/:online/:paidwithaffiliation', (req, res) => {
const competitionid = parseInt(req.params.competitionid)
const competitorid = parseInt(req.params.competitorid)
const amount = parseFloat(req.params.amount)
const online = parseInt(req.params.online)
const paidwithaffiliation = parseInt(req.params.paidwithaffiliation)
query2.update_paymentrecord(competitionid, competitorid, amount, online, paidwithaffiliation).then(function (value) {
log_debug(2)(value)
res.send(value);
},
function (err){
res.send(err);
});
})
app.get('/test/partnerships/', (req, res) => {
query2.get_all_partnerships().then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/partnerships/competitor/:id', (req, res) => {
const id = parseInt(req.params.id)
query2.get_partnerships_by_competitor(id).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/partnerships/competition/:competitionid/competitor/:competitorid', (req, res) => {
const competitionid = parseInt(req.params.competitionid)
const competitorid = parseInt(req.params.competitorid)
query2.get_partnerships_by_competition_competitor(competitionid, competitorid).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/partnerships/lead/:competitiorid1/follow/:competitorid2/event/:eventid', (req, res) => {
const competitiorid1 = parseInt(req.params.competitiorid1)
const competitorid2 = parseInt(req.params.competitorid2)
const eventid = parseInt(req.params.eventid)
query2.get_partnership(competitiorid1, competitorid2, eventid).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/partnerships/event/:eventid', (req, res) => {
const eventid = parseInt(req.params.eventid)
query2.get_partnerships_by_event(eventid).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/partnerships/competition/:cid/number/:number', (req, res) => {
const cid = parseInt(req.params.cid)
const number = parseInt(req.params.number)
query2.get_partnership_by_number(cid, number).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/partnerships/comfirmed/event/:eventid', (req, res) => {
const eventid = parseInt(req.params.eventid)
console.log("here")
query2.get_confirmed_partnerships_by_event(eventid).then(function (value) {
log_debug(2)(value)
res.send(value);
});
})
app.get('/test/partnerships/insert/:leadcompetitorid/:followcompetitorid/:eventid/:competitionid', (req, res) => {
const leadcompetitorid = parseInt(req.params.leadcompetitorid)
const followcompetitorid = parseInt(req.params.followcompetitorid)
const eventid = parseInt(req.params.eventid)
const competitionid = parseInt(req.params.competitionid)
query2.create_partnership(leadcompetitorid, followcompetitorid, eventid, competitionid).then(function (value) {
log_debug(2)(value)
res.send(value);
},
function (err){
console.log(err);
res.send(err);
});
})
app.get('/test/partnerships/update/:leadcompetitorid/:followcompetitorid/:eventid/:leadconfirmed/:followconfirmed/:calledback/:number', (req, res) => {
const leadcompetitorid = parseInt(req.params.leadcompetitorid)
const followcompetitorid = parseInt(req.params.followcompetitorid)
const eventid = parseInt(req.params.eventid)
const leadconfirmed = parseInt(req.params.leadconfirmed)
const followconfirmed = parseInt(req.params.followconfirmed)
const calledback = parseInt(req.params.calledback)
const number = parseInt(req.params.number)
query2.update_partnership(leadcompetitorid, followcompetitorid, eventid, leadconfirmed, followconfirmed, calledback, number).then(function (value) {
log_debug(2)(value)
res.send(value);
},
function (err){
res.send(err);
});
})
app.get('/test/', (req, res) => {
res.send({routes: [
'/test/competitors',
'/test/competitors/id/:id',
'/test/competitors/email/:email',
'/test/competitors/insert/:email/:firstname/:lastname/:mailingaddress/:affiliationid/:password',
'/test/payment_records',
'/test/payment_records/competition/:id',
'/test/payment_records/competitor/:id',
'/test/payment_records/:competitionid/:competitorid',
'/test/payment_records/insert/:competitionid/:competitorid/:amount/:online/:paidwithaffiliation',
'/test/payment_records/update/:competitionid/:competitorid/:amount/:online/:paidwithaffiliation',
'/test/partnerships/',
'/test/partnerships/competitor/:id',
'/test/partnerships/competition/:competitionid/competitor/:competitorid',
'/test/partnerships/lead/:competitiorid1/follow/:competitorid2/event/:eventid',
'/test/partnerships/event/:eventid',
'/test/partnerships/competition/:competitionid/number/:number',
'/test/partnerships/comfirmed/event/:eventid',
'/test/partnerships/insert/:leadcompetitorid/:followcompetitorid/:eventid/:competitionid/:number',
'/test/partnerships/update/:leadcompetitorid/:followcompetitorid/:eventid/:leadconfirmed/:followconfirmed/:calledback/:numbe',
]})
})
}
|
#!/usr/bin/env bats
@test "accept when no settings are provided" {
run kwctl run policy.wasm -r test_data/ingress.json
# this prints the output when one the checks below fails
echo "output = ${output}"
# request accepted
[ "$status" -eq 0 ]
[ $(expr "$output" : '.*allowed.*true') -ne 0 ]
}
@test "accept user defined constraint is respected" {
run kwctl run policy.wasm \
-r test_data/ingress.json \
--settings-json '{"constrained_labels": {"owner": "^team-"}}'
# this prints the output when one the checks below fails
echo "output = ${output}"
# request accepted
[ "$status" -eq 0 ]
[ $(expr "$output" : '.*allowed.*true') -ne 0 ]
}
@test "accept labels are not on deny list" {
run kwctl run policy.wasm \
-r test_data/ingress.json \
--settings-json '{"denied_labels": ["foo", "bar"]}'
# this prints the output when one the checks below fails
echo "output = ${output}"
# request accepted
[ "$status" -eq 0 ]
[ $(expr "$output" : '.*allowed.*true') -ne 0 ]
}
@test "reject because label is on deny list" {
run kwctl run policy.wasm \
-r test_data/ingress.json --settings-json '{"denied_labels": ["foo", "owner"]}'
# this prints the output when one the checks below fails
echo "output = ${output}"
# request rejected
[ "$status" -eq 0 ]
[ $(expr "$output" : '.*allowed.*false') -ne 0 ]
[ $(expr "$output" : '.*The following labels are denied: owner".*') -ne 0 ]
}
@test "reject because label doesn't pass validation constraint" {
run kwctl run policy.wasm \
-r test_data/ingress.json \
--settings-json '{"constrained_labels": {"cc-center": "^cc-\\d+$"}}'
# this prints the output when one the checks below fails
echo "output = ${output}"
# request rejected
[ "$status" -eq 0 ]
[ $(expr "$output" : '.*allowed.*false') -ne 0 ]
[ $(expr "$output" : ".*The following labels are violating user constraints: cc-center.*") -ne 0 ]
}
@test "reject because a required label does not exist" {
run kwctl run policy.wasm \
-r test_data/ingress.json --settings-json '{"mandatory_labels": ["required"], "constrained_labels": {"foo", ".*"}}'
# this prints the output when one the checks below fails
echo "output = ${output}"
# request rejected
[ "$status" -eq 0 ]
[ $(expr "$output" : '.*allowed.*false') -ne 0 ]
[ $(expr "$output" : '.*The following mandatory labels are missing: required.*') -ne 0 ]
}
@test "fail settings validation because constrained labels are also denied" {
run kwctl run policy.wasm \
-r test_data/ingress.json \
--settings-json '{"denied_labels": ["foo", "cc-center"], "constrained_labels": {"cc-center": "^cc-\\d+$"}}'
# this prints the output when one the checks below fails
echo "output = ${output}"
# settings validation fails
[ "$status" -eq 1 ]
[ $(expr "$output" : '.*valid.*false') -ne 0 ]
[ $(expr "$output" : ".*Provided settings are not valid: These labels cannot be constrained and denied at the same time: cc-center.*") -ne 0 ]
}
@test "fail settings validation because mandatory labels are also denied" {
run kwctl run policy.wasm \
-r test_data/ingress.json \
--settings-json '{"denied_labels": ["foo", "cc-center"], "mandatory_labels": ["cc-center"]}'
# this prints the output when one the checks below fails
echo "output = ${output}"
# settings validation fails
[ "$status" -eq 1 ]
[ $(expr "$output" : '.*valid.*false') -ne 0 ]
[ $(expr "$output" : ".*Provided settings are not valid: These labels cannot be mandatory and denied at the same time: cc-center.*") -ne 0 ]
}
@test "fail settings validation because of invalid constraint" {
run kwctl run policy.wasm \
-r test_data/ingress.json \
--settings-json '{"constrained_labels": {"cc-center": "^cc-[12$"}}'
# this prints the output when one the checks below fails
echo "output = ${output}"
# settings validation fails
[ "$status" -eq 1 ]
[ $(expr "$output" : '.*valid.*false') -ne 0 ]
[ $(expr "$output" : ".*Provided settings are not valid: error parsing regexp: missing closing ]: `[12$`.*") -ne 0 ]
}
|
#!/usr/bin/env bash
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# You'll need a local installation of
# [Apache Yetus' precommit checker](http://yetus.apache.org/documentation/0.1.0/#yetus-precommit)
# to use this personality.
#
# Download from: http://yetus.apache.org/downloads/ . You can either grab the source artifact and
# build from it, or use the convenience binaries provided on that download page.
#
# To run against, e.g. HBASE-15074 you'd then do
# ```bash
# test-patch --personality=dev-support/hbase-personality.sh HBASE-15074
# ```
#
# If you want to skip the ~1 hour it'll take to do all the hadoop API checks, use
# ```bash
# test-patch --plugins=all,-hadoopcheck --personality=dev-support/hbase-personality.sh HBASE-15074
# ````
#
# pass the `--jenkins` flag if you want to allow test-patch to destructively alter local working
# directory / branch in order to have things match what the issue patch requests.
personality_plugins "all"
if ! declare -f "yetus_info" >/dev/null; then
function yetus_info
{
echo "[$(date) INFO]: $*" 1>&2
}
fi
## @description Globals specific to this personality
## @audience private
## @stability evolving
function personality_globals
{
BUILDTOOL=maven
#shellcheck disable=SC2034
PROJECT_NAME=hbase
#shellcheck disable=SC2034
PATCH_BRANCH_DEFAULT=master
#shellcheck disable=SC2034
JIRA_ISSUE_RE='^HBASE-[0-9]+$'
#shellcheck disable=SC2034
GITHUB_REPO="apache/hbase"
# TODO use PATCH_BRANCH to select jdk versions to use.
# Override the maven options
MAVEN_OPTS="${MAVEN_OPTS:-"-Xmx3100M"}"
# Yetus 0.7.0 enforces limits. Default proclimit is 1000.
# Up it. See HBASE-19902 for how we arrived at this number.
#shellcheck disable=SC2034
PROCLIMIT=10000
# Set docker container to run with 20g. Default is 4g in yetus.
# See HBASE-19902 for how we arrived at 20g.
#shellcheck disable=SC2034
DOCKERMEMLIMIT=20g
}
## @description Parse extra arguments required by personalities, if any.
## @audience private
## @stability evolving
function personality_parse_args
{
declare i
for i in "$@"; do
case ${i} in
--exclude-tests-url=*)
EXCLUDE_TESTS_URL=${i#*=}
;;
--include-tests-url=*)
INCLUDE_TESTS_URL=${i#*=}
;;
--hadoop-profile=*)
HADOOP_PROFILE=${i#*=}
;;
--skip-errorprone)
SKIP_ERRORPRONE=true
;;
esac
done
}
## @description Queue up modules for this personality
## @audience private
## @stability evolving
## @param repostatus
## @param testtype
function personality_modules
{
local repostatus=$1
local testtype=$2
local extra=""
local MODULES=("${CHANGED_MODULES[@]}")
yetus_info "Personality: ${repostatus} ${testtype}"
clear_personality_queue
extra="-DHBasePatchProcess"
if [[ "${PATCH_BRANCH}" = branch-1* ]]; then
extra="${extra} -Dhttps.protocols=TLSv1.2"
fi
if [[ -n "${HADOOP_PROFILE}" ]]; then
extra="${extra} -Dhadoop.profile=${HADOOP_PROFILE}"
fi
# BUILDMODE value is 'full' when there is no patch to be tested, and we are running checks on
# full source code instead. In this case, do full compiles, tests, etc instead of per
# module.
# Used in nightly runs.
# If BUILDMODE is 'patch', for unit and compile testtypes, there is no need to run individual
# modules if root is included. HBASE-18505
if [[ "${BUILDMODE}" == "full" ]] || \
( ( [[ "${testtype}" == unit ]] || [[ "${testtype}" == compile ]] || [[ "${testtype}" == checkstyle ]] ) && \
[[ "${MODULES[*]}" =~ \. ]] ); then
MODULES=(.)
fi
# If the checkstyle configs change, check everything.
if [[ "${testtype}" == checkstyle ]] && [[ "${MODULES[*]}" =~ hbase-checkstyle ]]; then
MODULES=(.)
fi
if [[ ${testtype} == mvninstall ]]; then
# shellcheck disable=SC2086
personality_enqueue_module . ${extra}
return
fi
if [[ ${testtype} == findbugs ]]; then
# Run findbugs on each module individually to diff pre-patch and post-patch results and
# report new warnings for changed modules only.
# For some reason, findbugs on root is not working, but running on individual modules is
# working. For time being, let it run on original list of CHANGED_MODULES. HBASE-19491
for module in "${CHANGED_MODULES[@]}"; do
# skip findbugs on hbase-shell and hbase-it. hbase-it has nothing
# in src/main/java where findbugs goes to look
if [[ ${module} == hbase-shell ]]; then
continue
elif [[ ${module} == hbase-it ]]; then
continue
else
# shellcheck disable=SC2086
personality_enqueue_module ${module} ${extra}
fi
done
return
fi
if [[ ${testtype} == compile ]] && [[ "${SKIP_ERRORPRONE}" != "true" ]]; then
extra="${extra} -PerrorProne"
fi
# If EXCLUDE_TESTS_URL/INCLUDE_TESTS_URL is set, fetches the url
# and sets -Dtest.exclude.pattern/-Dtest to exclude/include the
# tests respectively.
if [[ ${testtype} == unit ]]; then
local tests_arg=""
get_include_exclude_tests_arg tests_arg
extra="${extra} -PrunAllTests ${tests_arg}"
# Inject the jenkins build-id for our surefire invocations
# Used by zombie detection stuff, even though we're not including that yet.
if [ -n "${BUILD_ID}" ]; then
extra="${extra} -Dbuild.id=${BUILD_ID}"
fi
# If the set of changed files includes CommonFSUtils then add the hbase-server
# module to the set of modules (if not already included) to be tested
for f in "${CHANGED_FILES[@]}"
do
if [[ "${f}" =~ CommonFSUtils ]]; then
if [[ ! "${MODULES[*]}" =~ hbase-server ]] && [[ ! "${MODULES[*]}" =~ \. ]]; then
MODULES+=("hbase-server")
fi
break
fi
done
fi
for module in "${MODULES[@]}"; do
# shellcheck disable=SC2086
personality_enqueue_module ${module} ${extra}
done
}
## @description places where we override the built in assumptions about what tests to run
## @audience private
## @stability evolving
## @param filename of changed file
function personality_file_tests
{
local filename=$1
yetus_debug "HBase specific personality_file_tests"
# If the change is to the refguide, then we don't need any builtin yetus tests
# the refguide test (below) will suffice for coverage.
if [[ ${filename} =~ src/main/asciidoc ]] ||
[[ ${filename} =~ src/main/xslt ]]; then
yetus_debug "Skipping builtin yetus checks for ${filename}. refguide test should pick it up."
else
# If we change our asciidoc, rebuild mvnsite
if [[ ${BUILDTOOL} = maven ]]; then
if [[ ${filename} =~ src/site || ${filename} =~ src/main/asciidoc ]]; then
yetus_debug "tests/mvnsite: ${filename}"
add_test mvnsite
fi
fi
# If we change checkstyle configs, run checkstyle
if [[ ${filename} =~ checkstyle.*\.xml ]]; then
yetus_debug "tests/checkstyle: ${filename}"
add_test checkstyle
fi
# fallback to checking which tests based on what yetus would do by default
if declare -f "${BUILDTOOL}_builtin_personality_file_tests" >/dev/null; then
"${BUILDTOOL}_builtin_personality_file_tests" "${filename}"
elif declare -f builtin_personality_file_tests >/dev/null; then
builtin_personality_file_tests "${filename}"
fi
fi
}
## @description Uses relevant include/exclude env variable to fetch list of included/excluded
# tests and sets given variable to arguments to be passes to maven command.
## @audience private
## @stability evolving
## @param name of variable to set with maven arguments
function get_include_exclude_tests_arg
{
local __resultvar=$1
yetus_info "EXCLUDE_TESTS_URL=${EXCLUDE_TESTS_URL}"
yetus_info "INCLUDE_TESTS_URL=${INCLUDE_TESTS_URL}"
if [[ -n "${EXCLUDE_TESTS_URL}" ]]; then
if wget "${EXCLUDE_TESTS_URL}" -O "excludes"; then
excludes=$(cat excludes)
yetus_debug "excludes=${excludes}"
if [[ -n "${excludes}" ]]; then
eval "${__resultvar}='-Dtest.exclude.pattern=${excludes}'"
fi
rm excludes
else
yetus_error "Wget error $? in fetching excludes file from url" \
"${EXCLUDE_TESTS_URL}. Ignoring and proceeding."
fi
elif [[ -n "$INCLUDE_TESTS_URL" ]]; then
if wget "$INCLUDE_TESTS_URL" -O "includes"; then
includes=$(cat includes)
yetus_debug "includes=${includes}"
if [[ -n "${includes}" ]]; then
eval "${__resultvar}='-Dtest=${includes}'"
fi
rm includes
else
yetus_error "Wget error $? in fetching includes file from url" \
"${INCLUDE_TESTS_URL}. Ignoring and proceeding."
fi
else
# Use branch specific exclude list when EXCLUDE_TESTS_URL and INCLUDE_TESTS_URL are empty
FLAKY_URL="https://builds.apache.org/job/HBase-Find-Flaky-Tests/job/${PATCH_BRANCH}/lastSuccessfulBuild/artifact/excludes/"
if wget "${FLAKY_URL}" -O "excludes"; then
excludes=$(cat excludes)
yetus_debug "excludes=${excludes}"
if [[ -n "${excludes}" ]]; then
eval "${__resultvar}='-Dtest.exclude.pattern=${excludes}'"
fi
rm excludes
else
yetus_error "Wget error $? in fetching excludes file from url" \
"${FLAKY_URL}. Ignoring and proceeding."
fi
fi
}
###################################################
# Below here are our one-off tests specific to hbase.
# TODO break them into individual files so it's easier to maintain them?
# TODO line length check? could ignore all java files since checkstyle gets them.
###################################################
add_test_type refguide
function refguide_initialize
{
maven_add_install refguide
}
function refguide_filefilter
{
local filename=$1
if [[ ${filename} =~ src/main/asciidoc ]] ||
[[ ${filename} =~ src/main/xslt ]] ||
[[ ${filename} =~ hbase-common/src/main/resources/hbase-default.xml ]]; then
add_test refguide
fi
}
function refguide_rebuild
{
local repostatus=$1
local logfile="${PATCH_DIR}/${repostatus}-refguide.log"
declare -i count
declare pdf_output
if ! verify_needed_test refguide; then
return 0
fi
big_console_header "Checking we can create the ref guide on ${repostatus}"
start_clock
# disabled because "maven_executor" needs to return both command and args
# shellcheck disable=2046
echo_and_redirect "${logfile}" \
$(maven_executor) clean site --batch-mode \
-pl . \
-Dtest=NoUnitTests -DHBasePatchProcess -Prelease \
-Dmaven.javadoc.skip=true -Dcheckstyle.skip=true -Dfindbugs.skip=true
count=$(${GREP} -c '\[ERROR\]' "${logfile}")
if [[ ${count} -gt 0 ]]; then
add_vote_table -1 refguide "${repostatus} has ${count} errors when building the reference guide."
add_footer_table refguide "@@BASE@@/${repostatus}-refguide.log"
return 1
fi
if ! mv target/site "${PATCH_DIR}/${repostatus}-site"; then
add_vote_table -1 refguide "${repostatus} failed to produce a site directory."
add_footer_table refguide "@@BASE@@/${repostatus}-refguide.log"
return 1
fi
if [[ ! -f "${PATCH_DIR}/${repostatus}-site/book.html" ]]; then
add_vote_table -1 refguide "${repostatus} failed to produce the html version of the reference guide."
add_footer_table refguide "@@BASE@@/${repostatus}-refguide.log"
return 1
fi
if [[ "${PATCH_BRANCH}" = branch-1* ]]; then
pdf_output="book.pdf"
else
pdf_output="apache_hbase_reference_guide.pdf"
fi
if [[ ! -f "${PATCH_DIR}/${repostatus}-site/${pdf_output}" ]]; then
add_vote_table -1 refguide "${repostatus} failed to produce the pdf version of the reference guide."
add_footer_table refguide "@@BASE@@/${repostatus}-refguide.log"
return 1
fi
add_vote_table 0 refguide "${repostatus} has no errors when building the reference guide. See footer for rendered docs, which you should manually inspect."
add_footer_table refguide "@@BASE@@/${repostatus}-site/book.html"
return 0
}
add_test_type shadedjars
function shadedjars_initialize
{
yetus_debug "initializing shaded client checks."
maven_add_install shadedjars
}
## @description only run the test if java changes.
## @audience private
## @stability evolving
## @param filename
function shadedjars_filefilter
{
local filename=$1
if [[ ${filename} =~ \.java$ ]] || [[ ${filename} =~ pom.xml$ ]]; then
add_test shadedjars
fi
}
## @description test the shaded client artifacts
## @audience private
## @stability evolving
## @param repostatus
function shadedjars_rebuild
{
local repostatus=$1
local logfile="${PATCH_DIR}/${repostatus}-shadedjars.txt"
if ! verify_needed_test shadedjars; then
return 0
fi
big_console_header "Checking shaded client builds on ${repostatus}"
start_clock
# disabled because "maven_executor" needs to return both command and args
# shellcheck disable=2046
echo_and_redirect "${logfile}" \
$(maven_executor) clean verify -fae --batch-mode \
-pl hbase-shaded/hbase-shaded-check-invariants -am \
-Dtest=NoUnitTests -DHBasePatchProcess -Prelease \
-Dmaven.javadoc.skip=true -Dcheckstyle.skip=true -Dfindbugs.skip=true
count=$(${GREP} -c '\[ERROR\]' "${logfile}")
if [[ ${count} -gt 0 ]]; then
add_vote_table -1 shadedjars "${repostatus} has ${count} errors when building our shaded downstream artifacts."
add_footer_table shadedjars "@@BASE@@/${repostatus}-shadedjars.txt"
return 1
fi
add_vote_table +1 shadedjars "${repostatus} has no errors when building our shaded downstream artifacts."
return 0
}
###################################################
add_test_type hadoopcheck
## @description hadoopcheck file filter
## @audience private
## @stability evolving
## @param filename
function hadoopcheck_filefilter
{
local filename=$1
if [[ ${filename} =~ \.java$ ]] || [[ ${filename} =~ pom.xml$ ]]; then
add_test hadoopcheck
fi
}
## @description Parse args to detect if QUICK_HADOOPCHECK mode is enabled.
## @audience private
## @stability evolving
function hadoopcheck_parse_args
{
declare i
for i in "$@"; do
case ${i} in
--quick-hadoopcheck)
QUICK_HADOOPCHECK=true
;;
esac
done
}
## @description Adds QUICK_HADOOPCHECK env variable to DOCKER_EXTRAARGS.
## @audience private
## @stability evolving
function hadoopcheck_docker_support
{
DOCKER_EXTRAARGS=("${DOCKER_EXTRAARGS[@]}" "--env=QUICK_HADOOPCHECK=${QUICK_HADOOPCHECK}")
}
## @description hadoopcheck test
## @audience private
## @stability evolving
## @param repostatus
function hadoopcheck_rebuild
{
local repostatus=$1
local hadoopver
local logfile
local count
local result=0
local hbase_hadoop2_versions
local hbase_hadoop3_versions
if [[ "${repostatus}" = branch ]]; then
return 0
fi
if ! verify_needed_test hadoopcheck; then
return 0
fi
big_console_header "Compiling against various Hadoop versions"
start_clock
# All supported Hadoop versions that we want to test the compilation with
# See the Hadoop section on prereqs in the HBase Reference Guide
if [[ "${PATCH_BRANCH}" = branch-1.* ]] && [[ "${PATCH_BRANCH#branch-1.}" -lt "5" ]]; then
yetus_info "Setting Hadoop 2 versions to test based on before-branch-1.5 rules."
if [[ "${QUICK_HADOOPCHECK}" == "true" ]]; then
hbase_hadoop2_versions="2.4.1 2.5.2 2.6.5 2.7.7"
else
hbase_hadoop2_versions="2.4.0 2.4.1 2.5.0 2.5.1 2.5.2 2.6.1 2.6.2 2.6.3 2.6.4 2.6.5 2.7.1 2.7.2 2.7.3 2.7.4 2.7.5 2.7.6 2.7.7"
fi
elif [[ "${PATCH_BRANCH}" = branch-2.0 ]]; then
yetus_info "Setting Hadoop 2 versions to test based on branch-2.0 rules."
if [[ "${QUICK_HADOOPCHECK}" == "true" ]]; then
hbase_hadoop2_versions="2.6.5 2.7.7 2.8.5"
else
hbase_hadoop2_versions="2.6.1 2.6.2 2.6.3 2.6.4 2.6.5 2.7.1 2.7.2 2.7.3 2.7.4 2.7.5 2.7.6 2.7.7 2.8.2 2.8.3 2.8.4 2.8.5"
fi
elif [[ "${PATCH_BRANCH}" = branch-2.1 ]]; then
yetus_info "Setting Hadoop 2 versions to test based on branch-2.1 rules."
if [[ "${QUICK_HADOOPCHECK}" == "true" ]]; then
hbase_hadoop2_versions="2.7.7 2.8.5"
else
hbase_hadoop2_versions="2.7.1 2.7.2 2.7.3 2.7.4 2.7.5 2.7.6 2.7.7 2.8.2 2.8.3 2.8.4 2.8.5"
fi
else
yetus_info "Setting Hadoop 2 versions to test based on branch-1.5+/branch-2.1+/master/feature branch rules."
if [[ "${QUICK_HADOOPCHECK}" == "true" ]]; then
hbase_hadoop2_versions="2.8.5 2.9.2"
else
hbase_hadoop2_versions="2.8.2 2.8.3 2.8.4 2.8.5 2.9.1 2.9.2"
fi
fi
hbase_hadoop3_versions="3.0.0"
if [[ "${PATCH_BRANCH}" = branch-1* ]]; then
hbase_hadoop3_versions=""
fi
export MAVEN_OPTS="${MAVEN_OPTS}"
for hadoopver in ${hbase_hadoop2_versions}; do
logfile="${PATCH_DIR}/patch-javac-${hadoopver}.txt"
# disabled because "maven_executor" needs to return both command and args
# shellcheck disable=2046
echo_and_redirect "${logfile}" \
$(maven_executor) clean install \
-DskipTests -DHBasePatchProcess \
-Dhadoop-two.version="${hadoopver}"
count=$(${GREP} -c '\[ERROR\]' "${logfile}")
if [[ ${count} -gt 0 ]]; then
add_vote_table -1 hadoopcheck "${BUILDMODEMSG} causes ${count} errors with Hadoop v${hadoopver}."
add_footer_table hadoopcheck "@@BASE@@/patch-javac-${hadoopver}.txt"
((result=result+1))
fi
done
for hadoopver in ${hbase_hadoop3_versions}; do
logfile="${PATCH_DIR}/patch-javac-${hadoopver}.txt"
# disabled because "maven_executor" needs to return both command and args
# shellcheck disable=2046
echo_and_redirect "${logfile}" \
$(maven_executor) clean install \
-DskipTests -DHBasePatchProcess \
-Dhadoop-three.version="${hadoopver}" \
-Dhadoop.profile=3.0
count=$(${GREP} -c '\[ERROR\]' "${logfile}")
if [[ ${count} -gt 0 ]]; then
add_vote_table -1 hadoopcheck "${BUILDMODEMSG} causes ${count} errors with Hadoop v${hadoopver}."
add_footer_table hadoopcheck "@@BASE@@/patch-javac-${hadoopver}.txt"
((result=result+1))
fi
done
if [[ ${result} -gt 0 ]]; then
return 1
fi
if [[ -n "${hbase_hadoop3_versions}" ]]; then
add_vote_table +1 hadoopcheck "Patch does not cause any errors with Hadoop ${hbase_hadoop2_versions} or ${hbase_hadoop3_versions}."
else
add_vote_table +1 hadoopcheck "Patch does not cause any errors with Hadoop ${hbase_hadoop2_versions}."
fi
return 0
}
######################################
# TODO if we need the protoc check, we probably need to check building all the modules that rely on hbase-protocol
add_test_type hbaseprotoc
## @description hbaseprotoc file filter
## @audience private
## @stability evolving
## @param filename
function hbaseprotoc_filefilter
{
local filename=$1
if [[ ${filename} =~ \.proto$ ]]; then
add_test hbaseprotoc
fi
}
## @description check hbase proto compilation
## @audience private
## @stability evolving
## @param repostatus
function hbaseprotoc_rebuild
{
declare repostatus=$1
declare i=0
declare fn
declare module
declare logfile
declare count
declare result
if [[ "${repostatus}" = branch ]]; then
return 0
fi
if ! verify_needed_test hbaseprotoc; then
return 0
fi
big_console_header "HBase protoc plugin: ${BUILDMODE}"
start_clock
personality_modules patch hbaseprotoc
# Need to run 'install' instead of 'compile' because shading plugin
# is hooked-up to 'install'; else hbase-protocol-shaded is left with
# half of its process done.
modules_workers patch hbaseprotoc install -DskipTests -X -DHBasePatchProcess
# shellcheck disable=SC2153
until [[ $i -eq "${#MODULE[@]}" ]]; do
if [[ ${MODULE_STATUS[${i}]} == -1 ]]; then
((result=result+1))
((i=i+1))
continue
fi
module=${MODULE[$i]}
fn=$(module_file_fragment "${module}")
logfile="${PATCH_DIR}/patch-hbaseprotoc-${fn}.txt"
count=$(${GREP} -c '\[ERROR\]' "${logfile}")
if [[ ${count} -gt 0 ]]; then
module_status ${i} -1 "patch-hbaseprotoc-${fn}.txt" "Patch generated "\
"${count} new protoc errors in ${module}."
((result=result+1))
fi
((i=i+1))
done
modules_messages patch hbaseprotoc true
if [[ ${result} -gt 0 ]]; then
return 1
fi
return 0
}
######################################
add_test_type hbaseanti
## @description hbaseanti file filter
## @audience private
## @stability evolving
## @param filename
function hbaseanti_filefilter
{
local filename=$1
if [[ ${filename} =~ \.java$ ]]; then
add_test hbaseanti
fi
}
## @description hbaseanti patch file check
## @audience private
## @stability evolving
## @param filename
function hbaseanti_patchfile
{
local patchfile=$1
local warnings
local result
if [[ "${BUILDMODE}" = full ]]; then
return 0
fi
if ! verify_needed_test hbaseanti; then
return 0
fi
big_console_header "Checking for known anti-patterns"
start_clock
warnings=$(${GREP} -c 'new TreeMap<byte.*()' "${patchfile}")
if [[ ${warnings} -gt 0 ]]; then
add_vote_table -1 hbaseanti "" "The patch appears to have anti-pattern where BYTES_COMPARATOR was omitted."
((result=result+1))
fi
if [[ ${result} -gt 0 ]]; then
return 1
fi
add_vote_table +1 hbaseanti "" "Patch does not have any anti-patterns."
return 0
}
## @description process the javac output for generating WARNING/ERROR
## @audience private
## @stability evolving
## @param input filename
## @param output filename
# Override the default javac_logfilter so that we can do a sort before outputing the WARNING/ERROR.
# This is because that the output order of the error prone warnings is not stable, so the diff
# method will report unexpected errors if we do not sort it. Notice that a simple sort will cause
# line number being sorted by lexicographical so the output maybe a bit strange to human but it is
# really hard to sort by file name first and then line number and column number in shell...
function hbase_javac_logfilter
{
declare input=$1
declare output=$2
${GREP} -E '\[(ERROR|WARNING)\] /.*\.java:' "${input}" | sort > "${output}"
}
## This is named so that yetus will check us right after running tests.
## Essentially, we check for normal failures and then we look for zombies.
#function hbase_unit_logfilter
#{
# declare testtype="unit"
# declare input=$1
# declare output=$2
# declare processes
# declare process_output
# declare zombies
# declare zombie_count=0
# declare zombie_process
#
# yetus_debug "in hbase-specific unit logfilter."
#
# # pass-through to whatever is counting actual failures
# if declare -f ${BUILDTOOL}_${testtype}_logfilter >/dev/null; then
# "${BUILDTOOL}_${testtype}_logfilter" "${input}" "${output}"
# elif declare -f ${testtype}_logfilter >/dev/null; then
# "${testtype}_logfilter" "${input}" "${output}"
# fi
#
# start_clock
# if [ -n "${BUILD_ID}" ]; then
# yetus_debug "Checking for zombie test processes."
# processes=$(jps -v | "${GREP}" surefirebooter | "${GREP}" -e "hbase.build.id=${BUILD_ID}")
# if [ -n "${processes}" ] && [ "$(echo "${processes}" | wc -l)" -gt 0 ]; then
# yetus_warn "Found some suspicious process(es). Waiting a bit to see if they're just slow to stop."
# yetus_debug "${processes}"
# sleep 30
# #shellcheck disable=SC2016
# for pid in $(echo "${processes}"| ${AWK} '{print $1}'); do
# # Test our zombie still running (and that it still an hbase build item)
# process_output=$(ps -p "${pid}" | tail +2 | "${GREP}" -e "hbase.build.id=${BUILD_ID}")
# if [[ -n "${process_output}" ]]; then
# yetus_error "Zombie: ${process_output}"
# ((zombie_count = zombie_count + 1))
# zombie_process=$(jstack "${pid}" | "${GREP}" -e "\.Test" | "${GREP}" -e "\.java"| head -3)
# zombies="${zombies} ${zombie_process}"
# fi
# done
# fi
# if [ "${zombie_count}" -ne 0 ]; then
# add_vote_table -1 zombies "There are ${zombie_count} zombie test(s)"
# populate_test_table "zombie unit tests" "${zombies}"
# else
# yetus_info "Zombie check complete. All test runs exited normally."
# stop_clock
# fi
# else
# add_vote_table -0 zombies "There is no BUILD_ID env variable; can't check for zombies."
# fi
#
#}
|
//使用方法: sudo ./getClientNatIPMAC
package main
import (
"fmt"
"io/ioutil"
"net"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/aeden/traceroute" // 这个包用的时候注意自己的电脑使用一种网络,同时插着有线和无线会有问题。
)
const FILENAME = "debug.txt"
func main() {
//------get local ip-------------
fmt.Println("-------> local IP ----------")
debugFile(FILENAME, fmt.Sprintln("-------> local IP ----------"))
addrs, err := net.InterfaceAddrs()
if err != nil {
fmt.Println(err.Error())
}
for i, addr := range addrs {
fmt.Printf("%d:%s\n", i+1, addr.String())
debugFile(FILENAME, fmt.Sprintf("%d:%s\n", i+1, addr.String()))
}
//----get external ip from 3 web station----------------------
fmt.Println("------> get external ip ---------")
debugFile(FILENAME, fmt.Sprintln("------> get external ip ---------"))
ipcn, err := getipcn()
if err != nil {
fmt.Println(err.Error())
}
external, err := getexternalip()
if err != nil {
fmt.Println(err.Error())
}
ipipnet, err := getipipnet()
if err != nil {
fmt.Println(err.Error())
}
fmt.Printf("\n1. ip.cn:%s\n\n2. myexternalip.com:%s\n\n3. ipip.net:%s\n\n", ipcn, external, ipipnet)
debugFile(FILENAME, fmt.Sprintf("\n1. ip.cn:%s\r\n\n2. myexternalip.com:%s\r\n\n3. ipip.net:%s\r\n\n", ipcn, external, ipipnet))
//---begin to traceroute , 第二个参数为最大跳数-------
fmt.Println("------> traceroute---------")
debugFile(FILENAME, fmt.Sprintln("------> traceroute---------"))
if err := trac("www.liepin.com", 6, 20); err != nil { //参数2是探针的个数,参数3是最大探测的跳数
fmt.Println(err.Error())
}
if err := trac("www.zhaopin.com", 6, 20); err != nil { //参数2是探针的个数,参数3是最大探测的跳数
fmt.Println(err.Error())
}
// c := make(chan string, 0)
// <-c
fmt.Println("------> end---------")
debugFile(FILENAME, fmt.Sprintln("------> end---------"))
}
//tracefile 写入文件
func debugFile(fileName, strContent string) {
fd, _ := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
fdTime := time.Now().Format("2006-01-02 15:04:05")
fdContent := strings.Join([]string{fdTime, "> ", strContent}, "")
buf := []byte(fdContent)
fd.Write(buf)
fd.Close()
}
//20170511 改造这个函数将日志写入文件
func printHop(hop traceroute.TracerouteHop) {
addr := fmt.Sprintf("%v.%v.%v.%v", hop.Address[0], hop.Address[1], hop.Address[2], hop.Address[3])
hostOrAddr := addr
if hop.Host != "" {
hostOrAddr = hop.Host
}
if hop.Success {
fmt.Printf("%-3d %v (%v) %v\n", hop.TTL, hostOrAddr, addr, hop.ElapsedTime)
debugFile(FILENAME, fmt.Sprintf("%-3d %v (%v) %v\n", hop.TTL, hostOrAddr, addr, hop.ElapsedTime))
} else {
fmt.Printf("%-3d *\n", hop.TTL)
debugFile(FILENAME, fmt.Sprintf("%-3d *\n", hop.TTL))
}
}
func address(address [4]byte) string {
return fmt.Sprintf("%v.%v.%v.%v", address[0], address[1], address[2], address[3])
}
//trac 适用于mac下的trace
func trac(www string, probeNum, hops int) error {
options := traceroute.TracerouteOptions{}
options.SetRetries(probeNum - 1) //Set the number of probes per "ttl" to nqueries (default is 1 probe).
options.SetMaxHops(hops) //Set the max time-to-live (max number of hops) used in outgoing probe packets (default is 64)
ipAddr, err := net.ResolveIPAddr("ip", www)
if err != nil {
return err
}
fmt.Printf("traceroute to %v (%v), %v hops max, %v byte packets\n", www, ipAddr, options.MaxHops(), options.PacketSize())
debugFile(FILENAME, fmt.Sprintf("traceroute to %v (%v), %v hops max, %v byte packets\n", www, ipAddr, options.MaxHops(), options.PacketSize()))
c := make(chan traceroute.TracerouteHop, 0)
go func() {
for {
hop, ok := <-c
if !ok {
//fmt.Println("cddd")
return
}
//fmt.Println(hop)
printHop(hop)
}
}()
_, err = traceroute.Traceroute(www, &options, c)
if err != nil {
return err
}
return nil
}
//getexternalip 从国外获取本机的出口ip
func getexternalip() (string, error) {
ipString := ""
resp, err := http.Get("http://myexternalip.com/raw") //ip.cn
if err != nil {
return ipString, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ipString, err
}
return strings.TrimSpace(string(body)), nil
}
//getipcn 从ip.cn获取本机的出口ip <div id="result"><div class="well"><p>您现在的 IP:<code>172.16.31.10</code></p><p>所在地理位置:<code>北京市 联通</code></p><p>GeoIP: Beijing, China</p></div></div>
func getipcn() (string, error) {
ipString := ""
resp, err := http.Get("http://ip.cn") //ip.cn
if err != nil {
return ipString, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ipString, err
}
re, _ := regexp.Compile("<code>[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}</code>")
IP := re.Find([]byte(body))
re, _ = regexp.Compile("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}")
IP = re.Find(IP)
return string(IP), nil
}
//getipipnet <li>172.16.31.10</li>
func getipipnet() (string, error) {
ipString := ""
resp, err := http.Get("http://www.ipip.net/share.html") //ip.cn
if err != nil {
return ipString, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ipString, err
}
re, _ := regexp.Compile("<li>[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}</li>")
IP := re.Find([]byte(body))
re, _ = regexp.Compile("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}")
IP = re.Find(IP)
return string(IP), nil
}
// //gettaobaoip 从淘宝获取ip
// func gettaobaoip() (string, error) {
//
// ipString := ""
//
// resp, err := http.Get("http://ip.taobao.com") //ip.cn
// if err != nil {
// return ipString, err
// }
//
// defer resp.Body.Close()
//
// body, err := ioutil.ReadAll(resp.Body)
// if err != nil {
// return ipString, err
// }
// return string(body), nil
//
// }
//
// //
|
<gh_stars>0
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { ToolbarGroup } from '@patternfly/react-core';
import DriftFilterDropdown from './DriftFilterDropdown';
import DriftFilterValue from './DriftFilterValue';
function DriftFilter(props) {
const { activeFactFilters, addStateFilter, factFilter, factTypeFilters, filterByFact, handleFactFilter, removeChip,
setHistory, stateFilters, toggleFactTypeFilter } = props;
const [ filterType, toggleFilterType ] = useState('Fact name');
return (
<ToolbarGroup variant='filter-group'>
<DriftFilterDropdown
filterType={ filterType }
toggleFilterType={ toggleFilterType }
/>
<DriftFilterValue
activeFactFilters={ activeFactFilters }
addStateFilter={ addStateFilter }
factFilter={ factFilter }
factTypeFilters={ factTypeFilters }
filterByFact={ filterByFact }
filterType={ filterType }
handleFactFilter={ handleFactFilter }
removeChip={ removeChip }
setHistory={ setHistory }
stateFilters={ stateFilters }
toggleFactTypeFilter={ toggleFactTypeFilter }
/>
</ToolbarGroup>
);
}
DriftFilter.propTypes = {
activeFactFilters: PropTypes.array,
addStateFilter: PropTypes.func,
clearAllFactFilters: PropTypes.func,
clearAllStateChips: PropTypes.func,
factFilter: PropTypes.string,
factTypeFilters: PropTypes.array,
filterByFact: PropTypes.func,
handleFactFilter: PropTypes.func,
removeChip: PropTypes.func,
setHistory: PropTypes.func,
stateFilters: PropTypes.array,
toggleFactTypeFilter: PropTypes.func
};
export default DriftFilter;
|
#!/bin/bash
qemu-system-i386 pongloader.img
|
// NodeViews might be a better match here: https://prosemirror.net/examples/footnote/
// footnote example:
// https://prosemirror.net/examples/footnote/
// https://glitch.com/edit/#!/voracious-perigee?path=index.js:18:26
// simple paragraph example: https://observablehq.com/@hubgit/prosemirror-nodeviews-example
// discussion of input in node views:
// https://discuss.prosemirror.net/t/creating-a-custom-node-with-inline-input/1282/8
/*
- Add a new block level node type named 'aside'
- We create a node view for asides
- When inserting footnotes we check for an aside node view
for the current paragraph and then use that
- filterTransaction to prevent deletion? (https://discuss.prosemirror.net/t/how-to-prevent-node-deletion/130/8)
*/
// TODO: Way to prevent removal of decorations (NodeView?)
// TODO: Some sort of comment selection
// from the website: https://github.com/ProseMirror/website/blob/d9427c7ff48312149f7be4607b1bf393240ab683/src/collab/client/comment.js
import { Plugin, PluginKey } from "prosemirror-state"
import { Decoration, DecorationSet } from "prosemirror-view"
import { AddMarkStep } from "prosemirror-transform"
export function commentsPlugin(markType) {
return new Plugin({
key: new PluginKey('comments'),
state: {
init(config, instance) {
let doc = instance.doc;
let comments = [];
doc.descendants((node, pos) => {
node.marks.forEach(mark => {
if (mark.type === markType)
comments.push(createComment(doc, pos, mark))
})
});
return DecorationSet.create(doc, comments);
},
apply(tr, set) {
// adjust decoration positions to changes made by the transaction
set = set.map(tr.mapping, tr.doc, {
onRemove() {
}
});
// if any comments were inserted then add a comments aside
tr.steps.forEach(step => {
if (step instanceof AddMarkStep) {
if (step.mark.type === markType) {
let commentWidget = createComment(tr.doc, step.from, step.mark);
set = set.add(tr.doc, [commentWidget]);
}
}
});
return set;
}
},
props: {
decorations(state) {
return this.getState(state);
}
},
})
}
function createComment(doc, at, mark) {
const resolvedPos = doc.resolve(at);
const afterPos = resolvedPos.after(1);
let comment = document.createElement('aside');
comment.addEventListener("click", () => {
comment.classList.toggle('comment-expanded');
// set data-active attribute on other marks
});
comment.innerHTML = mark.attrs['data-comment'] + "<br/>";
return Decoration.widget(afterPos, comment, { marks: [] });
}
|
#!/bin/sh
#
# Homebrew
#
# This installs some of the common dependencies needed (or at least desired)
# using Homebrew.
if [[ "$PLATFORM" == "Darwin" ]]
then
# Check for Homebrew
if test ! $(which brew)
then
echo " Installing Homebrew for you."
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
fi
# Install homebrew packages
brew install grc coreutils spark moreutils findutils
exit 0
fi
|
#!/bin/bash
NC='\033[0m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
GREEN='\033[0;32m'
$SHELL<<EOF1
cd apps/
if [ -d "testapp/" ]; then
echo -e "${YELLOW}testapp already created${NC}"
else
sudo rails new testapp #-d mysql
fi
cd testapp/
bundle update
sudo rails server -b 0.0.0.0 #> /dev/null &
EOF1
echo "yay..." |
#!/bin/bash
# Copyright 2018 AT&T Intellectual Property. All other rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -xe
: "${PEGLEG_PATH:=../airship-pegleg}"
: "${PEGLEG_IMG:=quay.io/airshipit/pegleg:b7556bd89e99f2a6539e97d5a4ac6738751b9c55}"
: "${PEGLEG:=${PEGLEG_PATH}/tools/pegleg.sh}"
# TODO(drewwalters96): make Treasuremap sites P001 and P009 compliant.
IMAGE=${PEGLEG_IMG} TERM_OPTS=" " \
${PEGLEG} site -r . lint "$1" -x P001 -x P009
|
#!/bin/bash
# Copyright 2019 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
set -e
CLANG_FORMAT=$(which clang-format) || (echo "Please install 'clang-format' tool first"; exit 1)
version=$("${CLANG_FORMAT}" --version | sed -n "s/.*\ \([0-9]*\)\.[0-9]*\.[0-9]*.*/\1/p")
if [[ "${version}" -lt "8" ]]; then
echo "clang-format's version must be at least 8.0.0"
exit 1
fi
CURRENT_PATH=$(pwd)
SCRIPTS_PATH=$(dirname "$0")
echo "CURRENT_PATH=$CURRENT_PATH"
echo "SCRIPTS_PATH=$SCRIPTS_PATH"
# print usage message
function usage()
{
echo "Check whether the specified source files were well formated"
echo "Usage:"
echo "bash $0 [-a] [-c] [-l] [-h]"
echo "e.g. $0 -a"
echo ""
echo "Options:"
echo " -a Check code format of all files, default case"
echo " -c Check code format of the files changed compared to last commit"
echo " -l Check code format of the files changed in last commit"
echo " -h Print usage"
}
# check and set options
function checkopts()
{
# init variable
mode="all" # default check all files
# Process the options
while getopts 'aclh' opt
do
case "${opt}" in
a)
mode="all"
;;
c)
mode="changed"
;;
l)
mode="lastcommit"
;;
h)
usage
exit 0
;;
*)
echo "Unknown option ${opt}!"
usage
exit 1
esac
done
}
# init variable
# check options
checkopts "$@"
# switch to project root path, which contains clang-format config file '.clang-format'
cd "${SCRIPTS_PATH}/.." || exit 1
CHECK_LIST_FILE='__checked_files_list__'
if [ "X${mode}" == "Xall" ]; then
find mindspore/{ccsrc,core,lite} -type f -name "*" | grep "\.h$\|\.cc$\|\.c$" > "${CHECK_LIST_FILE}" || true
elif [ "X${mode}" == "Xchanged" ]; then
# --diff-filter=ACMRTUXB will ignore deleted files in commit
git diff --diff-filter=ACMRTUXB --name-only | grep "mindspore/ccsrc\|mindspore/core\|mindspore/lite" | grep "\.h$\|\.cc$\|\.c$" > "${CHECK_LIST_FILE}" || true
else # "X${mode}" == "Xlastcommit"
git diff --diff-filter=ACMRTUXB --name-only HEAD~ HEAD | grep "mindspore/ccsrc\|mindspore/core\|mindspore/lite" | grep "\.h$\|\.cc$\|\.c$" > "${CHECK_LIST_FILE}" || true
fi
CHECK_RESULT_FILE=__code_format_check_result__
echo "0" > "$CHECK_RESULT_FILE"
# check format of files modified in the lastest commit
while read line; do
BASE_NAME=$(basename "${line}")
TEMP_FILE="__TEMP__${BASE_NAME}"
cp "${line}" "${TEMP_FILE}"
${CLANG_FORMAT} -i "${TEMP_FILE}"
diff "${TEMP_FILE}" "${line}"
ret=$?
rm "${TEMP_FILE}"
if [[ "${ret}" -ne 0 ]]; then
echo "File ${line} is not formated, please format it."
echo "1" > "${CHECK_RESULT_FILE}"
break
fi
done < "${CHECK_LIST_FILE}"
result=$(cat "${CHECK_RESULT_FILE}")
rm "${CHECK_RESULT_FILE}"
rm "${CHECK_LIST_FILE}"
cd "${CURRENT_PATH}" || exit 1
if [[ "X${result}" == "X0" ]]; then
echo "Check PASS: specified files are well formated!"
fi
exit "${result}"
|
#!/bin/sh
set -eax
DIR=${1:-.}
cd $DIR
if [ -f Pipfile ]
then
pip install -U pipenv
pipenv install -d --system
elif [ -f requirements.txt ]
then
pip install -r requirements.txt
fi
flake8 --exclude .venv
|
const vscode = require(`vscode`);
const Cache = require(`./models/cache`);
const Declaration = require(`./models/declaration`);
const Statement = require(`./statement`);
const oneLineTriggers = require(`./models/oneLineTriggers`);
const IssueRange = require(`./models/ContentRange`);
const errorText = {
'BlankStructNamesCheck': `Struct names cannot be blank (\`*N\`).`,
'QualifiedCheck': `Struct names must be qualified (\`QUALIFIED\`).`,
'PrototypeCheck': `Prototypes can only be defined with either \`EXT\`, \`EXTPGM\` or \`EXTPROC\``,
'ForceOptionalParens': `Expressions must be surrounded by brackets.`,
'NoOCCURS': `\`OCCURS\` is not allowed.`,
'NoSELECTAll': `\`SELECT *\` is not allowed in Embedded SQL.`,
'UselessOperationCheck': `Redundant operation codes (EVAL, CALLP) not allowed.`,
'UppercaseConstants': `Constants must be in uppercase.`,
'SpecificCasing': `Does not match required case.`,
'InvalidDeclareNumber': `Variable names cannot start with a number`,
'IncorrectVariableCase': `Variable name casing does not match definition.`,
'RequiresParameter': `Procedure calls require brackets.`,
'RequiresProcedureDescription': `Procedures require a title and description.`,
'StringLiteralDupe': `Same string literal used more than once. Consider using a constant instead.`,
'RequireBlankSpecial': `\`*BLANK\` should be used over empty string literals.`,
'CopybookDirective': `Directive does not match requirement.`,
'UppercaseDirectives': `Directives must be in uppercase.`,
'NoSQLJoins': `SQL joins are not allowed. Consider creating a view instead.`,
'NoGlobalsInProcedures': `Global variables should not be referenced in procedures.`,
'NoCTDATA': `\`CTDATA\` is not allowed.`,
'PrettyComments': `Comments must be correctly formatted.`,
'NoGlobalSubroutines': `Subroutines should not be defined in the global scope.`,
'NoLocalSubroutines': `Subroutines should not be defined in procedures.`,
'UnexpectedEnd': `Statement unexpected. Likely missing the equivalent \`DCL..\``,
}
module.exports = class Linter {
static getErrorText(error) {
return errorText[error];
}
/**
* @param {string} content
* @param {{
* indent?: number,
* BlankStructNamesCheck?: boolean,
* QualifiedCheck?: boolean,
* PrototypeCheck?: boolean,
* ForceOptionalParens?: boolean,
* NoOCCURS?: boolean,
* NoSELECTAll?: boolean,
* UselessOperationCheck?: boolean,
* UppercaseConstants?: boolean,
* IncorrectVariableCase?: boolean,
* RequiresParameter?: boolean,
* RequiresProcedureDescription?: boolean,
* StringLiteralDupe?: boolean,
* literalMinimum?: number,
* RequireBlankSpecial?: boolean,
* CopybookDirective?: "copy"|"include"
* UppercaseDirectives?: boolean,
* NoSQLJoins?: boolean,
* NoGlobalsInProcedures?: boolean,
* SpecificCasing?: {operation: string, expected: string}[],
* NoCTDATA?: boolean,
* PrettyComments?: boolean,
* NoGlobalSubroutines?: boolean,
* NoLocalSubroutines?: boolean,
* CollectReferences?: boolean,
* }} rules
* @param {Cache|null} [globalScope]
*/
static getErrors(content, rules, globalScope) {
const newLineLength = (content.indexOf(`\r\n`) !== -1) ? 2 : 1;
/** @type {string[]} */
const lines = content.replace(new RegExp(`\\\r`, `g`), ``).split(`\n`);
const indentEnabled = rules.indent !== undefined;
const indent = rules.indent || 2;
// Excluding indent
const ruleCount = Object.keys(rules).length - (rules.indent ? 1 : 0);
if (!globalScope)
globalScope = new Cache();
const globalProcs = globalScope.procedures;
let inProcedure = false;
let inPrototype = false;
let inOnExit = false;
let lineNumber = -1;
/** @type {{line: number, expectedIndent: number, currentIndent: number}[]} */
const indentErrors = [];
// Offset is always the offset within the range
/** @type {IssueRange[]} */
const errors = [];
/** @type {Number} */
let expectedIndent = 0;
let currentIndent = 0;
/** @type {string[]} */
let pieces;
let continuedStatement = false;
let isLineComment = false;
let skipIndentCheck = false;
let currentStatement = ``;
let opcode;
/** @type {vscode.Position} */
let statementStart;
/** @type {vscode.Position} */
let statementEnd;
/** @type {{value: string, definition?: string, list: {range: vscode.Range, offset: {position: number, length: number}}[]}[]} */
const stringLiterals = [];
for (lineNumber = 0; lineNumber < lines.length; lineNumber++) {
const currentLine = lines[lineNumber];
currentIndent = currentLine.search(/\S/);
let line = currentLine.trimEnd();
let upperLine = line.trim().toUpperCase();
isLineComment = line.trimStart().startsWith(`//`);
if (currentIndent >= 0) {
skipIndentCheck = false;
if (continuedStatement) {
skipIndentCheck = true;
statementEnd = new vscode.Position(lineNumber, line.length);
if (currentIndent < expectedIndent) {
indentErrors.push({
line: lineNumber,
expectedIndent,
currentIndent
});
}
} else {
statementStart = new vscode.Position(lineNumber, currentIndent);
statementEnd = new vscode.Position(lineNumber, line.length);
}
if (isLineComment) {
const comment = line.substring(currentIndent + 2).trimEnd();
if (rules.PrettyComments) {
if (comment === ``) {
errors.push({
range: new vscode.Range(
new vscode.Position(lineNumber, currentIndent),
new vscode.Position(lineNumber, currentIndent + 2)
),
offset: undefined,
type: `PrettyComments`,
newValue: ``
});
} else {
// We check for the slash because the documentation requires ///.
if (comment !== `/`) {
const startSpaces = comment.search(/\S/);
if (startSpaces === 0) {
errors.push({
range: new vscode.Range(
new vscode.Position(lineNumber, currentIndent),
new vscode.Position(lineNumber, currentIndent + 2)
),
offset: undefined,
type: `PrettyComments`,
newValue: `// `,
});
}
}
}
} else {
skipIndentCheck = true;
}
// Special comment check
if (comment.trim() === `@rpglint-skip`) {
lineNumber += 1;
continue;
}
}
if (!isLineComment) {
if (line.endsWith(`;`)) {
statementEnd = new vscode.Position(lineNumber, line.length - 1);
line = line.substr(0, line.length-1);
currentStatement += line;
continuedStatement = false;
} else {
const semiIndex = line.lastIndexOf(`;`);
const commentIndex = line.lastIndexOf(`//`);
if (commentIndex > semiIndex && semiIndex >= 0) {
statementEnd = new vscode.Position(lineNumber, line.lastIndexOf(`;`));
line = line.substr(0, semiIndex);
continuedStatement = false;
} else {
continuedStatement = true;
}
currentStatement += line + ``.padEnd(newLineLength, ` `);
}
// We do it again for any changes to the line
upperLine = line.trim().toUpperCase();
// Generally ignore comments
if (upperLine.startsWith(`//`)) {
currentStatement = ``;
} else if (upperLine.startsWith(`/`)) {
// But not directives!
continuedStatement = false;
}
// Ignore free directive.
if (upperLine.startsWith(`**`)) {
continuedStatement = false;
}
// Linter checking
if (continuedStatement === false && currentStatement.length > 0) {
if (ruleCount > 0) {
const currentStatementUpper = currentStatement.toUpperCase();
currentStatement = currentStatement.trim();
const currentProcedure = globalScope.procedures.find(proc => lineNumber >= proc.range.start && lineNumber <= proc.range.end);
const currentScope = globalScope.merge(inProcedure && currentProcedure ? currentProcedure.scope : undefined);
const statement = Statement.parseStatement(currentStatement);
let value;
if (statement.length >= 1) {
if (statement[0].type === `directive` && statement[0].value.toUpperCase() === `/EOF`) {
// End of file
break;
}
switch (statement[0].type) {
case `format`:
if (statement[0].value.toUpperCase() === `**CTDATA`) {
if (rules.NoCTDATA) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + statement[0].value.length},
type: `NoCTDATA`,
newValue: undefined,
});
}
}
break;
case `directive`:
value = statement[0].value;
if (rules.UppercaseDirectives) {
if (value !== value.toUpperCase()) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + value.length},
type: `UppercaseDirectives`,
newValue: value.toUpperCase()
});
}
}
if (rules.CopybookDirective) {
if ([`/COPY`, `/INCLUDE`].includes(value.toUpperCase())) {
const correctDirective = `/${rules.CopybookDirective.toUpperCase()}`;
if (value.toUpperCase() !== correctDirective) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + value.length},
type: `CopybookDirective`,
newValue: correctDirective
});
}
}
}
break;
case `declare`:
if (statement.length < 2) break;
if (rules.SpecificCasing) {
const caseRule = rules.SpecificCasing.find(rule => [statement[0].value.toUpperCase(), `*DECLARE`].includes(rule.operation.toUpperCase()));
if (caseRule) {
let expected = caseRule.expected;
switch (expected.toUpperCase()) {
case `*UPPER`:
expected = statement[0].value.toUpperCase();
break;
case `*LOWER`:
expected = statement[0].value.toLowerCase();
break;
}
if (statement[0].value !== expected) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + statement[0].value.length},
type: `SpecificCasing`,
newValue: expected
});
}
}
}
value = statement[1].value;
if (value.match(/^\d/)) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[1].position, length: statement[1].position + value.length},
type: `InvalidDeclareNumber`,
newValue: undefined
});
}
switch (statement[0].value.toUpperCase()) {
case `BEGSR`:
if (inProcedure) {
if (rules.NoLocalSubroutines) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: undefined,
type: `NoLocalSubroutines`,
newValue: undefined,
});
}
} else {
if (rules.NoGlobalSubroutines) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + statement[0].value.length},
type: `NoGlobalSubroutines`,
newValue: `Dcl-Proc`
});
}
}
break;
case `DCL-PROC`:
inProcedure = true;
if (statement.length < 2) break;
if (rules.RequiresProcedureDescription) {
value = statement[1].value;
const procDef = globalProcs.find(def => def.name.toUpperCase() === value.toUpperCase());
if (procDef) {
if (!procDef.description) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: undefined,
type: `RequiresProcedureDescription`,
newValue: undefined,
});
}
}
}
break;
case `DCL-C`:
if (rules.UppercaseConstants) {
if (value !== value.toUpperCase()) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[1].position, length: statement[1].position + value.length},
type: `UppercaseConstants`,
newValue: value.toUpperCase()
});
}
}
if (rules.StringLiteralDupe) {
if (statement[2].type === `string`) {
let foundBefore = stringLiterals.find(literal => literal.value === statement[2].value);
// If it does not exist on our list, we can add it
if (!foundBefore) {
foundBefore = {
definition: value,
value: statement[2].value,
list: []
};
stringLiterals.push(foundBefore);
}
}
}
break;
case `DCL-PI`:
if (!statement.some(s => s.type === `end`)) {
inPrototype = true;
}
break;
case `DCL-PR`:
inPrototype = true;
if (rules.PrototypeCheck) {
// Unneeded PR
if (!statement.some(part => part.value && part.value.toUpperCase().startsWith(`EXT`))) {
errors.push({
range: new vscode.Range(statementStart, statementEnd),
offset: undefined,
type: `PrototypeCheck`,
newValue: undefined,
});
}
}
break;
case `DCL-DS`:
if (rules.NoOCCURS) {
if (statement.some(part => part.value && part.value.toUpperCase() === `OCCURS`)) {
errors.push({
range: new vscode.Range(statementStart, statementEnd),
offset: undefined,
type: `NoOCCURS`,
newValue: undefined,
});
}
}
if (rules.QualifiedCheck) {
if (!statement.some(part => part.value && [`LIKEDS`, `LIKEREC`, `QUALIFIED`].includes(part.value.toUpperCase()))) {
errors.push({
range: new vscode.Range(statementStart, statementEnd),
offset: undefined,
type: `QualifiedCheck`,
newValue: undefined,
});
}
}
if (rules.BlankStructNamesCheck) {
if (statement.some(part => part.type === `special` && part.value.toUpperCase() === `*N`)) {
errors.push({
range: new vscode.Range(statementStart, statementEnd),
offset: undefined,
type: `BlankStructNamesCheck`,
newValue: undefined,
});
}
}
if (rules.NoCTDATA) {
if (statement.some(part => [`CTDATA`, `*CTDATA`].includes(part.value.toUpperCase()))) {
errors.push({
range: new vscode.Range(statementStart, statementEnd),
offset: undefined,
type: `NoCTDATA`,
newValue: undefined,
});
}
}
break;
}
break;
case `end`:
value = statement[0].value.toUpperCase();
if (rules.SpecificCasing) {
const caseRule = rules.SpecificCasing.find(rule => [value, `*DECLARE`].includes(rule.operation.toUpperCase()));
if (caseRule) {
let expected = caseRule.expected;
switch (expected.toUpperCase()) {
case `*UPPER`:
expected = statement[0].value.toUpperCase();
break;
case `*LOWER`:
expected = statement[0].value.toLowerCase();
break;
}
if (statement[0].value !== expected) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + value.length},
type: `SpecificCasing`,
newValue: expected
});
}
}
}
switch (value) {
case `ENDSR`:
if (inProcedure === false) {
if (rules.NoGlobalSubroutines) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + statement[0].value.length},
type: `NoGlobalSubroutines`,
newValue: `End-Proc`
});
}
}
break;
case `END-PROC`:
if (inProcedure === false) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + statement[0].value.length},
type: `UnexpectedEnd`,
newValue: undefined,
});
}
inProcedure = false;
break;
case `END-PR`:
case `END-PI`:
if (inPrototype === false) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + statement[0].value.length},
type: `UnexpectedEnd`,
newValue: undefined,
});
}
inPrototype = false;
break;
}
break;
case `word`:
value = statement[0].value.toUpperCase();
if (rules.SpecificCasing) {
const caseRule = rules.SpecificCasing.find(rule => value === rule.operation.toUpperCase());
if (caseRule) {
let expected = caseRule.expected;
switch (expected.toUpperCase()) {
case `*UPPER`:
expected = statement[0].value.toUpperCase();
break;
case `*LOWER`:
expected = statement[0].value.toLowerCase();
break;
}
if (statement[0].value !== expected) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + value.length},
type: `SpecificCasing`,
newValue: expected
});
}
}
}
switch (value.toUpperCase()) {
case `EVAL`:
case `CALLP`:
if (rules.UselessOperationCheck) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: statement[0].position, length: statement[0].position + value.length + 1},
type: `UselessOperationCheck`,
newValue: undefined,
});
}
break;
case `EXSR`:
if (rules.NoGlobalSubroutines) {
if (statement.length === 2) {
if (globalScope.subroutines.find(sub => sub.name.toUpperCase() === statement[1].value.toUpperCase())) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: undefined,
type: `NoGlobalSubroutines`,
newValue: `${statement[1].value}()`
});
}
}
}
break;
case `EXEC`:
if (rules.NoSELECTAll) {
if (currentStatementUpper.includes(`SELECT *`)) {
errors.push({
range: new vscode.Range(statementStart, statementEnd),
offset: undefined,
type: `NoSELECTAll`,
newValue: undefined,
});
}
}
if (rules.NoSQLJoins) {
if (statement.some(part => part.value && part.value.toUpperCase() === `JOIN`)) {
errors.push({
range: new vscode.Range(statementStart, statementEnd),
offset: undefined,
type: `NoSQLJoins`,
newValue: undefined,
});
}
}
break;
case `IF`:
case `ELSEIF`:
case `WHEN`:
case `DOW`:
case `DOU`:
if (rules.ForceOptionalParens) {
const lastStatement = statement[statement.length-1];
if (statement[1].type !== `openbracket` || lastStatement.type !== `closebracket`) {
errors.push({
range: new vscode.Range(
new vscode.Position(statementStart.line, statementStart.character + statement[0].value.length + 1),
statementEnd
),
offset: undefined,
type: `ForceOptionalParens`,
newValue: undefined,
});
}
}
break;
}
break;
}
}
let part;
if (statement.length > 0 && [`declare`, `end`].includes(statement[0].type) === false) {
for (let i = 0; i < statement.length; i++) {
part = statement[i];
if (part.value) {
switch (part.type) {
case `builtin`:
if (rules.SpecificCasing) {
const caseRule = rules.SpecificCasing.find(rule => [part.value.toUpperCase(), `*BIF`].includes(rule.operation.toUpperCase()));
if (caseRule) {
let expected = caseRule.expected;
switch (expected.toUpperCase()) {
case `*UPPER`:
expected = part.value.toUpperCase();
break;
case `*LOWER`:
expected = part.value.toLowerCase();
break;
}
if (part.value !== expected) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: part.position, length: part.position + part.value.length},
type: `SpecificCasing`,
newValue: expected
});
}
}
}
break;
case `special`:
if (rules.CollectReferences) {
value = part.value.substring(1).toUpperCase();
const defRef = globalScope.find(value);
if (defRef) {
defRef.references.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: part.position, length: part.position + part.value.length},
type: null,
newValue: undefined,
})
}
}
break;
case `word`:
const upperName = part.value.toUpperCase();
if (rules.NoGlobalsInProcedures) {
if (inProcedure && !inPrototype) {
const existingVariable = globalScope.variables.find(variable => variable.name.toUpperCase() === upperName);
if (existingVariable) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: part.position, length: part.position + part.value.length},
type: `NoGlobalsInProcedures`,
newValue: undefined,
});
}
}
}
if (rules.IncorrectVariableCase) {
// Check the casing of the reference matches the definition
const definedNames = currentScope.getNames();
const definedName = definedNames.find(defName => defName.toUpperCase() === upperName);
if (definedName && definedName !== part.value) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: part.position, length: part.position + part.value.length},
type: `IncorrectVariableCase`,
newValue: definedName
});
}
}
if (rules.RequiresParameter && !inPrototype) {
// Check the procedure reference has a block following it
const definedProcedure = globalProcs.find(proc => proc.name.toUpperCase() === upperName);
if (definedProcedure) {
let requiresBlock = false;
if (statement.length <= i+1) {
requiresBlock = true;
} else if (statement[i+1].type !== `openbracket`) {
requiresBlock = true;
}
if (requiresBlock) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: part.position, length: part.position + part.value.length},
type: `RequiresParameter`,
newValue: undefined,
});
}
}
}
if (rules.CollectReferences) {
let defRef;
if (currentProcedure) {
defRef = currentProcedure.scope.find(upperName);
}
if (!defRef) {
defRef = globalScope.find(upperName);
}
if (defRef) {
defRef.references.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: part.position, length: part.position + part.value.length},
type: null,
newValue: undefined,
})
}
}
break;
case `string`:
if (part.value.substring(1, part.value.length-1).trim() === `` && rules.RequireBlankSpecial) {
errors.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: part.position, length: part.position + part.value.length},
type: `RequireBlankSpecial`,
newValue: `*BLANK`
});
} else if (rules.StringLiteralDupe) {
let foundBefore = stringLiterals.find(literal => literal.value === part.value);
// If it does not exist on our list, we can add it
if (!foundBefore) {
foundBefore = {
value: part.value,
list: []
};
stringLiterals.push(foundBefore);
}
// Then add our new found literal location to the list
foundBefore.list.push({
range: new vscode.Range(
statementStart,
statementEnd
),
offset: {position: part.position, length: part.position + part.value.length}
});
}
break;
}
}
}
}
}
// We don't want to lint CTDATA... so that's the end
if (upperLine.startsWith(`**CTDATA`)) {
break;
}
currentStatement = ``;
}
}
// Next, check for indentation errors
if (indentEnabled && skipIndentCheck === false) {
pieces = upperLine.split(` `).filter(piece => piece !== ``);
opcode = pieces[0];
if ([
`ENDIF`, `ENDFOR`, `ENDDO`, `ELSE`, `ELSEIF`, `ON-ERROR`, `ENDMON`, `ENDSR`, `WHEN`, `OTHER`, `END-PROC`, `END-PI`, `END-PR`, `END-DS`, `ENDSL`
].includes(opcode)) {
expectedIndent -= indent;
//Special case for `ENDSL` and `END-PROC
if ([
`ENDSL`
].includes(opcode)) {
expectedIndent -= indent;
}
// Support for on-exit
if (opcode === `END-PROC` && inOnExit) {
inOnExit = false;
expectedIndent -= indent;
}
}
if (currentIndent !== expectedIndent) {
indentErrors.push({
line: lineNumber,
expectedIndent,
currentIndent
});
}
if ([
`IF`, `ELSE`, `ELSEIF`, `FOR`, `FOR-EACH`, `DOW`, `DOU`, `MONITOR`, `ON-ERROR`, `ON-EXIT`, `BEGSR`, `SELECT`, `WHEN`, `OTHER`, `DCL-PROC`, `DCL-PI`, `DCL-PR`, `DCL-DS`
].includes(opcode)) {
if ([`DCL-DS`, `DCL-PI`, `DCL-PR`].includes(opcode) && oneLineTriggers[opcode].some(trigger => upperLine.includes(trigger))) {
//No change
}
else if (opcode === `SELECT`) {
if (skipIndentCheck === false) expectedIndent += (indent*2);
}
else if (opcode === `ON-EXIT`) {
expectedIndent += indent;
inOnExit = true;
} else {
expectedIndent += indent;
}
}
}
}
}
if (stringLiterals.length > 0) {
const literalMinimum = rules.literalMinimum || 2;
stringLiterals.forEach(literal => {
if (literal.list.length >= literalMinimum) {
literal.list.forEach(location => {
errors.push({
...location,
type: `StringLiteralDupe`,
newValue: literal.definition
})
});
}
})
}
return {
indentErrors,
errors
};
}
} |
<reponame>bhm/Cthulhator
package com.bustiblelemons.cthulhator.character.characteristics.logic;
import com.bustiblelemons.cthulhator.system.properties.ActionGroup;
import com.bustiblelemons.cthulhator.system.properties.CharacterProperty;
import java.util.Comparator;
/**
* Created by bhm on 27.09.14.
*/
public enum CharacterPropertyComparators implements Comparator<CharacterProperty> {
ALPHABETICAL {
@Override
public int compare(CharacterProperty lhs, CharacterProperty rhs) {
if (lhs != null && rhs != null) {
String lName = lhs.getName();
String rName = rhs.getName();
return lName.compareTo(rName);
} else {
return super.compare(lhs, rhs);
}
}
}, VALUE_DESC {
@Override
public int compare(CharacterProperty lhs, CharacterProperty rhs) {
return 0 - VALUE.compare(lhs, rhs);
}
}, VALUE {
@Override
public int compare(CharacterProperty lhs, CharacterProperty rhs) {
if (lhs != null && rhs != null) {
int lVal = lhs.getValue();
int rVal = rhs.getValue();
if (lVal > rVal) {
return 1;
} else if (lVal < rVal) {
return -1;
} else {
return ALPHABETICAL.compare(lhs, rhs);
}
} else {
return super.compare(lhs, rhs);
}
}
}, ACTION_GROUP {
@Override
public int compare(CharacterProperty lhs, CharacterProperty rhs) {
if (lhs != null && rhs != null) {
ActionGroup lGroup = lhs.getMainActionGroup();
ActionGroup rGroup = rhs.getMainActionGroup();
if (lGroup != null && rGroup == null) {
return 1;
} else if (lGroup == null && rGroup != null) {
return -1;
} else if (lGroup == null && rGroup == null) {
return 0;
} else {
int byGroup = lGroup.compareTo(rGroup);
return byGroup == 0 ? ALPHABETICAL.compare(lhs, rhs) : byGroup;
}
} else {
return super.compare(lhs, rhs);
}
}
}, ACTION_BY_VALUE {
@Override
public int compare(CharacterProperty lhs, CharacterProperty rhs) {
if (lhs != null && rhs != null) {
ActionGroup lGroup = lhs.getMainActionGroup();
ActionGroup rGroup = rhs.getMainActionGroup();
if (lGroup != null && rGroup == null) {
return 1;
} else if (lGroup == null && rGroup != null) {
return -1;
} else if (lGroup == null && rGroup == null) {
return 0;
} else {
int byGroup = ACTION_GROUP.compare(lhs, rhs);
return byGroup == 0 ? VALUE.compare(lhs, rhs) : byGroup;
}
} else {
return super.compare(lhs, rhs);
}
}
};
@Override
public int compare(CharacterProperty lhs, CharacterProperty rhs) {
if (lhs != null && rhs == null) {
return 1;
} else if (lhs == null && rhs != null) {
return -1;
} else {
return 0;
}
}
}
|
#!/usr/bin/env bash
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Script entry point.
source $(dirname "$0")/e2e-secret-tests.sh
if [ "${SKIP_TESTS:-}" == "true" ]; then
echo "**************************************"
echo "*** TESTS SKIPPED ***"
echo "**************************************"
exit 0
fi
initialize $@
go_test_e2e -timeout=30m -parallel=12 ./test/conformance \
-channels='messaging.cloud.google.com/v1beta1:Channel' \
|| fail_test
success
|
import * as React from 'react'
import { spy } from 'sinon'
import { expect } from 'chai'
import TabScrollButton from './TabScrollButton'
import { createRenderer } from '../test/utils'
import { fireEvent } from '@testing-library/dom'
describe('<TabScrollButton />', () => {
const { render } = createRenderer()
describe('events', () => {
it('should be called mouse events', () => {
const handleClick = spy()
const handleMouseUp = spy()
const handleMouseDown = spy()
const { container } = render(
<TabScrollButton
direction="left"
onClick={handleClick}
onMouseUp={handleMouseUp}
onMouseDown={handleMouseDown}
/>
)
const button = container.querySelector('.tab-button')
fireEvent.click(button!)
fireEvent.mouseUp(button!)
fireEvent.mouseDown(button!)
expect(handleClick.callCount).to.equal(1)
expect(handleMouseUp.callCount).to.equal(1)
expect(handleMouseDown.callCount).to.equal(1)
})
})
describe('prop: ref', () => {
it('should be able to access ref', () => {
const buttonRef = React.createRef<HTMLButtonElement>()
render(<TabScrollButton direction="left" ref={buttonRef} />)
expect(buttonRef.current).not.null
expect(buttonRef.current!.nodeName).to.equal('BUTTON')
})
})
describe('prop: direction', () => {
it('should render with the direction classes', () => {
const { container, setProps } = render(
<TabScrollButton direction="left" />
)
const button = container.querySelector('.tab-button')
expect(button).to.have.class('tabs-scroll-buttons-left')
expect(button).not.have.class('tabs-scroll-buttons-right')
setProps({
direction: 'right'
})
expect(button).to.have.class('tabs-scroll-buttons-right')
expect(button).not.have.class('tabs-scroll-buttons-left')
})
})
describe('prop: orientation', () => {
it('should render with the orientation classes', () => {
const { container, setProps } = render(
<TabScrollButton direction="left" orientation="vertical" />
)
const button = container.querySelector('.tab-button')
expect(button).to.have.class('tabs-scroll-buttons-vertical')
setProps({
orientation: 'horizontal'
})
expect(button).not.have.class('tabs-scroll-buttons-vertical')
})
})
describe('prop: disabled', () => {
it('should render with the disabled and tab classes', () => {
const { container } = render(
<TabScrollButton direction="left" disabled />
)
const button = container.querySelector('.tab-button')
expect(button).to.have.class('tabs-scroll-buttons-disabled')
})
})
})
|
#!/bin/bash -e -o pipefail
################################################################################
## File: pypy.sh
## Desc: Installs PyPy
################################################################################
source ~/utils/utils.sh
function InstallPyPy
{
PACKAGE_URL=$1
PACKAGE_TAR_NAME=$(echo $PACKAGE_URL | awk -F/ '{print $NF}')
echo "Downloading tar archive '$PACKAGE_TAR_NAME' - '$PACKAGE_URL'"
PACKAGE_TAR_TEMP_PATH="/tmp/$PACKAGE_TAR_NAME"
wget -q -O $PACKAGE_TAR_TEMP_PATH $PACKAGE_URL
echo "Expand '$PACKAGE_TAR_NAME' to the /tmp folder"
tar xf $PACKAGE_TAR_TEMP_PATH -C /tmp
# Get Python version
PACKAGE_NAME=${PACKAGE_TAR_NAME/.tar.bz2/}
MAJOR_VERSION=$(echo ${PACKAGE_NAME/pypy/} | cut -d. -f1)
PYTHON_MAJOR="python$MAJOR_VERSION"
if [ $MAJOR_VERSION != 2 ]; then
PYPY_MAJOR="pypy$MAJOR_VERSION"
else
PYPY_MAJOR="pypy"
fi
PACKAGE_TEMP_FOLDER="/tmp/$PACKAGE_NAME"
PYTHON_FULL_VERSION=$("$PACKAGE_TEMP_FOLDER/bin/$PYPY_MAJOR" -c "import sys;print('{}.{}.{}'.format(sys.version_info[0],sys.version_info[1],sys.version_info[2]))")
# PyPy folder structure
PYPY_TOOLCACHE_PATH=$AGENT_TOOLSDIRECTORY/PyPy
PYPY_TOOLCACHE_VERSION_PATH=$PYPY_TOOLCACHE_PATH/$PYTHON_FULL_VERSION
PYPY_TOOLCACHE_VERSION_ARCH_PATH=$PYPY_TOOLCACHE_VERSION_PATH/x64
echo "Check if PyPy hostedtoolcache folder exist..."
if [ ! -d $PYPY_TOOLCACHE_PATH ]; then
mkdir -p $PYPY_TOOLCACHE_PATH
fi
echo "Create PyPy '$PYPY_TOOLCACHE_VERSION_PATH' folder"
mkdir $PYPY_TOOLCACHE_VERSION_PATH
echo "Move PyPy '$PACKAGE_TEMP_FOLDER' binaries to '$PYPY_TOOLCACHE_VERSION_ARCH_PATH' folder"
mv $PACKAGE_TEMP_FOLDER $PYPY_TOOLCACHE_VERSION_ARCH_PATH
echo "Create additional symlinks (Required for UsePythonVersion Azure DevOps task)"
cd $PYPY_TOOLCACHE_VERSION_ARCH_PATH/bin
ln -s $PYPY_MAJOR $PYTHON_MAJOR
ln -s $PYTHON_MAJOR python
chmod +x ./python ./$PYTHON_MAJOR
echo "Install latest Pip"
./python -m ensurepip
./python -m pip install --ignore-installed pip
echo "Create complete file"
touch $PYPY_TOOLCACHE_VERSION_PATH/x64.complete
echo "Remove '$PACKAGE_TAR_TEMP_PATH'"
rm -f $PACKAGE_TAR_TEMP_PATH
}
uri="https://downloads.python.org/pypy/"
pypyVersions=$(curl -4 -s --compressed $uri | grep 'osx64' | awk -v uri="$uri" -F'>|<' '{print uri$5}')
toolsetVersions=$(get_toolset_value '.toolcache[] | select(.name | contains("PyPy")) | .versions[]')
versionPattern="v[0-9]+\.[0-9]+\.[0-9]+-"
# PyPy 7.3.2 for High Sierra is broken, use 7.3.1 instead https://foss.heptapod.net/pypy/pypy/-/issues/3311
if is_HighSierra; then
versionPattern="v7.3.1-"
# PyPy 7.3.1 relies on system libffi.6.dylib, which is not existed in in libffi 3.3 release. As a workaround symlink can be created
ln -s libffi.7.dylib /usr/local/opt/libffi/lib/libffi.6.dylib
fi
for toolsetVersion in $toolsetVersions; do
latestMajorPyPyVersion=$(echo "${pypyVersions}" | grep -E "pypy${toolsetVersion}-${versionPattern}" | head -1)
if [[ -z "$latestMajorPyPyVersion" ]]; then
echo "Failed to get PyPy version '$toolsetVersion'"
exit 1
fi
InstallPyPy $latestMajorPyPyVersion
done |
#!/bin/bash
cp ec2/*.yaml templates/
cp iam/*.yaml templates/
|
/*
* Copyright 1993-97 <NAME> <<EMAIL>>
*
* Permission to use, copy, hack, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. This application is presented as is
* without any implied or written warranty.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* libhtmlw is copyright (C) 1993, Board of Trustees of the University
* of Illinois. See the file libhtmlw/HTML.c for the complete text of
* the NCSA copyright.
*/
/* $Id: logo.c,v 1.2 1997/07/18 01:23:55 elf Exp $ */
#include <stdio.h>
#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#ifdef HAVE_XPM
#include <X11/xpm.h>
/* default pixmap that goes in the corner*/
#include "xlogo.xpm"
#endif
#include "maindefs.h"
/* default bitmap that goes in the corner*/
#include "xlogo.bm"
/* Creates an icon pixmap and returns it in icon_pixmap. If xpm is
supported, use it.*/
void
loadLogo(char *logo, Pixmap *icon_pixmap, Pixel fg, Pixel bg)
{
extern Widget topLevel;
#ifdef HAVE_XPM
Pixmap shape_mask_return;
#endif
if(logo)
{
#ifdef MOTIF
#ifdef HAVE_XPM
int rv=XpmReadFileToPixmap(XtDisplay(topLevel)
,RootWindowOfScreen(XtScreen(topLevel))
,logo, icon_pixmap
,&shape_mask_return, NULL);
if(rv!=BitmapSuccess)
{
fprintf(stderr,BAD_BITMAP_MESSAGE, logo);
exit(-1);
}
#else
*icon_pixmap=XmGetPixmap(XtScreen(topLevel),
logo, fg, bg);
#endif /* HAVE_XPM*/
#else
unsigned int width, height;
/* read-in user-specified bitmap*/
int rv=XReadBitmapFile(XtDisplay(topLevel),
RootWindowOfScreen(XtScreen(topLevel)),
logo, &width, &height, icon_pixmap,
(int *)NULL, (int*)NULL);
if(rv!=BitmapSuccess)
{
/* if xpm support is compiled in...*/
#ifdef HAVE_XPM
/*... attempt to load it as an xpm file*/
rv=XpmReadFileToPixmap(XtDisplay(topLevel)
,RootWindowOfScreen(XtScreen(topLevel))
,logo, icon_pixmap
,&shape_mask_return, NULL);
#endif
if(rv!=BitmapSuccess)
{
fprintf(stderr,BAD_BITMAP_MESSAGE, logo);
exit(-1);
}
}
#endif /*MOTIF*/
}
else
{
#ifdef HAVE_XPM
/* display default X pixmap compiled-in*/
XpmCreatePixmapFromData(XtDisplay(topLevel),
RootWindowOfScreen(XtScreen(topLevel)),
xlogo_xpm, icon_pixmap,
&shape_mask_return, NULL);
#else
/* display default X bitmap compiled-in*/
/* Note: XCreateBitmapFromData doesn't seem to work under Motif
for some reason, but XCreatePixmapFromBitmapData works for
both, so we use it.*/
*icon_pixmap=
XCreatePixmapFromBitmapData(XtDisplay(topLevel),
RootWindowOfScreen(XtScreen(topLevel)),
xlogo_bits,xlogo_width,xlogo_height,
fg, bg,
DefaultDepthOfScreen(XtScreen(topLevel)));
#if 0
*icon_pixmap=
XCreateBitmapFromData(XtDisplay(topLevel),
RootWindowOfScreen(XtScreen(topLevel)),
xlogo_bits,xlogo_width,xlogo_height);
#endif
#endif /*HAVE_XPM*/
}
}/*loadLogo*/
|
#! /bin/bash
# docker image to build
IMAGE_NAME=thecloudgarage/cloudomate-backend-docker
# build image
sudo docker build -t $IMAGE_NAME .
|
<filename>js/Rainbow.js<gh_stars>1-10
"use strict";
function Rainbow()
{
this.shader = new ShaderProgram(rainbowVertexShader, rainbowFragmentShader)
// generate some tesselation to allow deforming the mesh
steps = 100
var points = []
for (var i = 0; i < steps; i++)
{
var x = (i / (steps - 1)) * 2.0 - 1.0;
points.push(x)
points.push(-1.0)
points.push(x)
points.push(1.0)
}
this.mesh = new VertexBuffer(2, gl.FLOAT, new Float32Array(points))
}
Rainbow.prototype.render = function(time)
{
gl.disable(gl.DEPTH_TEST)
gl.depthMask(false)
this.shader.bind()
this.shader.setFloatUniform("time", time)
var posAttribute = this.shader.getAttributeLocation("pos")
this.mesh.bind(posAttribute)
gl.drawArrays(gl.TRIANGLE_STRIP, 0, this.mesh.itemCount)
gl.enable(gl.DEPTH_TEST)
}
|
#import <CoreLocation/CLPlacemark.h>
@interface MKPlacemark : CLPlacemark
@end
|
#!/bin/bash
#SBATCH -J Act_maxout-3_1
#SBATCH --mail-user=eger@ukp.informatik.tu-darmstadt.de
#SBATCH --mail-type=FAIL
#SBATCH -e /work/scratch/se55gyhe/log/output.err.%j
#SBATCH -o /work/scratch/se55gyhe/log/output.out.%j
#SBATCH -n 1 # Number of cores
#SBATCH --mem-per-cpu=2000
#SBATCH -t 23:59:00 # Hours, minutes and seconds, or '#SBATCH -t 10' -only mins
#module load intel python/3.5
python3 /home/se55gyhe/Act_func/progs/meta.py maxout-3 1 Adagrad 3 0.6737871152033766 168 0.00966082122357274 glorot_uniform PE-infersent
|
class Employee:
def __init__(self, name, salary, job_assignment):
self.name = name
self.salary = salary
self.job_assignment = job_assignment
# other methods here |
#!/bin/bash
sudo python /home/lego-robot/lego_robot/marsz.py
|
#!/usr/bin/env bats
load test_helper
@test "($PLUGIN_COMMAND_PREFIX:create) success" {
run dokku "$PLUGIN_COMMAND_PREFIX:create" l
assert_contains "${lines[*]}" "container created: l"
dokku --force "$PLUGIN_COMMAND_PREFIX:destroy" l
}
@test "($PLUGIN_COMMAND_PREFIX:create) service with dashes" {
run dokku "$PLUGIN_COMMAND_PREFIX:create" service-with-dashes
assert_contains "${lines[*]}" "container created: service-with-dashes"
assert_contains "${lines[*]}" "dokku-$PLUGIN_COMMAND_PREFIX-service-with-dashes"
assert_contains "${lines[*]}" "service_with_dashes"
dokku --force "$PLUGIN_COMMAND_PREFIX:destroy" service-with-dashes
}
@test "($PLUGIN_COMMAND_PREFIX:create) error when there are no arguments" {
run dokku "$PLUGIN_COMMAND_PREFIX:create"
assert_contains "${lines[*]}" "Please specify a valid name for the service"
}
@test "($PLUGIN_COMMAND_PREFIX:create) error when there is an invalid name specified" {
run dokku "$PLUGIN_COMMAND_PREFIX:create" d.erp
assert_failure
}
|
#!/bin/sh
echo "********************************************************"
echo "Waiting for the eureka server to start on port $EUREKASERVER_PORT"
echo "********************************************************"
while ! `nc -z eurekaserver $EUREKASERVER_PORT`; do sleep 3; done
echo "******* Eureka Server has started"
echo "********************************************************"
echo "Waiting for the database server to start on port $DATABASESERVER_PORT"
echo "********************************************************"
while ! `nc -z database $DATABASESERVER_PORT`; do sleep 3; done
echo "******** Database Server has started "
echo "********************************************************"
echo "Waiting for the configuration server to start on port $CONFIGSERVER_PORT"
echo "********************************************************"
while ! `nc -z configserver $CONFIGSERVER_PORT`; do sleep 3; done
echo "******* Configuration Server has started"
echo "********************************************************"
echo "Waiting for the kafka server to start on port $KAFKASERVER_PORT"
echo "********************************************************"
while ! `nc -z kafkaserver $KAFKASERVER_PORT`; do sleep 10; done
echo "******* Kafka Server has started"
echo "********************************************************"
echo "Waiting for the ZIPKIN server to start on port $ZIPKIN_PORT"
echo "********************************************************"
while ! `nc -z zipkin $ZIPKIN_PORT`; do sleep 10; done
echo "******* ZIPKIN has started"
echo "********************************************************"
echo "Starting Organization Service "
echo "********************************************************"
java -Djava.security.egd=file:/dev/./urandom -Dserver.port=$SERVER_PORT \
-Deureka.client.serviceUrl.defaultZone=$EUREKASERVER_URI \
-Dspring.cloud.config.uri=$CONFIGSERVER_URI \
-Dsecurity.oauth2.resource.userInfoUri=$AUTHSERVER_URI \
-Dspring.profiles.active=$PROFILE \
-Dspring.cloud.stream.kafka.binder.zkNodes=$KAFKASERVER_URI \
-Dspring.cloud.stream.kafka.binder.brokers=$ZKSERVER_URI \
-Dspring.zipkin.baseUrl=$ZIPKIN_URI \
-jar /usr/local/organizationservice/@project.build.finalName@.jar |
<reponame>lukasmerk/it-sicherheit
#include <stdio.h>
#include <stdlib.h>
#include "largeInt.h"
/**
** Returns the number of leading zeroes of the given argument.
**
** A leading zero is a binary digit of the given arg that is set
** to 0 and to the left of which only appear 0's.
**/
uint8 GetNumberOfLeadingZeroes(uint32 arg) {
uint32 mask = 0x80000000U;
uint8 count = 0;
while (((arg & mask) == 0) && (count < 32)) {
mask = mask >> 1;
count++;
}
return count;
}
/**
** \brief Checks for leading zeroes and, based on the number of these,
** computes b->usedWords and b->bitSize.
**
** \param[in] b The BigInt, for which to compute the usage values.
**/
void RecomputeUsageVariables(LargeInt* b) {
uint32 i;
uint32* dataPointer;
i = b->wordSize - 1;
dataPointer = &(b->data[i]);
while (((*dataPointer) == 0) && (i>0)) {
i--;
dataPointer--;
}
b->bitSize = 32 - GetNumberOfLeadingZeroes((*dataPointer)) + (i * BITSPERWORD);
if (b->bitSize == 0) {
b->usedWords = 0;
} else {
b->usedWords = i + 1;
}
}
/**
** Returns TRUE if and only> if the given LargeInt is even.
**/
boolean IsEven(const LargeInt* b) {
uint32 mask = 0x1U;
if(!(b->data[0] & mask)) return TRUE;
return FALSE;
}
/**
** Returns TRUE if and only if the given LargeInt is odd.
**/
boolean IsOdd(const LargeInt* b) {
uint32 mask = 0x1U;
if(b->data[0] & mask) return TRUE;
return FALSE;
}
/**
** Initializes a new LargeInt with the given integer value.
**
** \param[in] value The value that is to be passed to the new LargeInt.
** \param[wordSize] The number of 32-Bit-words that shall used in the new LargeInt.
** \return A LargeInt that has been initialized with the given value.
**/
LargeInt* InitLargeIntWithUint32(uint32 value, uint8 wordSize) {
LargeInt* x = (LargeInt*)calloc(1, sizeof(LargeInt));
x->data = (uint32*)calloc(wordSize, sizeof(uint32));
x->wordSize = wordSize;
if (value == 0) {
x->usedWords = 0;
x->bitSize = 0;
} else {
x->usedWords = 0;
x->bitSize = 32 - GetNumberOfLeadingZeroes(value);
while (value > 0) {
x->data[x->usedWords] = value & STANDARD_USEBIT_MASK;
x->usedWords++;
value = value >> BITSPERWORD;
}
}
return x;
}
/**
* Frees the memory of the given LargeInt.
*/
void freeLargeInt(LargeInt* x) {
free(x->data);
free(x);
}
/**
** \brief Adds the two given summands and returns the result.
**
** This algorithm treats the arguments as if they were both
** positive, i.e. the sign of the integers is ignored.
**
** \param[in] s1 The first summand.
** \param[in] s2 The second summand.
** \result The sum of s1 and s2. The word size of the result
** is exactly as large as needed to hold the sum.
**
**/
LargeInt* Add(LargeInt* s1, LargeInt* s2) {
// Bitte implementieren!}
//neues largeint mit bitsize
uint32 maxwords, maxusedwords;
if(s1->wordSize > s2->wordSize) {
maxwords = s1->wordSize+1;
} else {
maxwords = s2->wordSize+1;
}
if(s1->usedWords > s2->usedWords) {
maxusedwords = s1->usedWords;
} else {
maxusedwords = s2->usedWords;
}
LargeInt* ergebnis = InitLargeIntWithUint32(0, maxwords);
uint32 i = 0;
uint8 uebertrag = 0;
while (i<=maxusedwords || uebertrag != 0)
{
ergebnis->data[i] += uebertrag;
ergebnis->data[i] += s1->data[i];
ergebnis->data[i] += s2->data[i];
uebertrag = STANDARD_CALCBIT_MASK & ergebnis->data[i];
ergebnis->data[i] = STANDARD_USEBIT_MASK & ergebnis->data[i];
if(uebertrag>0) uebertrag = 1;
i++;
}
RecomputeUsageVariables(ergebnis);
return ergebnis;
}
LargeInt* Multiply(LargeInt* m1, LargeInt* m2) {
uint32 maxwords, maxusedwords, minreqwords, words;
if(m1->wordSize > m2->wordSize) {
maxwords = m1->wordSize;
} else {
maxwords = m2->wordSize;
}
if(m1->usedWords > m2->usedWords) {
maxusedwords = m1->usedWords;
} else {
maxusedwords = m2->usedWords;
}
minreqwords = maxusedwords*2;
if(minreqwords>maxwords) {
words = minreqwords;
} else {
words = maxwords;
}
LargeInt* ergebnis = InitLargeIntWithUint32(0, words);
uint32 i;
uint32 j;
uint32 overflow;
for(i = 0; i<m1->usedWords; i++)
{
overflow = 0;
for(j=0; j<m2->usedWords; j++)
{
uint32 blockindex = i+j;
uint32 mulergebnis = m1->data[i]*m2->data[j];
uint32 teilergebnis = mulergebnis + overflow + ergebnis->data[blockindex];
ergebnis->data[blockindex] = teilergebnis & STANDARD_USEBIT_MASK;
overflow = teilergebnis & STANDARD_CALCBIT_MASK;
overflow >>= BITSPERWORD;
// continue;
// uint32 k = blockindex;
// uint32 uebertrag = 0;
// do
// {
// ergebnis->data[k] += uebertrag;
// uebertrag = ergebnis->data[k] & STANDARD_CALCBIT_MASK;
// ergebnis->data[k] &= STANDARD_USEBIT_MASK;
// uebertrag >>= BITSPERWORD;
// k++;
// } while (uebertrag != 0);
// uint16 carry = teilergebnis & STANDARD_CALCBIT_MASK;
// carry >>= BITSPERWORD;
// ergebnis->data[blockindex+1] += carry;
// k = blockindex+1;
// uebertrag = 0;
// do
// {
// ergebnis->data[k] += uebertrag;
// uebertrag = ergebnis->data[k] & STANDARD_CALCBIT_MASK;
// ergebnis->data[k] &= STANDARD_USEBIT_MASK;
// uebertrag >>= BITSPERWORD;
// k++;
// } while (uebertrag != 0);
// j++;
}
if(overflow > 0)
ergebnis->data[i+j] = overflow;
}
RecomputeUsageVariables(ergebnis);
return ergebnis;
}
void printLargeInt(LargeInt *x) {
int i = x->bitSize - 1;
while (i >= 0) {
int wordIndex = i / BITSPERWORD;
int bitIndex = i % BITSPERWORD;
uint32 testBit = 1 << bitIndex;
if ((x->data[wordIndex] & testBit) != 0) {
printf("1");
} else {
printf("0");
}
i--;
}
printf("\n");
}
// Verstehen Sie die untige main-Funktion bitte als Anstoß zum
// Testen Ihres Codes. Fügen Sie weitere, sinnvolle Tests hinzu!
int main() {
LargeInt* x = InitLargeIntWithUint32(70000, 5);
LargeInt* y = InitLargeIntWithUint32(80000, 5);
printLargeInt(x);
printLargeInt(y);
printf("%i\n", IsEven(x));
printf("%i\n", IsEven(y));
printf("%i\n", IsOdd(x));
printf("%i\n", IsOdd(y));
LargeInt* z = Add(x, y);
printLargeInt(z);
LargeInt* u = Multiply(x,y);
printLargeInt(u);
printf("100001011101110010011100000000000\n");
LargeInt* test = Multiply(InitLargeIntWithUint32(10,5),InitLargeIntWithUint32(10,5));
printLargeInt(test);
return 0;
}
|
<gh_stars>0
package logging
import (
"context"
"github.com/go-nacelle/nacelle"
)
type (
Decorator struct {
extractors []LogFieldExtractor
}
LogFieldExtractor func(ctx context.Context, fields nacelle.LogFields)
)
func NewDecorator(extractors ...LogFieldExtractor) *Decorator {
return &Decorator{
extractors: extractors,
}
}
func (d *Decorator) Register(extractor LogFieldExtractor) {
d.extractors = append(d.extractors, extractor)
}
func (d *Decorator) Decorate(ctx context.Context, logger nacelle.Logger) nacelle.Logger {
fields := nacelle.LogFields{}
for _, extractor := range d.extractors {
extractor(ctx, fields)
}
return logger.WithFields(fields)
}
|
<reponame>minuk8932/Algorithm_BaekJoon<gh_stars>1-10
package math;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
/**
*
* @author exponential-e
* 백준 16889번: 중복 없는 님 게임
*
* @see https://www.acmicpc.net/problem/16889
*
*/
public class Boj16889 {
private static final int SIZE = 60;
private static int[] grundy = new int[SIZE + 1];
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
grundyNumber(); // pre-find grundy table with recursion
int result = 0;
StringTokenizer st = new StringTokenizer(br.readLine());
for(int i = 0; i < N; i++) {
result ^= grundy[Integer.parseInt(st.nextToken())]; // who is the winner ?
}
System.out.println(result != 0 ? "koosaga": "cubelover");
}
private static void grundyNumber() {
int cut = 2;
int val = 0;
for(int i = 1; i < 61; i++) {
grundy[i] = (cut - 1);
val++;
if(val == cut) {
cut++;
val = 0;
}
}
}
}
|
"use strict";
var util = require("util");
module.exports = function getSerializableError(err) {
//this copying of properties is needed to get Error properties serialized by JSON.stringify
var output = {};
//In order to get stack trace and so on, we use Object.getOwnPropertyNames, to get non-enumerable properties
err && (typeof err === 'object') && Object.getOwnPropertyNames(err).forEach(function (property) {
if (err[property] !== undefined && property !== "nodeErrors") {
if (property === "innerError" || property === "internal") {
output[property] = getSerializableError(err[property]); //deep copy, even if it has cyclic references.
} else {
if (shouldSerialize(err[property])) {
output[property] = err[property];
} else {
output[property] = "[cyclic or too complex]";
}
}
}
});
return output;
};
function shouldSerialize(obj) {
var count = 0;
return _shouldSerialize(obj);
function _shouldSerialize(obj) {
count++;
if (count >= 1000) {
return false;
}
//default: stringify stuff that can not be run through Object.keys
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) {
return true;
}
if (util.isArray(obj)) {
for (var j = 0; j < obj.length; j++) {
if (!_shouldSerialize(obj[j])) {
return false;
}
}
}
//JSON.stringify stringifies enumerable properties, so we use Object.keys
var keys = Object.keys(obj), len = keys.length;
for (var i = 0; i < len; i++) {
if (!_shouldSerialize(obj[keys[i]])) {
return false;
}
}
return true;
}
} |
package org.jeecg.modules.base.service;
import org.jeecg.modules.base.entity.BimGtlfModel;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* @Description: 小模型库
* @Author: jeecg-boot
* @Date: 2021-12-10
* @Version: V1.0
*/
public interface IBimGtlfModelService extends IService<BimGtlfModel> {
}
|
# Create a BankAccount object with an initial balance of 1000
account = BankAccount(1000)
# Deposit 500 into the account
account.deposit(500)
# Withdraw 200 from the account
account.withdraw(200)
# Get the current balance of the account
print(account.getBalance()) # Output: 1300 |
<reponame>saltares/grannys-bloodbath<filename>src/engine/hud.h<gh_stars>1-10
/*
This file is part of Granny's Bloodbath.
Granny's Bloodbath is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Granny's Bloodbath is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Granny's Bloodbath. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _HUD_
#define _HUD_
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include "image.h"
#include "font.h"
//!Actualiza y muestra el estado de la abuela
/**
@author <NAME>
@version 1.0
Esta clase se encarga de actualizar el estado actual de la abuela y mostralo por pantalla.
Ejemplo:
\code
void Granny::update(){
...
...
hud.update(lifes,points,munition,energy);
}
void Granny::draw(SDL_Surface *Screen){
...
...
hud.draw(screen);
}
\endcode
*/
class HUD{
public:
/**
Constructor
Carga e inicializa los distinos recursos necesarios
@param path Ruta del archivo donde se encuentra la configuración deseada.
@param e energía máxima que podra tener la abuela.
*/
HUD(const char *path, int e);
/**
Destructor
Libera los distintos recursos cargados.
*/
~HUD();
/**
Se encarga de actualizar el estado actual de la abuela
@param l vidas actuales de la abuela
@param p puntos actuales de la abuela
@param m munición actual de la abuela
@param e energía actual de la abuela.
*/
void update(int l, int p, int m, int e);
/**
Método encargado de dibujar el hud sobre la imagen dada
@param screen superficie destino del hud.
*/
void draw(SDL_Surface* screen);
private:
SDL_Surface *bar;
Image *hud;
Font *font;
std::string points, lifes, munition, image_code, font_code;
SDL_Rect hud_destiny, bar_destiny;//, munition_destiny, lifes_destiny, points_destiny;
SDL_Color color;
int max_energy, energy, lifesx, lifesy, munitionx, munitiony, pointsx, pointsy;
};
#endif
|
from shutil import copy, SameFileError
from jinja2 import Environment, FileSystemLoader
from lib.common import json_from_file
import os
def generate_and_copy_report(template_path, data_path, destination_path):
# Read JSON data from file
data = json_from_file(data_path)
# Create Jinja2 environment and render template
env = Environment(loader=FileSystemLoader(os.path.dirname(template_path)))
template = env.get_template(os.path.basename(template_path))
rendered_report = template.render(data)
# Copy the rendered report to destination, handling SameFileError
destination_file = destination_path
count = 1
while os.path.exists(destination_file):
destination_file = f"{os.path.splitext(destination_path)[0]}_{count}{os.path.splitext(destination_path)[1]}"
count += 1
copy(rendered_report, destination_file)
return destination_file |
# |source| this file
#
# Common utilities shared by other scripts in this directory
#
# The following directive disable complaints about unused variables in this
# file:
# shellcheck disable=2034
#
# shellcheck source=net/common.sh
source "$(cd "$(dirname "${BASH_SOURCE[0]}")"/.. || exit 1; pwd)"/net/common.sh
if [[ $(uname) != Linux ]]; then
# Protect against unsupported configurations to prevent non-obvious errors
# later. Arguably these should be fatal errors but for now prefer tolerance.
if [[ -n $PANOPTES_CUDA ]]; then
echo "Warning: CUDA is not supported on $(uname)"
PANOPTES_CUDA=
fi
fi
if [[ -n $USE_INSTALL || ! -f "$PANOPTES_ROOT"/Cargo.toml ]]; then
panoptes_program() {
declare program="$1"
if [[ -z $program ]]; then
printf "panoptes"
else
printf "solana-%s" "$program"
fi
}
else
panoptes_program() {
declare program="$1"
declare crate="$program"
if [[ -z $program ]]; then
crate="cli"
program="panoptes"
else
program="panoptes-$program"
fi
if [[ -r "$PANOPTES_ROOT/$crate"/Cargo.toml ]]; then
maybe_package="--package panoptes-$crate"
fi
if [[ -n $NDEBUG ]]; then
maybe_release=--release
fi
declare manifest_path="--manifest-path=$PANOPTES_ROOT/$crate/Cargo.toml"
printf "cargo $CARGO_TOOLCHAIN run $manifest_path $maybe_release $maybe_package --bin %s %s -- " "$program"
}
fi
panoptes_bench_tps=$(panoptes_program bench-tps)
panoptes_faucet=$(panoptes_program faucet)
panoptes_validator=$(panoptes_program validator)
panoptes_validator_cuda="$panoptes_validator --cuda"
panoptes_genesis=$(panoptes_program genesis)
panoptes_gossip=$(panoptes_program gossip)
panoptes_keygen=$(panoptes_program keygen)
panoptes_ledger_tool=$(panoptes_program ledger-tool)
panoptes_cli=$(panoptes_program)
export RUST_BACKTRACE=1
default_arg() {
declare name=$1
declare value=$2
for arg in "${args[@]}"; do
if [[ $arg = "$name" ]]; then
return
fi
done
if [[ -n $value ]]; then
args+=("$name" "$value")
else
args+=("$name")
fi
}
replace_arg() {
declare name=$1
declare value=$2
default_arg "$name" "$value"
declare index=0
for arg in "${args[@]}"; do
index=$((index + 1))
if [[ $arg = "$name" ]]; then
args[$index]="$value"
fi
done
}
|
<filename>42-ping/srcs/sockets.c<gh_stars>1-10
#include "../includes/ping.h"
int create_raw_socket(t_ping *ping)
{
int sockfd, sockopt;
t_ip *ip;
ip = &ping->ip;
sockfd = 0x00;
if ((sockfd = socket(ip->domain, SOCK_RAW, IPPROTO_ICMP)) == -1) {
printf("init_raw_socket(): ipv%c socket creation failure.\n", (ip->type + 0x30));
return (0);
}
else if (sockfd < 3) {
printf("init_raw_socket(): ipv%c socket creation failure.\n", (ip->type + 0x30));
return (0);
}
sockopt = 0x01;
if ((setsockopt(sockfd, IPPROTO_IP, IP_HDRINCL, &sockopt, sizeof(int))) == -1) {
printf("init_raw_socket(): option set failure.\n");
return (0);
}
ip->fd.raw = sockfd;
return (1);
}
|
#!/bin/sh
#
# Vivado(TM)
# runme.sh: a Vivado-generated Runs Script for UNIX
# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved.
#
echo "This script was generated under a different operating system."
echo "Please update the PATH and LD_LIBRARY_PATH variables below, before executing this script"
exit
if [ -z "$PATH" ]; then
PATH=C:/APPZ/Xilinx/Vivado/2020.1/ids_lite/ISE/bin/nt64;C:/APPZ/Xilinx/Vivado/2020.1/ids_lite/ISE/lib/nt64:C:/APPZ/Xilinx/Vivado/2020.1/bin
else
PATH=C:/APPZ/Xilinx/Vivado/2020.1/ids_lite/ISE/bin/nt64;C:/APPZ/Xilinx/Vivado/2020.1/ids_lite/ISE/lib/nt64:C:/APPZ/Xilinx/Vivado/2020.1/bin:$PATH
fi
export PATH
if [ -z "$LD_LIBRARY_PATH" ]; then
LD_LIBRARY_PATH=
else
LD_LIBRARY_PATH=:$LD_LIBRARY_PATH
fi
export LD_LIBRARY_PATH
HD_PWD='D:/Documents/xnerad04/digital-electronics-1/labs/03-vivado/comparator/comparator.runs/synth_1'
cd "$HD_PWD"
HD_LOG=runme.log
/bin/touch $HD_LOG
ISEStep="./ISEWrap.sh"
EAStep()
{
$ISEStep $HD_LOG "$@" >> $HD_LOG 2>&1
if [ $? -ne 0 ]
then
exit
fi
}
EAStep vivado -log comparator_4bit.vds -m64 -product Vivado -mode batch -messageDb vivado.pb -notrace -source comparator_4bit.tcl
|
import React, {FC} from 'react';
import clsx from 'clsx';
import {Link} from 'react-router-dom';
import './TopNavLink.scss';
interface ComponentProps {
className?: string;
text: string;
to: string;
}
const TopNavLink: FC<ComponentProps> = ({className, text, to}) => {
return (
<Link className={clsx('TopNavLink', className)} to={to}>
{text}
</Link>
);
};
export default TopNavLink;
|
<filename>SAEFun/util/config.py
__author__ = 'LeoDong'
import os
import logging
# db
db_host = "localhost"
db_name = "sae"
db_user = "sae"
db_pass = "<PASSWORD>"
# logger
logger_level = logging.INFO
# const
const_IS_TARGET_SIGNLE = 1
const_IS_TARGET_MULTIPLE = 2
const_IS_TARGET_UNKNOW = 0
const_IS_TARGET_NO = -1
const_RULE_UNKNOW = [-1]
const_CONFIDENCE_THRESHOLD = 70
# path
path_root = os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0]
path_working = path_root + "/working"
path_knowledge = path_root + "/knowledge"
path_fe = path_knowledge + "/fe"
path_fe_space = path_fe + "/featurespace.xml"
path_judge_inbox = path_working + "/inbox_judge"
path_judge_dtree = path_knowledge+"/judge/dtree"
path_judge_list = path_working + "/judge_list"
path_extractor_inbox = path_working + "/inbox_extractor"
path_extractor_backup = path_working + "/backup_extractor"
path_extract_onto = path_knowledge + "/extract"
path_extract_list = path_working + "/extract_list"
path_data = path_root+"/data"
# socket
socket_host = "localhost"
socket_addr_judge = (socket_host,10001)
socket_addr_extractor = (socket_host,10002)
socket_addr_rulegen = (socket_host,10003)
socket_CMD_judge_new = "0"
socket_CMD_judge_done = "1"
socket_CMD_judge_list = "2"
socket_CMD_judge_refresh = "3"
socket_CMD_extractor_new = "0"
socket_CMD_extractor_list = "1"
socket_CMD_extractor_maps = "2"
socket_CMD_extractor_preview = "3"
socket_CMD_extractor_rejudge_done = "4"
socket_CMD_extractor_test_rule = "5"
socket_CMD_extractor_add_rule = "6"
socket_CMD_extractor_test_extractor = "7"
socket_CMD_extractor_add_extract = "8"
socket_CMD_extractor_refresh="9"
socket_retry_seconds = 10
extractor_same_layout_number = 0
#
# retriever_start_urls = ["https://www.cs.ox.ac.uk/"]
retriever_start_urls = ["http://www.ox.ac.uk/"]
retriever_allow_content_type = ["text/html"]
# retriever_allow_domains = ["cs.ox.ac.uk"]
retriever_allow_domains = ["ox.ac.uk"]
retriever_deny_domains = ["webauth.ox.ac.uk","weblearn.ox.ac.uk","facebook.com","linkedin.com"]
retriever_deny_extensions = [
"pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "png", "jpg", "gif", "ps", "tex", "bib", "zip",
"tar", "gz", "tgz", "java", "cpp", "c", "scala", "msi", "exe", "sh", "com", "bin", "mp4", "avi"]
retriever_deny_regxs = [
"(\.php|\.jsp|\.asp|\.do)\?",
"\?"
"(edit).*(\\.php|\\.jsp|\\.asp)",
"roombooking",
"&day=.*&month=.*&year=.*",
"/search(/|\?)",
"/login(/|\?)",
"/rss(/|\?)",
"/(N|n)ews(/|\?)",
"/(P|p)eople(/|\?)",
"/(P|p)roject(s)?(/|\?)",
"/(P|p)ublication(s)?(/|\?)",
"/examregs(/|\?)",
"/(P|p)rofile(/|\?)",
"/supervision(/|\?)",
"/(S|s)upport(/|\?)",
"/gazette(/|\?)",
"/(S|s)taff(/|\?)",
"/finance(/|\?)",
"/(U|u)ser(/|\?)",
"/sitemap(/|\?)",
"/finance(/|\?)",
"/statutes(/|\?)",
"/(A|a)bout(/|\?)",
"/admissions(/|\?)",
"/tag(/|\?)",
"/blog(/|\?)",
"/personnel(/|\?)",
"/supervision(/|\?)",
"/supervisor(/|\?)",
"/safety(/|\?)",
"/handbook(/|\?)",
"/fellow(s)?(/|\?)",
"/archives.",
"/share.",
"/podcasts."
"/learning/",
"/teaching/",
"/[a-zA-Z]*support/",
"/[a-z]*thesis/",
"/past(-[a-zA-Z])?/",
]
retriever_max_url_length = 512
retriever_download_time_out = 2
retriever_depth_limit = 4
retriever_absolute_url_replace_pattern = {
"link": "href",
"script": "src",
"img": "src",
}
layout_tag_remove = ["script", "map", "p", "link", "meta", "img", "br", "head", "span", "a", "h1", "h2", "h3", "h4",
"h5", "h6", "li"]
layout_tag_clear_attr = ["input"]
layout_attr_remove = ["name", "content", "src", "href", "id", "type", "action", "rel", "placeholder", "style", "for",
"data.*?"]
layout_attr_clear = ["onclick", "onmouseover", "alt", "title", "value", "onblur", "autocomplete", "maxlength",
"onfocus",
"usemap", "media", "itemscope"]
#dtree
dtree_param = {
"criterion": "entropy", #"gini"
"splitter": "best", #"best"
"max_features": None, #None
"max_depth": None, #None
"min_samples_split": 20, #2
"min_samples_leaf": 10, #1
"min_weight_fraction_leaf": 0., #0.
"max_leaf_nodes": None, #None
"class_weight": None, #None
"random_state": None #None
} |
#!/usr/bin/env -S bash -euET -o pipefail -O inherit_errexit
SCRIPT=$(readlink -f "$0") && cd $(dirname "$SCRIPT")
# --- Script Init ---
mkdir -p log
rm -R -f log/*
# --- Setup run dirs ---
find output -type f -not -name '*summary-info*' -not -name '*.json' -exec rm -R -f {} +
rm -R -f fifo/*
rm -R -f work/*
mkdir work/kat/
mkdir work/gul_S1_summaryaalcalc
mkfifo fifo/gul_P17
mkfifo fifo/gul_S1_summary_P17
# --- Do ground up loss computes ---
tee < fifo/gul_S1_summary_P17 work/gul_S1_summaryaalcalc/P17.bin > /dev/null & pid1=$!
summarycalc -m -g -1 fifo/gul_S1_summary_P17 < fifo/gul_P17 &
eve 17 20 | getmodel | gulcalc -S100 -L100 -r -c - > fifo/gul_P17 &
wait $pid1
# --- Do ground up loss kats ---
|
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// Name :
// Author : Avi
// Revision : $Revision: #11 $
//
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//
// Description :
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
#include <stdexcept>
#include "Pid.hpp"
#include <unistd.h> // for getpid
#include <boost/lexical_cast.hpp>
std::string Pid::getpid()
{
std::string pid;
try { pid = boost::lexical_cast<std::string>(::getpid()); }
catch (boost::bad_lexical_cast& e) {
throw std::runtime_error("Pid::getpid(): Could not convert PID to a string\n");
}
return pid;
}
std::string Pid::unique_name(const std:: string& prefix)
{
std::string ret = prefix;
ret += "_";
ret += Pid::getpid();
return ret;
}
|
/**
* @form Create Newsletter
* @param button
*/
function form2_create_item(form)
{
if(is_create_access('form2'))
{
if(is_online())
{
var nl_id=document.getElementById('form2_master').elements[3].value;
var type=form.elements[0].value;
var name=form.elements[1].value;
var detail=form.elements[2].value;
var url=form.elements[3].value;
var column_size=form.elements[6].value;
var data_id=form.elements[7].value;
var blob=$("#img_form2_"+data_id).attr('src');
var blob_name="client_images/"+data_id+".jpeg";
var del_button=form.elements[9];
var last_updated=get_my_time();
var data_xml="<newsletter_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<item_type>"+type+"</item_type>" +
"<item_detail>"+detail+"</item_detail>" +
"<nl_id>"+nl_id+"</nl_id>" +
"<url>"+url+"</url>"+
"<data_blob>"+blob+"</data_blob>"+
"<pic_url>"+blob_name+"</pic_url>"+
"<column_size>"+column_size+"</column_size>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</newsletter_items>";
$.ajax(
{
type: "POST",
url: server_root+"/ajax/save_image.php",
data:
{
blob: blob,
name:blob_name
}
});
console.log(data_xml);
server_create_simple(data_xml);
for(var i=0;i<7;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form2_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form2_update_item(form);
});
}
else
{
$("#modal6_link").click();
}
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create NewsLetter
* @param button
*/
function form2_create_form()
{
if(is_create_access('form2'))
{
var form=document.getElementById("form2_master");
var name=form.elements[1].value;
var description=form.elements[2].value;
var data_id=form.elements[3].value;
var save_button=form.elements[4];
var last_updated=get_my_time();
var data_xml="<newsletter>" +
"<id>"+data_id+"</id>" +
"<name unique='yes'>"+name+"</name>" +
"<description>"+description+"</description>"+
"<status>active</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</newsletter>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>newsletter</tablename>" +
"<link_to>form2</link_to>" +
"<title>Created</title>" +
"<notes>NewsLetter "+name+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form2_update_form();
});
$("[id^='save_form2_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Service bill
* @param button
*/
function form10_create_item(form)
{
if(is_create_access('form10'))
{
var bill_id=document.getElementById("form10_master").elements['bill_id'].value;
var name=form.elements[0].value;
var notes=form.elements[1].value;
var quantity=form.elements[2].value;
var price=form.elements[3].value;
var amount=form.elements[4].value;
var discount=form.elements[5].value;
var tax=form.elements[6].value;
var total=form.elements[7].value;
var data_id=form.elements[8].value;
var save_button=form.elements[9];
var del_button=form.elements[10];
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<unit_price>"+price+"</unit_price>" +
"<notes>"+notes+"</notes>" +
"<quantity>"+quantity+"</quantity>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<discount>"+discount+"</discount>" +
"<type>bought</type>" +
"<tax>"+tax+"</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
create_simple(data_xml);
for(var i=0;i<8;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form10_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Service Reciept
* @param button
*/
function form10_create_form()
{
if(is_create_access('form10'))
{
var form=document.getElementById("form10_master");
var customer=form.elements['customer'].value;
var order_num=form.elements['order_num'].value;
var bill_num=form.elements['bill_num'].value;
var bill_date=get_raw_time(form.elements['bill_date'].value);
var due_date=get_raw_time(form.elements['due_date'].value);
var payment_filter=form.elements['payment'];
$('#form10_share').show();
$('#form10_share').click(function()
{
modal101_action('Sale Bill',customer,'customer',function (func)
{
print_form10(func);
});
});
var quantity=0;
var amount=0;
var discount=0;
var tax=0;
var total=0;
$("[id^='save_form10_']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(!isNaN(parseFloat(subform.elements[2].value)))
{
quantity+=parseFloat(subform.elements[2].value);
}
if(!isNaN(parseFloat(subform.elements[4].value)))
{
amount+=parseFloat(subform.elements[4].value);
}
if(!isNaN(parseFloat(subform.elements[5].value)))
{
discount+=parseFloat(subform.elements[5].value);
}
if(!isNaN(parseFloat(subform.elements[6].value)))
{
tax+=parseFloat(subform.elements[6].value);
}
if(!isNaN(parseFloat(subform.elements[7].value)))
{
total+=parseFloat(subform.elements[7].value);
}
});
var data_id=form.elements['bill_id'].value;
var order_id=form.elements['order_id'].value;
var transaction_id=form.elements['t_id'].value;
var save_button=form.elements['save'];
var last_updated=get_my_time();
var data_xml="<bills>" +
"<id>"+data_id+"</id>" +
"<bill_num>"+bill_num+"</bill_num>"+
"<order_id>"+order_id+"</order_id>"+
"<order_num>"+order_num+"</order_num>"+
"<customer_name>"+customer+"</customer_name>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<due_date>"+due_date+"</due_date>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<total_quantity>"+quantity+"</total_quantity>" +
"<type>service</type>" +
"<discount>"+discount+"</discount>" +
"<tax>"+tax+"</tax>" +
"<transaction_id>"+transaction_id+"</transaction_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form42</link_to>" +
"<title>Saved</title>" +
"<notes>Bill no "+bill_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var sale_order_xml="<sale_orders>" +
"<id>"+order_id+"</id>" +
"<bill_id>"+data_id+"</bill_id>"+
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<tax>"+tax+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</sale_orders>";
var transaction_xml="<transactions>" +
"<id>"+transaction_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+tax+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>pending</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>0</paid_amount>" +
"<acc_name>"+customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+bill_num+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>bill_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(bill_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
update_simple(num_xml);
}
},num_data);
create_row(data_xml,activity_xml);
create_simple(transaction_xml);
update_simple(sale_order_xml);
create_simple(pt_xml);
create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id,function (mode,paid)
{
if(parseFloat(paid)==0)
payment_filter.value="Unpaid<br>Balance: Rs. "+total;
else if(parseFloat(paid)==parseFloat(total))
payment_filter.value="Paid<br>Balance: Rs. 0";
else
payment_filter.value="Partially paid<br>Balance: Rs. "+(parseFloat(total)-parseFloat(paid));
modal127_action();
});
});
var total_row="<tr><td colspan='2' data-th='Total'>Total<br>PCS: "+quantity+"</td>" +
"<td>Amount:</br>Discount: </br>Tax: </br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"Rs. "+discount+"</br>" +
"Rs. "+tax+"</br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form10_foot').html(total_row);
var sms="We have got your clothes for drycleaning (total "+quantity+" pcs). It will be processed and delivered back to you soon.";
var phone_xml="<customers>"+
"<phone></phone>"+
"<name></name>"+
"<acc_name exact='yes'>"+customer+"</acc_name>"+
"</customers>";
fetch_requested_data('',phone_xml,function(phones)
{
var to=phones[0].phone;
var customer_name=phones[0].name;
var sms_content=sms.replace(/customer_name/g,customer_name);
send_sms(to,sms_content,'transaction');
//hide_loader();
});
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form10_update_form();
});
$("[id^='save_form10_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form New Bill
* @param button
*/
function form12_create_item(form)
{
if(is_create_access('form12'))
{
var bill_id=document.getElementById("form12_master").elements[4].value;
var name=form.elements[0].value;
var batch=form.elements[1].value;
var quantity=form.elements[2].value;
var price=form.elements[3].value;
var total=form.elements[4].value;
var amount=form.elements[5].value;
var discount=form.elements[6].value;
var tax=form.elements[7].value;
var offer=form.elements[8].value;
var data_id=form.elements[9].value;
var free_product_name=form.elements[12].value;
var free_product_quantity=form.elements[13].value;
var storage=get_session_var('sales_store');
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+batch+"</batch>" +
"<unit_price>"+price+"</unit_price>" +
"<quantity>"+quantity+"</quantity>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<discount>"+discount+"</discount>" +
"<offer>"+offer+"</offer>" +
"<type>bought</type>" +
"<tax>"+tax+"</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<free_with></free_with>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
//////adding free product to the bill if applicable
if(free_product_name!="" && free_product_name!=null)
{
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var id=vUtil.newKey();
rowsHTML="<tr>";
rowsHTML+="<form id='form12_"+id+"'></form>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' readonly='readonly' form='form12_"+id+"' value='"+free_product_name+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' required form='form12_"+id+"' value='"+free_batch+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form12_"+id+"' value='"+free_product_quantity+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form12_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form12_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value='free with "+name+"'>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value='"+id+"'>";
rowsHTML+="<input type='button' class='save_icon' form='form12_"+id+"' id='save_form12_"+id+"' >";
rowsHTML+="<input type='button' class='delete_icon' form='form12_"+id+"' id='delete_form12_"+id+"' onclick='form12_delete_item($(this));'>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value=''>";
rowsHTML+="</td>";
rowsHTML+="</tr>";
$('#form12_body').prepend(rowsHTML);
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<free_with>"+name+"</free_with>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
else
{
$("#modal7_link").click();
}
});
}
for(var i=0;i<10;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[11];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form12_delete_item(del_button);
});
var save_button=form.elements[10];
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form New Bill
* @param button
*/
function form12_create_form()
{
if(is_create_access('form12'))
{
var form=document.getElementById("form12_master");
var customer=form.elements[1].value;
var bill_date=get_raw_time(form.elements[2].value);
var bill_num=form.elements[3].value;
var storage=get_session_var('sales_store');
var message_string="Bill from:"+encodeURIComponent(get_session_var('title'))+"\nAddress: "+get_session_var('address');
var amount=0;
var discount=0;
var tax=0;
var total=0;
$("[id^='save_form12']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
total+=parseFloat(subform.elements[4].value);
amount+=parseFloat(subform.elements[5].value);
discount+=parseFloat(subform.elements[6].value);
tax+=parseFloat(subform.elements[7].value);
message_string+="\nItem: "+subform.elements[0].value;
message_string+=" Quantity: "+subform.elements[2].value;
message_string+=" Total: "+subform.elements[4].value;
});
var data_id=form.elements[4].value;
var transaction_id=form.elements[6].value;
var last_updated=get_my_time();
var offer_detail="";
var offer_data="<offers>" +
"<criteria_type>min amount crossed</criteria_type>" +
"<criteria_amount upperbound='yes'>"+(amount-discount)+"</criteria_amount>" +
"<offer_type exact='yes'>bill</offer_type>" +
"<result_type></result_type>" +
"<discount_percent></discount_percent>" +
"<discount_amount></discount_amount>" +
"<quantity_add_percent></quantity_add_percent>" +
"<quantity_add_amount></quantity_add_amount>" +
"<free_product_name></free_product_name>" +
"<free_product_quantity></free_product_quantity>" +
"<offer_detail></offer_detail>" +
"<status array='yes'>active--extended</status>" +
"</offers>";
fetch_requested_data('',offer_data,function(offers)
{
offers.sort(function(a,b)
{
if(a.criteria_amount<b.criteria_amount)
{ return 1;}
else
{ return -1;}
});
for(var i in offers)
{
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
var dis=parseFloat(((amount-discount)*parseInt(offers[i].discount_percent))/100);
tax-=(tax*(dis/(amount-discount)));
discount+=dis;
total=amount-discount+tax;
}
else
{
var dis=parseFloat(offers[i].discount_amount)*(Math.floor((amount-discount)/parseFloat(offers[i].criteria_amount)));
tax-=(tax*(dis/(amount-discount)));
discount+=dis;
total=amount-discount+tax;
}
}
else if(offers[i].result_type=='product free')
{
var free_product_name=offers[i].free_product_name;
var free_product_quantity=parseFloat(offers[i].free_product_quantity)*(Math.floor(parseFloat(amount-discount)/parseFloat(offers[i].criteria_amount)));
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var id=vUtil.newKey();
rowsHTML="<tr>";
rowsHTML+="<form id='form12_"+id+"'></form>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' readonly='readonly' form='form12_"+id+"' value='"+free_product_name+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' required form='form12_"+id+"' value='"+free_batch+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form12_"+id+"' value='"+free_product_quantity+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form12_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form12_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value='free on the bill amount'>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value='"+id+"'>";
rowsHTML+="<input type='button' class='save_icon' form='form12_"+id+"' id='save_form12_"+id+"' >";
rowsHTML+="<input type='button' class='delete_icon' form='form12_"+id+"' id='delete_form12_"+id+"' onclick='form12_delete_item($(this));'>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form12_"+id+"' value=''>";
rowsHTML+="</td>";
rowsHTML+="</tr>";
$('#form12_body').prepend(rowsHTML);
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+data_id+"</bill_id>" +
"<free_with>bill</free_with>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
else
{
$("#modal7_link").click();
}
});
}
offer_detail=offers[i].offer_detail;
break;
}
var data_xml="<bills>" +
"<id>"+data_id+"</id>" +
"<bill_num></bill_num>"+
"<customer_name>"+customer+"</customer_name>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<type>product</type>" +
"<offer>"+offer_detail+"</offer>" +
"<discount>"+discount+"</discount>" +
"<tax>"+tax+"</tax>" +
"<transaction_id>"+transaction_id+"</transaction_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form42</link_to>" +
"<title>Saved</title>" +
"<notes>Bill no "+bill_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+transaction_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+tax+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>closed</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>"+total+"</paid_amount>" +
"<acc_name>"+customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+bill_num+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>bill_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(bill_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
if(is_online())
{
server_update_simple(num_xml);
}
else
{
local_update_simple(num_xml);
}
}
},num_data);
if(is_online())
{
server_create_row(data_xml,activity_xml);
server_create_simple(transaction_xml);
server_create_simple(pt_xml);
server_create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id);
});
}
else
{
local_create_row(data_xml,activity_xml);
local_create_simple(transaction_xml);
local_create_simple(pt_xml);
local_create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id);
});
}
message_string+="\nAmount: "+amount;
message_string+="\ndiscount: "+discount;
message_string+="\nTax: "+tax;
message_string+="\nTotal: "+total;
var subject="Bill from "+get_session_var('title');
$('#form12_share').show();
$('#form12_share').click(function()
{
modal44_action(customer,subject,message_string);
});
var total_row="<tr><td colspan='3' data-th='Total'>Total</td>" +
"<td>Amount:</br>Discount: </br>Tax: </br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"Rs. "+discount+"</br>" +
"Rs. "+tax+"</br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form12_foot').html(total_row);
});
var save_button=form.elements[7];
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form12_update_form();
});
$("[id^='save_form12_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Manage Tasks
* @param button
*/
function form14_create_item(form)
{
if(is_create_access('form14'))
{
var name=form.elements[0].value;
var assignee=form.elements[1].value;
var t_due=get_raw_time(form.elements[2].value);
var status=form.elements[3].value;
var hours=form.elements[7].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_xml="<task_instances>" +
"<id>"+data_id+"</id>" +
"<name>"+name+"</name>" +
"<assignee>"+assignee+"</assignee>" +
"<t_initiated>"+get_my_time()+"</t_initiated>" +
"<t_due>"+t_due+"</t_due>" +
"<status>"+status+"</status>" +
"<task_hours>"+hours+"</task_hours>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</task_instances>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>task_instances</tablename>" +
"<link_to>form14</link_to>" +
"<title>Added</title>" +
"<notes>Task "+name+" assigned to "+assignee+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var message_string="Due time: "+form.elements[2].value+"\nTask: "+name+"\nAssignee:"+assignee;
message_string=encodeURIComponent(message_string);
$("#form14_whatsapp_"+data_id).attr('href',"whatsapp://send?text="+message_string);
$("#form14_whatsapp_"+data_id).show();
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form14_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form14_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form New Purchase Order
* @param button
*/
function form24_create_item(form)
{
if(is_create_access('form24'))
{
var order_id=document.getElementById("form24_master").elements['order_id'].value;
var name=form.elements[0].value;
var desc=form.elements[1].value;
var quantity=form.elements[2].value;
var make=form.elements[3].value;
var supplier_sku=form.elements[4].value;
var mrp=form.elements[5].value;
var price=form.elements[6].value;
var amount=form.elements[7].value;
var tax_rate=form.elements[8].value;
var tax=form.elements[9].value;
var total=form.elements[10].value;
var data_id=form.elements[11].value;
var save_button=form.elements[12];
var del_button=form.elements[13];
var last_updated=get_my_time();
var data_xml="<purchase_order_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<item_desc>"+desc+"</item_desc>" +
"<quantity>"+quantity+"</quantity>" +
"<order_id>"+order_id+"</order_id>" +
"<make>"+make+"</make>" +
"<supplier_sku>"+supplier_sku+"</supplier_sku>" +
"<mrp>"+mrp+"</mrp>" +
"<price>"+price+"</price>" +
"<amount>"+amount+"</amount>" +
"<tax>"+tax+"</tax>" +
"<tax_rate>"+tax_rate+"</tax_rate>" +
"<total>"+total+"</total>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</purchase_order_items>";
create_simple(data_xml);
for(var i=0;i<11;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form24_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form New Purchase Order
* @param button
*/
function form24_create_form()
{
if(is_create_access('form24'))
{
var form=document.getElementById("form24_master");
var supplier=form.elements['supplier'].value;
var order_date=get_raw_time(form.elements['date'].value);
var order_num=form.elements['order_num'].value;
var status=form.elements['status'].value;
var data_id=form.elements['order_id'].value;
var save_button=form.elements['save'];
var cst='no'
if(form.elements['cst'].checked)
{
cst='yes';
}
var payment_mode=form.elements['mode'].value;
var bt=get_session_var('title');
var data_array=[];
var amount=0;
var tax=0;
var total=0;
var total_quantity=0;
var counter=0;
$("[id^='save_form24']").each(function(index)
{
counter+=1;
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(!isNaN(parseFloat(subform.elements[7].value)))
{
amount+=parseFloat(subform.elements[7].value);
tax+=parseFloat(subform.elements[9].value);
total+=parseFloat(subform.elements[10].value);
}
if(!isNaN(parseFloat(subform.elements[2].value)))
total_quantity+=parseFloat(subform.elements[2].value);
var new_object=new Object();
new_object['S.No.']=counter;
new_object['Item Name']=subform.elements[1].value;
new_object['SKU']=subform.elements[0].value;
new_object['Supplier SKU']=subform.elements[4].value;
new_object['Quantity']=subform.elements[2].value;
new_object['MRP']=subform.elements[5].value;
new_object['Price']=subform.elements[6].value;
new_object['Tax']=subform.elements[9].value;
new_object['Total']=subform.elements[10].value;
data_array.push(new_object);
});
var message_attachment=vUtil.objArrayToCSVString(data_array);
$('#form24_share').show();
$('#form24_share').click(function()
{
modal101_action(bt+' - PO# '+order_num+' - '+supplier,supplier,'supplier',function (func)
{
print_form296(func);
},'csv',message_attachment);
});
if(form.elements['cst'].checked)
{
cst='yes';
//tax+=.02*amount;
//total+=.02*amount;
}
amount=vUtil.round(amount,2);
tax=vUtil.round(tax,2);
total=vUtil.round(total,2);
var total_row="<tr><td colspan='2' data-th='Total'>Total Quantity: "+total_quantity+"</td>" +
"<td>Amount:<br>Tax: <br>Total: </td>" +
"<td>Rs. "+amount+"<br>" +
"Rs. "+tax+"<br> " +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form24_foot').html(total_row);
var last_updated=get_my_time();
var data_xml="<purchase_orders>" +
"<id>"+data_id+"</id>" +
"<supplier>"+supplier+"</supplier>" +
"<order_date>"+order_date+"</order_date>" +
"<status>"+status+"</status>" +
"<order_num>"+order_num+"</order_num>" +
"<amount>"+amount+"</amount>" +
"<tax>"+tax+"</tax>" +
"<total>"+total+"</total>" +
"<total_quantity>"+total_quantity+"</total_quantity>" +
"<quantity_received>0</quantity_received>" +
"<quantity_accepted>0</quantity_accepted>" +
"<quantity_qc_pending>0</quantity_qc_pending>" +
"<cst>"+cst+"</cst>"+
"<payment_mode>"+payment_mode+"</payment_mode>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</purchase_orders>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>purchase_orders</tablename>" +
"<link_to>form43</link_to>" +
"<title>Created</title>" +
"<notes>Purchase order # "+order_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var notification_xml="<notifications>" +
"<id>"+vUtil.newKey()+"</id>" +
"<t_generated>"+get_my_time()+"</t_generated>" +
"<data_id unique='yes'>"+data_id+"</data_id>" +
"<title>Purchase Order created</title>" +
"<notes>Purchase order # "+order_num+" has been created. Please review and place order.</notes>" +
"<link_to>form43</link_to>" +
"<status>pending</status>" +
"<target_user></target_user>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</notifications>";
create_row(data_xml,activity_xml);
create_simple(notification_xml);
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>po_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(order_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
if(is_online())
{
server_update_simple(num_xml);
}
else
{
local_update_simple(num_xml);
}
}
},num_data);
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form24_update_form();
});
$("[id^='save_form24_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 58
* form Manage Service pre-requisites
* @param button
*/
function form58_create_item(form)
{
if(is_create_access('form58'))
{
var service=form.elements[0].value;
var type=form.elements[1].value;
var requisite=form.elements[2].value;
var quantity=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_json={data_store:'pre_requisites',
log:'yes',
data:[{index:'id',value:data_id},
{index:'name',value:service},
{index:'type',value:'service'},
{index:'requisite_type',value:type},
{index:'requisite_name',value:requisite},
{index:'quantity',value:quantity},
{index:'last_updated',value:last_updated}],
log_data:{title:'Added',notes:'Pre-requisite for service '+service,link_to:'form58'}};
create_json(data_json);
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form58_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form58_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 59
* form Manage product pre-requisites
* @param button
*/
function form59_create_item(form)
{
if(is_create_access('form59'))
{
var product=form.elements[0].value;
var type=form.elements[1].value;
var requisite=form.elements[2].value;
var quantity=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var table='pre_requisites';
var data_xml="<"+table+">" +
"<id>"+data_id+"</id>" +
"<name>"+product+"</name>" +
"<type>product</type>" +
"<requisite_type>"+type+"</requisite_type>" +
"<requisite_name>"+requisite+"</requisite_name>" +
"<quantity>"+quantity+"</quantity>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</"+table+">";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>"+table+"</tablename>" +
"<link_to>form59</link_to>" +
"<title>Added</title>" +
"<notes>Pre-requisite for product "+product+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form59_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form59_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 61
* form service Attributes
* @param button
*/
function form61_create_item(form)
{
if(is_create_access('form61'))
{
var service=form.elements[0].value;
var attribute=form.elements[1].value;
var value=form.elements[2].value;
var data_id=form.elements[3].value;
var last_updated=get_my_time();
var data_xml="<attributes>" +
"<id>"+data_id+"</id>" +
"<name>"+service+"</name>" +
"<type>service</type>" +
"<attribute>"+attribute+"</attribute>" +
"<value>"+value+"</value>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</attributes>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>attributes</tablename>" +
"<link_to>form61</link_to>" +
"<title>Added</title>" +
"<notes>Attribute "+attribute+" for service "+service+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<3;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[5];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form61_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form61_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 62
* form Product reviews
* @param button
*/
function form62_create_item(form)
{
if(is_create_access('form62'))
{
var product=form.elements[0].value;
var reviewer=form.elements[1].value;
var detail=form.elements[2].value;
var rating=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var table='reviews';
var data_xml="<"+table+">" +
"<id>"+data_id+"</id>" +
"<name>"+product+"</name>" +
"<type>product</type>" +
"<reviewer>"+reviewer+"</reviewer>" +
"<detail>"+detail+"</detail>" +
"<rating>"+rating+"</rating>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</"+table+">";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>"+table+"</tablename>" +
"<link_to>form62</link_to>" +
"<title>Added</title>" +
"<notes>Review for product "+product+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form62_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form62_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 63
* form service reviews
* @param button
*/
function form63_create_item(form)
{
if(is_create_access('form63'))
{
var service=form.elements[0].value;
var reviewer=form.elements[1].value;
var detail=form.elements[2].value;
var rating=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var table='reviews';
var data_xml="<reviews>" +
"<id>"+data_id+"</id>" +
"<name>"+service+"</name>" +
"<type>service</type>" +
"<reviewer>"+reviewer+"</reviewer>" +
"<detail>"+detail+"</detail>" +
"<rating>"+rating+"</rating>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</reviews>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>reviews</tablename>" +
"<link_to>form63</link_to>" +
"<title>Added</title>" +
"<notes>Review for service "+service+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form63_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form63_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 64
* form Service Cross sells
* @param button
*/
function form64_create_item(form)
{
if(is_create_access('form64'))
{
var service=form.elements[0].value;
var cross_type=form.elements[1].value;
var cross_name=form.elements[2].value;
var data_id=form.elements[3].value;
var last_updated=get_my_time();
var data_xml="<cross_sells>" +
"<id>"+data_id+"</id>" +
"<name>"+service+"</name>" +
"<type>service</type>" +
"<cross_type>"+cross_type+"</cross_type>" +
"<cross_name>"+cross_name+"</cross_name>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</cross_sells>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>cross_sells</tablename>" +
"<link_to>form64</link_to>" +
"<title>Added</title>" +
"<notes>Cross selling of "+cross_name+" to service "+service+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[5];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form64_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form64_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 66
* form Cross sells
* @param button
*/
function form66_create_item(form)
{
if(is_create_access('form66'))
{
var product=form.elements[0].value;
var cross_type=form.elements[1].value;
var cross_name=form.elements[2].value;
var data_id=form.elements[3].value;
var last_updated=get_my_time();
var table='cross_sells';
var data_xml="<"+table+">" +
"<id>"+data_id+"</id>" +
"<name>"+product+"</name>" +
"<type>product</type>" +
"<cross_type>"+cross_type+"</cross_type>" +
"<cross_name>"+cross_name+"</cross_name>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</"+table+">";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>"+table+"</tablename>" +
"<link_to>form66</link_to>" +
"<title>Added</title>" +
"<notes>Cross selling of "+cross_name+" to product "+product+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[5];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form66_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form66_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form New Sale Order
* @param button
*/
function form69_create_item(form)
{
if(is_create_access('form69'))
{
var order_id=document.getElementById("form69_master").elements['order_id'].value;
var name=form.elements[2].value;
var desc=form.elements[3].value;
var quantity=form.elements[4].value;
var sp=form.elements[5].value;
var freight=form.elements[6].value;
var mrp=form.elements[7].value;
var amount=form.elements[8].value;
var tax=form.elements[9].value;
var total=form.elements[10].value;
var data_id=form.elements[11].value;
var save_button=form.elements[12];
var del_button=form.elements[13];
var tax_rate=form.elements[15].value;
var price=form.elements[17].value;
var last_updated=get_my_time();
var data_xml="<sale_order_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<item_desc>"+desc+"</item_desc>" +
"<quantity>"+quantity+"</quantity>" +
"<unit_price>"+price+"</unit_price>" +
"<selling_price>"+sp+"</selling_price>" +
"<mrp>"+mrp+"</mrp>" +
"<amount>"+amount+"</amount>" +
"<tax>"+tax+"</tax>" +
"<tax_rate>"+tax_rate+"</tax_rate>" +
"<freight>"+freight+"</freight>" +
"<total>"+total+"</total>" +
"<order_id>"+order_id+"</order_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</sale_order_items>";
create_simple(data_xml);
for(var i=0;i<11;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form69_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form New Sale Order
* @param button
*/
function form69_create_form()
{
if(is_create_access('form69'))
{
var form=document.getElementById("form69_master");
var customer=form.elements['customer'].value;
var order_date=get_raw_time(form.elements['order_date'].value);
var status=form.elements['status'].value;
var data_id=form.elements['order_id'].value;
var order_num=form.elements['order_num'].value;
var channel=form.elements['channel'].value;
var bill_type=form.elements['bill_type'].value;
var save_button=form.elements['save'];
var amount=0;
var freight=0;
var tax=0;
var total=0;
var total_quantity=0;
$("[id^='save_form69']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(!isNaN(parseFloat(subform.elements[8].value)))
amount+=parseFloat(subform.elements[8].value);
if(!isNaN(parseFloat(subform.elements[9].value)))
tax+=parseFloat(subform.elements[9].value);
if(!isNaN(parseFloat(subform.elements[6].value)))
freight+=parseFloat(subform.elements[6].value);
if(!isNaN(parseFloat(subform.elements[10].value)))
total+=parseFloat(subform.elements[10].value);
if(!isNaN(parseFloat(subform.elements[4].value)))
total_quantity+=parseFloat(subform.elements[4].value);
});
amount=vUtil.round(amount,2);
tax=vUtil.round(tax,2);
total=vUtil.round(total,2);
freight=vUtil.round(freight,2);
var total_row="<tr><td colspan='1' data-th='Total'>Total Quantity: "+total_quantity+"</td>" +
"<td>Amount:</br>Tax: <br>Freight: </br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"Rs. "+tax+"</br>" +
"Rs. "+freight+"</br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form69_foot').html(total_row);
var last_updated=get_my_time();
var data_xml="<sale_orders>" +
"<id>"+data_id+"</id>" +
"<customer_name>"+customer+"</customer_name>" +
"<order_date>"+order_date+"</order_date>" +
"<order_num>"+order_num+"</order_num>" +
"<channel>"+channel+"</channel>" +
"<status>"+status+"</status>" +
"<amount>"+amount+"</amount>" +
"<tax>"+tax+"</tax>" +
"<freight>"+freight+"</freight>" +
"<total>"+total+"</total>" +
"<total_quantity>"+total_quantity+"</total_quantity>" +
"<billing_type>"+bill_type+"</billing_type>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</sale_orders>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>sale_orders</tablename>" +
"<link_to>form70</link_to>" +
"<title>Created</title>" +
"<notes>Sale order # "+order_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>so_num</name>"+
"</user_preferences>";
get_single_column_data(function (num_ids)
{
if(num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+num_ids[0]+"</id>"+
"<value>"+(parseInt(order_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
update_simple(num_xml);
}
},num_data);
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form69_update_form();
});
$("[id^='save_form69_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* This function transforms a sale order into a bill
* It is applicable for product bills only
* @form 70
* @param order_id
*/
function form70_bill(order_id)
{
if(is_create_access('form70'))
{
show_loader();
var bill_type='product';
var bill_amount=0;
var bill_total=0;
var bill_offer="";
var bill_discount=0;
var bill_tax=0;
var pending_items_count=0;
var storage=get_session_var('sales_store');
///////selecting all ordered items////
var order_item_data="<sale_order_items>" +
"<id></id>" +
"<order_id exact='yes'>"+order_id+"</order_id>" +
"<item_name></item_name>" +
"<quantity></quantity>" +
"<notes></notes>" +
"</sale_order_items>";
fetch_requested_data('',order_item_data,function(order_items)
{
console.log(order_items);
pending_items_count=order_items.length;
order_items.forEach(function(order_item)
{
var item_amount=0;
var item_total=0;
var item_offer="";
var item_discount=0;
var item_tax=0;
get_inventory(order_item.item_name,'',function(quantity)
{
console.log(quantity);
if(parseFloat(quantity)>=parseFloat(order_item.quantity))
{
var batch_data="<product_instances count='1'>" +
"<batch></batch>" +
"<sale_price></sale_price>" +
"<product_name exact='yes'>"+order_item.item_name+"</product_name>" +
"</product_instances>";
fetch_requested_data('',batch_data,function(batches)
{
console.log(batches);
var batch="";
var sale_price=0;
if(batches.length>0)
{
batch=batches[0].batch;
sale_price=batches[0].sale_price;
}
//////adding offer details
item_amount=parseFloat(order_item.quantity)*parseFloat(sale_price);
var offer_data="<offers>" +
"<offer_type>product</offer_type>" +
"<product_name exact='yes'>"+order_item.item_name+"</product_name>" +
"<batch array='yes'>"+batch+"--all</batch>" +
"<criteria_type></criteria_type>" +
"<criteria_amount></criteria_amount>" +
"<criteria_quantity></criteria_quantity>" +
"<result_type></result_type>" +
"<discount_percent></discount_percent>" +
"<discount_amount></discount_amount>" +
"<quantity_add_percent></quantity_add_percent>" +
"<quantity_add_amount></quantity_add_amount>" +
"<free_product_name></free_product_name>" +
"<free_product_quantity></free_product_quantity>" +
"<offer_detail></offer_detail>" +
"<status array='yes'>active--extended</status>" +
"</offers>";
fetch_requested_data('',offer_data,function(offers)
{
offers.sort(function(a,b)
{
if(parseFloat(a.criteria_amount)<parseFloat(b.criteria_amount))
{ return 1;}
else if(parseFloat(a.criteria_quantity)<parseFloat(b.criteria_quantity))
{ return 1;}
else
{ return -1;}
});
for(var i in offers)
{
//console.log("found atleast one offer");
item_offer=offers[i].offer_detail;
if(offers[i].criteria_type=='min quantity crossed' && parseFloat(offers[i].criteria_quantity)<=parseFloat(order_item.quantity))
{
console.log("offer criteria met");
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
item_discount=parseFloat((item_amount*parseInt(offers[i].discount_percent))/100);
}
else
{
item_discount=parseFloat(offers[i].discount_amount)*(Math.floor(parseFloat(order_item.quantity)/parseFloat(offers[i].criteria_quantity)));
}
}
else if(offers[i].result_type=='quantity addition')
{
if(offers[i].quantity_add_percent!="" && offers[i].quantity_add_percent!=0 && offers[i].quantity_add_percent!="0")
{
order_item.quantity=parseFloat(order_item.quantity)*(1+(parseFloat(offers[i].quantity_add_percent)/100));
}
else
{
order_items.quantity=parseFloat(order_item.quantity)+(parseFloat(offers[i].quantity_add_amount)*(Math.floor(parseFloat(order_items.quantity)/parseFloat(offers[i].criteria_quantity))));
}
}
else if(offers[i].result_type=='product free')
{
//console.log("adding free product as per offer");
var free_product_name=offers[i].free_product_name;
var free_product_quantity=parseFloat(offers[i].free_product_quantity)*(Math.floor(parseFloat(order_item.quantity)/parseFloat(offers[i].criteria_quantity)));
get_inventory(free_product_name,'',function(free_quantities)
{
if(parseFloat(free_quantities)>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var bill_item_id=vUtil.newKey();
var free_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with>"+order_item.item_name+"</free_with>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
});
}
break;
}
else if(offers[i].criteria_type=='min amount crossed' && offers[i].criteria_amount<=item_amount)
{
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
item_discount=parseFloat((item_amount*parseInt(offers[i].discount_percent))/100);
}
else
{
item_discount=parseFloat(offers[i].discount_amount)*(Math.floor(parseFloat(item_amount)/parseFloat(offers[i].criteria_amount)));
}
}
else if(offers[i].result_type=='quantity addition')
{
if(offers[i].quantity_add_percent!="" && offers[i].quantity_add_percent!=0 && offers[i].quantity_add_percent!="0")
{
order_item.quantity=parseFloat(order_item.quantity)*(1+(parseFloat(offers[i].quantity_add_percent)/100));
}
else
{
order_item.quantity=parseFloat(order_item.quantity)+(parseFloat(offers[i].quantity_add_amount)*(Math.floor(parseFloat(item_amount)/parseFloat(offers[i].criteria_amount))));
}
}
else if(offers[i].result_type=='product free')
{
var free_product_name=offers[i].free_product_name;
var free_product_quantity=parseFloat(offers[i].free_product_quantity)*(Math.floor(parseFloat(bill_amount-bill_discount)/parseFloat(offers[i].criteria_amount)));
//////updating product quantity in inventory
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var bill_item_id=vUtil.newKey();
var free_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with>"+order_item.item_name+"</free_with>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
});
}
break;
}
}
var tax_data="<product_master>" +
"<name exact='yes'>"+order_item.item_name+"</name>" +
"<tax></tax>" +
"</product_master>";
fetch_requested_data('',tax_data,function(taxes)
{
console.log(taxes);
taxes.forEach(function(tax)
{
item_tax=parseFloat((parseFloat(tax.tax)*(item_amount-parseFloat(item_discount)))/100);
});
item_total=parseFloat(item_amount)+parseFloat(item_tax)-parseFloat(item_discount);
/////saving to bill item
var bill_item_id=vUtil.newKey();
var data_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+order_item.item_name+"</item_name>" +
"<batch>"+batch+"</batch>" +
"<unit_price>"+sale_price+"</unit_price>" +
"<quantity>"+order_item.quantity+"</quantity>" +
"<amount>"+item_amount+"</amount>" +
"<total>"+item_total+"</total>" +
"<discount>"+item_discount+"</discount>" +
"<offer>"+item_offer+"</offer>" +
"<type>bought</type>" +
"<tax>"+item_tax+"</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with></free_with>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bill_items>";
bill_amount+=item_amount;
bill_total+=item_total;
bill_discount+=item_discount;
bill_tax+=item_tax;
pending_items_count-=1;
console.log(data_xml);
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
});
});
});
}
else
{
pending_items_count-=1;
}
});
});
});
/////saving bill details
var bill_items_complete=setInterval(function()
{
if(pending_items_count===0)
{
clearInterval(bill_items_complete);
var order_data="<sale_orders>" +
"<id>"+order_id+"</id>" +
"<customer_name></customer_name>" +
"<order_date></order_date>" +
"<type>product</type>" +
"<status exact='yes'>pending</status>" +
"</sale_orders>";
fetch_requested_data('',order_data,function(sale_orders)
{
console.log(sale_orders);
///////////////////////////////////////////////////////////
var offer_data="<offers>" +
"<criteria_type exact='yes'>min amount crossed</criteria_type>" +
"<criteria_amount upperbound='yes'>"+(bill_amount-bill_discount)+"</criteria_amount>" +
"<offer_type exact='yes'>bill</offer_type>" +
"<result_type></result_type>" +
"<discount_percent></discount_percent>" +
"<discount_amount></discount_amount>" +
"<quantity_add_percent></quantity_add_percent>" +
"<quantity_add_amount></quantity_add_amount>" +
"<free_product_name></free_product_name>" +
"<free_product_quantity></free_product_quantity>" +
"<offer_detail></offer_detail>" +
"<status array='yes'>active--extended</status>" +
"</offers>";
fetch_requested_data('',offer_data,function(offers)
{
offers.sort(function(a,b)
{
if(parseFloat(a.criteria_amount)<parseFloat(b.criteria_amount))
{ return 1;}
else
{ return -1;}
});
for(var i in offers)
{
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
var dis=parseFloat(((bill_amount-bill_discount)*parseInt(offers[i].discount_percent))/100);
bill_tax-=(bill_tax*(dis/(bill_amount-bill_discount)));
bill_discount+=dis;
bill_total=bill_amount-bill_discount+bill_tax;
}
else
{
var dis=parseFloat(offers[i].discount_amount)*(Math.floor((bill_amount-bill_discount)/parseFloat(offers[i].criteria_amount)));
bill_tax-=(bill_tax*(dis/(bill_amount-bill_discount)));
bill_discount+=dis;
bill_total=bill_amount-bill_discount+bill_tax;
}
}
else if(offers[i].result_type=='product free')
{
var free_product_name=offers[i].free_product_name;
var free_product_quantity=parseFloat(offers[i].free_product_quantity)*(Math.floor(parseFloat(bill_amount-bill_discount)/parseFloat(offers[i].criteria_amount)));
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var bill_item_id=vUtil.newKey();
var free_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with>bill</free_with>" +
"<storage></storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
});
}
bill_offer=offers[i].offer_detail;
break;
}
console.log(sale_orders);
for(var z in sale_orders)
{
var sale_order_xml="<sale_orders>" +
"<id>"+order_id+"</id>" +
"<status>billed</status>" +
"</sale_orders>";
var bill_xml="<bills>" +
"<id>"+order_id+"</id>" +
"<customer_name>"+sale_orders[z].customer_name+"</customer_name>" +
"<bill_date>"+get_my_time()+"</bill_date>" +
"<amount>"+bill_amount+"</amount>" +
"<total>"+bill_total+"</total>" +
"<type>product</type>" +
"<offer>"+bill_offer+"</offer>" +
"<discount>"+bill_discount+"</discount>" +
"<tax>"+bill_tax+"</tax>" +
"<transaction_id>"+order_id+"</transaction_id>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+order_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form42</link_to>" +
"<title>Saved</title>" +
"<notes>Bill no "+order_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+order_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+bill_total+"</amount>" +
"<receiver>"+sale_orders[z].customer_name+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+bill_tax+"</tax>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>pending</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+bill_total+"</total_amount>" +
"<paid_amount>0</paid_amount>" +
"<acc_name>"+sale_orders[z].customer_name+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+order_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+order_id+"</source_info>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+bill_total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+sale_orders[z].customer_name+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</transactions>";
if(is_online())
{
server_update_simple(sale_order_xml);
server_create_row(bill_xml,activity_xml);
server_create_simple(transaction_xml);
server_create_simple(pt_xml);
server_create_simple(payment_xml);
}
else
{
local_update_simple(sale_order_xml);
local_create_row(bill_xml,activity_xml);
local_create_simple(transaction_xml);
local_create_simple(pt_xml);
local_create_simple(payment_xml);
}
}
hide_loader();
});
///////////////////////////////////////////////////////////
});
}
},100);
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Sale leads
* @param button
*/
function form81_create_item(form)
{
if(is_create_access('form81'))
{
var customer=form.elements[0].value;
var detail=form.elements[1].value;
var due_date=get_raw_time(form.elements[2].value);
var identified_by=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_xml="<sale_leads>" +
"<id>"+data_id+"</id>" +
"<customer>"+customer+"</customer>" +
"<detail>"+detail+"</detail>" +
"<due_date>"+due_date+"</due_date>" +
"<identified_by>"+identified_by+"</identified_by>" +
"<status>open</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</sale_leads>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>sale_leads</tablename>" +
"<link_to>form81</link_to>" +
"<title>Added</title>" +
"<notes>Sale lead for customer "+customer+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var customer_data="<customers>"+
"<id></id>"+
"<name></name>"+
"<phone></phone>"+
"<email></email>"+
"<acc_name exact='yes'>"+customer+"</acc_name>"+
"</customers>";
fetch_requested_data('',customer_data,function(customers)
{
var customer_name=customers[0].name;
var customer_phone=customers[0].phone;
var business_title=get_session_var('title');
var sms_content=get_session_var('sms_content');
var message=sms_content.replace(/customer_name/g,customer_name);
message=message.replace(/business_title/g,business_title);
send_sms(customer_phone,message,'transaction');
///////////////////////////////////////////////////////////////////////////////
var nl_name=get_session_var('default_newsletter');
var nl_id_xml="<newsletter>"+
"<id></id>"+
"<name exact='yes'>"+nl_name+"</name>"+
"</newsletter>";
get_single_column_data(function(nls)
{
if(nls.length>0)
{
var subject=nl_name;
var nl_id=nls[0];
print_newsletter(nl_name,nl_id,'mail',function(container)
{
var message=container.innerHTML;
var to_array=[{"name":customers[0].name,"email":customers[0].email,"customer_id":customers[0].id}];
var to=JSON.stringify(to_array);
var from=get_session_var('email');
send_email(to,from,business_title,subject,message,function(){});
});
}
},nl_id_xml);
});
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form81_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form81_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* This function transforms scanned items into a bill
* @form 82
*/
function form82_bill()
{
if(is_create_access('form82'))
{
var master_form=document.getElementById('form82_master');
var storage=get_session_var('sales_store');
var bill_type='product';
var bill_amount=0;
var bill_total=0;
var bill_offer="";
var bill_discount=0;
var bill_tax=0;
var pending_items_count=0;
var order_id=master_form.elements[4].value;
///////selecting all scanned items////
var order_items=new Array();
var message_string="Bill from:"+get_session_var('title')+"\nAddress: "+get_session_var('address');
$("[id^='delete_form82']").each(function(index)
{
var form_id=$(this).attr('form');
var form=document.getElementById(form_id);
var order_item=new Object();
order_item.item_name=form.elements[1].value;
order_item.batch=form.elements[2].value;
order_item.quantity=1;
order_item.sale_price=parseFloat(form.elements[3].value);
order_items.push(order_item);
message_string+="\nItem: "+form.elements[1].value;
message_string+=" Price: "+form.elements[3].value;
});
var scanned_items=new Array();
for(var i=0; i<order_items.length;i++)
{
var new_obj=new Object();
new_obj.item_name=order_items[i].item_name;
new_obj.batch=order_items[i].batch;
new_obj.sale_price=order_items[i].sale_price;
new_obj.quantity=parseFloat(order_items[i].quantity);
for(var j=i+1;j<order_items.length;j++)
{
if(order_items[j].item_name==new_obj.item_name && order_items[j].batch==new_obj.batch)
{
new_obj.quantity+=parseFloat(order_items[j].quantity);
order_items.splice(j,1);
j-=1;
}
}
scanned_items.push(new_obj);
}
pending_items_count=scanned_items.length;
scanned_items.forEach(function(order_item)
{
var item_amount=0;
var item_total=0;
var item_offer="";
var item_discount=0;
var item_tax=0;
var batch=order_item.batch;
var sale_price=order_item.sale_price;
//////adding offer details
item_amount=parseFloat(order_item.quantity)*parseFloat(sale_price);
var offer_data="<offers>" +
"<offer_type>product</offer_type>" +
"<product_name exact='yes'>"+order_item.item_name+"</product_name>" +
"<batch array='yes'>"+batch+"--all</batch>" +
"<criteria_type></criteria_type>" +
"<criteria_amount></criteria_amount>" +
"<criteria_quantity></criteria_quantity>" +
"<result_type></result_type>" +
"<discount_percent></discount_percent>" +
"<discount_amount></discount_amount>" +
"<quantity_add_percent></quantity_add_percent>" +
"<quantity_add_amount></quantity_add_amount>" +
"<free_product_name></free_product_name>" +
"<free_product_quantity></free_product_quantity>" +
"<offer_detail></offer_detail>" +
"<status array='yes'>active--extended</status>" +
"</offers>";
fetch_requested_data('',offer_data,function(offers)
{
offers.sort(function(a,b)
{
if(a.criteria_amount<b.criteria_amount)
{ return 1;}
else if(a.criteria_quantity<b.criteria_quantity)
{ return 1;}
else
{ return -1;}
});
for(var i in offers)
{
//console.log("found atleast one offer");
item_offer=offers[i].offer_detail;
if(offers[i].criteria_type=='min quantity crossed' && parseFloat(offers[i].criteria_quantity)<=parseFloat(order_item.quantity))
{
//console.log("offer criteria met");
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
item_discount=parseFloat((item_amount*parseInt(offers[i].discount_percent))/100);
}
else
{
item_discount=parseFloat(offers[i].discount_amount)*(Math.floor(parseFloat(order_item.quantity)/parseFloat(offers[i].criteria_quantity)));
}
}
else if(offers[i].result_type=='quantity addition')
{
if(offers[i].quantity_add_percent!="" && offers[i].quantity_add_percent!=0 && offers[i].quantity_add_percent!="0")
{
order_item.quantity=parseFloat(order_item.quantity)*(1+(parseFloat(offers[i].quantity_add_percent)/100));
}
else
{
order_items.quantity=parseFloat(order_item.quantity)+(parseFloat(offers[i].quantity_add_amount)*(Math.floor(parseFloat(order_items.quantity)/parseFloat(offers[i].criteria_quantity))));
}
}
else if(offers[i].result_type=='product free')
{
//console.log("adding free product as per offer");
var free_product_name=offers[i].free_product_name;
var free_product_quantity=parseFloat(offers[i].free_product_quantity)*(Math.floor(parseFloat(order_item.quantity)/parseFloat(offers[i].criteria_quantity)));
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var bill_item_id=vUtil.newKey();
var free_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with>"+order_item.item_name+"</free_with>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
});
}
break;
}
else if(offers[i].criteria_type=='min amount crossed' && offers[i].criteria_amount<=item_amount)
{
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
item_discount=parseFloat((item_amount*parseInt(offers[i].discount_percent))/100);
}
else
{
item_discount=parseFloat(offers[i].discount_amount)*(Math.floor(parseFloat(item_amount)/parseFloat(offers[i].criteria_amount)));
}
}
else if(offers[i].result_type=='quantity addition')
{
if(offers[i].quantity_add_percent!="" && offers[i].quantity_add_percent!=0 && offers[i].quantity_add_percent!="0")
{
order_item.quantity=parseFloat(order_item.quantity)*(1+(parseFloat(offers[i].quantity_add_percent)/100));
}
else
{
order_item.quantity=parseFloat(order_item.quantity)+(parseFloat(offers[i].quantity_add_amount)*(Math.floor(parseFloat(item_amount)/parseFloat(offers[i].criteria_amount))));
}
}
else if(offers[i].result_type=='product free')
{
var free_product_name=offers[i].free_product_name;
var free_product_quantity=parseFloat(offers[i].free_product_quantity)*(Math.floor(parseFloat(bill_amount-bill_discount)/parseFloat(offers[i].criteria_amount)));
//////updating product quantity in inventory
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var bill_item_id=vUtil.newKey();
var free_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with>"+order_item.item_name+"</free_with>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
});
}
break;
}
}
var tax_data="<product_master>" +
"<name exact='yes'>"+order_item.item_name+"</name>" +
"<tax></tax>" +
"</product_master>";
fetch_requested_data('',tax_data,function(taxes)
{
taxes.forEach(function(tax)
{
item_tax=parseFloat((parseFloat(tax.tax)*(item_amount-parseFloat(item_discount)))/100);
});
item_total=parseFloat(item_amount)+parseFloat(item_tax)-parseFloat(item_discount);
/////saving to bill item
var bill_item_id=vUtil.newKey();
var data_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+order_item.item_name+"</item_name>" +
"<batch>"+batch+"</batch>" +
"<unit_price>"+sale_price+"</unit_price>" +
"<quantity>"+order_item.quantity+"</quantity>" +
"<amount>"+item_amount+"</amount>" +
"<total>"+item_total+"</total>" +
"<discount>"+item_discount+"</discount>" +
"<offer>"+item_offer+"</offer>" +
"<type>bought</type>" +
"<tax>"+item_tax+"</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with></free_with>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bill_items>";
bill_amount+=item_amount;
bill_total+=item_total;
bill_discount+=item_discount;
bill_tax+=item_tax;
pending_items_count-=1;
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
});
});
});
/////saving bill details
var bill_items_complete=setInterval(function()
{
if(pending_items_count===0)
{
clearInterval(bill_items_complete);
var customer=master_form.elements[1].value;
var bill_date=master_form.elements[2].value;
var bill_num=master_form.elements[3].value;
///////////////////////////////////////////////////////////
var offer_data="<offers>" +
"<criteria_type>min amount crossed</criteria_type>" +
"<criteria_amount upperbound='yes'>"+(bill_amount-bill_discount)+"</criteria_amount>" +
"<offer_type exact='yes'>bill</offer_type>" +
"<result_type></result_type>" +
"<discount_percent></discount_percent>" +
"<discount_amount></discount_amount>" +
"<quantity_add_percent></quantity_add_percent>" +
"<quantity_add_amount></quantity_add_amount>" +
"<free_product_name></free_product_name>" +
"<free_product_quantity></free_product_quantity>" +
"<offer_detail></offer_detail>" +
"<status array='yes'>active--extended</status>" +
"</offers>";
fetch_requested_data('',offer_data,function(offers)
{
offers.sort(function(a,b)
{
if(parseFloat(a.criteria_amount)<parseFloat(b.criteria_amount))
{ return 1;}
else
{ return -1;}
});
for(var i in offers)
{
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
var dis=parseFloat(((bill_amount-bill_discount)*parseInt(offers[i].discount_percent))/100);
bill_tax-=(bill_tax*(dis/(bill_amount-bill_discount)));
bill_discount+=dis;
bill_total=bill_amount-bill_discount+bill_tax;
}
else
{
var dis=parseFloat(offers[i].discount_amount)*(Math.floor((bill_amount-bill_discount)/parseFloat(offers[i].criteria_amount)));
bill_tax-=(bill_tax*(dis/(bill_amount-bill_discount)));
bill_discount+=dis;
bill_total=bill_amount-bill_discount+bill_tax;
}
}
else if(offers[i].result_type=='product free')
{
var free_product_name=offers[i].free_product_name;
var free_product_quantity=parseFloat(offers[i].free_product_quantity)*(Math.floor(parseFloat(bill_amount-bill_discount)/parseFloat(offers[i].criteria_amount)));
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var bill_item_id=vUtil.newKey();
var free_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with>bill</free_with>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
});
}
bill_offer=offers[i].offer_detail;
break;
}
var total_row="<tr><td colspan='2' data-th='Total'>Total</td>" +
"<td>Amount:</br>Discount: </br>Tax: </br>Total: </td>" +
"<td>Rs. "+bill_amount+"</br>" +
"Rs. "+bill_discount+"</br>" +
"Rs. "+bill_tax+"</br>" +
"Rs. "+bill_total+"</td>" +
"<td></td>" +
"</tr>";
$('#form82_foot').html(total_row);
var save_button=master_form.elements[7];
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
});
message_string+="\nAmount: "+bill_amount;
message_string+="\ndiscount: "+bill_discount;
message_string+="\nTax: "+bill_tax;
message_string+="\nTotal: "+bill_total;
var subject="Bill from "+get_session_var('title');
$('#form82_share').show();
$('#form82_share').click(function()
{
modal44_action(customer,subject,message_string);
});
var bill_xml="<bills>" +
"<id>"+order_id+"</id>" +
"<bill_num>"+bill_num+"</bill_num>"+
"<customer_name>"+customer+"</customer_name>" +
"<bill_date>"+get_raw_time(bill_date)+"</bill_date>" +
"<amount>"+bill_amount+"</amount>" +
"<total>"+bill_total+"</total>" +
"<type>product</type>" +
"<offer>"+bill_offer+"</offer>" +
"<discount>"+bill_discount+"</discount>" +
"<tax>"+bill_tax+"</tax>" +
"<transaction_id>"+order_id+"</transaction_id>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+order_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form42</link_to>" +
"<title>Saved</title>" +
"<notes>Bill no "+bill_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+order_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+bill_total+"</amount>" +
"<receiver>"+customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+bill_tax+"</tax>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>closed</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+bill_total+"</total_amount>" +
"<paid_amount>"+bill_total+"</paid_amount>" +
"<acc_name>"+customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+order_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+bill_num+"</source_info>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+bill_total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</transactions>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>bill_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(bill_num)+1)+"</value>"+
"<last_updated>"+get_my_time()+"</last_updated>"+
"</user_preferences>";
if(is_online())
{
server_update_simple(num_xml);
}
else
{
local_update_simple(num_xml);
}
}
},num_data);
if(is_online())
{
server_create_row(bill_xml,activity_xml);
server_create_simple(transaction_xml);
server_create_simple(pt_xml);
server_create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id);
});
}
else
{
local_create_row(bill_xml,activity_xml);
local_create_simple(transaction_xml);
local_create_simple(pt_xml);
local_create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id);
});
}
});
}
},100);
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Manage Subscriptions
* @param button
*/
function form84_create_item(form)
{
if(is_create_access('form84'))
{
var customer=form.elements[0].value;
var service=form.elements[1].value;
var status=form.elements[2].value;
var notes=form.elements[3].value;
var data_id=form.elements[5].value;
var last_updated=get_my_time();
var next_due_date=get_my_time();
var data_xml="<service_subscriptions>" +
"<id>"+data_id+"</id>" +
"<customer>"+customer+"</customer>" +
"<service>"+service+"</service>" +
"<status>"+status+"</status>" +
"<notes>"+notes+"</notes>" +
"<next_due_date>"+next_due_date+"</next_due_date>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</service_subscriptions>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>service_subscriptions</tablename>" +
"<link_to>form84</link_to>" +
"<title>Added</title>" +
"<notes>Customer "+customer+" for subscription to "+service+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[7];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form84_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form84_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Manage Subscriptions
* @formNo 84
*/
function form84_bills()
{
var due_lead_time=parseFloat(get_my_time())+86400000;
var subscriptions_data="<service_subscriptions>" +
"<id></id>" +
"<customer></customer>" +
"<service></service>" +
"<status exact='yes'>active</status>" +
"<notes></notes>" +
"<next_due_date upperbound='yes'>"+due_lead_time+"</next_due_date>" +
"</service_subscriptions>";
fetch_requested_data('',subscriptions_data,function(subscriptions)
{
subscriptions.forEach(function(subscription)
{
var bill_type='service';
var order_id=vUtil.newKey();
var item_amount=0;
var item_total=0;
var item_offer="";
var item_discount=0;
var item_tax=0;
var service_data="<services count='1'>" +
"<name exact='yes'>"+subscription.service+"</name>" +
"<price></price>" +
"<tax></tax>" +
"</services>";
fetch_requested_data('',service_data,function(services)
{
item_amount=parseFloat(services[0].price);
var offer_data="<offers>" +
"<offer_type>service</offer_type>" +
"<service exact='yes'>"+subscriptions.service+"</service>" +
"<criteria_type></criteria_type>" +
"<criteria_amount></criteria_amount>" +
"<criteria_quantity></criteria_quantity>" +
"<result_type></result_type>" +
"<discount_percent></discount_percent>" +
"<discount_amount></discount_amount>" +
"<quantity_add_percent></quantity_add_percent>" +
"<quantity_add_amount></quantity_add_amount>" +
"<free_product_name></free_product_name>" +
"<free_product_quantity></free_product_quantity>" +
"<offer_detail></offer_detail>" +
"<status array='yes'>active--extended</status>" +
"</offers>";
fetch_requested_data('',offer_data,function(offers)
{
offers.sort(function(a,b)
{
if(a.criteria_amount<b.criteria_amount)
{ return 1;}
else
{ return -1;}
});
for(var i in offers)
{
item_offer=offers[i].offer_detail;
if(offers[i].criteria_type=='min quantity crossed' && parseFloat(offers[i].criteria_quantity)<=1)
{
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
item_discount=parseFloat((item_amount*parseInt(offers[i].discount_percent))/100);
}
else
{
item_discount=parseFloat(offers[i].discount_amount)*(Math.floor(1/parseFloat(offers[i].criteria_quantity)));
}
}
else if(offers[i].result_type=='service free')
{
var free_service_name=offers[i].free_service_name;
var id=vUtil.newKey();
var free_pre_requisite_data="<pre_requisites>" +
"<type exact='yes'>service</type>" +
"<requisite_type exact='yes'>task</requisite_type>" +
"<name exact='yes'>"+free_service_name+"</name>" +
"<requisite_name></requisite_name>" +
"<quantity></quantity>" +
"</pre_requisites>";
fetch_requested_data('',free_pre_requisite_data,function(free_pre_requisites)
{
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_service_name+"</item_name>" +
"<staff></staff>" +
"<notes>free service</notes>" +
"<unit_price>0</unit_price>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with>"+subscription.service+"</free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
free_pre_requisites.forEach(function(free_pre_requisite)
{
var task_id=vUtil.newKey();
var task_xml="<task_instances>" +
"<id>"+task_id+"</id>" +
"<name>"+free_pre_requisite.name+"</name>" +
"<assignee></assignee>" +
"<t_initiated>"+get_my_time()+"</t_initiated>" +
"<t_due>"+get_task_due_period()+"</t_due>" +
"<status>pending</status>" +
"<task_hours>"+free_pre_requisite.quantity+"</task_hours>" +
"<source>service</source>" +
"<source_id>"+id+"</source_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</task_instances>";
var activity_xml="<activity>" +
"<data_id>"+task_id+"</data_id>" +
"<tablename>task_instances</tablename>" +
"<link_to>form14</link_to>" +
"<title>Added</title>" +
"<notes>Task "+free_pre_requisite.name+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(task_xml,activity_xml);
}
else
{
local_create_row(task_xml,activity_xml);
}
});
});
}
break;
}
else if(offers[i].criteria_type=='min amount crossed' && offers[i].criteria_amount<=item_amount)
{
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
item_discount=parseFloat((item_amount*parseInt(offers[i].discount_percent))/100);
}
else
{
item_discount=parseFloat(offers[i].discount_amount)*(Math.floor(parseFloat(item_amount)/parseFloat(offers[i].criteria_amount)));
}
}
else if(offers[i].result_type=='service free')
{
var free_service_name=offers[i].free_service_name;
var id=vUtil.newKey();
var free_pre_requisite_data="<pre_requisites>" +
"<type exact='yes'>service</type>" +
"<requisite_type exact='yes'>task</requisite_type>" +
"<name exact='yes'>"+free_service_name+"</name>" +
"<requisite_name></requisite_name>" +
"<quantity></quantity>" +
"</pre_requisites>";
fetch_requested_data('',free_pre_requisite_data,function(free_pre_requisites)
{
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_service_name+"</item_name>" +
"<staff></staff>" +
"<notes>free service</notes>" +
"<unit_price>0</unit_price>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with>"+subscription.service+"</free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
free_pre_requisites.forEach(function(free_pre_requisite)
{
var task_id=vUtil.newKey();
var task_xml="<task_instances>" +
"<id>"+task_id+"</id>" +
"<name>"+free_pre_requisite.name+"</name>" +
"<assignee></assignee>" +
"<t_initiated>"+get_my_time()+"</t_initiated>" +
"<t_due>"+get_task_due_period()+"</t_due>" +
"<status>pending</status>" +
"<task_hours>"+free_pre_requisite.quantity+"</task_hours>" +
"<source>service</source>" +
"<source_id>"+id+"</source_id>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</task_instances>";
var activity_xml="<activity>" +
"<data_id>"+task_id+"</data_id>" +
"<tablename>task_instances</tablename>" +
"<link_to>form14</link_to>" +
"<title>Added</title>" +
"<notes>Task "+free_pre_requisite.name+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(task_xml,activity_xml);
}
else
{
local_create_row(task_xml,activity_xml);
}
});
});
}
break;
}
}
item_tax=parseFloat((parseFloat(services[0].tax)*(item_amount-parseFloat(item_discount)))/100);
item_total=parseFloat(item_amount)+parseFloat(item_tax)-parseFloat(item_discount);
var bill_num_data="<user_preferences count='1'>"+
"<value></value>"+
"<name exact='yes'>bill_num</name>"+
"</user_preferences>";
get_single_column_data(function(bill_nums)
{
var bill_num=bill_nums[0];
/////saving to bill item
var bill_item_id=vUtil.newKey();
var data_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+subscription.service+"</item_name>" +
"<batch></batch>" +
"<unit_price>"+services[0].price+"</unit_price>" +
"<quantity>1</quantity>" +
"<amount>"+item_amount+"</amount>" +
"<total>"+item_total+"</total>" +
"<discount>"+item_discount+"</discount>" +
"<offer>"+item_offer+"</offer>" +
"<type>bought</type>" +
"<tax>"+item_tax+"</tax>" +
"<bill_id>"+order_id+"</bill_id>" +
"<free_with></free_with>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bill_items>";
var bill_xml="<bills>" +
"<id>"+order_id+"</id>" +
"<bill_num>"+bill_num+"</bill_num>"+
"<customer_name>"+subscription.customer+"</customer_name>" +
"<bill_date>"+get_my_time()+"</bill_date>" +
"<amount>"+item_amount+"</amount>" +
"<total>"+item_total+"</total>" +
"<type>service</type>" +
"<offer></offer>" +
"<discount>"+item_discount+"</discount>" +
"<tax>"+item_tax+"</tax>" +
"<transaction_id>"+order_id+"</transaction_id>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+order_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form42</link_to>" +
"<title>Saved</title>" +
"<notes>Bill no "+order_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+order_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+item_total+"</amount>" +
"<receiver>"+subscription.customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+item_tax+"</tax>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>pending</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+item_total+"</total_amount>" +
"<paid_amount>0</paid_amount>" +
"<acc_name>"+subscription.customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+order_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+bill_num+"</source_info>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+item_total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+subscription.customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</transactions>";
if(is_online())
{
server_create_simple(data_xml);
server_create_row(bill_xml,activity_xml);
server_create_simple(transaction_xml);
server_create_simple(pt_xml);
server_create_simple(payment_xml);
}
else
{
local_create_simple(data_xml);
local_create_row(bill_xml,activity_xml);
local_create_simple(transaction_xml);
local_create_simple(pt_xml);
local_create_simple(payment_xml);
}
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>bill_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(bill_num)+1)+"</value>"+
"<last_updated>"+get_my_time()+"</last_updated>"+
"</user_preferences>";
if(is_online())
{
server_update_simple(num_xml);
}
else
{
local_update_simple(num_xml);
}
}
},num_data);
},bill_num_data);
////adding pre-requisite tasks
var pre_requisite_data="<pre_requisites>" +
"<type exact='yes'>service</type>" +
"<requisite_type exact='yes'>task</requisite_type>" +
"<name exact='yes'>"+subscription.service+"</name>" +
"<requisite_name></requisite_name>" +
"<quantity></quantity>" +
"</pre_requisites>";
fetch_requested_data('',pre_requisite_data,function(pre_requisites)
{
pre_requisites.forEach(function(pre_requisite)
{
var task_id=vUtil.newKey();
var task_xml="<task_instances>" +
"<id>"+task_id+"</id>" +
"<name>"+pre_requisite.name+"</name>" +
"<assignee></assignee>" +
"<t_initiated>"+get_my_time()+"</t_initiated>" +
"<t_due>"+get_task_due_period()+"</t_due>" +
"<status>pending</status>" +
"<task_hours>"+pre_requisite.quantity+"</task_hours>" +
"<source>service</source>" +
"<source_id>"+bill_item_id+"</source_id>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</task_instances>";
var activity_xml="<activity>" +
"<data_id>"+task_id+"</data_id>" +
"<tablename>task_instances</tablename>" +
"<link_to>form14</link_to>" +
"<title>Added</title>" +
"<notes>Task "+pre_requisite.name+" assigned to </notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(task_xml,activity_xml);
}
else
{
local_create_row(task_xml,activity_xml);
}
});
});
////////////updating subscription//////////////
var subscription_period_data="<attributes>" +
"<type exact='yes'>service</type>" +
"<attribute>subscription period</attribute>" +
"<name exact='yes'>"+subscription.service+"</name>" +
"<value></value>" +
"</attributes>";
fetch_requested_data('',subscription_period_data,function(periods)
{
if(periods.length>0)
{
var date=new Date(parseFloat(subscription.next_due_date));
var day=date.getDate();
var month=date.getMonth();
var year=date.getFullYear();
var next_due_date="";
var period_value=parseInt(periods[0].value.substring(0,2));
console.log(periods[0].value);
console.log(periods[0].value.search('month'));
if(periods[0].value.search('month')!=-1)
{
month+=period_value;
year+=parseInt(month/12);
month=parseInt(month%12);
}
else if(periods[0].value.search('day')!=-1)
{
day+=period_value;
month+=parseInt(day/30);
day=parseInt(day%30);
year+=parseInt(month/12);
month=parseInt(month%12);
}
else if(periods[0].value.search('year')!=-1)
{
year+=period_value;
}
var new_date=new Date(year,month,day,0,0,0,0);
next_due_date=new_date.getTime();
var subscription_xml="<service_subscriptions>" +
"<id>"+subscription.id+"</id>" +
"<last_bill_id>"+order_id+"</last_bill_id>" +
"<last_bill_date>"+get_my_time()+"</last_bill_date>" +
"<next_due_date>"+next_due_date+"</next_due_date>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</service_subscriptions>";
if(is_online())
{
server_update_simple(subscription_xml);
}
else
{
local_update_simple(subscription_xml);
}
}
});
});
});
});
});
}
/**
* @form Manufacturing Schedule
* @formNo 88
*/
function form88_create_item(form)
{
if(is_create_access('form88'))
{
var product=form.elements[0].value;
var process=form.elements[1].value;
var status=form.elements[2].value;
var schedule=get_raw_time(form.elements[3].value);
var iteration=form.elements[4].value;
var data_id=form.elements[5].value;
form.elements[8].value=status;
var last_updated=get_my_time();
var data_xml="<manufacturing_schedule>" +
"<id>"+data_id+"</id>" +
"<product>"+product+"</product>" +
"<process_notes>"+process+"</process_notes>" +
"<status>"+status+"</status>" +
"<schedule>"+schedule+"</schedule>" +
"<iteration_notes>"+iteration+"</iteration_notes>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</manufacturing_schedule>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>manufacturing_schedule</tablename>" +
"<link_to>form88</link_to>" +
"<title>Added</title>" +
"<notes>Manufacturing schedule for product "+product+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
if(status=='scheduled')
{
var pre_requisite_data="<pre_requisites>" +
"<type exact='yes'>product</type>" +
"<requisite_type exact='yes'>task</requisite_type>" +
"<name exact='yes'>"+product+"</name>" +
"<requisite_name></requisite_name>" +
"<quantity></quantity>" +
"</pre_requisites>";
fetch_requested_data('',pre_requisite_data,function(pre_requisites)
{
pre_requisites.forEach(function(pre_requisite)
{
var task_id=vUtil.newKey();
var task_xml="<task_instances>" +
"<id>"+task_id+"</id>" +
"<name>"+pre_requisite.name+"</name>" +
"<assignee></assignee>" +
"<t_initiated>"+get_my_time()+"</t_initiated>" +
"<t_due>"+get_task_due_time(schedule)+"</t_due>" +
"<status>pending</status>" +
"<task_hours>"+pre_requisite.quantity+"</task_hours>" +
"<source>product</source>" +
"<source_id>"+data_id+"</source_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</task_instances>";
var activity_xml="<activity>" +
"<data_id>"+task_id+"</data_id>" +
"<tablename>task_instances</tablename>" +
"<link_to>form14</link_to>" +
"<title>Added</title>" +
"<notes>Task "+pre_requisite.name+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(task_xml,activity_xml);
}
else
{
local_create_row(task_xml,activity_xml);
}
});
});
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[7];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form88_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form88_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Bill(multiple registers)
* @formNo 91
* @param button
*/
function form91_create_item(form)
{
if(is_create_access('form91'))
{
var bill_id=document.getElementById("form91_master").elements['bill_id'].value;
var bill_type=document.getElementById("form91_master").elements['bill_type'].value;
var name=form.elements[0].value;
var desc=form.elements[1].value;
var batch=form.elements[2].value;
var quantity=form.elements[3].value;
var mrp=form.elements[4].value;
var price=form.elements[5].value;
var freight=form.elements[6].value;
var amount=form.elements[7].value;
var tax=form.elements[8].value;
var total=form.elements[9].value;
var storage=form.elements['storage'].value;
var tax_rate=form.elements['tax_unit'].value;
var data_id=form.elements[12].value;
var save_button=form.elements[13];
var del_button=form.elements[14];
var is_unbilled=form.elements[17].value;
var last_updated=get_my_time();
var tax_type_string="<cst>0</cst>"+
"<vat>"+tax+"</vat>";
if(bill_type=='Retail-CST' || bill_type=='Retail-CST-C')
{
tax_type_string="<cst>"+tax+"</cst>"+
"<vat>0</vat>";
}
var picked_status='pending';
var packed_status='pending';
if(is_unbilled=='yes')
{
picked_status='picked';
packed_status='packed';
}
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<item_desc>"+desc+"</item_desc>" +
"<batch>"+batch+"</batch>" +
"<unit_price>"+price+"</unit_price>" +
"<mrp>"+mrp+"</mrp>" +
"<quantity>"+quantity+"</quantity>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<freight>"+freight+"</freight>" +
"<tax>"+tax+"</tax>";
data_xml+=tax_type_string;
data_xml+="<storage>"+storage+"</storage>" +
"<tax_rate>"+tax_rate+"</tax_rate>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<picked_status>"+picked_status+"</picked_status>"+
"<packing_status>"+packed_status+"</packing_status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
create_simple(data_xml);
////////////////update status of unbilled item///////////
if(is_unbilled=='yes')
{
var unbilled_xml="<unbilled_sale_items>"+
"<id>"+data_id+"</id>"+
"<bill_status>completed</bill_status>"+
"</unbilled_sale_items>";
update_simple(unbilled_xml);
}
for(var i=0;i<12;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form91_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create bill(nikki)
* @formNo 91
* @param button
*/
function form91_create_form()
{
if(is_create_access('form91'))
{
var form=document.getElementById("form91_master");
var customer=form.elements['customer'].value;
var bill_type=form.elements['bill_type'].value;
var bill_date=get_raw_time(form.elements['date'].value);
var bill_num=form.elements['bill_num'].value;
var amount=0;
var tax_name="VAT";
var tax_array=[];
var freight=0;
var total=0;
var total_quantity=0;
var tax=0;
$("[id^='save_form91']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(!isNaN(parseFloat(subform.elements[3].value)))
{
total_quantity+=parseFloat(subform.elements[3].value);
}
if(!isNaN(parseFloat(subform.elements[7].value)))
{
amount+=parseFloat(subform.elements[7].value);
}
if(!isNaN(parseFloat(subform.elements[8].value)))
{
if(typeof tax_array[subform.elements[11].value]=='undefined')
{
tax_array[subform.elements[11].value]=0;
}
tax_array[subform.elements[11].value]+=parseFloat(subform.elements[8].value);
}
if(!isNaN(parseFloat(subform.elements[9].value)))
{
total+=parseFloat(subform.elements[9].value);
}
});
var form=document.getElementById("form91_master");
var tax_type_string="<cst>0</cst>"+
"<vat>"+tax+"</vat>";
if(form.elements['bill_type'].value=='Retail-CST' || form.elements['bill_type'].value=='Retail-CST-C')
{
tax_name="CST";
tax_type_string="<cst>"+tax+"</cst>"+
"<vat>0</vat>";
}
var tax_string="";
var tax_amount_string="";
for(var x in tax_array)
{
tax_array[x]=vUtil.round(tax_array[x],2);
tax_string+=tax_name+" @"+x+"%: <br>";
tax_amount_string+="Rs. "+tax_array[x]+": <br>";
}
amount=vUtil.round(amount,2);
freight=vUtil.round(freight,2);
total=vUtil.round(total,2);
var total_row="<tr><td colspan='3' data-th='Total'>Total Quantity: "+total_quantity+"</td>" +
"<td>Amount:</br>"+tax_string+"Freight: </br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +tax_amount_string+
"Rs. "+freight+"</br>" +
"Rs. <vyavsaay_p id='form91_final_total'>"+total+"</vyavsaay_p></td>" +
"<td></td>" +
"</tr>";
$('#form91_foot').html(total_row);
var data_id=form.elements['bill_id'].value;
var order_id=form.elements['order_id'].value;
var order_num=form.elements['order_num'].value;
var channel=form.elements['channel'].value;
var transaction_id=form.elements['t_id'].value;
var save_button=form.elements['save'];
var last_updated=get_my_time();
var data_xml="<bills>" +
"<id>"+data_id+"</id>" +
"<bill_num>"+bill_num+"</bill_num>"+
"<order_num>"+order_num+"</order_num>"+
"<order_id>"+order_id+"</order_id>"+
"<channel>"+channel+"</channel>"+
"<customer_name>"+customer+"</customer_name>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<billing_type>"+bill_type+"</billing_type>" +
"<freight>"+freight+"</freight>" +
"<tax>"+tax+"</tax>";
data_xml+=tax_type_string;
data_xml+="<transaction_id>"+transaction_id+"</transaction_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form92</link_to>" +
"<title>Saved</title>" +
"<notes>Bill # "+bill_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+transaction_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+tax+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>closed</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>"+total+"</paid_amount>" +
"<acc_name>"+customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+bill_num+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>"+bill_type+"_bill_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(bill_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
update_simple(num_xml);
}
},num_data);
create_row(data_xml,activity_xml);
create_simple(transaction_xml);
create_simple(pt_xml);
create_simple_func(payment_xml,function()
{
//modal26_action(pt_tran_id);
});
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form91_update_form();
});
$("[id^='save_form91_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 101
* form Manage Projects
* @param button
*/
function form101_create_item(form)
{
if(is_create_access('form101'))
{
var name=form.elements[0].value;
var details=form.elements[1].value;
var start_date=get_raw_time(form.elements[2].value);
var status=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_xml="<projects>" +
"<id>"+data_id+"</id>" +
"<name>"+name+"</name>" +
"<details>"+details+"</details>" +
"<start_date>"+start_date+"</start_date>" +
"<status>"+status+"</status>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</projects>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>projects</tablename>" +
"<link_to>form101</link_to>" +
"<title>Added</title>" +
"<notes>Project "+name+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var access_xml="<data_access>" +
"<id>"+vUtil.newKey()+"</id>" +
"<tablename>projects</tablename>" +
"<record_id>"+data_id+"</record_id>" +
"<access_type>all</access_type>" +
"<user_type>user</user_type>" +
"<user>"+get_account_name()+"</user>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</data_access>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
server_create_simple(access_xml);
}
else
{
local_create_row(data_xml,activity_xml);
local_create_simple(access_xml);
}
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form101_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form101_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Project Team
* @formNo 102
* @param button
*/
function form102_create_item(form)
{
if(is_create_access('form102'))
{
var project_id=document.getElementById('form102_master').elements[2].value;
var member=form.elements[0].value;
var role=form.elements[1].value;
var notes=form.elements[2].value;
var status=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_xml="<project_team>" +
"<id>"+data_id+"</id>" +
"<project_id>"+project_id+"</project_id>" +
"<member>"+member+"</member>" +
"<role>"+role+"</role>" +
"<notes>"+notes+"</notes>" +
"<status>"+status+"</status>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</project_team>";
var access_xml="<data_access>" +
"<id>"+vUtil.newKey()+"</id>" +
"<tablename>project_team</tablename>" +
"<record_id>"+data_id+"</record_id>" +
"<access_type>all</access_type>" +
"<user_type>user</user_type>"+
"<user>"+get_account_name()+"</user>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</data_access>";
if(is_online())
{
server_create_simple(data_xml);
server_create_simple(access_xml);
}
else
{
local_create_simple(data_xml);
local_create_simple(access_xml);
}
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form102_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form102_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Project Team
* @param button
*/
function form102_create_form()
{
$("[id^='save_form102_']").click();
}
/**
* @form Project Phases
* @formNo 103
* @param button
*/
function form103_create_item(form)
{
if(is_create_access('form103'))
{
var project_id=document.getElementById('form103_master').elements[2].value;
var phase=form.elements[0].value;
var details=form.elements[1].value;
var start_date=get_raw_time(form.elements[2].value);
var due_date=get_raw_time(form.elements[3].value);
var status=form.elements[4].value;
var data_id=form.elements[5].value;
var last_updated=get_my_time();
var data_xml="<project_phases>" +
"<id>"+data_id+"</id>" +
"<project_id>"+project_id+"</project_id>" +
"<phase_name>"+phase+"</phase_name>" +
"<details>"+details+"</details>" +
"<start_date>"+start_date+"</start_date>" +
"<due_date>"+due_date+"</due_date>" +
"<status>"+status+"</status>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</project_phases>";
var access_xml="<data_access>" +
"<id>"+vUtil.newKey()+"</id>" +
"<tablename>project_phases</tablename>" +
"<record_id>"+data_id+"</record_id>" +
"<access_type>all</access_type>" +
"<user_type>user</user_type>"+
"<user>"+get_account_name()+"</user>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</data_access>";
create_simple(data_xml);
create_simple(access_xml);
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[7];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form103_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form103_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Project Team
* @param button
*/
function form103_create_form()
{
$("[id^='save_form103_']").click();
}
/**
* This function transforms a sale order into a bill
* It is applicable for product bills only
* @form 108
* @param order_id
*/
function form108_bill(order_id,bill_type,order_num,sale_channel,customer,order_time)
{
///check following data is adequately updated
//a. product batches
//b. channel prices
//c. pickup charges
if(is_create_access('form108'))
{
show_loader();
var bill_amount=0;
var bill_total=0;
var bill_freight=0;
var bill_tax=0;
var bill_channel_charges=0;
var bill_channel_tax=0;
var bill_channel_payable=0;
var pending_items_count=0;
var actual_order_items=[];
var order_items=[];
var bill_key=vUtil.newKey();
$("#modal133_item_table tr").each(function(index)
{
var checked=false;
if($(this).find('td:nth-child(3)>input').length>0)
checked=$(this).find('td:nth-child(3)>input')[0].checked;
var order_item=new Object();
if(checked)
{
//console.log($(this).attr('data-object'));
order_item=vUtil.jsonParse($(this).attr('data-object'));
order_items.push(order_item);
}
actual_order_items.push(order_item);
});
//console.log(order_items);
//console.log(actual_order_items);
if(!(order_items.length!=(actual_order_items.length-1) && get_session_var('allow_partial_billing')=='no'))
{
if(order_items.length>0)
{
pending_items_count=order_items.length;
//console.log(order_items);
var inventory_adjust_array=[];
var bill_items_xml_array=[];
var order_items_xml_array=[];
order_items.forEach(function(order_item)
{
var components_data="<pre_requisites>"+
"<type exact='yes'>product</type>"+
"<requisite_type exact='yes'>product</requisite_type>"+
"<requisite_name></requisite_name>"+
"<requisite_desc></requisite_desc>"+
"<quantity></quantity>"+
"<name exact='yes'>"+order_item.item_name+"</name>"+
"</pre_requisites>";
fetch_requested_data('',components_data,function(components)
{
if(components.length>0)
{
//////////////////////////////////////////////////
var item_amount=order_item.amount;
var item_total=order_item.total;
var item_freight=order_item.freight;
var item_tax=order_item.tax;
var item_mrp=order_item.mrp;
var item_channel_charges=0;
var item_tax_rate=order_item.tax_rate;
var price_data="<channel_prices count='1'>" +
"<from_time upperbound='yes'>"+order_time+"</from_time>"+
"<channel exact='yes'>"+sale_channel+"</channel>"+
"<item exact='yes'>"+order_item.item_name+"</item>"+
"<sale_price></sale_price>"+
"<freight></freight>"+
"<mrp></mrp>"+
"<discount_customer></discount_customer>"+
"<gateway_charges></gateway_charges>"+
"<storage_charges></storage_charges>"+
"<channel_commission></channel_commission>"+
"<total_charges></total_charges>"+
"<service_tax></service_tax>"+
"<total_payable></total_payable>"+
"<total_receivable></total_receivable>"+
"</channel_prices>";
fetch_requested_data('',price_data,function(sale_prices)
{
//console.log(sale_prices);
if(sale_prices.length>0)
{
//////adding offer details
var pickup_data="<pickup_charges>"+
"<rate></rate>"+
"<min_charges></min_charges>"+
"<max_charges></max_charges>"+
"<pincode exact='yes'>all</pincode>"+
"<channel exact='yes'>"+sale_channel+"</channel>"+
"</pickup_charges>";
fetch_requested_data('',pickup_data,function(pickups)
{
//console.log(pickups);
var pickup_charges=0;
var item_dead_weight=100;
if(pickups.length>0)
{
pickup_charges=parseFloat(pickups[0].rate)*parseFloat(item_dead_weight);
if(pickup_charges>parseFloat(pickups[0].max_charges))
{
pickup_charges=parseFloat(pickups[0].max_charges);
}
else if(pickup_charges<parseFloat(pickups[0].min_charges))
{
pickup_charges=parseFloat(pickups[0].min_charges);
}
}
//item_freight=parseFloat(order_item.quantity)*parseFloat(sale_prices[0].freight);
//item_total=(parseFloat(order_item.quantity)*parseFloat(sale_prices[0].sale_price))+item_freight;
item_channel_charges=(parseFloat(order_item.quantity)*(parseFloat(sale_prices[0].channel_commission)+pickup_charges));
item_channel_tax=item_channel_charges*.14;
item_channel_payable=item_channel_charges*1.14;
//item_tax_rate=0;
var tax_data="<product_master count='1'>" +
"<name exact='yes'>"+order_item.item_name+"</name>" +
"<description></description>"+
"<tax></tax>" +
"</product_master>";
fetch_requested_data('',tax_data,function(taxes)
{
//console.log(taxes);
order_item.item_desc=taxes[0].description;
/*
if(bill_type=='Retail-CST-C')
{
taxes[0].tax=get_session_var('cst_rate');
}
*/
//item_tax_rate=taxes[0].tax;
//item_amount=vUtil.round((item_total-item_freight)/(1+(parseFloat(taxes[0].tax)/100)),2);
//item_tax=vUtil.round((item_total-item_amount-item_freight),2);
var unit_price=item_amount/parseFloat(order_item.quantity);
var item_storage="";
var bill_item_id=vUtil.newKey();
var adjust2_data_xml="<inventory_adjust>"+
"<id>"+bill_item_id+"</id>" +
"<product_name>"+order_item.item_name+"</product_name>" +
"<item_desc>"+order_item.item_desc+"</item_desc>" +
"<batch>NA</batch>" +
"<picked_status>picked</picked_status>" +
"<quantity>"+order_item.quantity+"</quantity>" +
"<picked_quantity>"+order_item.quantity+"</picked_quantity>" +
"<storage>NA</storage>"+
"<source>picked</source>"+
"<source_id>"+bill_key+"</source_id>"+
"<show_for_packing>dummy</show_for_packing>"+
"<last_updated>"+get_my_time()+"</last_updated>"+
"</inventory_adjust>";
inventory_adjust_array.push(adjust2_data_xml);
var data_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+order_item.item_name+"</item_name>" +
"<item_desc>"+order_item.item_desc+"</item_desc>" +
"<batch>NA</batch>" +
"<unit_price>"+unit_price+"</unit_price>" +
"<mrp>"+item_mrp+"</mrp>" +
"<quantity>"+order_item.quantity+"</quantity>" +
"<amount>"+item_amount+"</amount>" +
"<total>"+item_total+"</total>" +
"<channel_charges>"+item_channel_charges+"</channel_charges>" +
"<freight>"+item_freight+"</freight>" +
"<tax>"+item_tax+"</tax>" +
"<tax_rate>"+item_tax_rate+"</tax_rate>" +
"<bill_id>"+bill_key+"</bill_id>" +
"<storage>NA</storage>"+
"<picked_status>picked</picked_status>"+
"<picked_quantity>"+order_item.quantity+"</picked_quantity>"+
"<packed_quantity>"+order_item.quantity+"</packed_quantity>"+
"<packing_status>packed</packing_status>"+
"<show_for_packing>dummy</show_for_packing>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bill_items>";
bill_items_xml_array.push(data_xml);
bill_amount+=item_amount;
bill_freight+=item_freight;
bill_total+=item_total;
bill_tax+=item_tax;
bill_channel_charges+=item_channel_charges;
bill_channel_tax+=item_channel_tax;
bill_channel_payable+=item_channel_payable;
pending_items_count-=1;
var order_item_xml="<sale_order_items>" +
"<id>"+order_item.id+"</id>" +
"<item_name>"+order_item.item_name+"</item_name>" +
"<item_desc>"+order_item.item_desc+"</item_desc>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</sale_order_items>";
order_items_xml_array.push(order_item_xml);
});
});
}
else
{
pending_items_count-=1;
}
});
pending_items_count+=components.length;
components.forEach(function(component)
{
component.quantity=parseFloat(component.quantity)*parseFloat(order_item.quantity);
var batch_data="<product_instances>" +
"<batch></batch>" +
"<expiry></expiry>" +
"<product_name exact='yes'>"+component.requisite_name+"</product_name>" +
//"<status exact='yes'>available</status>"+
"</product_instances>";
fetch_requested_data('',batch_data,function(batches_array)
{
console.log(batches_array);
//batches.reverse();
batches_array.sort(function(a,b)
{
if(parseFloat(a.expiry)>parseFloat(b.expiry) || isNaN(a.expiry) || a.expiry=="" || a.expiry==0)
{ return 1;}
else
{ return -1;}
});
var batches=[];
batches_array.forEach(function (batches_array_elem)
{
console.log(batches_array_elem);
batches.push(batches_array_elem.batch);
});
console.log(batches);
var single_batch=batches[0];
var batches_result_array=[];
get_available_batch(component.requisite_name,batches,component.quantity,batches_result_array,function()
{
console.log(batches_result_array);
if(batches_result_array.length===0)
{
var single_batch_object=new Object();
single_batch_object.batch=single_batch;
single_batch_object.quantity=order_item.quantity;
batches_result_array.push(single_batch_object);
}
pending_items_count+=batches_result_array.length-1;
batches_result_array.forEach(function(batch_result)
{
var storage_xml="<area_utilization>"+
"<name></name>"+
"<item_name exact='yes'>"+component.requisite_name+"</item_name>"+
"<batch exact='yes'>"+batch_result.batch+"</batch>"+
"</area_utilization>";
get_single_column_data(function (storages)
{
var storage_result_array=[];
get_available_storage(component.requisite_name,batch_result.batch,storages,batch_result.quantity,storage_result_array,function ()
{
console.log(storage_result_array);
var item_storage="";
var bill_item_id=vUtil.newKey();
var adjust_count=1;
if(storage_result_array.length>0)
{
item_storage=storage_result_array[0].storage;
}
else
{
adjust_count+=1;
var adjust_data_xml="<inventory_adjust>"+
"<id>"+(bill_item_id+adjust_count)+"</id>" +
"<product_name>"+component.requisite_name+"</product_name>" +
"<item_desc>"+component.requisite_desc+"</item_desc>" +
"<batch>"+batch_result.batch+"</batch>" +
"<picked_status>pending</picked_status>" +
"<packing_status>pending</packing_status>" +
"<quantity>-"+batch_result.quantity+"</quantity>" +
"<picked_quantity>0</picked_quantity>" +
"<packed_quantity>0</packed_quantity>" +
"<storage></storage>"+
"<source>picking</source>"+
"<source_id>"+bill_key+"</source_id>"+
"<show_for_packing>yes</show_for_packing>"+
"<last_updated>"+get_my_time()+"</last_updated>"+
"</inventory_adjust>";
inventory_adjust_array.push(adjust_data_xml);
}
storage_result_array.forEach(function(storage_result)
{
adjust_count+=1;
var adjust_data_xml="<inventory_adjust>"+
"<id>"+(bill_item_id+adjust_count)+"</id>" +
"<product_name>"+component.requisite_name+"</product_name>" +
"<item_desc>"+component.requisite_desc+"</item_desc>" +
"<batch>"+batch_result.batch+"</batch>" +
"<picked_status>pending</picked_status>" +
"<packing_status>pending</packing_status>" +
"<quantity>-"+storage_result.quantity+"</quantity>" +
"<picked_quantity>0</picked_quantity>" +
"<packed_quantity>0</packed_quantity>" +
"<storage>"+storage_result.storage+"</storage>"+
"<source>picking</source>"+
"<source_id>"+bill_key+"</source_id>"+
"<show_for_packing>yes</show_for_packing>"+
"<last_updated>"+get_my_time()+"</last_updated>"+
"</inventory_adjust>";
inventory_adjust_array.push(adjust_data_xml);
});
pending_items_count-=1;
});
},storage_xml);
});
});
});
});
//////////////////////////////////////////////////
}
else
{
var item_amount=order_item.amount;
var item_total=order_item.total;
var item_freight=order_item.freight;
var item_tax=order_item.tax;
var item_mrp=order_item.mrp;
var item_channel_charges=0;
var item_tax_rate=order_item.tax_rate;
var batch_data="<product_instances>" +
"<batch></batch>" +
"<expiry></expiry>" +
"<product_name exact='yes'>"+order_item.item_name+"</product_name>" +
//"<status exact='yes'>available</status>"+
"</product_instances>";
fetch_requested_data('',batch_data,function(batches_array)
{
//console.log(batches_array);
//batches.reverse();
batches_array.sort(function(a,b)
{
if(parseFloat(a.expiry)>parseFloat(b.expiry) || isNaN(a.expiry) || a.expiry=="" || a.expiry==0)
{ return 1;}
else
{ return -1;}
});
var batches=[];
batches_array.forEach(function (batches_array_elem)
{
//console.log(batches_array_elem);
batches.push(batches_array_elem.batch);
});
//console.log(batches);
var single_batch=batches[0];
var batches_result_array=[];
get_available_batch(order_item.item_name,batches,order_item.quantity,batches_result_array,function()
{
var price_data="<channel_prices count='1'>" +
"<from_time upperbound='yes'>"+order_time+"</from_time>"+
"<channel exact='yes'>"+sale_channel+"</channel>"+
"<item exact='yes'>"+order_item.item_name+"</item>"+
"<sale_price></sale_price>"+
"<freight></freight>"+
"<mrp></mrp>"+
"<discount_customer></discount_customer>"+
"<gateway_charges></gateway_charges>"+
"<storage_charges></storage_charges>"+
"<channel_commission></channel_commission>"+
"<total_charges></total_charges>"+
"<service_tax></service_tax>"+
"<total_payable></total_payable>"+
"<total_receivable></total_receivable>"+
"</channel_prices>";
fetch_requested_data('',price_data,function(sale_prices)
{
//console.log(sale_prices);
if(sale_prices.length>0)
{
//////adding offer details
var pickup_data="<pickup_charges>"+
"<rate></rate>"+
"<min_charges></min_charges>"+
"<max_charges></max_charges>"+
"<pincode exact='yes'>all</pincode>"+
"<channel exact='yes'>"+sale_channel+"</channel>"+
"</pickup_charges>";
fetch_requested_data('',pickup_data,function(pickups)
{
//console.log(pickups);
var pickup_charges=0;
var item_dead_weight=100;
if(pickups.length>0)
{
pickup_charges=parseFloat(pickups[0].rate)*parseFloat(item_dead_weight);
if(pickup_charges>parseFloat(pickups[0].max_charges))
{
pickup_charges=parseFloat(pickups[0].max_charges);
}
else if(pickup_charges<parseFloat(pickups[0].min_charges))
{
pickup_charges=parseFloat(pickups[0].min_charges);
}
}
//item_freight=parseFloat(order_item.quantity)*parseFloat(sale_prices[0].freight);
//item_total=(parseFloat(order_item.quantity)*parseFloat(sale_prices[0].sale_price))+item_freight;
item_channel_charges=(parseFloat(order_item.quantity)*(parseFloat(sale_prices[0].channel_commission)+pickup_charges));
item_channel_tax=item_channel_charges*.14;
item_channel_payable=item_channel_charges*1.14;
//item_tax_rate=0;
var tax_data="<product_master count='1'>" +
"<name exact='yes'>"+order_item.item_name+"</name>" +
"<description></description>"+
"<tax></tax>" +
"</product_master>";
fetch_requested_data('',tax_data,function(taxes)
{
//console.log(taxes);
order_item.item_desc=taxes[0].description;
/*
if(bill_type=='Retail-CST-C')
{
taxes[0].tax=get_session_var('cst_rate');
}
item_tax_rate=taxes[0].tax;
item_amount=vUtil.round((item_total-item_freight)/(1+(parseFloat(taxes[0].tax)/100)),2);
item_tax=vUtil.round((item_total-item_amount-item_freight),2);
*/
var unit_price=item_amount/parseFloat(order_item.quantity);
//console.log(batches_result_array);
if(batches_result_array.length===0)
{
var single_batch_object=new Object();
single_batch_object.batch=single_batch;
single_batch_object.quantity=order_item.quantity;
batches_result_array.push(single_batch_object);
}
pending_items_count+=batches_result_array.length-1;
batches_result_array.forEach(function(batch_result)
{
var storage_xml="<area_utilization>"+
"<name></name>"+
"<item_name exact='yes'>"+order_item.item_name+"</item_name>"+
"<batch exact='yes'>"+batch_result.batch+"</batch>"+
"</area_utilization>";
get_single_column_data(function (storages)
{
var storage_result_array=[];
get_available_storage(order_item.item_name,batch_result.batch,storages,batch_result.quantity,storage_result_array,function ()
{
console.log(storage_result_array);
var item_storage="";
if(storage_result_array.length>0)
{
item_storage=storage_result_array[0].storage;
}
var bill_item_picked_status='pending';
var bill_item_picked_quantity=0;
var bill_item_amount=vUtil.round((item_amount*batch_result.quantity/order_item.quantity),2);
var bill_item_total=vUtil.round((item_total*batch_result.quantity/order_item.quantity),2);
var bill_item_channel_charges=vUtil.round((item_channel_charges*batch_result.quantity/order_item.quantity),2);
var bill_item_freight=vUtil.round((item_freight*batch_result.quantity/order_item.quantity),2);
var bill_item_tax=vUtil.round((item_tax*batch_result.quantity/order_item.quantity),2);
var bill_item_channel_tax=vUtil.round((item_channel_tax*batch_result.quantity/order_item.quantity),2);
var bill_item_channel_payable=vUtil.round((item_channel_payable*batch_result.quantity/order_item.quantity),2);
var bill_item_id=vUtil.newKey();
if(storage_result_array.length>1)
{
bill_item_picked_status='picked';
bill_item_picked_quantity=batch_result.quantity;
var adjust_count=1;
storage_result_array.forEach(function(storage_result)
{
adjust_count+=1;
var adjust_data_xml="<inventory_adjust>"+
"<id>"+(bill_item_id+adjust_count)+"</id>" +
"<product_name>"+order_item.item_name+"</product_name>" +
"<item_desc>"+order_item.item_desc+"</item_desc>" +
"<batch>"+batch_result.batch+"</batch>" +
"<picked_status>pending</picked_status>" +
"<quantity>-"+storage_result.quantity+"</quantity>" +
"<picked_quantity>0</picked_quantity>" +
"<storage>"+storage_result.storage+"</storage>"+
"<source>picking</source>"+
"<source_id>"+bill_key+"</source_id>"+
"<last_updated>"+get_my_time()+"</last_updated>"+
"</inventory_adjust>";
inventory_adjust_array.push(adjust_data_xml);
});
var adjust2_data_xml="<inventory_adjust>"+
"<id>"+bill_item_id+"</id>" +
"<product_name>"+order_item.item_name+"</product_name>" +
"<item_desc>"+order_item.item_desc+"</item_desc>" +
"<batch>"+batch_result.batch+"</batch>" +
"<picked_status>picked</picked_status>" +
"<quantity>"+batch_result.quantity+"</quantity>" +
"<picked_quantity>"+batch_result.quantity+"</picked_quantity>" +
"<storage>"+item_storage+"</storage>"+
"<source>picked</source>"+
"<source_id>"+bill_key+"</source_id>"+
"<last_updated>"+get_my_time()+"</last_updated>"+
"</inventory_adjust>";
inventory_adjust_array.push(adjust2_data_xml);
}
var data_xml="<bill_items>" +
"<id>"+bill_item_id+"</id>" +
"<item_name>"+order_item.item_name+"</item_name>" +
"<item_desc>"+order_item.item_desc+"</item_desc>" +
"<batch>"+batch_result.batch+"</batch>" +
"<unit_price>"+unit_price+"</unit_price>" +
"<mrp>"+item_mrp+"</mrp>" +
"<quantity>"+batch_result.quantity+"</quantity>" +
"<amount>"+bill_item_amount+"</amount>" +
"<total>"+bill_item_total+"</total>" +
"<channel_charges>"+bill_item_channel_charges+"</channel_charges>" +
"<freight>"+bill_item_freight+"</freight>" +
"<tax>"+bill_item_tax+"</tax>" +
"<tax_rate>"+item_tax_rate+"</tax_rate>" +
"<bill_id>"+bill_key+"</bill_id>" +
"<storage>"+item_storage+"</storage>"+
"<picked_status>"+bill_item_picked_status+"</picked_status>"+
"<picked_quantity>"+bill_item_picked_quantity+"</picked_quantity>"+
"<packing_status>pending</packing_status>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bill_items>";
bill_items_xml_array.push(data_xml);
bill_amount+=bill_item_amount;
bill_freight+=bill_item_freight;
bill_total+=bill_item_total;
bill_tax+=bill_item_tax;
bill_channel_charges+=bill_item_channel_charges;
bill_channel_tax+=bill_item_channel_tax;
bill_channel_payable+=bill_item_channel_payable;
pending_items_count-=1;
});
},storage_xml);
});
var order_item_xml="<sale_order_items>" +
"<id>"+order_item.id+"</id>" +
"<item_name>"+order_item.item_name+"</item_name>" +
"<item_desc>"+order_item.item_desc+"</item_desc>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</sale_order_items>";
order_items_xml_array.push(order_item_xml);
});
});
}
else
{
pending_items_count-=1;
}
});
});
});
}
});
});
/////saving bill details
var bill_items_complete=setInterval(function()
{
if(pending_items_count===0)
{
clearInterval(bill_items_complete);
var num_data="<user_preferences>"+
"<id></id>"+
"<value></value>"+
"<name exact='yes'>"+bill_type+"_bill_num</name>"+
"</user_preferences>";
fetch_requested_data('',num_data,function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
//////////////////////////////////////////////
var sale_order_xml="<sale_orders>"+
"<id>"+order_id+"</id>" +
"<bill_id></bill_id>" +
"<total_quantity></total_quantity>"+
"</sale_orders>";
fetch_requested_data('',sale_order_xml,function (sorders)
{
if(sorders.length>0)
{
var id_object_array=vUtil.jsonParse(sorders[0].bill_id);
var id_object=new Object();
id_object.bill_num=bill_num_ids[0].value;
id_object.bill_id=bill_key;
id_object.quantity=0;
for(var j in order_items)
{
id_object.quantity+=parseFloat(order_items[j].quantity);
}
id_object_array.push(id_object);
var master_total_quantity=0;
for(var k in id_object_array)
{
master_total_quantity+=parseFloat(id_object_array[k].quantity);
}
var status='partially billed';
if(master_total_quantity==parseFloat(sorders[0].total_quantity))
{
status='billed';
}
var new_bill_id=JSON.stringify(id_object_array);
//console.log(new_bill_id);
var so_xml="<sale_orders>" +
"<id>"+order_id+"</id>" +
"<bill_id>"+new_bill_id+"</bill_id>" +
"<status>"+status+"</status>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</sale_orders>";
update_simple_func(so_xml,function ()
{
form108_ini();
});
}
});
/////////////////////////////////////////////
var bill_key_string=""+bill_key;
var pick_bag_num=bill_key_string.slice(-3);
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0].id+"</id>"+
"<value>"+(parseInt(bill_num_ids[0].value)+1)+"</value>"+
"<last_updated>"+get_my_time()+"</last_updated>"+
"</user_preferences>";
var bill_xml="<bills>" +
"<id>"+bill_key+"</id>" +
"<bill_num>"+bill_num_ids[0].value+"</bill_num>"+
"<order_num>"+order_num+"</order_num>"+
"<order_id>"+order_id+"</order_id>"+
"<customer_name>"+customer+"</customer_name>" +
"<bill_date>"+get_my_time()+"</bill_date>" +
"<billing_type>"+bill_type+"</billing_type>" +
"<amount>"+bill_amount+"</amount>" +
"<freight>"+bill_freight+"</freight>"+
"<total>"+bill_total+"</total>" +
"<discount>0</discount>" +
"<channel>"+sale_channel+"</channel>"+
"<channel_charges>"+bill_channel_charges+"</channel_charges>"+
"<channel_tax>"+bill_channel_tax+"</channel_tax>"+
"<channel_payable>"+bill_channel_payable+"</channel_payable>"+
"<tax>"+bill_tax+"</tax>" +
"<transaction_id>"+order_id+"</transaction_id>" +
"<pick_bag_num>"+pick_bag_num+"</pick_bag_num>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+bill_key+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form42</link_to>" +
"<title>Saved</title>" +
"<notes>Billed order# "+order_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+bill_key+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+bill_total+"</amount>" +
"<receiver>"+customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+bill_tax+"</tax>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>pending</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+bill_total+"</total_amount>" +
"<paid_amount>0</paid_amount>" +
"<acc_name>"+customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+order_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+bill_num_ids[0].value+"</source_info>"+
"<last_updated>"+get_my_time()+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+bill_total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</transactions>";
create_simple(transaction_xml);
create_simple(pt_xml);
create_simple(payment_xml);
update_simple(num_xml);
create_row(bill_xml,activity_xml);
//console.log(bill_items_xml_array);
//console.log(bill_xml);
bill_items_xml_array.forEach(function (bill_item_xml)
{
create_simple(bill_item_xml);
});
inventory_adjust_array.forEach(function (adjust_item_xml)
{
create_simple(adjust_item_xml);
});
order_items_xml_array.forEach(function (order_item_xml)
{
update_simple(order_item_xml);
});
}
});
hide_loader();
}
},200);
}
else
{
hide_loader();
$("#modal63_link").click();
}
}
else
{
hide_loader();
$("#modal64_link").click();
}
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 109
* form Asset Attributes
* @param button
*/
function form109_create_item(form)
{
if(is_create_access('form109'))
{
var asset=form.elements[0].value;
var attribute=form.elements[1].value;
var value=form.elements[2].value;
var data_id=form.elements[3].value;
var last_updated=get_my_time();
var data_xml="<attributes>" +
"<id>"+data_id+"</id>" +
"<name>"+asset+"</name>" +
"<type>asset</type>" +
"<attribute>"+attribute+"</attribute>" +
"<value>"+value+"</value>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</attributes>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>attributes</tablename>" +
"<link_to>form109</link_to>" +
"<title>Added</title>" +
"<notes>Attribute "+attribute+" for asset "+asset+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<3;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[5];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form109_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form109_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Add unbilled sale items
* @param button
*/
function form112_create_item(form)
{
if(is_create_access('form112'))
{
var customer=document.getElementById('form112_master').elements[1].value;
var sale_date=get_raw_time(document.getElementById('form112_master').elements[2].value);
var item_name=form.elements[1].value;
var item_desc=form.elements[2].value;
var batch=form.elements[3].value;
var quantity=form.elements[4].value;
var unit_price=form.elements[5].value;
var mrp=form.elements[6].value;
var amount=form.elements[7].value;
var tax=form.elements[8].value;
var total=parseFloat(amount)+parseFloat(tax);
var storage=form.elements[9].value;
var data_id=form.elements[10].value;
var save_button=form.elements[11];
var del_button=form.elements[12];
var last_updated=get_my_time();
var data_xml="<unbilled_sale_items>" +
"<id>"+data_id+"</id>" +
"<customer>"+customer+"</customer>" +
"<item_name>"+item_name+"</item_name>" +
"<item_desc>"+item_desc+"</item_desc>"+
"<batch>"+batch+"</batch>" +
"<quantity>"+quantity+"</quantity>" +
"<unit_price>"+unit_price+"</unit_price>"+
"<amount>"+amount+"</amount>"+
"<mrp>"+mrp+"</mrp>"+
"<tax>"+tax+"</tax>"+
"<total>"+total+"</total>"+
"<storage>"+storage+"</storage>"+
"<bill_status>pending</bill_status>"+
"<picked_status>pending</picked_status>"+
"<sale_date>"+sale_date+"</sale_date>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</unbilled_sale_items>";
create_simple(data_xml);
for(var i=0;i<10;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form112_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Add unbilled sale items
* @param button
*/
function form112_create_form()
{
if(is_create_access('form112'))
{
$("[id^='save_form112_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Add unbilled purchase items
* @param button
*/
function form114_create_item(form)
{
if(is_create_access('form114'))
{
var supplier=document.getElementById('form114_master').elements[1].value;
var purchase_date=get_raw_time(document.getElementById('form114_master').elements[2].value);
var item_name=form.elements[1].value;
var item_desc=form.elements[2].value;
var batch=form.elements[3].value;
var quantity=form.elements[4].value;
var unit_price=form.elements[5].value;
var amount=form.elements[6].value;
var tax=form.elements[7].value;
var total=parseFloat(amount)+parseFloat(tax);
var storage=form.elements[8].value;
var data_id=form.elements[9].value;
var save_button=form.elements[10];
var del_button=form.elements[11];
var last_updated=get_my_time();
var data_xml="<unbilled_purchase_items>" +
"<id>"+data_id+"</id>" +
"<supplier>"+supplier+"</supplier>" +
"<item_name>"+item_name+"</item_name>" +
"<item_desc>"+item_desc+"</item_desc>"+
"<batch>"+batch+"</batch>" +
"<quantity>"+quantity+"</quantity>" +
"<purchase_date>"+purchase_date+"</purchase_date>" +
"<unit_price>"+unit_price+"</unit_price>"+
"<amount>"+amount+"</amount>"+
"<tax>"+tax+"</tax>"+
"<total>"+total+"</total>"+
"<storage>"+storage+"</storage>"+
"<bill_status>pending</bill_status>"+
"<put_away_status>pending</put_away_status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</unbilled_purchase_items>";
create_simple(data_xml);
for(var i=0;i<9;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form114_delete_item(del_button);
});
///////////adding store placement////////
var storage_data="<area_utilization>" +
"<id></id>" +
"<name exact='yes'>"+storage+"</name>" +
"<item_name exact='yes'>"+item_name+"</item_name>" +
"<batch exact='yes'>"+batch+"</batch>" +
"</area_utilization>";
fetch_requested_data('',storage_data,function(placements)
{
if(placements.length===0)
{
var storage_xml="<area_utilization>" +
"<id>"+vUtil.newKey()+"</id>" +
"<name>"+storage+"</name>" +
"<item_name>"+item_name+"</item_name>" +
"<batch>"+batch+"</batch>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</area_utilization>";
create_simple(storage_xml);
}
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Add unbilled purchase items
* @param button
*/
function form114_create_form()
{
if(is_create_access('form114'))
{
$("[id^='save_form114_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Bill(loyalty)
* @formNo 118
* @param button
*/
function form118_create_item(form)
{
if(is_create_access('form118'))
{
var bill_id=document.getElementById("form118_master").elements[4].value;
var name=form.elements[0].value;
var batch=form.elements[1].value;
var quantity=form.elements[2].value;
var price=form.elements[3].value;
var total=form.elements[4].value;
var amount=form.elements[5].value;
var discount=form.elements[6].value;
var tax=form.elements[7].value;
var offer=form.elements[8].value;
var data_id=form.elements[9].value;
var free_product_name=form.elements[12].value;
var free_product_quantity=form.elements[13].value;
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+batch+"</batch>" +
"<unit_price>"+price+"</unit_price>" +
"<quantity>"+quantity+"</quantity>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<discount>"+discount+"</discount>" +
"<offer>"+offer+"</offer>" +
"<type>bought</type>" +
"<tax>"+tax+"</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<free_with></free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
//////adding free product to the bill if applicable
if(free_product_name!="" && free_product_name!=null)
{
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var id=vUtil.newKey();
rowsHTML="<tr>";
rowsHTML+="<form id='form118_"+id+"'></form>";
rowsHTML+="<td data-th='Item'>";
rowsHTML+="<input type='text' readonly='readonly' form='form118_"+id+"' value='"+free_product_name+"'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Batch'>";
rowsHTML+="<input type='text' required form='form118_"+id+"' value='"+free_batch+"'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Quantity'>";
rowsHTML+="<input type='number' readonly='readonly' required form='form118_"+id+"' value='"+free_product_quantity+"'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Unit Price'>";
rowsHTML+="<input type='number' readonly='readonly' required form='form118_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Total'>";
rowsHTML+="<input type='number' readonly='readonly' required form='form118_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Action'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value='free with "+name+"'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value='"+id+"'>";
rowsHTML+="<input type='button' class='save_icon' form='form118_"+id+"' id='save_form118_"+id+"' >";
rowsHTML+="<input type='button' class='delete_icon' form='form118_"+id+"' id='delete_form118_"+id+"' onclick='form118_delete_item($(this));'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value=''>";
rowsHTML+="</td>";
rowsHTML+="</tr>";
$('#form118_body').prepend(rowsHTML);
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<free_with>"+name+"</free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
create_simple(free_xml);
},free_batch_data);
}
else
{
$("#modal7_link").click();
}
});
}
for(var i=0;i<10;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[11];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form118_delete_item(del_button);
});
var save_button=form.elements[10];
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create bill(loyalty)
* @formNo 118
* @param button
*/
function form118_create_form()
{
if(is_create_access('form118'))
{
var form=document.getElementById("form118_master");
var customer=form.elements[1].value;
var bill_date=get_raw_time(form.elements[2].value);
var bill_num=form.elements[3].value;
var message_string="Bill from: "+get_session_var('title')+"\nAddress: "+get_session_var('address');
var amount=0;
var discount=0;
var tax=0;
var total=0;
$("[id^='save_form118']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
total+=parseFloat(subform.elements[4].value);
amount+=parseFloat(subform.elements[5].value);
discount+=parseFloat(subform.elements[6].value);
tax+=parseFloat(subform.elements[7].value);
message_string+="\nItem: "+subform.elements[0].value;
message_string+=" Quantity: "+subform.elements[2].value;
message_string+=" Total: "+subform.elements[4].value;
});
var data_id=form.elements[4].value;
var transaction_id=form.elements[6].value;
var last_updated=get_my_time();
var offer_detail="";
var offer_data="<offers>" +
"<criteria_type>min amount crossed</criteria_type>" +
"<criteria_amount upperbound='yes'>"+(amount-discount)+"</criteria_amount>" +
"<offer_type exact='yes'>bill</offer_type>" +
"<result_type></result_type>" +
"<discount_percent></discount_percent>" +
"<discount_amount></discount_amount>" +
"<quantity_add_percent></quantity_add_percent>" +
"<quantity_add_amount></quantity_add_amount>" +
"<free_product_name></free_product_name>" +
"<free_product_quantity></free_product_quantity>" +
"<offer_detail></offer_detail>" +
"<status array='yes'>active--extended</status>" +
"</offers>";
fetch_requested_data('',offer_data,function(offers)
{
offers.sort(function(a,b)
{
if(a.criteria_amount<b.criteria_amount)
{ return 1;}
else
{ return -1;}
});
for(var i in offers)
{
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
var dis=parseFloat(((amount-discount)*parseInt(offers[i].discount_percent))/100);
tax-=(tax*(dis/(amount-discount)));
discount+=dis;
total=amount-discount+tax;
}
else
{
var dis=parseFloat(offers[i].discount_amount)*(Math.floor((amount-discount)/parseFloat(offers[i].criteria_amount)));
tax-=(tax*(dis/(amount-discount)));
discount+=dis;
total=amount-discount+tax;
}
}
else if(offers[i].result_type=='product free')
{
var free_product_name=offers[i].free_product_name;
var free_product_quantity=parseFloat(offers[i].free_product_quantity)*(Math.floor(parseFloat(amount-discount)/parseFloat(offers[i].criteria_amount)));
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var id=vUtil.newKey();
rowsHTML="<tr>";
rowsHTML+="<form id='form118_"+id+"'></form>";
rowsHTML+="<td data-th='Item'>";
rowsHTML+="<input type='text' readonly='readonly' form='form118_"+id+"' value='"+free_product_name+"'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Batch'>";
rowsHTML+="<input type='text' required form='form118_"+id+"' value='"+free_batch+"'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Quantity'>";
rowsHTML+="<input type='number' readonly='readonly' required form='form118_"+id+"' value='"+free_product_quantity+"'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Unit Price'>";
rowsHTML+="<input type='number' readonly='readonly' required form='form118_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Total'>";
rowsHTML+="<input type='number' readonly='readonly' required form='form118_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Action'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value='free on the bill amount'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value='"+id+"'>";
rowsHTML+="<input type='button' class='save_icon' form='form118_"+id+"' id='save_form118_"+id+"' >";
rowsHTML+="<input type='button' class='delete_icon' form='form118_"+id+"' id='delete_form118_"+id+"' onclick='form118_delete_item($(this));'>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form118_"+id+"' value=''>";
rowsHTML+="</td>";
rowsHTML+="</tr>";
$('#form118_body').prepend(rowsHTML);
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+data_id+"</bill_id>" +
"<free_with>bill</free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
else
{
$("#modal7_link").click();
}
});
}
offer_detail=offers[i].offer_detail;
break;
}
var data_xml="<bills>" +
"<id>"+data_id+"</id>" +
"<bill_num>"+bill_num+"</bill_num>"+
"<customer_name>"+customer+"</customer_name>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<type>product</type>" +
"<offer>"+offer_detail+"</offer>" +
"<discount>"+discount+"</discount>" +
"<tax>"+tax+"</tax>" +
"<transaction_id>"+transaction_id+"</transaction_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form42</link_to>" +
"<title>Saved</title>" +
"<notes>Bill no "+bill_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+transaction_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+tax+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>closed</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>"+total+"</paid_amount>" +
"<acc_name>"+customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+bill_num+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>bill_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(bill_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
if(is_online())
{
server_update_simple(num_xml);
}
else
{
local_update_simple(num_xml);
}
}
},num_data);
if(is_online())
{
server_create_row(data_xml,activity_xml);
server_create_simple(transaction_xml);
server_create_simple(pt_xml);
server_create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id);
});
}
else
{
local_create_row(data_xml,activity_xml);
local_create_simple(transaction_xml);
local_create_simple(pt_xml);
local_create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id);
});
}
var loyalty_program_data="<loyalty_programs>"+
"<name></name>"+
"<points_addition></points_addition>"+
"<status exact='yes'>active</status>"+
"</loyalty_programs>";
fetch_requested_data('',loyalty_program_data,function(programs)
{
vUtil.arrayUnique(programs);
programs.forEach(function(program)
{
var points=parseFloat(program.points_addition)*parseFloat(total);
var loyalty_points_xml="<loyalty_points>"+
"<id>"+vUtil.newKey()+"</id>"+
"<program_name>"+program.name+"</program_name>"+
"<customer>"+customer+"</customer>"+
"<points_addition>"+program.points_addition+"</points_addition>"+
"<points>"+points+"</points>"+
"<date>"+vTime.date()+"</date>"+
"<source>sale</source>"+
"<source_id>"+data_id+"</source_id>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</loyalty_points>";
if(is_online())
{
server_create_simple(loyalty_points_xml);
}
else
{
local_create_simple(loyalty_points_xml);
}
});
});
var total_row="<tr><td colspan='3' data-th='Total'>Total</td>" +
"<td>Amount:</br>Discount: </br>Tax: </br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"Rs. "+discount+"</br>" +
"Rs. "+tax+"</br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form118_foot').html(total_row);
message_string+="\nAmount: "+amount;
message_string+="\ndiscount: "+discount;
message_string+="\nTax: "+tax;
message_string+="\nTotal: "+total;
var subject="Bill from "+get_session_var('title');
$('#form118_share').show();
$('#form118_share').off('click');
$('#form118_share').click(function()
{
modal44_action(customer,subject,message_string);
});
});
var save_button=form.elements[10];
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form118_update_form();
});
$("[id^='save_form118_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Bill(multiple registers, unbilled items)
* @formNo 119
* @param button
*/
function form119_create_item(form)
{
if(is_create_access('form119'))
{
var bill_id=document.getElementById("form119_master").elements[6].value;
var customer=document.getElementById("form119_master").elements[1].value;
var name=form.elements[0].value;
var batch=form.elements[1].value;
var squantity=form.elements[2].value;
var fquantity=form.elements[3].value;
var quantity=parseFloat(squantity)+parseFloat(fquantity);
var price=form.elements[4].value;
var mrp=form.elements[5].value;
var amount=form.elements[6].value;
var discount=form.elements[7].value;
var tax=form.elements[8].value;
var total=form.elements[9].value;
var offer=form.elements[10].value;
var data_id=form.elements[11].value;
var free_product_name=form.elements[14].value;
var free_product_quantity=form.elements[15].value;
var unbilled_item=form.elements[16].value;
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+batch+"</batch>" +
"<quantity>"+quantity+"</quantity>" +
"<p_quantity>"+squantity+"</p_quantity>" +
"<f_quantity>"+fquantity+"</f_quantity>" +
"<unit_price>"+price+"</unit_price>" +
"<mrp>"+mrp+"</mrp>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<discount>"+discount+"</discount>" +
"<offer>"+offer+"</offer>" +
"<type>bought</type>" +
"<tax>"+tax+"</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<free_with></free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
var unbilled_xml="<unbilled_sale_items>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+batch+"</batch>" +
"<customer>"+customer+"</customer>" +
"</unbilled_sale_items>";
if(is_online())
{
server_create_simple(data_xml);
if(unbilled_item=='yes')
server_delete_simple(unbilled_xml);
}
else
{
local_create_simple(data_xml);
if(unbilled_item=='yes')
local_delete_simple(unbilled_xml);
}
//////adding free product to the bill if applicable
if(free_product_name!="" && free_product_name!=null)
{
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var id=vUtil.newKey();
var rowsHTML="<tr>";
rowsHTML+="<form id='form119_"+id+"'></form>";
rowsHTML+="<td data-th='Product Name'>";
rowsHTML+="<label id='form119_product_make_"+id+"'></label>";
rowsHTML+="<br><v2></v2><textarea required form='form119_"+id+"' readonly='readonly'>"+free_product_name+"</textarea>";
rowsHTML+="<img src='"+server_root+"/images/add_image.png' class='add_image' title='Add new product' onclick='modal14_action();'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Batch'>";
rowsHTML+="<input type='text' required form='form119_"+id+"' value='"+free_batch+"'>";
rowsHTML+="<img src='"+server_root+"/images/add_image.png' class='add_image' title='Add new batch' onclick='modal22_action();'>";
rowsHTML+="<br><v2>Expiry: </v2><label id='form119_exp_"+id+"'></label>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Quantity'>";
rowsHTML+="<v1>Bought: </v1><input type='number' min='0' required readonly='readonly' form='form119_"+id+"' step='any' value='0'>";
rowsHTML+="<br><v2>Free: </v2><input type='number' min='0' value='0' required readonly='readonly' form='form119_"+id+"' step='any' value='"+free_product_quantity+"'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Price'>";
rowsHTML+="<v1>Sale: </v1>Rs. <input type='number' required min='0' readonly='readonly' form='form119_"+id+"' step='any'>";
rowsHTML+="<br><v2>MRP: </v2>Rs. <input type='number' min='0' readonly='readonly' form='form119_"+id+"' step='any'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Total'>";
rowsHTML+="<v1>Amount: </v1>Rs. <input type='number' required min='0' form='form119_"+id+"' readonly='readonly' step='any' value='0'>";
rowsHTML+="<input type='hidden' value='0' form='form119_"+id+"' readonly='readonly'>";
rowsHTML+="<br><v2>Tax: </v2>Rs. <input type='number' required min='0' value='0' form='form119_"+id+"' readonly='readonly' step='any' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Action'>";
rowsHTML+="<input type='hidden' form='form119_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form119_"+id+"' value='free with "+name+"'>";
rowsHTML+="<input type='hidden' form='form119_"+id+"' value='"+id+"'>";
rowsHTML+="<input type='button' class='submit_hidden' form='form119_"+id+"' id='save_form119_"+id+"' >";
rowsHTML+="<input type='button' class='delete_icon' form='form119_"+id+"' id='delete_form119_"+id+"' onclick='form119_delete_item($(this));'>";
rowsHTML+="</td>";
rowsHTML+="</tr>";
$('#form119_body').prepend(rowsHTML);
var make_data="<product_master>" +
"<make></make>" +
"<name exact='yes'>"+free_product_name+"</name>" +
"</product_master>";
get_single_column_data(function(data)
{
if(data.length>0)
{
document.getElementById('form119_product_make_'+id).innerHTML=data[0]+":";
}
},make_data);
var exp_data="<product_instances>" +
"<expiry></expiry>" +
"<product_name exact='yes'>"+free_product_name+"</product_name>" +
"<batch exact='yes'>"+free_batch+"</batch>" +
"</product_instances>";
get_single_column_data(function(data)
{
if(data.length>0)
{
document.getElementById('form119_exp_'+id).innerHTML=get_my_past_date(data[0]);
}
},exp_data);
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<mrp>0</mrp>" +
"<p_quantity>0</p_quantity>" +
"<f_quantity>"+free_product_quantity+"</f_quantity>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<free_with>"+name+"</free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
else
{
$("#modal7_link").click();
}
});
}
for(var i=0;i<10;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var save_button=form.elements[12];
$(save_button).off('click');
var del_button=form.elements[13];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form119_delete_item(del_button);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create bill(multiple registers, unbilled items)
* @formNo 119
* @param button
*/
function form119_create_form()
{
if(is_create_access('form119'))
{
var form=document.getElementById("form119_master");
var customer=form.elements[1].value;
var bill_type=form.elements[2].value;
var bill_date=get_raw_time(form.elements[3].value);
var bill_num=form.elements[4].value;
var amount=0;
var discount=0;
var tax=0;
var total=0;
$("[id^='save_form119']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
amount+=parseFloat(subform.elements[6].value);
discount+=parseFloat(subform.elements[7].value);
tax+=parseFloat(subform.elements[8].value);
total+=parseFloat(subform.elements[9].value);
});
var data_id=form.elements[6].value;
var transaction_id=form.elements[8].value;
var last_updated=get_my_time();
var offer_detail="";
var offer_data="<offers>" +
"<criteria_type>min amount crossed</criteria_type>" +
"<criteria_amount upperbound='yes'>"+(amount-discount)+"</criteria_amount>" +
"<offer_type exact='yes'>bill</offer_type>" +
"<result_type></result_type>" +
"<discount_percent></discount_percent>" +
"<discount_amount></discount_amount>" +
"<quantity_add_percent></quantity_add_percent>" +
"<quantity_add_amount></quantity_add_amount>" +
"<free_product_name></free_product_name>" +
"<free_product_quantity></free_product_quantity>" +
"<offer_detail></offer_detail>" +
"<status array='yes'>--active--extended--</status>" +
"</offers>";
fetch_requested_data('',offer_data,function(offers)
{
offers.sort(function(a,b)
{
if(a.criteria_amount<b.criteria_amount)
{ return 1;}
else
{ return -1;}
});
for(var i in offers)
{
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
var dis=parseFloat(((amount-discount)*parseInt(offers[i].discount_percent))/100);
tax-=(tax*(dis/(amount-discount)));
discount+=dis;
total=amount-discount+tax;
}
else
{
var dis=parseFloat(offers[i].discount_amount)*(Math.floor((amount-discount)/parseFloat(offers[i].criteria_amount)));
tax-=(tax*(dis/(amount-discount)));
discount+=dis;
total=amount-discount+tax;
}
}
else if(offers[i].result_type=='product free')
{
var free_product_name=offers[i].free_product_name;
var free_product_quantity=parseFloat(offers[i].free_product_quantity)*(Math.floor(parseFloat(amount-discount)/parseFloat(offers[i].criteria_amount)));
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var id=vUtil.newKey();
var rowsHTML="<tr>";
rowsHTML+="<form id='form119_"+id+"'></form>";
rowsHTML+="<td data-th='Product Name'>";
rowsHTML+="<label id='form119_product_make_"+id+"'></label>";
rowsHTML+="<br><v2></v2><textarea required form='form119_"+id+"' readonly='readonly'>"+free_product_name+"</textarea>";
rowsHTML+="<img src='"+server_root+"/images/add_image.png' class='add_image' title='Add new product' onclick='modal14_action();'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Batch'>";
rowsHTML+="<input type='text' required form='form119_"+id+"' value='"+free_batch+"'>";
rowsHTML+="<img src='"+server_root+"/images/add_image.png' class='add_image' title='Add new batch' onclick='modal22_action();'>";
rowsHTML+="<br><v2>Expiry: </v2><label id='form119_exp_"+id+"'></label>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Quantity'>";
rowsHTML+="<v1>Bought: </v1><input type='number' min='0' required readonly='readonly' form='form119_"+id+"' step='any' value='0'>";
rowsHTML+="<br><v2>Free: </v2><input type='number' min='0' value='0' required readonly='readonly' form='form119_"+id+"' step='any' value='"+free_product_quantity+"'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Price'>";
rowsHTML+="<v1>Sale: </v1>Rs. <input type='number' required min='0' readonly='readonly' form='form119_"+id+"' step='any'>";
rowsHTML+="<br><v2>MRP: </v2>Rs. <input type='number' min='0' readonly='readonly' form='form119_"+id+"' step='any'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Total'>";
rowsHTML+="<v1>Amount: </v1>Rs. <input type='number' required min='0' form='form119_"+id+"' readonly='readonly' step='any' value='0'>";
rowsHTML+="<input type='hidden' value='0' form='form119_"+id+"' readonly='readonly'>";
rowsHTML+="<br><v2>Tax: </v2>Rs. <input type='number' required min='0' value='0' form='form119_"+id+"' readonly='readonly' step='any' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td data-th='Action'>";
rowsHTML+="<input type='hidden' form='form119_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form119_"+id+"' value='free with "+name+"'>";
rowsHTML+="<input type='hidden' form='form119_"+id+"' value='"+id+"'>";
rowsHTML+="<input type='button' class='submit_hidden' form='form119_"+id+"' id='save_form119_"+id+"' >";
rowsHTML+="<input type='button' class='delete_icon' form='form119_"+id+"' id='delete_form119_"+id+"' onclick='form119_delete_item($(this));'>";
rowsHTML+="</td>";
rowsHTML+="</tr>";
$('#form119_body').prepend(rowsHTML);
var make_data="<product_master>" +
"<make></make>" +
"<name exact='yes'>"+free_product_name+"</name>" +
"</product_master>";
get_single_column_data(function(data)
{
if(data.length>0)
{
document.getElementById('form119_product_make_'+id).innerHTML=data[0]+":";
}
},make_data);
var exp_data="<product_instances>" +
"<expiry></expiry>" +
"<product_name exact='yes'>"+free_product_name+"</product_name>" +
"<batch exact='yes'>"+free_batch+"</batch>" +
"</product_instances>";
get_single_column_data(function(data)
{
if(data.length>0)
{
document.getElementById('form119_exp_'+id).innerHTML=get_my_past_date(data[0]);
}
},exp_data);
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<mrp>0</mrp>" +
"<p_quantity>0</p_quantity>" +
"<f_quantity>"+free_product_quantity+"</f_quantity>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+data_id+"</bill_id>" +
"<free_with>bill</free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
else
{
$("#modal7_link").click();
}
});
}
offer_detail=offers[i].offer_detail;
break;
}
var data_xml="<bills>" +
"<id>"+data_id+"</id>" +
"<bill_num>"+bill_num+"</bill_num>"+
"<customer_name>"+customer+"</customer_name>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<type>product</type>" +
"<billing_type>"+bill_type+"</billing_type>" +
"<offer>"+offer_detail+"</offer>" +
"<discount>"+discount+"</discount>" +
"<tax>"+tax+"</tax>" +
"<transaction_id>"+transaction_id+"</transaction_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form92</link_to>" +
"<title>Saved</title>" +
"<notes>Bill no "+bill_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+transaction_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+tax+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>"+bill_type+"_bill_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(bill_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
if(is_online())
{
server_update_simple(num_xml);
}
else
{
local_update_simple(num_xml);
}
}
},num_data);
var pt_tran_id=vUtil.newKey();
var p_status="closed";
var p_amount=total;
if((get_payment_mode())=='credit')
{
p_status='pending';
p_amount=0;
}
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>"+p_status+"</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>"+p_amount+"</paid_amount>" +
"<acc_name>"+customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+bill_num+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
server_create_simple(transaction_xml);
server_create_simple(pt_xml);
server_create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id,function(mode,paid_amount)
{
document.getElementById('form119_payment_info').innerHTML="Payment: "+mode+"<br>Paid: Rs."+paid_amount;
});
});
}
else
{
local_create_row(data_xml,activity_xml);
local_create_simple(transaction_xml);
local_create_simple(pt_xml);
local_create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id,function(mode,paid_amount)
{
document.getElementById('form119_payment_info').innerHTML="Payment: "+mode+"<br>Paid: Rs."+paid_amount;
});
});
}
var total_row="<tr><td colspan='3' data-th='Total'>Total</td>" +
"<td>Amount:</br>Discount: </br>Tax: </br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"Rs. "+discount+"</br>" +
"Rs. "+tax+"</br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form119_foot').html(total_row);
var subject="Bill from "+get_session_var('title');
$('#form119_share').show();
$('#form119_share').off('click');
$('#form119_share').click(function()
{
});
});
var save_button=form.elements[10];
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form119_update_form();
});
$("[id^='save_form119_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 121
* form Adjust Loyalty Points
* @param button
*/
function form121_create_item(form)
{
if(is_create_access('form121'))
{
var program=form.elements[0].value;
var customer=form.elements[1].value;
var points=form.elements[2].value;
var date=form.elements[3].value;
var source=form.elements[4].value;
var data_id=form.elements[5].value;
var last_updated=get_my_time();
var data_xml="<loyalty_points>" +
"<id>"+data_id+"</id>" +
"<program_name>"+program+"</program_name>" +
"<customer>"+customer+"</customer>" +
"<points>"+points+"</points>" +
"<date>"+get_raw_time(date)+"</date>" +
"<source>"+source+"</source>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</loyalty_points>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>loyalty_points</tablename>" +
"<link_to>form121</link_to>" +
"<title>Added</title>" +
"<notes>"+points+" Loyalty points to "+customer+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[7];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form121_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Enter Supplier Bill(unbilled items)
* @formNo 122
* @param button
*/
function form122_create_item(form)
{
if(is_create_access('form122'))
{
var bill_id=document.getElementById('form122_master').elements['bill_id'].value;
var supplier=document.getElementById('form122_master').elements['supplier'].value;
var entry_date=get_raw_time(document.getElementById('form122_master').elements['entry_date'].value);
var item_name=form.elements[1].value;
var item_desc=form.elements[2].value;
var batch=form.elements[3].value;
var quantity=form.elements[4].value;
var mrp=form.elements[5].value;
var unit_price=form.elements[6].value;
var amount=form.elements[7].value;
var tax=form.elements[8].value;
var po_price=form.elements[9].value;
var po_amount=form.elements[10].value;
var po_tax=form.elements[11].value;
var total=parseFloat(amount)+parseFloat(tax);
var qc=form.elements[12].value;
var qc_comments=form.elements[13].value;
var storage=form.elements[14].value;
var data_id=form.elements[15].value;
var save_button=form.elements[16];
var del_button=form.elements[17];
var is_unbilled=form.elements['unbilled'].value;
var put_away_status='pending';
if(is_unbilled=='yes' || qc=='rejected')
{
put_away_status='completed';
}
var last_updated=get_my_time();
var data_xml="<supplier_bill_items>" +
"<id>"+data_id+"</id>" +
"<bill_id>"+bill_id+"</bill_id>"+
"<product_name>"+item_name+"</product_name>" +
"<item_desc>"+item_desc+"</item_desc>"+
"<batch>"+batch+"</batch>" +
"<quantity>"+quantity+"</quantity>" +
"<mrp>"+mrp+"</mrp>"+
"<unit_price>"+unit_price+"</unit_price>"+
"<amount>"+amount+"</amount>"+
"<tax>"+tax+"</tax>"+
"<po_price>"+po_price+"</po_price>"+
"<po_amount>"+po_amount+"</po_amount>"+
"<po_tax>"+po_tax+"</po_tax>"+
"<total>"+total+"</total>"+
"<storage>"+storage+"</storage>"+
"<qc>"+qc+"</qc>"+
"<qc_comments>"+qc_comments+"</qc_comments>"+
"<put_away_status>"+put_away_status+"</put_away_status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_bill_items>";
create_simple(data_xml);
if(qc=='rejected')
{
var return_xml="<supplier_returns>" +
"<id>"+bill_id+"</id>" +
"<supplier>"+supplier+"</supplier>" +
"<return_date>"+entry_date+"</return_date>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_returns>";
var return_data_xml="<supplier_return_items>" +
"<id>"+data_id+"</id>" +
"<return_id>"+bill_id+"</return_id>"+
"<item_name>"+item_name+"</item_name>" +
"<item_desc>"+item_desc+"</item_desc>"+
"<batch>"+batch+"</batch>" +
"<quantity>"+quantity+"</quantity>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_return_items>";
create_simple(return_data_xml);
create_simple_no_warning(return_xml);
}
else
{
var product_instances_xml="<product_instances>"+
"<id></id>"+
"<product_name exact='yes'>"+item_name+"</product_name>"+
"<batch exact='yes'>"+batch+"</batch>"+
"</product_instances>";
fetch_requested_data('',product_instances_xml,function(batches)
{
var product_instances_xml="<product_instances>"+
"<id>"+batches[0].id+"</id>"+
"<status>available</status>"+
"</product_instances>";
update_simple(product_instances_xml);
});
}
for(var i=0;i<15;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form122_delete_item(del_button);
});
////////////////update status of unbilled item///////////
if(is_unbilled=='yes')
{
var unbilled_id=form.elements['unbilled_id'].value;
var unbilled_xml="<unbilled_purchase_items>"+
"<id>"+unbilled_id+"</id>"+
"<bill_status>completed</bill_status>"+
"</unbilled_purchase_items>";
update_simple(unbilled_xml);
}
///////////adding store placement////////
var storage_data="<area_utilization>" +
"<id></id>" +
"<name exact='yes'>"+storage+"</name>" +
"<item_name exact='yes'>"+item_name+"</item_name>" +
"<batch exact='yes'>"+batch+"</batch>" +
"</area_utilization>";
fetch_requested_data('',storage_data,function(placements)
{
if(placements.length===0)
{
var storage_xml="<area_utilization>" +
"<id>"+vUtil.newKey()+"</id>" +
"<name>"+storage+"</name>" +
"<item_name>"+item_name+"</item_name>" +
"<batch>"+batch+"</batch>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</area_utilization>";
create_simple(storage_xml);
}
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form New supplier Bill
* @param button
*/
function form122_create_form()
{
if(is_create_access('form122'))
{
var form=document.getElementById("form122_master");
var supplier=form.elements['supplier'].value;
var bill_id=form.elements['bill_num'].value;
var bill_date=get_raw_time(form.elements['bill_date'].value);
var entry_date=get_raw_time(form.elements['entry_date'].value);
var data_id=form.elements['bill_id'].value;
var transaction_id=form.elements['t_id'].value;
var last_updated=get_my_time();
var save_button=form.elements['save'];
var share_button=form.elements['share'];
var order_id=form.elements['order_id'].value;
var order_num=form.elements['po_num'].value;
var cst='no';
if(form.elements['cst'].checked)
{
cst='yes';
}
var bt=get_session_var('title');
$(share_button).show();
$(share_button).click(function()
{
modal101_action(bt+' - Purchase bill # '+bill_id,supplier,'supplier',function (func)
{
print_form122(func);
});
});
var total=0;
var tax=0;
var amount=0;
var total_accepted=0;
var total_quantity=0;
$("[id^='save_form122']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(subform.elements[1].value=="")
{
$(this).parent().parent().remove();
}
else
{
if(subform.elements[12].value=='accepted')
{
if(!isNaN(parseFloat(subform.elements[7].value)))
amount+=parseFloat(subform.elements[7].value);
if(!isNaN(parseFloat(subform.elements[8].value)))
tax+=parseFloat(subform.elements[8].value);
if(!isNaN(parseFloat(subform.elements[4].value)))
total_accepted+=parseFloat(subform.elements[4].value);
}
if(!isNaN(parseFloat(subform.elements[4].value)))
total_quantity+=parseFloat(subform.elements[4].value);
}
});
amount=vUtil.round(amount,2);
tax=vUtil.round(tax,2);
total=amount+tax;
var total_row="<tr><td colspan='3' data-th='Total'>Total Accepted Quantity: "+total_accepted+"<br>Total Rejected Quantity: "+(total_quantity-total_accepted)+"</td>" +
"<td>Amount:</br>Tax: </br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"Rs. "+tax+"</br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form122_foot').html(total_row);
var data_xml="<supplier_bills>" +
"<id>"+data_id+"</id>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<order_id>"+order_id+"</order_id>" +
"<order_num>"+order_num+"</order_num>" +
"<supplier>"+supplier+"</supplier>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<entry_date>"+entry_date+"</entry_date>" +
"<total>"+total+"</total>" +
"<discount>0</discount>" +
"<amount>"+amount+"</amount>" +
"<tax>"+tax+"</tax>" +
"<cst>"+cst+"</cst>"+
"<notes>pending approval</notes>"+
"<transaction_id>"+transaction_id+"</transaction_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>supplier_bills</tablename>" +
"<link_to>form53</link_to>" +
"<title>Saved</title>" +
"<notes>Supplier Bill # "+bill_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var po_data="<purchase_orders>"+
"<id>"+order_id+"</id>" +
"<bill_id></bill_id>" +
"<total_quantity></total_quantity>"+
"<quantity_received></quantity_received>"+
"<quantity_accepted></quantity_accepted>"+
"</purchase_orders>";
fetch_requested_data('',po_data,function (porders)
{
if(porders.length>0)
{
var id_object_array=vUtil.jsonParse(porders[0].bill_id);
var id_object=new Object();
id_object.bill_num=bill_id;
id_object.bill_id=data_id;
id_object.total_received=total_quantity;
id_object.total_accepted=total_accepted;
id_object_array.push(id_object);
var quantity_accepted=0;
var quantity_received=0;
var quantity_qc_pending=0;
for(var x in id_object_array)
{
quantity_received+=parseFloat(id_object_array[x].total_received);
quantity_accepted+=parseFloat(id_object_array[x].total_accepted);
}
if(porders[0].quantity_received=="" || porders[0].quantity_received=='null')
{
porders[0].quantity_received=0;
}
if(parseFloat(porders[0].quantity_received)>quantity_received)
{
quantity_qc_pending=parseFloat(porders[0].quantity_received)-quantity_received;
quantity_received=parseFloat(porders[0].quantity_received);
}
var status='partially received';
if(parseFloat(porders[0].total_quantity)<=quantity_accepted)
{
status='completely received';
}
var new_bill_id=JSON.stringify(id_object_array);
console.log(new_bill_id);
var po_xml="<purchase_orders>" +
"<id>"+order_id+"</id>" +
"<bill_id>"+new_bill_id+"</bill_id>" +
"<quantity_received>"+quantity_received+"</quantity_received>"+
"<quantity_accepted>"+quantity_accepted+"</quantity_accepted>"+
"<quantity_qc_pending>"+quantity_qc_pending+"</quantity_qc_pending>"+
"<status>"+status+"</status>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</purchase_orders>";
update_simple(po_xml);
}
});
var transaction_xml="<transactions>" +
"<id>"+transaction_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+supplier+"</giver>" +
"<tax>"+(-tax)+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>pending</status>" +
"<type>paid</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>0</paid_amount>" +
"<acc_name>"+supplier+"</acc_name>" +
"<due_date>"+get_debit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>purchase bill</source>" +
"<source_info>"+bill_id+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+supplier+"</receiver>" +
"<giver>master</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var notification_xml="<notifications>" +
"<id>"+vUtil.newKey()+"</id>" +
"<t_generated>"+get_my_time()+"</t_generated>" +
"<data_id unique='yes'>"+data_id+"</data_id>" +
"<title>Pending purchase bill approval</title>" +
"<notes>Purchase bill # "+bill_id+" is pending for approval</notes>" +
"<link_to>form53</link_to>" +
"<status>pending</status>" +
"<target_user>"+get_session_var('purchase_bill_approver')+"</target_user>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</notifications>";
create_row(data_xml,activity_xml);
create_simple(transaction_xml);
create_simple(pt_xml);
create_simple_func(payment_xml,function()
{
//modal28_action(pt_tran_id);
});
create_simple_no_warning(notification_xml);
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form122_update_form();
});
$("[id^='save_form122_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 125
* form Customer Accounts
* @param button
*/
function form125_create_item(form)
{
if(is_create_access('form125'))
{
var customer=form.elements[0].value;
var username=form.elements[1].value;
var password=form.elements[2].value;
var status=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var domain=get_domain();
var salt='$2a$10$'+domain+'1234567891234567891234';
var salt_22=salt.substring(0, 29);
var bcrypt = new bCrypt();
bcrypt.hashpw(password, salt_22, function(newhash)
{
var data_xml="<accounts>" +
"<id>"+data_id+"</id>" +
"<acc_name>"+customer+"</acc_name>" +
"<username unique='yes'>"+username+"</username>" +
"<status>"+status+"</status>" +
"<password>"+<PASSWORD>+"</password>"+
"<type>customer</type>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</accounts>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>accounts</tablename>" +
"<link_to>form125</link_to>" +
"<title>Added</title>" +
"<notes>Account for username "+username+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form125_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form125_update_item(form);
});
});
}
else
{
$("#modal2_link").click();
}
};
/**
* @form Job Order
* @param button
*/
function form130_create_item(form)
{
if(is_create_access('form130'))
{
var bill_id=document.getElementById("form130_master").elements[3].value;
var name=form.elements[0].value;
var batch="";
var staff="";
var quantity="";
var notes="";
if(isNaN(form.elements[2].value))
{
staff=form.elements[1].value;
notes=form.elements[2].value;
}
else
{
batch=form.elements[1].value;
quantity=form.elements[2].value;
}
var price=form.elements[3].value;
var total=form.elements[4].value;
var amount=form.elements[5].value;
var discount=form.elements[6].value;
var tax=form.elements[7].value;
var offer=form.elements[8].value;
var data_id=form.elements[9].value;
var free_product_name=form.elements[12].value;
var free_product_quantity=form.elements[13].value;
var free_service_name=form.elements[14].value;
var last_updated=get_my_time();
if(isNaN(form.elements[2].value))
{
var pre_requisite_data="<pre_requisites>" +
"<type exact='yes'>service</type>" +
"<requisite_type exact='yes'>task</requisite_type>" +
"<name exact='yes'>"+name+"</name>" +
"<requisite_name></requisite_name>" +
"<quantity></quantity>" +
"</pre_requisites>";
fetch_requested_data('',pre_requisite_data,function(pre_requisites)
{
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<unit_price>"+price+"</unit_price>" +
"<notes>"+notes+"</notes>" +
"<staff>"+staff+"</staff>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<discount>"+discount+"</discount>" +
"<offer>"+offer+"</offer>" +
"<type>bought</type>" +
"<tax>"+tax+"</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
pre_requisites.forEach(function(pre_requisite)
{
var task_id=vUtil.newKey();
var task_xml="<task_instances>" +
"<id>"+task_id+"</id>" +
"<name>"+pre_requisite.name+"</name>" +
"<assignee>"+staff+"</assignee>" +
"<t_initiated>"+get_my_time()+"</t_initiated>" +
"<t_due>"+get_task_due_period()+"</t_due>" +
"<status>pending</status>" +
"<task_hours>"+pre_requisite.quantity+"</task_hours>" +
"<source>service</source>" +
"<source_id>"+data_id+"</source_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</task_instances>";
var activity_xml="<activity>" +
"<data_id>"+task_id+"</data_id>" +
"<tablename>task_instances</tablename>" +
"<link_to>form14</link_to>" +
"<title>Added</title>" +
"<notes>Task "+pre_requisite.name+" assigned to "+staff+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(task_xml,activity_xml);
}
else
{
local_create_row(task_xml,activity_xml);
}
});
});
}
else
{
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+batch+"</batch>" +
"<unit_price>"+price+"</unit_price>" +
"<quantity>"+quantity+"</quantity>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<discount>"+discount+"</discount>" +
"<offer>"+offer+"</offer>" +
"<type>bought</type>" +
"<tax>"+tax+"</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<free_with></free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
}
////adding free service
if(free_service_name!="" && free_service_name!=null)
{
var id=vUtil.newKey();
rowsHTML="<tr>";
rowsHTML+="<form id='form130_"+id+"'></form>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' readonly='readonly' form='form130_"+id+"' value='"+free_service_name+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' readonly='readonly' required form='form130_"+id+"' value='"+staff+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<textarea readonly='readonly' required form='form130_"+id+">free with "+name+"</textarea>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form130_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form130_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='free with "+name+"'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='"+id+"'>";
rowsHTML+="<input type='button' class='save_icon' form='form130_"+id+"' id='save_form130_"+id+"' >";
rowsHTML+="<input type='button' class='delete_icon' form='form130_"+id+"' id='delete_form130_"+id+"' onclick='form130_delete_item($(this));'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="</td>";
rowsHTML+="</tr>";
$('#form130_body').prepend(rowsHTML);
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_service_name+"</item_name>" +
"<staff>"+staff+"</staff>" +
"<notes>free with "+name+"</notes>" +
"<unit_price>0</unit_price>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<free_with>"+name+"</free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
offer_invalid=false;
}
//////adding free product to the bill if applicable
if(free_product_name!="" && free_product_name!=null)
{
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var id=vUtil.newKey();
rowsHTML="<tr>";
rowsHTML+="<form id='form130_"+id+"'></form>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' readonly='readonly' form='form130_"+id+"' value='"+free_product_name+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' readonly='readonly' required form='form130_"+id+"' value='"+free_batch+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form130_"+id+"' value='"+free_product_quantity+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form130_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form130_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='free with "+name+"'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='"+id+"'>";
rowsHTML+="<input type='button' class='save_icon' form='form130_"+id+"' id='save_form130_"+id+"' >";
rowsHTML+="<input type='button' class='delete_icon' form='form130_"+id+"' id='delete_form130_"+id+"' onclick='form130_delete_item($(this));'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="</td>";
rowsHTML+="</tr>";
$('#form130_body').prepend(rowsHTML);
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<free_with>"+name+"</free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
else
{
$("#modal7_link").click();
}
});
}
for(var i=0;i<10;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[11];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form130_delete_item(del_button);
});
var save_button=form.elements[10];
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Job Order
* @param button
*/
function form130_create_form()
{
if(is_create_access('form130'))
{
var form=document.getElementById("form130_master");
var customer=form.elements[1].value;
var bill_date=get_raw_time(form.elements[2].value);
var message_string="Bill from:"+get_session_var('title')+"\nAddress: "+get_session_var('address');
var amount=0;
var discount=0;
var tax=0;
var total=0;
$("[id^='save_form130']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
total+=parseFloat(subform.elements[4].value);
amount+=parseFloat(subform.elements[5].value);
discount+=parseFloat(subform.elements[6].value);
tax+=parseFloat(subform.elements[7].value);
message_string+="\nItem: "+subform.elements[0].value;
message_string+=" Price: "+subform.elements[3].value;
message_string+=" Total: "+subform.elements[4].value;
});
var data_id=form.elements[3].value;
var transaction_id=form.elements[5].value;
var last_updated=get_my_time();
var offer_detail="";
var offer_data="<offers>" +
"<criteria_type>min amount crossed</criteria_type>" +
"<criteria_amount upperbound='yes'>"+(amount-discount)+"</criteria_amount>" +
"<offer_type exact='yes'>bill</offer_type>" +
"<result_type></result_type>" +
"<discount_percent></discount_percent>" +
"<discount_amount></discount_amount>" +
"<quantity_add_percent></quantity_add_percent>" +
"<quantity_add_amount></quantity_add_amount>" +
"<free_product_name></free_product_name>" +
"<free_product_quantity></free_product_quantity>" +
"<free_service_name></free_service_name>" +
"<offer_detail></offer_detail>" +
"<status array='yes'>active--extended</status>" +
"</offers>";
fetch_requested_data('',offer_data,function(offers)
{
offers.sort(function(a,b)
{
if(a.criteria_amount<b.criteria_amount)
{ return 1;}
else
{ return -1;}
});
for(var i in offers)
{
if(offers[i].result_type=='discount')
{
if(offers[i].discount_percent!="" && offers[i].discount_percent!=0 && offers[i].discount_percent!="0")
{
var dis=parseFloat(((amount-discount)*parseInt(offers[i].discount_percent))/100);
tax-=(tax*(dis/(amount-discount)));
discount+=dis;
total=amount-discount+tax;
}
else
{
var dis=parseFloat(offers[i].discount_amount)*(Math.floor((amount-discount)/parseFloat(offers[i].criteria_amount)));
tax-=(tax*(dis/(amount-discount)));
discount+=dis;
total=amount-discount+tax;
}
}
else if(offers[i].result_type=='product free')
{
var free_product_name=offers[i].free_product_name;
var free_product_quantity=parseFloat(offers[i].free_product_quantity)*(Math.floor(parseFloat(amount-discount)/parseFloat(offers[i].criteria_amount)));
get_inventory(free_product_name,'',function(free_quantities)
{
if(free_quantities>=free_product_quantity)
{
var free_batch_data="<bill_items count='1'>" +
"<batch></batch>" +
"<item_name exact='yes'>"+free_product_name+"</item_name>" +
"</bill_items>";
get_single_column_data(function(data)
{
var free_batch="";
if(data.length>0)
{
free_batch=data[0];
}
var id=vUtil.newKey();
rowsHTML="<tr>";
rowsHTML+="<form id='form130_"+id+"'></form>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' readonly='readonly' form='form130_"+id+"' value='"+free_product_name+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' required form='form130_"+id+"' value='"+free_batch+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form130_"+id+"' value='"+free_product_quantity+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form130_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form130_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='free on the bill amount'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='"+id+"'>";
rowsHTML+="<input type='button' class='save_icon' form='form130_"+id+"' id='save_form130_"+id+"' >";
rowsHTML+="<input type='button' class='delete_icon' form='form130_"+id+"' id='delete_form130_"+id+"' onclick='form130_delete_item($(this));'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="</td>";
rowsHTML+="</tr>";
$('#form130_body').prepend(rowsHTML);
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_product_name+"</item_name>" +
"<batch>"+free_batch+"</batch>" +
"<unit_price>0</unit_price>" +
"<quantity>"+free_product_quantity+"</quantity>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+data_id+"</bill_id>" +
"<free_with>bill</free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
},free_batch_data);
}
else
{
$("#modal7_link").click();
}
});
}
else if(offers[i].result_type=='service free')
{
var free_service_name=offers[i].free_service_name;
var id=vUtil.newKey();
rowsHTML="<tr>";
rowsHTML+="<form id='form130_"+id+"'></form>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' readonly='readonly' form='form130_"+id+"' value='"+free_service_name+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='text' readonly='readonly' required form='form130_"+id+"'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<textarea readonly='readonly' required form='form130_"+id+"'>free service</textarea>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form130_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='number' readonly='readonly' required form='form130_"+id+"' value='0'>";
rowsHTML+="</td>";
rowsHTML+="<td>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='0'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='free on the bill amount'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value='"+id+"'>";
rowsHTML+="<input type='button' class='save_icon' form='form130_"+id+"' id='save_form130_"+id+"' >";
rowsHTML+="<input type='button' class='delete_icon' form='form130_"+id+"' id='delete_form130_"+id+"' onclick='form130_delete_item($(this));'>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="<input type='hidden' form='form130_"+id+"' value=''>";
rowsHTML+="</td>";
rowsHTML+="</tr>";
$('#form130_body').prepend(rowsHTML);
var free_pre_requisite_data="<pre_requisites>" +
"<type exact='yes'>service</type>" +
"<requisite_type exact='yes'>task</requisite_type>" +
"<name exact='yes'>"+free_service_name+"</name>" +
"<requisite_name></requisite_name>" +
"<quantity></quantity>" +
"</pre_requisites>";
fetch_requested_data('',free_pre_requisite_data,function(free_pre_requisites)
{
var free_xml="<bill_items>" +
"<id>"+id+"</id>" +
"<item_name>"+free_service_name+"</item_name>" +
"<staff></staff>" +
"<notes>free service</notes>" +
"<unit_price>0</unit_price>" +
"<amount>0</amount>" +
"<total>0</total>" +
"<discount>0</discount>" +
"<offer></offer>" +
"<type>free</type>" +
"<tax>0</tax>" +
"<bill_id>"+data_id+"</bill_id>" +
"<free_with>bill</free_with>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(free_xml);
}
else
{
local_create_simple(free_xml);
}
free_pre_requisites.forEach(function(free_pre_requisite)
{
var task_id=vUtil.newKey();
var task_xml="<task_instances>" +
"<id>"+task_id+"</id>" +
"<name>"+free_pre_requisite.name+"</name>" +
"<assignee></assignee>" +
"<t_initiated>"+get_my_time()+"</t_initiated>" +
"<t_due>"+get_task_due_period()+"</t_due>" +
"<status>pending</status>" +
"<task_hours>"+free_pre_requisite.quantity+"</task_hours>" +
"<source>service</source>" +
"<source_id>"+id+"</source_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</task_instances>";
var activity_xml="<activity>" +
"<data_id>"+task_id+"</data_id>" +
"<tablename>task_instances</tablename>" +
"<link_to>form14</link_to>" +
"<title>Added</title>" +
"<notes>Task "+free_pre_requisite.name+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(task_xml,activity_xml);
}
else
{
local_create_row(task_xml,activity_xml);
}
});
});
}
offer_detail=offers[i].offer_detail;
break;
}
var data_xml="<bills>" +
"<id>"+data_id+"</id>" +
"<customer_name>"+customer+"</customer_name>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<type>both</type>" +
"<offer>"+offer_detail+"</offer>" +
"<discount>"+discount+"</discount>" +
"<tax>"+tax+"</tax>" +
"<transaction_id>"+transaction_id+"</transaction_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form42</link_to>" +
"<title>Saved</title>" +
"<notes>Bill no "+data_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+transaction_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+tax+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>closed</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>"+total+"</paid_amount>" +
"<acc_name>"+customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+data_id+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
server_create_simple(transaction_xml);
server_create_simple(pt_xml);
server_create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id);
});
}
else
{
local_create_row(data_xml,activity_xml);
local_create_simple(transaction_xml);
local_create_simple(pt_xml);
local_create_simple_func(payment_xml,function()
{
modal26_action(pt_tran_id);
});
}
message_string+="\nAmount: "+amount;
message_string+="\ndiscount: "+discount;
message_string+="\nTax: "+tax;
message_string+="\nTotal: "+total;
var subject="Bill from "+get_session_var('title');
$('#form130_share').show();
$('#form130_share').click(function()
{
modal44_action(customer,subject,message_string);
});
var total_row="<tr><td colspan='3' data-th='Total'>Total</td>" +
"<td>Amount:</br>Discount: </br>Tax: </br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"Rs. "+discount+"</br>" +
"Rs. "+tax+"</br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form130_foot').html(total_row);
});
var save_button=form.elements[6];
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form130_update_form();
});
$("[id^='save_form130_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 134
* form Service dashboard - Add issue
* @param button
*/
function form134_add_issue(button,problem_type,problem_detail,solution)
{
if(is_create_access('form126'))
{
var issue_xml="<issues>"+
"<id></id>"+
"<detail>"+problem_detail+"</detail>"+
"</issues>";
get_single_column_data(function(problems)
{
var last_updated=get_my_time();
var data_id=vUtil.newKey();
if(problems.length==0)
{
var data_xml="<issues>" +
"<id>"+data_id+"</id>" +
"<short_desc>"+problem_type+"</short_desc>"+
"<detail>"+problem_detail+"</detail>"+
"<status>active</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</issues>";
var solution_xml="<solutions>" +
"<id>"+data_id+"</id>" +
"<issue_id>"+data_id+"</issue_id>"+
"<detail>"+solution+"</detail>"+
"<status>active</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</solutions>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>issues</tablename>" +
"<link_to>form126</link_to>" +
"<title>Added</title>" +
"<notes>Issue to repository</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
if(solution!="")
server_create_simple(solution_xml);
}
else
{
local_create_row(data_xml,activity_xml);
if(solution!="")
local_create_simple(solution_xml);
}
}
else if(solution!="")
{
var issue_id=problems[0];
var solution_xml="<solutions>"+
"<id></id>"+
"<issue_id exact='yes'>"+issue_id+"</issue_id>"+
"<detail exact='yes'>"+solution+"</detail>"+
"</solutions>";
get_single_column_data(function(solutions)
{
if(solutions.length==0)
{
var solution_xml="<solutions>" +
"<id>"+vUtil.newKey()+"</id>" +
"<issue_id>"+issue_id+"</issue_id>"+
"<detail>"+solution+"</detail>"+
"<status>active</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</solutions>";
if(is_online())
{
server_create_simple(solution_xml);
}
else
{
local_create_simple(solution_xml);
}
}
},solution_xml);
}
},issue_xml);
$(button).attr("onclick",'');
$(button).attr('value','Added to Repo');
}
else
{
$("#modal2_link").click();
}
};
/**
* formNo 134
* form Service dashboard - machine
* @param button
*/
function form134_create_machine(form)
{
if(is_create_access('form134'))
{
var master_fields=document.getElementById('form134_master');
var request_id=master_fields.elements[1].value;
var type=form.elements[0].value;
var machine=form.elements[1].value;
var problem=form.elements[2].value;
var closing_notes=form.elements[3].value;
var status=form.elements[4].value;
var data_id=form.elements[5].value;
var last_updated=get_my_time();
var data_xml="<service_request_machines>" +
"<id>"+data_id+"</id>" +
"<request_id>"+request_id+"</request_id>"+
"<machine_type>"+type+"</machine_type>" +
"<machine>"+machine+"</machine>" +
"<problem>"+problem+"</problem>" +
"<closing_notes>"+closing_notes+"</closing_notes>"+
"<status>"+status+"</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</service_request_machines>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>service_request_machines</tablename>" +
"<link_to>form134</link_to>" +
"<title>Added</title>" +
"<notes>Machine "+machine+" to SR# "+request_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[7];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form134_delete_machine(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form134_update_machine(form);
});
}
else
{
$("#modal2_link").click();
}
};
/**
* formNo 134
* form Service dashboard - team
* @param button
*/
function form134_create_team(form)
{
if(is_create_access('form134'))
{
var master_fields=document.getElementById('form134_master');
var request_id=master_fields.elements[1].value;
var assignee=form.elements[0].value;
var phone=form.elements[1].value;
var email=form.elements[2].value;
var data_id=form.elements[3].value;
var last_updated=get_my_time();
var data_xml="<service_request_team>" +
"<id>"+data_id+"</id>" +
"<request_id>"+request_id+"</request_id>"+
"<assignee>"+assignee+"</assignee>" +
"<phone>"+phone+"</phone>" +
"<email>"+email+"</email>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</service_request_team>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>service_request_team</tablename>" +
"<link_to>form134</link_to>" +
"<title>Added</title>" +
"<notes>Assignee "+assignee+" to SR# "+request_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var access_xml="<data_access>" +
"<id>"+vUtil.newKey()+"</id>" +
"<tablename>service_requests</tablename>" +
"<record_id>"+request_id+"</record_id>" +
"<access_type>all</access_type>" +
"<user>"+assignee+"</user>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</data_access>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
server_create_simple(access_xml);
}
else
{
local_create_row(data_xml,activity_xml);
local_create_simple(access_xml);
}
for(var i=0;i<3;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[5];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form134_delete_team(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form134_update_team(form);
});
}
else
{
$("#modal2_link").click();
}
};
/**
* formNo 134
* form Service dashboard - document
* @param button
*/
function form134_create_document(form)
{
if(is_create_access('form134'))
{
var master_fields=document.getElementById('form134_master');
var request_id=master_fields.elements[1].value;
var doc_name=form.elements[0].value;
var data_id=form.elements[2].value;
var url_id="form134_document_url_"+data_id;
var docInfo=document.getElementById(url_id);
var url=$(docInfo).attr('href');
var last_updated=get_my_time();
var data_xml="<documents>" +
"<id>"+data_id+"</id>" +
"<target_id>"+request_id+"</target_id>"+
"<url>"+url+"</url>"+
"<doc_name>"+doc_name+"</doc_name>" +
"<doc_type>service request</doc_type>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</documents>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>documents</tablename>" +
"<link_to>form134</link_to>" +
"<title>Added</title>" +
"<notes>Document "+doc_name+" for SR# "+request_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<2;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[4];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form134_delete_document(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
});
}
else
{
$("#modal2_link").click();
}
};
/**
* formNo 134
* form Service dashboard - task
* @param button
*/
function form134_create_task(form)
{
if(is_create_access('form134'))
{
var master_fields=document.getElementById('form134_master');
var request_id=master_fields.elements[1].value;
var description=form.elements[0].value;
var assignee=form.elements[1].value;
var due_by=get_raw_time(form.elements[2].value);
var status=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_xml="<task_instances>" +
"<id>"+data_id+"</id>" +
"<source_id>"+request_id+"</source_id>"+
"<source>service request</source>"+
"<assignee>"+assignee+"</assignee>" +
"<name>SR #"+request_id+"</name>" +
"<description>"+description+"</description>" +
"<t_initiated>"+last_updated+"</t_initiated>"+
"<t_due>"+due_by+"</t_due>"+
"<status>"+status+"</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</task_instances>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>task_instances</tablename>" +
"<link_to>form134</link_to>" +
"<title>Added</title>" +
"<notes>Task for SR# "+request_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form134_delete_task(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form134_update_task(form);
});
}
else
{
$("#modal2_link").click();
}
};
/**
* @form Customer Profiling
* @formNo 139
* @param button
*/
function form139_create_item(form)
{
if(is_create_access('form139'))
{
var owner=form.elements[0].value;
var facility=form.elements[1].value;
var location=form.elements[2].value;
var area=form.elements[3].value;
var floors=form.elements[4].value;
var data_id=form.elements[5].value;
var last_updated=get_my_time();
var data_xml="<assets>" +
"<id>"+data_id+"</id>" +
"<name>"+facility+"</name>" +
"<type>facility</type>"+
"<owner>"+owner+"</owner>" +
"<owner_type>customer</owner_type>" +
"<location>"+location+"</location>" +
"<floors>"+floors+"</floors>"+
"<area>"+area+"</area>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</assets>";
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[7];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form139_delete_item(del_button);
$(form).off('submit');
});
$(form).on('submit',function(event)
{
event.preventDefault();
form139_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Supplier Profiling
* @formNo 140
* @param button
*/
function form140_create_item(form)
{
if(is_create_access('form140'))
{
var supplier=form.elements[0].value;
var asset_type=form.elements[1].value;
var desc=form.elements[2].value;
var location=form.elements[3].value;
var notes=form.elements[4].value;
var data_id=form.elements[5].value;
var last_updated=get_my_time();
var data_xml="<assets>" +
"<id>"+data_id+"</id>" +
"<type>"+asset_type+"</type>"+
"<description>"+desc+"</description>"+
"<owner>"+supplier+"</owner>" +
"<owner_type>supplier</owner_type>" +
"<location>"+location+"</location>"+
"<notes>"+notes+"</notes>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</assets>";
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[7];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form140_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form140_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Manufacturing Schedule
* @formNo 146
*/
function form146_create_item(form)
{
if(is_create_access('form146'))
{
var product=form.elements[0].value;
var batch=form.elements[1].value;
var quantity=form.elements[2].value;
var schedule=get_raw_time(form.elements[3].value);
var status=form.elements[4].value;
var data_id=form.elements[5].value;
var last_updated=get_my_time();
var data_xml="<manufacturing_schedule>" +
"<id>"+data_id+"</id>" +
"<product>"+product+"</product>" +
"<batch>"+batch+"</batch>" +
"<status>"+status+"</status>" +
"<schedule>"+schedule+"</schedule>" +
"<quantity>"+quantity+"</quantity>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</manufacturing_schedule>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>manufacturing_schedule</tablename>" +
"<link_to>form146</link_to>" +
"<title>Scheduled</title>" +
"<notes>Manufacturing of product "+product+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[7];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form146_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form146_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
function form150_post_feed()
{
if(is_create_access('form150'))
{
var form=document.getElementById('form150_master');
var title=form.elements[1].value;
var detail=form.elements[2].value;
var project_id=form.elements[3].value;
var owner=get_account_name();
var last_updated=get_my_time();
var data_id=vUtil.newKey();
var data_xml="<feeds>" +
"<id>"+data_id+"</id>" +
"<content_type>text</content_type>"+
"<content_title>"+title+"</content_title>" +
"<content_detail>"+detail+"</content_detail>" +
"<source>project</source>"+
"<source_id>"+project_id+"</source_id>"+
"<status>visible</status>" +
"<owner>"+owner+"</owner>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</feeds>";
create_simple(data_xml);
form.elements[1].value="";
form.elements[2].value="";
form.elements[3].value="";
var feed_content="<div class='feed_item'>"+
"<br><div class='feed_title'>"+title+
" <a class='small_cross_icon' onclick=\"delete_feed('"+data_id+"',$(this));\" title='Delete post'>✖</a></div>"+
"<br><u>"+owner+"</u>: <div class='feed_detail'>"+detail+"</div>"+
"<br><div id='form150_likes_"+data_id+"' class='feed_likes'>"+
"<img src='"+server_root+"/images/thumbs_up_line.png' class='thumbs_icon' onclick=\"like_feed('"+data_id+"',$(this))\" title='Like this post'> <b id='form150_likes_count_"+data_id+"'>0</b> likes"+
"</div>"+
"<br><div id='form150_comments_"+data_id+"' class='feed_comments'>"+
"<label><u>"+owner+"</u>: <textarea class='feed_comments' placeholder='comment..'></textarea></label>"+
"</div>"+
"</div>";
$('#form150_body').prepend(feed_content);
$('#form150_comments_'+data_id).find('label').find('textarea').on('keyup',function(e)
{
if (e.keyCode==13)
{
create_feed_comment(data_id,this);
}
});
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 151
* form Service dashboard - item
* @param button
*/
function form151_create_item(form)
{
if(is_create_access('form151'))
{
var master_fields=document.getElementById('form151_master');
var request_id=master_fields.elements[1].value;
var item=form.elements[0].value;
var quantity=form.elements[1].value;
var est_amount=form.elements[2].value;
var amount=form.elements[3].value;
var status=form.elements[4].value;
var data_id=form.elements[5].value;
var last_updated=get_my_time();
var data_xml="<service_request_items>" +
"<id>"+data_id+"</id>" +
"<request_id>"+request_id+"</request_id>"+
"<item_name>"+item+"</item_name>" +
"<est_amount>"+est_amount+"</est_amount>"+
"<amount>"+amount+"</amount>"+
"<quantity>"+quantity+"</quantity>" +
"<status>"+status+"</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</service_request_items>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>service_request_items</tablename>" +
"<link_to>form151</link_to>" +
"<title>Requested</title>" +
"<notes>Item "+item+" for SR# "+request_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[7];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form151_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form151_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
};
/**
* formNo 151
* form Service dashboard - expense
* @param button
*/
function form151_create_expense(form)
{
if(is_create_access('form151'))
{
var master_fields=document.getElementById('form151_master');
var request_id=master_fields.elements[1].value;
var person=form.elements[0].value;
var amount=form.elements[1].value;
var detail=form.elements[2].value;
var status=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_xml="<expenses>" +
"<id>"+data_id+"</id>" +
"<source_id>"+request_id+"</source_id>"+
"<source>service request</source>"+
"<person>"+person+"</person>"+
"<amount>"+amount+"</amount>"+
"<detail>"+detail+"</detail>" +
"<status>"+status+"</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</expenses>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>expenses</tablename>" +
"<link_to>form151</link_to>" +
"<title>Added</title>" +
"<notes>Expense of Rs. "+amount+" for SR# "+request_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form151_delete_expense(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form151_update_expense(form);
});
}
else
{
$("#modal2_link").click();
}
};
/**
* @form Prepare Quotation
* @formNo 153
* @param button
*/
function form153_create_item(form)
{
if(is_create_access('form153'))
{
var quot_id=document.getElementById("form153_master").elements['quot_id'].value;
var name=form.elements[0].value;
var description=form.elements[1].value;
var quantity=form.elements[2].value;
var unit=form.elements[3].value;
var price=form.elements[4].value;
var amount=form.elements[5].value;
var data_id=form.elements[6].value;
var save_button=form.elements[7];
var del_button=form.elements[8];
var type=form.elements[9];
var last_updated=get_my_time();
var data_xml="<quotation_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<description>"+description+"</description>"+
"<unit>"+unit+"</unit>" +
"<unit_price>"+price+"</unit_price>" +
"<quantity>"+quantity+"</quantity>" +
"<amount>"+amount+"</amount>" +
"<type>"+type+"</type>" +
"<quotation_id>"+quot_id+"</quotation_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</quotation_items>";
create_simple(data_xml);
for(var i=0;i<6;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form153_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Prepare Quotation
* @formNo 153
* @param button
*/
function form153_create_form()
{
if(is_create_access('form153'))
{
var form=document.getElementById("form153_master");
var customer=form.elements['customer'].value;
var quot_type=form.elements['type'].value;
var quot_date=get_raw_time(form.elements['date'].value);
var intro_notes=form.elements['notes'].value;
var quot_num=form.elements['quot_num'].value;
var save_button=form.elements['save'];
var data_id=form.elements['quot_id'].value;
var bt=get_session_var('title');
$('#form153_share').show();
$('#form153_share').click(function()
{
modal101_action('Quotation from '+bt+' - '+quot_num,customer,'customer',function (func)
{
print_form153(func);
});
});
var amount=0;
var discount=0;
var tax=0;
var tax_rate=0;
if(document.getElementById('form153_discount'))
{
discount=parseFloat(document.getElementById('form153_discount').value);
tax_rate=parseFloat(document.getElementById('form153_tax').value);
}
$("[id^='save_form153']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
amount+=vUtil.round(parseFloat(subform.elements[5].value),0);
});
var tax=vUtil.round((tax_rate*((amount-discount)/100)),0);
var total=vUtil.round(amount+tax-discount,0);
var last_updated=get_my_time();
var data_xml="<quotation>" +
"<id>"+data_id+"</id>" +
"<quot_num>"+quot_num+"</quot_num>" +
"<customer>"+customer+"</customer>" +
"<date>"+quot_date+"</date>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<billing_type>"+quot_type+"</billing_type>" +
"<discount>"+discount+"</discount>" +
"<tax>"+tax+"</tax>" +
"<tax_rate>"+tax_rate+"</tax_rate>" +
"<status>generated</status>"+
"<intro_notes>"+intro_notes+"</intro_notes>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</quotation>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>quotation</tablename>" +
"<link_to>form152</link_to>" +
"<title>Saved</title>" +
"<notes>Quotation # "+quot_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
var total_row="<tr><td colspan='2' data-th='Total'>Total</td>" +
"<td>Amount:</br>Discount: </br>Tax:@ <input type='number' value='"+tax_rate+"' title='specify tax rate' step='any' id='form153_tax' class='dblclick_editable'>%</br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"Rs. <input type='number' value='"+discount+"' step='any' id='form153_discount' class='dblclick_editable'></br>" +
"Rs. "+tax+" <br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form153_foot').html(total_row);
longPressEditable($('.dblclick_editable'));
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>quot_num</name>"+
"</user_preferences>";
get_single_column_data(function (num_ids)
{
if(num_ids.length>0)
{
var quot_num_array=quot_num.split("-");
var num_xml="<user_preferences>"+
"<id>"+num_ids[0]+"</id>"+
"<value>"+(parseInt(quot_num_array[1])+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
update_simple(num_xml);
}
},num_data);
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form153_update_form();
});
$("[id^='save_form153_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Bill(DLM)
* @formNo 154
* @param button
*/
function form154_create_product(form)
{
if(is_create_access('form154'))
{
var storage=document.getElementById("form154_master").elements['store'].value;
var bill_id=document.getElementById("form154_master").elements['bill_id'].value;
var name=form.elements[0].value;
var quantity=form.elements[1].value;
var price=form.elements[2].value;
//var tax=form.elements[3].value;
var amount=form.elements[3].value;
//var total=form.elements[5].value;
//var discount=form.elements[6].value;
var data_id=form.elements[4].value;
var save_button=form.elements[5];
var del_button=form.elements[6];
var unit=$('#form154_unit_'+data_id).html();
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+name+"</batch>" +
"<unit_price>"+price+"</unit_price>" +
"<quantity>"+quantity+"</quantity>" +
"<unit>"+unit+"</unit>"+
"<amount>"+amount+"</amount>" +
//"<total>"+total+"</total>" +
//"<discount>"+discount+"</discount>" +
"<type>bought</type>" +
//"<tax>"+tax+"</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
create_simple(data_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form154_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Bill(DLM)
* @formNo 154
* @param button
*/
function form154_create_service(form)
{
if(is_create_access('form154'))
{
var storage=document.getElementById("form154_master").elements['store'].value;
var bill_id=document.getElementById("form154_master").elements['bill_id'].value;
var name=form.elements[0].value;
var quantity=form.elements[1].value;
var price=form.elements[2].value;
//var tax=form.elements[3].value;
var amount=form.elements[3].value;
//var total=form.elements[5].value;
//var discount=form.elements[6].value;
var data_id=form.elements[4].value;
var save_button=form.elements[5];
var del_button=form.elements[6];
var unit=$('#form154_unit_'+data_id).html();
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<item_desc></item_desc>" +
"<batch>"+name+"</batch>" +
"<unit_price>"+price+"</unit_price>" +
"<quantity>"+quantity+"</quantity>" +
"<unit>"+unit+"</unit>"+
"<amount>"+amount+"</amount>" +
//"<total>"+total+"</total>" +
//"<discount>"+discount+"</discount>" +
"<type>bought</type>" +
//"<tax>"+tax+"</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form154_delete_service_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Bill(DLM)
* @formNo 154
* @param button
*/
function form154_create_hiring_item(form)
{
if(is_create_access('form154'))
{
var storage=document.getElementById("form154_master").elements['store'].value;
var bill_id=document.getElementById("form154_master").elements['bill_id'].value;
var name=form.elements[0].value;
var fresh='no';
if(form.elements[1].checked)
{
fresh='yes';
}
var quantity=form.elements[2].value;
var from_date=get_raw_time(form.elements[3].value);
var to_date=get_raw_time(form.elements[4].value);
var price=form.elements[6].value;
//var tax=form.elements[7].value;
var amount=form.elements[7].value;
//var total=form.elements[9].value;
//var discount=form.elements[10].value;
var data_id=form.elements[8].value;
var save_button=form.elements[9];
var del_button=form.elements[10];
var unit=$('#form154_unit_'+data_id).html();
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+name+"</batch>" +
"<unit_price>"+price+"</unit_price>" +
"<quantity>"+quantity+"</quantity>" +
"<unit>"+unit+"</unit>"+
"<amount>"+amount+"</amount>" +
//"<total>"+total+"</total>" +
//"<discount>"+discount+"</discount>" +
//"<tax>"+tax+"</tax>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<storage>"+storage+"</storage>"+
"<from_date>"+from_date+"</from_date>"+
"<to_date>"+to_date+"</to_date>"+
"<last_updated>"+last_updated+"</last_updated>" +
"<hired>yes</hired>"+
"<fresh>"+fresh+"</fresh>"+
"</bill_items>";
create_simple(data_xml);
for(var i=0;i<8;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form154_delete_hiring_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create bill(DLM)
* @formNo 154
* @param button
*/
function form154_create_form()
{
if(is_create_access('form154'))
{
var form=document.getElementById("form154_master");
var customer=form.elements['customer'].value;
var bill_type=form.elements['bill_type'].value;
var tax_type=form.elements['tax_type'].value;
var storage=form.elements['store'].value;
var bill_date=get_raw_time(form.elements['date'].value);
var narration=form.elements['narration'].value;
var print_1_job='no';
var cform='no';
var tax_type=form.elements['tax_type'].value;
var tax_text="VAT";
if(tax_type=='CST' || tax_type=='Retail Central')
{
tax_text="CST";
}
if(form.elements['job'].checked)
print_1_job='yes';
var bill_num=form.elements['bill_num'].value;
if(form.elements['cform'].checked)
cform='yes';
var hiring=false;
if(bill_type=='Hiring')
hiring=true;
var amount=0;
var discount=0;
var tax_rate=0;
var cartage=0;
if(document.getElementById('form154_discount'))
{
discount=parseFloat(document.getElementById('form154_discount').value);
tax_rate=parseFloat(document.getElementById('form154_tax').value);
cartage=parseFloat(document.getElementById('form154_cartage').value);
}
$("[id^='save_form154']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(hiring)
{
//tax+=parseFloat(subform.elements[7].value);
if(isNaN(parseFloat(subform.elements[7].value)))
amount+=0;
else
amount+=Math.round(parseFloat(subform.elements[7].value));
//total+=Math.round(parseFloat(subform.elements[9].value));
//discount+=parseFloat(subform.elements[10].value);
}
else if(bill_type=='Installation' || bill_type=='Repair')
{
//tax+=parseFloat(subform.elements[3].value);
if(isNaN(parseFloat(subform.elements[3].value)))
amount+=0;
else
amount+=Math.round(parseFloat(subform.elements[3].value));
//total+=Math.round(parseFloat(subform.elements[5].value));
//discount+=parseFloat(subform.elements[6].value);
}
else
{
//tax+=parseFloat(subform.elements[3].value);
if(isNaN(parseFloat(subform.elements[3].value)))
amount+=0;
else
amount+=Math.round(parseFloat(subform.elements[3].value));
//total+=Math.round(parseFloat(subform.elements[5].value));
//discount+=parseFloat(subform.elements[6].value);
}
});
var tax=Math.round((tax_rate*((amount-discount)/100)));
var total=Math.round(amount+tax-discount+cartage).toFixed(2);
form.elements['bill_total'].value=total;
var data_id=form.elements['bill_id'].value;
var transaction_id=form.elements['t_id'].value;
var save_button=form.elements['save'];
var last_updated=get_my_time();
var data_xml="<bills>" +
"<id>"+data_id+"</id>" +
"<bill_num>"+bill_num+"</bill_num>"+
"<customer_name>"+customer+"</customer_name>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<billing_type>"+bill_type+"</billing_type>" +
"<tax_type>"+tax_type+"</tax_type>" +
"<discount>"+discount+"</discount>" +
"<cartage>0</cartage>" +
"<tax>"+tax+"</tax>" +
"<tax_rate>"+tax_rate+"</tax_rate>"+
"<transaction_id>"+transaction_id+"</transaction_id>" +
"<storage>"+storage+"</storage>"+
"<print_1_job>"+print_1_job+"</print_1_job>"+
"<cform>"+cform+"</cform>"+
"<notes>"+narration+"</notes>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form92</link_to>" +
"<title>Saved</title>" +
"<notes>Bill no "+bill_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+transaction_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+tax+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>pending</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>"+total+"</paid_amount>" +
"<acc_name>"+customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+bill_num+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>"+bill_type+"_bill_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(bill_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
if(is_online())
{
server_update_simple(num_xml);
}
else
{
local_update_simple(num_xml);
}
}
},num_data);
if(is_online())
{
server_create_row(data_xml,activity_xml);
server_create_simple(transaction_xml);
server_create_simple(pt_xml);
server_create_simple_func(payment_xml,function()
{
//modal26_action(pt_tran_id);
});
}
else
{
local_create_row(data_xml,activity_xml);
local_create_simple(transaction_xml);
local_create_simple(pt_xml);
local_create_simple_func(payment_xml,function()
{
//modal26_action(pt_tran_id);
});
}
var total_row="<tr><td colspan='3' data-th='Total'>Total</td>" +
"<td>Amount:<disc><br>Discount: </disc><br>"+tax_text+":@ <input type='number' value='"+tax_rate+"' step='any' id='form154_tax' class='dblclick_editable'>%<br>Cartage: <br>Total: </td>" +
"<td>Rs. "+amount.toFixed(2)+"</br>" +
"<disc_amount>Rs. <input type='number' value='"+discount.toFixed(2)+"' step='any' id='form154_discount' class='dblclick_editable'></br></disc_amount>" +
"Rs. "+tax.toFixed(2)+"<br>" +
"Rs. <input type='number' value='0.00' step='any' id='form154_cartage' class='dblclick_editable'></br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
if(hiring)
{
total_row="<tr><td colspan='4' data-th='Total'>Total</td>" +
"<td>Amount:<disc><br>Discount: </disc><br>Service Tax:@ <input type='number' value='"+tax_rate+"' step='any' id='form154_tax' class='dblclick_editable'>% <br>Cartage: <br>Total: </td>" +
"<td>Rs. "+amount.toFixed(2)+"</br>" +
"<disc_amount>Rs. <input type='number' value='"+discount.toFixed(2)+"' step='any' id='form154_discount' class='dblclick_editable'><br><disc_amount>" +
"Rs. "+tax.toFixed(2)+"<br>" +
"Rs. <input type='number' value='0.00' step='any' id='form154_cartage' class='dblclick_editable'></br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
}
else if(bill_type=='Service')
{
total_row="<tr><td colspan='3' data-th='Total'>Total</td>" +
"<td>Amount:<disc><br>Discount: </disc><br>Service Tax:@ <input type='number' value='"+tax_rate+"' step='any' id='form154_tax' class='dblclick_editable'>%<br>Cartage: <br>Total: </td>" +
"<td>Rs. "+amount.toFixed(2)+"</br>" +
"<disc_amount>Rs. <input type='number' value='"+discount.toFixed(2)+"' step='any' id='form154_discount' class='dblclick_editable'></br></disc_amount>" +
"Rs. "+tax.toFixed(2)+" <br>" +
"Rs. <input type='number' value='0.00' step='any' id='form154_cartage' class='dblclick_editable'></br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
}
$('#form154_foot').html(total_row);
longPressEditable($('.dblclick_editable'));
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form154_update_form();
});
$("[id^='save_form154_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Store Placement (DLM)
* @param button
*/
function form156_create_item(form)
{
if(is_create_access('form156'))
{
var product_name=form.elements[0].value;
var name=form.elements[1].value;
var data_id=form.elements[3].value;
var last_updated=get_my_time();
var data_xml="<area_utilization>" +
"<id>"+data_id+"</id>" +
"<item_name>"+product_name+"</item_name>" +
"<batch>"+product_name+"</batch>" +
"<name>"+name+"</name>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</area_utilization>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>area_utilization</tablename>" +
"<link_to>form156</link_to>" +
"<title>Added</title>" +
"<notes>Item "+product_name+" to storage area "+name+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var save_button=form.elements[4];
$(save_button).hide();
var del_button=form.elements[5];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form156_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Store Movement (DLM)
* @param button
*/
function form157_create_item(form)
{
if(is_create_access('form157'))
{
var product_name=form.elements[0].value;
var quantity=form.elements[1].value;
var source=form.elements[2].value;
var target=form.elements[3].value;
var status=form.elements[4].value;
var data_id=form.elements[5].value;
var receiver=form.elements[6].value;
//console.log(receiver);
var last_updated=get_my_time();
var data_xml="<store_movement>" +
"<id>"+data_id+"</id>" +
"<item_name>"+product_name+"</item_name>" +
"<batch>"+product_name+"</batch>" +
"<quantity>"+quantity+"</quantity>" +
"<source>"+source+"</source>"+
"<target>"+target+"</target>"+
"<status>"+status+"</status>"+
"<dispatcher>"+get_account_name()+"</dispatcher>"+
"<receiver>"+receiver+"</receiver>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</store_movement>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>store_movement</tablename>" +
"<link_to>form157</link_to>" +
"<title>New</title>" +
"<notes>Store movement initiated for item "+product_name+" from storage area "+source+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<6;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var save_button=form.elements[7];
$(save_button).hide();
var del_button=form.elements[8];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form157_delete_item(del_button);
});
var dispatch_button=form.elements[9];
$(dispatch_button).show();
///////////adding store placement////////
var storage_data="<area_utilization>" +
"<id></id>" +
"<name exact='yes'>"+target+"</name>" +
"<item_name exact='yes'>"+product_name+"</item_name>" +
"</area_utilization>";
fetch_requested_data('',storage_data,function(placements)
{
if(placements.length===0 && target!="")
{
var storage_xml="<area_utilization>" +
"<id>"+vUtil.newKey()+"</id>" +
"<name>"+target+"</name>" +
"<item_name>"+product_name+"</item_name>" +
"<batch>"+product_name+"</batch>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</area_utilization>";
if(is_online())
{
server_create_simple(storage_xml);
}
else
{
local_create_simple(storage_xml);
}
}
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Enter Purchase Bill (DLM)
* @formNo 158
* @param button
*/
function form158_create_item(form)
{
if(is_create_access('form158'))
{
var master_form=document.getElementById("form158_master");
var imported=master_form.elements['imported'].checked;
var bill_id=master_form.elements['bill_id'].value;
var name=form.elements[0].value;
var quantity=form.elements[1].value;
var price=form.elements[2].value;
var amount=form.elements[3].value;
//var amount=total-tax;
var storage=form.elements[4].value;
var data_id=form.elements[5].value;
var save_button=form.elements[6];
var del_button=form.elements[7];
var last_updated=get_my_time();
var unit=$('#form158_unit_'+data_id).html();
var data_xml="<supplier_bill_items>" +
"<id>"+data_id+"</id>" +
"<product_name>"+name+"</product_name>" +
"<batch>"+name+"</batch>" +
"<quantity>"+quantity+"</quantity>" +
"<unit>"+unit+"</unit>"+
//"<total>"+total+"</total>" +
//"<tax>"+tax+"</tax>" +
"<amount>"+amount+"</amount>" +
"<unit_price>"+price+"</unit_price>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<storage>"+storage+"</storage>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_bill_items>";
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form158_delete_item(del_button);
});
$(save_button).off('click');
///////////adding store placement////////
var storage_data="<area_utilization>" +
"<id></id>" +
"<name exact='yes'>"+storage+"</name>" +
"<item_name exact='yes'>"+name+"</item_name>" +
"<batch exact='yes'>"+name+"</batch>" +
"</area_utilization>";
fetch_requested_data('',storage_data,function(placements)
{
if(placements.length===0)
{
var storage_xml="<area_utilization>" +
"<id>"+vUtil.newKey()+"</id>" +
"<name>"+storage+"</name>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+name+"</batch>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</area_utilization>";
if(is_online())
{
server_create_simple(storage_xml);
}
else
{
local_create_simple(storage_xml);
}
}
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Enter Purchase Bill (DLM)
* @param button
*/
function form158_create_form()
{
if(is_create_access('form158'))
{
var form=document.getElementById("form158_master");
var supplier=form.elements['supplier'].value;
var bill_id=form.elements['bill_num'].value;
var bill_date=get_raw_time(form.elements['date'].value);
var imported='no';
var notes='Local Purchase';
if(form.elements['imported'].checked)
{
imported='yes';
notes='Imported';
}
var amount=0;
$("[id^='save_form158']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(isNaN(parseFloat(subform.elements[3].value)))
amount+=0;
else
amount+=parseFloat(subform.elements[3].value);
});
var discount=0;
var tax_rate=0;
var cartage=0;
if(document.getElementById('form158_discount'))
{
discount=parseFloat(document.getElementById('form158_discount').value);
tax_rate=parseFloat(document.getElementById('form158_tax').value);
cartage=parseFloat(document.getElementById('form158_cartage').value);
}
var tax=Math.round((tax_rate*((amount-discount)/100)));
var total=Math.round(amount+tax-discount+cartage);
var total_row="<tr><td colspan='2' data-th='Total'>Total</td>" +
"<td>Amount:<br>Discount: <br>Tax:@ <input type='number' value='"+tax_rate+"' step='any' id='form158_tax' class='dblclick_editable'>%<br>Cartage: <br>Total: </td>" +
"<td>Rs. "+Math.round(amount)+"</br>" +
"<disc_amount>Rs. <input type='number' value='"+Math.round(discount)+"' step='any' id='form158_discount' class='dblclick_editable'><br></disc_amount>" +
"Rs. "+tax+" <br>" +
"Rs. <input type='number' value='"+Math.round(cartage)+"' step='any' id='form158_cartage' class='dblclick_editable'><br>" +
"Rs. "+Math.round(total)+"</td>" +
"<td></td>" +
"</tr>";
$('#form158_foot').html(total_row);
longPressEditable($('.dblclick_editable'));
var data_id=form.elements['bill_id'].value;
var transaction_id=form.elements['t_id'].value;
var save_button=form.elements['save'];
var last_updated=get_my_time();
var data_xml="<supplier_bills>" +
"<id>"+data_id+"</id>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<supplier>"+supplier+"</supplier>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<total>"+total+"</total>" +
"<discount>"+discount+"</discount>" +
"<amount>"+amount+"</amount>" +
"<cartage>"+cartage+"</cartage>"+
"<tax>"+tax+"</tax>" +
"<tax_rate>"+tax_rate+"</tax_rate>"+
"<transaction_id>"+transaction_id+"</transaction_id>" +
"<imported>"+imported+"</imported>" +
"<notes>"+notes+"</notes>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>supplier_bills</tablename>" +
"<link_to>form53</link_to>" +
"<title>Saved</title>" +
"<notes>Supplier Bill no "+bill_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+transaction_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+supplier+"</giver>" +
"<tax>"+(-tax)+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>pending</status>" +
"<type>paid</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>0</paid_amount>" +
"<acc_name>"+supplier+"</acc_name>" +
"<due_date>"+get_debit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>purchase bill</source>" +
"<source_info>"+bill_id+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+supplier+"</receiver>" +
"<giver>master</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
server_create_simple(transaction_xml);
server_create_simple(pt_xml);
server_create_simple_func(payment_xml,function()
{
//modal28_action(pt_tran_id);
});
}
else
{
local_create_row(data_xml,activity_xml);
local_create_simple(transaction_xml);
local_create_simple(pt_xml);
local_create_simple_func(payment_xml,function()
{
//modal28_action(pt_tran_id);
});
}
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form158_update_form();
});
$("[id^='save_form158_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Checklist Items
* @formNo 161
* @param button
*/
function form161_create_item(form)
{
if(is_create_access('form161'))
{
var cp=form.elements[0].value;
var desired_result=form.elements[1].value;
var status=form.elements[2].value;
var data_id=form.elements[3].value;
var save_button=form.elements[4];
var del_button=form.elements[5];
var last_updated=get_my_time();
var data_xml="<checklist_items>" +
"<id>"+data_id+"</id>" +
"<checkpoint unique='yes'>"+cp+"</checkpoint>" +
"<desired_result>"+desired_result+"</desired_result>" +
"<status>"+status+"</status>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</checklist_items>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>checklist_items</tablename>" +
"<link_to>form161</link_to>" +
"<title>Added</title>" +
"<notes>Item Checkpoint "+cp+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<3;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form161_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form161_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Product Checklist
* @formNo 162
* @param button
*/
function form162_create_item(form)
{
if(is_create_access('form162'))
{
var item=form.elements[0].value;
var cp=form.elements[1].value;
var desired_result=form.elements[2].value;
var data_id=form.elements[3].value;
var save_button=form.elements[4];
var del_button=form.elements[5];
var last_updated=get_my_time();
var data_xml="<checklist_mapping>" +
"<id>"+data_id+"</id>" +
"<item>"+item+"</item>"+
"<checkpoint>"+cp+"</checkpoint>" +
"<desired_result>"+desired_result+"</desired_result>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</checklist_mapping>";
if(is_online())
{
server_create_simple(data_xml);
}
else
{
local_create_simple(data_xml);
}
for(var i=0;i<3;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form162_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form162_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Storage Structure
* @formNo 167
* @param button
*/
function form167_create_item(form)
{
if(is_create_access('form167'))
{
var name=form.elements[0].value;
var parent=form.elements[1].value;
var length=form.elements[2].value;
var breadth=form.elements[3].value;
var height=form.elements[4].value;
var unit=form.elements[5].value;
var data_id=form.elements[6].value;
var save_button=form.elements[7];
var del_button=form.elements[8];
var last_updated=get_my_time();
var data_xml="<storage_structure>" +
"<id>"+data_id+"</id>" +
"<name>"+name+"</name>" +
"<parent>"+parent+"</parent>" +
"<len>"+length+"</len>" +
"<breadth>"+breadth+"</breadth>" +
"<height>"+height+"</height>" +
"<unit>"+unit+"</unit>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</storage_structure>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>storage_structure</tablename>" +
"<link_to>form167</link_to>" +
"<title>Added</title>" +
"<notes>Storage type of "+name+" to structure</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
if(is_online())
{
server_create_row(data_xml,activity_xml);
}
else
{
local_create_row(data_xml,activity_xml);
}
for(var i=0;i<6;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form167_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form167_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Manage Channels
* @formNo 171
*/
function form171_create_item(form)
{
if(is_create_access('form171'))
{
show_loader();
var name=form.elements[0].value;
var details=form.elements[1].value;
var dead_weight_factor=form.elements[2].value;
var data_id=form.elements[3].value;
var del_button=form.elements[5];
var last_updated=get_my_time();
var data_xml="<sale_channels>" +
"<id>"+data_id+"</id>" +
"<name unique='yes'>"+name+"</name>" +
"<details>"+details+"</details>" +
"<dead_weight_factor>"+dead_weight_factor+"</dead_weight_factor>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</sale_channels>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>sale_channels</tablename>" +
"<link_to>form171</link_to>" +
"<title>Added</title>" +
"<notes>Sale channel "+name+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var pickup_xml="<pickup_charges>" +
"<id>"+vUtil.newKey()+"</id>" +
"<channel>"+name+"</channel>" +
"<pincode>all</pincode>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</pickup_charges>";
var time_xml="<user_preferences>" +
"<id>"+data_id+"</id>" +
"<name unique='yes'>"+name+"_order_time_limit</name>" +
"<display_name>Sale order time limit for "+name+" (in hours)</display_name>"+
"<value>48</value>" +
"<status>active</status>" +
"<type>accounting</type>"+
"<shortcut></shortcut>"+
"<sync>checked</sync>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</user_preferences>";
create_row(data_xml,activity_xml);
create_simple(pickup_xml);
create_simple(time_xml);
var product_data="<product_master>" +
"<id></id>" +
"<name></name>" +
"<description></description>"+
"</product_master>";
fetch_requested_data('',product_data,function(items)
{
var sku_mapping_xml="<sku_mapping>";
var cat_sku_mapping_xml="<category_sku_mapping>";
var channel_price_xml="<channel_prices>";
var id=parseFloat(vUtil.newKey());
var counter=0;
var last_updated=get_my_time();
items.forEach(function(item)
{
if(counter==500)
{
counter=0;
sku_mapping_xml+="</sku_mapping><separator></separator><sku_mapping>";
cat_sku_mapping_xml+="</category_sku_mapping><separator></separator><category_sku_mapping>";
channel_price_xml+="</channel_prices><separator></separator><channel_prices>";
}
sku_mapping_xml+="<row>" +
"<id>"+id+"</id>" +
"<channel>"+name+"</channel>"+
"<system_sku>"+item.name+"</system_sku>"+
"<item_desc>"+item.description+"</item_desc>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</row>";
cat_sku_mapping_xml+="<row>" +
"<id>"+id+"</id>" +
"<channel>"+name+"</channel>" +
"<sku>"+item.name+"</sku>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</row>";
channel_price_xml+="<row>" +
"<id>"+id+"</id>" +
"<channel>"+name+"</channel>" +
"<item>"+item.name+"</item>" +
//"<latest>yes</latest>"+
"<from_time>"+last_updated+"</from_time>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</row>";
id+=1;
counter+=1;
});
sku_mapping_xml+="</sku_mapping>";
cat_sku_mapping_xml+="</category_sku_mapping>";
channel_price_xml+="</channel_prices>";
create_batch(sku_mapping_xml);
create_batch(cat_sku_mapping_xml);
create_batch(channel_price_xml);
});
for(var i=0;i<3;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form171_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form171_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Pricing Sheet
* @formNo 172
*/
function form172_create_item(fields)
{
if(is_create_access('form172'))
{
var channel=fields.elements[0].value;
var sku=fields.elements[1].value;
var from_time=get_raw_time(fields.elements[2].value);
var mrp=fields.elements[3].value;
var discount_customer=fields.elements[4].value;
var sale_price=fields.elements[5].value;
var freight=fields.elements[6].value;
var commission_percentage=fields.elements[7].value;
var commission_charges=fields.elements[8].value;
var pickup=fields.elements[9].value;
var others=fields.elements[10].value;
var service_tax=fields.elements[11].value;
var total_charges=fields.elements[12].value;
var cost_price=fields.elements[13].value;
var profit=fields.elements[14].value;
var profit_mrp=fields.elements[15].value;
var profit_sp=fields.elements[16].value;
var data_id=fields.elements[17].value;
var del_button=fields.elements[19];
var last_updated=get_my_time();
var data_xml="<channel_prices>" +
"<id>"+data_id+"</id>" +
"<channel>"+channel+"</channel>" +
"<item>"+sku+"</item>" +
"<sale_price>"+sale_price+"</sale_price>"+
"<cost_price>"+cost_price+"</cost_price>"+
"<mrp>"+mrp+"</mrp>"+
"<freight>"+freight+"</freight>"+
"<pickup_charges>"+pickup+"</pickup_charges>"+
"<discount_customer>"+discount_customer+"</discount_customer>"+
"<gateway_charges>"+others+"</gateway_charges>"+
"<channel_commission_percentage>"+commission_percentage+"</channel_commission_percentage>"+
"<channel_commission>"+commission_charges+"</channel_commission>"+
"<total_charges>"+total_charges+"</total_charges>"+
"<service_tax>"+service_tax+"</service_tax>"+
"<total_payable>"+(parseFloat(total_charges))+"</total_payable>"+
"<total_receivable>"+(parseFloat(sale_price)+parseFloat(freight)-parseFloat(total_charges))+"</total_receivable>"+
"<profit_mrp>"+profit_mrp+"</profit_mrp>"+
"<profit_sp>"+profit_sp+"</profit_sp>"+
"<profit>"+profit+"</profit>"+
"<from_time>"+from_time+"</from_time>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</channel_prices>";
create_simple(data_xml);
for(var i=0;i<15;i++)
{
$(fields.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form172_delete_item(del_button);
});
$(fields).off('submit');
$(fields).on('submit',function(event)
{
event.preventDefault();
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form SKU mappings
* @formNo 173
*/
function form173_create_item(form)
{
if(is_create_access('form173'))
{
var channel=form.elements[0].value;
var channel_sku=form.elements[1].value;
var vendor_sku=form.elements[2].value;
var system_sku=form.elements[3].value;
var description=form.elements[4].value;
var data_id=form.elements[5].value;
var del_button=form.elements[7];
var last_updated=get_my_time();
var data_xml="<sku_mapping>" +
"<id>"+data_id+"</id>" +
"<channel>"+channel+"</channel>" +
"<item_desc>"+description+"</item_desc>" +
"<channel_sku>"+channel_sku+"</channel_sku>" +
"<channel_system_sku>"+vendor_sku+"</channel_system_sku>" +
"<system_sku>"+system_sku+"</system_sku>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</sku_mapping>";
create_simple(data_xml);
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form173_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form173_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Pickup Charges
* @formNo 174
*/
function form174_create_item(form)
{
if(is_create_access('form174'))
{
var channel=form.elements[0].value;
var pincode=form.elements[1].value;
var minimum=form.elements[2].value;
var maximum=form.elements[3].value;
var rate=form.elements[4].value;
var data_id=form.elements[5].value;
var del_button=form.elements[7];
var last_updated=get_my_time();
var data_xml="<pickup_charges>" +
"<id>"+data_id+"</id>" +
"<channel>"+channel+"</channel>" +
"<pincode>"+pincode+"</pincode>" +
"<min_charges>"+minimum+"</min_charges>" +
"<max_charges>"+maximum+"</max_charges>" +
"<rate>"+rate+"</rate>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</pickup_charges>";
create_simple(data_xml);
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form174_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form174_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Channel Category
* @formNo 175
*/
function form175_create_item(form)
{
if(is_create_access('form175'))
{
var channel=form.elements[0].value;
var type=form.elements[1].value;
var name=form.elements[2].value;
var parent=form.elements[3].value;
var commission=form.elements[4].value;
var data_id=form.elements[5].value;
var del_button=form.elements[7];
var last_updated=get_my_time();
var data_xml="<channel_category>" +
"<id>"+data_id+"</id>" +
"<channel>"+channel+"</channel>" +
"<type>"+type+"</type>" +
"<name>"+name+"</name>" +
"<parent>"+parent+"</parent>" +
"<commission>"+commission+"</commission>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</channel_category>";
create_simple(data_xml);
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form175_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form175_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Category Item mapping
* @formNo 176
* @param button
*/
function form176_create_item(form)
{
if(is_create_access('form176'))
{
var channel=form.elements[0].value;
var type=form.elements[1].value;
var category=form.elements[2].value;
var item=form.elements[3].value;
var desc=form.elements[4].value;
var data_id=form.elements[5].value;
var last_updated=get_my_time();
var data_xml="<category_sku_mapping>" +
"<id>"+data_id+"</id>" +
"<channel>"+channel+"</channel>" +
"<cat_type>"+type+"</cat_type>" +
"<cat_name>"+category+"</cat_name>" +
"<sku>"+item+"</sku>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</category_sku_mapping>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>category_sku_mapping</tablename>" +
"<link_to>form176</link_to>" +
"<title>Mapped</title>" +
"<notes>Item "+item+" to category "+category+" for channel "+channel+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form176_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Prioritization Parameters
* @formNo 177
*/
function form177_create_item(form)
{
if(is_create_access('form177'))
{
show_loader();
var type=form.elements[0].value;
var name=form.elements[1].value;
var values=form.elements[2].value;
var threshold=form.elements[3].value;
var data_id=form.elements[4].value;
var del_button=form.elements[6];
var last_updated=get_my_time();
var data_xml="<prioritization_parameters>" +
"<id>"+data_id+"</id>" +
"<type>"+type+"</type>" +
"<name>"+name+"</name>" +
"<values>"+values+"</values>" +
"<threshold>"+threshold+"</threshold>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</prioritization_parameters>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>prioritization_parameters</tablename>" +
"<link_to>form177</link_to>" +
"<title>Added</title>" +
"<notes>"+name+" parameter for prioritization of "+type+"s</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form177_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form177_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Production Steps
* @formNo 184
*/
function form184_create_item(form)
{
if(is_create_access('form184'))
{
show_loader();
var order_no=form.elements[0].value;
var name=form.elements[1].value;
var time=form.elements[2].value;
var assignee=form.elements[3].value;
var details=form.elements[4].value;
var type=form.elements[5].value;
var status=form.elements[6].value;
var data_id=form.elements[7].value;
var del_button=form.elements[9];
var last_updated=get_my_time();
var data_xml="<business_processes>" +
"<id>"+data_id+"</id>" +
"<order_no>"+order_no+"</order_no>" +
"<name>"+name+"</name>" +
"<details>"+details+"</details>" +
"<time_estimate>"+time+"</time_estimate>"+
"<default_assignee>"+assignee+"</default_assignee>"+
"<type>"+type+"</type>"+
"<status>"+status+"</status>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</business_processes>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>business_processes</tablename>" +
"<link_to>form184</link_to>" +
"<title>Added</title>" +
"<notes>"+name+" to production process steps</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<7;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form184_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form184_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Testing Steps
* @formNo 187
*/
function form187_create_item(form)
{
if(is_create_access('form187'))
{
show_loader();
var order_no=form.elements[0].value;
var name=form.elements[1].value;
var time=form.elements[2].value;
var assignee=form.elements[3].value;
var details=form.elements[4].value;
var status=form.elements[5].value;
var data_id=form.elements[6].value;
var del_button=form.elements[8];
var last_updated=get_my_time();
var data_xml="<business_processes>" +
"<id>"+data_id+"</id>" +
"<order_no>"+order_no+"</order_no>" +
"<name>"+name+"</name>" +
"<details>"+details+"</details>" +
"<time_estimate>"+time+"</time_estimate>"+
"<default_assignee>"+assignee+"</default_assignee>"+
"<type>testing</type>"+
"<status>"+status+"</status>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</business_processes>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>business_processes</tablename>" +
"<link_to>form187</link_to>" +
"<title>Added</title>" +
"<notes>"+name+" to testing process steps</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<6;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form187_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form187_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Enter Purchase Bill (Laundry)
* @formNo 192
* @param button
*/
function form192_create_item(form)
{
if(is_create_access('form192'))
{
var master_form=document.getElementById("form192_master");
var bill_id=master_form.elements[5].value;
var name=form.elements[0].value;
var quantity=form.elements[1].value;
var price=form.elements[2].value;
var amount=form.elements[3].value;
var tax=form.elements[4].value;
var total=form.elements[5].value;
var data_id=form.elements[6].value;
var save_button=form.elements[7];
var del_button=form.elements[8];
var last_updated=get_my_time();
var data_xml="<supplier_bill_items>" +
"<id>"+data_id+"</id>" +
"<product_name>"+name+"</product_name>" +
"<batch>"+name+"</batch>" +
"<quantity>"+quantity+"</quantity>" +
"<total>"+total+"</total>" +
"<tax>"+tax+"</tax>" +
"<amount>"+amount+"</amount>" +
"<unit_price>"+price+"</unit_price>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_bill_items>";
create_simple(data_xml);
for(var i=0;i<6;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form192_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Enter Purchase Bill (Laundry)
* @param button
*/
function form192_create_form()
{
if(is_create_access('form192'))
{
var form=document.getElementById("form192_master");
var supplier=form.elements[1].value;
var bill_id=form.elements[2].value;
var bill_date=get_raw_time(form.elements[3].value);
var entry_date=get_raw_time(form.elements[4].value);
var total=0;
var tax=0;
var amount=0;
$("[id^='save_form192']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
total+=parseFloat(subform.elements[5].value);
tax+=parseFloat(subform.elements[4].value);
});
var discount=0;
amount=total-tax;
var total_row="<tr><td colspan='2' data-th='Total'>Total</td>" +
"<td>Amount:</br>Discount: </br>Tax: </br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"Rs. "+discount+"</br>" +
"Rs. "+tax+"</br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form192_foot').html(total_row);
var data_id=form.elements[5].value;
var transaction_id=form.elements[6].value;
var save_button=form.elements[7];
var last_updated=get_my_time();
var data_xml="<supplier_bills>" +
"<id>"+data_id+"</id>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<supplier>"+supplier+"</supplier>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<entry_date>"+entry_date+"</entry_date>" +
"<total>"+total+"</total>" +
"<discount>"+discount+"</discount>" +
"<amount>"+amount+"</amount>" +
"<tax>"+tax+"</tax>" +
"<transaction_id>"+transaction_id+"</transaction_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>supplier_bills</tablename>" +
"<link_to>form53</link_to>" +
"<title>Saved</title>" +
"<notes>Supplier Bill no "+bill_id+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+transaction_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+supplier+"</giver>" +
"<tax>"+(-tax)+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>pending</status>" +
"<type>paid</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>0</paid_amount>" +
"<acc_name>"+supplier+"</acc_name>" +
"<due_date>"+get_debit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>purchase bill</source>" +
"<source_info>"+bill_id+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+supplier+"</receiver>" +
"<giver>master</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
create_row(data_xml,activity_xml);
create_simple(transaction_xml);
create_simple(pt_xml);
create_simple_func(payment_xml,function()
{
modal28_action(pt_tran_id);
});
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form192_update_form();
});
$("[id^='save_form192_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Treatment plan
* @formNo 209
* @param button
*/
function form209_create_item(form)
{
if(is_create_access('form209'))
{
var master_form=document.getElementById("form209_master");
var plan_id=master_form.elements['plan_id'].value;
var order=form.elements[0].value;
var item=form.elements[1].value;
var details=form.elements[2].value;
var from=get_raw_time(form.elements[4].value);
var to=get_raw_time(form.elements[5].value);
var status=form.elements[6].value;
var data_id=form.elements[7].value;
var save_button=form.elements[8];
var del_button=form.elements[9];
var last_updated=get_my_time();
var data_xml="<treatment_plan_items>" +
"<id>"+data_id+"</id>" +
"<order_no>"+order+"</order_no>" +
"<item>"+item+"</item>" +
"<details>"+details+"</details>" +
"<from_time>"+from+"</from_time>" +
"<to_time>"+to+"</to_time>" +
"<status>"+status+"</status>" +
"<plan_id>"+plan_id+"</plan_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</treatment_plan_items>";
create_simple(data_xml);
for(var i=0;i<7;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form209_delete_item(del_button);
});
$(save_button).off('click');
$(save_button).on('click',function ()
{
form209_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create production plan
* @param button
*/
function form209_create_form()
{
if(is_create_access('form209'))
{
show_loader();
var form=document.getElementById("form209_master");
var num=form.elements['num'].value;
var customer=form.elements['customer'].value;
var start_date=get_raw_time(form.elements['date'].value);
var status=form.elements['status'].value;
var data_id=form.elements['plan_id'].value;
var save_button=form.elements['save'];
var last_updated=get_my_time();
var data_xml="<treatment_plans>" +
"<id>"+data_id+"</id>" +
"<plan_num>"+num+"</plan_num>" +
"<customer>"+customer+"</customer>" +
"<start_date>"+start_date+"</start_date>" +
"<status>"+status+"</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</treatment_plans>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>treatment_plans</tablename>" +
"<link_to>form208</link_to>" +
"<title>Saved</title>" +
"<notes>Treatment plan "+num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form209_update_form();
});
$('#form209_share').show();
$('#form209_share').click(function()
{
modal101_action('Treatment Plan',customer,'customer',function (func)
{
print_form209(func);
});
});
$("[id^='save_form209_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 200
* form Create Manifest
* @param button
*/
function form215_create_item(form)
{
//console.log('form215_create_form');
if(is_create_access('form215'))
{
var drs_num=document.getElementById('form215_master').elements['man_num'].value;
var drs_id=document.getElementById('form215_master').elements['id'].value;
var data_id=form.elements[4].value;
var save_button=form.elements[5];
var del_button=form.elements[6];
var last_updated=get_my_time();
var data_xml="<bills>" +
"<id>"+data_id+"</id>" +
"<manifest_num>"+drs_num+"</manifest_num>"+
"<manifest_id>"+drs_id+"</manifest_id>"+
"<status>dispatched</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bills>";
update_simple(data_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form215_delete_item(del_button);
});
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form215_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create DRS
* @param button
*/
function form215_create_form(func)
{
if(is_create_access('form215'))
{
var form=document.getElementById("form215_master");
var drs_num=form.elements['man_num'].value;
var ddate=get_raw_time(form.elements['date'].value);
var data_id=form.elements['id'].value;
$('#form215_share').show();
$('#form215_share').click(function()
{
modal101_action('Order Manifest','','staff',function (func)
{
print_form215(func);
});
});
var save_button=form.elements['save'];
var last_updated=get_my_time();
var num_orders=0;
$("[id^='save_form215']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(subform.elements[1].value!="")
{
num_orders+=1;
}
});
var drs_columns="<drs count='1'>" +
"<drs_num exact='yes'>"+drs_num+"</drs_num>"+
"</drs>";
get_single_column_data(function(drses)
{
if(drses.length==0)
{
var data_xml="<drs>" +
"<id>"+data_id+"</id>" +
"<drs_num>"+drs_num+"</drs_num>"+
"<drs_time>"+ddate+"</drs_time>"+
"<num_orders>"+num_orders+"</num_orders>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</drs>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>drs</tablename>" +
"<link_to>form236</link_to>" +
"<title>Generated</title>" +
"<notes>Manifest # "+drs_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>drs_num</name>"+
"</user_preferences>";
get_single_column_data(function (drs_num_ids)
{
if(drs_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+drs_num_ids[0]+"</id>"+
"<value>"+(parseInt(drs_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
update_simple(num_xml);
}
},num_data);
create_row(data_xml,activity_xml);
$(save_button).show();
if(typeof func!='undefined')
{
func();
}
}
else
{
$("#modal68_link").click();
}
},drs_columns);
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 217
* form SKU mapping (Supplier)
* @param button
*/
function form217_create_item(form)
{
if(is_create_access('form217'))
{
var supplier=form.elements[0].value;
var item=form.elements[1].value;
var desc=form.elements[2].value;
var sku=form.elements[3].value;
var margin=form.elements[4].value;
var data_id=form.elements[5].value;
var del_button=form.elements[7];
var last_updated=get_my_time();
var data_xml="<supplier_item_mapping>" +
"<id>"+data_id+"</id>" +
"<item>"+item+"</item>" +
"<item_desc>"+desc+"</item_desc>" +
"<supplier>"+supplier+"</supplier>" +
"<supplier_sku>"+sku+"</supplier_sku>" +
"<margin>"+margin+"</margin>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_item_mapping>";
create_simple(data_xml);
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form217_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form217_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form New Purchase Order (Aurilion)
* @param button
*/
function form222_create_item(form)
{
if(is_create_access('form222'))
{
var order_id=document.getElementById("form222_master").elements['order_id'].value;
var name=form.elements[0].value;
var quantity=form.elements[1].value;
var make=form.elements[2].value;
var mrp=form.elements[3].value;
var price=form.elements[4].value;
var amount=form.elements[5].value;
var tax=form.elements[6].value;
var total=form.elements[7].value;
var data_id=form.elements[8].value;
var save_button=form.elements[9];
var del_button=form.elements[10];
var last_updated=get_my_time();
var data_xml="<purchase_order_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<quantity>"+quantity+"</quantity>" +
"<order_id>"+order_id+"</order_id>" +
"<make>"+make+"</make>" +
"<mrp>"+mrp+"</mrp>" +
"<price>"+price+"</price>" +
"<amount>"+amount+"</amount>" +
"<tax>"+tax+"</tax>" +
"<total>"+total+"</total>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</purchase_order_items>";
create_simple(data_xml);
for(var i=0;i<8;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form222_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form New Purchase Order
* @param button
*/
function form222_create_form()
{
if(is_create_access('form222'))
{
var form=document.getElementById("form222_master");
var supplier=form.elements['supplier'].value;
var order_date=get_raw_time(form.elements['date'].value);
var order_num=form.elements['order_num'].value;
var status=form.elements['status'].value;
var data_id=form.elements['order_id'].value;
var save_button=form.elements['save'];
var bt=get_session_var('title');
$('#form222_share').show();
$('#form222_share').click(function()
{
modal101_action(bt+' - PO# '+order_num,supplier,'supplier',function (func)
{
print_form222(func);
});
});
var amount=0;
var tax=0;
var total=0;
$("[id^='save_form222']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(!isNaN(parseFloat(subform.elements[5].value)))
{
amount+=parseFloat(subform.elements[5].value);
tax+=parseFloat(subform.elements[6].value);
total+=parseFloat(subform.elements[7].value);
}
});
var total_row="<tr><td colspan='2' data-th='Total'>Total</td>" +
"<td>Amount:<br>Tax: <br>Total: </td>" +
"<td>Rs. "+amount+"<br>" +
"Rs. "+tax+"<br> " +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form222_foot').html(total_row);
var last_updated=get_my_time();
var data_xml="<purchase_orders>" +
"<id>"+data_id+"</id>" +
"<supplier>"+supplier+"</supplier>" +
"<order_date>"+order_date+"</order_date>" +
"<status>"+status+"</status>" +
"<order_num>"+order_num+"</order_num>" +
"<amount>"+amount+"</amount>" +
"<tax>"+tax+"</tax>" +
"<total>"+total+"</total>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</purchase_orders>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>purchase_orders</tablename>" +
"<link_to>form43</link_to>" +
"<title>Created</title>" +
"<notes>Purchase order # "+order_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var notification_xml="<notifications>" +
"<id>"+vUtil.newKey()+"</id>" +
"<t_generated>"+get_my_time()+"</t_generated>" +
"<data_id unique='yes'>"+data_id+"</data_id>" +
"<title>Purchase Order created</title>" +
"<notes>Purchase order # "+order_num+" has been created. Please review and place order.</notes>" +
"<link_to>form43</link_to>" +
"<status>pending</status>" +
"<target_user></target_user>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</notifications>";
create_row(data_xml,activity_xml);
create_simple(notification_xml);
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>po_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(order_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
update_simple(num_xml);
}
},num_data);
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form222_update_form();
});
$("[id^='save_form222_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 228
* form Demo
* @param button
*/
function form228_create_item(form)
{
if(is_create_access('form228'))
{
var item=form.elements[0].value;
var quantity=form.elements[1].value;
var customer=form.elements[3].value;
var negative="";
if(parseFloat(quantity)>0)
{
negative="-";
}
var date=get_raw_time(form.elements[4].value);
var data_id=form.elements[6].value;
var del_button=form.elements[8];
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+item+"</item_name>" +
"<hiring_type>demo</hiring_type>" +
"<issue_type>out</issue_type>" +
"<issue_date>"+date+"</issue_date>" +
"<customer>"+customer+"</customer>" +
"<quantity>"+negative+quantity+"</quantity>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bill_items</tablename>" +
"<link_to>form228</link_to>" +
"<title>Out</title>" +
"<notes>"+quantity+" pieces of "+item+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<7;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form228_delete_item(del_button);
});
$(form).off('submit');
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 229
* form Hire
* @param button
*/
function form229_create_item(form)
{
if(is_create_access('form229'))
{
var item=form.elements[0].value;
var quantity=form.elements[1].value;
var customer=form.elements[3].value;
var negative="";
if(parseFloat(quantity)>0)
{
negative="-";
}
var date=get_raw_time(form.elements[4].value);
var data_id=form.elements[6].value;
var del_button=form.elements[8];
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+item+"</item_name>" +
"<hiring_type>hire</hiring_type>" +
"<issue_type>out</issue_type>" +
"<issue_date>"+date+"</issue_date>" +
"<customer>"+customer+"</customer>" +
"<quantity>"+negative+quantity+"</quantity>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bill_items</tablename>" +
"<link_to>form229</link_to>" +
"<title>Out</title>" +
"<notes>"+quantity+" pieces of "+item+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<7;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form229_delete_item(del_button);
});
$(form).off('submit');
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 230
* form In-out
* @param button
*/
function form230_create_item(form)
{
if(is_create_access('form230'))
{
var item=form.elements[0].value;
var quantity=form.elements[1].value;
var issue_type=form.elements[2].value;
var negative="";
if(issue_type=='out' && parseFloat(quantity)>0)
{
negative="-";
}
var hiring_type=form.elements[3].value;
var customer=form.elements[4].value;
var date=get_raw_time(form.elements[5].value);
var notes=form.elements[6].value;
var data_id=form.elements[7].value;
var del_button=form.elements[9];
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+item+"</item_name>" +
"<hiring_type>"+hiring_type+"</hiring_type>" +
"<issue_type>"+issue_type+"</issue_type>" +
"<issue_date>"+date+"</issue_date>" +
"<customer>"+customer+"</customer>" +
"<notes>"+notes+"</notes>" +
"<quantity>"+negative+quantity+"</quantity>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bill_items</tablename>" +
"<link_to>form230</link_to>" +
"<title>"+issue_type+"</title>" +
"<notes>"+quantity+" pieces of "+item+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<7;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form230_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form230_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Prescriptions
* @formNo 231
* @param button
*/
function form231_create_item(form)
{
if(is_create_access('form231'))
{
var master_form=document.getElementById("form231_master");
var pres_id=master_form.elements['pres_id'].value;
var pres_num=master_form.elements['p_num'].value;
var type=form.elements[0].value;
var item=form.elements[1].value;
var dosage=form.elements[2].value;
var frequency=form.elements[3].value;
var days=form.elements[4].value;
var data_id=form.elements[5].value;
var save_button=form.elements[6];
var del_button=form.elements[7];
var last_updated=get_my_time();
var data_xml="<prescription_items>" +
"<id>"+data_id+"</id>" +
"<p_id>"+pres_id+"</p_id>" +
"<item>"+item+"</item>" +
"<type>"+type+"</type>" +
"<dosage>"+dosage+"</dosage>" +
"<frequency>"+frequency+"</frequency>" +
"<num_days>"+days+"</num_days>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</prescription_items>";
create_simple(data_xml);
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form231_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Prescription
* @param button
*/
function form231_create_form()
{
if(is_create_access('form231'))
{
show_loader();
var form=document.getElementById("form231_master");
var data_id=form.elements['pres_id'].value;
var date=get_raw_time(form.elements['date'].value);
var next_visit=get_raw_time(form.elements['next'].value);
var pres_num=form.elements['p_num'].value;
var patient=form.elements['patient'].value;
var doctor=form.elements['doctor'].value;
var save_button=form.elements['save'];
var last_updated=get_my_time();
var data_xml="<prescriptions>" +
"<id>"+data_id+"</id>" +
"<p_num>"+pres_num+"</p_num>" +
"<date>"+date+"</date>" +
"<next_date>"+next_visit+"</next_date>" +
"<patient>"+patient+"</patient>"+
"<doctor>"+doctor+"</doctor>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</prescriptions>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>prescriptions</tablename>" +
"<link_to>form232</link_to>" +
"<title>Saved</title>" +
"<notes>Prescription # "+pres_num+" for "+patient+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form231_update_form();
});
var bt=get_session_var('title');
$('#form231_share').show();
$('#form231_share').click(function()
{
modal101_action('Prescription from '+bt,patient,'customer',function (func)
{
print_form231(func);
});
});
$("[id^='save_form231_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Newsletter Creator
* @param button
*/
function form233_create_item()
{
if(is_create_access('form233'))
{
show_loader();
var form=document.getElementById("form233_form");
var data_id=form.elements['id'].value;
var name=form.elements['name'].value;
var description=form.elements['description'].value;
var new_key=vUtil.newKey();
var counter=0;
$("[id^='vyavsaay_image_box_']").each(function(index)
{
counter+=1;
var image_elem=$(this)[0];
vUtil.resize_picture(image_elem,image_elem.width);
var data_src=image_elem.getAttribute('data-src');
console.log(data_src);
if(data_src=="" || data_src=='undefined' || data_src=='null' || data_src==null)
{
var blob=image_elem.src;
var blob_name=vUtil.newKey()+".jpeg";
image_elem.setAttribute('data-src',blob_name);
if(is_online())
{
$.ajax(
{
type: "POST",
url: server_root+"/ajax/s3_doc.php",
data:
{
blob: blob,
name:blob_name,
content_type:'image/jpeg'
},
success: function(return_data,return_status,e)
{
console.log(e.responseText);
}
});
}
else
{
var s3_xml="<s3_objects>"+
"<id>"+(new_key+counter)+"</id>"+
"<data_blob>"+blob+"</data_blob>"+
"<name>"+blob_name+"</name>"+
"<type>image/jpeg</type>"+
"<status>pending</status>"+
"<last_updated>"+get_my_time()+"</last_updated>"+
"</s3_objects>";
create_simple(s3_xml);
}
console.log('image saved');
}
});
var html_content=htmlentities(document.getElementById('form233_section').innerHTML);
var save_button=form.elements['save'];
var last_updated=get_my_time();
//console.log(html_content);
var data_xml="<newsletter>" +
"<id>"+data_id+"</id>" +
"<name>"+name+"</name>" +
"<description>"+description+"</description>" +
"<status>active</status>" +
"<html_content>"+html_content+"</html_content>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</newsletter>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>newsletter</tablename>" +
"<link_to>form2</link_to>" +
"<title>Added</title>" +
"<notes>Newsletter "+name+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
//console.log(data_xml);
create_row(data_xml,activity_xml);
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form233_update_item();
});
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 245
* form SKU components
* @param button
*/
function form245_create_item(form)
{
//console.log('form245_create_form');
if(is_create_access('form245'))
{
var item_name=document.getElementById('form245_master').elements['item_name'].value;
var requisite_name=form.elements[0].value;
var requisite_desc=form.elements[1].value;
var quantity=form.elements[2].value;
var data_id=form.elements[3].value;
var save_button=form.elements[4];
var del_button=form.elements[5];
var last_updated=get_my_time();
var data_xml="<pre_requisites>" +
"<id>"+data_id+"</id>" +
"<name>"+item_name+"</name>" +
"<type>product</type>"+
"<quantity>"+quantity+"</quantity>"+
"<requisite_type>product</requisite_type>"+
"<requisite_name>"+requisite_name+"</requisite_name>"+
"<requisite_desc>"+requisite_desc+"</requisite_desc>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</pre_requisites>";
create_simple(data_xml);
for(var i=0;i<3;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form245_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Assign raw material requirements
* @param button
*/
function form245_create_form(func)
{
if(is_create_access('form245'))
{
$("[id^='save_form245_']").click();
}
else
{
$("#modal2_link").click();
}
}
function form245_update_serial_numbers()
{
$('#form245_body').find('tr').each(function(index)
{
$(this).find('td:nth-child(2)').html(index+1);
});
}
/**
* formNo 248
* form Create Transit Bag
* @param button
*/
function form248_create_item(form)
{
//console.log('form248_create_form');
if(is_create_access('form248'))
{
var master_form=document.getElementById('form248_master');
var bag_num=master_form.elements['bag_num'].value;
var bag_id=master_form.elements['id'].value;
var bag_date=master_form.elements['date'].value;
var lbh=master_form.elements['lbh'].value;
var weight=master_form.elements['weight'].value;
var num_orders=master_form.elements['num_orders'].value;
var branch=master_form.elements['branch'].value;
var data_id=form.elements[6].value;
var save_button=form.elements[7];
var del_button=form.elements[8];
var old_order_history=form.elements[9].value;
var order_history=vUtil.jsonParse(old_order_history);
var history_object=new Object();
history_object.timeStamp=get_my_time();
history_object.details="Order in-transit";
history_object.location=branch;
history_object.status="in-transit";
order_history.push(history_object);
var order_history_string=JSON.stringify(order_history);
var last_updated=get_my_time();
var data_xml="<logistics_orders>" +
"<id>"+data_id+"</id>" +
"<status>in-transit</status>" +
"<bag_num>"+bag_num+"</bag_num>"+
"<bag_id>"+bag_id+"</bag_id>"+
"<order_history>"+order_history_string+"</order_history>"+
"<branch>"+branch+"</branch>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</logistics_orders>";
update_simple(data_xml);
for(var i=0;i<6;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form248_delete_item(del_button);
});
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form248_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create bag
* @param button
*/
function form248_create_form(func)
{
if(is_create_access('form248'))
{
var form=document.getElementById("form248_master");
var bag_num=form.elements['bag_num'].value;
var lbh=form.elements['lbh'].value;
var weight=form.elements['weight'].value;
var date=get_raw_time(form.elements['date'].value);
var data_id=form.elements['id'].value;
var num_orders=form.elements['num_orders'].value;
var branch_filter=form.elements['branch'];
var branch=branch_filter.value;
branch_filter.setAttribute('readonly','readonly');
var save_button=form.elements['save'];
var last_updated=get_my_time();
var bag_columns="<transit_bags count='1'>" +
"<bag_num exact='yes'>"+bag_num+"</bag_num>"+
"</transit_bags>";
get_single_column_data(function(bags)
{
if(bags.length==0)
{
var data_xml="<transit_bags>" +
"<id>"+data_id+"</id>" +
"<bag_num>"+bag_num+"</bag_num>"+
"<lbh>"+lbh+"</lbh>"+
"<date>"+date+"</date>"+
"<weight>"+weight+"</weight>"+
"<num_orders>"+num_orders+"</num_orders>"+
"<status>pending</status>"+
"<branch>"+branch+"</branch>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</transit_bags>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>transit_bags</tablename>" +
"<link_to>form249</link_to>" +
"<title>Create</title>" +
"<notes>Bag # "+bag_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>bag_num</name>"+
"</user_preferences>";
get_single_column_data(function (bag_num_ids)
{
if(bag_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bag_num_ids[0]+"</id>"+
"<value>"+(parseInt(bag_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
update_simple(num_xml);
}
},num_data);
create_row(data_xml,activity_xml);
$(save_button).show();
if(typeof func!='undefined')
{
func();
}
}
else
{
$("#modal77_link").click();
}
},bag_columns);
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 250
* form Create MTS
* @param button
*/
function form250_create_item(form)
{
//console.log('form250_create_form');
if(is_create_access('form250'))
{
var master_form=document.getElementById('form250_master');
var mts_num=master_form.elements['mts_num'].value;
var mts_id=master_form.elements['id'].value;
var data_id=form.elements[4].value;
var save_button=form.elements[5];
var del_button=form.elements[6];
var last_updated=get_my_time();
var data_xml="<transit_bags>" +
"<id>"+data_id+"</id>" +
"<status>in-transit</status>" +
"<mts>"+mts_num+"</mts>"+
"<mts_id>"+mts_id+"</mts_id>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</transit_bags>";
update_simple(data_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form250_delete_item(del_button);
});
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form250_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create mts
* @param button
*/
function form250_create_form(func)
{
if(is_create_access('form250'))
{
var master_form=document.getElementById('form250_master');
var mts_num=master_form.elements['mts_num'].value;
var data_id=master_form.elements['id'].value;
var date=get_raw_time(master_form.elements['date'].value);
var weight=master_form.elements['weight'].value;
var num_orders=master_form.elements['num_orders'].value;
var num_bags=master_form.elements['num_bags'].value;
var branch=master_form.elements['branch'].value;
var save_button=master_form.elements['save'];
var last_updated=get_my_time();
$('#form250_share').show();
$('#form250_share').click(function()
{
modal101_action('Material Transfer Sheet','','staff',function (func)
{
print_form250(func);
});
});
var mts_columns="<mts count='1'>" +
"<mts_num exact='yes'>"+mts_num+"</mts_num>"+
"</mts>";
get_single_column_data(function(mtss)
{
if(mtss.length==0)
{
var data_xml="<mts>" +
"<id>"+data_id+"</id>" +
"<mts_num>"+mts_num+"</mts_num>"+
"<branch>"+branch+"</branch>"+
"<date>"+date+"</date>"+
"<weight>"+weight+"</weight>"+
"<num_orders>"+num_orders+"</num_orders>"+
"<num_bags>"+num_bags+"</num_bags>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</mts>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>mts</tablename>" +
"<link_to>form251</link_to>" +
"<title>Created</title>" +
"<notes>MTS # "+mts_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>mts_num</name>"+
"</user_preferences>";
get_single_column_data(function (mts_num_ids)
{
if(mts_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+mts_num_ids[0]+"</id>"+
"<value>"+(parseInt(mts_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
update_simple(num_xml);
}
},num_data);
create_row(data_xml,activity_xml);
$(save_button).show();
if(typeof func!='undefined')
{
func();
}
}
else
{
$("#modal78_link").click();
}
},mts_columns);
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Vendor leads
* @param button
*/
function form252_create_item(form)
{
if(is_create_access('form252'))
{
var customer=form.elements[0].value;
var detail=form.elements[1].value;
var due_date=get_raw_time(form.elements[2].value);
var identified_by=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_xml="<sale_leads>" +
"<id>"+data_id+"</id>" +
"<customer>"+customer+"</customer>" +
"<detail>"+detail+"</detail>" +
"<due_date>"+due_date+"</due_date>" +
"<identified_by>"+identified_by+"</identified_by>" +
"<status>open</status>"+
"<type>vendor</type>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</sale_leads>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>sale_leads</tablename>" +
"<link_to>form252</link_to>" +
"<title>Added</title>" +
"<notes>Lead for customer "+customer+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var customer_data="<customers>"+
"<id></id>"+
"<name></name>"+
"<phone></phone>"+
"<email></email>"+
"<acc_name exact='yes'>"+customer+"</acc_name>"+
"</customers>";
fetch_requested_data('',customer_data,function(customers)
{
var customer_name=customers[0].name;
var customer_phone=customers[0].phone;
var business_title=get_session_var('title');
var sms_content=get_session_var('sms_content');
var message=sms_content.replace(/customer_name/g,customer_name);
message=message.replace(/business_title/g,business_title);
send_sms(customer_phone,message,'transaction');
///////////////////////////////////////////////////////////////////////////////
var nl_name=get_session_var('default_newsletter');
var nl_id_xml="<newsletter>"+
"<id></id>"+
"<name exact='yes'>"+nl_name+"</name>"+
"</newsletter>";
get_single_column_data(function(nls)
{
if(nls.length>0)
{
var subject=nl_name;
var nl_id=nls[0];
print_newsletter(nl_name,nl_id,'mail',function(container)
{
var message=container.innerHTML;
var from=get_session_var('email');
var to_array=[{"name":customers[0].name,"email":customers[0].email,"customer_id":customers[0].id}];
var to=JSON.stringify(to_array);
send_email(to,from,business_title,subject,message,function(){});
});
}
},nl_id_xml);
});
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form252_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form252_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Customer leads
* @param button
*/
function form253_create_item(form)
{
if(is_create_access('form253'))
{
var customer=form.elements[0].value;
var detail=form.elements[1].value;
var due_date=get_raw_time(form.elements[2].value);
var identified_by=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_xml="<sale_leads>" +
"<id>"+data_id+"</id>" +
"<customer>"+customer+"</customer>" +
"<detail>"+detail+"</detail>" +
"<due_date>"+due_date+"</due_date>" +
"<identified_by>"+identified_by+"</identified_by>" +
"<status>open</status>"+
"<type>customer</type>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</sale_leads>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>sale_leads</tablename>" +
"<link_to>form253</link_to>" +
"<title>Added</title>" +
"<notes>Lead for customer "+customer+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var customer_data="<customers>"+
"<id></id>"+
"<name></name>"+
"<phone></phone>"+
"<email></email>"+
"<acc_name exact='yes'>"+customer+"</acc_name>"+
"</customers>";
fetch_requested_data('',customer_data,function(customers)
{
var customer_name=customers[0].name;
var customer_phone=customers[0].phone;
var business_title=get_session_var('title');
var sms_content=get_session_var('sms_content');
var message=sms_content.replace(/customer_name/g,customer_name);
message=message.replace(/business_title/g,business_title);
send_sms(customer_phone,message,'transaction');
///////////////////////////////////////////////////////////////////////////////
var nl_name=get_session_var('default_newsletter');
var nl_id_xml="<newsletter>"+
"<id></id>"+
"<name exact='yes'>"+nl_name+"</name>"+
"</newsletter>";
get_single_column_data(function(nls)
{
if(nls.length>0)
{
var subject=nl_name;
var nl_id=nls[0];
print_newsletter(nl_name,nl_id,'mail',function(container)
{
var message=container.innerHTML;
var from=get_session_var('email');
var to_array=[{"name":customers[0].name,"email":customers[0].email,"customer_id":customers[0].id}];
var to=JSON.stringify(to_array);
send_email(to,from,business_title,subject,message,function(){});
});
}
},nl_id_xml);
});
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form253_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form253_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Telecalling leads
* @param button
*/
function form254_create_item(form)
{
if(is_create_access('form254'))
{
var customer=form.elements[0].value;
var detail=form.elements[1].value;
var due_date=get_raw_time(form.elements[2].value);
var identified_by=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_xml="<sale_leads>" +
"<id>"+data_id+"</id>" +
"<customer>"+customer+"</customer>" +
"<detail>"+detail+"</detail>" +
"<due_date>"+due_date+"</due_date>" +
"<identified_by>"+identified_by+"</identified_by>" +
"<type>telecalling</type>" +
"<status>open</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</sale_leads>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>sale_leads</tablename>" +
"<link_to>form254</link_to>" +
"<title>Added</title>" +
"<notes>Lead for customer "+customer+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var customer_data="<customers>"+
"<id></id>"+
"<name></name>"+
"<phone></phone>"+
"<email></email>"+
"<acc_name exact='yes'>"+customer+"</acc_name>"+
"</customers>";
fetch_requested_data('',customer_data,function(customers)
{
var customer_name=customers[0].name;
var customer_phone=customers[0].phone;
var business_title=get_session_var('title');
var sms_content=get_session_var('sms_content');
var message=sms_content.replace(/customer_name/g,customer_name);
message=message.replace(/business_title/g,business_title);
send_sms(customer_phone,message,'transaction');
///////////////////////////////////////////////////////////////////////////////
var nl_name=get_session_var('default_newsletter');
var nl_id_xml="<newsletter>"+
"<id></id>"+
"<name exact='yes'>"+nl_name+"</name>"+
"</newsletter>";
get_single_column_data(function(nls)
{
if(nls.length>0)
{
var subject=nl_name;
var nl_id=nls[0];
print_newsletter(nl_name,nl_id,'mail',function(container)
{
var message=container.innerHTML;
var to_array=[{"name":customers[0].name,"email":customers[0].email,"customer_id":customers[0].id}];
var to=JSON.stringify(to_array);
var from=get_session_var('email');
send_email(to,from,business_title,subject,message,function(){});
});
}
},nl_id_xml);
});
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form254_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form254_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Marketing leads
* @param button
*/
function form255_create_item(form)
{
if(is_create_access('form255'))
{
var customer=form.elements[0].value;
var detail=form.elements[1].value;
var due_date=get_raw_time(form.elements[2].value);
var identified_by=form.elements[3].value;
var data_id=form.elements[4].value;
var last_updated=get_my_time();
var data_xml="<sale_leads>" +
"<id>"+data_id+"</id>" +
"<customer>"+customer+"</customer>" +
"<detail>"+detail+"</detail>" +
"<due_date>"+due_date+"</due_date>" +
"<identified_by>"+identified_by+"</identified_by>" +
"<type>marketing</type>" +
"<status>open</status>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</sale_leads>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>sale_leads</tablename>" +
"<link_to>form255</link_to>" +
"<title>Added</title>" +
"<notes>Lead for customer "+customer+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
var customer_data="<customers>"+
"<id></id>"+
"<name></name>"+
"<phone></phone>"+
"<email></email>"+
"<acc_name exact='yes'>"+customer+"</acc_name>"+
"</customers>";
fetch_requested_data('',customer_data,function(customers)
{
var customer_name=customers[0].name;
var customer_phone=customers[0].phone;
var business_title=get_session_var('title');
var sms_content=get_session_var('sms_content');
var message=sms_content.replace(/customer_name/g,customer_name);
message=message.replace(/business_title/g,business_title);
send_sms(customer_phone,message,'transaction');
///////////////////////////////////////////////////////////////////////////////
var nl_name=get_session_var('default_newsletter');
var nl_id_xml="<newsletter>"+
"<id></id>"+
"<name exact='yes'>"+nl_name+"</name>"+
"</newsletter>";
get_single_column_data(function(nls)
{
if(nls.length>0)
{
var subject=nl_name;
var nl_id=nls[0];
print_newsletter(nl_name,nl_id,'mail',function(container)
{
var message=container.innerHTML;
var from=get_session_var('email');
var to_array=[{"name":customers[0].name,"email":customers[0].email,"customer_id":customers[0].id}];
var to=JSON.stringify(to_array);
send_email(to,from,business_title,subject,message,function(){});
});
}
},nl_id_xml);
});
var del_button=form.elements[6];
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form255_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form255_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Purchase leads
* @param button
*/
function form273_create_item(form)
{
if(is_create_access('form273'))
{
var supplier=form.elements[0].value;
var item=form.elements[1].value;
var make=form.elements[2].value;
var price=form.elements[3].value;
var quantity=form.elements[4].value;
var detail=form.elements[5].value;
var identified_date=get_raw_time(form.elements[6].value);
var data_id=form.elements[7].value;
var del_button=form.elements[9];
var last_updated=get_my_time();
var data_xml="<purchase_leads>" +
"<id>"+data_id+"</id>" +
"<supplier>"+supplier+"</supplier>" +
"<item_name>"+item+"</item_name>" +
"<item_company>"+make+"</item_company>" +
"<detail>"+detail+"</detail>" +
"<price>"+price+"</price>" +
"<quantity>"+quantity+"</quantity>" +
"<status>open</status>" +
"<identified_date>"+identified_date+"</identified_date>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</purchase_leads>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>purchase_leads</tablename>" +
"<link_to>form273</link_to>" +
"<title>Added</title>" +
"<notes>Purchase lead from "+supplier+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<7;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form273_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form273_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* formNo 275
* form In-out (poojaelec)
* @param button
*/
function form275_create_item(form)
{
if(is_create_access('form275'))
{
var item=form.elements[0].value;
var quantity=form.elements[1].value;
var issue_type=form.elements[2].value;
var negative="";
if(issue_type=='out' && parseFloat(quantity)>0)
{
negative="-";
}
var customer=form.elements[3].value;
var date=get_raw_time(form.elements[4].value);
var notes=form.elements[5].value;
var data_id=form.elements[6].value;
var del_button=form.elements[8];
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+item+"</item_name>" +
"<issue_type>"+issue_type+"</issue_type>" +
"<issue_date>"+date+"</issue_date>" +
"<customer>"+customer+"</customer>" +
"<notes>"+notes+"</notes>" +
"<quantity>"+negative+quantity+"</quantity>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bill_items</tablename>" +
"<link_to>form275</link_to>" +
"<title>"+issue_type+"</title>" +
"<notes>"+quantity+" pieces of "+item+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<6;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form275_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form275_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Buyer leads
* @param button
*/
function form289_create_item(form)
{
if(is_create_access('form289'))
{
var customer=form.elements[0].value;
var item=form.elements[1].value;
var make=form.elements[2].value;
var price=form.elements[3].value;
var quantity=form.elements[4].value;
var poc=form.elements[5].value;
var detail=form.elements[6].value;
var due_date=get_raw_time(form.elements[7].value);
var data_id=form.elements[8].value;
var del_button=form.elements[10];
var last_updated=get_my_time();
var data_xml="<sale_leads>" +
"<id>"+data_id+"</id>" +
"<customer>"+customer+"</customer>" +
"<item_name>"+item+"</item_name>" +
"<item_company>"+make+"</item_company>" +
"<detail>"+detail+"</detail>" +
"<price>"+price+"</price>" +
"<quantity>"+quantity+"</quantity>" +
"<identified_by>"+poc+"</identified_by>" +
"<due_date>"+due_date+"</due_date>" +
"<status>open</status>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</sale_leads>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>sale_leads</tablename>" +
"<link_to>form289</link_to>" +
"<title>Added</title>" +
"<notes>Sale lead for "+customer+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
for(var i=0;i<8;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form289_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
form289_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Cities
* @param button
*/
function form290_create_item(form)
{
if(is_create_access('form290'))
{
var city=form.elements[0].value;
var state=form.elements[1].value;
var country=form.elements[2].value;
var data_id=form.elements[3].value;
var del_button=form.elements[5];
var last_updated=get_my_time();
var data_xml="<cities_data>" +
"<id>"+data_id+"</id>" +
"<city>"+city+"</city>" +
"<state>"+state+"</state>" +
"<country>"+country+"</country>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</cities_data>";
create_simple(data_xml);
for(var i=0;i<3;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form290_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function(event)
{
event.preventDefault();
});
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Bill(Sehgal)
* @formNo 294
* @param button
*/
function form294_create_item(form)
{
if(is_create_access('form294'))
{
var bill_id=document.getElementById("form294_master").elements['bill_id'].value;
var name=form.elements[0].value;
var quantity=form.elements[1].value;
var price=form.elements[2].value;
var amount=form.elements[3].value;
var storage=form.elements[4].value;
var data_id=form.elements[5].value;
var save_button=form.elements[6];
var del_button=form.elements[7];
var unit=$('#form294_unit_'+data_id).html();
var last_updated=get_my_time();
var data_xml="<bill_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+name+"</batch>" +
"<unit_price>"+price+"</unit_price>" +
"<quantity>"+quantity+"</quantity>" +
"<unit>"+unit+"</unit>"+
"<amount>"+amount+"</amount>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</bill_items>";
create_simple(data_xml);
var storage_data="<area_utilization>" +
"<id></id>" +
"<name exact='yes'>"+storage+"</name>" +
"<item_name exact='yes'>"+name+"</item_name>" +
"</area_utilization>";
fetch_requested_data('',storage_data,function(placements)
{
if(placements.length===0)
{
var storage_xml="<area_utilization>" +
"<id>"+vUtil.newKey()+"</id>" +
"<name>"+storage+"</name>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+name+"</batch>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</area_utilization>";
create_simple(storage_xml);
}
});
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form294_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create bill(Sehgal)
* @formNo 294
* @param button
*/
function form294_create_form()
{
if(is_create_access('form294'))
{
var form=document.getElementById("form294_master");
var customer=form.elements['customer'].value;
var bill_type=form.elements['tax_type'].value;
var bill_date=get_raw_time(form.elements['date'].value);
var bill_num=form.elements['bill_num'].value;
var bt=get_session_var('title');
$('#form294_share').show();
$('#form294_share').click(function()
{
modal101_action('Invoice from '+bt+' - '+bill_num,customer,'customer',function (func)
{
print_form294(func);
});
});
var amount=0;
var discount=0;
var tax_rate=0;
var cartage=0;
if(document.getElementById('form294_discount'))
{
discount=parseFloat(document.getElementById('form294_discount').value);
tax_rate=parseFloat(document.getElementById('form294_tax').value);
cartage=parseFloat(document.getElementById('form294_cartage').value);
}
$("[id^='save_form294']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(!isNaN(parseFloat(subform.elements[3].value)))
amount+=parseFloat(subform.elements[3].value);
});
var amount=vUtil.round(amount,2);
var tax=vUtil.round((tax_rate*((amount-discount)/100)),2);
var total=vUtil.round(amount+tax-discount+cartage,0);
var data_id=form.elements['bill_id'].value;
var save_button=form.elements['save'];
var last_updated=get_my_time();
var data_xml="<bills>" +
"<id>"+data_id+"</id>" +
"<bill_num>"+bill_num+"</bill_num>"+
"<customer_name>"+customer+"</customer_name>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<billing_type>"+bill_type+"</billing_type>" +
"<discount>"+discount+"</discount>" +
"<cartage>0</cartage>" +
"<tax>"+tax+"</tax>" +
"<tax_rate>"+tax_rate+"</tax_rate>"+
"<transaction_id>"+data_id+"</transaction_id>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form92</link_to>" +
"<title>Saved</title>" +
"<notes>Bill # "+bill_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+data_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>"+customer+"</receiver>" +
"<giver>master</giver>" +
"<tax>"+tax+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>pending</status>" +
"<type>received</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>"+total+"</paid_amount>" +
"<acc_name>"+customer+"</acc_name>" +
"<due_date>"+get_credit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>sale bill</source>" +
"<source_info>"+bill_num+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<receiver>master</receiver>" +
"<giver>"+customer+"</giver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>"+bill_type+"_bill_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(bill_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
update_simple(num_xml);
}
},num_data);
create_row(data_xml,activity_xml);
create_simple(transaction_xml);
create_simple(pt_xml);
create_simple_func(payment_xml,function()
{
//modal26_action(pt_tran_id);
});
var total_row="<tr><td colspan='3' data-th='Total'>Total</td>" +
"<td>Amount:<disc><br>Discount: </disc><br>Tax:@ <input type='number' value='"+tax_rate+"' step='any' id='form294_tax' class='dblclick_editable'>%<br>Cartage: <br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"<disc_amount>Rs. <input type='number' value='"+discount+"' step='any' id='form294_discount' class='dblclick_editable'></br></disc_amount>" +
"Rs. "+tax+"<br>" +
"Rs. <input type='number' value='0.00' step='any' id='form294_cartage' class='dblclick_editable'></br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form294_foot').html(total_row);
longPressEditable($('.dblclick_editable'));
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form294_update_form();
});
$("[id^='save_form294_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Purchase Bill(Sehgal)
* @formNo 295
* @param button
*/
function form295_create_item(form)
{
if(is_create_access('form295'))
{
var bill_id=document.getElementById("form295_master").elements['bill_id'].value;
var name=form.elements[0].value;
var quantity=form.elements[1].value;
var price=form.elements[2].value;
var amount=form.elements[3].value;
var storage=form.elements[4].value;
var data_id=form.elements[5].value;
var save_button=form.elements[6];
var del_button=form.elements[7];
var unit=$('#form295_unit_'+data_id).html();
var last_updated=get_my_time();
var data_xml="<supplier_bill_items>" +
"<id>"+data_id+"</id>" +
"<product_name>"+name+"</product_name>" +
"<batch>"+name+"</batch>" +
"<unit_price>"+price+"</unit_price>" +
"<quantity>"+quantity+"</quantity>" +
"<unit>"+unit+"</unit>"+
"<amount>"+amount+"</amount>" +
"<bill_id>"+bill_id+"</bill_id>" +
"<storage>"+storage+"</storage>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_bill_items>";
create_simple(data_xml);
var storage_data="<area_utilization>" +
"<id></id>" +
"<name exact='yes'>"+storage+"</name>" +
"<item_name exact='yes'>"+name+"</item_name>" +
"</area_utilization>";
fetch_requested_data('',storage_data,function(placements)
{
if(placements.length===0)
{
var storage_xml="<area_utilization>" +
"<id>"+vUtil.newKey()+"</id>" +
"<name>"+storage+"</name>" +
"<item_name>"+name+"</item_name>" +
"<batch>"+name+"</batch>" +
"<last_updated>"+get_my_time()+"</last_updated>" +
"</area_utilization>";
create_simple(storage_xml);
}
});
for(var i=0;i<5;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form295_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create purchase bill(Sehgal)
* @formNo 295
* @param button
*/
function form295_create_form()
{
if(is_create_access('form295'))
{
var form=document.getElementById("form295_master");
var supplier=form.elements['supplier'].value;
var bill_date=get_raw_time(form.elements['date'].value);
var entry_date=get_raw_time(form.elements['entry_date'].value);
var bill_num=form.elements['bill_num'].value;
var order_num=form.elements['po_num'].value;
var order_id=form.elements['order_id'].value;
var notes=form.elements['notes'].value;
var amount=0;
var discount=0;
var tax_rate=0;
var cartage=0;
if(document.getElementById('form295_discount'))
{
discount=parseFloat(document.getElementById('form295_discount').value);
tax_rate=parseFloat(document.getElementById('form295_tax').value);
cartage=parseFloat(document.getElementById('form295_cartage').value);
}
$("[id^='save_form295']").each(function(index)
{
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(!isNaN(parseFloat(subform.elements[3].value)))
amount+=parseFloat(subform.elements[3].value);
});
var amount=vUtil.round(amount,2);
var tax=vUtil.round((tax_rate*((amount-discount)/100)),2);
var total=vUtil.round(amount+tax-discount+cartage,0);
var data_id=form.elements['bill_id'].value;
var save_button=form.elements['save'];
var last_updated=get_my_time();
var data_xml="<supplier_bills>" +
"<id>"+data_id+"</id>" +
"<bill_id>"+bill_num+"</bill_id>"+
"<order_id>"+order_id+"</order_id>" +
"<order_num>"+order_num+"</order_num>" +
"<supplier>"+supplier+"</supplier>" +
"<bill_date>"+bill_date+"</bill_date>" +
"<entry_date>"+entry_date+"</entry_date>" +
"<amount>"+amount+"</amount>" +
"<total>"+total+"</total>" +
"<discount>"+discount+"</discount>" +
"<cartage>0</cartage>" +
"<tax>"+tax+"</tax>" +
"<tax_rate>"+tax_rate+"</tax_rate>"+
"<transaction_id>"+data_id+"</transaction_id>" +
"<notes>"+notes+"</notes>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</supplier_bills>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>bills</tablename>" +
"<link_to>form53</link_to>" +
"<title>Saved</title>" +
"<notes>Purchase Bill # "+bill_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
var transaction_xml="<transactions>" +
"<id>"+data_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<giver>"+supplier+"</giver>" +
"<receiver>master</receiver>" +
"<tax>"+tax+"</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
var pt_tran_id=vUtil.newKey();
var payment_xml="<payments>" +
"<id>"+pt_tran_id+"</id>" +
"<status>pending</status>" +
"<type>paid</type>" +
"<date>"+get_my_time()+"</date>" +
"<total_amount>"+total+"</total_amount>" +
"<paid_amount>"+total+"</paid_amount>" +
"<acc_name>"+supplier+"</acc_name>" +
"<due_date>"+get_debit_period()+"</due_date>" +
"<mode>"+get_payment_mode()+"</mode>" +
"<transaction_id>"+pt_tran_id+"</transaction_id>" +
"<source_id>"+data_id+"</source_id>" +
"<source>purchase bill</source>" +
"<source_info>"+bill_num+"</source_info>"+
"<last_updated>"+last_updated+"</last_updated>" +
"</payments>";
var pt_xml="<transactions>" +
"<id>"+pt_tran_id+"</id>" +
"<trans_date>"+get_my_time()+"</trans_date>" +
"<amount>"+total+"</amount>" +
"<giver>master</giver>" +
"<receiver>"+supplier+"</receiver>" +
"<tax>0</tax>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</transactions>";
create_row(data_xml,activity_xml);
create_simple(transaction_xml);
create_simple(pt_xml);
create_simple_func(payment_xml,function()
{
//modal28_action(pt_tran_id);
});
var po_data="<purchase_orders>"+
"<id>"+order_id+"</id>" +
"<bill_id></bill_id>" +
"</purchase_orders>";
fetch_requested_data('',po_data,function (porders)
{
if(porders.length>0)
{
var id_object_array=vUtil.jsonParse(porders[0].bill_id);
var id_object=new Object();
id_object.bill_num=bill_num;
id_object.bill_id=data_id;
id_object_array.push(id_object);
var status='received';
var new_bill_id=JSON.stringify(id_object_array);
var po_xml="<purchase_orders>" +
"<id>"+order_id+"</id>" +
"<bill_id>"+new_bill_id+"</bill_id>" +
"<status>"+status+"</status>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</purchase_orders>";
update_simple(po_xml);
}
});
var total_row="<tr><td colspan='3' data-th='Total'>Total</td>" +
"<td>Amount:<disc><br>Discount: </disc><br>Tax:@ <input type='number' value='"+tax_rate+"' step='any' id='form295_tax' class='dblclick_editable'>%<br>Cartage: <br>Total: </td>" +
"<td>Rs. "+amount+"</br>" +
"<disc_amount>Rs. <input type='number' value='"+discount+"' step='any' id='form295_discount' class='dblclick_editable'></br></disc_amount>" +
"Rs. "+tax+"<br>" +
"Rs. <input type='number' value='0.00' step='any' id='form295_cartage' class='dblclick_editable'></br>" +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form295_foot').html(total_row);
longPressEditable($('.dblclick_editable'));
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form295_update_form();
});
$("[id^='save_form295_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Create Purchase Order (Sehgal)
* @param button
*/
function form296_create_item(form)
{
if(is_create_access('form296'))
{
var order_id=document.getElementById("form296_master").elements['order_id'].value;
var name=form.elements[0].value;
var desc=form.elements[1].value;
var quantity=form.elements[2].value;
var make=form.elements[3].value;
var mrp=form.elements[4].value;
var price=form.elements[5].value;
var amount=form.elements[6].value;
var tax_rate=form.elements[7].value;
var tax=form.elements[8].value;
var total=form.elements[9].value;
var data_id=form.elements[10].value;
var save_button=form.elements[11];
var del_button=form.elements[12];
var last_updated=get_my_time();
var data_xml="<purchase_order_items>" +
"<id>"+data_id+"</id>" +
"<item_name>"+name+"</item_name>" +
"<item_desc>"+desc+"</item_desc>" +
"<quantity>"+quantity+"</quantity>" +
"<order_id>"+order_id+"</order_id>" +
"<make>"+make+"</make>" +
"<mrp>"+mrp+"</mrp>" +
"<price>"+price+"</price>" +
"<amount>"+amount+"</amount>" +
"<tax>"+tax+"</tax>" +
"<tax_rate>"+tax_rate+"</tax_rate>" +
"<total>"+total+"</total>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</purchase_order_items>";
create_simple(data_xml);
for(var i=0;i<10;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form296_delete_item(del_button);
});
$(save_button).off('click');
}
else
{
$("#modal2_link").click();
}
}
/**
* @form New Purchase Order
* @param button
*/
function form296_create_form()
{
if(is_create_access('form296'))
{
var form=document.getElementById("form296_master");
var supplier=form.elements['supplier'].value;
var order_date=get_raw_time(form.elements['date'].value);
var order_num=form.elements['order_num'].value;
var status=form.elements['status'].value;
var data_id=form.elements['order_id'].value;
var save_button=form.elements['save'];
var bt=get_session_var('title');
var data_array=[];
var amount=0;
var tax=0;
var total=0;
var total_quantity=0;
var counter=0;
$("[id^='save_form296']").each(function(index)
{
counter+=1;
var subform_id=$(this).attr('form');
var subform=document.getElementById(subform_id);
if(!isNaN(parseFloat(subform.elements[6].value)))
{
amount+=parseFloat(subform.elements[6].value);
tax+=parseFloat(subform.elements[8].value);
total+=parseFloat(subform.elements[9].value);
}
if(!isNaN(parseFloat(subform.elements[2].value)))
total_quantity+=parseFloat(subform.elements[2].value);
var new_object=new Object();
new_object['S.No.']=counter;
new_object['Item Name']=subform.elements[0].value;
new_object['Description']=subform.elements[1].value;
new_object['Quantity']=subform.elements[2].value;
new_object['MRP']=subform.elements[4].value;
new_object['Price']=subform.elements[5].value;
new_object['Tax']=subform.elements[8].value;
new_object['Total']=subform.elements[9].value;
data_array.push(new_object);
});
var message_attachment=vUtil.objArrayToCSVString(data_array);
$('#form296_share').show();
$('#form296_share').click(function()
{
modal101_action(bt+' - PO# '+order_num+' - '+supplier,supplier,'supplier',function (func)
{
print_form296(func);
},'csv',message_attachment);
});
amount=vUtil.round(amount,2);
tax=vUtil.round(tax,2);
total=vUtil.round(total,2);
var total_row="<tr><td colspan='2' data-th='Total'>Total Quantity: "+total_quantity+"</td>" +
"<td>Amount:<br>Tax: <br>Total: </td>" +
"<td>Rs. "+amount+"<br>" +
"Rs. "+tax+"<br> " +
"Rs. "+total+"</td>" +
"<td></td>" +
"</tr>";
$('#form296_foot').html(total_row);
var last_updated=get_my_time();
var data_xml="<purchase_orders>" +
"<id>"+data_id+"</id>" +
"<supplier>"+supplier+"</supplier>" +
"<order_date>"+order_date+"</order_date>" +
"<status>"+status+"</status>" +
"<order_num>"+order_num+"</order_num>" +
"<amount>"+amount+"</amount>" +
"<tax>"+tax+"</tax>" +
"<total>"+total+"</total>" +
"<total_quantity>"+total_quantity+"</total_quantity>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</purchase_orders>";
var activity_xml="<activity>" +
"<data_id>"+data_id+"</data_id>" +
"<tablename>purchase_orders</tablename>" +
"<link_to>form297</link_to>" +
"<title>Created</title>" +
"<notes>Purchase order # "+order_num+"</notes>" +
"<updated_by>"+get_name()+"</updated_by>" +
"</activity>";
create_row(data_xml,activity_xml);
var num_data="<user_preferences>"+
"<id></id>"+
"<name exact='yes'>po_num</name>"+
"</user_preferences>";
get_single_column_data(function (bill_num_ids)
{
if(bill_num_ids.length>0)
{
var num_xml="<user_preferences>"+
"<id>"+bill_num_ids[0]+"</id>"+
"<value>"+(parseInt(order_num)+1)+"</value>"+
"<last_updated>"+last_updated+"</last_updated>"+
"</user_preferences>";
update_simple(num_xml);
}
},num_data);
$(save_button).off('click');
$(save_button).on('click',function(event)
{
event.preventDefault();
form296_update_form();
});
$("[id^='save_form296_']").click();
}
else
{
$("#modal2_link").click();
}
}
/**
* @form Convert QR Data
* @param button
*/
function form302_create_item(form)
{
if(is_create_access('form302'))
{
var source=form.elements[0].value;
var format=form.elements[1].value;
var func=form.elements[2].value;
format=htmlentities(format);
func=htmlentities(func);
var data_id=form.elements[4].value;
var save_button=form.elements[5];
var del_button=form.elements[6];
var last_updated=get_my_time();
var data_xml="<qr_contexts>" +
"<id>"+data_id+"</id>" +
"<source unique='yes'>"+source+"</source>" +
"<format>"+format+"</format>" +
"<conversion_func>"+func+"</conversion_func>" +
"<last_updated>"+last_updated+"</last_updated>" +
"</qr_contexts>";
create_simple(data_xml);
for(var i=0;i<4;i++)
{
$(form.elements[i]).attr('readonly','readonly');
}
del_button.removeAttribute("onclick");
$(del_button).on('click',function(event)
{
form302_delete_item(del_button);
});
$(form).off('submit');
$(form).on('submit',function (e)
{
e.preventDefault();
form302_update_item(form);
});
}
else
{
$("#modal2_link").click();
}
}
|
#!/usr/bin/env bash
set -e
cd "$(dirname "$0")/.."
echo "Running black..."
black . --check
echo "Running add trailing commas..."
add-trailing-comma $(find . -type f -name '*.py')
echo "Running isort..."
isort . -c
echo "Running mypy..."
mypy chalicelib
|
<reponame>whilein/wbot<filename>src/main/java/w/bot/method/photos/VkPhotosSaveMessagesPhoto.java
/*
* Copyright 2022 Whilein
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package w.bot.method.photos;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.jetbrains.annotations.NotNull;
import w.bot.VkBot;
import w.bot.method.AbstractVkMethod;
import w.bot.method.VkMethod;
import w.bot.type.Photo;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
/**
* @author whilein
*/
public interface VkPhotosSaveMessagesPhoto extends VkMethod<Photo[]> {
static @NotNull VkPhotosSaveMessagesPhoto create(final @NotNull VkBot bot) {
return new Stub(bot);
}
@NotNull VkPhotosSaveMessagesPhoto hash(@NotNull String hash);
@NotNull VkPhotosSaveMessagesPhoto photo(@NotNull String photo);
@NotNull VkPhotosSaveMessagesPhoto server(int server);
final class Stub extends AbstractVkMethod<Photo[]> implements VkPhotosSaveMessagesPhoto {
@Accessors(fluent = true)
@Setter
String hash;
@Accessors(fluent = true)
@Setter
String photo;
@Accessors(fluent = true)
@Setter
int server;
private Stub(final VkBot vkBot) {
super(vkBot, "photos.saveMessagesPhoto", Photo[].class);
}
@Override
protected void initQuery(final @NotNull StringBuilder out) {
super.initQuery(out);
out
.append("&hash=").append(hash)
.append("&photo=").append(URLEncoder.encode(photo, StandardCharsets.UTF_8))
.append("&server=").append(server);
}
}
}
|
<reponame>jackwickham/simple-deploy
import {fork} from "child_process";
import {promises as fs} from "fs";
import {Probot} from "probot";
import yaml from "js-yaml";
import {Config, WorkerArgs} from "./types";
export default async function deployApp(app: Probot): Promise<void> {
app.on("deployment.created", async (context) => {
const configFile = await fs.readFile(".config.yml", "utf-8");
const config = yaml.load(configFile) as Config;
const repo = context.repo();
const service = config.services.find(
(svc) =>
svc.repo === `${repo.owner}/${repo.repo}` &&
svc.environment == context.payload.deployment.environment
);
if (!service) {
context.log.info(
`No deployment config found for ${repo.owner}/${repo.repo} ${context.payload.deployment.environment}, skipping`
);
return;
}
context.log.info(
`Starting deployment for ${repo.owner}/${repo.repo} ${context.payload.deployment.environment}`
);
await context.octokit.repos.createDeploymentStatus(
context.repo({
deployment_id: context.payload.deployment.id,
state: "in_progress",
headers: {
accept: "application/vnd.github.flash-preview+json",
},
})
);
const token = (await (context.octokit.auth({type: "installation"}) as Promise<{token: string}>))
.token;
const args: WorkerArgs = {
dir: service.dir,
commitHash: context.payload.deployment.sha,
token: token,
repoOwner: context.repo().owner,
repo: context.repo().repo,
deploymentId: context.payload.deployment.id,
steps: service.steps,
};
const errorFile = config.errorFile ? (await fs.open(config.errorFile, "a")).fd : "ignore";
const child = fork(__dirname + "/standalone.js", [], {
detached: true,
stdio: ["ipc", errorFile, errorFile],
});
child.send(args);
await new Promise<void>((resolve) => {
const timeout = setTimeout(async () => {
const exitCode = child.exitCode;
if (exitCode !== null) {
context.log.error(`Deployment script exited with code ${exitCode}`);
} else {
child.disconnect();
child.unref();
context.log.error(`Deployment init timed out`);
}
await context.octokit.repos.createDeploymentStatus(
context.repo({
deployment_id: context.payload.deployment.id,
state: "error",
})
);
resolve();
}, 1000);
child.on("message", async (m: {ack: boolean}) => {
clearTimeout(timeout);
child.disconnect();
child.unref();
if (m.ack === true) {
// Child is happy, let it do its thing
context.log.info(`Running deployment (pid ${child.pid})`);
} else {
context.log.error(`Deployment init failed`);
await context.octokit.repos.createDeploymentStatus(
context.repo({
deployment_id: context.payload.deployment.id,
state: "error",
})
);
}
resolve();
});
});
});
}
|
require 'spec_helper'
require 'rest_spec_helper'
require 'rhc/commands/cartridge'
require 'rhc/config'
describe RHC::Commands::Cartridge do
def exit_with_code_and_message(code, message = nil)
expect{ run }.should exit_with_code(code)
run_output.should match(message) if message
end
def succeed_with_message(message = "Success")
exit_with_code_and_message(0,message)
end
def fail_with_message(message,code = 1)
exit_with_code_and_message(code, message)
end
def fail_with_code(code = 1)
exit_with_code_and_message(code)
end
before(:each) do
RHC::Config.set_defaults
end
describe 'run' do
let(:arguments) { ['cartridge', '--trace', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
end
it { succeed_with_message /mock_cart-1.*mock_cart-2.*unique_mock_cart-1/m }
end
end
describe 'run without password' do
let(:arguments) { ['cartridge', '--trace', '--noprompt', '--config', 'test.conf'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
end
it { succeed_with_message /mock_cart-1.*mock_cart-2.*unique_mock_cart-1/m }
end
end
describe 'alias app cartridge' do
let(:arguments) { ['app', 'cartridge', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
end
it { succeed_with_message /mock_cart-1.*mock_cart-2.*unique_mock_cart-1/m }
end
end
describe 'cartridge add' do
let(:arguments) { ['cartridge', 'add', 'mock_cart-1', '--app', 'app1', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
end
it {
succeed_with_message
}
end
end
describe 'cartridge add with app context' do
let(:arguments) { ['cartridge', 'add', 'mock_cart-1', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
instance = RHC::Commands::Cartridge.new
instance.stub(:git_config_get) { |key| app.uuid if key == "rhc.app-uuid" }
RHC::Commands::Cartridge.stub(:new) { instance }
end
it {
succeed_with_message
}
end
end
describe 'cartridge add with no app context' do
let(:arguments) { ['cartridge', 'add', 'mock_cart-1', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
instance = RHC::Commands::Cartridge.new
instance.stub(:git_config_get) { |key| "" if key == "rhc.app-uuid" }
RHC::Commands::Cartridge.stub(:new) { instance }
end
it {
fail_with_code
}
end
end
describe 'alias app cartridge add' do
let(:arguments) { ['app', 'cartridge', 'add', 'unique_mock_cart', '--app', 'app1', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
end
it {
succeed_with_message
}
end
end
describe 'cartridge add no cart found error' do
let(:arguments) { ['cartridge', 'add', 'nomatch_cart', '--app', 'app1', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
end
it {
fail_with_code 154
}
end
end
describe 'cartridge add too many carts found error' do
let(:arguments) { ['cartridge', 'add', 'mock_cart', '-a', 'app1','--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
end
it {
fail_with_code 155
}
end
end
describe 'cartridge remove without confirming' do
let(:arguments) { ['cartridge', 'remove', 'mock_cart-1', '-a', 'app1', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
app.add_cartridge('mock_cart-1')
end
it {
fail_with_message "Removing a cartridge is a destructive operation"
}
end
end
describe 'cartridge remove' do
let(:arguments) { ['cartridge', 'remove', 'mock_cart-1', '--confirm', '--trace', '-a', 'app1', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
@app = domain.add_application("app1", "mock_type")
end
it "should remove cartridge" do
@app.add_cartridge('mock_cart-1')
expect { run }.should exit_with_code(0)
# framework cart should be the only one listed
@app.cartridges.length.should == 1
end
it "should raise cartridge not found exception" do
expect { run }.should raise_error RHC::CartridgeNotFoundException
end
end
end
describe 'cartridge status' do
let(:arguments) { ['cartridge', 'status', 'mock_cart-1', '-a', 'app1','--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
before(:each) do
@rc = MockRestClient.new
@domain = @rc.add_domain("mock_domain")
@app = @domain.add_application("app1", "mock_type")
@app.add_cartridge('mock_cart-1')
end
context 'when run' do
it { run_output.should match('started') }
end
context 'when run with cart stopped' do
before(:each) { @app.find_cartridge('mock_cart-1').stop }
it { run_output.should match('stopped') }
end
end
describe 'cartridge start' do
let(:arguments) { ['cartridge', 'start', 'mock_cart-1', '-a', 'app1','--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
app.add_cartridge('mock_cart-1')
end
it { run_output.should match('start') }
end
end
describe 'cartridge stop' do
let(:arguments) { ['cartridge', 'stop', 'mock_cart-1', '-a', 'app1','--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
app.add_cartridge('mock_cart-1')
end
it { run_output.should match('stop') }
end
end
describe 'cartridge restart' do
let(:arguments) { ['cartridge', 'restart', 'mock_cart-1', '-a', 'app1','--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
app.add_cartridge('mock_cart-1')
end
it { run_output.should match('restart') }
end
end
describe 'cartridge reload' do
let(:arguments) { ['cartridge', 'reload', 'mock_cart-1', '-a', 'app1','--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
app.add_cartridge('mock_cart-1')
end
it { run_output.should match('reload') }
end
end
describe 'cartridge show' do
let(:arguments) { ['cartridge', 'show', 'mock_cart-1', '-a', 'app1', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type")
app.add_cartridge('mock_cart-1')
end
context 'when run' do
it { run_output.should match('Connection URL: http://fake.url') }
end
end
describe 'cartridge show scaled' do
let(:arguments) { ['cartridge', 'show', 'mock_type', '-a', 'app1', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] }
context 'when run' do
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type", true)
end
it { run_output.should match(/Scaling: .*x2 \(minimum/) }
it { run_output.should match('minimum: 2') }
it { run_output.should match('maximum: available') }
end
end
describe 'cartridge scale' do
let(:arguments) { ['cartridge', 'scale', @cart_type || 'mock_type', '-a', 'app1', '--noprompt', '--config', 'test.conf', '-l', '<EMAIL>', '-p', 'password'] | (@extra_args || []) }
let(:current_scale) { 1 }
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type", scalable)
app.cartridges.first.stub(:current_scale).and_return(current_scale)
end
context 'when run with scalable app' do
let(:scalable){ true }
it "with no values" do
fail_with_message "Must provide either a min or max"
end
it "with a min value" do
@extra_args = ["--min","6"]
succeed_with_message "minimum: 6"
end
it "with a max value" do
@extra_args = ["--max","3"]
succeed_with_message 'maximum: 3'
end
it "with an invalid min value" do
@extra_args = ["--min","a"]
fail_with_message "invalid argument: --min"
end
it "with an invalid max value" do
@extra_args = ["--max","a"]
fail_with_message "invalid argument: --max"
end
end
context 'when run with a nonscalable app' do
let(:scalable){ false }
it "with a min value" do
@extra_args = ["--min","6"]
fail_with_message "Cartridge is not scalable"
end
end
end
=begin
# Commenting this out for US2438
describe 'cartridge storage' do
let(:cmd_base) { ['cartridge', 'storage'] }
let(:std_args) { ['-a', 'app1', '--noprompt', '--config', 'test.conf', '-l', 'test<EMAIL>', '-p', 'password'] | (@extra_args || []) }
let(:cart_type) { ['mock_cart-1'] }
before(:each) do
@rc = MockRestClient.new
domain = @rc.add_domain("mock_domain")
app = domain.add_application("app1", "mock_type", false)
app.add_cartridge('mock_cart-1', true, 5)
end
context 'when run with no arguments' do
let(:arguments) { cmd_base | std_args }
it "should show a list of storage info for all carts" do
run_output.should match('mock_type')
run_output.should match('mock_cart-1')
end
end
context 'when run for a non-existent cartridge' do
let(:arguments) { cmd_base | ['bogus_cart'] | std_args }
it { fail_with_message("Cartridge bogus_cart can't be found in application", 154) }
end
context 'when run with -c flag' do
let(:arguments) { cmd_base | ['-c', 'mock_cart-1'] | std_args}
it "should show storage info for the indicated app and cart" do
run_output.should match('mock_cart-1')
run_output.should_not match('mock_type')
end
it "should set storage for the indicated app and cart" do
@extra_args = ["--set", "6GB"]
run_output.should match('6GB')
end
end
context 'when run with valid arguments' do
let(:arguments) { cmd_base | cart_type | std_args }
it "should show storage info for the indicated app and cart" do
@extra_args = ["--show"]
run_output.should match('mock_cart-1')
run_output.should_not match('mock_type')
end
it "should add storage for the indicated app and cart" do
@extra_args = ["--add", "5GB"]
run_output.should match('10GB')
end
it "should remove storage for the indicated app and cart" do
@extra_args = ["--remove", "5GB"]
run_output.should match('None')
end
it "should warn when told to remove more storage than the indicated app and cart have" do
@extra_args = ["--remove", "70GB"]
fail_with_message('The amount of additional storage to be removed exceeds the total amount in use')
end
it "should not warn when told to remove more storage than the indicated app and cart have when forced" do
@extra_args = ["--remove", "70GB", "--force"]
run_output.should match('None')
end
it "should set storage for the indicated app and cart" do
@extra_args = ["--set", "6GB"]
run_output.should match('6GB')
end
it "should work correctly with a bare number value" do
@extra_args = ["--set", "6"]
run_output.should match('6GB')
end
end
context 'when run with invalid arguments' do
let(:arguments) { cmd_base | cart_type | std_args }
it "should raise an error when multiple storage operations are provided" do
@extra_args = ["--show", "--add", "5GB"]
fail_with_message('Only one storage action can be performed at a time')
end
it "should raise an error when the storage amount is not provided" do
@extra_args = ["--set"]
fail_with_message('missing argument')
end
it "should raise an error when the storage amount is invalid" do
@extra_args = ["--set", "5ZB"]
fail_with_message("The amount format must be a number, optionally followed by 'GB'")
end
end
end
=end
end
|
#!/bin/bash
ZIP=/usr/bin/zip
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" #directory of the current script
source $DIR/package_config.sh
echo "Splitting into copy_this and changed_full"
cd $DIR
rm -rf package_unenc
mkdir package_unenc
cd package_unenc
mkdir copy_this changed_full
cp -r $DIR/productive/* copy_this/
mkdir -p changed_full/application/views
mkdir -p changed_full/out
mv copy_this/application/views/roxid_mod changed_full/application/views/
mv copy_this/out/roxid_mod changed_full/out
mv copy_this/sql .
cd $DIR
echo -e " Adding install instructions..."
cp $DIR/install_instruction/README.txt .
echo -e " Compressing to $FILENAME..."
rm -f ../$FILENAME
$ZIP -r -9 -q ../$FILENAME *
cd ..
rm -r package/
echo "Creating package"
cd package_unenc
echo " Adding install instructions..."
cp $DIR/install_instruction/README.txt .
echo " Adding license comment..."
for FILE in `find . -type f -name "*.php"`
do
$DIR/add_license.rb $FILE $DIR/license_comment.txt > tmp.php
mv tmp.php $FILE
done
echo " Compressing to $FILENAME..."
rm -f ../$FILENAME
$ZIP -r -9 -q ../$FILENAME *
cd ..
rm -r package_unenc
|
#!/usr/bin/env bash
################################################################################
### Head: Init
##
THE_BASE_DIR_PATH=$(cd -P -- "$(dirname -- "$0")" && pwd -P)
THE_BASE_DIR_PATH="$THE_BASE_DIR_PATH/../ext"
source "$THE_BASE_DIR_PATH/init.sh"
##
### Tail: Init
################################################################################
################################################################################
### Head: Main
##
__main__ () {
THE_DICT_IDIOMS_SOURCE_DIR_PATH="$THE_VAR_DIR_PATH/dict_idioms"
mkdir -p "$THE_DICT_IDIOMS_SOURCE_DIR_PATH"
cd "$THE_DICT_IDIOMS_SOURCE_DIR_PATH"
## https://language.moe.gov.tw/001/Upload/Files/site_content/M0001/respub/dict_idiomsdict_download.html
wget -c 'https://language.moe.gov.tw/001/Upload/Files/site_content/M0001/respub/download/dict_idioms_2011_20190329.zip'
#unar 'dict_idioms_2011_20190329.zip'
unzip -O Big5 'dict_idioms_2011_20190329.zip'
}
__main__ "$@"
##
### Tail: Main
################################################################################
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.